diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 50dcf7d..0000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.md linguist-language=Objective-C diff --git a/.github/ISSUE_REPLY_TEMPLATE.md b/.github/ISSUE_REPLY_TEMPLATE.md new file mode 100644 index 0000000..944c73f --- /dev/null +++ b/.github/ISSUE_REPLY_TEMPLATE.md @@ -0,0 +1,3 @@ +# 注意 + +由于评论维护的问题,所有在 GitHub Issue 中提的问题都不会得到作者的回复,请到对应[博客](http://draveness.me)下面的 Disqus 评论系统留言,谢谢。 diff --git a/.github/issue_template.md b/.github/issue_template.md new file mode 100644 index 0000000..944c73f --- /dev/null +++ b/.github/issue_template.md @@ -0,0 +1,3 @@ +# 注意 + +由于评论维护的问题,所有在 GitHub Issue 中提的问题都不会得到作者的回复,请到对应[博客](http://draveness.me)下面的 Disqus 评论系统留言,谢谢。 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cfc4d70 --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +# Xcode +# +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata +*.xccheckout +*.moved-aside +DerivedData +*.hmap +*.ipa +*.xcuserstate + +fastlane/report.xml + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control +# +Pods/ + +.DS_Store diff --git a/README.md b/README.md index 2919f79..c4ee9dd 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,51 @@ -# iOS-Source-Code-Analyze +# Analyze

- + Banner designed by Levine

## 为什么要建这个仓库 +欢迎使用 RSS 订阅我的博客 [点击订阅](http://draveness.me/feed.xml) + 世人都说阅读开源框架的源代码对于功力有显著的提升,所以我也尝试阅读开源框架的源代码,并对其内容进行详细地分析和理解。在这里将自己阅读开源框架源代码的心得记录下来,希望能对各位开发者有所帮助。我会不断更新这个仓库中的文章,如果想要关注可以点 `star`。 ## 目录 -> Latest:[如何实现 iOS 中的 Associated Object](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/FBRetainCycleDetector/如何实现%20iOS%20中的%20Associated%20Object.md) +Latest: + ++ [谈谈 MVX 中的 Model](contents/architecture/mvx-model.md) ++ [谈谈 MVX 中的 View](contents/architecture/mvx-view.md) ++ [谈谈 MVX 中的 Controller](contents/architecture/mvx-controller.md) ++ [浅谈 MVC、MVP 和 MVVM 架构模式](contents/architecture/mvx.md) | Project | Version | Article | |:-------:|:-------:|:------| -| FBRetainCycleDetector | 0.1.2 | [如何在 iOS 中解决循环引用的问题](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/FBRetainCycleDetector/如何在%20iOS%20中解决循环引用的问题.md)
[检测 NSObject 对象持有的强指针](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/FBRetainCycleDetector/检测%20NSObject%20对象持有的强指针.md)
[如何实现 iOS 中的 Associated Object](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/FBRetainCycleDetector/如何实现%20iOS%20中的%20Associated%20Object.md)| -| fishhook | 0.2 |[动态修改 C 语言函数的实现](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/fishhook/动态修改%20C%20语言函数的实现.md) | -| libextobjc | |[如何在 Objective-C 的环境下实现 defer](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/libextobjc/如何在%20Objective-C%20的环境下实现%20defer.md) | -| IQKeyboardManager | 4.0.3 |[『零行代码』解决键盘遮挡问题(iOS)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/IQKeyboardManager/『零行代码』解决键盘遮挡问题(iOS).md) | -| ObjC | | [从 NSObject 的初始化了解 isa](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/从%20NSObject%20的初始化了解%20isa.md)
[深入解析 ObjC 中方法的结构](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/深入解析%20ObjC%20中方法的结构.md)
[从源代码看 ObjC 中消息的发送](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/从源代码看%20ObjC%20中消息的发送.md)
[你真的了解 load 方法么?](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/你真的了解%20load%20方法么?.md)
[上古时代 Objective-C 中哈希表的实现](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/上古时代%20Objective-C%20中哈希表的实现.md)
[自动释放池的前世今生](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/自动释放池的前世今生.md)
[黑箱中的 retain 和 release](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/黑箱中的%20retain%20和%20release.md)
[关联对象 AssociatedObject 完全解析](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/关联对象%20AssociatedObject%20完全解析.md)
[懒惰的 initialize 方法](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/懒惰的%20initialize%20方法.md)| -| DKNightVersion | 2.3.0 | [成熟的夜间模式解决方案](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/DKNightVersion/成熟的夜间模式解决方案.md) | -| AFNetworking | 3.0.4 | [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20概述(一).md)
[AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md)
[处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/处理请求和响应%20AFURLSerialization(三).md)
[AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md)
[验证 HTTPS 请求的证书(五)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/验证%20HTTPS%20请求的证书(五).md) | -| BlocksKit | 2.2.5 | [神奇的 BlocksKit(一)遍历、KVO 和分类](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/BlocksKit/神奇的%20BlocksKit%20(一).md)
[神奇的 BlocksKit(二)动态代理的实现 ](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/BlocksKit/神奇的%20BlocksKit%20(二).md) | -| Alamofire | | [iOS 源代码分析 --- Alamofire](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/Alamofire/iOS%20源代码分析%20----%20Alamofire.md) | -| SDWebImage | | [iOS 源代码分析 --- SDWebImage](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/SDWebImage/iOS%20源代码分析%20---%20SDWebImage.md) | -| MBProgressHUD | | [iOS 源代码分析 --- MBProgressHUD](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/MBProgressHUD/iOS%20源代码分析%20---%20MBProgressHUD.md) | -| Masonry | | [iOS 源代码分析 --- Masonry](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/Masonry/iOS%20源代码分析%20---%20Masonry.md) | - +| Architecture | | [谈谈 MVX 中的 Model](contents/architecture/mvx-model.md)
[谈谈 MVX 中的 View](contents/architecture/mvx-view.md)
[谈谈 MVX 中的 Controller](contents/architecture/mvx-controller.md)
[浅谈 MVC、MVP 和 MVVM 架构模式](contents/architecture/mvx.md) | +| ReactiveObjC | 2.1.2 | [『状态』驱动的世界:ReactiveCocoa](contents/ReactiveObjC/RACSignal.md)
[Pull-Driven 的数据流 RACSequence](contents/ReactiveObjC/RACSequence.md)
[『可变』的热信号 RACSubject](contents/ReactiveObjC/RACSubject.md)
[优雅的 RACCommand](contents/ReactiveObjC/RACCommand.md)
[用于多播的 RACMulticastConnection](contents/ReactiveObjC/RACMulticastConnection.md)
[RAC 中的双向数据绑定 RACChannel](contents/ReactiveObjC/RACChannel.md)
[理解 RACScheduler 的实现](contents/ReactiveObjC/RACScheduler.md)
[从代理到 RACSignal](contents/ReactiveObjC/RACDelegateProxy.md)| +| ObjC | | [从 NSObject 的初始化了解 isa](contents/objc/从%20NSObject%20的初始化了解%20isa.md)
[深入解析 ObjC 中方法的结构](contents/objc/深入解析%20ObjC%20中方法的结构.md)
[从源代码看 ObjC 中消息的发送](contents/objc/从源代码看%20ObjC%20中消息的发送.md)
[你真的了解 load 方法么?](contents/objc/你真的了解%20load%20方法么?.md)
[上古时代 Objective-C 中哈希表的实现](contents/objc/上古时代%20Objective-C%20中哈希表的实现.md)
[自动释放池的前世今生](contents/objc/自动释放池的前世今生.md)
[黑箱中的 retain 和 release](contents/objc/黑箱中的%20retain%20和%20release.md)
[关联对象 AssociatedObject 完全解析](contents/objc/关联对象%20AssociatedObject%20完全解析.md)
[懒惰的 initialize 方法](contents/objc/懒惰的%20initialize%20方法.md)
[对象是如何初始化的(iOS)](contents/objc/对象是如何初始化的(iOS).md)| +| KVOController | 1.2.0 | [如何优雅地使用 KVO](contents/KVOController/KVOController.md) | +| AsyncDisplayKit | 1.9.81 | [提升 iOS 界面的渲染性能](contents/AsyncDisplayKit/提升%20iOS%20界面的渲染性能%20.md)
[从 Auto Layout 的布局算法谈性能](contents/AsyncDisplayKit/从%20Auto%20Layout%20的布局算法谈性能.md)
[预加载与智能预加载(iOS)](contents/AsyncDisplayKit/预加载与智能预加载(iOS).md)| +| CocoaPods | 1.1.0 | [CocoaPods 都做了什么?](contents/CocoaPods/CocoaPods%20都做了什么?.md)
[谈谈 DSL 以及 DSL 的应用(以 CocoaPods 为例)](contents/CocoaPods/谈谈%20DSL%20以及%20DSL%20的应用(以%20CocoaPods%20为例).md)| +| OHHTTPStubs | 5.1.0 | [iOS 开发中使用 NSURLProtocol 拦截 HTTP 请求](contents/OHHTTPStubs/iOS%20开发中使用%20NSURLProtocol%20拦截%20HTTP%20请求.md)
[如何进行 HTTP Mock(iOS)](contents/OHHTTPStubs/如何进行%20HTTP%20Mock(iOS).md) | +| ProtocolKit | | [如何在 Objective-C 中实现协议扩展](contents/ProtocolKit/如何在%20Objective-C%20中实现协议扩展.md) | +| FBRetainCycleDetector | 0.1.2 | [如何在 iOS 中解决循环引用的问题](contents/FBRetainCycleDetector/如何在%20iOS%20中解决循环引用的问题.md)
[检测 NSObject 对象持有的强指针](contents/FBRetainCycleDetector/检测%20NSObject%20对象持有的强指针.md)
[如何实现 iOS 中的 Associated Object](contents/FBRetainCycleDetector/如何实现%20iOS%20中的%20Associated%20Object.md)
[iOS 中的 block 是如何持有对象的](contents/FBRetainCycleDetector/iOS%20中的%20block%20是如何持有对象的.md)| +| fishhook | 0.2 |[动态修改 C 语言函数的实现](contents/fishhook/动态修改%20C%20语言函数的实现.md) | +| libextobjc | |[如何在 Objective-C 的环境下实现 defer](contents/libextobjc/如何在%20Objective-C%20的环境下实现%20defer.md) | +| IQKeyboardManager | 4.0.3 |[『零行代码』解决键盘遮挡问题(iOS)](contents/IQKeyboardManager/『零行代码』解决键盘遮挡问题(iOS).md) | +| DKNightVersion | 2.3.0 | [成熟的夜间模式解决方案](contents/DKNightVersion/成熟的夜间模式解决方案.md) | +| AFNetworking | 3.0.4 | [AFNetworking 概述(一)](contents/AFNetworking/AFNetworking%20概述(一).md)
[AFNetworking 的核心 AFURLSessionManager(二)](contents/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md)
[处理请求和响应 AFURLSerialization(三)](contents/AFNetworking/处理请求和响应%20AFURLSerialization(三).md)
[AFNetworkReachabilityManager 监控网络状态(四)](contents/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md)
[验证 HTTPS 请求的证书(五)](contents/AFNetworking/验证%20HTTPS%20请求的证书(五).md) | +| BlocksKit | 2.2.5 | [神奇的 BlocksKit(一)遍历、KVO 和分类](contents/BlocksKit/神奇的%20BlocksKit%20(一).md)
[神奇的 BlocksKit(二)动态代理的实现 ](contents/BlocksKit/神奇的%20BlocksKit%20(二).md) | +| Alamofire | | [iOS 源代码分析 --- Alamofire](contents/Alamofire/iOS%20源代码分析%20----%20Alamofire.md) | +| SDWebImage | | [iOS 源代码分析 --- SDWebImage](contents/SDWebImage/iOS%20源代码分析%20---%20SDWebImage.md) | +| MBProgressHUD | | [iOS 源代码分析 --- MBProgressHUD](contents/MBProgressHUD/iOS%20源代码分析%20---%20MBProgressHUD.md) | +| Masonry | | [iOS 源代码分析 --- Masonry](contents/Masonry/iOS%20源代码分析%20---%20Masonry.md) | +| Redis | 3.2.5 | [Redis 和 I/O 多路复用](contents/Redis/redis-io-multiplexing.md)
[Redis 中的事件循环](contents/Redis/redis-eventloop.md)
[Redis 是如何处理命令的(客户端)](contents/Redis/redis-cli)| + +## 微信公众号 + +![](https://img.draveness.me/2020-03-11-15839264230785-wechat-qr-code.png) ## 勘误 diff --git "a/AFNetworking/AFNetworkReachabilityManager \347\233\221\346\216\247\347\275\221\347\273\234\347\212\266\346\200\201\357\274\210\345\233\233\357\274\211.md" "b/contents/AFNetworking/AFNetworkReachabilityManager \347\233\221\346\216\247\347\275\221\347\273\234\347\212\266\346\200\201\357\274\210\345\233\233\357\274\211.md" similarity index 95% rename from "AFNetworking/AFNetworkReachabilityManager \347\233\221\346\216\247\347\275\221\347\273\234\347\212\266\346\200\201\357\274\210\345\233\233\357\274\211.md" rename to "contents/AFNetworking/AFNetworkReachabilityManager \347\233\221\346\216\247\347\275\221\347\273\234\347\212\266\346\200\201\357\274\210\345\233\233\357\274\211.md" index b10cd00..9667575 100644 --- "a/AFNetworking/AFNetworkReachabilityManager \347\233\221\346\216\247\347\275\221\347\273\234\347\212\266\346\200\201\357\274\210\345\233\233\357\274\211.md" +++ "b/contents/AFNetworking/AFNetworkReachabilityManager \347\233\221\346\216\247\347\275\221\347\273\234\347\212\266\346\200\201\357\274\210\345\233\233\357\274\211.md" @@ -299,11 +299,11 @@ self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; 关于其他 AFNetworking 源代码分析的其他文章: -+ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20概述(一).md) -+ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) -+ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) -+ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) -+ [验证 HTTPS 请求的证书(五)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/验证%20HTTPS%20请求的证书(五).md) ++ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20概述(一).md) ++ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) ++ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) ++ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) ++ [验证 HTTPS 请求的证书(五)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/验证%20HTTPS%20请求的证书(五).md) Follow: [@Draveness](https://github.com/Draveness) diff --git "a/AFNetworking/AFNetworking \346\246\202\350\277\260\357\274\210\344\270\200\357\274\211.md" "b/contents/AFNetworking/AFNetworking \346\246\202\350\277\260\357\274\210\344\270\200\357\274\211.md" similarity index 92% rename from "AFNetworking/AFNetworking \346\246\202\350\277\260\357\274\210\344\270\200\357\274\211.md" rename to "contents/AFNetworking/AFNetworking \346\246\202\350\277\260\357\274\210\344\270\200\357\274\211.md" index 7d95f8e..3bab002 100644 --- "a/AFNetworking/AFNetworking \346\246\202\350\277\260\357\274\210\344\270\200\357\274\211.md" +++ "b/contents/AFNetworking/AFNetworking \346\246\202\350\277\260\357\274\210\344\270\200\357\274\211.md" @@ -135,11 +135,11 @@ AFNetworking 实际上只是对 `NSURLSession` 高度地封装, 提供一些简 关于其他 AFNetworking 源代码分析的其他文章: -+ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20概述(一).md) -+ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) -+ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) -+ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) -+ [验证 HTTPS 请求的证书(五)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/验证%20HTTPS%20请求的证书(五).md) ++ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20概述(一).md) ++ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) ++ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) ++ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) ++ [验证 HTTPS 请求的证书(五)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/验证%20HTTPS%20请求的证书(五).md) Follow: [@Draveness](https://github.com/Draveness) diff --git "a/AFNetworking/AFNetworking \347\232\204\346\240\270\345\277\203 AFURLSessionManager\357\274\210\344\272\214\357\274\211.md" "b/contents/AFNetworking/AFNetworking \347\232\204\346\240\270\345\277\203 AFURLSessionManager\357\274\210\344\272\214\357\274\211.md" similarity index 97% rename from "AFNetworking/AFNetworking \347\232\204\346\240\270\345\277\203 AFURLSessionManager\357\274\210\344\272\214\357\274\211.md" rename to "contents/AFNetworking/AFNetworking \347\232\204\346\240\270\345\277\203 AFURLSessionManager\357\274\210\344\272\214\357\274\211.md" index 7dc7477..bb4e823 100644 --- "a/AFNetworking/AFNetworking \347\232\204\346\240\270\345\277\203 AFURLSessionManager\357\274\210\344\272\214\357\274\211.md" +++ "b/contents/AFNetworking/AFNetworking \347\232\204\346\240\270\345\277\203 AFURLSessionManager\357\274\210\344\272\214\357\274\211.md" @@ -113,7 +113,7 @@ Blog: [Draveness](http://draveness.me) > `url_session_manager_create_task_safely` 的调用是因为苹果框架中的一个 bug [#2093](https://github.com/AFNetworking/AFNetworking/issues/2093),如果有兴趣可以看一下,在这里就不说明了 1. 调用 `- [NSURLSession dataTaskWithRequest:]` 方法传入 `NSURLRequest` -2. 调用 `- [AFURLSessionManager addDelegateForDataTask:uploadProgress:downloadProgress:completionHandler:]` 方法返回一个 `AFURLSessionManagerTaskDelegate` 对象 +2. 调用 `- [AFURLSessionManager addDelegateForDataTask:uploadProgress:downloadProgress:completionHandler:]` 方法创建一个 `AFURLSessionManagerTaskDelegate` 对象 3. 将 `completionHandler` `uploadProgressBlock` 和 `downloadProgressBlock` 传入该对象并在相应事件发生时进行回调 ```objectivec @@ -563,10 +563,10 @@ didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge 关于其他 AFNetworking 源代码分析的其他文章: -+ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20概述(一).md) -+ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) -+ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) -+ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) ++ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20概述(一).md) ++ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) ++ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) ++ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) diff --git "a/AFNetworking/\345\244\204\347\220\206\350\257\267\346\261\202\345\222\214\345\223\215\345\272\224 AFURLSerialization\357\274\210\344\270\211\357\274\211.md" "b/contents/AFNetworking/\345\244\204\347\220\206\350\257\267\346\261\202\345\222\214\345\223\215\345\272\224 AFURLSerialization\357\274\210\344\270\211\357\274\211.md" similarity index 97% rename from "AFNetworking/\345\244\204\347\220\206\350\257\267\346\261\202\345\222\214\345\223\215\345\272\224 AFURLSerialization\357\274\210\344\270\211\357\274\211.md" rename to "contents/AFNetworking/\345\244\204\347\220\206\350\257\267\346\261\202\345\222\214\345\223\215\345\272\224 AFURLSerialization\357\274\210\344\270\211\357\274\211.md" index edfc710..540d9f3 100644 --- "a/AFNetworking/\345\244\204\347\220\206\350\257\267\346\261\202\345\222\214\345\223\215\345\272\224 AFURLSerialization\357\274\210\344\270\211\357\274\211.md" +++ "b/contents/AFNetworking/\345\244\204\347\220\206\350\257\267\346\261\202\345\222\214\345\223\215\345\272\224 AFURLSerialization\357\274\210\344\270\211\357\274\211.md" @@ -680,11 +680,11 @@ for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { 关于其他 AFNetworking 源代码分析的其他文章: -+ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20概述(一).md) -+ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) -+ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) -+ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) -+ [验证 HTTPS 请求的证书(五)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/验证%20HTTPS%20请求的证书(五).md) ++ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20概述(一).md) ++ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) ++ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) ++ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) ++ [验证 HTTPS 请求的证书(五)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/验证%20HTTPS%20请求的证书(五).md) diff --git "a/AFNetworking/\351\252\214\350\257\201 HTTPS \350\257\267\346\261\202\347\232\204\350\257\201\344\271\246\357\274\210\344\272\224\357\274\211.md" "b/contents/AFNetworking/\351\252\214\350\257\201 HTTPS \350\257\267\346\261\202\347\232\204\350\257\201\344\271\246\357\274\210\344\272\224\357\274\211.md" similarity index 96% rename from "AFNetworking/\351\252\214\350\257\201 HTTPS \350\257\267\346\261\202\347\232\204\350\257\201\344\271\246\357\274\210\344\272\224\357\274\211.md" rename to "contents/AFNetworking/\351\252\214\350\257\201 HTTPS \350\257\267\346\261\202\347\232\204\350\257\201\344\271\246\357\274\210\344\272\224\357\274\211.md" index f02580d..6f77c4b 100644 --- "a/AFNetworking/\351\252\214\350\257\201 HTTPS \350\257\267\346\261\202\347\232\204\350\257\201\344\271\246\357\274\210\344\272\224\357\274\211.md" +++ "b/contents/AFNetworking/\351\252\214\350\257\201 HTTPS \350\257\267\346\261\202\347\232\204\350\257\201\344\271\246\357\274\210\344\272\224\357\274\211.md" @@ -371,11 +371,11 @@ if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthent 关于其他 AFNetworking 源代码分析的其他文章: -+ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20概述(一).md) -+ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) -+ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) -+ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) -+ [验证 HTTPS 请求的证书(五)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/AFNetworking/验证%20HTTPS%20请求的证书(五).md) ++ [AFNetworking 概述(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20概述(一).md) ++ [AFNetworking 的核心 AFURLSessionManager(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworking%20的核心%20AFURLSessionManager(二).md) ++ [处理请求和响应 AFURLSerialization(三)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/处理请求和响应%20AFURLSerialization(三).md) ++ [AFNetworkReachabilityManager 监控网络状态(四)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/AFNetworkReachabilityManager%20监控网络状态(四).md) ++ [验证 HTTPS 请求的证书(五)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AFNetworking/验证%20HTTPS%20请求的证书(五).md) diff --git "a/Alamofire/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 ---- Alamofire.md" "b/contents/Alamofire/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 ---- Alamofire.md" similarity index 100% rename from "Alamofire/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 ---- Alamofire.md" rename to "contents/Alamofire/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 ---- Alamofire.md" diff --git a/contents/AsyncDisplayKit/Layout/.gitignore b/contents/AsyncDisplayKit/Layout/.gitignore new file mode 100644 index 0000000..200a88b --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/.gitignore @@ -0,0 +1,28 @@ +# Xcode +# +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata +*.xccheckout +*.moved-aside +DerivedData +*.hmap +*.ipa +*.xcuserstate + +fastlane/report.xml + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control +# +#Pods/ diff --git a/contents/AsyncDisplayKit/Layout/Layout.xcodeproj/project.pbxproj b/contents/AsyncDisplayKit/Layout/Layout.xcodeproj/project.pbxproj new file mode 100644 index 0000000..39d8928 --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout.xcodeproj/project.pbxproj @@ -0,0 +1,385 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 518A37E5D0220B807E99ECA0 /* libPods-Layout.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4318ABCD72DA5B6C8E3E7A23 /* libPods-Layout.a */; }; + 724CC0131D729ACE00969D19 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 724CC0121D729ACE00969D19 /* main.m */; }; + 724CC0161D729ACE00969D19 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 724CC0151D729ACE00969D19 /* AppDelegate.m */; }; + 724CC0191D729ACE00969D19 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 724CC0181D729ACE00969D19 /* ViewController.m */; }; + 724CC01C1D729ACE00969D19 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 724CC01A1D729ACE00969D19 /* Main.storyboard */; }; + 724CC01E1D729ACE00969D19 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 724CC01D1D729ACE00969D19 /* Assets.xcassets */; }; + 724CC0211D729ACE00969D19 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 724CC01F1D729ACE00969D19 /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 1C89D50C35EC2591F7CB69A9 /* Pods-Layout.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Layout.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Layout/Pods-Layout.debug.xcconfig"; sourceTree = ""; }; + 2CC6845D33268FBA5F260319 /* Pods-Layout.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Layout.release.xcconfig"; path = "Pods/Target Support Files/Pods-Layout/Pods-Layout.release.xcconfig"; sourceTree = ""; }; + 4318ABCD72DA5B6C8E3E7A23 /* libPods-Layout.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Layout.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 724CC00E1D729ACE00969D19 /* Layout.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Layout.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 724CC0121D729ACE00969D19 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + 724CC0141D729ACE00969D19 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + 724CC0151D729ACE00969D19 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; + 724CC0171D729ACE00969D19 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; + 724CC0181D729ACE00969D19 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; + 724CC01B1D729ACE00969D19 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 724CC01D1D729ACE00969D19 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 724CC0201D729ACE00969D19 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 724CC0221D729ACE00969D19 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 724CC00B1D729ACE00969D19 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 518A37E5D0220B807E99ECA0 /* libPods-Layout.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 17FDB5A80DF243428EBD53E9 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 4318ABCD72DA5B6C8E3E7A23 /* libPods-Layout.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + 724CC0051D729ACE00969D19 = { + isa = PBXGroup; + children = ( + 724CC0101D729ACE00969D19 /* Layout */, + 724CC00F1D729ACE00969D19 /* Products */, + DFFAE951264B58C7C0914F93 /* Pods */, + 17FDB5A80DF243428EBD53E9 /* Frameworks */, + ); + sourceTree = ""; + }; + 724CC00F1D729ACE00969D19 /* Products */ = { + isa = PBXGroup; + children = ( + 724CC00E1D729ACE00969D19 /* Layout.app */, + ); + name = Products; + sourceTree = ""; + }; + 724CC0101D729ACE00969D19 /* Layout */ = { + isa = PBXGroup; + children = ( + 724CC0141D729ACE00969D19 /* AppDelegate.h */, + 724CC0151D729ACE00969D19 /* AppDelegate.m */, + 724CC0171D729ACE00969D19 /* ViewController.h */, + 724CC0181D729ACE00969D19 /* ViewController.m */, + 724CC01A1D729ACE00969D19 /* Main.storyboard */, + 724CC01D1D729ACE00969D19 /* Assets.xcassets */, + 724CC01F1D729ACE00969D19 /* LaunchScreen.storyboard */, + 724CC0221D729ACE00969D19 /* Info.plist */, + 724CC0111D729ACE00969D19 /* Supporting Files */, + ); + path = Layout; + sourceTree = ""; + }; + 724CC0111D729ACE00969D19 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 724CC0121D729ACE00969D19 /* main.m */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + DFFAE951264B58C7C0914F93 /* Pods */ = { + isa = PBXGroup; + children = ( + 1C89D50C35EC2591F7CB69A9 /* Pods-Layout.debug.xcconfig */, + 2CC6845D33268FBA5F260319 /* Pods-Layout.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 724CC00D1D729ACE00969D19 /* Layout */ = { + isa = PBXNativeTarget; + buildConfigurationList = 724CC0251D729ACE00969D19 /* Build configuration list for PBXNativeTarget "Layout" */; + buildPhases = ( + 817069C0FFA3399E7AC74743 /* [CP] Check Pods Manifest.lock */, + 724CC00A1D729ACE00969D19 /* Sources */, + 724CC00B1D729ACE00969D19 /* Frameworks */, + 724CC00C1D729ACE00969D19 /* Resources */, + 2F6F816CEDFB06833A4A6211 /* [CP] Embed Pods Frameworks */, + 13F926A8EF9EB7E48D00948B /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Layout; + productName = Layout; + productReference = 724CC00E1D729ACE00969D19 /* Layout.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 724CC0061D729ACE00969D19 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0730; + ORGANIZATIONNAME = Draveness; + TargetAttributes = { + 724CC00D1D729ACE00969D19 = { + CreatedOnToolsVersion = 7.3.1; + }; + }; + }; + buildConfigurationList = 724CC0091D729ACE00969D19 /* Build configuration list for PBXProject "Layout" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 724CC0051D729ACE00969D19; + productRefGroup = 724CC00F1D729ACE00969D19 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 724CC00D1D729ACE00969D19 /* Layout */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 724CC00C1D729ACE00969D19 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 724CC0211D729ACE00969D19 /* LaunchScreen.storyboard in Resources */, + 724CC01E1D729ACE00969D19 /* Assets.xcassets in Resources */, + 724CC01C1D729ACE00969D19 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 13F926A8EF9EB7E48D00948B /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Layout/Pods-Layout-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + 2F6F816CEDFB06833A4A6211 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Layout/Pods-Layout-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 817069C0FFA3399E7AC74743 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 724CC00A1D729ACE00969D19 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 724CC0191D729ACE00969D19 /* ViewController.m in Sources */, + 724CC0161D729ACE00969D19 /* AppDelegate.m in Sources */, + 724CC0131D729ACE00969D19 /* main.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 724CC01A1D729ACE00969D19 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 724CC01B1D729ACE00969D19 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 724CC01F1D729ACE00969D19 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 724CC0201D729ACE00969D19 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 724CC0231D729ACE00969D19 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + 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; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + }; + name = Debug; + }; + 724CC0241D729ACE00969D19 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + 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; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 724CC0261D729ACE00969D19 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1C89D50C35EC2591F7CB69A9 /* Pods-Layout.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = Layout/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.draveness.Layout; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 724CC0271D729ACE00969D19 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2CC6845D33268FBA5F260319 /* Pods-Layout.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = Layout/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.draveness.Layout; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 724CC0091D729ACE00969D19 /* Build configuration list for PBXProject "Layout" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 724CC0231D729ACE00969D19 /* Debug */, + 724CC0241D729ACE00969D19 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 724CC0251D729ACE00969D19 /* Build configuration list for PBXNativeTarget "Layout" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 724CC0261D729ACE00969D19 /* Debug */, + 724CC0271D729ACE00969D19 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 724CC0061D729ACE00969D19 /* Project object */; +} diff --git a/contents/AsyncDisplayKit/Layout/Layout.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/contents/AsyncDisplayKit/Layout/Layout.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..329be3e --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/contents/AsyncDisplayKit/Layout/Layout.xcworkspace/contents.xcworkspacedata b/contents/AsyncDisplayKit/Layout/Layout.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..7a392f3 --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/contents/AsyncDisplayKit/Layout/Layout/AppDelegate.h b/contents/AsyncDisplayKit/Layout/Layout/AppDelegate.h new file mode 100644 index 0000000..3272743 --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout/AppDelegate.h @@ -0,0 +1,17 @@ +// +// AppDelegate.h +// Layout +// +// Created by Draveness on 8/28/16. +// Copyright © 2016 Draveness. All rights reserved. +// + +#import + +@interface AppDelegate : UIResponder + +@property (strong, nonatomic) UIWindow *window; + + +@end + diff --git a/contents/AsyncDisplayKit/Layout/Layout/AppDelegate.m b/contents/AsyncDisplayKit/Layout/Layout/AppDelegate.m new file mode 100644 index 0000000..2c1ac88 --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout/AppDelegate.m @@ -0,0 +1,45 @@ +// +// AppDelegate.m +// Layout +// +// Created by Draveness on 8/28/16. +// Copyright © 2016 Draveness. All rights reserved. +// + +#import "AppDelegate.h" + +@interface AppDelegate () + +@end + +@implementation AppDelegate + + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + // Override point for customization after application launch. + return YES; +} + +- (void)applicationWillResignActive:(UIApplication *)application { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. +} + +- (void)applicationDidEnterBackground:(UIApplication *)application { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. +} + +- (void)applicationWillEnterForeground:(UIApplication *)application { + // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. +} + +- (void)applicationDidBecomeActive:(UIApplication *)application { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. +} + +- (void)applicationWillTerminate:(UIApplication *)application { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. +} + +@end diff --git a/contents/AsyncDisplayKit/Layout/Layout/Assets.xcassets/AppIcon.appiconset/Contents.json b/contents/AsyncDisplayKit/Layout/Layout/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..118c98f --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,38 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/contents/AsyncDisplayKit/Layout/Layout/Base.lproj/LaunchScreen.storyboard b/contents/AsyncDisplayKit/Layout/Layout/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..2e721e1 --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contents/AsyncDisplayKit/Layout/Layout/Base.lproj/Main.storyboard b/contents/AsyncDisplayKit/Layout/Layout/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f56d2f3 --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout/Base.lproj/Main.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contents/AsyncDisplayKit/Layout/Layout/Info.plist b/contents/AsyncDisplayKit/Layout/Layout/Info.plist new file mode 100644 index 0000000..6905cc6 --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout/Info.plist @@ -0,0 +1,40 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/contents/AsyncDisplayKit/Layout/Layout/ViewController.h b/contents/AsyncDisplayKit/Layout/Layout/ViewController.h new file mode 100644 index 0000000..ad103b0 --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout/ViewController.h @@ -0,0 +1,15 @@ +// +// ViewController.h +// Layout +// +// Created by Draveness on 8/28/16. +// Copyright © 2016 Draveness. All rights reserved. +// + +#import + +@interface ViewController : UIViewController + + +@end + diff --git a/contents/AsyncDisplayKit/Layout/Layout/ViewController.m b/contents/AsyncDisplayKit/Layout/Layout/ViewController.m new file mode 100644 index 0000000..d650d9f --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout/ViewController.m @@ -0,0 +1,273 @@ +// +// ViewController.m +// Layout +// +// Created by Draveness on 8/28/16. +// Copyright © 2016 Draveness. All rights reserved. +// + +#import "ViewController.h" + +#import + +@interface ViewController () + +@end + +@implementation ViewController { + UITextField *_textField; + UILabel *_indicateLabel; + NSMutableArray *_views; + + NSMutableDictionary *_resultDictionary; +} + +- (void)viewDidLoad { + [super viewDidLoad]; + + _views = [[NSMutableArray alloc] init]; + + UIButton *autoLayoutButton = [[UIButton alloc] init]; + [autoLayoutButton setTitle:@"AutoLayout" forState:UIControlStateNormal]; + [autoLayoutButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; + [autoLayoutButton addTarget:self action:@selector(generateViews) + forControlEvents:UIControlEventTouchUpInside]; + [self.view addSubview:autoLayoutButton]; + [autoLayoutButton mas_makeConstraints:^(MASConstraintMaker *make) { + make.height.mas_equalTo(20); + make.bottom.mas_equalTo(0); + }]; + + UIButton *nestedButton = [[UIButton alloc] init]; + [nestedButton setTitle:@"Nested" forState:UIControlStateNormal]; + [nestedButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; + [nestedButton addTarget:self action:@selector(generateNestedViews) + forControlEvents:UIControlEventTouchUpInside]; + [self.view addSubview:nestedButton]; + [nestedButton mas_makeConstraints:^(MASConstraintMaker *make) { + make.height.mas_equalTo(20); + make.bottom.mas_equalTo(0); + }]; + + UIButton *frameButton = [[UIButton alloc] init]; + [frameButton setTitle:@"Frame" forState:UIControlStateNormal]; + [frameButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; + [frameButton addTarget:self action:@selector(generateFrameViews) forControlEvents:UIControlEventTouchUpInside]; + [self.view addSubview:frameButton]; + [frameButton mas_makeConstraints:^(MASConstraintMaker *make) { + make.height.mas_equalTo(20); + make.bottom.mas_equalTo(0); + }]; + + [@[autoLayoutButton, nestedButton, frameButton] mas_distributeViewsAlongAxis:MASAxisTypeHorizontal + withFixedItemLength:140 leadSpacing:0 tailSpacing:0]; + + _textField = [[UITextField alloc] init]; + _textField.textAlignment = NSTextAlignmentCenter; + [self.view addSubview:_textField]; + [_textField mas_makeConstraints:^(MASConstraintMaker *make) { + make.left.mas_equalTo(20); + make.right.mas_equalTo(-20); + make.bottom.mas_equalTo(autoLayoutButton.mas_top); + make.height.mas_equalTo(20); + }]; + + _indicateLabel = [[UILabel alloc] init]; + _indicateLabel.textColor = [UIColor blackColor]; + _indicateLabel.textAlignment = NSTextAlignmentRight; + [self.view addSubview:_indicateLabel]; + [_indicateLabel mas_makeConstraints:^(MASConstraintMaker *make) { + make.right.top.mas_equalTo(0); + make.height.mas_equalTo(20); + }]; + + UIButton *printResult = [[UIButton alloc] init]; + [printResult setTitle:@"PrintResult" forState:UIControlStateNormal]; + [printResult setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; + [printResult addTarget:self action:@selector(printerResult) forControlEvents:UIControlEventTouchUpInside]; + [self.view addSubview:printResult]; + [printResult mas_makeConstraints:^(MASConstraintMaker *make) { + make.height.mas_equalTo(20); + make.top.left.mas_equalTo(0); + make.width.mas_equalTo(100); + }]; + + _resultDictionary = [[NSMutableDictionary alloc] init]; + [_resultDictionary setObject:[[NSMutableDictionary alloc] init] forKey:@"AutoLayout"]; + [_resultDictionary setObject:[[NSMutableDictionary alloc] init] forKey:@"NestedAutoLayout"]; + [_resultDictionary setObject:[[NSMutableDictionary alloc] init] forKey:@"Frame"]; + [_resultDictionary setObject:[[NSMutableDictionary alloc] init] forKey:@"ASDK"]; +} + +- (void)viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + [_textField becomeFirstResponder]; +} + +- (void)generateViews { + NSInteger number = _textField.text.integerValue; + for (UIView *view in _views) { + [view removeFromSuperview]; + } + _views = [[NSMutableArray alloc] init]; + + NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]; + for (NSInteger i = 0; i < number; i++) { + UIView *leftView = self.view; + UIView *topView = self.view; + if (_views.count != 0) { + NSInteger left = arc4random() % _views.count; + NSInteger top = arc4random() % _views.count; + leftView = _views[left]; + topView = _views[top]; + } + + CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0 + CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white + CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black + UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1]; + + NSInteger leftSpace = (arc4random() % 414) - (int)leftView.frame.origin.x; + NSInteger topSpace = (arc4random() % 568) - (int)topView.frame.origin.y; + + UIView *newView = [[UIView alloc] init]; + newView.backgroundColor = color; + [self.view addSubview:newView]; + [newView mas_makeConstraints:^(MASConstraintMaker *make) { + make.left.mas_greaterThanOrEqualTo(0); + make.right.mas_lessThanOrEqualTo(0); + make.top.mas_greaterThanOrEqualTo(20); + make.bottom.mas_lessThanOrEqualTo(-40); + make.left.mas_equalTo(leftView).offset(leftSpace).priorityMedium(); + make.top.mas_equalTo(topView).offset(topSpace).priorityMedium(); + make.size.mas_equalTo(10); + }]; + + [_views addObject:newView]; + } + NSTimeInterval endTime = [NSDate timeIntervalSinceReferenceDate]; + + NSTimeInterval timeInterval = endTime - startTime; + + NSMutableDictionary *autoLayoutDictionary = _resultDictionary[@"AutoLayout"]; + NSMutableDictionary *currentTimesDictionary = autoLayoutDictionary[@(number)] ?: [[NSMutableDictionary alloc] init]; + NSNumber *times = currentTimesDictionary[@"times"] ? : @0; + NSNumber *avgTime = currentTimesDictionary[@"avgTime"] ? : @0; + currentTimesDictionary[@"avgTime"] = @((times.integerValue * avgTime.doubleValue + timeInterval) / (double)(times.integerValue + 1)); + currentTimesDictionary[@"times"] = @(times.integerValue + 1); + [autoLayoutDictionary setObject:currentTimesDictionary forKey:@(number)]; + + _indicateLabel.text = [NSString stringWithFormat:@"%ld: %f", (long)number, endTime-startTime]; +} + +- (void)generateFrameViews { + NSInteger number = _textField.text.integerValue; + for (UIView *view in _views) { + [view removeFromSuperview]; + } + _views = [[NSMutableArray alloc] init]; + + NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]; + for (NSInteger i = 0; i < number; i++) { + CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0 + CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white + CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black + UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1]; + + NSInteger leftSpace = (arc4random() % 404) % (int)self.view.frame.size.width; + NSInteger topSpace = (arc4random() % 676) % (int)self.view.frame.size.height + 20; + + UIView *newView = [[UIView alloc] init]; + newView.backgroundColor = color; + newView.frame = CGRectMake(leftSpace, topSpace, 10, 10); + [self.view addSubview:newView]; + + [_views addObject:newView]; + } + NSTimeInterval endTime = [NSDate timeIntervalSinceReferenceDate]; + + NSTimeInterval timeInterval = endTime - startTime; + + NSMutableDictionary *frameDictionary = _resultDictionary[@"Frame"]; + NSMutableDictionary *currentTimesDictionary = frameDictionary[@(number)] ?: [[NSMutableDictionary alloc] init]; + NSNumber *times = currentTimesDictionary[@"times"] ? : @0; + NSNumber *avgTime = currentTimesDictionary[@"avgTime"] ? : @0; + currentTimesDictionary[@"avgTime"] = @((times.integerValue * avgTime.doubleValue + timeInterval) / (double)(times.integerValue + 1)); + currentTimesDictionary[@"times"] = @(times.integerValue + 1); + [frameDictionary setObject:currentTimesDictionary forKey:@(number)]; + + _indicateLabel.text = [NSString stringWithFormat:@"%ld: %f", (long)number, endTime-startTime]; +} + +- (void)generateNestedViews { + NSInteger number = _textField.text.integerValue; + for (UIView *view in _views) { + [view removeFromSuperview]; + } + _views = [[NSMutableArray alloc] init]; + + NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]; + for (NSInteger i = 0; i < number; i++) { + UIView *leftView = self.view; + UIView *topView = self.view; + if (_views.count != 0) { + NSInteger left = arc4random() % _views.count; + NSInteger top = arc4random() % _views.count; + leftView = _views[left]; + topView = _views[top]; + } + + CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0 + CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white + CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black + UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1]; + + UIView *newView = [[UIView alloc] init]; + newView.backgroundColor = color; + [self.view addSubview:newView]; + if (_views.count == 0) { + [self.view addSubview:newView]; + + [newView mas_makeConstraints:^(MASConstraintMaker *make) { + make.left.mas_equalTo(0.5); + make.top.mas_equalTo(20.5); + make.bottom.mas_equalTo(-40.5); + make.right.mas_equalTo(-0.5); + }]; + } else { + UIView *aView = _views[i - 1]; + [aView addSubview:newView]; + + [newView mas_makeConstraints:^(MASConstraintMaker *make) { + make.top.left.mas_equalTo(1); + make.bottom.right.mas_equalTo(-1); + }]; + } + + [_views addObject:newView]; + } + NSTimeInterval endTime = [NSDate timeIntervalSinceReferenceDate]; + + NSTimeInterval timeInterval = endTime - startTime; + + NSMutableDictionary *autoLayoutDictionary = _resultDictionary[@"NestedAutoLayout"]; + NSMutableDictionary *currentTimesDictionary = autoLayoutDictionary[@(number)] ?: [[NSMutableDictionary alloc] init]; + NSNumber *times = currentTimesDictionary[@"times"] ? : @0; + NSNumber *avgTime = currentTimesDictionary[@"avgTime"] ? : @0; + currentTimesDictionary[@"avgTime"] = @((times.integerValue * avgTime.doubleValue + timeInterval) / (double)(times.integerValue + 1)); + currentTimesDictionary[@"times"] = @(times.integerValue + 1); + [autoLayoutDictionary setObject:currentTimesDictionary forKey:@(number)]; + + _indicateLabel.text = [NSString stringWithFormat:@"%ld: %f", (long)number, endTime-startTime]; + +} + +- (void)printerResult { + NSLog(@"%@", _resultDictionary); +} + +- (BOOL)prefersStatusBarHidden { + return YES; +} + +@end \ No newline at end of file diff --git a/contents/AsyncDisplayKit/Layout/Layout/main.m b/contents/AsyncDisplayKit/Layout/Layout/main.m new file mode 100644 index 0000000..954480b --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Layout/main.m @@ -0,0 +1,16 @@ +// +// main.m +// Layout +// +// Created by Draveness on 8/28/16. +// Copyright © 2016 Draveness. All rights reserved. +// + +#import +#import "AppDelegate.h" + +int main(int argc, char * argv[]) { + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + } +} diff --git a/contents/AsyncDisplayKit/Layout/Podfile b/contents/AsyncDisplayKit/Layout/Podfile new file mode 100644 index 0000000..c853f7c --- /dev/null +++ b/contents/AsyncDisplayKit/Layout/Podfile @@ -0,0 +1,7 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '9.0' + +target 'Layout' do + # use_frameworks! + pod 'Masonry' +end diff --git a/contents/AsyncDisplayKit/images/CRT.png b/contents/AsyncDisplayKit/images/CRT.png new file mode 100644 index 0000000..291af72 Binary files /dev/null and b/contents/AsyncDisplayKit/images/CRT.png differ diff --git a/contents/AsyncDisplayKit/images/advertise.jpg b/contents/AsyncDisplayKit/images/advertise.jpg new file mode 100644 index 0000000..cb44637 Binary files /dev/null and b/contents/AsyncDisplayKit/images/advertise.jpg differ diff --git a/contents/AsyncDisplayKit/images/apple-a9.jpg b/contents/AsyncDisplayKit/images/apple-a9.jpg new file mode 100644 index 0000000..d50cff3 Binary files /dev/null and b/contents/AsyncDisplayKit/images/apple-a9.jpg differ diff --git a/contents/AsyncDisplayKit/images/asdk-hierarchy.png b/contents/AsyncDisplayKit/images/asdk-hierarchy.png new file mode 100644 index 0000000..544294a Binary files /dev/null and b/contents/AsyncDisplayKit/images/asdk-hierarchy.png differ diff --git a/contents/AsyncDisplayKit/images/asdk-logo.png b/contents/AsyncDisplayKit/images/asdk-logo.png new file mode 100644 index 0000000..dce1ebc Binary files /dev/null and b/contents/AsyncDisplayKit/images/asdk-logo.png differ diff --git a/contents/AsyncDisplayKit/images/aslayout-range-mode-display-preload.jpeg b/contents/AsyncDisplayKit/images/aslayout-range-mode-display-preload.jpeg new file mode 100644 index 0000000..f0cd284 Binary files /dev/null and b/contents/AsyncDisplayKit/images/aslayout-range-mode-display-preload.jpeg differ diff --git a/contents/AsyncDisplayKit/images/astableview-astablenode.jpg b/contents/AsyncDisplayKit/images/astableview-astablenode.jpg new file mode 100644 index 0000000..0c4a039 Binary files /dev/null and b/contents/AsyncDisplayKit/images/astableview-astablenode.jpg differ diff --git a/contents/AsyncDisplayKit/images/astableview-data.png b/contents/AsyncDisplayKit/images/astableview-data.png new file mode 100644 index 0000000..745edb1 Binary files /dev/null and b/contents/AsyncDisplayKit/images/astableview-data.png differ diff --git a/contents/AsyncDisplayKit/images/async-node-calculate.jpeg b/contents/AsyncDisplayKit/images/async-node-calculate.jpeg new file mode 100644 index 0000000..90f4f20 Binary files /dev/null and b/contents/AsyncDisplayKit/images/async-node-calculate.jpeg differ diff --git a/contents/AsyncDisplayKit/images/box-layout.jpg b/contents/AsyncDisplayKit/images/box-layout.jpg new file mode 100644 index 0000000..feff3a7 Binary files /dev/null and b/contents/AsyncDisplayKit/images/box-layout.jpg differ diff --git a/contents/AsyncDisplayKit/images/cache-layer.png b/contents/AsyncDisplayKit/images/cache-layer.png new file mode 100644 index 0000000..dec7937 Binary files /dev/null and b/contents/AsyncDisplayKit/images/cache-layer.png differ diff --git a/contents/AsyncDisplayKit/images/cellforrowatindexpath.jpg b/contents/AsyncDisplayKit/images/cellforrowatindexpath.jpg new file mode 100644 index 0000000..6bdb48b Binary files /dev/null and b/contents/AsyncDisplayKit/images/cellforrowatindexpath.jpg differ diff --git a/contents/AsyncDisplayKit/images/cpu-gpu.jpg b/contents/AsyncDisplayKit/images/cpu-gpu.jpg new file mode 100644 index 0000000..cc341e2 Binary files /dev/null and b/contents/AsyncDisplayKit/images/cpu-gpu.jpg differ diff --git a/contents/AsyncDisplayKit/images/dynamic-threshold.jpeg b/contents/AsyncDisplayKit/images/dynamic-threshold.jpeg new file mode 100644 index 0000000..b94d8c0 Binary files /dev/null and b/contents/AsyncDisplayKit/images/dynamic-threshold.jpeg differ diff --git a/contents/AsyncDisplayKit/images/dynamic-threshold.jpg b/contents/AsyncDisplayKit/images/dynamic-threshold.jpg new file mode 100644 index 0000000..f3f0c4d Binary files /dev/null and b/contents/AsyncDisplayKit/images/dynamic-threshold.jpg differ diff --git a/contents/AsyncDisplayKit/images/how-to-solve-tearing-problem.jpg b/contents/AsyncDisplayKit/images/how-to-solve-tearing-problem.jpg new file mode 100644 index 0000000..8a361e6 Binary files /dev/null and b/contents/AsyncDisplayKit/images/how-to-solve-tearing-problem.jpg differ diff --git a/contents/AsyncDisplayKit/images/infinite-list.jpg b/contents/AsyncDisplayKit/images/infinite-list.jpg new file mode 100644 index 0000000..ecef2a8 Binary files /dev/null and b/contents/AsyncDisplayKit/images/infinite-list.jpg differ diff --git a/contents/AsyncDisplayKit/images/intelligent-preloading-ranges-screenfuls.png b/contents/AsyncDisplayKit/images/intelligent-preloading-ranges-screenfuls.png new file mode 100644 index 0000000..019762c Binary files /dev/null and b/contents/AsyncDisplayKit/images/intelligent-preloading-ranges-screenfuls.png differ diff --git a/contents/AsyncDisplayKit/images/intelligent-preloading-ranges-with-names.png b/contents/AsyncDisplayKit/images/intelligent-preloading-ranges-with-names.png new file mode 100644 index 0000000..472163b Binary files /dev/null and b/contents/AsyncDisplayKit/images/intelligent-preloading-ranges-with-names.png differ diff --git a/contents/AsyncDisplayKit/images/lag-vsync.png b/contents/AsyncDisplayKit/images/lag-vsync.png new file mode 100644 index 0000000..9204986 Binary files /dev/null and b/contents/AsyncDisplayKit/images/lag-vsync.png differ diff --git a/contents/AsyncDisplayKit/images/layout-header.jpg b/contents/AsyncDisplayKit/images/layout-header.jpg new file mode 100644 index 0000000..f218a6b Binary files /dev/null and b/contents/AsyncDisplayKit/images/layout-header.jpg differ diff --git a/contents/AsyncDisplayKit/images/layout-hierarchy.png b/contents/AsyncDisplayKit/images/layout-hierarchy.png new file mode 100644 index 0000000..658829d Binary files /dev/null and b/contents/AsyncDisplayKit/images/layout-hierarchy.png differ diff --git a/contents/AsyncDisplayKit/images/layout-phase.png b/contents/AsyncDisplayKit/images/layout-phase.png new file mode 100644 index 0000000..b6fae26 Binary files /dev/null and b/contents/AsyncDisplayKit/images/layout-phase.png differ diff --git a/contents/AsyncDisplayKit/images/lazy-loading.png b/contents/AsyncDisplayKit/images/lazy-loading.png new file mode 100644 index 0000000..131dad3 Binary files /dev/null and b/contents/AsyncDisplayKit/images/lazy-loading.png differ diff --git a/contents/AsyncDisplayKit/images/lcd.png b/contents/AsyncDisplayKit/images/lcd.png new file mode 100644 index 0000000..71320cc Binary files /dev/null and b/contents/AsyncDisplayKit/images/lcd.png differ diff --git a/contents/AsyncDisplayKit/images/masonry.jpg b/contents/AsyncDisplayKit/images/masonry.jpg new file mode 100644 index 0000000..087cd70 Binary files /dev/null and b/contents/AsyncDisplayKit/images/masonry.jpg differ diff --git a/contents/AsyncDisplayKit/images/multi-layer-asdk.jpg b/contents/AsyncDisplayKit/images/multi-layer-asdk.jpg new file mode 100644 index 0000000..6eb1d06 Binary files /dev/null and b/contents/AsyncDisplayKit/images/multi-layer-asdk.jpg differ diff --git a/contents/AsyncDisplayKit/images/multi-layer.jpg b/contents/AsyncDisplayKit/images/multi-layer.jpg new file mode 100644 index 0000000..afd96c0 Binary files /dev/null and b/contents/AsyncDisplayKit/images/multi-layer.jpg differ diff --git a/contents/AsyncDisplayKit/images/network.jpg b/contents/AsyncDisplayKit/images/network.jpg new file mode 100644 index 0000000..f2cdd57 Binary files /dev/null and b/contents/AsyncDisplayKit/images/network.jpg differ diff --git a/contents/AsyncDisplayKit/images/normal-vsync.png b/contents/AsyncDisplayKit/images/normal-vsync.png new file mode 100644 index 0000000..9cb93a5 Binary files /dev/null and b/contents/AsyncDisplayKit/images/normal-vsync.png differ diff --git a/contents/AsyncDisplayKit/images/performance-chart-100-1000.jpeg b/contents/AsyncDisplayKit/images/performance-chart-100-1000.jpeg new file mode 100644 index 0000000..ca7aeac Binary files /dev/null and b/contents/AsyncDisplayKit/images/performance-chart-100-1000.jpeg differ diff --git a/contents/AsyncDisplayKit/images/performance-layout-10-90.jpeg b/contents/AsyncDisplayKit/images/performance-layout-10-90.jpeg new file mode 100644 index 0000000..3fcf4ff Binary files /dev/null and b/contents/AsyncDisplayKit/images/performance-layout-10-90.jpeg differ diff --git a/contents/AsyncDisplayKit/images/performance-loss.jpeg b/contents/AsyncDisplayKit/images/performance-loss.jpeg new file mode 100644 index 0000000..07d116a Binary files /dev/null and b/contents/AsyncDisplayKit/images/performance-loss.jpeg differ diff --git a/contents/AsyncDisplayKit/images/performance-nested-autolayout-frame.jpeg b/contents/AsyncDisplayKit/images/performance-nested-autolayout-frame.jpeg new file mode 100644 index 0000000..1f07b26 Binary files /dev/null and b/contents/AsyncDisplayKit/images/performance-nested-autolayout-frame.jpeg differ diff --git a/contents/AsyncDisplayKit/images/phone-in-hand.jpg b/contents/AsyncDisplayKit/images/phone-in-hand.jpg new file mode 100644 index 0000000..21a8d04 Binary files /dev/null and b/contents/AsyncDisplayKit/images/phone-in-hand.jpg differ diff --git a/contents/AsyncDisplayKit/images/placeholder-layer.png b/contents/AsyncDisplayKit/images/placeholder-layer.png new file mode 100644 index 0000000..306e71a Binary files /dev/null and b/contents/AsyncDisplayKit/images/placeholder-layer.png differ diff --git a/contents/AsyncDisplayKit/images/pros-cons.jpg b/contents/AsyncDisplayKit/images/pros-cons.jpg new file mode 100644 index 0000000..a742a0d Binary files /dev/null and b/contents/AsyncDisplayKit/images/pros-cons.jpg differ diff --git a/contents/AsyncDisplayKit/images/screen-tearing.jpg b/contents/AsyncDisplayKit/images/screen-tearing.jpg new file mode 100644 index 0000000..bd83f0c Binary files /dev/null and b/contents/AsyncDisplayKit/images/screen-tearing.jpg differ diff --git a/contents/AsyncDisplayKit/images/scrollview-demo.png b/contents/AsyncDisplayKit/images/scrollview-demo.png new file mode 100644 index 0000000..3f92e75 Binary files /dev/null and b/contents/AsyncDisplayKit/images/scrollview-demo.png differ diff --git a/contents/AsyncDisplayKit/images/stack.jpg b/contents/AsyncDisplayKit/images/stack.jpg new file mode 100644 index 0000000..7e9823e Binary files /dev/null and b/contents/AsyncDisplayKit/images/stack.jpg differ diff --git a/contents/AsyncDisplayKit/images/threshold.jpeg b/contents/AsyncDisplayKit/images/threshold.jpeg new file mode 100644 index 0000000..60bdf61 Binary files /dev/null and b/contents/AsyncDisplayKit/images/threshold.jpeg differ diff --git a/contents/AsyncDisplayKit/images/view-demonstrate.png b/contents/AsyncDisplayKit/images/view-demonstrate.png new file mode 100644 index 0000000..68e6a0a Binary files /dev/null and b/contents/AsyncDisplayKit/images/view-demonstrate.png differ diff --git a/contents/AsyncDisplayKit/images/view-layer-cg-compare.png b/contents/AsyncDisplayKit/images/view-layer-cg-compare.png new file mode 100644 index 0000000..a4f9e63 Binary files /dev/null and b/contents/AsyncDisplayKit/images/view-layer-cg-compare.png differ diff --git "a/contents/AsyncDisplayKit/\344\273\216 Auto Layout \347\232\204\345\270\203\345\261\200\347\256\227\346\263\225\350\260\210\346\200\247\350\203\275.md" "b/contents/AsyncDisplayKit/\344\273\216 Auto Layout \347\232\204\345\270\203\345\261\200\347\256\227\346\263\225\350\260\210\346\200\247\350\203\275.md" new file mode 100644 index 0000000..aff99d4 --- /dev/null +++ "b/contents/AsyncDisplayKit/\344\273\216 Auto Layout \347\232\204\345\270\203\345\261\200\347\256\227\346\263\225\350\260\210\346\200\247\350\203\275.md" @@ -0,0 +1,319 @@ +# 从 Auto Layout 的布局算法谈性能 + +> 这是使用 ASDK 性能调优系列的第二篇文章,前一篇文章中讲到了如何提升 iOS 应用的渲染性能,你可以点击 [这里](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/AsyncDisplayKit/提升%20iOS%20界面的渲染性能.md) 了解这部分的内容。 + +在上一篇文章中,我们提到了 iOS 界面的渲染过程以及如何对渲染过程进行优化。ASDK 的做法是将渲染绘制的工作抛到后台线程进行,并在每次 Runloop 结束时,将绘制结果交给 `CALayer` 进行展示。 + +而这篇文章就要从 iOS 中影响性能的另一大杀手,也就是万恶之源 Auto Layout(自动布局)来分析如何对 iOS 应用的性能进行优化以及 Auto Layout 到底为什么会影响性能? + +![box-layout](images/box-layout.jpg) + +## 把 Auto Layout 批判一番 + +由于在 2012 年苹果发布了 4.0 寸的 iPhone5,在 iOS 平台上出现了不同尺寸的移动设备,使得原有的 `frame` 布局方式无法很好地适配不同尺寸的屏幕,所以,为了解决这一问题 Auto Layout 就诞生了。 + +Auto Layout 的诞生并没有如同苹果的其它框架一样收到开发者的好评,它自诞生的第一天起就饱受 iOS 开发者的批评,其蹩脚、冗长的语法使得它在刚刚面世就被无数开发者吐槽,写了几个屏幕的代码都不能完成一个简单的布局,哪怕是 VFL(Visual Format Language)也拯救不了它。 + +真正使 Auto Layout 大规模投入使用的应该还是 [Masonry](https://github.com/SnapKit/Masonry),它使用了链式的语法对 Auto Layout 进行了很好的封装,使得 Auto Layout 更加简单易用;时至今日,开发者也在日常使用中发现了 Masonry 的各种问题,于是出现了各种各样的布局框架,不过这都是后话了。 + +![masonry](images/masonry.jpg) + +## Auto Layout 的原理和 Cassowary + +Auto Layout 的原理其实非常简单,在这里通过一个例子先简单的解释一下: + +![view-demonstrate](images/view-demonstrate.png) + +iOS 中视图所需要的布局信息只有两个,分别是 `origin/center` 和 `size`,在这里我们以 `origin & size` 为例,也就是 `frame` 时代下布局的需要的两个信息;这两个信息由四部分组成: + ++ `x` & `y` ++ `width` & `height` + +以左上角的 `(0, 0)` 为坐标的原点,找到坐标 `(x, y)`,然后绘制一个大小为 `(width, height)` 的矩形,这样就完成了一个最简单的布局。而 Auto Layout 的布局方式与上面所说的 `frame` 有些不同,`frame` 的原理是与父视图之间的绝对距离,但是 Auto Layout 中大部分的约束都是**描述性的**,表示视图间相对距离,以上图为例: + +```objectivec +A.left = Superview.left + 50 +A.top = Superview.top + 30 +A.width = 100 +A.height = 100 + +B.left = (A.left + A.width)/(A.right) + 30 +B.top = A.top +B.width = A.width +B.height = A.height +``` + +虽然上面的约束很好的表示了各个视图之间的关系,但是 Auto Layout 实际上并没有改变原有的 Hard-Coded 形式的布局方式,只是将原有没有太多意义的 `(x, y)` 值,变成了描述性的代码。 + +我们仍然需要知道布局信息所需要的四部分 `x`、`y`、`width` 以及 `height`。换句话说,我们要求解上述的**八元一次**方程组,将每个视图所需要的信息解出来;Cocoa 会在运行时求解上述的方程组,最终使用 `frame` 来绘制视图。 + +![layout-phase](images/layout-phase.png) + +### Cassowary 算法 + +在上世纪 90 年代,一个名叫 [Cassowary](https://en.wikipedia.org/wiki/Cassowary_(software)) 的布局算法解决了用户界面的布局问题,它通过将布局问题抽象成线性等式和不等式约束来进行求解。 + +Auto Layout 其实就是对 Cassowary 算法的一种实现,但是这里并不会对它展开介绍,有兴趣的读者可以在文章最后的 Reference 中了解一下 Cassowary 算法相关的文章。 + +> Auto Layout 的原理就是对**线性方程组或者不等式**的求解。 + +## Auto Layout 的性能 + +在使用 Auto Layout 进行布局时,可以指定一系列的约束,比如视图的高度、宽度等等。而每一个约束其实都是一个简单的线性等式或不等式,整个界面上的所有约束在一起就**明确地(没有冲突)**定义了整个系统的布局。 + +> 在涉及冲突发生时,Auto Layout 会尝试 break 一些优先级低的约束,尽量满足最多并且优先级最高的约束。 + +因为布局系统在最后仍然需要通过 `frame` 来进行,所以 Auto Layout 虽然为开发者在描述布局时带来了一些好处,不过它相比原有的布局系统加入了从约束计算 `frame` 的过程,而在这里,我们需要了解 Auto Layout 的布局性能如何。 + +![performance-loss](images/performance-loss.jpeg) + +因为使用 Cassowary 算法解决约束问题就是对线性等式或不等式求解,所以其时间复杂度就是**多项式时间**的,不难推测出,在处理极其复杂的 UI 界面时,会造成性能上的巨大损失。 + +在这里我们会对 Auto Layout 的性能进行测试,为了更明显的展示 Auto Layout 的性能,我们通过 `frame` 的性能建立一条基准线**以消除对象的创建和销毁、视图的渲染、视图层级的改变带来的影响**。 + +> 你可以在 [这里](https://github.com/Draveness/iOS-Source-Code-Analyze/tree/master/contents/AsyncDisplayKit/Layout) 找到这次对 Layout 性能测量使用的代码。 + +代码分别使用 Auto Layout 和 `frame` 对 N 个视图进行布局,测算其运行时间。 + +使用 AutoLayout 时,每个视图会随机选择两个视图对它的 `top` 和 `left` 进行约束,随机生成一个数字作为 `offset`;同时,还会用几个优先级高的约束保证视图的布局不会超出整个 `keyWindow`。 + +而下图就是对 100~1000 个视图布局所需要的时间的折线图。 + +> 这里的数据是在 OS X EL Captain,Macbook Air (13-inch Mid 2013)上的 iPhone 6s Plus 模拟器上采集的, Xcode 版本为 7.3.1。在其他设备上可能不会获得一致的信息,由于笔者的 iPhone 升级到了 iOS 10,所以没有办法真机测试,最后的结果可能会有一定的偏差。 + +![performance-chart-100-1000](images/performance-chart-100-1000.jpeg) + +从图中可以看到,使用 Auto Layout 进行布局的时间会是只使用 `frame` 的 **16 倍**左右,虽然这里的测试结果可能**受外界条件影响差异**比较大,不过 Auto Layout 的性能相比 `frame` 确实差很多,如果去掉设置 `frame` 的过程消耗的时间,Auto Layout 过程进行的计算量也是非常巨大的。 + +在上一篇文章中,我们曾经提到,想要让 iOS 应用的视图保持 60 FPS 的刷新频率,我们必须在 **1/60 = 16.67 ms** 之内完成包括布局、绘制以及渲染等操作。 + +也就是说如果当前界面上的视图大于 100 的话,使用 Auto Layout 是很难达到绝对流畅的要求的;而在使用 `frame` 时,同一个界面下哪怕有 500 个视图,也是可以在 16.67 ms 之内完成布局的。不过在一般情况下,在 iOS 的整个 `UIWindow` 中也不会一次性出现如此多的视图。 + +我们更关心的是,在日常开发中难免会使用 Auto Layout 进行布局,既然有 16.67 ms 这个限制,那么在界面上出现了多少个视图时,我才需要考虑其它的布局方式呢?在这里,我们将需要布局的视图数量减少一个量级,重新绘制一个图表: + +![performance-layout-10-90](images/performance-layout-10-90.jpeg) + +从图中可以看出,当对 **30 个左右视图**使用 Auto Layout 进行布局时,所需要的时间就会在 16.67 ms 左右,当然这里不排除一些其它因素的影响;到目前为止,会得出一个大致的结论,使用 Auto Layout 对复杂的 UI 界面进行布局时(大于 30 个视图)就会对性能有严重的影响(同时与设备有关,文章中不会考虑设备性能的差异性)。 + +上述对 Auto Layout 的使用还是比较简单的,而在日常使用中,使用嵌套的视图层级又非常正常。 + +> 在笔者对嵌套视图层级中使用 Auto Layout 进行布局时,当视图的数量超过了 500 时,模拟器直接就 crash 了,所以这里没有超过 500 个视图的数据。 + +我们对嵌套视图数量在 100~500 之间布局时间进行测量,并与 Auto Layout 进行比较: + +![performance-nested-autolayout-frame](images/performance-nested-autolayout-frame.jpeg) + +在视图数量大于 200 之后,随着视图数量的增加,使用 Auto Layout 对嵌套视图进行布局的时间相比非嵌套的布局成倍增长。 + +虽然说 Auto Layout 为开发者在多尺寸布局上提供了遍历,而且**支持跨越视图层级**的约束,但是由于其实现原理导致其时间复杂度为**多项式时间**,其性能损耗是仅使用 `frame` 的十几倍,所以在处理庞大的 UI 界面时表现差强人意。 + +> 在三年以前,有一篇关于 Auto Layout 性能分析的文章,可以点击这里了解这篇文章的内容 [Auto Layout Performance on iOS](http://floriankugler.com/2013/04/22/auto-layout-performance-on-ios/)。 + +## ASDK 的布局引擎 + +Auto Layout 不止在复杂 UI 界面布局的表现不佳,它还会强制视图在主线程上布局;所以在 ASDK 中提供了另一种可以在后台线程中运行的布局引擎,它的结构大致是这样的: + +![layout-hierarchy](images/layout-hierarchy.png) + +`ASLayoutSpec` 与下面的所有的 Spec 类都是继承关系,在视图需要布局时,会调用 `ASLayoutSpec` 或者它的子类的 `- measureWithSizeRange:` 方法返回一个用于布局的对象 [ASLayout](#aslayout)。 + +> `ASLayoutable` 是 ASDK 中一个协议,遵循该协议的类实现了一系列的布局方法。 + +当我们使用 ASDK 布局时,需要做下面四件事情中的一件: + ++ 提供 `layoutSpecBlock` ++ 覆写 `- layoutSpecThatFits:` 方法 ++ 覆写 `- calculateSizeThatFits:` 方法 ++ 覆写 `- calculateLayoutThatFits:` 方法 + +只有做上面四件事情中的其中一件才能对 ASDK 中的视图或者说结点进行布局。 + +方法 `- calculateSizeThatFits:` 提供了手动布局的方式,通过在该方法内对 `frame` 进行计算,返回一个当前视图的 `CGSize`。 + +而 `- layoutSpecThatFits:` 与 `layoutSpecBlock` 其实没什么不同,只是前者通过覆写方法返回 `ASLayoutSpec`;后者通过 block 的形式提供一种不需要子类化就可以完成布局的方法,两者可以看做是完全等价的。 + +`- calculateLayoutThatFits:` 方法有一些不同,它把上面的两种布局方式:手动布局和 Spec 布局封装成了一个接口,这样,无论是 `CGSize` 还是 `ASLayoutSpec` 最后都会以 `ASLayout` 的形式返回给方法调用者。 + +### 手动布局 + +这里简单介绍一下手动布局使用的 `-[ASDisplayNode calculatedSizeThatFits:]` 方法,这个方法与 `UIView` 中的 `-[UIView sizeThatFits:]` 非常相似,其区别只是在 ASDK 中,所有的计算出的大小都会通过缓存来提升性能。 + +```objectivec +- (CGSize)calculateSizeThatFits:(CGSize)constrainedSize { + return _preferredFrameSize; +} +``` + +子类可以在这个方法中进行计算,通过覆写这个方法返回一个合适的大小,不过一般情况下都不会使用手动布局的方式。 + +### 使用 ASLayoutSpec 布局 + +在 ASDK 中,更加常用的是使用 `ASLayoutSpec` 布局,在上面提到的 `ASLayout` 是一个保存布局信息的媒介,而真正计算视图布局的代码都在 `ASLayoutSpec` 中;所有 ASDK 中的布局(手动 / Spec)都是由 `-[ASLayoutable measureWithSizeRange:]` 方法触发的,在这里我们以 `ASDisplayNode` 的调用栈为例看一下方法的执行过程: + +```objectivec +-[ASDisplayNode measureWithSizeRange:] + -[ASDisplayNode shouldMeasureWithSizeRange:] + -[ASDisplayNode calculateLayoutThatFits:] + -[ASDisplayNode layoutSpecThatFits:] + -[ASLayoutSpec measureWithSizeRange:] + +[ASLayout layoutWithLayoutableObject:constrainedSizeRange:size:sublayouts:] + -[ASLayout filteredNodeLayoutTree] +``` + +ASDK 的文档中推荐在子类中覆写 `- layoutSpecThatFits:` 方法,返回一个用于布局的 `ASLayoutSpec` 对象,然后使用 `ASLayoutSpec` 中的 `- measureWithSizeRange:` 方法对它指定的视图进行布局,不过通过覆写 [ASDK 的布局引擎](#asdk-的布局引擎) 一节中的其它方法也都是可以的。 + +如果我们使用 `ASStackLayoutSpec` 对视图进行布局的话,方法调用栈大概是这样的: + +```objectivec +-[ASDisplayNode measureWithSizeRange:] + -[ASDisplayNode shouldMeasureWithSizeRange:] + -[ASDisplayNode calculateLayoutThatFits:] + -[ASDisplayNode layoutSpecThatFits:] + -[ASStackLayoutSpec measureWithSizeRange:] + ASStackUnpositionedLayout::compute + ASStackPositionedLayout::compute ASStackBaselinePositionedLayout::compute +[ASLayout layoutWithLayoutableObject:constrainedSizeRange:size:sublayouts:] + -[ASLayout filteredNodeLayoutTree] +``` + +这里只是执行了 `ASStackLayoutSpec` 对应的 `- measureWithSizeRange:` 方法,对其中的视图进行布局。在 `- measureWithSizeRange:` 中调用了一些 C++ 方法 `ASStackUnpositionedLayout`、`ASStackPositionedLayout` 以及 `ASStackBaselinePositionedLayout` 的 `compute` 方法,这些方法完成了对 `ASStackLayoutSpec` 中视图的布局。 + +相比于 Auto Layout,ASDK 实现了一种完全不同的布局方式;比较类似与前端开发中的 `Flexbox` 模型,而 ASDK 其实就实现了 `Flexbox` 的一个子集。 + +在 ASDK 1.0 时代,很多开发者都表示希望 ASDK 中加入 ComponentKit 的布局引擎;而现在,ASDK 布局引擎的大部分代码都是从 [ComponentKit](http://componentkit.org) 中移植过来的(ComponentKit 是另一个 Facebook 团队开发的用于布局的框架)。 + +#### ASLayout + +`ASLayout` 表示当前的结点在布局树中的大小和位置;当然,它还有一些其它的奇怪的属性: + +```objectivec +@interface ASLayout : NSObject + +@property (nonatomic, weak, readonly) id layoutableObject; +@property (nonatomic, readonly) CGSize size; +@property (nonatomic, readwrite) CGPoint position; +@property (nonatomic, readonly) NSArray *sublayouts; +@property (nonatomic, readonly) CGRect frame; + +... + +@end +``` + +代码中的 `layoutableObject` 表示当前的对象,`sublayouts` 表示当前视图的子布局 `ASLayout` 数组。 + +整个类的实现都没有什么值得多说的,除了大量的构造方法,唯一一个做了一些事情的就是 `-[ASLayout filteredNodeLayoutTree]` 方法了: + +```objectivec +- (ASLayout *)filteredNodeLayoutTree { + NSMutableArray *flattenedSublayouts = [NSMutableArray array]; + struct Context { + ASLayout *layout; + CGPoint absolutePosition; + }; + std::queue queue; + queue.push({self, CGPointMake(0, 0)}); + while (!queue.empty()) { + Context context = queue.front(); + queue.pop(); + + if (self != context.layout && context.layout.type == ASLayoutableTypeDisplayNode) { + ASLayout *layout = [ASLayout layoutWithLayout:context.layout position:context.absolutePosition]; + layout.flattened = YES; + [flattenedSublayouts addObject:layout]; + } + + for (ASLayout *sublayout in context.layout.sublayouts) { + if (sublayout.isFlattened == NO) queue.push({sublayout, context.absolutePosition + sublayout.position}); + } + + return [ASLayout layoutWithLayoutableObject:_layoutableObject + constrainedSizeRange:_constrainedSizeRange + size:_size + sublayouts:flattenedSublayouts]; +} +``` + +而这个方法也只是将 `sublayouts` 中的内容展平,然后实例化一个新的 `ASLayout` 对象。 + +#### ASLayoutSpec + +`ASLayoutSpec` 的作用更像是一个抽象类,在真正使用 ASDK 的布局引擎时,都不会直接使用这个类,而是会用类似 `ASStackLayoutSpec`、`ASRelativeLayoutSpec`、`ASOverlayLayoutSpec` 以及 `ASRatioLayoutSpec` 等子类。 + +笔者不打算一行一行代码深入讲解其内容,简单介绍一下最重要的 `ASStackLayoutSpec`。 + +![stack](images/stack.jpg) + +`ASStackLayoutSpec` 从 `Flexbox` 中获得了非常多的灵感,比如说 `justifyContent`、`alignItems` 等属性,它和苹果的 `UIStackView` 比较类似,不过底层并没有使用 Auto Layout 进行计算。如果没有接触过 `ASStackLayoutSpec` 的开发者,可以通过这个小游戏 [Foggy-ASDK-Layout](http://nguyenhuy.github.io/froggy-asdk-layout/) 快速学习 `ASStackLayoutSpec` 的使用。 + +### 关于缓存以及异步并发 + +因为计算视图的 `CGRect` 进行布局是一种非常昂贵的操作,所以 ASDK 在这里面加入了缓存机制,在每次执行 `- measureWithSizeRange:` 方法时,都会通过 `-shouldMeasureWithSizeRange:` 判断是否需要重新计算布局: + +```objectivec +- (BOOL)shouldMeasureWithSizeRange:(ASSizeRange)constrainedSize { + return [self _hasDirtyLayout] || !ASSizeRangeEqualToSizeRange(constrainedSize, _calculatedLayout.constrainedSizeRange); +} + +- (BOOL)_hasDirtyLayout { + return _calculatedLayout == nil || _calculatedLayout.isDirty; +} +``` + +在一般情况下,只有当前结点被标记为 `dirty` 或者这一次布局传入的 `constrainedSize` 不同时,才需要进行重新计算。在不需要重新计算布局的情况下,只需要直接返回 `_calculatedLayout` 布局对象就可以了。 + +因为 ASDK 实现的布局引擎其实只是对 `frame` 的计算,所以无论是在主线程还是后台的异步并发进程中都是可以执行的,也就是说,你可以在任意线程中调用 `- measureWithSizeRange:` 方法,ASDK 中的一些 `ViewController` 比如:`ASDataViewController` 就会在后台并发进程中执行该方法: + +```objectivec +- (NSArray *)_layoutNodesFromContexts:(NSArray *)contexts { + ... + + dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + dispatch_apply(nodeCount, queue, ^(size_t i) { + ASIndexedNodeContext *context = contexts[i]; + ASCellNode *node = [context allocateNode]; + if (node == nil) node = [[ASCellNode alloc] init]; + + CGRect frame = CGRectZero; + frame.size = [node measureWithSizeRange:context.constrainedSize].size; + node.frame = frame; + + [ASDataController _didLayoutNode]; + }); + + ... + + return nodes; +} +``` + +> 上述代码做了比较大的修改,将原有一些方法调用放到了当前方法中,并省略了大量的代码。 + +### 关于性能的对比 + +由于 ASDK 的布局引擎的问题,其性能比较难以测试,在这里只对 ASDK 使用 `ASStackLayoutSpec` 的**布局计算时间**进行了测试,不包括视图的渲染以及其它时间: + +![async-node-calculate](images/async-node-calculate.jpeg) + +测试结果表明 `ASStackLayoutSpec` 花费的布局时间与结点的数量成正比,哪怕计算 100 个视图的布局也只需要 **8.89 ms**,虽然这里没有包括视图的渲染时间,不过与 Auto Layout 相比性能还是有比较大的提升。 + +## 总结 + +其实 ASDK 的布局引擎大部分都是对 ComponentKit 的封装,不过由于摆脱了 Auto Layout 这一套低效但是通用的布局方式,ASDK 的布局计算不仅在后台并发线程中进行、而且通过引入 `Flexbox` 提升了布局的性能,但是 ASDK 的使用相对比较复杂,如果只想对布局性能进行优化,更推荐单独使用 ComponentKit 框架。 + +## References + ++ [Cassowary, Cocoa Auto Layout, and enaml constraints](http://stacks.11craft.com/cassowary-cocoa-autolayout-and-enaml-constraints.html) ++ [Solving constraint systems](http://cassowary.readthedocs.io/en/latest/topics/theory.html) ++ [Auto Layout Performance on iOS](http://floriankugler.com/2013/04/22/auto-layout-performance-on-ios/) ++ [The Cassowary Linear Arithmetic Constraint Solving Algorithm: Interface and Implementation](https://constraints.cs.washington.edu/cassowary/cassowary-tr.pdf) ++ [The Cassowary Linear Arithmetic Constraint Solving Algorithm](http://constraints.cs.washington.edu/solvers/cassowary-tochi.pdf) ++ [Solving Linear Arithmetic Constraints for User Interface Applications](http://constraints.cs.washington.edu/solvers/uist97.pdf) ++ [AsyncDisplayKit 介绍(二)布局系统](https://medium.com/@jasonyuh/asyncdisplaykit介绍-二-布局系统-1f1a674cf644#.8jskykm15) + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/layout-performance + + diff --git "a/contents/AsyncDisplayKit/\344\275\277\347\224\250 ASDK \346\200\247\350\203\275\350\260\203\344\274\230 - \346\217\220\345\215\207 iOS \347\225\214\351\235\242\347\232\204\346\270\262\346\237\223\346\200\247\350\203\275.md" "b/contents/AsyncDisplayKit/\344\275\277\347\224\250 ASDK \346\200\247\350\203\275\350\260\203\344\274\230 - \346\217\220\345\215\207 iOS \347\225\214\351\235\242\347\232\204\346\270\262\346\237\223\346\200\247\350\203\275.md" new file mode 100644 index 0000000..07bf5cf --- /dev/null +++ "b/contents/AsyncDisplayKit/\344\275\277\347\224\250 ASDK \346\200\247\350\203\275\350\260\203\344\274\230 - \346\217\220\345\215\207 iOS \347\225\214\351\235\242\347\232\204\346\270\262\346\237\223\346\200\247\350\203\275.md" @@ -0,0 +1,808 @@ +# 使用 ASDK 性能调优 - 提升 iOS 界面的渲染性能 + +> 这一系列的文章会从几个方面对 [ASDK](http://asyncdisplaykit.org) 在性能调优方面策略的实现进行分析,帮助读者理解 ASDK 如何做到使复杂的 UI 界面达到 60 FPS 的刷新频率的;本篇文章会从视图的渲染层面讲解 ASDK 对于渲染过程的优化并对 ASDK 进行概述。 + +在客户端或者前端开发中,对于性能的优化,尤其是 UI,往往都不是最先考虑的问题。 + +因为在大多数场景下,使用更加复杂的高性能代码替代可用的代码经常会导致代码的可维护性下降,所以更需要我们开发者对优化的时间点以及原因有一个比较清楚的认识,避免过度优化带来的问题。 + +对 iOS 开发比较熟悉的开发者都知道,iOS 中的性能问题大多是阻塞主线程导致用户的交互反馈出现可以感知的延迟。 + +![scrollview-demo](images/scrollview-demo.png) + +详细说起来,大体有三种原因: + +1. UI 渲染需要时间较长,无法按时提交结果; +2. 一些需要**密集计算**的处理放在了主线程中执行,导致主线程被阻塞,无法渲染 UI 界面; +3. 网络请求由于网络状态的问题响应较慢,UI 层由于没有模型返回无法渲染。 + +上面的这些问题都会影响应用的性能,最常见的表现就是 `UITableView` 在滑动时没有达到 **60 FPS**,用户能感受到明显的卡顿。 + +## 屏幕的渲染 + +相信点开这篇文章的大多数开发者都知道 FPS 是什么,那么如何才能优化我们的 App 使其达到 60 FPS 呢?在具体了解方法之前,我们先退一步,提出另一个问题,屏幕是如何渲染的? + +> 对于第一个问题,可能需要几篇文章来回答,希望整个系列的文章能给你一个满意的答案。3 + +### CRT 和 LCD + +屏幕的渲染可能要从 [CRT(Cathode ray tube) 显示器](https://en.wikipedia.org/wiki/Cathode_ray_tube)和 [LCD(Liquid-crystal display) 显示器](https://en.wikipedia.org/wiki/Liquid-crystal_display)讲起。 + +![CRT](images/CRT.png) + +CRT 显示器是比较古老的技术,它使用阴极电子枪发射电子,在阴极高压的作用下,电子由电子枪射向荧光屏,使荧光粉发光,将图像显示在屏幕上,这也就是用磁铁靠近一些老式电视机的屏幕会让它们变色的原因。 + +而 FPS 就是 CRT 显示器的刷新频率,电子枪每秒会对显示器上内容进行 60 - 100 次的刷新,哪怕在我们看来没有任何改变。 + +![lcd](images/lcd.png) + + +但是 LCD 的原理与 CRT 非常不同,LCD 的成像原理跟光学有关: + ++ 在不加电压下,光线会沿着液晶分子的间隙前进旋转 90°,所以光可以通过; ++ 在加入电压之后,光沿着液晶分子的间隙直线前进,被滤光板挡住。 + +如果你可以翻墙,相信下面的视频会更好得帮助你理解 LCD 的工作原理: + + + +LCD 的成像原理虽然与 CRT 截然不同,每一个像素的颜色可以**在需要改变时**才去改变电压,也就是不需要刷新频率,但是由于一些历史原因,LCD 仍然需要按照一定的刷新频率向 GPU 获取新的图像用于显示。 + +### 屏幕撕裂 + +但是显示器只是用于将图像显示在屏幕上,谁又是图像的提供者呢?图像都是我们经常说的 GPU 提供的。 + +而这导致了另一个问题,由于 GPU 生成图像的频率与显示器刷新的频率是不相关的,那么在显示器刷新时,GPU 没有准备好需要显示的图像怎么办;或者 GPU 的渲染速度过快,显示器来不及刷新,GPU 就已经开始渲染下一帧图像又该如何处理? + +![screen-tearing](images/screen-tearing.jpg) + +如果解决不了这两个问题,就会出现上图中的*屏幕撕裂*(Screen Tearing)现象,屏幕中一部分显示的是上一帧的内容,另一部分显示的是下一帧的内容。 + +我们用两个例子来说明可能出现屏幕撕裂的两种情况: + ++ 如果显示器的刷新频率为 75 Hz,GPU 的渲染速度为 100 Hz,那么在两次屏幕刷新的间隔中,GPU 会渲染 4/3 个帧,后面的 1/3 帧会覆盖已经渲染好的帧栈,最终会导致屏幕在 1/3 或者 2/3 的位置出现屏幕撕裂效果; ++ 那么 GPU 的渲染速度小于显示器呢,比如说 50 Hz,那么在两次屏幕刷新的间隔中,GPU 只会渲染 2/3 帧,剩下的 1/3 会来自上一帧,与上面的结果完全相同,在同样的位置出现撕裂效果。 + +到这里,有人会说,如果显示器的刷新频率与 GPU 的渲染速度完全相同,应该就会解决屏幕撕裂的问题了吧?其实并不是。显示器从 GPU 拷贝帧的过程依然需要消耗一定的时间,如果屏幕在拷贝图像时刷新,仍然会导致屏幕撕裂问题。 + +![how-to-solve-tearing-proble](images/how-to-solve-tearing-problem.jpg) + +引入多个缓冲区可以有效地**缓解**屏幕撕裂,也就是同时使用一个*帧缓冲区*(frame buffer)和多个*后备缓冲区*(back buffer);在每次显示器请求内容时,都会从**帧缓冲区**中取出图像然后渲染。 + +虽然缓冲区可以减缓这些问题,但是却不能解决;如果后备缓冲区绘制完成,而帧缓冲区的图像没有被渲染,后备缓冲区中的图像就会覆盖帧缓冲区,仍然会导致屏幕撕裂。 + +解决这个问题需要另一个机制的帮助,也就是垂直同步(Vertical synchronization),简称 V-Sync 来解决。 + +### V-Sync + +V-Sync 的主要作用就是保证**只有在帧缓冲区中的图像被渲染之后,后备缓冲区中的内容才可以被拷贝到帧缓冲区中**,理想情况下的 V-Sync 会按这种方式工作: + +![normal-vsyn](images/normal-vsync.png) + +每次 V-Sync 发生时,CPU 以及 GPU 都已经完成了对图像的处理以及绘制,显示器可以直接拿到缓冲区中的帧。但是,如果 CPU 或者 GPU 的处理需要的时间较长,就会发生掉帧的问题: + +![lag-vsyn](images/lag-vsync.png) + + +在 V-Sync 信号发出时,CPU 和 GPU 并没有准备好需要渲染的帧,显示器就会继续使用当前帧,这就**加剧**了屏幕的显示问题,而每秒显示的帧数会少于 60。 + +由于会发生很多次掉帧,在开启了 V-Sync 后,40 ~ 50 FPS 的渲染频率意味着显示器输出的画面帧率会从 60 FPS 急剧下降到 30 FPS,原因在这里不会解释,读者可以自行思考。 + +其实到这里关于屏幕渲染的内容就已经差不多结束了,根据 V-Sync 的原理,优化应用性能、提高 App 的 FPS 就可以从两个方面来入手,优化 CPU 以及 GPU 的处理时间。 + +> 读者也可以从 [iOS 保持界面流畅的技巧](http://blog.ibireme.com/2015/11/12/smooth_user_interfaces_for_ios/)这篇文章中了解更多的相关内容。 + +## 性能调优的策略 + +CPU 和 GPU 在每次 V-Sync 时间点到达之前都在干什么?如果,我们知道了它们各自负责的工作,通过优化代码就可以提升性能。 + +![cpu-gpu](images/cpu-gpu.jpg) + +很多 CPU 的操作都会延迟 GPU 开始渲染的时间: + ++ 布局的计算 - 如果你的视图层级太过于复杂,或者视图需要重复多次进行布局,尤其是在使用 Auto Layout 进行自动布局时,对性能影响尤为严重; ++ 视图的惰性加载 - 在 iOS 中只有当视图控制器的视图显示到屏幕时才会加载; ++ 解压图片 - iOS 通常会在真正绘制时才会解码图片,对于一个较大的图片,无论是直接或间接使用 `UIImageView` 或者绘制到 Core Graphics 中,都需要对图片进行解压; ++ ... + +宽泛的说,大多数的 `CALayer` 的属性都是由 GPU 来绘制的,比如图片的圆角、变换、应用纹理;但是过多的几何结构、重绘、离屏绘制(Offscrren)以及过大的图片都会导致 GPU 的性能明显降低。 + +> 上面的内容出自 [CPU vs GPU · iOS 核心动画高级技巧](https://zsisme.gitbooks.io/ios-/content/chapter12/cpu-versus-gpu.html),你可以在上述文章中对 CPU 和 GPU 到底各自做了什么有一个更深的了解。 + +也就是说,如果我们解决了上述问题,就能加快应用的渲染速度,大大提升用户体验。 + +## AsyncDisplayKit + +文章的前半部分已经从屏幕的渲染原理讲到了性能调优的几个策略;而 [AsyncDisplayKit](http://asyncdisplaykit.org) 就根据上述的策略帮助我们对应用性能进行优化。 + +![asdk-logo](images/asdk-logo.png) + +AsyncDisplayKit(以下简称 ASDK)是由 Facebook 开源的一个 iOS 框架,能够帮助最复杂的 UI 界面保持流畅和快速响应。 + +ASDK 从开发到开源大约经历了一年多的时间,它其实并不是一个简单的框架~~它是一个复杂的框架~~,更像是对 UIKit 的重新实现,把整个 UIKit 以及 CALayer 层封装成一个一个 `Node`,**将昂贵的渲染、图片解码、布局以及其它 UI 操作移出主线程**,这样主线程就可以对用户的操作及时做出反应。 + +很多分析 ASDK 的文章都会有这么一张图介绍框架中的最基本概念: + +![asdk-hierarchy](images/asdk-hierarchy.png) + +在 ASDK 中最基本的单位就是 `ASDisplayNode`,每一个 node 都是对 `UIView` 以及 `CALayer` 的抽象。但是与 `UIView` 不同的是,`ASDisplayNode` 是线程安全的,它可以在后台线程中完成初始化以及配置工作。 + +如果按照 60 FPS 的刷新频率来计算,每一帧的渲染时间只有 16ms,在 16ms 的时间内要完成对 `UIView` 的创建、布局、绘制以及渲染,CPU 和 GPU 面临着巨大的压力。 + +![apple-a9](images/apple-a9.jpg) + +但是从 A5 处理器之后,多核的设备成为了主流,原有的将所有操作放入主线程的实践已经不能适应复杂的 UI 界面,所以 **ASDK 将耗时的 CPU 操作以及 GPU 渲染纹理(Texture)的过程全部放入后台进程,使主线程能够快速响应用户操作**。 + +ASDK 通过独特的渲染技巧、代替 AutoLayout 的布局系统、智能的预加载方式等模块来实现对 App 性能的优化。 + +## ASDK 的渲染过程 + +ASDK 中到底使用了哪些方法来对视图进行渲染呢?本文主要会从渲染的过程开始分析,了解 ASDK 底层如何提升界面的渲染性能。 + +在 ASDK 中的渲染围绕 `ASDisplayNode` 进行,其过程总共有四条主线: + ++ 初始化 `ASDisplayNode` 对应的 `UIView` 或者 `CALayer`; ++ 在当前视图进入视图层级时执行 `setNeedsDisplay`; ++ `display` 方法执行时,向后台线程派发绘制事务; ++ 注册成为 `RunLoop` 观察者,在每个 `RunLoop` 结束时回调。 + +### UIView 和 CALayer 的加载 + +当我们运行某一个使用 ASDK 的工程时,`-[ASDisplayNode _loadViewOrLayerIsLayerBacked:]` 总是 ASDK 中最先被调用的方法,而这个方法执行的原因往往就是 `ASDisplayNode` 对应的 `UIView` 和 `CALayer` 被引用了: + +```objectivec +- (CALayer *)layer { + if (!_layer) { + ASDisplayNodeAssertMainThread(); + + if (!_flags.layerBacked) return self.view.layer; + [self _loadViewOrLayerIsLayerBacked:YES]; + } + return _layer; +} + +- (UIView *)view { + if (_flags.layerBacked) return nil; + if (!_view) { + ASDisplayNodeAssertMainThread(); + [self _loadViewOrLayerIsLayerBacked:NO]; + } + return _view; +} +``` + +这里涉及到一个 ASDK 中比较重要的概念,如果 `ASDisplayNode` 是 `layerBacked` 的,它不会渲染对应的 `UIView` 以此来提升性能: + +```objectivec +- (void)_loadViewOrLayerIsLayerBacked:(BOOL)isLayerBacked { + if (isLayerBacked) { + _layer = [self _layerToLoad]; + _layer.delegate = (id)self; + } else { + _view = [self _viewToLoad]; + _view.asyncdisplaykit_node = self; + _layer = _view.layer; + } + _layer.asyncdisplaykit_node = self; + + self.asyncLayer.asyncDelegate = self; +} +``` + +因为 `UIView` 和 `CALayer` 虽然都可以用于展示内容,不过由于 `UIView` 可以用于处理用户的交互,所以如果不需要使用 `UIView` 的特性,直接使用 `CALayer` 进行渲染,能够节省大量的渲染时间。 + +> 如果你使用 Xcode 查看过视图的层级,那么你应该知道,`UIView` 在 Debug View Hierarchy 中是有层级的;而 `CALayer` 并没有,它门的显示都在一个平面上。 + +上述方法中的 `-[ASDisplayNode _layerToLoad]` 以及 `[ASDisplayNode _viewToLoad]` 都只会根据当前节点的 `layerClass` 或者 `viewClass` 初始化一个对象。 + +> [Layer Trees vs. Flat Drawing – Graphics Performance Across iOS Device Generations](http://floriankugler.com/2013/05/24/layer-trees-vs-flat-drawing-graphics-performance-across-ios-device-generations/) 这篇文章比较了 `UIView` 和 `CALayer` 的渲染时间。 + +![view-layer-cg-compare](images/view-layer-cg-compare.png) + +`-[ASDisplayNode asyncLayer]` 只是对当前 `node` 持有的 `layer` 进行封装,确保会返回一个 `_ASDisplayLayer` 的实例: + +```objectivec +- (_ASDisplayLayer *)asyncLayer { + ASDN::MutexLocker l(_propertyLock); + return [_layer isKindOfClass:[_ASDisplayLayer class]] ? (_ASDisplayLayer *)_layer : nil; +} +``` + +最重要的是 `-[ASDisplayNode _loadViewOrLayerIsLayerBacked:]` 方法会将当前节点设置为 `asyncLayer` 的代理,在后面会使用 `ASDisplayNode` 为 `CALayer` 渲染内容。 + +### 视图层级 + +在初始化工作完成之后,当 `ASDisplayNode` 第一次被加入到视图的层级时,`-[_ASDisplayView willMoveToWindow:]` 就会被调用。 + +#### _ASDisplayView 和 _ASDisplayLayer + +`_ASDisplayView` 和 `_ASDisplayLayer` 都是私有类,它们之间的对应关系其实和 `UIView` 与 `CALayer` 完全相同。 + +```objectivec ++ (Class)layerClass { + return [_ASDisplayLayer class]; +} +``` + +`_ASDisplayView` 覆写了很多跟视图层级改变有关的方法: + ++ `-[_ASDisplayView willMoveToWindow:]` ++ `-[_ASDisplayView didMoveToWindow]` ++ `-[_ASDisplayView willMoveToSuperview:]` ++ `-[_ASDisplayView didMoveToSuperview]` + +它们用于在视图的层级改变时,通知对应 `ASDisplayNode` 作出相应的反应,比如 `-[_ASDisplayView willMoveToWindow:]` 方法会在视图被加入层级时调用: + +```objectivec +- (void)willMoveToWindow:(UIWindow *)newWindow { + BOOL visible = (newWindow != nil); + if (visible && !_node.inHierarchy) { + [_node __enterHierarchy]; + } +} +``` + +#### setNeedsDisplay + +当前视图如果不在视图层级中,就会通过 `_node` 的实例方法 `-[ASDisplayNode __enterHierarchy]` 加入视图层级: + +```objectivec +- (void)__enterHierarchy { + if (!_flags.isInHierarchy && !_flags.visibilityNotificationsDisabled && ![self __selfOrParentHasVisibilityNotificationsDisabled]) { + _flags.isEnteringHierarchy = YES; + _flags.isInHierarchy = YES; + + if (_flags.shouldRasterizeDescendants) { + [self _recursiveWillEnterHierarchy]; + } else { + [self willEnterHierarchy]; + } + _flags.isEnteringHierarchy = NO; + + # 更新 layer 显示的内容 + } +} + +``` + +> `_flags` 是 `ASDisplayNodeFlags` 结构体,用于标记当前 `ASDisplayNode` 的一些 BOOL 值,比如,异步显示、栅格化子视图等等,你不需要知道都有什么,根据这些值的字面意思理解就已经足够了。 + +上述方法的前半部分只是对 `_flags` 的标记,如果需要将当前视图的子视图栅格化,也就是**将它的全部子视图与当前视图压缩成一个图层**,就会向这些视图递归地调用 `-[ASDisplayNode willEnterHierarchy]` 方法通知目前的状态: + +```objectivec +- (void)_recursiveWillEnterHierarchy { + _flags.isEnteringHierarchy = YES; + [self willEnterHierarchy]; + _flags.isEnteringHierarchy = NO; + + for (ASDisplayNode *subnode in self.subnodes) { + [subnode _recursiveWillEnterHierarchy]; + } +} +``` + +而 `-[ASDisplayNode willEnterHierarchy]` 会修改当前节点的 `interfaceState` 到 `ASInterfaceStateInHierarchy`,表示当前节点不包含在 `cell` 或者其它,但是在 `window` 中。 + +```objectivec +- (void)willEnterHierarchy { + if (![self supportsRangeManagedInterfaceState]) { + self.interfaceState = ASInterfaceStateInHierarchy; + } +} +``` + +当前结点需要被显示在屏幕上时,如果其内容 `contents` 为空,就会调用 `-[CALayer setNeedsDisplay]` 方法将 `CALayer` 标记为脏的,通知系统需要在下一个绘制循环中重绘视图: + +```objectivec +- (void)__enterHierarchy { + if (!_flags.isInHierarchy && !_flags.visibilityNotificationsDisabled && ![self __selfOrParentHasVisibilityNotificationsDisabled]) { + + # 标记节点的 flag + + if (self.contents == nil) { + CALayer *layer = self.layer; + [layer setNeedsDisplay]; + + if ([self _shouldHavePlaceholderLayer]) { + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + [self _setupPlaceholderLayerIfNeeded]; + _placeholderLayer.opacity = 1.0; + [CATransaction commit]; + [layer addSublayer:_placeholderLayer]; + } + } + } +} +``` + +在将 `CALayer` 标记为 dirty 之后,在绘制循环中就会执行 `-[CALayer display]` 方法,对它要展示的内容进行绘制;如果当前视图需要一些占位图,那么就会在这里的代码中,为当前 `node` 对应的 `layer` 添加合适颜色的占位层。 + +![placeholder-laye](images/placeholder-layer.png) + +### 派发异步绘制事务 + +在上一节中调用 `-[CALayer setNeedsDisplay]` 方法将当前节点标记为 dirty 之后,在下一个绘制循环时就会对所有需要重绘的 `CALayer` 执行 `-[CALayer display]`,这也是这一小节需要分析的方法的入口: + +```objectivec +- (void)display { + [self _hackResetNeedsDisplay]; + + ASDisplayNodeAssertMainThread(); + if (self.isDisplaySuspended) return; + + [self display:self.displaysAsynchronously]; +} +``` + +这一方法的调用栈比较复杂,在具体分析之前,笔者会先给出这个方法的调用栈,给读者一个关于该方法实现的简要印象: + +```objectivec +-[_ASDisplayLayer display] + -[_ASDisplayLayer display:] // 将绘制工作交给 ASDisplayNode 处理 + -[ASDisplayNode(AsyncDisplay) displayAsyncLayer:asynchronously:] + -[ASDisplayNode(AsyncDisplay) _displayBlockWithAsynchronous:isCancelledBlock:rasterizing:] + -[ASDisplayNode(AsyncDisplay) _recursivelyRasterizeSelfAndSublayersWithIsCancelledBlock:displayBlocks:] + -[CALayer(ASDisplayNodeAsyncTransactionContainer) asyncdisplaykit_parentTransactionContainer] + -[CALayer(ASDisplayNodeAsyncTransactionContainer) asyncdisplaykit_asyncTransaction] + -[_ASAsyncTransaction initWithCallbackQueue:completionBlock:] + -[_ASAsyncTransactionGroup addTransactionContainer:] + -[_ASAsyncTransaction addOperationWithBlock:priority:queue:completion:] + ASAsyncTransactionQueue::GroupImpl::schedule(NSInteger priority, dispatch_queue_t queue, dispatch_block_t block) + void dispatch_async(dispatch_queue_t queue, dispatch_block_t block); +``` + +`-[_ASDisplayLayer display]` 在调用栈中其实会创建一个 `displayBlock`,它其实是一个使用 Core Graphics 进行图像绘制的过程,整个绘制过程是通过事务的形式进行管理的;而 `displayBlock` 会被 GCD 分发到后台的并发进程来处理。 + +调用栈中的第二个方法 `-[_ASDisplayLayer display]` 会将异步绘制的工作交给自己的 `asyncDelegate`,也就是[第一部分](#uiview-和-calayer-的加载)中设置的 `ASDisplayNode`: + +```objectivec +- (void)display:(BOOL)asynchronously { + [_asyncDelegate displayAsyncLayer:self asynchronously:asynchronously]; +} +``` + +#### ASDisplayNode(AsyncDisplay) + +这里省略了一部分 `-[ASDisplayNode(AsyncDisplay) displayAsyncLayer:asynchronously:]` 方法的实现: + +```objectivec +- (void)displayAsyncLayer:(_ASDisplayLayer *)asyncLayer asynchronously:(BOOL)asynchronously { + ASDisplayNodeAssertMainThread(); + + ... + + asyncdisplaykit_async_transaction_operation_block_t displayBlock = [self _displayBlockWithAsynchronous:asynchronously isCancelledBlock:isCancelledBlock rasterizing:NO]; + + if (!displayBlock) return; + + asyncdisplaykit_async_transaction_operation_completion_block_t completionBlock = ^(id value, BOOL canceled){ + ASDisplayNodeCAssertMainThread(); + if (!canceled && !isCancelledBlock()) { + UIImage *image = (UIImage *)value; + _layer.contentsScale = self.contentsScale; + _layer.contents = (id)image.CGImage; + } + }; + + if (asynchronously) { + CALayer *containerLayer = _layer.asyncdisplaykit_parentTransactionContainer ? : _layer; + _ASAsyncTransaction *transaction = containerLayer.asyncdisplaykit_asyncTransaction; + [transaction addOperationWithBlock:displayBlock priority:self.drawingPriority queue:[_ASDisplayLayer displayQueue] completion:completionBlock]; + } else { + UIImage *contents = (UIImage *)displayBlock(); + completionBlock(contents, NO); + } +} +``` + +省略后的代码脉络非常清晰,`-[ASDisplayNode(AsyncDisplay) _displayBlockWithAsynchronous:isCancelledBlock:rasterizing:]` 返回一个用于 `displayBlock`,然后构造一个 `completionBlock`,在绘制结束时执行,在主线程中设置当前 `layer` 的内容。 + +如果当前的渲染是异步的,就会将 `displayBlock` 包装成一个事务,添加到队列中执行,否则就会同步执行当前的 block,并执行 `completionBlock` 回调,通知 `layer` 更新显示的内容。 + +同步显示的部分到这里已经很清楚了,我们更关心的其实还是异步绘制的部分,因为这部分才是 ASDK 提升效率的关键;而这就要从获取 `displayBlock` 的方法开始了解了。 + +#### displayBlock 的构建 + +`displayBlock` 的创建一般分为三种不同的方式: + +1. 将当前视图的子视图压缩成一层绘制在当前页面上 +2. 使用 `- displayWithParameters:isCancelled:` 返回一个 `UIImage`,对图像节点 `ASImageNode` 进行绘制 +3. 使用 `- drawRect:withParameters:isCancelled:isRasterizing:` 在 CG 上下文中绘制文字节点 `ASTextNode` + +这三种方式都通过 ASDK 来优化视图的渲染速度,这些操作最后都会扔到后台的并发线程中进行处理。 + +> 下面三个部分的代码经过了删减,省略了包括取消绘制、通知代理、控制并发数量以及用于调试的代码。 + +##### 栅格化子视图 + +如果当前的视图需要栅格化子视图,就会进入启用下面的构造方式创建一个 block,它会递归地将子视图绘制在父视图上: + +```objectivec +- (asyncdisplaykit_async_transaction_operation_block_t)_displayBlockWithAsynchronous:(BOOL)asynchronous isCancelledBlock:(asdisplaynode_iscancelled_block_t)isCancelledBlock rasterizing:(BOOL)rasterizing { + asyncdisplaykit_async_transaction_operation_block_t displayBlock = nil; + ASDisplayNodeFlags flags = _flags; + + if (!rasterizing && self.shouldRasterizeDescendants) { + NSMutableArray *displayBlocks = [NSMutableArray array]; + [self _recursivelyRasterizeSelfAndSublayersWithIsCancelledBlock:isCancelledBlock displayBlocks:displayBlocks]; + + CGFloat contentsScaleForDisplay = self.contentsScaleForDisplay; + BOOL opaque = self.opaque && CGColorGetAlpha(self.backgroundColor.CGColor) == 1.0f; + + displayBlock = ^id{ + + UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, contentsScaleForDisplay); + + for (dispatch_block_t block in displayBlocks) { + block(); + } + + UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + + return image; + }; + } else if (flags.implementsInstanceImageDisplay || flags.implementsImageDisplay) { + #:绘制 UIImage + } else if (flags.implementsInstanceDrawRect || flags.implementsDrawRect) { + #:提供 context,使用 CG 绘图 + } + + return [displayBlock copy]; +} +``` + +在压缩视图层级的过程中就会调用 `-[ASDisplayNode(AsyncDisplay) _recursivelyRasterizeSelfAndSublayersWithIsCancelledBlock:displayBlocks:]` 方法,获取子视图的所有 `displayBlock`,在得到 `UIGraphicsBeginImageContextWithOptions` 需要的参数之后,创建一个新的 context,执行了所有的 `displayBlock` 将子视图的绘制到当前图层之后,使用 `UIGraphicsGetImageFromCurrentImageContext` 取出图层的内容并返回。 + +`-[ASDisplayNode(AsyncDisplay) _recursivelyRasterizeSelfAndSublayersWithIsCancelledBlock:displayBlocks:]` 的实现还是有些繁琐的,它主要的功能就是使用 Core Graphics 进行绘图,将背景颜色、仿射变换、位置大小以及圆角等参数绘制到当前的上下文中,而且这个过程是递归的,直到不存在或者不需要绘制子节点为止。 + +##### 绘制图片 + +`displayBlock` 的第二种绘制策略更多地适用于图片节点 `ASImageNode` 的绘制: + +```objectivec +- (asyncdisplaykit_async_transaction_operation_block_t)_displayBlockWithAsynchronous:(BOOL)asynchronous isCancelledBlock:(asdisplaynode_iscancelled_block_t)isCancelledBlock rasterizing:(BOOL)rasterizing { + asyncdisplaykit_async_transaction_operation_block_t displayBlock = nil; + ASDisplayNodeFlags flags = _flags; + + if (!rasterizing && self.shouldRasterizeDescendants) { + #:栅格化 + } else if (flags.implementsInstanceImageDisplay || flags.implementsImageDisplay) { + id drawParameters = [self drawParameters]; + + displayBlock = ^id{ + UIImage *result = nil; + if (flags.implementsInstanceImageDisplay) { + result = [self displayWithParameters:drawParameters isCancelled:isCancelledBlock]; + } else { + result = [[self class] displayWithParameters:drawParameters isCancelled:isCancelledBlock]; + } + return result; + }; + } else if (flags.implementsInstanceDrawRect || flags.implementsDrawRect) { + #:提供 context,使用 CG 绘图 + } + + return [displayBlock copy]; +} +``` + +通过 `- displayWithParameters:isCancelled:` 的执行返回一个图片,不过这里的绘制也离不开 Core Graphics 的一些 C 函数,你会在 `-[ASImageNode displayWithParameters:isCancelled:]` 中看到对于 CG 的运用,它会使用 `drawParameters` 来修改并绘制自己持有的 `image` 对象。 + +##### 使用 CG 绘图 + +文字的绘制一般都会在 `- drawRect:withParameters:isCancelled:isRasterizing:` 进行,这个方法只是提供了一个合适的用于绘制的上下文,该方法不止可以绘制文字,只是在这里绘制文字比较常见: + +```objectivec +- (asyncdisplaykit_async_transaction_operation_block_t)_displayBlockWithAsynchronous:(BOOL)asynchronous isCancelledBlock:(asdisplaynode_iscancelled_block_t)isCancelledBlock rasterizing:(BOOL)rasterizing { + asyncdisplaykit_async_transaction_operation_block_t displayBlock = nil; + ASDisplayNodeFlags flags = _flags; + + if (!rasterizing && self.shouldRasterizeDescendants) { + #:栅格化 + } else if (flags.implementsInstanceImageDisplay || flags.implementsImageDisplay) { + #:绘制 UIImage + } else if (flags.implementsInstanceDrawRect || flags.implementsDrawRect) { + if (!rasterizing) { + UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, contentsScaleForDisplay); + } + + if (flags.implementsInstanceDrawRect) { + [self drawRect:bounds withParameters:drawParameters isCancelled:isCancelledBlock isRasterizing:rasterizing]; + } else { + [[self class] drawRect:bounds withParameters:drawParameters isCancelled:isCancelledBlock isRasterizing:rasterizing]; + } + + UIImage *image = nil; + if (!rasterizing) { + image = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + } + + return image; + }; + } + + return [displayBlock copy]; +} +``` + +上述代码跟第一部分比较像,区别是这里不会栅格化子视图;代码根据情况会决定是否重新开一个新的上下文,然后通过 `- drawRect:withParameters:isCancelled:isRasterizing:` 方法实现绘制。 + +#### 管理绘制事务 + +ASDK 提供了一个私有的管理事务的机制,由三部分组成 `_ASAsyncTransactionGroup`、`_ASAsyncTransactionContainer` 以及 `_ASAsyncTransaction`,这三者各自都有不同的功能: + ++ `_ASAsyncTransactionGroup` 会在初始化时,向 Runloop 中注册一个回调,在每次 Runloop 结束时,执行回调来提交 `displayBlock` 执行的结果 ++ `_ASAsyncTransactionContainer` 为当前 `CALayer` 提供了用于保存事务的容器,并提供了获取新的 `_ASAsyncTransaction` 实例的便利方法 ++ `_ASAsyncTransaction` 将异步操作封装成了轻量级的事务对象,使用 C++ 代码对 GCD 进行了封装 + +从上面的小节中,我们已经获取到了用于绘制的 `displayBlock`,然后就需要将 block 添加到绘制事务中: + +```objectivec +- (void)displayAsyncLayer:(_ASDisplayLayer *)asyncLayer asynchronously:(BOOL)asynchronously { + ... + + if (asynchronously) { + CALayer *containerLayer = _layer.asyncdisplaykit_parentTransactionContainer ? : _layer; + _ASAsyncTransaction *transaction = containerLayer.asyncdisplaykit_asyncTransaction; + [transaction addOperationWithBlock:displayBlock priority:self.drawingPriority queue:[_ASDisplayLayer displayQueue] completion:completionBlock]; + } else { + ... + } +} +``` + +前两行代码是获取 `_ASAsyncTransaction` 实例的过程,这个实例会包含在一个 `layer` 的哈希表中,最后调用的实例方法 `-[_ASAsyncTransaction addOperationWithBlock:priority:queue:completion:]` 会把用于绘制的 `displayBlock` 添加到后台并行队列中: + +```objectivec ++ (dispatch_queue_t)displayQueue { + static dispatch_queue_t displayQueue = NULL; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + displayQueue = dispatch_queue_create("org.AsyncDisplayKit.ASDisplayLayer.displayQueue", DISPATCH_QUEUE_CONCURRENT); + dispatch_set_target_queue(displayQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)); + }); + + return displayQueue; +} +``` + +这个队列是一个并行队列,并且优先级是 `DISPATCH_QUEUE_PRIORITY_HIGH`,**确保 UI 的渲染会在其它异步操作执行之前进行**,而 `-[_ASAsyncTransaction addOperationWithBlock:priority:queue:completion:]` 中会初始化 `ASDisplayNodeAsyncTransactionOperation` 的实例,然后传入 `completionBlock`,在绘制结束时回调: + +```objectivec +- (void)addOperationWithBlock:(asyncdisplaykit_async_transaction_operation_block_t)block priority:(NSInteger)priority queue:(dispatch_queue_t)queue completion:(asyncdisplaykit_async_transaction_operation_completion_block_t)completion { + ASDisplayNodeAssertMainThread(); + + [self _ensureTransactionData]; + + ASDisplayNodeAsyncTransactionOperation *operation = [[ASDisplayNodeAsyncTransactionOperation alloc] initWithOperationCompletionBlock:completion]; + [_operations addObject:operation]; + _group->schedule(priority, queue, ^{ + @autoreleasepool { + operation.value = block(); + } + }); +} +``` + +`schedule` 方法是一个 C++ 方法,它会向 `ASAsyncTransactionQueue::Group` 中派发一个 block,这个 block 中会执行 `displayBlock`,然后将结果传给 `operation.value`: + +```objectivec +void ASAsyncTransactionQueue::GroupImpl::schedule(NSInteger priority, dispatch_queue_t queue, dispatch_block_t block) { + ASAsyncTransactionQueue &q = _queue; + ASDN::MutexLocker locker(q._mutex); + + DispatchEntry &entry = q._entries[queue]; + + Operation operation; + operation._block = block; + operation._group = this; + operation._priority = priority; + entry.pushOperation(operation); + + ++_pendingOperations; + + NSUInteger maxThreads = [NSProcessInfo processInfo].activeProcessorCount * 2; + + if ([[NSRunLoop mainRunLoop].currentMode isEqualToString:UITrackingRunLoopMode]) + --maxThreads; + + if (entry._threadCount < maxThreads) { + bool respectPriority = entry._threadCount > 0; + ++entry._threadCount; + + dispatch_async(queue, ^{ + while (!entry._operationQueue.empty()) { + Operation operation = entry.popNextOperation(respectPriority); + { + if (operation._block) { + operation._block(); + } + operation._group->leave(); + operation._block = nil; + } + } + --entry._threadCount; + + if (entry._threadCount == 0) { + q._entries.erase(queue); + } + }); + } +} +``` + +`ASAsyncTransactionQueue::GroupImpl` 其实现其实就是对 GCD 的封装,同时添加一些最大并发数、线程锁的功能。通过 `dispatch_async` 将 block 分发到 `queue` 中,立刻执行 block,将数据传回 `ASDisplayNodeAsyncTransactionOperation` 实例。 + +### 回调 + +在 `_ASAsyncTransactionGroup` 调用 `mainTransactionGroup` 类方法获取单例时,会通过 `+[_ASAsyncTransactionGroup registerTransactionGroupAsMainRunloopObserver]` 向 Runloop 中注册回调: + +```objectivec ++ (void)registerTransactionGroupAsMainRunloopObserver:(_ASAsyncTransactionGroup *)transactionGroup { + static CFRunLoopObserverRef observer; + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); + CFOptionFlags activities = (kCFRunLoopBeforeWaiting | kCFRunLoopExit); + CFRunLoopObserverContext context = {0, (__bridge void *)transactionGroup, &CFRetain, &CFRelease, NULL}; + + observer = CFRunLoopObserverCreate(NULL, activities, YES, INT_MAX, &_transactionGroupRunLoopObserverCallback, &context); + CFRunLoopAddObserver(runLoop, observer, kCFRunLoopCommonModes); + CFRelease(observer); +} +``` + +上述代码会在即将退出 Runloop 或者 Runloop 开始休眠时执行回调 `_transactionGroupRunLoopObserverCallback`,而这个回调方法就是这一条主线的入口: + +```objectivec +static void _transactionGroupRunLoopObserverCallback(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) { + ASDisplayNodeCAssertMainThread(); + _ASAsyncTransactionGroup *group = (__bridge _ASAsyncTransactionGroup *)info; + [group commit]; +} +``` + +上一节中只是会将绘制代码提交到后台的并发进程中,而这里才会将结果提交,也就是在每次 Runloop 循环结束时开始绘制内容,而 `-[_operationCompletionBlock commit]` 方法的调用栈能够帮助我们理解内容是如何提交的,又是如何传回 `node` 持有的 `layer` 的: + +```objectivec +-[_ASAsyncTransactionGroup commit] + -[_ASAsyncTransaction commit] + ASAsyncTransactionQueue::GroupImpl::notify(dispatch_queue_t, dispatch_block_t) + _notifyList.push_back(GroupNotify) +``` + +`-[_ASAsyncTransactionGroup commit]` 方法的调用完成了对绘制事务的提交,而在 `-[_ASAsyncTransaction commit]` 中会调用 `notify` 方法,在上一节中的 `displayBlock` 执行结束后调用这里传入的 block 执行 `-[_ASAsyncTransaction completeTransaction]` 方法: + +```objectivec +- (void)commit { + ASDisplayNodeAssertMainThread(); + __atomic_store_n(&_state, ASAsyncTransactionStateCommitted, __ATOMIC_SEQ_CST); + + _group->notify(_callbackQueue, ^{ + ASDisplayNodeAssertMainThread(); + [self completeTransaction]; + }); +} +``` + +我们按照时间顺序来分析在上面的 block 执行之前,方法是如何调用的,以及 block 是如何被执行的;这就不得不回到派发绘制事务的部分了,在 `ASAsyncTransactionQueue::GroupImpl::schedule` 方法中,使用了 `dispatch_async` 将派发 block: + +```objectivec +void ASAsyncTransactionQueue::GroupImpl::schedule(NSInteger priority, dispatch_queue_t queue, dispatch_block_t block) { + ... + if (entry._threadCount < maxThreads) { + ... + dispatch_async(queue, ^{ + ... + while (!entry._operationQueue.empty()) { + Operation operation = entry.popNextOperation(respectPriority); + { + ASDN::MutexUnlocker unlock(q._mutex); + if (operation._block) { + operation._block(); + } + operation._group->leave(); + operation._block = nil; + } + } + ... + }); + } +} +``` + +在 `displayBlock` 执行之后,会调用的 `group` 的 `leave` 方法: + +```objectivec +void ASAsyncTransactionQueue::GroupImpl::leave() { + if (_pendingOperations == 0) { + std::list notifyList; + _notifyList.swap(notifyList); + + for (GroupNotify & notify : notifyList) { + dispatch_async(notify._queue, notify._block); + } + } +} +``` + +这里终于执行了在 `- commit` 中加入的 block,也就是 `-[_ASAsyncTransaction completeTransaction]` 方法: + +```objectivec +- (void)completeTransaction { + if (__atomic_load_n(&_state, __ATOMIC_SEQ_CST) != ASAsyncTransactionStateComplete) { + BOOL isCanceled = (__atomic_load_n(&_state, __ATOMIC_SEQ_CST) == ASAsyncTransactionStateCanceled); + for (ASDisplayNodeAsyncTransactionOperation *operation in _operations) { + [operation callAndReleaseCompletionBlock:isCanceled]; + } + + __atomic_store_n(&_state, ASAsyncTransactionStateComplete, __ATOMIC_SEQ_CST); + } +} +``` + +最后的最后,`-[ASDisplayNodeAsyncTransactionOperation callAndReleaseCompletionBlock:]` 方法执行了回调将 `displayBlock` 执行的结果传回了 CALayer: + +```objectivec +- (void)callAndReleaseCompletionBlock:(BOOL)canceled; { + if (_operationCompletionBlock) { + _operationCompletionBlock(self.value, canceled); + self.operationCompletionBlock = nil; + } +} +``` + +也就是在 `-[ASDisplayNode(AsyncDisplay) displayAsyncLayer:asynchronously:]` 方法中构建的 `completionBlock`: + +```objectivec +asyncdisplaykit_async_transaction_operation_completion_block_t completionBlock = ^(id value, BOOL canceled){ + ASDisplayNodeCAssertMainThread(); + if (!canceled && !isCancelledBlock()) { + UIImage *image = (UIImage *)value; + BOOL stretchable = !UIEdgeInsetsEqualToEdgeInsets(image.capInsets, UIEdgeInsetsZero); + if (stretchable) { + ASDisplayNodeSetupLayerContentsWithResizableImage(_layer, image); + } else { + _layer.contentsScale = self.contentsScale; + _layer.contents = (id)image.CGImage; + } + [self didDisplayAsyncLayer:self.asyncLayer]; + } +}; +``` + +这一部分进行的大量的数据传递都是通过 block 进行的,从 Runloop 中对事务的提交,以及通过 `notify` 方法加入的 block,都是为了最后将绘制的结果传回 `CALayer` 对象,而到这里可以说整个 ASDK 对于视图内容的绘制过程就结束了。 + +## 总结 + +ASDK 对于绘制过程的优化有三部分:分别是栅格化子视图、绘制图像以及绘制文字。 + +它拦截了视图加入层级时发出的通知 `- willMoveToWindow:` 方法,然后手动调用 `- setNeedsDisplay`,强制所有的 `CALayer` 执行 `- display` 更新内容; + +然后将上面的操作全部抛入了后台的并发线程中,并在 Runloop 中注册回调,在每次 Runloop 结束时,对已经完成的事务进行 `- commit`,以图片的形式直接传回对应的 `layer.content` 中,完成对内容的更新。 + +从它的实现来看,确实从主线程移除了很多昂贵的 CPU 以及 GPU 操作,有效地加快了视图的绘制和渲染,保证了主线程的流畅执行。 + +## References + ++ [How VSync works, and why people loathe it](https://hardforum.com/threads/how-vsync-works-and-why-people-loathe-it.928593/) ++ [脑洞大开:为啥帧率达到 60 fps 就流畅?](http://www.jianshu.com/p/71cba1711de0) ++ [iOS 保持界面流畅的技巧](http://blog.ibireme.com/2015/11/12/smooth_user_interfaces_for_ios/) ++ [CADiplayLink Class Reference - Developer- Apple](https://en.wikipedia.org/wiki/Analog_television#Vertical_synchronization) ++ [CPU vs GPU · iOS 核心动画高级技巧](https://zsisme.gitbooks.io/ios-/content/chapter12/cpu-versus-gpu.html) ++ [理解 UIView 的绘制](http://vizlabxt.github.io/blog/2012/10/22/UIView-Rendering/) ++ [Introduce to AsyncDisplayKit](http://vizlabxt.github.io/blog/2015/01/09/Behind-AsyncDisplayKit/) ++ [AsyncDisplayKit Tutorial: Achieving 60 FPS scrolling](https://www.raywenderlich.com/86365/asyncdisplaykit-tutorial-achieving-60-fps-scrolling) ++ [Layer Trees vs. Flat Drawing – Graphics Performance Across iOS Device Generations](http://floriankugler.com/2013/05/24/layer-trees-vs-flat-drawing-graphics-performance-across-ios-device-generations/) ++ [深入理解 RunLoop](http://blog.ibireme.com/2015/05/18/runloop/) + +## 其它 + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · Github](https://github.com/Draveness) +> +> Source: http://draveness.me/asdk-rendering + + diff --git "a/contents/AsyncDisplayKit/\346\217\220\345\215\207 iOS \347\225\214\351\235\242\347\232\204\346\270\262\346\237\223\346\200\247\350\203\275 .md" "b/contents/AsyncDisplayKit/\346\217\220\345\215\207 iOS \347\225\214\351\235\242\347\232\204\346\270\262\346\237\223\346\200\247\350\203\275 .md" new file mode 100644 index 0000000..2ff39e3 --- /dev/null +++ "b/contents/AsyncDisplayKit/\346\217\220\345\215\207 iOS \347\225\214\351\235\242\347\232\204\346\270\262\346\237\223\346\200\247\350\203\275 .md" @@ -0,0 +1,808 @@ +# 使用 ASDK 性能调优 - 提升 iOS 界面的渲染性能 + +> 这一系列的文章会从几个方面对 [ASDK](http://asyncdisplaykit.org) 在性能调优方面策略的实现进行分析,帮助读者理解 ASDK 如何做到使复杂的 UI 界面达到 60 FPS 的刷新频率的;本篇文章会从视图的渲染层面讲解 ASDK 对于渲染过程的优化并对 ASDK 进行概述。 + +在客户端或者前端开发中,对于性能的优化,尤其是 UI,往往都不是最先考虑的问题。 + +因为在大多数场景下,使用更加复杂的高性能代码替代可用的代码经常会导致代码的可维护性下降,所以更需要我们开发者对优化的时间点以及原因有一个比较清楚的认识,避免过度优化带来的问题。 + +对 iOS 开发比较熟悉的开发者都知道,iOS 中的性能问题大多是阻塞主线程导致用户的交互反馈出现可以感知的延迟。 + +![scrollview-demo](images/scrollview-demo.png) + +详细说起来,大体有三种原因: + +1. UI 渲染需要时间较长,无法按时提交结果; +2. 一些需要**密集计算**的处理放在了主线程中执行,导致主线程被阻塞,无法渲染 UI 界面; +3. 网络请求由于网络状态的问题响应较慢,UI 层由于没有模型返回无法渲染。 + +上面的这些问题都会影响应用的性能,最常见的表现就是 `UITableView` 在滑动时没有达到 **60 FPS**,用户能感受到明显的卡顿。 + +## 屏幕的渲染 + +相信点开这篇文章的大多数开发者都知道 FPS 是什么,那么如果才能优化我们的 App 使其达到 60 FPS 呢?在具体了解方法之前,我们先退一步,提出另一个问题,屏幕是如何渲染的? + +> 对于第一个问题,可能需要几篇文章来回答,希望整个系列的文章能给你一个满意的答案。3 + +### CRT 和 LCD + +屏幕的渲染可能要从 [CRT(Cathode ray tube) 显示器](https://en.wikipedia.org/wiki/Cathode_ray_tube)和 [LCD(Liquid-crystal display) 显示器](https://en.wikipedia.org/wiki/Liquid-crystal_display)讲起。 + +![CRT](images/CRT.png) + +CRT 显示器是比较古老的技术,它使用阴极电子枪发射电子,在阴极高压的作用下,电子由电子枪射向荧光屏,使荧光粉发光,将图像显示在屏幕上,这也就是用磁铁靠近一些老式电视机的屏幕会让它们变色的原因。 + +而 FPS 就是 CRT 显示器的刷新频率,电子枪每秒会对显示器上内容进行 60 - 100 次的刷新,哪怕在我们看来没有任何改变。 + +![lcd](images/lcd.png) + + +但是 LCD 的原理与 CRT 非常不同,LCD 的成像原理跟光学有关: + ++ 在不加电压下,光线会沿着液晶分子的间隙前进旋转 90°,所以光可以通过; ++ 在加入电压之后,光沿着液晶分子的间隙直线前进,被滤光板挡住。 + +如果你可以翻墙,相信下面的视频会更好得帮助你理解 LCD 的工作原理: + + + +LCD 的成像原理虽然与 CRT 截然不同,每一个像素的颜色可以**在需要改变时**才去改变电压,也就是不需要刷新频率,但是由于一些历史原因,LCD 仍然需要按照一定的刷新频率向 GPU 获取新的图像用于显示。 + +### 屏幕撕裂 + +但是显示器只是用于将图像显示在屏幕上,谁又是图像的提供者呢?图像都是我们经常说的 GPU 提供的。 + +而这导致了另一个问题,由于 GPU 生成图像的频率与显示器刷新的频率是不相关的,那么在显示器刷新时,GPU 没有准备好需要显示的图像怎么办;或者 GPU 的渲染速度过快,显示器来不及刷新,GPU 就已经开始渲染下一帧图像又该如何处理? + +![screen-tearing](images/screen-tearing.jpg) + +如果解决不了这两个问题,就会出现上图中的*屏幕撕裂*(Screen Tearing)现象,屏幕中一部分显示的是上一帧的内容,另一部分显示的是下一帧的内容。 + +我们用两个例子来说明可能出现屏幕撕裂的两种情况: + ++ 如果显示器的刷新频率为 75 Hz,GPU 的渲染速度为 100 Hz,那么在两次屏幕刷新的间隔中,GPU 会渲染 4/3 个帧,后面的 1/3 帧会覆盖已经渲染好的帧栈,最终会导致屏幕在 1/3 或者 2/3 的位置出现屏幕撕裂效果; ++ 那么 GPU 的渲染速度小于显示器呢,比如说 50 Hz,那么在两次屏幕刷新的间隔中,GPU 只会渲染 2/3 帧,剩下的 1/3 会来自上一帧,与上面的结果完全相同,在同样的位置出现撕裂效果。 + +到这里,有人会说,如果显示器的刷新频率与 GPU 的渲染速度完全相同,应该就会解决屏幕撕裂的问题了吧?其实并不是。显示器从 GPU 拷贝帧的过程依然需要消耗一定的时间,如果屏幕在拷贝图像时刷新,仍然会导致屏幕撕裂问题。 + +![how-to-solve-tearing-proble](images/how-to-solve-tearing-problem.jpg) + +引入多个缓冲区可以有效地**缓解**屏幕撕裂,也就是同时使用一个*帧缓冲区*(frame buffer)和多个*后备缓冲区*(back buffer);在每次显示器请求内容时,都会从**帧缓冲区**中取出图像然后渲染。 + +虽然缓冲区可以减缓这些问题,但是却不能解决;如果后备缓冲区绘制完成,而帧缓冲区的图像没有被渲染,后备缓冲区中的图像就会覆盖帧缓冲区,仍然会导致屏幕撕裂。 + +解决这个问题需要另一个机制的帮助,也就是垂直同步(Vertical synchronization),简称 V-Sync 来解决。 + +### V-Sync + +V-Sync 的主要作用就是保证**只有在帧缓冲区中的图像被渲染之后,后备缓冲区中的内容才可以被拷贝到帧缓冲区中**,理想情况下的 V-Sync 会按这种方式工作: + +![normal-vsyn](images/normal-vsync.png) + +每次 V-Sync 发生时,CPU 以及 GPU 都已经完成了对图像的处理以及绘制,显示器可以直接拿到缓冲区中的帧。但是,如果 CPU 或者 GPU 的处理需要的时间较长,就会发生掉帧的问题: + +![lag-vsyn](images/lag-vsync.png) + + +在 V-Sync 信号发出时,CPU 和 GPU 并没有准备好需要渲染的帧,显示器就会继续使用当前帧,这就**加剧**了屏幕的显示问题,而每秒显示的帧数会少于 60。 + +由于会发生很多次掉帧,在开启了 V-Sync 后,40 ~ 50 FPS 的渲染频率意味着显示器输出的画面帧率会从 60 FPS 急剧下降到 30 FPS,原因在这里不会解释,读者可以自行思考。 + +其实到这里关于屏幕渲染的内容就已经差不多结束了,根据 V-Sync 的原理,优化应用性能、提高 App 的 FPS 就可以从两个方面来入手,优化 CPU 以及 GPU 的处理时间。 + +> 读者也可以从 [iOS 保持界面流畅的技巧](http://blog.ibireme.com/2015/11/12/smooth_user_interfaces_for_ios/)这篇文章中了解更多的相关内容。 + +## 性能调优的策略 + +CPU 和 GPU 在每次 V-Sync 时间点到达之前都在干什么?如果,我们知道了它们各自负责的工作,通过优化代码就可以提升性能。 + +![cpu-gpu](images/cpu-gpu.jpg) + +很多 CPU 的操作都会延迟 GPU 开始渲染的时间: + ++ 布局的计算 - 如果你的视图层级太过于复杂,或者视图需要重复多次进行布局,尤其是在使用 Auto Layout 进行自动布局时,对性能影响尤为严重; ++ 视图的惰性加载 - 在 iOS 中只有当视图控制器的视图显示到屏幕时才会加载; ++ 解压图片 - iOS 通常会在真正绘制时才会解码图片,对于一个较大的图片,无论是直接或间接使用 `UIImageView` 或者绘制到 Core Graphics 中,都需要对图片进行解压; ++ ... + +宽泛的说,大多数的 `CALayer` 的属性都是由 GPU 来绘制的,比如图片的圆角、变换、应用纹理;但是过多的几何结构、重绘、离屏绘制(Offscrren)以及过大的图片都会导致 GPU 的性能明显降低。 + +> 上面的内容出自 [CPU vs GPU · iOS 核心动画高级技巧](https://zsisme.gitbooks.io/ios-/content/chapter12/cpu-versus-gpu.html),你可以在上述文章中对 CPU 和 GPU 到底各自做了什么有一个更深的了解。 + +也就是说,如果我们解决了上述问题,就能加快应用的渲染速度,大大提升用户体验。 + +## AsyncDisplayKit + +文章的前半部分已经从屏幕的渲染原理讲到了性能调优的几个策略;而 [AsyncDisplayKit](http://asyncdisplaykit.org) 就根据上述的策略帮助我们对应用性能进行优化。 + +![asdk-logo](images/asdk-logo.png) + +AsyncDisplayKit(以下简称 ASDK)是由 Facebook 开源的一个 iOS 框架,能够帮助最复杂的 UI 界面保持流畅和快速响应。 + +ASDK 从开发到开源大约经历了一年多的时间,它其实并不是一个简单的框架~~它是一个复杂的框架~~,更像是对 UIKit 的重新实现,把整个 UIKit 以及 CALayer 层封装成一个一个 `Node`,**将昂贵的渲染、图片解码、布局以及其它 UI 操作移出主线程**,这样主线程就可以对用户的操作及时做出反应。 + +很多分析 ASDK 的文章都会有这么一张图介绍框架中的最基本概念: + +![asdk-hierarchy](images/asdk-hierarchy.png) + +在 ASDK 中最基本的单位就是 `ASDisplayNode`,每一个 node 都是对 `UIView` 以及 `CALayer` 的抽象。但是与 `UIView` 不同的是,`ASDisplayNode` 是线程安全的,它可以在后台线程中完成初始化以及配置工作。 + +如果按照 60 FPS 的刷新频率来计算,每一帧的渲染时间只有 16ms,在 16ms 的时间内要完成对 `UIView` 的创建、布局、绘制以及渲染,CPU 和 GPU 面临着巨大的压力。 + +![apple-a9](images/apple-a9.jpg) + +但是从 A5 处理器之后,多核的设备成为了主流,原有的将所有操作放入主线程的实践已经不能适应复杂的 UI 界面,所以 **ASDK 将耗时的 CPU 操作以及 GPU 渲染纹理(Texture)的过程全部放入后台进程,使主线程能够快速响应用户操作**。 + +ASDK 通过独特的渲染技巧、代替 AutoLayout 的布局系统、智能的预加载方式等模块来实现对 App 性能的优化。 + +## ASDK 的渲染过程 + +ASDK 中到底使用了哪些方法来对视图进行渲染呢?本文主要会从渲染的过程开始分析,了解 ASDK 底层如何提升界面的渲染性能。 + +在 ASDK 中的渲染围绕 `ASDisplayNode` 进行,其过程总共有四条主线: + ++ 初始化 `ASDisplayNode` 对应的 `UIView` 或者 `CALayer`; ++ 在当前视图进入视图层级时执行 `setNeedsDisplay`; ++ `display` 方法执行时,向后台线程派发绘制事务; ++ 注册成为 `RunLoop` 观察者,在每个 `RunLoop` 结束时回调。 + +### UIView 和 CALayer 的加载 + +当我们运行某一个使用 ASDK 的工程时,`-[ASDisplayNode _loadViewOrLayerIsLayerBacked:]` 总是 ASDK 中最先被调用的方法,而这个方法执行的原因往往就是 `ASDisplayNode` 对应的 `UIView` 和 `CALayer` 被引用了: + +```objectivec +- (CALayer *)layer { + if (!_layer) { + ASDisplayNodeAssertMainThread(); + + if (!_flags.layerBacked) return self.view.layer; + [self _loadViewOrLayerIsLayerBacked:YES]; + } + return _layer; +} + +- (UIView *)view { + if (_flags.layerBacked) return nil; + if (!_view) { + ASDisplayNodeAssertMainThread(); + [self _loadViewOrLayerIsLayerBacked:NO]; + } + return _view; +} +``` + +这里涉及到一个 ASDK 中比较重要的概念,如果 `ASDisplayNode` 是 `layerBacked` 的,它不会渲染对应的 `UIView` 以此来提升性能: + +```objectivec +- (void)_loadViewOrLayerIsLayerBacked:(BOOL)isLayerBacked { + if (isLayerBacked) { + _layer = [self _layerToLoad]; + _layer.delegate = (id)self; + } else { + _view = [self _viewToLoad]; + _view.asyncdisplaykit_node = self; + _layer = _view.layer; + } + _layer.asyncdisplaykit_node = self; + + self.asyncLayer.asyncDelegate = self; +} +``` + +因为 `UIView` 和 `CALayer` 虽然都可以用于展示内容,不过由于 `UIView` 可以用于处理用户的交互,所以如果不需要使用 `UIView` 的特性,直接使用 `CALayer` 进行渲染,能够节省大量的渲染时间。 + +> 如果你使用 Xcode 查看过视图的层级,那么你应该知道,`UIView` 在 Debug View Hierarchy 中是有层级的;而 `CALayer` 并没有,它门的显示都在一个平面上。 + +上述方法中的 `-[ASDisplayNode _layerToLoad]` 以及 `[ASDisplayNode _viewToLoad]` 都只会根据当前节点的 `layerClass` 或者 `viewClass` 初始化一个对象。 + +> [Layer Trees vs. Flat Drawing – Graphics Performance Across iOS Device Generations](http://floriankugler.com/2013/05/24/layer-trees-vs-flat-drawing-graphics-performance-across-ios-device-generations/) 这篇文章比较了 `UIView` 和 `CALayer` 的渲染时间。 + +![view-layer-cg-compare](images/view-layer-cg-compare.png) + +`-[ASDisplayNode asyncLayer]` 只是对当前 `node` 持有的 `layer` 进行封装,确保会返回一个 `_ASDisplayLayer` 的实例: + +```objectivec +- (_ASDisplayLayer *)asyncLayer { + ASDN::MutexLocker l(_propertyLock); + return [_layer isKindOfClass:[_ASDisplayLayer class]] ? (_ASDisplayLayer *)_layer : nil; +} +``` + +最重要的是 `-[ASDisplayNode _loadViewOrLayerIsLayerBacked:]` 方法会将当前节点设置为 `asyncLayer` 的代理,在后面会使用 `ASDisplayNode` 为 `CALayer` 渲染内容。 + +### 视图层级 + +在初始化工作完成之后,当 `ASDisplayNode` 第一次被加入到视图的层级时,`-[_ASDisplayView willMoveToWindow:]` 就会被调用。 + +#### _ASDisplayView 和 _ASDisplayLayer + +`_ASDisplayView` 和 `_ASDisplayLayer` 都是私有类,它们之间的对应关系其实和 `UIView` 与 `CALayer` 完全相同。 + +```objectivec ++ (Class)layerClass { + return [_ASDisplayLayer class]; +} +``` + +`_ASDisplayView` 覆写了很多跟视图层级改变有关的方法: + ++ `-[_ASDisplayView willMoveToWindow:]` ++ `-[_ASDisplayView didMoveToWindow]` ++ `-[_ASDisplayView willMoveToSuperview:]` ++ `-[_ASDisplayView didMoveToSuperview]` + +它们用于在视图的层级改变时,通知对应 `ASDisplayNode` 作出相应的反应,比如 `-[_ASDisplayView willMoveToWindow:]` 方法会在视图被加入层级时调用: + +```objectivec +- (void)willMoveToWindow:(UIWindow *)newWindow { + BOOL visible = (newWindow != nil); + if (visible && !_node.inHierarchy) { + [_node __enterHierarchy]; + } +} +``` + +#### setNeedsDisplay + +当前视图如果不在视图层级中,就会通过 `_node` 的实例方法 `-[ASDisplayNode __enterHierarchy]` 加入视图层级: + +```objectivec +- (void)__enterHierarchy { + if (!_flags.isInHierarchy && !_flags.visibilityNotificationsDisabled && ![self __selfOrParentHasVisibilityNotificationsDisabled]) { + _flags.isEnteringHierarchy = YES; + _flags.isInHierarchy = YES; + + if (_flags.shouldRasterizeDescendants) { + [self _recursiveWillEnterHierarchy]; + } else { + [self willEnterHierarchy]; + } + _flags.isEnteringHierarchy = NO; + + # 更新 layer 显示的内容 + } +} + +``` + +> `_flags` 是 `ASDisplayNodeFlags` 结构体,用于标记当前 `ASDisplayNode` 的一些 BOOL 值,比如,异步显示、栅格化子视图等等,你不需要知道都有什么,根据这些值的字面意思理解就已经足够了。 + +上述方法的前半部分只是对 `_flags` 的标记,如果需要将当前视图的子视图栅格化,也就是**将它的全部子视图与当前视图压缩成一个图层**,就会向这些视图递归地调用 `-[ASDisplayNode willEnterHierarchy]` 方法通知目前的状态: + +```objectivec +- (void)_recursiveWillEnterHierarchy { + _flags.isEnteringHierarchy = YES; + [self willEnterHierarchy]; + _flags.isEnteringHierarchy = NO; + + for (ASDisplayNode *subnode in self.subnodes) { + [subnode _recursiveWillEnterHierarchy]; + } +} +``` + +而 `-[ASDisplayNode willEnterHierarchy]` 会修改当前节点的 `interfaceState` 到 `ASInterfaceStateInHierarchy`,表示当前节点不包含在 `cell` 或者其它,但是在 `window` 中。 + +```objectivec +- (void)willEnterHierarchy { + if (![self supportsRangeManagedInterfaceState]) { + self.interfaceState = ASInterfaceStateInHierarchy; + } +} +``` + +当前结点需要被显示在屏幕上时,如果其内容 `contents` 为空,就会调用 `-[CALayer setNeedsDisplay]` 方法将 `CALayer` 标记为脏的,通知系统需要在下一个绘制循环中重绘视图: + +```objectivec +- (void)__enterHierarchy { + if (!_flags.isInHierarchy && !_flags.visibilityNotificationsDisabled && ![self __selfOrParentHasVisibilityNotificationsDisabled]) { + + # 标记节点的 flag + + if (self.contents == nil) { + CALayer *layer = self.layer; + [layer setNeedsDisplay]; + + if ([self _shouldHavePlaceholderLayer]) { + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + [self _setupPlaceholderLayerIfNeeded]; + _placeholderLayer.opacity = 1.0; + [CATransaction commit]; + [layer addSublayer:_placeholderLayer]; + } + } + } +} +``` + +在将 `CALayer` 标记为 dirty 之后,在绘制循环中就会执行 `-[CALayer display]` 方法,对它要展示的内容进行绘制;如果当前视图需要一些占位图,那么就会在这里的代码中,为当前 `node` 对应的 `layer` 添加合适颜色的占位层。 + +![placeholder-laye](images/placeholder-layer.png) + +### 派发异步绘制事务 + +在上一节中调用 `-[CALayer setNeedsDisplay]` 方法将当前节点标记为 dirty 之后,在下一个绘制循环时就会对所有需要重绘的 `CALayer` 执行 `-[CALayer display]`,这也是这一小节需要分析的方法的入口: + +```objectivec +- (void)display { + [self _hackResetNeedsDisplay]; + + ASDisplayNodeAssertMainThread(); + if (self.isDisplaySuspended) return; + + [self display:self.displaysAsynchronously]; +} +``` + +这一方法的调用栈比较复杂,在具体分析之前,笔者会先给出这个方法的调用栈,给读者一个关于该方法实现的简要印象: + +```objectivec +-[_ASDisplayLayer display] + -[_ASDisplayLayer display:] // 将绘制工作交给 ASDisplayNode 处理 + -[ASDisplayNode(AsyncDisplay) displayAsyncLayer:asynchronously:] + -[ASDisplayNode(AsyncDisplay) _displayBlockWithAsynchronous:isCancelledBlock:rasterizing:] + -[ASDisplayNode(AsyncDisplay) _recursivelyRasterizeSelfAndSublayersWithIsCancelledBlock:displayBlocks:] + -[CALayer(ASDisplayNodeAsyncTransactionContainer) asyncdisplaykit_parentTransactionContainer] + -[CALayer(ASDisplayNodeAsyncTransactionContainer) asyncdisplaykit_asyncTransaction] + -[_ASAsyncTransaction initWithCallbackQueue:completionBlock:] + -[_ASAsyncTransactionGroup addTransactionContainer:] + -[_ASAsyncTransaction addOperationWithBlock:priority:queue:completion:] + ASAsyncTransactionQueue::GroupImpl::schedule(NSInteger priority, dispatch_queue_t queue, dispatch_block_t block) + void dispatch_async(dispatch_queue_t queue, dispatch_block_t block); +``` + +`-[_ASDisplayLayer display]` 在调用栈中其实会创建一个 `displayBlock`,它其实是一个使用 Core Graphics 进行图像绘制的过程,整个绘制过程是通过事务的形式进行管理的;而 `displayBlock` 会被 GCD 分发到后台的并发进程来处理。 + +调用栈中的第二个方法 `-[_ASDisplayLayer display]` 会将异步绘制的工作交给自己的 `asyncDelegate`,也就是[第一部分](#uiview-和-calayer-的加载)中设置的 `ASDisplayNode`: + +```objectivec +- (void)display:(BOOL)asynchronously { + [_asyncDelegate displayAsyncLayer:self asynchronously:asynchronously]; +} +``` + +#### ASDisplayNode(AsyncDisplay) + +这里省略了一部分 `-[ASDisplayNode(AsyncDisplay) displayAsyncLayer:asynchronously:]` 方法的实现: + +```objectivec +- (void)displayAsyncLayer:(_ASDisplayLayer *)asyncLayer asynchronously:(BOOL)asynchronously { + ASDisplayNodeAssertMainThread(); + + ... + + asyncdisplaykit_async_transaction_operation_block_t displayBlock = [self _displayBlockWithAsynchronous:asynchronously isCancelledBlock:isCancelledBlock rasterizing:NO]; + + if (!displayBlock) return; + + asyncdisplaykit_async_transaction_operation_completion_block_t completionBlock = ^(id value, BOOL canceled){ + ASDisplayNodeCAssertMainThread(); + if (!canceled && !isCancelledBlock()) { + UIImage *image = (UIImage *)value; + _layer.contentsScale = self.contentsScale; + _layer.contents = (id)image.CGImage; + } + }; + + if (asynchronously) { + CALayer *containerLayer = _layer.asyncdisplaykit_parentTransactionContainer ? : _layer; + _ASAsyncTransaction *transaction = containerLayer.asyncdisplaykit_asyncTransaction; + [transaction addOperationWithBlock:displayBlock priority:self.drawingPriority queue:[_ASDisplayLayer displayQueue] completion:completionBlock]; + } else { + UIImage *contents = (UIImage *)displayBlock(); + completionBlock(contents, NO); + } +} +``` + +省略后的代码脉络非常清晰,`-[ASDisplayNode(AsyncDisplay) _displayBlockWithAsynchronous:isCancelledBlock:rasterizing:]` 返回一个用于 `displayBlock`,然后构造一个 `completionBlock`,在绘制结束时执行,在主线程中设置当前 `layer` 的内容。 + +如果当前的渲染是异步的,就会将 `displayBlock` 包装成一个事务,添加到队列中执行,否则就会同步执行当前的 block,并执行 `completionBlock` 回调,通知 `layer` 更新显示的内容。 + +同步显示的部分到这里已经很清楚了,我们更关心的其实还是异步绘制的部分,因为这部分才是 ASDK 提升效率的关键;而这就要从获取 `displayBlock` 的方法开始了解了。 + +#### displayBlock 的构建 + +`displayBlock` 的创建一般分为三种不同的方式: + +1. 将当前视图的子视图压缩成一层绘制在当前页面上 +2. 使用 `- displayWithParameters:isCancelled:` 返回一个 `UIImage`,对图像节点 `ASImageNode` 进行绘制 +3. 使用 `- drawRect:withParameters:isCancelled:isRasterizing:` 在 CG 上下文中绘制文字节点 `ASTextNode` + +这三种方式都通过 ASDK 来优化视图的渲染速度,这些操作最后都会扔到后台的并发线程中进行处理。 + +> 下面三个部分的代码经过了删减,省略了包括取消绘制、通知代理、控制并发数量以及用于调试的代码。 + +##### 栅格化子视图 + +如果当前的视图需要栅格化子视图,就会进入启用下面的构造方式创建一个 block,它会递归地将子视图绘制在父视图上: + +```objectivec +- (asyncdisplaykit_async_transaction_operation_block_t)_displayBlockWithAsynchronous:(BOOL)asynchronous isCancelledBlock:(asdisplaynode_iscancelled_block_t)isCancelledBlock rasterizing:(BOOL)rasterizing { + asyncdisplaykit_async_transaction_operation_block_t displayBlock = nil; + ASDisplayNodeFlags flags = _flags; + + if (!rasterizing && self.shouldRasterizeDescendants) { + NSMutableArray *displayBlocks = [NSMutableArray array]; + [self _recursivelyRasterizeSelfAndSublayersWithIsCancelledBlock:isCancelledBlock displayBlocks:displayBlocks]; + + CGFloat contentsScaleForDisplay = self.contentsScaleForDisplay; + BOOL opaque = self.opaque && CGColorGetAlpha(self.backgroundColor.CGColor) == 1.0f; + + displayBlock = ^id{ + + UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, contentsScaleForDisplay); + + for (dispatch_block_t block in displayBlocks) { + block(); + } + + UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + + return image; + }; + } else if (flags.implementsInstanceImageDisplay || flags.implementsImageDisplay) { + #:绘制 UIImage + } else if (flags.implementsInstanceDrawRect || flags.implementsDrawRect) { + #:提供 context,使用 CG 绘图 + } + + return [displayBlock copy]; +} +``` + +在压缩视图层级的过程中就会调用 `-[ASDisplayNode(AsyncDisplay) _recursivelyRasterizeSelfAndSublayersWithIsCancelledBlock:displayBlocks:]` 方法,获取子视图的所有 `displayBlock`,在得到 `UIGraphicsBeginImageContextWithOptions` 需要的参数之后,创建一个新的 context,执行了所有的 `displayBlock` 将子视图的绘制到当前图层之后,使用 `UIGraphicsGetImageFromCurrentImageContext` 取出图层的内容并返回。 + +`-[ASDisplayNode(AsyncDisplay) _recursivelyRasterizeSelfAndSublayersWithIsCancelledBlock:displayBlocks:]` 的实现还是有些繁琐的,它主要的功能就是使用 Core Graphics 进行绘图,将背景颜色、仿射变换、位置大小以及圆角等参数绘制到当前的上下文中,而且这个过程是递归的,直到不存在或者不需要绘制子节点为止。 + +##### 绘制图片 + +`displayBlock` 的第二种绘制策略更多地适用于图片节点 `ASImageNode` 的绘制: + +```objectivec +- (asyncdisplaykit_async_transaction_operation_block_t)_displayBlockWithAsynchronous:(BOOL)asynchronous isCancelledBlock:(asdisplaynode_iscancelled_block_t)isCancelledBlock rasterizing:(BOOL)rasterizing { + asyncdisplaykit_async_transaction_operation_block_t displayBlock = nil; + ASDisplayNodeFlags flags = _flags; + + if (!rasterizing && self.shouldRasterizeDescendants) { + #:栅格化 + } else if (flags.implementsInstanceImageDisplay || flags.implementsImageDisplay) { + id drawParameters = [self drawParameters]; + + displayBlock = ^id{ + UIImage *result = nil; + if (flags.implementsInstanceImageDisplay) { + result = [self displayWithParameters:drawParameters isCancelled:isCancelledBlock]; + } else { + result = [[self class] displayWithParameters:drawParameters isCancelled:isCancelledBlock]; + } + return result; + }; + } else if (flags.implementsInstanceDrawRect || flags.implementsDrawRect) { + #:提供 context,使用 CG 绘图 + } + + return [displayBlock copy]; +} +``` + +通过 `- displayWithParameters:isCancelled:` 的执行返回一个图片,不过这里的绘制也离不开 Core Graphics 的一些 C 函数,你会在 `-[ASImageNode displayWithParameters:isCancelled:]` 中看到对于 CG 的运用,它会使用 `drawParameters` 来修改并绘制自己持有的 `image` 对象。 + +##### 使用 CG 绘图 + +文字的绘制一般都会在 `- drawRect:withParameters:isCancelled:isRasterizing:` 进行,这个方法只是提供了一个合适的用于绘制的上下文,该方法不止可以绘制文字,只是在这里绘制文字比较常见: + +```objectivec +- (asyncdisplaykit_async_transaction_operation_block_t)_displayBlockWithAsynchronous:(BOOL)asynchronous isCancelledBlock:(asdisplaynode_iscancelled_block_t)isCancelledBlock rasterizing:(BOOL)rasterizing { + asyncdisplaykit_async_transaction_operation_block_t displayBlock = nil; + ASDisplayNodeFlags flags = _flags; + + if (!rasterizing && self.shouldRasterizeDescendants) { + #:栅格化 + } else if (flags.implementsInstanceImageDisplay || flags.implementsImageDisplay) { + #:绘制 UIImage + } else if (flags.implementsInstanceDrawRect || flags.implementsDrawRect) { + if (!rasterizing) { + UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, contentsScaleForDisplay); + } + + if (flags.implementsInstanceDrawRect) { + [self drawRect:bounds withParameters:drawParameters isCancelled:isCancelledBlock isRasterizing:rasterizing]; + } else { + [[self class] drawRect:bounds withParameters:drawParameters isCancelled:isCancelledBlock isRasterizing:rasterizing]; + } + + UIImage *image = nil; + if (!rasterizing) { + image = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + } + + return image; + }; + } + + return [displayBlock copy]; +} +``` + +上述代码跟第一部分比较像,区别是这里不会栅格化子视图;代码根据情况会决定是否重新开一个新的上下文,然后通过 `- drawRect:withParameters:isCancelled:isRasterizing:` 方法实现绘制。 + +#### 管理绘制事务 + +ASDK 提供了一个私有的管理事务的机制,由三部分组成 `_ASAsyncTransactionGroup`、`_ASAsyncTransactionContainer` 以及 `_ASAsyncTransaction`,这三者各自都有不同的功能: + ++ `_ASAsyncTransactionGroup` 会在初始化时,向 Runloop 中注册一个回调,在每次 Runloop 结束时,执行回调来提交 `displayBlock` 执行的结果 ++ `_ASAsyncTransactionContainer` 为当前 `CALayer` 提供了用于保存事务的容器,并提供了获取新的 `_ASAsyncTransaction` 实例的便利方法 ++ `_ASAsyncTransaction` 将异步操作封装成了轻量级的事务对象,使用 C++ 代码对 GCD 进行了封装 + +从上面的小节中,我们已经获取到了用于绘制的 `displayBlock`,然后就需要将 block 添加到绘制事务中: + +```objectivec +- (void)displayAsyncLayer:(_ASDisplayLayer *)asyncLayer asynchronously:(BOOL)asynchronously { + ... + + if (asynchronously) { + CALayer *containerLayer = _layer.asyncdisplaykit_parentTransactionContainer ? : _layer; + _ASAsyncTransaction *transaction = containerLayer.asyncdisplaykit_asyncTransaction; + [transaction addOperationWithBlock:displayBlock priority:self.drawingPriority queue:[_ASDisplayLayer displayQueue] completion:completionBlock]; + } else { + ... + } +} +``` + +前两行代码是获取 `_ASAsyncTransaction` 实例的过程,这个实例会包含在一个 `layer` 的哈希表中,最后调用的实例方法 `-[_ASAsyncTransaction addOperationWithBlock:priority:queue:completion:]` 会把用于绘制的 `displayBlock` 添加到后台并行队列中: + +```objectivec ++ (dispatch_queue_t)displayQueue { + static dispatch_queue_t displayQueue = NULL; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + displayQueue = dispatch_queue_create("org.AsyncDisplayKit.ASDisplayLayer.displayQueue", DISPATCH_QUEUE_CONCURRENT); + dispatch_set_target_queue(displayQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)); + }); + + return displayQueue; +} +``` + +这个队列是一个并行队列,并且优先级是 `DISPATCH_QUEUE_PRIORITY_HIGH`,**确保 UI 的渲染会在其它异步操作执行之前进行**,而 `-[_ASAsyncTransaction addOperationWithBlock:priority:queue:completion:]` 中会初始化 `ASDisplayNodeAsyncTransactionOperation` 的实例,然后传入 `completionBlock`,在绘制结束时回调: + +```objectivec +- (void)addOperationWithBlock:(asyncdisplaykit_async_transaction_operation_block_t)block priority:(NSInteger)priority queue:(dispatch_queue_t)queue completion:(asyncdisplaykit_async_transaction_operation_completion_block_t)completion { + ASDisplayNodeAssertMainThread(); + + [self _ensureTransactionData]; + + ASDisplayNodeAsyncTransactionOperation *operation = [[ASDisplayNodeAsyncTransactionOperation alloc] initWithOperationCompletionBlock:completion]; + [_operations addObject:operation]; + _group->schedule(priority, queue, ^{ + @autoreleasepool { + operation.value = block(); + } + }); +} +``` + +`schedule` 方法是一个 C++ 方法,它会向 `ASAsyncTransactionQueue::Group` 中派发一个 block,这个 block 中会执行 `displayBlock`,然后将结果传给 `operation.value`: + +```objectivec +void ASAsyncTransactionQueue::GroupImpl::schedule(NSInteger priority, dispatch_queue_t queue, dispatch_block_t block) { + ASAsyncTransactionQueue &q = _queue; + ASDN::MutexLocker locker(q._mutex); + + DispatchEntry &entry = q._entries[queue]; + + Operation operation; + operation._block = block; + operation._group = this; + operation._priority = priority; + entry.pushOperation(operation); + + ++_pendingOperations; + + NSUInteger maxThreads = [NSProcessInfo processInfo].activeProcessorCount * 2; + + if ([[NSRunLoop mainRunLoop].currentMode isEqualToString:UITrackingRunLoopMode]) + --maxThreads; + + if (entry._threadCount < maxThreads) { + bool respectPriority = entry._threadCount > 0; + ++entry._threadCount; + + dispatch_async(queue, ^{ + while (!entry._operationQueue.empty()) { + Operation operation = entry.popNextOperation(respectPriority); + { + if (operation._block) { + operation._block(); + } + operation._group->leave(); + operation._block = nil; + } + } + --entry._threadCount; + + if (entry._threadCount == 0) { + q._entries.erase(queue); + } + }); + } +} +``` + +`ASAsyncTransactionQueue::GroupImpl` 其实现其实就是对 GCD 的封装,同时添加一些最大并发数、线程锁的功能。通过 `dispatch_async` 将 block 分发到 `queue` 中,立刻执行 block,将数据传回 `ASDisplayNodeAsyncTransactionOperation` 实例。 + +### 回调 + +在 `_ASAsyncTransactionGroup` 调用 `mainTransactionGroup` 类方法获取单例时,会通过 `+[_ASAsyncTransactionGroup registerTransactionGroupAsMainRunloopObserver]` 向 Runloop 中注册回调: + +```objectivec ++ (void)registerTransactionGroupAsMainRunloopObserver:(_ASAsyncTransactionGroup *)transactionGroup { + static CFRunLoopObserverRef observer; + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); + CFOptionFlags activities = (kCFRunLoopBeforeWaiting | kCFRunLoopExit); + CFRunLoopObserverContext context = {0, (__bridge void *)transactionGroup, &CFRetain, &CFRelease, NULL}; + + observer = CFRunLoopObserverCreate(NULL, activities, YES, INT_MAX, &_transactionGroupRunLoopObserverCallback, &context); + CFRunLoopAddObserver(runLoop, observer, kCFRunLoopCommonModes); + CFRelease(observer); +} +``` + +上述代码会在即将退出 Runloop 或者 Runloop 开始休眠时执行回调 `_transactionGroupRunLoopObserverCallback`,而这个回调方法就是这一条主线的入口: + +```objectivec +static void _transactionGroupRunLoopObserverCallback(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) { + ASDisplayNodeCAssertMainThread(); + _ASAsyncTransactionGroup *group = (__bridge _ASAsyncTransactionGroup *)info; + [group commit]; +} +``` + +上一节中只是会将绘制代码提交到后台的并发进程中,而这里才会将结果提交,也就是在每次 Runloop 循环结束时开始绘制内容,而 `-[_operationCompletionBlock commit]` 方法的调用栈能够帮助我们理解内容是如何提交的,又是如何传回 `node` 持有的 `layer` 的: + +```objectivec +-[_ASAsyncTransactionGroup commit] + -[_ASAsyncTransaction commit] + ASAsyncTransactionQueue::GroupImpl::notify(dispatch_queue_t, dispatch_block_t) + _notifyList.push_back(GroupNotify) +``` + +`-[_ASAsyncTransactionGroup commit]` 方法的调用完成了对绘制事务的提交,而在 `-[_ASAsyncTransaction commit]` 中会调用 `notify` 方法,在上一节中的 `displayBlock` 执行结束后调用这里传入的 block 执行 `-[_ASAsyncTransaction completeTransaction]` 方法: + +```objectivec +- (void)commit { + ASDisplayNodeAssertMainThread(); + __atomic_store_n(&_state, ASAsyncTransactionStateCommitted, __ATOMIC_SEQ_CST); + + _group->notify(_callbackQueue, ^{ + ASDisplayNodeAssertMainThread(); + [self completeTransaction]; + }); +} +``` + +我们按照时间顺序来分析在上面的 block 执行之前,方法是如何调用的,以及 block 是如何被执行的;这就不得不回到派发绘制事务的部分了,在 `ASAsyncTransactionQueue::GroupImpl::schedule` 方法中,使用了 `dispatch_async` 将派发 block: + +```objectivec +void ASAsyncTransactionQueue::GroupImpl::schedule(NSInteger priority, dispatch_queue_t queue, dispatch_block_t block) { + ... + if (entry._threadCount < maxThreads) { + ... + dispatch_async(queue, ^{ + ... + while (!entry._operationQueue.empty()) { + Operation operation = entry.popNextOperation(respectPriority); + { + ASDN::MutexUnlocker unlock(q._mutex); + if (operation._block) { + operation._block(); + } + operation._group->leave(); + operation._block = nil; + } + } + ... + }); + } +} +``` + +在 `displayBlock` 执行之后,会调用的 `group` 的 `leave` 方法: + +```objectivec +void ASAsyncTransactionQueue::GroupImpl::leave() { + if (_pendingOperations == 0) { + std::list notifyList; + _notifyList.swap(notifyList); + + for (GroupNotify & notify : notifyList) { + dispatch_async(notify._queue, notify._block); + } + } +} +``` + +这里终于执行了在 `- commit` 中加入的 block,也就是 `-[_ASAsyncTransaction completeTransaction]` 方法: + +```objectivec +- (void)completeTransaction { + if (__atomic_load_n(&_state, __ATOMIC_SEQ_CST) != ASAsyncTransactionStateComplete) { + BOOL isCanceled = (__atomic_load_n(&_state, __ATOMIC_SEQ_CST) == ASAsyncTransactionStateCanceled); + for (ASDisplayNodeAsyncTransactionOperation *operation in _operations) { + [operation callAndReleaseCompletionBlock:isCanceled]; + } + + __atomic_store_n(&_state, ASAsyncTransactionStateComplete, __ATOMIC_SEQ_CST); + } +} +``` + +最后的最后,`-[ASDisplayNodeAsyncTransactionOperation callAndReleaseCompletionBlock:]` 方法执行了回调将 `displayBlock` 执行的结果传回了 CALayer: + +```objectivec +- (void)callAndReleaseCompletionBlock:(BOOL)canceled; { + if (_operationCompletionBlock) { + _operationCompletionBlock(self.value, canceled); + self.operationCompletionBlock = nil; + } +} +``` + +也就是在 `-[ASDisplayNode(AsyncDisplay) displayAsyncLayer:asynchronously:]` 方法中构建的 `completionBlock`: + +```objectivec +asyncdisplaykit_async_transaction_operation_completion_block_t completionBlock = ^(id value, BOOL canceled){ + ASDisplayNodeCAssertMainThread(); + if (!canceled && !isCancelledBlock()) { + UIImage *image = (UIImage *)value; + BOOL stretchable = !UIEdgeInsetsEqualToEdgeInsets(image.capInsets, UIEdgeInsetsZero); + if (stretchable) { + ASDisplayNodeSetupLayerContentsWithResizableImage(_layer, image); + } else { + _layer.contentsScale = self.contentsScale; + _layer.contents = (id)image.CGImage; + } + [self didDisplayAsyncLayer:self.asyncLayer]; + } +}; +``` + +这一部分进行的大量的数据传递都是通过 block 进行的,从 Runloop 中对事务的提交,以及通过 `notify` 方法加入的 block,都是为了最后将绘制的结果传回 `CALayer` 对象,而到这里可以说整个 ASDK 对于视图内容的绘制过程就结束了。 + +## 总结 + +ASDK 对于绘制过程的优化有三部分:分别是栅格化子视图、绘制图像以及绘制文字。 + +它拦截了视图加入层级时发出的通知 `- willMoveToWindow:` 方法,然后手动调用 `- setNeedsDisplay`,强制所有的 `CALayer` 执行 `- display` 更新内容; + +然后将上面的操作全部抛入了后台的并发线程中,并在 Runloop 中注册回调,在每次 Runloop 结束时,对已经完成的事务进行 `- commit`,以图片的形式直接传回对应的 `layer.content` 中,完成对内容的更新。 + +从它的实现来看,确实从主线程移除了很多昂贵的 CPU 以及 GPU 操作,有效地加快了视图的绘制和渲染,保证了主线程的流畅执行。 + +## References + ++ [How VSync works, and why people loathe it](https://hardforum.com/threads/how-vsync-works-and-why-people-loathe-it.928593/) ++ [脑洞大开:为啥帧率达到 60 fps 就流畅?](http://www.jianshu.com/p/71cba1711de0) ++ [iOS 保持界面流畅的技巧](http://blog.ibireme.com/2015/11/12/smooth_user_interfaces_for_ios/) ++ [CADiplayLink Class Reference - Developer- Apple](https://en.wikipedia.org/wiki/Analog_television#Vertical_synchronization) ++ [CPU vs GPU · iOS 核心动画高级技巧](https://zsisme.gitbooks.io/ios-/content/chapter12/cpu-versus-gpu.html) ++ [理解 UIView 的绘制](http://vizlabxt.github.io/blog/2012/10/22/UIView-Rendering/) ++ [Introduce to AsyncDisplayKit](http://vizlabxt.github.io/blog/2015/01/09/Behind-AsyncDisplayKit/) ++ [AsyncDisplayKit Tutorial: Achieving 60 FPS scrolling](https://www.raywenderlich.com/86365/asyncdisplaykit-tutorial-achieving-60-fps-scrolling) ++ [Layer Trees vs. Flat Drawing – Graphics Performance Across iOS Device Generations](http://floriankugler.com/2013/05/24/layer-trees-vs-flat-drawing-graphics-performance-across-ios-device-generations/) ++ [深入理解 RunLoop](http://blog.ibireme.com/2015/05/18/runloop/) + +## 其它 + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · Github](https://github.com/Draveness) +> +> Source: http://draveness.me/asdk-rendering + + diff --git "a/contents/AsyncDisplayKit/\351\242\204\345\212\240\350\275\275\344\270\216\346\231\272\350\203\275\351\242\204\345\212\240\350\275\275\357\274\210iOS\357\274\211.md" "b/contents/AsyncDisplayKit/\351\242\204\345\212\240\350\275\275\344\270\216\346\231\272\350\203\275\351\242\204\345\212\240\350\275\275\357\274\210iOS\357\274\211.md" new file mode 100644 index 0000000..af45a4b --- /dev/null +++ "b/contents/AsyncDisplayKit/\351\242\204\345\212\240\350\275\275\344\270\216\346\231\272\350\203\275\351\242\204\345\212\240\350\275\275\357\274\210iOS\357\274\211.md" @@ -0,0 +1,531 @@ +# 预加载与智能预加载(iOS) + +> 前两次的分享分别介绍了 ASDK 对于渲染的优化以及 ASDK 中使用的另一种布局模型;这两个新机制的引入分别解决了 iOS 在主线程渲染视图以及 Auto Layout 的性能问题,而这一次讨论的主要内容是 ASDK 如何预先请求服务器数据,达到看似无限滚动列表的效果的。 + +这篇文章是 ASDK 系列中的最后一篇,文章会介绍 iOS 中几种*预加载*的方案,以及 ASDK 中是如何处理预加载的。 + +不过,在介绍 ASDK 中实现**智能预加载**的方式之前,文章中会介绍几种简单的预加载方式,方便各位开发者进行对比,选择合适的机制实现预加载这一功能。 + +## 网络与性能 + +ASDK 通过在渲染视图和布局方面的优化已经可以使应用在任何用户的疯狂操作下都能保持 60 FPS 的流畅程度,也就是说,我们已经充分的利用了当前设备的性能,调动各种资源加快视图的渲染。 + +但是,仅仅在 CPU 以及 GPU 方面的优化往往是远远不够的。在目前的软件开发中,很难找到一个**没有任何网络请求**的应用,哪怕是一个记账软件也需要服务器来同步保存用户的信息,防止资料的丢失;所以,只在渲染这一层面进行优化还不能让用户的体验达到最佳,因为网络请求往往是一个应用**最为耗时以及昂贵**的操作。 + +![network](images/network.jpg) + +每一个应用程序在运行时都可以看做是 CPU 在底层利用各种资源疯狂做加减法运算,其中最耗时的操作并不是进行加减法的过程,而是**资源转移**的过程。 + +> 举一个不是很恰当的例子,主厨(CPU)在炒一道菜(计算)时往往需要的时间并不多,但是菜的采购以及准备(资源的转移)会占用大量的时间,如果在每次炒菜之前,都由帮厨提前准备好所有的食材(缓存),那么做一道菜的时间就大大减少了。 + +而提高资源转移的效率的最佳办法就是使用多级缓存: + +![multi-laye](images/multi-layer.jpg) + +从上到下,虽然容量越来越大,直到 Network 层包含了整个互联网的内容,但是访问时间也是直线上升;在 Core 或者三级缓存中的资源可能访问只需要几个或者几十个时钟周期,但是网络中的资源就**远远**大于这个数字,几分钟、几小时都是有可能的。 + +更糟糕的是,因为天朝的网络情况及其复杂,运营商劫持 DNS、404 无法访问等问题导致网络问题极其严重;而如何加速网络请求成为了很多移动端以及 Web 应用的重要问题。 + +## 预加载 + +本文就会提供一种**缓解网络请求缓慢导致用户体验较差**的解决方案,也就是预加载;在本地真正需要渲染界面之前就通过网络请求获取资源存入内存或磁盘。 + +> 预加载并不能彻底解决网络请求缓慢的问题,而是通过提前发起网络请求**缓解**这一问题。 + +那么,预加载到底要关注哪些方面的问题呢?总结下来,有以下两个关注点: + ++ 需要预加载的资源 ++ 预加载发出的时间 + +文章会根据上面的两个关注点,分别分析四种预加载方式的实现原理以及优缺点: + +1. 无限滚动列表 +2. threshold +3. 惰性加载 +4. 智能预加载 + +### 无限滚动列表 + +其实,无限滚动列表并不能算是一种预加载的实现原理,它只是提供一种分页显示的方法,在每次滚动到 `UITableView` 底部时,才会开始发起网络请求向服务器获取对应的资源。 + +虽然这种方法并不是预加载方式的一种,放在这里的主要作用是作为对比方案,看看如果不使用预加载的机制,用户体验是什么样的。 + +![infinite-list](images/infinite-list.jpg) + +很多客户端都使用了分页的加载方式,并没有添加额外的预加载的机制来提升用户体验,虽然这种方式并不是不能接受,不过每次滑动到视图底部之后,总要等待网络请求的完成确实对视图的流畅性有一定影响。 + +虽然仅仅使用无限滚动列表而不提供预加载机制会在一定程度上影响用户体验,不过,这种**需要用户等待几秒钟**的方式,在某些时候确实非常好用,比如:投放广告。 + +![advertise](images/advertise.jpg) + +> QQ 空间就是这么做的,它们**投放的广告基本都是在整个列表的最底端**,这样,当你滚动到列表最下面的时候,就能看到你急需的租房、租车、同城交友、信用卡办理、只有 iPhone 能玩的游戏以及各种奇奇怪怪的辣鸡广告了,很好的解决了我们的日常生活中的各种需求。(哈哈哈哈哈哈哈哈哈哈哈哈哈) + +### Threshold + +使用 Threshold 进行预加载是一种最为常见的预加载方式,知乎客户端就使用了这种方式预加载条目,而其原理也非常简单,根据当前 `UITableView` 的所在位置,除以目前整个 `UITableView.contentView` 的高度,来判断当前是否需要发起网络请求: + +```swift +let threshold: CGFloat = 0.7 +var currentPage = 0 + +override func scrollViewDidScroll(_ scrollView: UIScrollView) { + let current = scrollView.contentOffset.y + scrollView.frame.size.height + let total = scrollView.contentSize.height + let ratio = current / total + + if ratio >= threshold { + currentPage += 1 + print("Request page \(currentPage) from server.") + } +} +``` + +上面的代码在当前页面已经划过了 70% 的时候,就请求新的资源,加载数据;但是,仅仅使用这种方法会有另一个问题,尤其是当列表变得很长时,十分明显,比如说:用户从上向下滑动,总共加载了 5 页数据: + +| Page | Total | Threshold | Diff | +| :-: | :-: | :-: | :-: | +| 1 | 10 | 7 | 7 | +| 2 | 20 | 14 | 4 | +| 3 | 30 | 21 | 1 | +| 4 | 40 | 28 | -2 | +| 5 | 50 | 35 | -5 | + ++ Page 当前总页数; ++ Total 当前 `UITableView` 总元素个数; ++ Threshold 网络请求触发时间; ++ Diff 表示最新加载的页面被浏览了多少; + +当 Threshold 设置为 70% 的时候,其实并不是单页 70%,这就会导致**新加载的页面都没有看,应用就会发出另一次请求,获取新的资源**。 + +#### 动态的 Threshold + +解决这个问题的办法,还是比较简单的,通过修改上面的代码,将 Threshold 变成一个动态的值,随着页数的增长而增长: + +```swift +let threshold: CGFloat = 0.7 +let itemPerPage: CGFloat = 10 +var currentPage: CGFloat = 0 + +override func scrollViewDidScroll(_ scrollView: UIScrollView) { + let current = scrollView.contentOffset.y + scrollView.frame.size.height + let total = scrollView.contentSize.height + let ratio = current / total + + let needRead = itemPerPage * threshold + currentPage * itemPerPage + let totalItem = itemPerPage * (currentPage + 1) + let newThreshold = needRead / totalItem + + if ratio >= newThreshold { + currentPage += 1 + print("Request page \(currentPage) from server.") + } +} +``` + +通过这种方法获取的 `newThreshold` 就会随着页数的增长而动态的改变,解决了上面出现的问题: + +![dynamic-threshold](images/dynamic-threshold.jpeg) + +### 惰性加载 + +使用 Threshold 进行预加载其实已经适用于大多数应用场景了;但是,下面介绍的方式,*惰性加载*能够有针对性的加载用户“会看到的” Cell。 + +> *惰性加载*,就是在用户滚动的时候会对用户滚动结束的区域进行计算,只加载目标区域中的资源。 + +用户在飞速滚动中会看到巨多的空白条目,因为用户并不想阅读这些条目,所以,我们并不需要真正去加载这些内容,只需要在 `ASTableView/ASCollectionView` 中只根据用户滚动的目标区域惰性加载资源。 + +![lazy-loading](images/lazy-loading.png) + +惰性加载的方式不仅仅减少了网络请求的冗余资源,同时也减少了渲染视图、数据绑定的耗时。 + +计算用户滚动的目标区域可以直接使用下面的代理方法获取: + +```swift +let markedView = UIView() +let rowHeight: CGFloat = 44.0 + +override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) { + let targetOffset = targetContentOffset.pointee + let targetRect = CGRect(origin: targetOffset, size: scrollView.frame.size) + + markedView.frame = targetRect + markedView.backgroundColor = UIColor.black.withAlphaComponent(0.1) + tableView.addSubview(markedView) + + var indexPaths: [IndexPath] = [] + + let startIndex = Int(targetRect.origin.y / rowHeight) + let endIndex = Int((targetRect.origin.y + tableView.frame.height) / rowHeight) + + for index in startIndex...endIndex { + indexPaths.append(IndexPath(row: index, section: 0)) + } + + print("\(targetRect) \(indexPaths)") +} +``` + +> 以上代码只会大致计算出目标区域内的 `IndexPath` 数组,并不会展开新的 page,同时会使用浅黑色标记目标区域。 + +当然,惰性加载的实现也并不只是这么简单,不仅需要客户端的工作,同时因为需要**加载特定 offset 资源**,也需要服务端提供相应 API 的支持。 + +虽然惰性加载的方式能够按照用户的需要请求对应的资源,但是,在用户滑动 `UITableView` 的过程中会看到大量的空白条目,这样的用户体验是否可以接受又是值得考虑的问题了。 + +### 智能预加载 + +终于到了智能预加载的部分了,当我第一次得知 ASDK 可以通过滚动的方向预加载不同数量的内容,感觉是非常神奇的。 + + + +如上图所示 ASDK 把正在滚动的 ` ASTableView/ASCollectionView` 划分为三种状态: + ++ Fetch Data ++ Display ++ Visible + +上面的这三种状态都是由 ASDK 来管理的,而每一个 `ASCellNode` 的状态都是由 `ASRangeController` 控制,所有的状态都对应一个 `ASInterfaceState`: + ++ `ASInterfaceStatePreload` 当前元素貌似要显示到屏幕上,需要从磁盘或者网络请求数据; ++ `ASInterfaceStateDisplay` 当前元素非常可能要变成可见的,需要进行异步绘制; ++ `ASInterfaceStateVisible` 当前元素最少在屏幕上显示了 1px + +当用户滚动当前视图时,`ASRangeController` 就会修改不同区域内元素的状态: + + + +上图是用户在向下滑动时,`ASCellNode` 是如何被标记的,假设**当前视图可见的范围高度为 1**,那么在默认情况下,五个区域会按照上图的形式进行划分: + +| Buffer | Size | +| :-: | :-: | +| Fetch Data Leading Buffer | 2 | +| Display Leading Buffer | 1 | +| Visible | 1 | +| Display Trailing Buffer | 1 | +| Fetch Data Trailing Buffer | 1 | + +在滚动方向(Leading)上 Fetch Data 区域会是非滚动方向(Trailing)的两倍,ASDK 会根据滚动方向的变化实时改变缓冲区的位置;在向下滚动时,下面的 Fetch Data 区域就是上面的两倍,向上滚动时,上面的 Fetch Data 区域就是下面的两倍。 + +> 这里的两倍并不是一个确定的数值,ASDK 会根据当前设备的不同状态,改变不同区域的大小,但是**滚动方向的区域总会比非滚动方向大一些**。 + +智能预加载能够根据当前的滚动方向,自动改变当前的工作区域,选择合适的区域提前触发请求资源、渲染视图以及异步布局等操作,让视图的滚动达到真正的流畅。 + +#### 原理 + +在 ASDK 中整个智能预加载的概念是由三个部分来统一协调管理的: + ++ `ASRangeController` ++ `ASDataController` ++ `ASTableView` 与 `ASTableNode` + +对智能预加载实现的分析,也是根据这三个部分来介绍的。 + +#### 工作区域的管理 + +`ASRangeController` 是 `ASTableView` 以及 `ASCollectionView` 内部使用的控制器,主要用于监控视图的可见区域、维护工作区域、触发网络请求以及绘制、单元格的异步布局。 + +以 `ASTableView` 为例,在视图进行滚动时,会触发 `-[UIScrollView scrollViewDidScroll:]` 代理方法: + +```objectivec +- (void)scrollViewDidScroll:(UIScrollView *)scrollView { + ASInterfaceState interfaceState = [self interfaceStateForRangeController:_rangeController]; + if (ASInterfaceStateIncludesVisible(interfaceState)) { + [_rangeController updateCurrentRangeWithMode:ASLayoutRangeModeFull]; + } + ... +} +``` + +> 每一个 `ASTableView` 的实例都持有一个 `ASRangeController` 以及 `ASDataController` 用于管理工作区域以及数据更新。 + +ASRangeController 最重要的私有方法 `-[ASRangeController _updateVisibleNodeIndexPaths]` 一般都是因为上面的方法间接调用的: + +```objectivec +-[ASRangeController updateCurrentRangeWithMode:] + -[ASRangeController setNeedsUpdate] + -[ASRangeController updateIfNeeded] + -[ASRangeController _updateVisibleNodeIndexPaths] +``` + +调用栈中间的过程其实并不重要,最后的私有方法的主要工作就是计算不同区域内 Cell 的 `NSIndexPath` 数组,然后更新对应 Cell 的状态 `ASInterfaceState` 触发对应的操作。 + +我们将这个私有方法的实现分开来看: + +```objectivec +- (void)_updateVisibleNodeIndexPaths { + NSArray *allNodes = [_dataSource completedNodes]; + NSUInteger numberOfSections = [allNodes count]; + + NSArray *visibleNodePaths = [_dataSource visibleNodeIndexPathsForRangeController:self]; + + ASScrollDirection scrollDirection = [_dataSource scrollDirectionForRangeController:self]; + if (_layoutControllerImplementsSetViewportSize) { + [_layoutController setViewportSize:[_dataSource viewportSizeForRangeController:self]]; + } + + if (_layoutControllerImplementsSetVisibleIndexPaths) { + [_layoutController setVisibleNodeIndexPaths:visibleNodePaths]; + } + ... +} +``` + +当前 `ASRangeController` 的数据源以及代理就是 `ASTableView`,这段代码首先就获取了完成计算和布局的 `ASCellNode` 以及可见的 `ASCellNode` 的 `NSIndexPath`: + +```objectivec +- (void)_updateVisibleNodeIndexPaths { + NSArray *currentSectionNodes = nil; + NSInteger currentSectionIndex = -1; + NSUInteger numberOfNodesInSection = 0; + + NSSet *visibleIndexPaths = [NSSet setWithArray:visibleNodePaths]; + NSSet *displayIndexPaths = nil; + NSSet *preloadIndexPaths = nil; + + NSMutableOrderedSet *allIndexPaths = [[NSMutableOrderedSet alloc] initWithSet:visibleIndexPaths]; + + ASLayoutRangeMode rangeMode = _currentRangeMode; + + ASRangeTuningParameters parametersPreload = [_layoutController tuningParametersForRangeMode:rangeMode + rangeType:ASLayoutRangeTypePreload]; + if (ASRangeTuningParametersEqualToRangeTuningParameters(parametersPreload, ASRangeTuningParametersZero)) { + preloadIndexPaths = visibleIndexPaths; + } else { + preloadIndexPaths = [_layoutController indexPathsForScrolling:scrollDirection + rangeMode:rangeMode + rangeType:ASLayoutRangeTypePreload]; + } + + #: displayIndexPaths 的计算和 preloadIndexPaths 非常类似 + + [allIndexPaths unionSet:displayIndexPaths]; + [allIndexPaths unionSet:preloadIndexPaths]; + ... +} +``` + +预加载以及展示部分的 `ASRangeTuningParameters` 都是以二维数组的形式保存在 `ASAbstractLayoutController` 中的: + +![aslayout-range-mode-display-preload](images/aslayout-range-mode-display-preload.jpeg) + +在获取了 `ASRangeTuningParameters` 之后,ASDK 也会通过 `ASFlowLayoutController` 的方法 `-[ASFlowLayoutController indexPathsForScrolling:rangeMode:rangeType:]` 获取 `NSIndexPath` 对象的集合: + +```objectivec +- (NSSet *)indexPathsForScrolling:(ASScrollDirection)scrollDirection rangeMode:(ASLayoutRangeMode)rangeMode rangeType:(ASLayoutRangeType)rangeType { + #: 获取 directionalBuffer 以及 viewportDirectionalSize + ASIndexPath startPath = [self findIndexPathAtDistance:(-directionalBuffer.negativeDirection * viewportDirectionalSize) + fromIndexPath:_visibleRange.start]; + ASIndexPath endPath = [self findIndexPathAtDistance:(directionalBuffer.positiveDirection * viewportDirectionalSize) + fromIndexPath:_visibleRange.end]; + + NSMutableSet *indexPathSet = [[NSMutableSet alloc] init]; + NSArray *completedNodes = [_dataSource completedNodes]; + ASIndexPath currPath = startPath; + while (!ASIndexPathEqualToIndexPath(currPath, endPath)) { + [indexPathSet addObject:[NSIndexPath indexPathWithASIndexPath:currPath]]; + currPath.row++; + + while (currPath.row >= [(NSArray *)completedNodes[currPath.section] count] && currPath.section < endPath.section) { + currPath.row = 0; + currPath.section++; + } + } + [indexPathSet addObject:[NSIndexPath indexPathWithASIndexPath:endPath]]; + return indexPathSet; +} +``` + +方法的执行过程非常简单,根据 `ASRangeTuningParameters` 获取该滚动方向上的缓冲区大小,在区域内遍历所有的 `ASCellNode` 查看其是否在当前区域内,然后加入数组中。 + +到这里,所有工作区域 `visibleIndexPaths` `displayIndexPaths` 以及 `preloadIndexPaths` 都已经获取到了;接下来,就到了遍历 `NSIndexPath`,修改结点状态的过程了; + +```objectivec +- (void)_updateVisibleNodeIndexPaths { + ... + for (NSIndexPath *indexPath in allIndexPaths) { + ASInterfaceState interfaceState = ASInterfaceStateMeasureLayout; + + if (ASInterfaceStateIncludesVisible(selfInterfaceState)) { + if ([visibleIndexPaths containsObject:indexPath]) { + interfaceState |= (ASInterfaceStateVisible | ASInterfaceStateDisplay | ASInterfaceStatePreload); + } else { + if ([preloadIndexPaths containsObject:indexPath]) { + interfaceState |= ASInterfaceStatePreload; + } + if ([displayIndexPaths containsObject:indexPath]) { + interfaceState |= ASInterfaceStateDisplay; + } + } + } +``` + +根据当前 `ASTableView` 的状态以及 `NSIndexPath` 所在的区域,打开 `ASInterfaceState` 对应的位。 + +```objectivec + NSInteger section = indexPath.section; + NSInteger row = indexPath.row; + + if (section >= 0 && row >= 0 && section < numberOfSections) { + if (section != currentSectionIndex) { + currentSectionNodes = allNodes[section]; + numberOfNodesInSection = [currentSectionNodes count]; + currentSectionIndex = section; + } + + if (row < numberOfNodesInSection) { + ASDisplayNode *node = currentSectionNodes[row]; + + if (node.interfaceState != interfaceState) { + BOOL nodeShouldScheduleDisplay = [node shouldScheduleDisplayWithNewInterfaceState:interfaceState]; + [node recursivelySetInterfaceState:interfaceState]; + + if (nodeShouldScheduleDisplay) { + [self registerForNodeDisplayNotificationsForInterfaceStateIfNeeded:selfInterfaceState]; + if (_didRegisterForNodeDisplayNotifications) { + _pendingDisplayNodesTimestamp = CFAbsoluteTimeGetCurrent(); + } + } + } + } + } + } + ... +} +``` + +后面的一部分代码就会递归的设置结点的 `interfaceState`,并且在当前 `ASRangeController` 的 `ASLayoutRangeMode` 发生改变时,发出通知,调用 `-[ASRangeController _updateVisibleNodeIndexPaths]` 私有方法,更新结点的状态。 + +```objectivec +- (void)scheduledNodesDidDisplay:(NSNotification *)notification { + CFAbsoluteTime notificationTimestamp = ((NSNumber *) notification.userInfo[ASRenderingEngineDidDisplayNodesScheduledBeforeTimestamp]).doubleValue; + if (_pendingDisplayNodesTimestamp < notificationTimestamp) { + [[NSNotificationCenter defaultCenter] removeObserver:self name:ASRenderingEngineDidDisplayScheduledNodesNotification object:nil]; + _didRegisterForNodeDisplayNotifications = NO; + + [self setNeedsUpdate]; + } +} +``` + +#### 数据的加载和更新 + +`ASTableNode` 既然是对 `ASTableView` 的封装,那么表视图中显示的数据仍然需要数据源来提供,而在 ASDK 中这一机制就比较复杂: + +![astableview-data](images/astableview-data.png) + +整个过程是由四部分协作完成的,`Controller`、`ASTableNode`、`ASTableView` 以及 `ASDataController`,网络请求发起并返回数据之后,会调用 `ASTableNode` 的 API 执行插入行的方法,最后再通过 `ASTableView` 的同名方法,执行管理和更新节点数据的 `ASDataController` 的方法: + +```objectivec +- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withAnimationOptions:(ASDataControllerAnimationOptions)animationOptions { + dispatch_group_wait(_editingTransactionGroup, DISPATCH_TIME_FOREVER); + + NSArray *sortedIndexPaths = [indexPaths sortedArrayUsingSelector:@selector(compare:)]; + NSMutableArray *contexts = [[NSMutableArray alloc] initWithCapacity:indexPaths.count]; + + __weak id environment = [self.environmentDelegate dataControllerEnvironment]; + + for (NSIndexPath *indexPath in sortedIndexPaths) { + ASCellNodeBlock nodeBlock = [_dataSource dataController:self nodeBlockAtIndexPath:indexPath]; + ASSizeRange constrainedSize = [self constrainedSizeForNodeOfKind:ASDataControllerRowNodeKind atIndexPath:indexPath]; + [contexts addObject:[[ASIndexedNodeContext alloc] initWithNodeBlock:nodeBlock + indexPath:indexPath + supplementaryElementKind:nil + constrainedSize:constrainedSize + environment:environment]]; + } + ASInsertElementsIntoMultidimensionalArrayAtIndexPaths(_nodeContexts[ASDataControllerRowNodeKind], sortedIndexPaths, contexts); + dispatch_group_async(_editingTransactionGroup, _editingTransactionQueue, ^{ + [self _batchLayoutAndInsertNodesFromContexts:contexts withAnimationOptions:animationOptions]; + }); +} +``` + +上面的方法总共做了几件事情: + +1. 遍历所有要插入的 `NSIndexPath` 数组,然后从数据源中获取对应的 `ASCellNodeBlock`; +2. 获取每一个 `NSIndexPath` 对应的单元的大小 `constrainedSize`(在图中没有表现出来); +3. 初始化一堆 `ASIndexedNodeContext` 实例,然后加入到控制器维护的 `_nodeContexts` 数组中; +4. 将节点插入到 `_completedNodes` 中,用于之后的缓存,以及提供给 `ASTableView` 的数据源代理方法使用; + +`ASTableView` 会将数据源协议的代理设置为自己,而最常见的数据源协议在 `ASTableView` 中的实现是这样的: + +```objectivec +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + _ASTableViewCell *cell = [self dequeueReusableCellWithIdentifier:kCellReuseIdentifier forIndexPath:indexPath]; + cell.delegate = self; + + ASCellNode *node = [_dataController nodeAtCompletedIndexPath:indexPath]; + if (node) { + [_rangeController configureContentView:cell.contentView forCellNode:node]; + cell.node = node; + cell.backgroundColor = node.backgroundColor; + cell.selectionStyle = node.selectionStyle; + cell.clipsToBounds = node.clipsToBounds; + } + + return cell; +} +``` + +上面的方法会从 `ASDataController` 中的 `_completedNodes` 中获取元素的数量信息: + +![cellforrowatindexpath](images/cellforrowatindexpath.jpg) + +> 在内部 `_externalCompletedNodes` 与 `_completedNodes` 作用基本相同,在这里我们不对它们的区别进行分析以及解释。 + +当 `ASTableView` 向数据源请求数据时,ASDK 就会从对应的 `ASDataController` 中取回最新的 `node`,添加在 `_ASTableViewCell` 的实例上显示出来。 + +#### ASTableView 和 ASTableNode + +`ASTableView` 和 `ASTableNode` 的关系,其实就相当于 `CALayer` 和 `UIView` 的关系一样,后者都是前者的一个包装: + +![astableview-astablenode](images/astableview-astablenode.jpg) + +`ASTableNode` 为开发者提供了非常多的接口,其内部实现往往都是直接调用 `ASTableView` 的对应方法,在这里简单举几个例子: + +```objectivec +- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation { + [self.view insertSections:sections withRowAnimation:animation]; +} + +- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation { + [self.view deleteSections:sections withRowAnimation:animation]; +} +``` + +如果你再去看 `ASTableView` 中方法的实现的话,会发现很多方法都是由 `ASDataController` 和 `ASRangeController` 驱动的,上面的两个方法的实现就是这样的: + +```objectivec +- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation { + if (sections.count == 0) { return; } + [_dataController insertSections:sections withAnimationOptions:animation]; +} + +- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation { + if (sections.count == 0) { return; } + [_dataController deleteSections:sections withAnimationOptions:animation]; +} +``` + +到这里,整个智能预加载的部分就结束了,从*需要预加载的资源*以及*预加载发出的时间*两个方面来考虑,ASDK 在不同工作区域中合理标记了需要预加载的资源,并在节点状态改变时就发出请求,在用户体验上是非常优秀的。 + +## 总结 + +ASDK 中的表视图以及智能预加载其实都是通过下面这四者共同实现的,上层只会暴露出 `ASTableNode` 的接口,所有的数据的批量更新、工作区域的管理都是在幕后由 `ASDataController` 以及 `ASRangeController` 这两个控制器协作完成。 + +![multi-layer-asdk](images/multi-layer-asdk.jpg) + +智能预加载的使用相比其它实现可能相对复杂,但是在笔者看来,ASDK 对于这一套机制的实现还是非常完善的,同时也提供了极其优秀的用户体验,不过同时带来的也是相对较高的学习成本。 + +如果真正要选择预加载的机制,笔者觉得最好从 Threshold 以及智能预加载两种方式中选择: + +![pros-cons](images/pros-cons.jpg) + +这两种方式的选择,其实也就是实现复杂度和用户体验之间的权衡了。 + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/preload + + diff --git "a/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\270\200\357\274\211.md" "b/contents/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\270\200\357\274\211.md" similarity index 99% rename from "BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\270\200\357\274\211.md" rename to "contents/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\270\200\357\274\211.md" index 6233bb0..b718ad1 100644 --- "a/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\270\200\357\274\211.md" +++ "b/contents/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\270\200\357\274\211.md" @@ -94,7 +94,7 @@ BlocksKit 在这些集合类中所添加的一些方法在 Ruby、Haskell 等语 ```objectivec NSObject *test = [[NSObject alloc] init]; -[test bk_associateValue:@"Draveness" withKey:@" name"]; +[test bk_associateValue:@"Draveness" withKey:@"name"]; NSLog(@"%@",[test bk_associatedValueForKey:@"name"]); 2016-03-05 16:02:25.761 Draveness[10699:452125] Draveness @@ -630,8 +630,8 @@ void (^block)(void) = ^{ 由于这篇文章中的内容较多,所以内容分成了两个部分,下一部分介绍的是 BlocksKit 中的最重要的部分动态代理: -+ [神奇的 BlocksKit(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/BlocksKit/神奇的%20BlocksKit%20(一).md) -+ [神奇的 BlocksKit(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/BlocksKit/神奇的%20BlocksKit%20(二).md) ++ [神奇的 BlocksKit(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/BlocksKit/神奇的%20BlocksKit%20(一).md) ++ [神奇的 BlocksKit(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/BlocksKit/神奇的%20BlocksKit%20(二).md) diff --git "a/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\272\214\357\274\211.md" "b/contents/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\272\214\357\274\211.md" similarity index 98% rename from "BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\272\214\357\274\211.md" rename to "contents/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\272\214\357\274\211.md" index b2f1037..43033ce 100644 --- "a/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\272\214\357\274\211.md" +++ "b/contents/BlocksKit/\347\245\236\345\245\207\347\232\204 BlocksKit \357\274\210\344\272\214\357\274\211.md" @@ -4,8 +4,8 @@ Blog: [Draveness](http://draveness.me) 这篇文章『神奇的 BlocksKit』的第二部分,关于第一部分的内容在这里: -+ [神奇的 BlocksKit(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/BlocksKit/神奇的%20BlocksKit%20(一).md) -+ [神奇的 BlocksKit(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/BlocksKit/神奇的%20BlocksKit%20(二).md) ++ [神奇的 BlocksKit(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/BlocksKit/神奇的%20BlocksKit%20(一).md) ++ [神奇的 BlocksKit(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/BlocksKit/神奇的%20BlocksKit%20(二).md) ## 动态代理 @@ -680,8 +680,8 @@ if (retSize) { 我写这篇文章大约用了七天的时间,如果你对其中的内容有些疑问,可以发邮件或者在下面留言。 -+ [神奇的 BlocksKit(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/BlocksKit/神奇的%20BlocksKit%20(一).md) -+ [神奇的 BlocksKit(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/BlocksKit/神奇的%20BlocksKit%20(二).md) ++ [神奇的 BlocksKit(一)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/BlocksKit/神奇的%20BlocksKit%20(一).md) ++ [神奇的 BlocksKit(二)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/BlocksKit/神奇的%20BlocksKit%20(二).md) diff --git a/contents/Blog/images/initialize-comments/new-token.png b/contents/Blog/images/initialize-comments/new-token.png new file mode 100644 index 0000000..9404350 Binary files /dev/null and b/contents/Blog/images/initialize-comments/new-token.png differ diff --git a/contents/Blog/images/initialize-comments/personal-access-token.png b/contents/Blog/images/initialize-comments/personal-access-token.png new file mode 100644 index 0000000..bd43b0a Binary files /dev/null and b/contents/Blog/images/initialize-comments/personal-access-token.png differ diff --git a/contents/Blog/initialize-comments.md b/contents/Blog/initialize-comments.md new file mode 100644 index 0000000..ded378d --- /dev/null +++ b/contents/Blog/initialize-comments.md @@ -0,0 +1,136 @@ +# 如何自动初始化 Gitalk/Gitment 评论 + +之前的博客一直都使用 Disqus 作为评论系统,然后因为 Disqus 在国内无法访问,很多读者都只能通过邮件的方式咨询一些问题,昨天觉得长痛不如短痛,直接将博客的评论迁移到了 [Gitalk](https://github.com/gitalk/gitalk),最开始选择了使用 Gitment 作为评论系统,但是由于其开发者很久没有维护、代码七个月也没有更新,所以就选择了有更多人维护的 Gitalk 作为目前博客的评论系统。 + +无论是 Gitalk 还是 Gitment 都只能手动初始化所有文章的评论或者一个一个点开界面,作者觉得这件事情非常麻烦,所以手动抓了一下 Gitalk 和 Gitment 在初始化评论时发出的网络请求后写了一个用于自动化初始评论的脚本。 + +## 获得权限 + +在使用该脚本之前首先要在 GitHub 创建一个新的 [Personal access tokens](https://github.com/settings/tokens),选择 `Generate new token` 后,在当前的页面中为 Token 添加所有 Repo 的权限: + +![personal-access-token](images/initialize-comments/personal-access-token.png) + +在这里创建之后,点击界面最下的面 `Generate token` 按钮获得一个新的 token: + +![new-token](images/initialize-comments/new-token.png) + +> 作者已经把这个 token 删掉了,不要想着用这个 token 就能获得到作者 GitHub 的权限。 + +## 脚本 + +作者在抓取了 Gitalk 和 Gitment 的 API 请求发现,这两个评论服务是**通过 GitHub 提供的 API 创建含有相应标签的 issue**,所以我们应该也可以直接使用 GitHub 的 API 创建所有博客文章对应的 issue,这与通过评论插件创建 issue 是完全一样的,在创建之后无论是 Gitalk 还是 Gitment 都可以通过对应的标签直接在仓库中找到对应的 issue 了。 + +本文中提供的自动化脚本使用的是 Ruby 代码,请确定自己的机器上已经安装了 Ruby,并且使用如下的命令安装脚本所需要的所有依赖: + +```ruby +$ sudo gem install faraday activesupport sitemap-parser +``` + +### 使用 sitemap 文件 + +如果我们使用的博客服务是 Jekyll,那么就可以通过 [jekyll-sitemap](https://github.com/jekyll/jekyll-sitemap) 插件为博客创建对应的 sitemap 文件,例如:https://draveness.me/sitemap.xml。 + +有 sitemap 文件之后就非常好办了,在任意目录下创建 `comment.rb` 文件后,将下面的代码粘贴到文件中: + +```ruby +username = "draveness" # GitHub 用户名 +new_token = "xxxxxxx" # GitHub Token +repo_name = "github-comments-repo" # 存放 issues +sitemap_url = "https://draveness.me/sitemap.xml" # sitemap +kind = "Gitalk" # "Gitalk" or "gitment" + +require 'open-uri' +require 'faraday' +require 'active_support' +require 'active_support/core_ext' +require 'sitemap-parser' + +sitemap = SitemapParser.new sitemap_url +urls = sitemap.to_a + +conn = Faraday.new(:url => "https://api.github.com/repos/#{username}/#{repo_name}/issues") do |conn| + conn.basic_auth(username, token) + conn.adapter Faraday.default_adapter +end + +urls.each_with_index do |url, index| + title = open(url).read.scan(/(.*?)<\/title>/).first.first.force_encoding('UTF-8') + response = conn.post do |req| + req.body = { body: url, labels: [kind, url], title: title }.to_json + end + puts response.body + sleep 15 if index % 20 == 0 +end +``` + +在这里有 5 个配置项,分别是 GitHub 用户名、在上一步获得的 Token、存放 issues 的仓库、sitemap 的地址以及最后你在博客中使用了哪个评论插件,不同的插件拥有标签,可以选择 `"Gitalk"` 或者 `"gitment"`,对于其他评论的插件应该如何设置,作者就并不清楚了。 + +> 需要注意的是,在使用上述的代码为博客创建 issue 时,会为博客中 sitemap 包含的**全部界面创建对应的 issue**,其中包括例如首页、标签界面等,这对于作者来说不是太大的问题,但是对这个问题敏感的读者可以使用下一小节中的代码。 + +在配置完成后就可以在命令行中的当前目录下输入以下命令: + +```ruby +$ ruby comment.rb +``` + +然后当前脚本就会运行并初始化所有的评论了。 + +### 无 sitemap 或自定义 + +如果博客中不包含任何的 sitemap 文件,或者想要手动选择想要初始化的一些文章其实也是可以的,可以使用简化的代码**批量初始化指定博客**的评论: + +```ruby +username = "draveness" # GitHub 用户名 +new_token = "xxxxxxx" # GitHub Token +repo_name = "github-comments-repo" # 存放 issues +kind = "Gitalk" # "Gitalk" or "gitment" +urls = ["xxxxx"] + +require 'open-uri' +require 'faraday' +require 'active_support' +require 'active_support/core_ext' + +conn = Faraday.new(:url => "https://api.github.com/repos/#{username}/#{repo_name}/issues") do |conn| + conn.basic_auth(username, token) + conn.adapter Faraday.default_adapter +end + +urls.each_with_index do |url, index| + title = open(url).read.scan(/<title>(.*?)<\/title>/).first.first.force_encoding('UTF-8') + response = conn.post do |req| + req.body = { body: url, labels: [kind, url], title: title }.to_json + end + puts response.body + sleep 15 if index % 20 == 0 +end +``` + +在这里就需要**手动填入需要初始化文章的数组**了,当然如果你有 sitemap 文件,其实可以在 irb 中运行以下的代码得到全部的文章数组,再手动从其中剔除不想要创建评论的页面: + +```ruby +$ irb +2.3.3 :001 > require 'sitemap-parser' + => true +2.3.3 :002 > sitemap_url = "https://draveness.me/sitemap.xml" + => "https://draveness.me/sitemap.xml" +2.3.3 :003 > SitemapParser.new(sitemap_url).to_a + => ["https://draveness.me/prolog-ji-chu-1", "https://draveness.me/prolog-pi-pei-2", "https://draveness.me/prolog-di-gui-3", ..., "https://draveness.me/dynamo"] + ``` + +当我们将上述结果中不想要创建评论的文章删除之后,将结果填到 `urls` 这个临时变量中,运行下面的命令就可以了。 + +```ruby +$ ruby comment.rb +``` + +## 其他 + +由于 GitHub 会脚本的请求会做一定的限制,所以在连续请求接口,批量创建 issues 的过程中可能会出现创建失败的情况,你可以通过命令中打印的结果看到,不过在脚本中已经在每 20 次创建时休眠 15 秒,所以应该也不会遇到这个问题。 + +另外,GitHub 中 issue 的可以创建但是并不能删除,所以在配置时请一定检查好所有的配置项是否正确,否则会批量创建一些无用的 issue 虽然没有什么影响,但是看起来非常头疼。 + +## 总结 + +手动初始化每一篇文章的评论确实是非常痛苦的,放弃 Disqus 确实也考虑了比较久的事件,Disqus 中也确实有一些有价值的评论,但是本着长痛不如短痛的原则,还是选择迁移到 Gitalk,当然作者也希望 Gitalk 官方能够提供更好地使用体验。 + diff --git "a/contents/CocoaPods/CocoaPods \351\203\275\345\201\232\344\272\206\344\273\200\344\271\210\357\274\237.md" "b/contents/CocoaPods/CocoaPods \351\203\275\345\201\232\344\272\206\344\273\200\344\271\210\357\274\237.md" new file mode 100644 index 0000000..714ae26 --- /dev/null +++ "b/contents/CocoaPods/CocoaPods \351\203\275\345\201\232\344\272\206\344\273\200\344\271\210\357\274\237.md" @@ -0,0 +1,667 @@ +# CocoaPods 都做了什么? + +稍有 iOS 开发经验的人应该都是用过 CocoaPods,而对于 CI、CD 有了解的同学也都知道 Fastlane。而这两个在 iOS 开发中非常便捷的第三方库都是使用 Ruby 来编写的,这是为什么? + +![](images/cocoapods-image.jpg) + +先抛开这个话题不谈,我们来看一下 CocoaPods 和 Fastlane 是如何使用的,首先是 CocoaPods,在每一个使用 CocoaPods 的工程中都有一个 Podfile: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' + +target 'Demo' do + pod 'Mantle', '~> 1.5.1' + pod 'SDWebImage', '~> 3.7.1' + pod 'BlocksKit', '~> 2.2.5' + pod 'SSKeychain', '~> 1.2.3' + pod 'UMengAnalytics', '~> 3.1.8' + pod 'UMengFeedback', '~> 1.4.2' + pod 'Masonry', '~> 0.5.3' + pod 'AFNetworking', '~> 2.4.1' + pod 'Aspects', '~> 1.4.1' +end +``` + +这是一个使用 Podfile 定义依赖的一个例子,不过 Podfile 对约束的描述其实是这样的: + +```ruby +source('https://github.com/CocoaPods/Specs.git') + +target('Demo') do + pod('Mantle', '~> 1.5.1') + ... +end +``` + +> Ruby 代码在调用方法时可以省略括号。 + +Podfile 中对于约束的描述,其实都可以看作是对代码简写,上面的代码在解析时可以当做 Ruby 代码来执行。 + +Fastlane 中的代码 Fastfile 也是类似的: + +```ruby +lane :beta do + increment_build_number + cocoapods + match + testflight + sh "./customScript.sh" + slack +end +``` + +使用描述性的”代码“编写脚本,如果没有接触或者使用过 Ruby 的人很难相信上面的这些文本是代码的。 + +## Ruby 概述 + +在介绍 CocoaPods 的实现之前,我们需要对 Ruby 的一些特性有一个简单的了解,在向身边的朋友“传教”的时候,我往往都会用优雅这个词来形容这门语言~~(手动微笑)~~。 + +除了优雅之外,Ruby 的语法具有强大的表现力,并且其使用非常灵活,能快速实现我们的需求,这里简单介绍一下 Ruby 中的一些特性。 + +### 一切皆对象 + +在许多语言,比如 Java 中,数字与其他的基本类型都不是对象,而在 Ruby 中所有的元素,包括基本类型都是对象,同时也不存在运算符的概念,所谓的 `1 + 1`,其实只是 `1.+(1)` 的语法糖而已。 + +得益于一切皆对象的概念,在 Ruby 中,你可以向任意的对象发送 `methods` 消息,在运行时自省,所以笔者在每次忘记方法时,都会直接用 `methods` 来“查文档”: + +```ruby +2.3.1 :003 > 1.methods + => [:%, :&, :*, :+, :-, :/, :<, :>, :^, :|, :~, :-@, :**, :<=>, :<<, :>>, :<=, :>=, :==, :===, :[], :inspect, :size, :succ, :to_s, :to_f, :div, :divmod, :fdiv, :modulo, :abs, :magnitude, :zero?, :odd?, :even?, :bit_length, :to_int, :to_i, :next, :upto, :chr, :ord, :integer?, :floor, :ceil, :round, :truncate, :downto, :times, :pred, :to_r, :numerator, :denominator, :rationalize, :gcd, :lcm, :gcdlcm, :+@, :eql?, :singleton_method_added, :coerce, :i, :remainder, :real?, :nonzero?, :step, :positive?, :negative?, :quo, :arg, :rectangular, :rect, :polar, :real, :imaginary, :imag, :abs2, :angle, :phase, :conjugate, :conj, :to_c, :between?, :instance_of?, :public_send, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :private_methods, :kind_of?, :instance_variables, :tap, :is_a?, :extend, :define_singleton_method, :to_enum, :enum_for, :=~, :!~, :respond_to?, :freeze, :display, :send, :object_id, :method, :public_method, :singleton_method, :nil?, :hash, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :trust, :untrusted?, :methods, :protected_methods, :frozen?, :public_methods, :singleton_methods, :!, :!=, :__send__, :equal?, :instance_eval, :instance_exec, :__id__] +``` + +比如在这里向对象 `1` 调用 `methods` 就会返回它能响应的所有方法。 + +一切皆对象不仅减少了语言中类型的不一致,消灭了基本数据类型与对象之间的边界;这一概念同时也简化了语言中的组成元素,这样 Ruby 中只有对象和方法,这两个概念,这也降低了我们理解这门语言的复杂度: + ++ 使用对象存储状态 ++ 对象之间通过方法通信 + +### block + +Ruby 对函数式编程范式的支持是通过 block,这里的 block 和 Objective-C 中的 block 有些不同。 + +首先 Ruby 中的 block 也是一种对象,所有的 Block 都是 Proc 类的实例,也就是所有的 block 都是 first-class 的,可以作为参数传递,返回。 + +```ruby +def twice(&proc) + 2.times { proc.call() } if proc +end + +def twice + 2.times { yield } if block_given? +end +``` + +> `yield` 会调用外部传入的 block,`block_given?` 用于判断当前方法是否传入了 `block`。 + +在这个方法调用时,是这样的: + +```ruby +twice do + puts "Hello" +end +``` + +### eval + +最后一个需要介绍的特性就是 `eval` 了,早在几十年前的 Lisp 语言就有了 `eval` 这个方法,这个方法会将字符串当做代码来执行,也就是说 `eval` 模糊了代码与数据之间的边界。 + +```ruby +> eval "1 + 2 * 3" + => 7 +``` + +有了 `eval` 方法,我们就获得了更加强大的动态能力,在运行时,使用字符串来改变控制流程,执行代码;而不需要去手动解析输入、生成语法树。 + +### 手动解析 Podfile + +在我们对 Ruby 这门语言有了一个简单的了解之后,就可以开始写一个简易的解析 Podfile 的脚本了。 + +在这里,我们以一个非常简单的 Podfile 为例,使用 Ruby 脚本解析 Podfile 中指定的依赖: + +```ruby +source 'http://source.git' +platform :ios, '8.0' + +target 'Demo' do + pod 'AFNetworking' + pod 'SDWebImage' + pod 'Masonry' + pod "Typeset" + pod 'BlocksKit' + pod 'Mantle' + pod 'IQKeyboardManager' + pod 'IQDropDownTextField' +end +``` + +因为这里的 `source`、`platform`、`target` 以及 `pod` 都是方法,所以在这里我们需要构建一个包含上述方法的上下文: + +```ruby +# eval_pod.rb +$hash_value = {} + +def source(url) +end + +def target(target) +end + +def platform(platform, version) +end + +def pod(pod) +end +``` + +使用一个全局变量 `hash_value` 存储 Podfile 中指定的依赖,并且构建了一个 Podfile 解析脚本的骨架;我们先不去完善这些方法的实现细节,先尝试一下读取 Podfile 中的内容并执行会不会有什么问题。 + +在 `eval_pod.rb` 文件的最下面加入这几行代码: + +```ruby +content = File.read './Podfile' +eval content +p $hash_value +``` + +这里读取了 Podfile 文件中的内容,并把其中的内容当做字符串执行,最后打印 `hash_value` 的值。 + +```shell +$ ruby eval_pod.rb +``` + +运行这段 Ruby 代码虽然并没有什么输出,但是并没有报出任何的错误,接下来我们就可以完善这些方法了: + +```ruby +def source(url) + $hash_value['source'] = url +end + +def target(target) + targets = $hash_value['targets'] + targets = [] if targets == nil + targets << target + $hash_value['targets'] = targets + yield if block_given? +end + +def platform(platform, version) +end + +def pod(pod) + pods = $hash_value['pods'] + pods = [] if pods == nil + pods << pod + $hash_value['pods'] = pods +end +``` + +在添加了这些方法的实现之后,再次运行脚本就会得到 Podfile 中的依赖信息了,不过这里的实现非常简单的,很多情况都没有处理: + +```shell +$ ruby eval_pod.rb +{"source"=>"http://source.git", "targets"=>["Demo"], "pods"=>["AFNetworking", "SDWebImage", "Masonry", "Typeset", "BlocksKit", "Mantle", "IQKeyboardManager", "IQDropDownTextField"]} +``` + +CocoaPods 中对于 Podfile 的解析与这里的实现其实差不多,接下来就进入了 CocoaPods 的实现部分了。 + +## CocoaPods 的实现 + +在上面简单介绍了 Ruby 的一些语法以及如何解析 Podfile 之后,我们开始深入了解一下 CocoaPods 是如何管理 iOS 项目的依赖,也就是 `pod install` 到底做了些什么。 + +### Pod install 的过程 + +`pod install` 这个命令到底做了什么?首先,在 CocoaPods 中,所有的命令都会由 `Command` 类派发到将对应的类,而真正执行 `pod install` 的类就是 `Install`: + +```ruby +module Pod + class Command + class Install < Command + def run + verify_podfile_exists! + installer = installer_for_config + installer.repo_update = repo_update?(:default => false) + installer.update = false + installer.install! + end + end + end +end +``` + +这里面会从配置类的实例 `config` 中获取一个 `Installer` 的实例,然后执行 `install!` 方法,这里的 `installer` 有一个 `update` 属性,而这也就是 `pod install` 和 `update` 之间最大的区别,**其中后者会无视已有的 Podfile.lock 文件,重新对依赖进行分析**: + +```ruby +module Pod + class Command + class Update < Command + def run + ... + + installer = installer_for_config + installer.repo_update = repo_update?(:default => true) + installer.update = true + installer.install! + end + end + end +end +``` + +### Podfile 的解析 + +Podfile 中依赖的解析其实是与我们在手动解析 Podfile 章节所介绍的差不多,整个过程主要都是由 **CocoaPods-Core** 这个模块来完成的,而这个过程早在 `installer_for_config` 中就已经开始了: + +```ruby +def installer_for_config + Installer.new(config.sandbox, config.podfile, config.lockfile) +end +``` + +这个方法会从 `config.podfile` 中取出一个 `Podfile` 类的实例: + +```ruby +def podfile + @podfile ||= Podfile.from_file(podfile_path) if podfile_path +end +``` + +类方法 `Podfile.from_file` 就定义在 CocoaPods-Core 这个库中,用于分析 Podfile 中定义的依赖,这个方法会根据 Podfile 不同的类型选择不同的调用路径: + +```ruby +Podfile.from_file +`-- Podfile.from_ruby + |-- File.open + `-- eval +``` + +`from_ruby` 类方法就会像我们在前面做的解析 Podfile 的方法一样,从文件中读取数据,然后使用 `eval` 直接将文件中的内容当做 Ruby 代码来执行。 + +```ruby +def self.from_ruby(path, contents = nil) + contents ||= File.open(path, 'r:utf-8', &:read) + + podfile = Podfile.new(path) do + begin + eval(contents, nil, path.to_s) + rescue Exception => e + message = "Invalid `#{path.basename}` file: #{e.message}" + raise DSLError.new(message, path, e, contents) + end + end + podfile +end +``` + +在 Podfile 这个类的顶部,我们使用 Ruby 的 `Mixin` 的语法来混入 Podfile 中代码执行所需要的上下文: + +```ruby +include Pod::Podfile::DSL +``` + +Podfile 中的所有你见到的方法都是定义在 `DSL` 这个模块下面的: + +```ruby +module Pod + class Podfile + module DSL + def pod(name = nil, *requirements) end + def target(name, options = nil) end + def platform(name, target = nil) end + def inhibit_all_warnings! end + def use_frameworks!(flag = true) end + def source(source) end + ... + end + end +end +``` + +这里定义了很多 Podfile 中使用的方法,当使用 `eval` 执行文件中的代码时,就会执行这个模块里的方法,在这里简单看一下其中几个方法的实现,比如说 `source` 方法: + +```ruby +def source(source) + hash_sources = get_hash_value('sources') || [] + hash_sources << source + set_hash_value('sources', hash_sources.uniq) +end +``` + +该方法会将新的 `source` 加入已有的源数组中,然后更新原有的 `sources` 对应的值。 + +稍微复杂一些的是 `target` 方法: + +```ruby +def target(name, options = nil) + if options + raise Informative, "Unsupported options `#{options}` for " \ + "target `#{name}`." + end + + parent = current_target_definition + definition = TargetDefinition.new(name, parent) + self.current_target_definition = definition + yield if block_given? +ensure + self.current_target_definition = parent +end +``` + +这个方法会创建一个 `TargetDefinition` 类的实例,然后将当前环境系的 `target_definition` 设置成这个刚刚创建的实例。这样,之后使用 `pod` 定义的依赖都会填充到当前的 `TargetDefinition` 中: + +```ruby +def pod(name = nil, *requirements) + unless name + raise StandardError, 'A dependency requires a name.' + end + + current_target_definition.store_pod(name, *requirements) +end +``` + +当 `pod` 方法被调用时,会执行 `store_pod` 将依赖存储到当前 `target` 中的 `dependencies` 数组中: + +```ruby +def store_pod(name, *requirements) + return if parse_subspecs(name, requirements) + parse_inhibit_warnings(name, requirements) + parse_configuration_whitelist(name, requirements) + + if requirements && !requirements.empty? + pod = { name => requirements } + else + pod = name + end + + get_hash_value('dependencies', []) << pod + nil +end +``` + +总结一下,CocoaPods 对 Podfile 的解析与我们在前面做的手动解析 Podfile 的原理差不多,构建一个包含一些方法的上下文,然后直接执行 `eval` 方法将文件的内容当做代码来执行,这样只要 Podfile 中的数据是符合规范的,那么解析 Podfile 就是非常简单容易的。 + +### 安装依赖的过程 + +Podfile 被解析后的内容会被转化成一个 `Podfile` 类的实例,而 `Installer` 的实例方法 `install!` 就会使用这些信息安装当前工程的依赖,而整个安装依赖的过程大约有四个部分: + ++ 解析 Podfile 中的依赖 ++ 下载依赖 ++ 创建 `Pods.xcodeproj` 工程 ++ 集成 workspace + +```ruby +def install! + resolve_dependencies + download_dependencies + generate_pods_project + integrate_user_project +end +``` + +在上面的 `install` 方法调用的 `resolve_dependencies` 会创建一个 `Analyzer` 类的实例,在这个方法中,你会看到一些非常熟悉的字符串: + +```ruby +def resolve_dependencies + analyzer = create_analyzer + + plugin_sources = run_source_provider_hooks + analyzer.sources.insert(0, *plugin_sources) + + UI.section 'Updating local specs repositories' do + analyzer.update_repositories + end if repo_update? + + UI.section 'Analyzing dependencies' do + analyze(analyzer) + validate_build_configurations + clean_sandbox + end +end +``` + +在使用 CocoaPods 中经常出现的 `Updating local specs repositories` 以及 `Analyzing dependencies` 就是从这里输出到终端的,该方法不仅负责对本地所有 PodSpec 文件的更新,还会对当前 `Podfile` 中的依赖进行分析: + +```ruby +def analyze(analyzer = create_analyzer) + analyzer.update = update + @analysis_result = analyzer.analyze + @aggregate_targets = analyzer.result.targets +end +``` + +`analyzer.analyze` 方法最终会调用 `Resolver` 的实例方法 `resolve`: + +```ruby +def resolve + dependencies = podfile.target_definition_list.flat_map do |target| + target.dependencies.each do |dep| + @platforms_by_dependency[dep].push(target.platform).uniq! if target.platform + end + end + @activated = Molinillo::Resolver.new(self, self).resolve(dependencies, locked_dependencies) + specs_by_target +rescue Molinillo::ResolverError => e + handle_resolver_error(e) +end +``` + +这里的 `Molinillo::Resolver` 就是用于解决依赖关系的类。 + +#### 解决依赖关系(Resolve Dependencies) + +CocoaPods 为了解决 Podfile 中声明的依赖关系,使用了一个叫做 [Milinillo](https://github.com/CocoaPods/Molinillo/blob/master/ARCHITECTURE.md) 的依赖关系解决算法;但是,笔者在 Google 上并没有找到与这个算法相关的其他信息,推测是 CocoaPods 为了解决 iOS 中的依赖关系创造的算法。 + +Milinillo 算法的核心是 [回溯(Backtracking)](https://en.wikipedia.org/wiki/Backtracking) 以及 [向前检查(forward check)](https://en.wikipedia.org/wiki/Look-ahead_(backtracking)),整个过程会追踪栈中的两个状态(依赖和可能性)。 + +在这里并不想陷入对这个算法执行过程的分析之中,如果有兴趣可以看一下仓库中的 [ARCHITECTURE.md](https://github.com/CocoaPods/Molinillo/blob/master/ARCHITECTURE.md) 文件,其中比较详细的解释了 Milinillo 算法的工作原理,并对其功能执行过程有一个比较详细的介绍。 + +`Molinillo::Resolver` 方法会返回一个依赖图,其内容大概是这样的: + +```ruby +Molinillo::DependencyGraph:[ + Molinillo::DependencyGraph::Vertex:AFNetworking(#<Pod::Specification name="AFNetworking">), + Molinillo::DependencyGraph::Vertex:SDWebImage(#<Pod::Specification name="SDWebImage">), + Molinillo::DependencyGraph::Vertex:Masonry(#<Pod::Specification name="Masonry">), + Molinillo::DependencyGraph::Vertex:Typeset(#<Pod::Specification name="Typeset">), + Molinillo::DependencyGraph::Vertex:CCTabBarController(#<Pod::Specification name="CCTabBarController">), + Molinillo::DependencyGraph::Vertex:BlocksKit(#<Pod::Specification name="BlocksKit">), + Molinillo::DependencyGraph::Vertex:Mantle(#<Pod::Specification name="Mantle">), + ... +] +``` + +这个依赖图是由一个结点数组组成的,在 CocoaPods 拿到了这个依赖图之后,会在 `specs_by_target` 中按照 `Target` 将所有的 `Specification` 分组: + +```ruby +{ + #<Pod::Podfile::TargetDefinition label=Pods>=>[], + #<Pod::Podfile::TargetDefinition label=Pods-Demo>=>[ + #<Pod::Specification name="AFNetworking">, + #<Pod::Specification name="AFNetworking/NSURLSession">, + #<Pod::Specification name="AFNetworking/Reachability">, + #<Pod::Specification name="AFNetworking/Security">, + #<Pod::Specification name="AFNetworking/Serialization">, + #<Pod::Specification name="AFNetworking/UIKit">, + #<Pod::Specification name="BlocksKit/Core">, + #<Pod::Specification name="BlocksKit/DynamicDelegate">, + #<Pod::Specification name="BlocksKit/MessageUI">, + #<Pod::Specification name="BlocksKit/UIKit">, + #<Pod::Specification name="CCTabBarController">, + #<Pod::Specification name="CategoryCluster">, + ... + ] +} +``` + +而这些 `Specification` 就包含了当前工程依赖的所有第三方框架,其中包含了名字、版本、源等信息,用于依赖的下载。 + +#### 下载依赖 + +在依赖关系解决返回了一系列 `Specification` 对象之后,就到了 Pod install 的第二部分,下载依赖: + +```ruby +def install_pod_sources + @installed_specs = [] + pods_to_install = sandbox_state.added | sandbox_state.changed + title_options = { :verbose_prefix => '-> '.green } + root_specs.sort_by(&:name).each do |spec| + if pods_to_install.include?(spec.name) + if sandbox_state.changed.include?(spec.name) && sandbox.manifest + previous = sandbox.manifest.version(spec.name) + title = "Installing #{spec.name} #{spec.version} (was #{previous})" + else + title = "Installing #{spec}" + end + UI.titled_section(title.green, title_options) do + install_source_of_pod(spec.name) + end + else + UI.titled_section("Using #{spec}", title_options) do + create_pod_installer(spec.name) + end + end + end +end +``` + +在这个方法中你会看到更多熟悉的提示,CocoaPods 会使用沙盒(sandbox)存储已有依赖的数据,在更新现有的依赖时,会根据依赖的不同状态显示出不同的提示信息: + +```ruby +-> Using AFNetworking (3.1.0) + +-> Using AKPickerView (0.2.7) + +-> Using BlocksKit (2.2.5) was (2.2.4) + +-> Installing MBProgressHUD (1.0.0) +... +``` + +虽然这里的提示会有三种,但是 CocoaPods 只会根据不同的状态分别调用两种方法: + ++ `install_source_of_pod` ++ `create_pod_installer` + +`create_pod_installer` 方法只会创建一个 `PodSourceInstaller` 的实例,然后加入 `pod_installers` 数组中,因为依赖的版本没有改变,所以不需要重新下载,而另一个方法的 `install_source_of_pod` 的调用栈非常庞大: + +```ruby +installer.install_source_of_pod +|-- create_pod_installer +| `-- PodSourceInstaller.new +`-- podSourceInstaller.install! + `-- download_source + `-- Downloader.download + `-- Downloader.download_request + `-- Downloader.download_source + |-- Downloader.for_target + | |-- Downloader.class_for_options + | `-- Git/HTTP/Mercurial/Subversion.new + |-- Git/HTTP/Mercurial/Subversion.download + `-- Git/HTTP/Mercurial/Subversion.download! + `-- Git.clone +``` + +在调用栈的末端 `Downloader.download_source` 中执行了另一个 CocoaPods 组件 **CocoaPods-Download** 中的方法: + +```ruby +def self.download_source(target, params) + FileUtils.rm_rf(target) + downloader = Downloader.for_target(target, params) + downloader.download + target.mkpath + + if downloader.options_specific? + params + else + downloader.checkout_options + end +end +``` + +方法中调用的 `for_target` 根据不同的源会创建一个下载器,因为依赖可能通过不同的协议或者方式进行下载,比如说 Git/HTTP/SVN 等等,组件 CocoaPods-Downloader 就会根据 Podfile 中依赖的参数选项使用不同的方法下载依赖。 + +大部分的依赖都会被下载到 `~/Library/Caches/CocoaPods/Pods/Release/` 这个文件夹中,然后从这个这里复制到项目工程目录下的 `./Pods` 中,这也就完成了整个 CocoaPods 的下载流程。 + +#### 生成 Pods.xcodeproj + +CocoaPods 通过组件 CocoaPods-Downloader 已经成功将所有的依赖下载到了当前工程中,这里会将所有的依赖打包到 `Pods.xcodeproj` 中: + +```ruby +def generate_pods_project(generator = create_generator) + UI.section 'Generating Pods project' do + generator.generate! + @pods_project = generator.project + run_podfile_post_install_hooks + generator.write + generator.share_development_pod_schemes + write_lockfiles + end +end +``` + +`generate_pods_project` 中会执行 `PodsProjectGenerator` 的实例方法 `generate!`: + +```ruby +def generate! + prepare + install_file_references + install_libraries + set_target_dependencies +end +``` + +这个方法做了几件小事: + ++ 生成 `Pods.xcodeproj` 工程 ++ 将依赖中的文件加入工程 ++ 将依赖中的 Library 加入工程 ++ 设置目标依赖(Target Dependencies) + +这几件事情都离不开 CocoaPods 的另外一个组件 Xcodeproj,这是一个可以操作一个 Xcode 工程中的 Group 以及文件的组件,我们都知道对 Xcode 工程的修改大多数情况下都是对一个名叫 `project.pbxproj` 的文件进行修改,而 Xcodeproj 这个组件就是 CocoaPods 团队开发的用于操作这个文件的第三方库。 + +#### 生成 workspace + +最后的这一部分与生成 `Pods.xcodeproj` 的过程有一些相似,这里使用的类是 `UserProjectIntegrator`,调用方法 `integrate!` 时,就会开始集成工程所需要的 Target: + +```ruby +def integrate! + create_workspace + integrate_user_targets + warn_about_xcconfig_overrides + save_projects +end +``` + +对于这一部分的代码,也不是很想展开来细谈,简单介绍一下这里的代码都做了什么,首先会通过 `Xcodeproj::Workspace` 创建一个 workspace,之后会获取所有要集成的 Target 实例,调用它们的 `integrate!` 方法: + +```ruby +def integrate! + UI.section(integration_message) do + XCConfigIntegrator.integrate(target, native_targets) + + add_pods_library + add_embed_frameworks_script_phase + remove_embed_frameworks_script_phase_from_embedded_targets + add_copy_resources_script_phase + add_check_manifest_lock_script_phase + end +end +``` + +方法将每一个 Target 加入到了工程,使用 Xcodeproj 修改 `Copy Resource Script Phrase` 等设置,保存 `project.pbxproj`,整个 Pod install 的过程就结束了。 + +## 总结 + +最后想说的是 pod install 和 pod update 区别还是比较大的,每次在执行 pod install 或者 update 时最后都会生成或者修改 `Podfile.lock` 文件,其中前者并不会修改 `Podfile.lock` 中**显示指定**的版本,而后者会会无视该文件的内容,尝试将所有的 pod 更新到最新版。 + +CocoaPods 工程的代码虽然非常多,不过代码的逻辑非常清晰,整个管理并下载依赖的过程非常符合直觉以及逻辑。 + +## 其它 + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/cocoapods + + diff --git a/contents/CocoaPods/images/cocoapods-image.jpg b/contents/CocoaPods/images/cocoapods-image.jpg new file mode 100644 index 0000000..df4a1af Binary files /dev/null and b/contents/CocoaPods/images/cocoapods-image.jpg differ diff --git a/contents/CocoaPods/images/cocoapods.png b/contents/CocoaPods/images/cocoapods.png new file mode 100644 index 0000000..0b69f9b Binary files /dev/null and b/contents/CocoaPods/images/cocoapods.png differ diff --git a/contents/CocoaPods/images/compiler.png b/contents/CocoaPods/images/compiler.png new file mode 100644 index 0000000..e5c9d00 Binary files /dev/null and b/contents/CocoaPods/images/compiler.png differ diff --git a/contents/CocoaPods/images/css-sass.jpg b/contents/CocoaPods/images/css-sass.jpg new file mode 100644 index 0000000..f88d21e Binary files /dev/null and b/contents/CocoaPods/images/css-sass.jpg differ diff --git a/contents/CocoaPods/images/dom-tree.png b/contents/CocoaPods/images/dom-tree.png new file mode 100644 index 0000000..c8d219a Binary files /dev/null and b/contents/CocoaPods/images/dom-tree.png differ diff --git a/contents/CocoaPods/images/magic.jpg b/contents/CocoaPods/images/magic.jpg new file mode 100644 index 0000000..8401db4 Binary files /dev/null and b/contents/CocoaPods/images/magic.jpg differ diff --git a/contents/CocoaPods/images/rails.jpeg b/contents/CocoaPods/images/rails.jpeg new file mode 100644 index 0000000..45387fa Binary files /dev/null and b/contents/CocoaPods/images/rails.jpeg differ diff --git a/contents/CocoaPods/images/regex.jpg b/contents/CocoaPods/images/regex.jpg new file mode 100644 index 0000000..f35d410 Binary files /dev/null and b/contents/CocoaPods/images/regex.jpg differ diff --git a/contents/CocoaPods/images/silver-bullet.jpg b/contents/CocoaPods/images/silver-bullet.jpg new file mode 100644 index 0000000..3632da2 Binary files /dev/null and b/contents/CocoaPods/images/silver-bullet.jpg differ diff --git "a/contents/CocoaPods/\350\260\210\350\260\210 DSL \344\273\245\345\217\212 DSL \347\232\204\345\272\224\347\224\250\357\274\210\344\273\245 CocoaPods \344\270\272\344\276\213\357\274\211.md" "b/contents/CocoaPods/\350\260\210\350\260\210 DSL \344\273\245\345\217\212 DSL \347\232\204\345\272\224\347\224\250\357\274\210\344\273\245 CocoaPods \344\270\272\344\276\213\357\274\211.md" new file mode 100644 index 0000000..158dca5 --- /dev/null +++ "b/contents/CocoaPods/\350\260\210\350\260\210 DSL \344\273\245\345\217\212 DSL \347\232\204\345\272\224\347\224\250\357\274\210\344\273\245 CocoaPods \344\270\272\344\276\213\357\274\211.md" @@ -0,0 +1,435 @@ +![](images/magic.jpg) + +# 谈谈 DSL 以及 DSL 的应用(以 CocoaPods 为例) + +> 因为 DSL 以及 DSL 的界定本身就是一个比较模糊的概念,所以难免有与他人观点意见相左的地方,如果有不同的意见,我们可以具体讨论。 + +最近在公司做了一次有关 DSL 在 iOS 开发中的应用的分享,这篇文章会简单介绍这次分享的内容。 + +这次文章的题目虽然是谈谈 DSL 以及 DSL 的应用,不过文章中主要侧重点仍然是 DSL,会简单介绍 DSL 在 iOS 开发中(CocoaPods)是如何应用的。 + +## 没有银弹? + +1987 年,IBM 大型电脑之父 Fred Brooks 发表了一篇关于软件工程中的论文 [No Silver Bullet—Essence and Accidents of Software Engineering](No Silver Bullet—Essence and Accidents of Software Engineering) 文中主要围绕这么一个观点:没有任何一种技术或者方法能使软件工程的生产力在十年之内提高十倍。 + +> There is no single development, in either technology or management technique, which by itself promises even one order-of-magnitude improvement within a decade in productivity, in reliability, in simplicity. + +时至今日,我们暂且不谈银弹在软件工程中是否存在(~~这句话在老板或者项目经理要求加快项目进度时,还是十分好用的~~),作为一个开发者也不是很关心这种抽象的理论,我们更关心的是开发效率能否有实质的提升。 + +![silver-bullet](images/silver-bullet.jpg) + +而今天要介绍的 DSL 就可以真正的提升生产力,减少不必要的工作,在一些领域帮助我们更快的实现需求。 + +## DSL 是什么? + +笔者是在两年以前,在大一的一次分享上听到 DSL 这个词的,但是当时并没有对这个名词有多深的理解与认识,听过也就忘记了,但是最近做的一些开源项目让我重新想起了 DSL,也是这次分享题目的由来。 + +DSL 其实是 Domain Specific Language 的缩写,中文翻译为*领域特定语言*(下简称 DSL);而与 DSL 相对的就是 GPL,这里的 GPL 并不是我们知道的开源许可证,而是 General Purpose Language 的简称,即*通用编程语言*,也就是我们非常熟悉的 Objective-C、Java、Python 以及 C 语言等等。 + +[Wikipedia](https://en.wikipedia.org/wiki/Domain-specific_language) 对于 DSL 的定义还是比较简单的: + +> A specialized computer language designed for a specific task. +> +> 为了解决某一类任务而专门设计的计算机语言。 + +与 GPL 相对,DSL 与传统意义上的通用编程语言 C、Python 以及 Haskell 完全不同。通用的计算机编程语言是可以用来编写任意计算机程序的,并且能表达任何的**可被计算**的逻辑,同时也是 [图灵完备](https://en.wikipedia.org/wiki/Turing_completeness) 的。 + +> 这一小节中的 DSL 指外部 DSL,下一节中会介绍 [内部 DSL/嵌入式 DSL](#embedded-dsl嵌入式-dsl) + +但是在里所说的 DSL 并不是图灵完备的,它们的**表达能力有限**,只是在特定领域解决特定任务的。 + +> A computer programming language of limited expressiveness focused on a particular domain. + +另一个世界级软件开发大师 Martin Fowler 对于领域特定语言的定义在笔者看来就更加具体了,**DSL 通过在表达能力上做的妥协换取在某一领域内的高效**。 + +而有限的表达能力就成为了 GPL 和 DSL 之间的一条界限。 + +### 几个栗子 + +最常见的 DSL 包括 Regex 以及 HTML & CSS,在这里会对这几个例子进行简单介绍 + ++ Regex + + 正则表达式仅仅指定了字符串的 pattern,其引擎就会根据 pattern 判断当前字符串跟正则表达式是否匹配。 + ![regex](images/regex.jpg) ++ SQL + + SQL 语句在使用时也并没有真正的执行,我们输入的 SQL 语句最终还要交给数据库来进行处理,数据库会从 SQL 语句中**读取**有用的信息,然后从数据库中返回使用者期望的结果。 ++ HTML & CSS + + HTML 和 CSS 只是对 Web 界面的结构语义和样式进行描述,虽然它们在构建网站时非常重要,但是它们并非是一种编程语言,正相反,我们可以认为 HTML 和 CSS 是在 Web 中的领域特定语言。 + +### Features + +上面的几个🌰明显的缩小了通用编程语言的概念,但是它们确实在自己领域表现地非常出色,因为这些 DSL 就是根据某一个特定领域的特点塑造的;而通用编程语言相比领域特定语言,在设计时是为了解决更加抽象的问题,而关注点并不只是在某一个领域。 + +上面的几个例子有着一些共同的特点: + ++ 没有计算和执行的概念; ++ 其本身并不需要直接表示计算; ++ 使用时只需要声明规则、事实以及某些元素之间的层级和关系; + +虽然了解了 DSL 以及 DSL 的一些特性,但是,到目前为止,我们对于如何构建一个 DSL 仍然不是很清楚。 + +### 构建 DSL + +DSL 的构建与编程语言其实比较类似,想想我们在重新实现编程语言时,需要做那些事情;实现编程语言的过程可以简化为定义语法与语义,然后实现编译器或者解释器的过程,而 DSL 的实现与它也非常类似,我们也需要对 DSL 进行语法与语义上的设计。 + +![compile](images/compiler.png) + +总结下来,实现 DSL 总共有这么两个需要完成的工作: + +1. 设计语法和语义,定义 DSL 中的元素是什么样的,元素代表什么意思 +2. 实现 parser,对 DSL 解析,最终通过解释器来执行 + +以 HTML 为例,HTML 中所有的元素都是包含在尖括号 `<>` 中的,尖括号中不同的元素代表了不同的标签,而这些标签会被浏览器**解析**成 DOM 树,再经过一系列的过程调用 Native 的图形 API 进行绘制。 + +![dom-tree](images/dom-tree.png) + +再比如,我们使用下面这种方式对一个模型进行定义,实现一个 ORM 领域的 DSL: + +```ruby +define :article do + attr :name + attr :content + attr :upvotes, :int + + has_many :comments +end +``` + +在上面的 DSL 中,使用 `define` 来定义一个新的模型,使用 `attr` 来为模型添加属性,使用 `has_many` 建立数据模型中的一对多关系;我们可以使用 DSL 对这段“字符串”进行解析,然后交给代码生成器来生成代码。 + +```swift +public struct Article { + public var title: String + public var content: String + public var createdAt: Date + + public init(title: String, content: String, createdAt: Date) + + static public func new(title: String, content: String, createdAt: Date) -> Article + static public func create(title: String, content: String, createdAt: Date) -> Article? + ... +} +``` + +这里创建的 DSL 中的元素数量非常少,只有 `define` `attr` 以及 `has_many` 等几个关键字,但是通过这几个关键字就可以完成在模型层需要表达的绝大部分语义。 + +### 设计原则和妥协 + +DSL 最大的设计原则就是**简单**,通过简化语言中的元素,降低使用者的负担;无论是 Regex、SQL 还是 HTML 以及 CSS,其说明文档往往只有几页,非常易于学习和掌握。但是,由此带来的问题就是,DSL 中缺乏抽象的概念,比如:模块化、变量以及方法等。 + +> 抽象的概念并不是某个领域所关注的问题,就像 Regex 并不需要有模块、变量以及方法等概念。 + +由于抽象能力的缺乏,在我们的项目规模变得越来越大时,DSL 往往满足不了开发者的需求;我们仍然需要编程语言中的模块化等概念对 DSL 进行补充,以此解决 DSL 并不是真正编程语言的问题。 + +![css-sass](images/css-sass.jpg) + +在当今的 Web 前端项目中,我们在开发大规模项目时往往不会直接手写 CSS 文件,而是会使用 Sass 或者 Less 为 CSS 带来更强大的抽象能力,比如嵌套规则,变量,混合以及继承等特性。 + +```css +nav { + ul { + margin: 0; + padding: 0; + list-style: none; + } + + li { display: inline-block; } + + a { + display: block; + padding: 6px 12px; + text-decoration: none; + } +} +``` + +也就是说,在使用 DSL 的项目规模逐渐变大时,开发者会通过增加抽象能力的方式,对已有的 DSL 进行拓展;但是这种扩展往往需要重新实现通用编程语言中的特性,所以一般情况下都是比较复杂的。 + +## Embedded DSL(嵌入式 DSL) + +那么,是否有一种其它的方法为 DSL 快速添加抽象能力呢?而这也就是这一小节的主题,嵌入式 DSL。 + +在上一节讲到的 DSL 其实可以被称为外部 DSL;而这里即将谈到的嵌入式 DSL 也有一个别名,内部 DSL。 + +这两者最大的区别就是,内部 DSL 的实现往往是嵌入一些编程语言的,比如 iOS 的依赖管理组件 CocoaPods 和 Android 的主流编译工具 Gradle,前者的实现是基于 Ruby 语言的一些特性,而后者基于 Groovy。 + +![cocoapods](images/cocoapods.png) + +CocoaPods 以及其它的嵌入式 DSL 使用了宿主语言(host language)的抽象能力,并且省去了实现复杂语法分析器(Parser)的过程,并不需要重新实现模块、变量等特性。 + +嵌入式 DSL 的产生其实模糊了框架和 DSL 的边界,不过这两者看起来也没有什么比较明显的区别;不过,DSL 一般会使用宿主语言的特性进行创造,在设计 DSL 时,也不会考虑宿主语言中有哪些 API 以及方法,而框架一般都是对语言中的 API 进行组合和再包装。 + +> 我们没有必要争论哪些是框架,哪些是 DSL,因为这些争论并没有什么意义。 + +### Rails 和 Embedded DSL + +最出名也最成功的嵌入式 DSL 应该就是 Ruby on Rails 了,虽然对于 Rails 是否是 DSL 有争议,不过 Rails 为 Web 应用的创建提供大量的内置的支撑,使我们在开发 Web 应用时变得非常容易。 + +![rails](images/rails.jpeg) + +## Ruby、 DSL 和 iOS + +> 为了保证这篇文章的完整性,这一小节中有的一些内容都出自上一篇文章 [CocoaPods 都做了什么?](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/CocoaPods/CocoaPods%20都做了什么?.md)。 + +笔者同时作为 iOS 和 Rails 开发者接触了非常多的 DSL,而在 iOS 开发中最常见的 DSL 就是 CocoaPods 了,而这里我们以 CocoaPods 为例,介绍如何使用 Ruby 创造一个嵌入式 DSL。 + +### Why Ruby? + +看到这里有人可能会问了,为什么使用 Ruby 创造嵌入式 DSL,而不是使用 C、Java、Python 等等语言呢,这里大概有四个原因: + ++ 一切皆对象的特性减少了语言中的元素,不存在基本类型、操作符; ++ 向 Ruby 方法中传入代码块非常方便; ++ 作为解释执行的语言,eval 模糊了数据和代码的边界; ++ 不对代码的格式进行约束,同时一些约定减少了代码中的噪音。 + +#### 一切皆对象 + +在许多语言,比如 Java 中,数字与其他的基本类型都不是对象,而在 Ruby 中所有的元素,包括基本类型都是对象,同时也不存在运算符的概念,所谓的 `1 + 1`,其实只是 `1.+(1)` 的语法糖而已。 + +得益于一切皆对象的概念,在 Ruby 中,你可以向任意的对象发送 `methods` 消息,在运行时自省,所以笔者在每次忘记方法时,都会直接用 `methods` 来“查阅文档”: + +```ruby +2.3.1 :003 > 1.methods + => [:%, :&, :*, :+, :-, :/, :<, :>, :^, :|, :~, :-@, :**, :<=>, :<<, :>>, :<=, :>=, :==, :===, :[], :inspect, :size, :succ, :to_s, :to_f, :div, :divmod, :fdiv, :modulo, ...] +``` + +比如在这里向对象 `1` 调用 `methods` 就会返回它能响应的所有方法。 + +一切皆对象不仅减少了语言中类型的数量,消灭了基本数据类型与对象之间的边界;这一概念同时也简化了组成语言的元素,这样 Ruby 中只有对象和方法,这两个概念,极大降低了这门语言的复杂度: + ++ 使用对象存储状态 ++ 对象之间通过方法通信 + +#### block + +Ruby 对函数式编程范式的支持是通过 block,这里的 block 和 Objective-C 中的 block 有些不同。 + +首先 Ruby 中的 block 也是一种对象,即 `Proc` 类的实例,也就是所有的 block 都是 first-class 的,可以作为参数传递,返回。 + +下面的代码演示了两种向 Ruby 方法中传入代码块的方式: + +```ruby +def twice(&proc) + 2.times { proc.call() } if proc +end + +def twice + 2.times { yield } if block_given? +end +``` + +`yield` 会调用外部传入的 block,`block_given?` 用于判断当前方法是否传入了 `block`。 + +```ruby +twice do + puts "Hello" +end + +twice { puts "hello" } +``` + +向 `twice` 方法传入 block 也非常简单,使用 `do`、`end` 或者 `{`、`}` 就可以向任何的 Ruby 方法中传入代码块。 + +#### eval + +早在几十年前的 Lisp 语言就有了 `eval` 这个方法,这个方法会将字符串当做代码来执行,也就是说 `eval` 模糊了代码与数据之间的边界。 + +```ruby +> eval "1 + 2 * 3" + => 7 +``` + +有了 `eval` 方法,我们就获得了更加强大的动态能力,在运行时,使用字符串来改变控制流程,执行代码并可以直接利用当前语言的解释器;而不需要去手动解析字符串然后执行代码。 + +#### 格式和约定 + +编写 Ruby 脚本时并不需要像 Python 一样对代码的格式有着严格的规定,没有对空行、Tab 的要求,完全可以想怎么写就怎么写,这样极大的增加了 DSL 设计的可能性。 + +同时,在一般情况下,Ruby 在方法调用时并不需要添加括号: + +```ruby +puts "Wello World!" +puts("Hello World!") +``` + +这样减少了 DSL 中的噪音,能够帮助我们更加关心语法以及语义上的设计,降低了使用者出错的可能性。 + +最后,Ruby 中存在一种特殊的数据格式 `Symbol`: + +```ruby +> :symbol.to_s + => "symbol" +> "symbol".to_sym + => :symbol +``` + +Symbol 可以通过 Ruby 中内置的方法与字符串之间无缝转换。那么作为一种字符串的替代品,它的使用也能够降低使用者出错的成本并提升使用体验,我们并不需要去写两边加上引号的字符串,只需要以 `:` 开头就能创建一个 Symbol 对象。 + +### Podfile 是什么 + +对 Ruby 有了一些了解之后,我们就可以再看一下使用 CocoaPods 的工程中的 Podfile 到底是什么了: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' + +target 'Demo' do + pod 'Mantle', '~> 1.5.1' + ... +end +``` + +> 如果不了解 iOS 开发后者没有使用过 CocoaPods,笔者在这里简单介绍一下这个文件中的一些信息。 +> +> `source` 可以看作是存储依赖元信息(包括依赖的对应的 GitHub 地址)的源地址; +> +> `target` 表示需要添加依赖的工程的名字; +> +> `pod` 表示依赖,`Mantle` 为依赖的框架,后面是版本号。 + +上面是一个使用 Podfile 定义依赖的一个例子,不过 Podfile 对约束的描述其实是这样的: + +```ruby +source('https://github.com/CocoaPods/Specs.git') + +target('Demo') do + pod('Mantle', '~> 1.5.1') + ... +end +``` + +Podfile 中对于约束的描述,其实都可以看作是代码的简写,在解析时会当做 Ruby 代码来执行。 + +### 简单搞个 Embedded DSL + +使用 Ruby 实现嵌入式 DSL 一般需要三个步骤,这里以 CocoaPods 为例进行简单介绍: + ++ 创建一个 Podfile 中“代码”执行的上下文,也就是一些方法; ++ 读取 Podfile 中的内容到脚本中; ++ 使用 `eval` 在上下文中执行 Podfile 中的“代码”; + +#### 原理 + +CocoaPods 对于 DSL 的实现基本上就是我们创建一个 DSL 的过程,定义一系列必要的方法,比如 `source`、`pod` 等等,创造一个执行的上下文;然后去读存储 DSL 的文件,并且使用 `eval` 执行。 + +**信息的传递一般都是通过参数**来进行的,比如: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +``` + +`source` 方法的参数就是依赖元信息 `Specs` 的 Git 地址,在 `eval` 执行时就会被读取到 CocoaPods 中,然后进行分析。 + +#### 实现 + +下面是一个非常常见的 Podfile 内容: + +```ruby +source 'http://source.git' +platform :ios, '8.0' + +target 'Demo' do + pod 'AFNetworking' + pod 'SDWebImage' + pod 'Masonry' + pod "Typeset" + pod 'BlocksKit' + pod 'Mantle' + pod 'IQKeyboardManager' + pod 'IQDropDownTextField' +end +``` + +因为这里的 `source`、`platform`、`target` 以及 `pod` 都是方法,所以在这里我们需要构建一个包含上述方法的上下文: + +```ruby +# eval_pod.rb +$hash_value = {} + +def source(url) +end + +def target(target) +end + +def platform(platform, version) +end + +def pod(pod) +end +``` + +使用一个全局变量 `hash_value` 存储 Podfile 中指定的依赖,并且构建了一个 Podfile 解析脚本的骨架;我们先不去完善这些方法的实现细节,先尝试一下读取 Podfile 中的内容并执行 `eval` 看看会不会有问题。 + +在 `eval_pod.rb` 文件的最下面加入这几行代码: + +```ruby +content = File.read './Podfile' +eval content +p $hash_value +``` + +这里读取了 Podfile 文件中的内容,并把其中的内容当做字符串执行,最后打印 `hash_value` 的值。 + +```shell +$ ruby eval_pod.rb +``` + +运行这段 Ruby 代码虽然并没有什么输出,但是并没有报出任何的错误,接下来我们就可以完善这些方法了: + +```ruby +def source(url) + $hash_value['source'] = url +end + +def target(target) + targets = $hash_value['targets'] + targets = [] if targets == nil + targets << target + $hash_value['targets'] = targets + yield if block_given? +end + +def platform(platform, version) +end + +def pod(pod) + pods = $hash_value['pods'] + pods = [] if pods == nil + pods << pod + $hash_value['pods'] = pods +end +``` + +在添加了这些方法的实现之后,再次运行脚本就会得到 Podfile 中的依赖信息了,不过这里的实现非常简单的,很多情况都没有处理: + +```shell +$ ruby eval_pod.rb +{"source"=>"http://source.git", "targets"=>["Demo"], "pods"=>["AFNetworking", "SDWebImage", "Masonry", "Typeset", "BlocksKit", "Mantle", "IQKeyboardManager", "IQDropDownTextField"]} +``` + +不过使用 Ruby 构建一个嵌入式 DSL 的过程大概就是这样,使用语言内建的特性来进行创作,创造出一个在使用时看起来并不像代码的 DSL。 + +## 写在后面 + +在最后,笔者想说的是,当我们在某一个领域经常需要解决重复性问题时,可以考虑实现一个 DSL 专门用来解决这些类似的问题。 + +而使用嵌入式 DSL 来解决这些问题是一个非常好的办法,我们并不需要重新实现解释器,也可以利用宿主语言的抽象能力。 + +同时,在嵌入式 DSL 扩展了 DSL 的范畴之后,不要纠结于某些东西到底是框架还是领域特定语言,这些都不重要,重要的是,在遇到了某些问题时,我们能否跳出来,使用文中介绍的方法减轻我们的工作量。 + +## Reference + ++ [No Silver Bullet—Essence and Accidents of Software Engineering](No Silver Bullet—Essence and Accidents of Software Engineering) ++ [Domain-specific language](https://en.wikipedia.org/wiki/Domain-specific_language) ++ [DomainSpecificLanguage](http://martinfowler.com/bliki/DomainSpecificLanguage.html) ++ [How browsers work](http://taligarsiel.com/Projects/howbrowserswork1.htm) + +## 其它 + +> GitHub Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/dsl + + diff --git "a/DKNightVersion/\346\210\220\347\206\237\347\232\204\345\244\234\351\227\264\346\250\241\345\274\217\350\247\243\345\206\263\346\226\271\346\241\210.md" "b/contents/DKNightVersion/\346\210\220\347\206\237\347\232\204\345\244\234\351\227\264\346\250\241\345\274\217\350\247\243\345\206\263\346\226\271\346\241\210.md" similarity index 100% rename from "DKNightVersion/\346\210\220\347\206\237\347\232\204\345\244\234\351\227\264\346\250\241\345\274\217\350\247\243\345\206\263\346\226\271\346\241\210.md" rename to "contents/DKNightVersion/\346\210\220\347\206\237\347\232\204\345\244\234\351\227\264\346\250\241\345\274\217\350\247\243\345\206\263\346\226\271\346\241\210.md" diff --git a/contents/Database/concurrency-control.md b/contents/Database/concurrency-control.md new file mode 100644 index 0000000..9ab9a6f --- /dev/null +++ b/contents/Database/concurrency-control.md @@ -0,0 +1,201 @@ +# 浅谈数据库并发控制 - 锁和 MVCC + +在学习几年编程之后,你会发现所有的问题都没有简单、快捷的解决方案,很多问题都需要权衡和妥协,而本文介绍的就是数据库在并发性能和可串行化之间做的权衡和妥协 - 并发控制机制。 + +![tradeoff-between-performance-and-serializability](images/concurrency-control/tradeoff-between-performance-and-serializability.png) + +如果数据库中的所有事务都是串行执行的,那么它非常容易成为整个应用的性能瓶颈,虽然说没法水平扩展的节点在最后都会成为瓶颈,但是串行执行事务的数据库会加速这一过程;而并发(Concurrency)使一切事情的发生都有了可能,它能够解决一定的性能问题,但是它会带来更多诡异的错误。 + +引入了并发事务之后,如果不对事务的执行进行控制就会出现各种各样的问题,你可能没有享受到并发带来的性能提升就已经被各种奇怪的问题折磨的欲仙欲死了。 + +## 概述 + +如何控制并发是数据库领域中非常重要的问题之一,不过到今天为止事务并发的控制已经有了很多成熟的解决方案,而这些方案的原理就是这篇文章想要介绍的内容,文章中会介绍最为常见的三种并发控制机制: + +![pessimistic-optimistic-multiversion-conccurency-control](images/concurrency-control/pessimistic-optimistic-multiversion-conccurency-control.png) + +分别是悲观并发控制、乐观并发控制和多版本并发控制,其中悲观并发控制其实是最常见的并发控制机制,也就是锁;而乐观并发控制其实也有另一个名字:乐观锁,乐观锁其实并不是一种真实存在的锁,我们会在文章后面的部分中具体介绍;最后就是多版本并发控制(MVCC)了,与前两者对立的命名不同,MVCC 可以与前两者中的任意一种机制结合使用,以提高数据库的读性能。 + +既然这篇文章介绍了不同的并发控制机制,那么一定会涉及到不同事务的并发,我们会通过示意图的方式分析各种机制是如何工作的。 + +## 悲观并发控制 + +控制不同的事务对同一份数据的获取是保证数据库的一致性的最根本方法,如果我们能够让事务在同一时间对同一资源有着独占的能力,那么就可以保证操作同一资源的不同事务不会相互影响。 + +![pessimistic-conccurency-control](images/concurrency-control/pessimistic-conccurency-control.png) + +最简单的、应用最广的方法就是使用锁来解决,当事务需要对资源进行操作时需要先获得资源对应的锁,保证其他事务不会访问该资源后,在对资源进行各种操作;在悲观并发控制中,数据库程序对于数据被修改持悲观的态度,在数据处理的过程中都会被锁定,以此来解决竞争的问题。 + +### 读写锁 + +为了最大化数据库事务的并发能力,数据库中的锁被设计为两种模式,分别是共享锁和互斥锁。当一个事务获得共享锁之后,它只可以进行读操作,所以共享锁也叫读锁;而当一个事务获得一行数据的互斥锁时,就可以对该行数据进行读和写操作,所以互斥锁也叫写锁。 + +![Shared-Exclusive-Lock](images/concurrency-control/Shared-Exclusive-Lock.png) + +共享锁和互斥锁除了限制事务能够执行的读写操作之外,它们之间还有『共享』和『互斥』的关系,也就是多个事务可以同时获得某一行数据的共享锁,但是互斥锁与共享锁和其他的互斥锁并不兼容,我们可以很自然地理解这么设计的原因:多个事务同时写入同一数据难免会发生各种诡异的问题。 + +![lock-and-wait](images/concurrency-control/lock-and-wait.png) + +如果当前事务没有办法获取该行数据对应的锁时就会陷入等待的状态,直到其他事务将当前数据对应的锁释放才可以获得锁并执行相应的操作。 + +### 两阶段锁协议 + +两阶段锁协议(2PL)是一种能够保证事务可串行化的协议,它将事务的获取锁和释放锁划分成了增长(Growing)和缩减(Shrinking)两个不同的阶段。 + +![growing-to-shrinking](images/concurrency-control/growing-to-shrinking.png) + +在增长阶段,一个事务可以获得锁但是不能释放锁;而在缩减阶段事务只可以释放锁,并不能获得新的锁,如果只看 2PL 的定义,那么到这里就已经介绍完了,但是它还有两个变种: + +1. **Strict 2PL**:事务持有的**互斥**锁必须在提交后再释放; +2. **Rigorous 2PL**:事务持有的**所有**锁必须在提交后释放; + +![two-phase-locking](images/concurrency-control/two-phase-locking.png) + +虽然锁的使用能够为我们解决不同事务之间由于并发执行造成的问题,但是两阶段锁的使用却引入了另一个严重的问题,死锁;不同的事务等待对方已经锁定的资源就会造成死锁,我们在这里举一个简单的例子: + +![deadlock](images/concurrency-control/deadlock.png) + +两个事务在刚开始时分别获取了 draven 和 beacon 资源上面的锁,然后再请求对方已经获得的锁时就会发生死锁,双方都没有办法等到锁的释放,如果没有死锁的处理机制就会无限等待下去,两个事务都没有办法完成。 + +### 死锁的处理 + +死锁在多线程编程中是经常遇到的事情,一旦涉及多个线程对资源进行争夺就需要考虑当前的几个线程或者事务是否会造成死锁;解决死锁大体来看有两种办法,一种是从源头杜绝死锁的产生和出现,另一种是允许系统进入死锁的状态,但是在系统出现死锁时能够及时发现并且进行恢复。 + +![deadlock-handling](images/concurrency-control/deadlock-handling.png) + +#### 预防死锁 + +有两种方式可以帮助我们预防死锁的出现,一种是保证事务之间的等待不会出现环,也就是事务之间的等待图应该是一张**有向无环图**,没有循环等待的情况或者保证一个事务中想要获得的所有资源都在事务开始时以原子的方式被锁定,所有的资源要么被锁定要么都不被锁定。 + +但是这种方式有两个问题,在事务一开始时很难判断哪些资源是需要锁定的,同时因为一些很晚才会用到的数据被提前锁定,数据的利用率与事务的并发率也非常的低。一种解决的办法就是按照一定的顺序为所有的数据行加锁,同时与 2PL 协议结合,在加锁阶段保证所有的数据行都是从小到大依次进行加锁的,不过这种方式依然需要事务提前知道将要加锁的数据集。 + +另一种预防死锁的方法就是使用抢占加事务回滚的方式预防死锁,当事务开始执行时会先获得一个时间戳,数据库程序会根据事务的时间戳决定事务应该等待还是回滚,在这时也有两种机制供我们选择,一种是 wait-die 机制: + +![deadlock-prevention-wait-die](images/concurrency-control/deadlock-prevention-wait-die.png) + +当执行事务的时间戳小于另一事务时,即事务 A 先于 B 开始,那么它就会等待另一个事务释放对应资源的锁,否则就会保持当前的时间戳并回滚。 + +另一种机制叫做 wound-wait,这是一种抢占的解决方案,它和 wait-die 机制的结果完全相反,当前事务如果先于另一事务执行并请求了另一事务的资源,那么另一事务会立刻回滚,将资源让给先执行的事务,否则就会等待其他事务释放资源: + +![deadlock-prevention-wound-wait](images/concurrency-control/deadlock-prevention-wound-wait.png) + +两种方法都会造成不必要的事务回滚,由此会带来一定的性能损失,更简单的解决死锁的方式就是使用超时时间,但是超时时间的设定是需要仔细考虑的,否则会造成耗时较长的事务无法正常执行,或者无法及时发现需要解决的死锁,所以它的使用还是有一定的局限性。 + +### 死锁检测和恢复 + +如果数据库程序无法通过协议从原理上保证死锁不会发生,那么就需要在死锁发生时及时检测到并从死锁状态恢复到正常状态保证数据库程序可以正常工作。在使用检测和恢复的方式解决死锁时,数据库程序需要维护数据和事务之间的引用信息,同时也需要提供一个用于判断当前数据库是否进入死锁状态的算法,最后需要在死锁发生时提供合适的策略及时恢复。 + +在上一节中我们其实提到死锁的检测可以通过一个有向的等待图来进行判断,如果一个事务依赖于另一个事务正在处理的数据,那么当前事务就会等待另一个事务的结束,这也就是整个等待图中的一条边: + +![deadlock-wait-for-graph](images/concurrency-control/deadlock-wait-for-graph.png) + +如上图所示,如果在这个有向图中出现了环,就说明当前数据库进入了死锁的状态 `TransB -> TransE -> TransF -> TransD -> TransB`,在这时就需要死锁恢复机制接入了。 + +如何从死锁中恢复其实非常简单,最常见的解决办法就是选择整个环中一个事务进行回滚,以打破整个等待图中的环,在整个恢复的过程中有三个事情需要考虑: + +![deadlock-recovery](images/concurrency-control/deadlock-recovery.png) + +每次出现死锁时其实都会有多个事务被波及,而选择其中哪一个任务进行回滚是必须要做的事情,在选择牺牲品(Victim)时的黄金原则就是**最小化代价**,所以我们需要综合考虑事务已经计算的时间、使用的数据行以及涉及的事务等因素;当我们选择了牺牲品之后就可以开始回滚了,回滚其实有两种选择一种是全部回滚,另一种是部分回滚,部分回滚会回滚到事务之前的一个检查点上,如果没有检查点那自然没有办法进行部分回滚。 + +> 在死锁恢复的过程中,其实还可能出现某些任务在多次死锁时都被选择成为牺牲品,一直都不会成功执行,造成饥饿(Starvation),我们需要保证事务会在有穷的时间内执行,所以要在选择牺牲品时将时间戳加入考虑的范围。 + +### 锁的粒度 + +到目前为止我们都没有对不同粒度的锁进行讨论,一直以来我们都讨论的都是数据行锁,但是在有些时候我们希望将多个节点看做一个数据单元,使用锁直接将这个数据单元、表甚至数据库锁定起来。这个目标的实现需要我们在数据库中定义不同粒度的锁: + +![granularity-hierarchy](images/concurrency-control/granularity-hierarchy.png) + +当我们拥有了不同粒度的锁之后,如果某个事务想要锁定整个数据库或者整张表时只需要简单的锁住对应的节点就会在当前节点加上显示(explicit)锁,在所有的子节点上加隐式(implicit)锁;虽然这种不同粒度的锁能够解决父节点被加锁时,子节点不能被加锁的问题,但是我们没有办法在子节点被加锁时,立刻确定父节点不能被加锁。 + +在这时我们就需要引入*意向锁*来解决这个问题了,当需要给子节点加锁时,先给所有的父节点加对应的意向锁,意向锁之间是完全不会互斥的,只是用来帮助父节点快速判断是否可以对该节点进行加锁: + +![lock-type-compatibility-matrix](images/concurrency-control/lock-type-compatibility-matrix.png) + +这里是一张引入了两种意向锁,*意向共享锁*和*意向互斥锁*之后所有的锁之间的兼容关系;到这里,我们通过不同粒度的锁和意向锁加快了数据库的吞吐量。 + +## 乐观并发控制 + +除了悲观并发控制机制 - 锁之外,我们其实还有其他的并发控制机制,*乐观并发控制*(Optimistic Concurrency Control)。乐观并发控制也叫乐观锁,但是它并不是真正的锁,很多人都会误以为乐观锁是一种真正的锁,然而它只是一种并发控制的思想。 + +![pessimistic-and-optimisti](images/concurrency-control/pessimistic-and-optimistic.png) + +在这一节中,我们将会先介绍*基于时间戳的并发控制机制*,然后在这个协议的基础上进行扩展,实现乐观的并发控制机制。 + +### 基于时间戳的协议 + +锁协议按照不同事务对同一数据项请求的时间依次执行,因为后面执行的事务想要获取的数据已将被前面的事务加锁,只能等待锁的释放,所以基于锁的协议执行事务的顺序与获得锁的顺序有关。在这里想要介绍的基于时间戳的协议能够在事务执行之前先决定事务的执行顺序。 + +每一个事务都会具有一个全局唯一的时间戳,它即可以使用系统的时钟时间,也可以使用计数器,只要能够保证所有的时间戳都是唯一并且是随时间递增的就可以。 + +![timestamp-ordering-protocol](images/concurrency-control/timestamp-ordering-protocol.png) + +基于时间戳的协议能够保证事务并行执行的顺序与事务按照时间戳串行执行的效果完全相同;每一个数据项都有两个时间戳,读时间戳和写时间戳,分别代表了当前成功执行对应操作的事务的时间戳。 + +该协议能够保证所有冲突的读写操作都能按照时间戳的大小串行执行,在执行对应的操作时不需要关注其他的事务只需要关心数据项对应时间戳的值就可以了: + +![timestamp-ordering-protocol-process](images/concurrency-control/timestamp-ordering-protocol-process.png) + +无论是读操作还是写操作都会从左到右依次比较读写时间戳的值,如果小于当前值就会直接被拒绝然后回滚,数据库系统会给回滚的事务添加一个新的时间戳并重新执行这个事务。 + +### 基于验证的协议 + +*乐观并发控制*其实本质上就是基于验证的协议,因为在多数的应用中只读的事务占了绝大多数,事务之间因为写操作造成冲突的可能非常小,也就是说大多数的事务在不需要并发控制机制也能运行的非常好,也可以保证数据库的一致性;而并发控制机制其实向整个数据库系统添加了很多的开销,我们其实可以通过别的策略降低这部分开销。 + +而验证协议就是我们找到的解决办法,它根据事务的只读或者更新将所有事务的执行分为两到三个阶段: + +![validation-based-protoco](images/concurrency-control/validation-based-protocol.png) + +在读阶段,数据库会执行事务中的**全部读操作和写操作**,并将所有写后的值存入临时变量中,并不会真正更新数据库中的内容;在这时候会进入下一个阶段,数据库程序会检查当前的改动是否合法,也就是是否有其他事务在 RAED PHASE 期间更新了数据,如果通过测试那么直接就进入 WRITE PHASE 将所有存在临时变量中的改动全部写入数据库,没有通过测试的事务会直接被终止。 + +为了保证乐观并发控制能够正常运行,我们需要知道一个事务不同阶段的发生时间,包括事务开始时间、验证阶段的开始时间以及写阶段的结束时间;通过这三个时间戳,我们可以保证任意冲突的事务不会同时写入数据库,一旦由一个事务完成了验证阶段就会立即写入,其他读取了相同数据的事务就会回滚重新执行。 + +作为乐观的并发控制机制,它会假定所有的事务在最终都会通过验证阶段并且执行成功,而锁机制和基于时间戳排序的协议是悲观的,因为它们会在发生冲突时强制事务进行等待或者回滚,哪怕有不需要锁也能够保证事务之间不会冲突的可能。 + +## 多版本并发控制 + +到目前为止我们介绍的并发控制机制其实都是通过延迟或者终止相应的事务来解决事务之间的竞争条件(Race condition)来保证事务的可串行化;虽然前面的两种并发控制机制确实能够从根本上解决并发事务的可串行化的问题,但是在实际环境中数据库的事务大都是只读的,读请求是写请求的很多倍,如果写请求和读请求之前没有并发控制机制,那么最坏的情况也是读请求读到了已经写入的数据,这对很多应用完全是可以接受的。 + +![multiversion-scheme](images/concurrency-control/multiversion-scheme.png) + +在这种大前提下,数据库系统引入了另一种并发控制机制 - *多版本并发控制*(Multiversion Concurrency Control),每一个写操作都会创建一个新版本的数据,读操作会从有限多个版本的数据中挑选一个最合适的结果直接返回;在这时,读写操作之间的冲突就不再需要被关注,而管理和快速挑选数据的版本就成了 MVCC 需要解决的主要问题。 + +MVCC 并不是一个与乐观和悲观并发控制对立的东西,它能够与两者很好的结合以增加事务的并发量,在目前最流行的 SQL 数据库 MySQL 和 PostgreSQL 中都对 MVCC 进行了实现;但是由于它们分别实现了悲观锁和乐观锁,所以 MVCC 实现的方式也不同。 + +### MySQL 与 MVCC + +MySQL 中实现的多版本两阶段锁协议(Multiversion 2PL)将 MVCC 和 2PL 的优点结合了起来,每一个版本的数据行都具有一个唯一的时间戳,当有读事务请求时,数据库程序会直接从多个版本的数据项中具有最大时间戳的返回。 + +![multiversion-2pl-read](images/concurrency-control/multiversion-2pl-read.png) + +更新操作就稍微有些复杂了,事务会先读取最新版本的数据计算出数据更新后的结果,然后创建一个新版本的数据,新数据的时间戳是目前数据行的最大版本 `+1`: + +![multiversion-2pl-write](images/concurrency-control/multiversion-2pl-write.png) + +数据版本的删除也是根据时间戳来选择的,MySQL 会将版本最低的数据定时从数据库中清除以保证不会出现大量的遗留内容。 + +### PostgreSQL 与 MVCC + +与 MySQL 中使用悲观并发控制不同,PostgreSQL 中都是使用乐观并发控制的,这也就导致了 MVCC 在于乐观锁结合时的实现上有一些不同,最终实现的叫做多版本时间戳排序协议(Multiversion Timestamp Ordering),在这个协议中,所有的的事务在执行之前都会被分配一个唯一的时间戳,每一个数据项都有读写两个时间戳: + +![dataitem-with-timestamps](images/concurrency-control/dataitem-with-timestamps.png) + +当 PostgreSQL 的事务发出了一个读请求,数据库直接将最新版本的数据返回,不会被任何操作阻塞,而写操作在执行时,事务的时间戳一定要大或者等于数据行的读时间戳,否则就会被回滚。 + +这种 MVCC 的实现保证了读事务永远都不会失败并且不需要等待锁的释放,对于读请求远远多于写请求的应用程序,乐观锁加 MVCC 对数据库的性能有着非常大的提升;虽然这种协议能够针对一些实际情况做出一些明显的性能提升,但是也会导致两个问题,一个是每一次读操作都会更新读时间戳造成两次的磁盘写入,第二是事务之间的冲突是通过回滚解决的,所以如果冲突的可能性非常高或者回滚代价巨大,数据库的读写性能还不如使用传统的锁等待方式。 + +## 总结 + +数据库的并发控制机制到今天已经有了非常成熟、完善的解决方案,我们并不需要自己去设计一套新的协议来处理不同事务之间的冲突问题,从数据库的并发控制机制中学习到的相关知识,无论是锁还是乐观并发控制在其他的领域或者应用中都被广泛使用,所以了解、熟悉不同的并发控制机制的原理是很有必要的。 + +> 原文链接:[浅谈数据库并发控制 - 锁和 MVCC · 面向信仰编程](https://draveness.me/database-concurrency-control.html) +> Follow: [Draveness · GitHub](https://github.com/Draveness) + +## Reference + ++ [浅谈数据库并发控制 - 锁和 MVCC · 面向信仰编程](https://draveness.me/database-concurrency-control.html) ++ [PESSIMISTIC vs. OPTIMISTIC concurrency control](https://www.ibm.com/support/knowledgecenter/en/SSPK3V_7.0.0/com.ibm.swg.im.soliddb.sql.doc/doc/pessimistic.vs.optimistic.concurrency.control.html) ++ [PostgreSQL Concurrency with MVCC](https://devcenter.heroku.com/articles/postgresql-concurrency) ++ [Well-known Databases Use Different Approaches for MVCC](https://www.enterprisedb.com/well-known-databases-use-different-approaches-mvcc) ++ [Serializability](http://www.cs.unc.edu/~dewan/242/s01/notes/trans/node3.html) ++ [Race condition](https://en.wikipedia.org/wiki/Race_condition) + diff --git a/contents/Database/dynamo.md b/contents/Database/dynamo.md new file mode 100644 index 0000000..89cc929 --- /dev/null +++ b/contents/Database/dynamo.md @@ -0,0 +1,156 @@ +# 分布式键值存储 Dynamo 的实现原理 + +在最近的一周时间里,一直都在研究和阅读 Amazon 的一篇论文 [Dynamo: Amazon’s Highly Available Key-value Store](http://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf),论文中描述了 Amazon 的高可用分布式键值存储服务 Dynamo 的实现原理。 + +![dynamodb](images/dynamo/dynamodb.png) + +之前在阅读 Google 的 [Bigtable: A Distributed Storage System for Structured Data](https://static.googleusercontent.com/media/research.google.com/en//archive/bigtable-osdi06.pdf) 时写了一篇 [浅析 Bigtable 和 LevelDB 的实现](https://draveness.me/bigtable-leveldb) 文章分析了 Bigtable 的单机版 LevelDB 的实现原理;在研究 Dynamo 时,作者发现 Dynamo 虽然和 Bigtable 同为 NoSQL,但是它们的实现却有着很大的不同,最主要的原因来自不同的应用场景和不同的目的。 + +## Bigtable 和 Dynamo + +Bigtable 和 Dynamo 两者分别是 Google 和 Amazon 两大巨头给出的存储海量数据的解决方法,作为 NoSQL 两者都具有分布式、容错以及可扩展的几大特性。 + +![nosql-main-characteristics](images/dynamo/nosql-main-characteristics.png) + +虽然两者都是 NoSQL,并且有着相似的特性,但是它们在侧重的方向上有非常明显的不同,从两个数据库论文的标题中,我们就能看到 Amazon 的 Dynamo 追求的是高可用性并且提供的是类似 MongoDB 的 Key-value 文档存储,而 Bigtable 中描述的数据库却可以用于结构化的数据存储。 + +由于 Bigtable 和 Dynamo 都属于同一个类别 - NoSQL,所以它们经常会被放在一起进行对比,这篇文章不仅会介绍 Dynamo 的设计理念以及架构等问题,还会就其中的部分问题与 Bigtable 中相对应的概念进行对比,这样能够让我们更加清楚地了解不同的数据库对不同问题,因设计理念的差异做出的权衡。 + +## 架构 + +在数据库领域中尤其是分布式数据库,最重要的就是服务的架构,多数的分布式系统在设计时都会假设服务运行在廉价的节点上,并没有出众的性能和也不能提供稳定的服务,所以水平扩展和容错的能力是分布式数据库的标配;但是不同的分布式数据库选用了不同的架构来组织大量的节点。 + +很多的分布式服务例如 GFS 和 Bigtable 都使用了带有主节点的架构来维护整个系统中的元数据,包括节点的位置等信息,而 Dynamo 的实现不同于这些中心化的分布式服务,在 Dynamo 中所有的节点都有着完全相同的职责,会对外界提供同样的服务,所以在整个系统中并不会出现单点故障的问题。 + +![dynamo-architecture](images/dynamo/dynamo-architecture.png) + +去中心化的架构使得系统的水平扩展非常容易,节点可以在任何时候直接加入到整个 Dynamo 的集群中,并且只会造成集群中少量数据的迁移。 + +Bigtable 使用了中心化的架构,通过主节点来维护整个系统中全部的元数据信息,但是 Bigtable 本身其实并不会处理来自客户端的读写请求,所有请求都会由客户端直接和从节点通信,不过由于有了中心化的主节点,所以主节点一旦发生故障宕机就会造成服务的不可用,虽然 Bigtable 以及类似的服务通过其他方式解决这个问题,但是这个问题仍然是中心化的设计所造成的。 + +![centralized-architecture](images/dynamo/centralized-architecture.png) + +中心化或者去中心化并不是一个绝对好或者绝对坏的选择,选择中心化的解决方案能够降低系统实现的复杂度,而去中心化的方式能够避免单点故障,让系统能够更好更快地增加新的节点,提供优秀的水平扩展能力。 + +## 分片和复制 + +Dynamo 在设计之初就定下了**增量扩展**(Incremental Scalability)的核心需求,这也就需要一种能够在一组节点中动态分片的机制,Dynamo 的分片策略依赖于*一致性哈希*,通过这种策略 Dynamo 能够将负载合理的分配到不同的存储节点上。 + +所有的键在存储之前都会通过哈希函数得到一个唯一的值,哈希函数的输出被看做是一个固定长度的环,也就是其输出的最大值和最小值是『连接』到一起的: + +![partition-in-dynamo](images/dynamo/partition-in-dynamo.png) + +每一个节点都会被 Dynamo 在这个环中分配一个随机的位置,而这个节点会处理从哈希的输出在当前节点前的所有键;假设我们有一个键值对 `(draven, developer)`,`Hash(draven)` 的结果位于上图中的绿色区域,从环中的位置开始按照**顺时针**的顺序寻找,找到的以第一个节点 B 就会成为协调者(coordinator)负责处理当前的键值对,上图中的每一个节点都会负责与其颜色相同的部分。 + +由于 Dynamo 系统中的每一个节点在刚刚加入当前的集群时,会被分配一个随机的位置,所以由于算法的随机性可能会导致不同节点处理的范围有所不同,最终每一个节点的负载也并不相同;为了解决这个问题,Dynamo 使用了一致性哈希算法的变种,将同一个物理节点分配到环中的多个位置(标记),成为多个虚拟节点,但是在这种策略下,如果当前的 Dynamo 节点一天处理上百万的请求,那么新增节点为了不影响已有节点的性能,会在后台进行启动,整个过程大约会**消耗一整天**的时间,这其实是很难接受的,除此之外这种策略还会造成系统进行日常归档极其缓慢。 + +![equal-size-partition-in-dynamo](images/dynamo/equal-size-partition-in-dynamo.png) + +为了解决负载的不均衡的问题,除了上面使用虚拟节点的策略之外,Dynamo 论文中还提供了另外两种策略,其中性能相对较好的是将数据的哈希分成 Q 个大小相等的区域,S 个节点每一个处理 Q/S 个分区,当某一个节点因为故障或者其他原因需要退出集群时,会将它处理的数据分片随机分配给其它的节点,当有节点加入系统时,会从其它的节点中『接管』对应的数据分片。上图只是对这种策略下的分片情况简单展示,在真实环境中分片数 Q 的值远远大于节点数 S。 + +Dynamo 为了达到高可用性和持久性,防止由于节点宕机故障或者数据丢失,将同一份数据在协调者和随后的 `N-1` 个节点上备份了多次,N 是一个可以配置的值,在一般情况下都为 3。 + +![replication-in-dynamo](images/dynamo/replication-in-dynamo.png) + +也就是说,上图中黄色区域的值会存储在三个节点 A、B 和 C 中,绿色的区域会被 B、C、D 三个节点处理,从另一个角度来看,A 节点会处理范围在 `(C, A]` 之间的值,而 B 节点会处理从 `(D, B]` 区域内的值。 + +![replication-range-in-dynamo](images/dynamo/replication-range-in-dynamo.png) + +负责存储某一个特定键值对的节点列表叫做偏好列表(preference list),因为虚拟节点在环中会随机存在,为了保证出现节点故障时不会影响可用性和持久性,偏好列表中的全部节点必须都为**不同的物理节点**。 + +Bigtable 中对分片和复制的实现其实就与 Dynamo 中完全不同,这不仅是因为 Bigtable 的节点有主从之分,还因为 Bigtable 的设计理念与 Dynamo 完全不同。在 Bigtable 中,数据是按照键的顺序存储的,数据存储的单位都是 tablet,每一张表都由多个 tablet 组成,而每一个的 tablet 都有一个 tablet 服务器来处理,而 tablet 的位置都存储在 METADATA 表中。 + +![partition-in-bigtable](images/dynamo/partition-in-bigtable.png) + +在 Bigtable 中,所有的 tablet 都在 GFS 中以 SSTable 的格式存储起来,这些 SSTable 都被分成了固定大小的块在 chunkserver 上存储,而每一个块也都会在存储在多个 chunkserver 中。 + +## 读写请求的执行 + +Dynamo 集群中的任意节点都能够接受来自客户端的对于任意键的读写请求,所有的请求都通过 RPC 调用执行,客户端在选择节点时有两种不同的策略:一种是通过一个负载均衡器根据负载选择不同的节点,另一种是通过一个清楚当前集群分片的库直接请求相应的节点。 + +![node-selecting-strategies](images/dynamo/node-selecting-strategies.png) + +从上面我们就已经知道了处理读写请求的节点就叫做协调者(coordinator),前 N 个『健康』的节点会参与读写请求的处理;Dynamo 使用了 Quorum 一致性协议来保证系统中的一致性,协议中有两个可以配置的值:R 和 W,其中 R 是成功参与一个读请求的最小节点数,而 W 是成功参与写请求的最小节点数。 + +![dynamo-read-write-operation](images/dynamo/dynamo-read-write-operation.png) + +当 R = 2 时,所有的读请求必须等待两个节点成功返回对应键的结果,才认为当前的请求结束了,也就是说读请求的时间取决于返回最慢的节点,对于写请求来说也是完全相同的;当协调者接收到了来自客户端的写请求 `put()` 时,它会创建一个新的向量时钟(vector clock),然后将新版本的信息存储在本地,之后向偏好列表(preference list)中的前 `N-1` 个节点发送消息,直到其中的 `W-1` 个返回这次请求才成功结束,读请求 `get()` 与上述请求的唯一区别就是,如果协调者发现节点中的数据出现了冲突,就会对冲突尝试进行解决并将结果重新写回对应的节点。 + +## 冲突和向量时钟 + +Dynamo 与目前的绝大多数分布式系统一样都提供了**最终一致性**,最终一致性能够允许我们异步的更新集群中的节点,`put()` 请求可能会在所有的节点后更新前就返回对应的结果了,在这时随后的 `get()` 就可能获取到过期的数据。 + +![inconsistent-in-dynamo](images/dynamo/inconsistent-in-dynamo.png) + +如果在系统中出现了节点故障宕机,那么数据的更新可能在一段时间内都不会到达失效的节点,这也是在使用 Dynamo 或者使用相似原理的系统时会遇到的问题,Amazon 中的很多应用虽然都能够忍受这种数据层面可能发生的不一致性,但是有些对业务数据一致性非常高的应用在选择 Dynamo 时就需要好好考虑了。 + +因为 Dynamo 在工作的过程中不同的节点可能会发生数据不一致的问题,这种问题肯定是需要解决的,Dynamo 能够确保**一旦数据之间发生了冲突不会丢失**,但是可能会有**已被删除的数据重新出现**的问题。 + +在多数情况下,Dynamo 中的最新版本的数据都会取代之前的版本,系统在这时可以通过语法调解(syntactic reconcile)数据库中的正确版本。但是版本也可能会出现分支,在这时,Dynamo 就会返回所有它无法处理的数据版本,由客户端在多个版本的数据中选择或者创建(collapse)合适的版本返回给 Dynamo,其实这个过程比较像出现冲突的 `git merge` 操作,git 没有办法判断当前的哪个版本是合适的,所以只能由开发者对分支之间的冲突进行处理。 + +![version-evolution-in-dynamo](images/dynamo/version-evolution-in-dynamo.png) + +上图中的每一个对象的版本 Dx 中存储着一个或多个向量时钟 `[Sn, N]`,每次 Dynamo 对数据进行写入时都会更新向量时钟的版本,节点 Sx 第一次写入时向量时钟为 `[Sx, 1]`,第二次为 `[Sx, 2]`,在这时假设节点 Sy 和 Sz 都不知道 Sx 已经对节点进行写入了,它们接收到了来自其他客户端的请求,在本地也对同样键做出了写入并分别生成了不同的时钟 `[Sy, 1]` 和 `[Sz, 1]`,当客户端再次使用 `get()` 请求时就会发现数据出现了冲突,由于 Dynamo 无法根据向量时钟自动解决,所以它需要手动合并三个不同的数据版本。 + +论文中对 24 小时内的请求进行了统计,其中 99.94% 的请求仅会返回一个版本,0.00057% 的请求会返回两个版本,0.00047 的请求会返回三个版本,0.000009% 的请求会返回四个版本,虽然论文中说: + +> This shows that divergent versions are created rarely. + +但是作者仍然认为在海量的数据面前 99.94% 并不是一个特别高的百分比,处理分歧的数据版本仍然会带来额外的工作量和负担。虽然在这种情况下,数据库本身确实没有足够的信息来解决数据的不一致问题,也确实只能由客户端去解决冲突,但是这种将问题抛给上层去解决的方式并不友好,论文中也提到了 Amazon 中使用 Dynamo 的应用程序也都是能够适应并解决这些数据不一致的问题的,不过对于作者来说,仅仅这一个问题就成为不选择 Dynamo 的理由了。 + +## 节点的增删 + +因为在分布式系统中节点的失效是非常常见的事情,而节点也很少会因为某些原因永久失效,往往大部分节点会临时宕机然后快速重新加入系统;由于这些原因,Dynamo 选择使用了显式的机制向系统中添加和移除节点。 + +![ring-membership](images/dynamo/ring-membership.png) + +添加节点时可以使用命令行工具或者浏览器连接 Dynamo 中的任意节点后触发一个成员变动的事件,这个事件会从当前的环中移除或者向环中添加一个新的节点,当节点的信息发生改变时,该节点会通过 Gossip 协议通知它所能通知的最多的节点。 + +![gossip-protoco](images/dynamo/gossip-protocol.png) + +在 Gossip 协议中,每次通讯的两个节点会对当前系统中的节点信息达成一致;通过节点之间互相传递成员信息,最终整个 Dyanmo 的集群中所有的节点都会就成员信息达成一致,如上图所示,"gossip" 首先会被 C 节点接收,然后它会传递给它能接触到的最多的节点 A、D、F、G 四个节点,然后 "gossip" 会进行二次传播传递给系统中的灰色节点,到此为止系统中的所有节点都得到了最新的 "gossip" 消息。 + +当我们向 Dynamo 中加入了新的节点时,会发生节点之间的分片转移,假设我们连接上了 Dynamo 数据库,然后添加了一个 X 节点,该节点被分配到了如下图所示的 A 和 B 节点之间。 + +![adding-storage-node](images/dynamo/adding-storage-node.png) + +新引入的节点 X 会从三个节点 C、D、E 中接受它们管理的分片的一部分,也就是上图中彩色的 `(E, A]`、`(A, B]` 和 `(B, X]` 三个部分,在 X 节点加入集群之前分别属于与其颜色相同的节点管理。 + +Dynamo 由于其去中心化的架构,节点增删的事件都需要通过 Gossip 协议进行传递,然而拥有主从节点之分的 Bigtable 就不需要上述的方式对集群中的节点进行增删了,它可以直接通过用于管理其他从节点的服务直接注册新的节点或者撤下已有的节点。 + +## 副本同步 + +在 Dynamo 运行的过程中,由于一些情况会造成不同节点中的数据不一致的问题,Dynamo 使用了反信息熵(anti-entropy)的策略保证所有的副本存储的信息都是同步的。 + +为了快速确认多个副本之间的数据的一致性并避免大量的数据传输,Dynamo 使用了 [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree) 对不同节点中的数据进行快速验证。 + +![merkle-hash-tree](images/dynamo/merkle-hash-tree.png) + +在 Merkle 树中,所有父节点中的内容都是叶子节点的哈希,通过这种方式构建的树形结构能够保证整棵树不会被篡改,任何的改动都能被立刻发现。 + +Dynamo 中的每一个节点都为其持有的键的范围维护了一颗 Merkle 树,在验证两份节点中的数据是否相同时,只需要发送根节点中的哈希值,如果相同那么说明两棵树的内容全部相同,否则就会依次对比不同层级节点中的内容,直到找出不同的副本,这种做法虽然能够减少数据的传输并能够快速找到副本之间的不同,但是当有新的节点加入或者旧的节点退出时会导致大量的 Merkle 树重新计算。 + +## 总结 + +在 Dynamo 的论文公开之后,有一篇文章将 Dynamo 的设计称作 ["A flawed architecture"](http://jsensarma.com/blog/?p=55),这篇文章的作者在文中对 Dynamo 的实现进行了分析,主要对其最终一致性和 Quorom 机制进行了批评,它在 [HackerNews](https://news.ycombinator.com/item?id=915212) 上也引起了广泛的讨论,帖子中的很多内容都值得一看,能够帮助我们了解 Dynamo 的设计原理,而 Amazon 的 CTO 对于这篇文章也发了一条 Twitter: + +![amazon-cto-twitter-about-dynamo](images/dynamo/amazon-cto-twitter-about-dynamo.png) + +不管如何,Dynamo 作为支撑亚马逊业务的底层服务,其实现原理和思想对于整个社区都是非常有价值的,然而它使用的去中心化的策略也带了很多问题,虽然作者可能会因为这个原因在选择数据库时不会 Dynamo,不过相信它也是有合适的应用场景的。 + +> 原文链接:[理解 ActiveRecord](https://draveness.me/dynamo) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) + +## Reference + ++ [Dynamo: Amazon’s Highly Available Key-value Store](http://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf) ++ [Dynamo: A flawed architecture – Part I](http://jsensarma.com/blog/?p=55) ++ [Dynamo – Part I: a followup and re-rebuttals](http://jsensarma.com/blog/?p=64) ++ [Dynamo and BigTable - Review and Comparison](https://www.slideshare.net/GrishaWeintraub/presentation-46722530) ++ [DynamoDB vs. BigTable · vsChart](http://vschart.com/compare/dynamo-db/vs/bigtable) ++ [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree) ++ [A Digital Signature Based on a Conventional Encryption Function](https://link.springer.com/content/pdf/10.1007/3-540-48184-2_32.pdf) ++ [Dynamo 的实现技术和去中心化](http://www.raychase.net/2396) ++ [浅析 Bigtable 和 LevelDB 的实现](https://draveness.me/bigtable-leveldb) + diff --git a/contents/Database/images/concurrency-control/Shared-Exclusive-Lock.jpg b/contents/Database/images/concurrency-control/Shared-Exclusive-Lock.jpg new file mode 100644 index 0000000..8061f69 Binary files /dev/null and b/contents/Database/images/concurrency-control/Shared-Exclusive-Lock.jpg differ diff --git a/contents/Database/images/concurrency-control/Shared-Exclusive-Lock.png b/contents/Database/images/concurrency-control/Shared-Exclusive-Lock.png new file mode 100644 index 0000000..16a48a1 Binary files /dev/null and b/contents/Database/images/concurrency-control/Shared-Exclusive-Lock.png differ diff --git a/contents/Database/images/concurrency-control/dataitem-with-timestamps.jpg b/contents/Database/images/concurrency-control/dataitem-with-timestamps.jpg new file mode 100644 index 0000000..4cfa7b9 Binary files /dev/null and b/contents/Database/images/concurrency-control/dataitem-with-timestamps.jpg differ diff --git a/contents/Database/images/concurrency-control/dataitem-with-timestamps.png b/contents/Database/images/concurrency-control/dataitem-with-timestamps.png new file mode 100644 index 0000000..5037440 Binary files /dev/null and b/contents/Database/images/concurrency-control/dataitem-with-timestamps.png differ diff --git a/contents/Database/images/concurrency-control/deadlock-handling.jpg b/contents/Database/images/concurrency-control/deadlock-handling.jpg new file mode 100644 index 0000000..48c22b1 Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-handling.jpg differ diff --git a/contents/Database/images/concurrency-control/deadlock-handling.png b/contents/Database/images/concurrency-control/deadlock-handling.png new file mode 100644 index 0000000..d4ec5c4 Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-handling.png differ diff --git a/contents/Database/images/concurrency-control/deadlock-prevention-die.jpg b/contents/Database/images/concurrency-control/deadlock-prevention-die.jpg new file mode 100644 index 0000000..1c92221 Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-prevention-die.jpg differ diff --git a/contents/Database/images/concurrency-control/deadlock-prevention-wait-die.jpg b/contents/Database/images/concurrency-control/deadlock-prevention-wait-die.jpg new file mode 100644 index 0000000..658862e Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-prevention-wait-die.jpg differ diff --git a/contents/Database/images/concurrency-control/deadlock-prevention-wait-die.png b/contents/Database/images/concurrency-control/deadlock-prevention-wait-die.png new file mode 100644 index 0000000..e5078b7 Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-prevention-wait-die.png differ diff --git a/contents/Database/images/concurrency-control/deadlock-prevention-wait.jpg b/contents/Database/images/concurrency-control/deadlock-prevention-wait.jpg new file mode 100644 index 0000000..04166b4 Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-prevention-wait.jpg differ diff --git a/contents/Database/images/concurrency-control/deadlock-prevention-wound-wait.jpg b/contents/Database/images/concurrency-control/deadlock-prevention-wound-wait.jpg new file mode 100644 index 0000000..08d908e Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-prevention-wound-wait.jpg differ diff --git a/contents/Database/images/concurrency-control/deadlock-prevention-wound-wait.png b/contents/Database/images/concurrency-control/deadlock-prevention-wound-wait.png new file mode 100644 index 0000000..1b8f0cf Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-prevention-wound-wait.png differ diff --git a/contents/Database/images/concurrency-control/deadlock-recovery.jpg b/contents/Database/images/concurrency-control/deadlock-recovery.jpg new file mode 100644 index 0000000..b3f0437 Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-recovery.jpg differ diff --git a/contents/Database/images/concurrency-control/deadlock-recovery.png b/contents/Database/images/concurrency-control/deadlock-recovery.png new file mode 100644 index 0000000..f0d2076 Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-recovery.png differ diff --git a/contents/Database/images/concurrency-control/deadlock-wait-for-graph.jpg b/contents/Database/images/concurrency-control/deadlock-wait-for-graph.jpg new file mode 100644 index 0000000..3603d6e Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-wait-for-graph.jpg differ diff --git a/contents/Database/images/concurrency-control/deadlock-wait-for-graph.png b/contents/Database/images/concurrency-control/deadlock-wait-for-graph.png new file mode 100644 index 0000000..ff5734e Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock-wait-for-graph.png differ diff --git a/contents/Database/images/concurrency-control/deadlock.jpg b/contents/Database/images/concurrency-control/deadlock.jpg new file mode 100644 index 0000000..e953e58 Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock.jpg differ diff --git a/contents/Database/images/concurrency-control/deadlock.png b/contents/Database/images/concurrency-control/deadlock.png new file mode 100644 index 0000000..096ebac Binary files /dev/null and b/contents/Database/images/concurrency-control/deadlock.png differ diff --git a/contents/Database/images/concurrency-control/granularity-hierarchy.jpg b/contents/Database/images/concurrency-control/granularity-hierarchy.jpg new file mode 100644 index 0000000..0b612a2 Binary files /dev/null and b/contents/Database/images/concurrency-control/granularity-hierarchy.jpg differ diff --git a/contents/Database/images/concurrency-control/granularity-hierarchy.png b/contents/Database/images/concurrency-control/granularity-hierarchy.png new file mode 100644 index 0000000..2166a61 Binary files /dev/null and b/contents/Database/images/concurrency-control/granularity-hierarchy.png differ diff --git a/contents/Database/images/concurrency-control/growing-to-shrinking.jpg b/contents/Database/images/concurrency-control/growing-to-shrinking.jpg new file mode 100644 index 0000000..74c770b Binary files /dev/null and b/contents/Database/images/concurrency-control/growing-to-shrinking.jpg differ diff --git a/contents/Database/images/concurrency-control/growing-to-shrinking.png b/contents/Database/images/concurrency-control/growing-to-shrinking.png new file mode 100644 index 0000000..e38f6d4 Binary files /dev/null and b/contents/Database/images/concurrency-control/growing-to-shrinking.png differ diff --git a/contents/Database/images/concurrency-control/lock-and-wait.jpg b/contents/Database/images/concurrency-control/lock-and-wait.jpg new file mode 100644 index 0000000..8782c8b Binary files /dev/null and b/contents/Database/images/concurrency-control/lock-and-wait.jpg differ diff --git a/contents/Database/images/concurrency-control/lock-and-wait.png b/contents/Database/images/concurrency-control/lock-and-wait.png new file mode 100644 index 0000000..8615eab Binary files /dev/null and b/contents/Database/images/concurrency-control/lock-and-wait.png differ diff --git a/contents/Database/images/concurrency-control/lock-type-compatibility-matrix.jpg b/contents/Database/images/concurrency-control/lock-type-compatibility-matrix.jpg new file mode 100644 index 0000000..73fb3ef Binary files /dev/null and b/contents/Database/images/concurrency-control/lock-type-compatibility-matrix.jpg differ diff --git a/contents/Database/images/concurrency-control/lock-type-compatibility-matrix.png b/contents/Database/images/concurrency-control/lock-type-compatibility-matrix.png new file mode 100644 index 0000000..b066343 Binary files /dev/null and b/contents/Database/images/concurrency-control/lock-type-compatibility-matrix.png differ diff --git a/contents/Database/images/concurrency-control/multiversion-2pl-read.jpg b/contents/Database/images/concurrency-control/multiversion-2pl-read.jpg new file mode 100644 index 0000000..7d476ae Binary files /dev/null and b/contents/Database/images/concurrency-control/multiversion-2pl-read.jpg differ diff --git a/contents/Database/images/concurrency-control/multiversion-2pl-read.png b/contents/Database/images/concurrency-control/multiversion-2pl-read.png new file mode 100644 index 0000000..108b931 Binary files /dev/null and b/contents/Database/images/concurrency-control/multiversion-2pl-read.png differ diff --git a/contents/Database/images/concurrency-control/multiversion-2pl-write.jpg b/contents/Database/images/concurrency-control/multiversion-2pl-write.jpg new file mode 100644 index 0000000..2e6bf89 Binary files /dev/null and b/contents/Database/images/concurrency-control/multiversion-2pl-write.jpg differ diff --git a/contents/Database/images/concurrency-control/multiversion-2pl-write.png b/contents/Database/images/concurrency-control/multiversion-2pl-write.png new file mode 100644 index 0000000..68d54a7 Binary files /dev/null and b/contents/Database/images/concurrency-control/multiversion-2pl-write.png differ diff --git a/contents/Database/images/concurrency-control/multiversion-scheme.jpg b/contents/Database/images/concurrency-control/multiversion-scheme.jpg new file mode 100644 index 0000000..1f0cdca Binary files /dev/null and b/contents/Database/images/concurrency-control/multiversion-scheme.jpg differ diff --git a/contents/Database/images/concurrency-control/multiversion-scheme.png b/contents/Database/images/concurrency-control/multiversion-scheme.png new file mode 100644 index 0000000..3e6df5f Binary files /dev/null and b/contents/Database/images/concurrency-control/multiversion-scheme.png differ diff --git a/contents/Database/images/concurrency-control/pessimistic-and-optimistic.jpg b/contents/Database/images/concurrency-control/pessimistic-and-optimistic.jpg new file mode 100644 index 0000000..c17c9e2 Binary files /dev/null and b/contents/Database/images/concurrency-control/pessimistic-and-optimistic.jpg differ diff --git a/contents/Database/images/concurrency-control/pessimistic-and-optimistic.png b/contents/Database/images/concurrency-control/pessimistic-and-optimistic.png new file mode 100644 index 0000000..a363032 Binary files /dev/null and b/contents/Database/images/concurrency-control/pessimistic-and-optimistic.png differ diff --git a/contents/Database/images/concurrency-control/pessimistic-conccurency-control.jpg b/contents/Database/images/concurrency-control/pessimistic-conccurency-control.jpg new file mode 100644 index 0000000..36599dd Binary files /dev/null and b/contents/Database/images/concurrency-control/pessimistic-conccurency-control.jpg differ diff --git a/contents/Database/images/concurrency-control/pessimistic-conccurency-control.png b/contents/Database/images/concurrency-control/pessimistic-conccurency-control.png new file mode 100644 index 0000000..00debda Binary files /dev/null and b/contents/Database/images/concurrency-control/pessimistic-conccurency-control.png differ diff --git a/contents/Database/images/concurrency-control/pessimistic-optimistic-multiversion-conccurency-control.jpg b/contents/Database/images/concurrency-control/pessimistic-optimistic-multiversion-conccurency-control.jpg new file mode 100644 index 0000000..8c2a3a9 Binary files /dev/null and b/contents/Database/images/concurrency-control/pessimistic-optimistic-multiversion-conccurency-control.jpg differ diff --git a/contents/Database/images/concurrency-control/pessimistic-optimistic-multiversion-conccurency-control.png b/contents/Database/images/concurrency-control/pessimistic-optimistic-multiversion-conccurency-control.png new file mode 100644 index 0000000..9cbef29 Binary files /dev/null and b/contents/Database/images/concurrency-control/pessimistic-optimistic-multiversion-conccurency-control.png differ diff --git a/contents/Database/images/concurrency-control/rigorous-two-phase-locking.jpg b/contents/Database/images/concurrency-control/rigorous-two-phase-locking.jpg new file mode 100644 index 0000000..4d57e37 Binary files /dev/null and b/contents/Database/images/concurrency-control/rigorous-two-phase-locking.jpg differ diff --git a/contents/Database/images/concurrency-control/timestamp-ordering-protocol-process.jpg b/contents/Database/images/concurrency-control/timestamp-ordering-protocol-process.jpg new file mode 100644 index 0000000..0608b5e Binary files /dev/null and b/contents/Database/images/concurrency-control/timestamp-ordering-protocol-process.jpg differ diff --git a/contents/Database/images/concurrency-control/timestamp-ordering-protocol-process.png b/contents/Database/images/concurrency-control/timestamp-ordering-protocol-process.png new file mode 100644 index 0000000..38beea5 Binary files /dev/null and b/contents/Database/images/concurrency-control/timestamp-ordering-protocol-process.png differ diff --git a/contents/Database/images/concurrency-control/timestamp-ordering-protocol.jpg b/contents/Database/images/concurrency-control/timestamp-ordering-protocol.jpg new file mode 100644 index 0000000..a5b2d2e Binary files /dev/null and b/contents/Database/images/concurrency-control/timestamp-ordering-protocol.jpg differ diff --git a/contents/Database/images/concurrency-control/timestamp-ordering-protocol.png b/contents/Database/images/concurrency-control/timestamp-ordering-protocol.png new file mode 100644 index 0000000..e881e66 Binary files /dev/null and b/contents/Database/images/concurrency-control/timestamp-ordering-protocol.png differ diff --git a/contents/Database/images/concurrency-control/tradeoff-between-performance-and-serializability.jpg b/contents/Database/images/concurrency-control/tradeoff-between-performance-and-serializability.jpg new file mode 100644 index 0000000..2417555 Binary files /dev/null and b/contents/Database/images/concurrency-control/tradeoff-between-performance-and-serializability.jpg differ diff --git a/contents/Database/images/concurrency-control/tradeoff-between-performance-and-serializability.png b/contents/Database/images/concurrency-control/tradeoff-between-performance-and-serializability.png new file mode 100644 index 0000000..6b645c3 Binary files /dev/null and b/contents/Database/images/concurrency-control/tradeoff-between-performance-and-serializability.png differ diff --git a/contents/Database/images/concurrency-control/two-phase-locking.jpg b/contents/Database/images/concurrency-control/two-phase-locking.jpg new file mode 100644 index 0000000..637fa73 Binary files /dev/null and b/contents/Database/images/concurrency-control/two-phase-locking.jpg differ diff --git a/contents/Database/images/concurrency-control/two-phase-locking.png b/contents/Database/images/concurrency-control/two-phase-locking.png new file mode 100644 index 0000000..ffe7b08 Binary files /dev/null and b/contents/Database/images/concurrency-control/two-phase-locking.png differ diff --git a/contents/Database/images/concurrency-control/validation-based-protocol.jpg b/contents/Database/images/concurrency-control/validation-based-protocol.jpg new file mode 100644 index 0000000..a4d3a8c Binary files /dev/null and b/contents/Database/images/concurrency-control/validation-based-protocol.jpg differ diff --git a/contents/Database/images/concurrency-control/validation-based-protocol.png b/contents/Database/images/concurrency-control/validation-based-protocol.png new file mode 100644 index 0000000..e635152 Binary files /dev/null and b/contents/Database/images/concurrency-control/validation-based-protocol.png differ diff --git a/contents/Database/images/dynamo/adding-storage-node.png b/contents/Database/images/dynamo/adding-storage-node.png new file mode 100644 index 0000000..5ffcc57 Binary files /dev/null and b/contents/Database/images/dynamo/adding-storage-node.png differ diff --git a/contents/Database/images/dynamo/amazon-cto-twitter-about-dynamo.png b/contents/Database/images/dynamo/amazon-cto-twitter-about-dynamo.png new file mode 100644 index 0000000..69417c0 Binary files /dev/null and b/contents/Database/images/dynamo/amazon-cto-twitter-about-dynamo.png differ diff --git a/contents/Database/images/dynamo/centralized-architecture.png b/contents/Database/images/dynamo/centralized-architecture.png new file mode 100644 index 0000000..e3da755 Binary files /dev/null and b/contents/Database/images/dynamo/centralized-architecture.png differ diff --git a/contents/Database/images/dynamo/dynamo-architecture.png b/contents/Database/images/dynamo/dynamo-architecture.png new file mode 100644 index 0000000..b936260 Binary files /dev/null and b/contents/Database/images/dynamo/dynamo-architecture.png differ diff --git a/contents/Database/images/dynamo/dynamo-read-write-operation.png b/contents/Database/images/dynamo/dynamo-read-write-operation.png new file mode 100644 index 0000000..14d5583 Binary files /dev/null and b/contents/Database/images/dynamo/dynamo-read-write-operation.png differ diff --git a/contents/Database/images/dynamo/dynamodb.png b/contents/Database/images/dynamo/dynamodb.png new file mode 100644 index 0000000..0cce042 Binary files /dev/null and b/contents/Database/images/dynamo/dynamodb.png differ diff --git a/contents/Database/images/dynamo/equal-size-partition-in-dynamo.png b/contents/Database/images/dynamo/equal-size-partition-in-dynamo.png new file mode 100644 index 0000000..f5250e8 Binary files /dev/null and b/contents/Database/images/dynamo/equal-size-partition-in-dynamo.png differ diff --git a/contents/Database/images/dynamo/gossip-protocol.png b/contents/Database/images/dynamo/gossip-protocol.png new file mode 100644 index 0000000..68d9598 Binary files /dev/null and b/contents/Database/images/dynamo/gossip-protocol.png differ diff --git a/contents/Database/images/dynamo/inconsistent-in-dynamo.png b/contents/Database/images/dynamo/inconsistent-in-dynamo.png new file mode 100644 index 0000000..f2977f9 Binary files /dev/null and b/contents/Database/images/dynamo/inconsistent-in-dynamo.png differ diff --git a/contents/Database/images/dynamo/merkle-hash-tree.png b/contents/Database/images/dynamo/merkle-hash-tree.png new file mode 100644 index 0000000..68fa263 Binary files /dev/null and b/contents/Database/images/dynamo/merkle-hash-tree.png differ diff --git a/contents/Database/images/dynamo/node-selecting-strategies.png b/contents/Database/images/dynamo/node-selecting-strategies.png new file mode 100644 index 0000000..47b6245 Binary files /dev/null and b/contents/Database/images/dynamo/node-selecting-strategies.png differ diff --git a/contents/Database/images/dynamo/nosql-main-characteristics.png b/contents/Database/images/dynamo/nosql-main-characteristics.png new file mode 100644 index 0000000..5669c9d Binary files /dev/null and b/contents/Database/images/dynamo/nosql-main-characteristics.png differ diff --git a/contents/Database/images/dynamo/partition-in-bigtable.png b/contents/Database/images/dynamo/partition-in-bigtable.png new file mode 100644 index 0000000..d0441ef Binary files /dev/null and b/contents/Database/images/dynamo/partition-in-bigtable.png differ diff --git a/contents/Database/images/dynamo/partition-in-dynamo.png b/contents/Database/images/dynamo/partition-in-dynamo.png new file mode 100644 index 0000000..e7c9709 Binary files /dev/null and b/contents/Database/images/dynamo/partition-in-dynamo.png differ diff --git a/contents/Database/images/dynamo/replication-in-dynamo.png b/contents/Database/images/dynamo/replication-in-dynamo.png new file mode 100644 index 0000000..a61adc3 Binary files /dev/null and b/contents/Database/images/dynamo/replication-in-dynamo.png differ diff --git a/contents/Database/images/dynamo/replication-range-in-dynamo.png b/contents/Database/images/dynamo/replication-range-in-dynamo.png new file mode 100644 index 0000000..04bfdc5 Binary files /dev/null and b/contents/Database/images/dynamo/replication-range-in-dynamo.png differ diff --git a/contents/Database/images/dynamo/ring-membership.png b/contents/Database/images/dynamo/ring-membership.png new file mode 100644 index 0000000..e72933a Binary files /dev/null and b/contents/Database/images/dynamo/ring-membership.png differ diff --git a/contents/Database/images/dynamo/version-evolution-in-dynamo.png b/contents/Database/images/dynamo/version-evolution-in-dynamo.png new file mode 100644 index 0000000..af4b604 Binary files /dev/null and b/contents/Database/images/dynamo/version-evolution-in-dynamo.png differ diff --git a/contents/Database/images/leveldb-bigtable/Bigtable-DataModel-Row-Column-Timestamp-Value.jpg b/contents/Database/images/leveldb-bigtable/Bigtable-DataModel-Row-Column-Timestamp-Value.jpg new file mode 100644 index 0000000..c9899bb Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/Bigtable-DataModel-Row-Column-Timestamp-Value.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/Bigtable-LevelDB-Cover.jpg b/contents/Database/images/leveldb-bigtable/Bigtable-LevelDB-Cover.jpg new file mode 100644 index 0000000..ad58e03 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/Bigtable-LevelDB-Cover.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/FileMetaData.jpg b/contents/Database/images/leveldb-bigtable/FileMetaData.jpg new file mode 100644 index 0000000..65d6f84 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/FileMetaData.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/Goals-of-Bigtable.jpg b/contents/Database/images/leveldb-bigtable/Goals-of-Bigtable.jpg new file mode 100644 index 0000000..7a9cbba Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/Goals-of-Bigtable.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/Immutable-MemTable.jpg b/contents/Database/images/leveldb-bigtable/Immutable-MemTable.jpg new file mode 100644 index 0000000..c39b695 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/Immutable-MemTable.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-After-Compactions.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-After-Compactions.jpg new file mode 100644 index 0000000..6c81e8d Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-After-Compactions.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-BackgroundCompaction-Processes.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-BackgroundCompaction-Processes.jpg new file mode 100644 index 0000000..621f2fb Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-BackgroundCompaction-Processes.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-Level0-Layer.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-Level0-Layer.jpg new file mode 100644 index 0000000..1c35d9b Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-Level0-Layer.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-LevelN-Layers.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-LevelN-Layers.jpg new file mode 100644 index 0000000..e164f58 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-LevelN-Layers.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-MemTable-SkipList.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-MemTable-SkipList.jpg new file mode 100644 index 0000000..64b4351 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-MemTable-SkipList.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-Memtable-Key-Value-Format.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-Memtable-Key-Value-Format.jpg new file mode 100644 index 0000000..582c0b8 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-Memtable-Key-Value-Format.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-Pick-Compactions.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-Pick-Compactions.jpg new file mode 100644 index 0000000..e77d104 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-Pick-Compactions.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-Put.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-Put.jpg new file mode 100644 index 0000000..142b7a0 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-Put.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-Read-Processes.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-Read-Processes.jpg new file mode 100644 index 0000000..b55359e Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-Read-Processes.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-Serving.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-Serving.jpg new file mode 100644 index 0000000..d365bb1 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-Serving.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/LevelDB-log-format-and-recordtype.jpg b/contents/Database/images/leveldb-bigtable/LevelDB-log-format-and-recordtype.jpg new file mode 100644 index 0000000..a5c214a Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/LevelDB-log-format-and-recordtype.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/Major-Compaction.jpg b/contents/Database/images/leveldb-bigtable/Major-Compaction.jpg new file mode 100644 index 0000000..c9ac5ee Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/Major-Compaction.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/Master-Manage-Tablet-Servers-And-Tablets.jpg b/contents/Database/images/leveldb-bigtable/Master-Manage-Tablet-Servers-And-Tablets.jpg new file mode 100644 index 0000000..cee9f9e Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/Master-Manage-Tablet-Servers-And-Tablets.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/Minor-Compaction.jpg b/contents/Database/images/leveldb-bigtable/Minor-Compaction.jpg new file mode 100644 index 0000000..1ee6468 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/Minor-Compaction.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/SSTable-Footer.jpg b/contents/Database/images/leveldb-bigtable/SSTable-Footer.jpg new file mode 100644 index 0000000..5c4c2f5 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/SSTable-Footer.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/SSTable-Format.jpg b/contents/Database/images/leveldb-bigtable/SSTable-Format.jpg new file mode 100644 index 0000000..91f507a Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/SSTable-Format.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/Tablet-Location-Hierarchy.jpg b/contents/Database/images/leveldb-bigtable/Tablet-Location-Hierarchy.jpg new file mode 100644 index 0000000..66d67f0 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/Tablet-Location-Hierarchy.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/Tablet-Serving.jpg b/contents/Database/images/leveldb-bigtable/Tablet-Serving.jpg new file mode 100644 index 0000000..2b24d6c Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/Tablet-Serving.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/VersionSet-Version-And-VersionEdit.jpg b/contents/Database/images/leveldb-bigtable/VersionSet-Version-And-VersionEdit.jpg new file mode 100644 index 0000000..1599a71 Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/VersionSet-Version-And-VersionEdit.jpg differ diff --git a/contents/Database/images/leveldb-bigtable/leveldb-logo.png b/contents/Database/images/leveldb-bigtable/leveldb-logo.png new file mode 100644 index 0000000..5ce6e2d Binary files /dev/null and b/contents/Database/images/leveldb-bigtable/leveldb-logo.png differ diff --git a/contents/Database/images/mongodb-to-mysql/array-to-string-or-relation.png b/contents/Database/images/mongodb-to-mysql/array-to-string-or-relation.png new file mode 100644 index 0000000..fb797b3 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/array-to-string-or-relation.png differ diff --git a/contents/Database/images/mongodb-to-mysql/embedded-reference-documents.png b/contents/Database/images/mongodb-to-mysql/embedded-reference-documents.png new file mode 100644 index 0000000..3fc2b66 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/embedded-reference-documents.png differ diff --git a/contents/Database/images/mongodb-to-mysql/embedded-to-reference.png b/contents/Database/images/mongodb-to-mysql/embedded-to-reference.png new file mode 100644 index 0000000..4dfe55a Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/embedded-to-reference.png differ diff --git a/contents/Database/images/mongodb-to-mysql/embedded_reference_documents.png b/contents/Database/images/mongodb-to-mysql/embedded_reference_documents.png new file mode 100644 index 0000000..d9c9ca6 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/embedded_reference_documents.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mongodb-mysql-datatype-relation.png b/contents/Database/images/mongodb-to-mysql/mongodb-mysql-datatype-relation.png new file mode 100644 index 0000000..49c5cc7 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mongodb-mysql-datatype-relation.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mongodb-mysql-enum.png b/contents/Database/images/mongodb-to-mysql/mongodb-mysql-enum.png new file mode 100644 index 0000000..f7f9763 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mongodb-mysql-enum.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mongodb-mysql-id.png b/contents/Database/images/mongodb-to-mysql/mongodb-mysql-id.png new file mode 100644 index 0000000..814fcee Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mongodb-mysql-id.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mongodb-mysql-problems-to-be-solved.png b/contents/Database/images/mongodb-to-mysql/mongodb-mysql-problems-to-be-solved.png new file mode 100644 index 0000000..85caa78 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mongodb-mysql-problems-to-be-solved.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mongodb-pre-migration.png b/contents/Database/images/mongodb-to-mysql/mongodb-pre-migration.png new file mode 100644 index 0000000..7d1776f Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mongodb-pre-migration.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mongoid-activerecord-enum.png b/contents/Database/images/mongodb-to-mysql/mongoid-activerecord-enum.png new file mode 100644 index 0000000..54f5611 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mongoid-activerecord-enum.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mongoid-to-activerecord-model-and-query.png b/contents/Database/images/mongodb-to-mysql/mongoid-to-activerecord-model-and-query.png new file mode 100644 index 0000000..1de57a1 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mongoid-to-activerecord-model-and-query.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mysql-after-migrations.png b/contents/Database/images/mongodb-to-mysql/mysql-after-migrations.png new file mode 100644 index 0000000..81ef19c Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mysql-after-migrations.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mysql-and-mongodb-cover.png b/contents/Database/images/mongodb-to-mysql/mysql-and-mongodb-cover.png new file mode 100644 index 0000000..7efd294 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mysql-and-mongodb-cover.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mysql-and-mongodb-work-together.png b/contents/Database/images/mongodb-to-mysql/mysql-and-mongodb-work-together.png new file mode 100644 index 0000000..4a99859 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mysql-and-mongodb-work-together.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mysql-and-mongodb.png b/contents/Database/images/mongodb-to-mysql/mysql-and-mongodb.png new file mode 100644 index 0000000..77030fd Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mysql-and-mongodb.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mysql-before-migrations.png b/contents/Database/images/mongodb-to-mysql/mysql-before-migrations.png new file mode 100644 index 0000000..d9b0c2a Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mysql-before-migrations.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mysql-migrations.png b/contents/Database/images/mongodb-to-mysql/mysql-migrations.png new file mode 100644 index 0000000..65b1996 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mysql-migrations.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mysql-to-mongodb.png b/contents/Database/images/mongodb-to-mysql/mysql-to-mongodb.png new file mode 100644 index 0000000..a385137 Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mysql-to-mongodb.png differ diff --git a/contents/Database/images/mongodb-to-mysql/mysqldump-csv.png b/contents/Database/images/mongodb-to-mysql/mysqldump-csv.png new file mode 100644 index 0000000..295c44e Binary files /dev/null and b/contents/Database/images/mongodb-to-mysql/mysqldump-csv.png differ diff --git a/contents/Database/images/mongodb-wiredtiger/Checkpoints-Conditions.jpg b/contents/Database/images/mongodb-wiredtiger/Checkpoints-Conditions.jpg new file mode 100644 index 0000000..d9bddf7 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/Checkpoints-Conditions.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/Compound-Index.jpg b/contents/Database/images/mongodb-wiredtiger/Compound-Index.jpg new file mode 100644 index 0000000..bfddce0 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/Compound-Index.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/Different-Data-Structure.jpg b/contents/Database/images/mongodb-wiredtiger/Different-Data-Structure.jpg new file mode 100644 index 0000000..284ed3c Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/Different-Data-Structure.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/Embedded-Data-Models-MongoDB.jpg b/contents/Database/images/mongodb-wiredtiger/Embedded-Data-Models-MongoDB.jpg new file mode 100644 index 0000000..82d22a3 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/Embedded-Data-Models-MongoDB.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/MongoDB-Architecture.jpg b/contents/Database/images/mongodb-wiredtiger/MongoDB-Architecture.jpg new file mode 100644 index 0000000..84577b7 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/MongoDB-Architecture.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/MongoDB-Cover.jpg b/contents/Database/images/mongodb-wiredtiger/MongoDB-Cover.jpg new file mode 100644 index 0000000..c7c8965 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/MongoDB-Cover.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/MongoDB-Covers.jpg b/contents/Database/images/mongodb-wiredtiger/MongoDB-Covers.jpg new file mode 100644 index 0000000..c7c8965 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/MongoDB-Covers.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/MongoDB-Indexes.jpg b/contents/Database/images/mongodb-wiredtiger/MongoDB-Indexes.jpg new file mode 100644 index 0000000..309eb3d Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/MongoDB-Indexes.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/MongoDB-ObjectId.jpg b/contents/Database/images/mongodb-wiredtiger/MongoDB-ObjectId.jpg new file mode 100644 index 0000000..4242d98 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/MongoDB-ObjectId.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/Multiple-Storage-Engines.jpg b/contents/Database/images/mongodb-wiredtiger/Multiple-Storage-Engines.jpg new file mode 100644 index 0000000..3219800 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/Multiple-Storage-Engines.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/Not-Found-Document.jpg b/contents/Database/images/mongodb-wiredtiger/Not-Found-Document.jpg new file mode 100644 index 0000000..588f428 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/Not-Found-Document.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/Reference-MongoDB.jpg b/contents/Database/images/mongodb-wiredtiger/Reference-MongoDB.jpg new file mode 100644 index 0000000..36522a9 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/Reference-MongoDB.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/Single-Field-Index.jpg b/contents/Database/images/mongodb-wiredtiger/Single-Field-Index.jpg new file mode 100644 index 0000000..abd36b3 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/Single-Field-Index.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/Translating-Between-RDBMS-and-MongoDB.jpg b/contents/Database/images/mongodb-wiredtiger/Translating-Between-RDBMS-and-MongoDB.jpg new file mode 100644 index 0000000..71c19a8 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/Translating-Between-RDBMS-and-MongoDB.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/WiredTiger-Cache.jpg b/contents/Database/images/mongodb-wiredtiger/WiredTiger-Cache.jpg new file mode 100644 index 0000000..894174f Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/WiredTiger-Cache.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/its-not-always-simple-banner.jpg b/contents/Database/images/mongodb-wiredtiger/its-not-always-simple-banner.jpg new file mode 100644 index 0000000..c307a1a Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/its-not-always-simple-banner.jpg differ diff --git a/contents/Database/images/mongodb-wiredtiger/logo.png b/contents/Database/images/mongodb-wiredtiger/logo.png new file mode 100644 index 0000000..1537089 Binary files /dev/null and b/contents/Database/images/mongodb-wiredtiger/logo.png differ diff --git a/contents/Database/images/mysql/Antelope-Barracuda-Row-Format.jpg b/contents/Database/images/mysql/Antelope-Barracuda-Row-Format.jpg new file mode 100644 index 0000000..a4cca7f Binary files /dev/null and b/contents/Database/images/mysql/Antelope-Barracuda-Row-Format.jpg differ diff --git a/contents/Database/images/mysql/B+Tree.jpg b/contents/Database/images/mysql/B+Tree.jpg new file mode 100644 index 0000000..5346601 Binary files /dev/null and b/contents/Database/images/mysql/B+Tree.jpg differ diff --git a/contents/Database/images/mysql/COMPACT-And-REDUNDANT-Row-Format.jpg b/contents/Database/images/mysql/COMPACT-And-REDUNDANT-Row-Format.jpg new file mode 100644 index 0000000..ac01b41 Binary files /dev/null and b/contents/Database/images/mysql/COMPACT-And-REDUNDANT-Row-Format.jpg differ diff --git a/contents/Database/images/mysql/Clustered-Index.jpg b/contents/Database/images/mysql/Clustered-Index.jpg new file mode 100644 index 0000000..f313192 Binary files /dev/null and b/contents/Database/images/mysql/Clustered-Index.jpg differ diff --git a/contents/Database/images/mysql/Clustered-Secondary-Index.jpg b/contents/Database/images/mysql/Clustered-Secondary-Index.jpg new file mode 100644 index 0000000..c34c625 Binary files /dev/null and b/contents/Database/images/mysql/Clustered-Secondary-Index.jpg differ diff --git a/contents/Database/images/mysql/Database-Instance.jpg b/contents/Database/images/mysql/Database-Instance.jpg new file mode 100644 index 0000000..8f38d51 Binary files /dev/null and b/contents/Database/images/mysql/Database-Instance.jpg differ diff --git a/contents/Database/images/mysql/Deadlocks.jpg b/contents/Database/images/mysql/Deadlocks.jpg new file mode 100644 index 0000000..e2e4845 Binary files /dev/null and b/contents/Database/images/mysql/Deadlocks.jpg differ diff --git a/contents/Database/images/mysql/Infimum-Rows-Supremum.jpg b/contents/Database/images/mysql/Infimum-Rows-Supremum.jpg new file mode 100644 index 0000000..2894d4b Binary files /dev/null and b/contents/Database/images/mysql/Infimum-Rows-Supremum.jpg differ diff --git a/contents/Database/images/mysql/InnoDB-B-Tree-Node.jpg b/contents/Database/images/mysql/InnoDB-B-Tree-Node.jpg new file mode 100644 index 0000000..22409df Binary files /dev/null and b/contents/Database/images/mysql/InnoDB-B-Tree-Node.jpg differ diff --git a/contents/Database/images/mysql/Lock-Type-Compatibility-Matrix.jpg b/contents/Database/images/mysql/Lock-Type-Compatibility-Matrix.jpg new file mode 100644 index 0000000..c5098ee Binary files /dev/null and b/contents/Database/images/mysql/Lock-Type-Compatibility-Matrix.jpg differ diff --git a/contents/Database/images/mysql/Logical-View-of-MySQL-Architecture.jpg b/contents/Database/images/mysql/Logical-View-of-MySQL-Architecture.jpg new file mode 100644 index 0000000..be2c1ad Binary files /dev/null and b/contents/Database/images/mysql/Logical-View-of-MySQL-Architecture.jpg differ diff --git a/contents/Database/images/mysql/Optimistic-Pessimistic-Locks.jpg b/contents/Database/images/mysql/Optimistic-Pessimistic-Locks.jpg new file mode 100644 index 0000000..6cfff4a Binary files /dev/null and b/contents/Database/images/mysql/Optimistic-Pessimistic-Locks.jpg differ diff --git a/contents/Database/images/mysql/Read-Commited-Non-Repeatable-Read.jpg b/contents/Database/images/mysql/Read-Commited-Non-Repeatable-Read.jpg new file mode 100644 index 0000000..7d4b259 Binary files /dev/null and b/contents/Database/images/mysql/Read-Commited-Non-Repeatable-Read.jpg differ diff --git a/contents/Database/images/mysql/Read-Uncommited-Dirty-Read.jpg b/contents/Database/images/mysql/Read-Uncommited-Dirty-Read.jpg new file mode 100644 index 0000000..54d913d Binary files /dev/null and b/contents/Database/images/mysql/Read-Uncommited-Dirty-Read.jpg differ diff --git a/contents/Database/images/mysql/Relation-Between-Page-Size-Extent-Size.png b/contents/Database/images/mysql/Relation-Between-Page-Size-Extent-Size.png new file mode 100644 index 0000000..6f68e46 Binary files /dev/null and b/contents/Database/images/mysql/Relation-Between-Page-Size-Extent-Size.png differ diff --git a/contents/Database/images/mysql/Repeatable-Read-Phantom-Read.jpg b/contents/Database/images/mysql/Repeatable-Read-Phantom-Read.jpg new file mode 100644 index 0000000..a7633be Binary files /dev/null and b/contents/Database/images/mysql/Repeatable-Read-Phantom-Read.jpg differ diff --git a/contents/Database/images/mysql/Repeatable-with-Next-Key-Lock.jpg b/contents/Database/images/mysql/Repeatable-with-Next-Key-Lock.jpg new file mode 100644 index 0000000..bab3dc4 Binary files /dev/null and b/contents/Database/images/mysql/Repeatable-with-Next-Key-Lock.jpg differ diff --git a/contents/Database/images/mysql/Row-Overflow-in-Barracuda.jpg b/contents/Database/images/mysql/Row-Overflow-in-Barracuda.jpg new file mode 100644 index 0000000..f702e4e Binary files /dev/null and b/contents/Database/images/mysql/Row-Overflow-in-Barracuda.jpg differ diff --git a/contents/Database/images/mysql/Row-Overflow.jpg b/contents/Database/images/mysql/Row-Overflow.jpg new file mode 100644 index 0000000..c743e7a Binary files /dev/null and b/contents/Database/images/mysql/Row-Overflow.jpg differ diff --git a/contents/Database/images/mysql/Secondary-Index.jpg b/contents/Database/images/mysql/Secondary-Index.jpg new file mode 100644 index 0000000..1924223 Binary files /dev/null and b/contents/Database/images/mysql/Secondary-Index.jpg differ diff --git a/contents/Database/images/mysql/Shared-Exclusive-Lock.jpg b/contents/Database/images/mysql/Shared-Exclusive-Lock.jpg new file mode 100644 index 0000000..9f07746 Binary files /dev/null and b/contents/Database/images/mysql/Shared-Exclusive-Lock.jpg differ diff --git a/contents/Database/images/mysql/Tablespace-segment-extent-page-row.jpg b/contents/Database/images/mysql/Tablespace-segment-extent-page-row.jpg new file mode 100644 index 0000000..66db246 Binary files /dev/null and b/contents/Database/images/mysql/Tablespace-segment-extent-page-row.jpg differ diff --git a/contents/Database/images/mysql/Transaction-Isolation-Matrix.jpg b/contents/Database/images/mysql/Transaction-Isolation-Matrix.jpg new file mode 100644 index 0000000..c203fca Binary files /dev/null and b/contents/Database/images/mysql/Transaction-Isolation-Matrix.jpg differ diff --git a/contents/Database/images/mysql/frm-and-ibd-file.jpg b/contents/Database/images/mysql/frm-and-ibd-file.jpg new file mode 100644 index 0000000..dacb667 Binary files /dev/null and b/contents/Database/images/mysql/frm-and-ibd-file.jpg differ diff --git a/contents/Database/images/mysql/frm-file-hex.png b/contents/Database/images/mysql/frm-file-hex.png new file mode 100644 index 0000000..7e4a446 Binary files /dev/null and b/contents/Database/images/mysql/frm-file-hex.png differ diff --git a/contents/Database/images/mysql/mysql.png b/contents/Database/images/mysql/mysql.png new file mode 100644 index 0000000..5e57082 Binary files /dev/null and b/contents/Database/images/mysql/mysql.png differ diff --git a/contents/Database/images/mysql/page-size-and-extent-size.png b/contents/Database/images/mysql/page-size-and-extent-size.png new file mode 100644 index 0000000..c7a862d Binary files /dev/null and b/contents/Database/images/mysql/page-size-and-extent-size.png differ diff --git a/contents/Database/images/sql-index-intro/Behind-Three-Star-Index.jpg b/contents/Database/images/sql-index-intro/Behind-Three-Star-Index.jpg new file mode 100644 index 0000000..39fb485 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Behind-Three-Star-Index.jpg differ diff --git a/contents/Database/images/sql-index-intro/Combined-Filter-Factor-Related.jpg b/contents/Database/images/sql-index-intro/Combined-Filter-Factor-Related.jpg new file mode 100644 index 0000000..0371a61 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Combined-Filter-Factor-Related.jpg differ diff --git a/contents/Database/images/sql-index-intro/Combined-Filter-Factor.jpg b/contents/Database/images/sql-index-intro/Combined-Filter-Factor.jpg new file mode 100644 index 0000000..fe5237c Binary files /dev/null and b/contents/Database/images/sql-index-intro/Combined-Filter-Factor.jpg differ diff --git a/contents/Database/images/sql-index-intro/Different-Stars-Index.jpg b/contents/Database/images/sql-index-intro/Different-Stars-Index.jpg new file mode 100644 index 0000000..88b92d1 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Different-Stars-Index.jpg differ diff --git a/contents/Database/images/sql-index-intro/Disk-IO-Total-Time.jpg b/contents/Database/images/sql-index-intro/Disk-IO-Total-Time.jpg new file mode 100644 index 0000000..ee65dde Binary files /dev/null and b/contents/Database/images/sql-index-intro/Disk-IO-Total-Time.jpg differ diff --git a/contents/Database/images/sql-index-intro/Disk-IO.jpg b/contents/Database/images/sql-index-intro/Disk-IO.jpg new file mode 100644 index 0000000..5041d88 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Disk-IO.jpg differ diff --git a/contents/Database/images/sql-index-intro/Disk-Random-IO.jpg b/contents/Database/images/sql-index-intro/Disk-Random-IO.jpg new file mode 100644 index 0000000..9e7c535 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Disk-Random-IO.jpg differ diff --git a/contents/Database/images/sql-index-intro/Filter-Factor.jpg b/contents/Database/images/sql-index-intro/Filter-Factor.jpg new file mode 100644 index 0000000..e9792b8 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Filter-Factor.jpg differ diff --git a/contents/Database/images/sql-index-intro/Index-and-Performance.jpg b/contents/Database/images/sql-index-intro/Index-and-Performance.jpg new file mode 100644 index 0000000..0a73457 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Index-and-Performance.jpg differ diff --git a/contents/Database/images/sql-index-intro/Match-Columns-Filter-Columns.jpg b/contents/Database/images/sql-index-intro/Match-Columns-Filter-Columns.jpg new file mode 100644 index 0000000..23f8081 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Match-Columns-Filter-Columns.jpg differ diff --git a/contents/Database/images/sql-index-intro/Page-DatabaseBufferPool-Disk.jpg b/contents/Database/images/sql-index-intro/Page-DatabaseBufferPool-Disk.jpg new file mode 100644 index 0000000..cfe8b8c Binary files /dev/null and b/contents/Database/images/sql-index-intro/Page-DatabaseBufferPool-Disk.jpg differ diff --git a/contents/Database/images/sql-index-intro/Page-DatabaseBufferPool.jpg b/contents/Database/images/sql-index-intro/Page-DatabaseBufferPool.jpg new file mode 100644 index 0000000..4baa52d Binary files /dev/null and b/contents/Database/images/sql-index-intro/Page-DatabaseBufferPool.jpg differ diff --git a/contents/Database/images/sql-index-intro/Random-IO.jpg b/contents/Database/images/sql-index-intro/Random-IO.jpg new file mode 100644 index 0000000..41a5ce6 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Random-IO.jpg differ diff --git a/contents/Database/images/sql-index-intro/Random-to-Sequential.jpg b/contents/Database/images/sql-index-intro/Random-to-Sequential.jpg new file mode 100644 index 0000000..d1accfa Binary files /dev/null and b/contents/Database/images/sql-index-intro/Random-to-Sequential.jpg differ diff --git a/contents/Database/images/sql-index-intro/Read-from-Memory.jpg b/contents/Database/images/sql-index-intro/Read-from-Memory.jpg new file mode 100644 index 0000000..67ec820 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Read-from-Memory.jpg differ diff --git a/contents/Database/images/sql-index-intro/Same-Columns-Filter-Factor.jpg b/contents/Database/images/sql-index-intro/Same-Columns-Filter-Factor.jpg new file mode 100644 index 0000000..9a997f8 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Same-Columns-Filter-Factor.jpg differ diff --git a/contents/Database/images/sql-index-intro/Sequential-Reads-from-Disk.jpg b/contents/Database/images/sql-index-intro/Sequential-Reads-from-Disk.jpg new file mode 100644 index 0000000..355b671 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Sequential-Reads-from-Disk.jpg differ diff --git a/contents/Database/images/sql-index-intro/Thin-Index-and-Clustered-Index.jpg b/contents/Database/images/sql-index-intro/Thin-Index-and-Clustered-Index.jpg new file mode 100644 index 0000000..fa3e541 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Thin-Index-and-Clustered-Index.jpg differ diff --git a/contents/Database/images/sql-index-intro/Thin-Index-and-Fat-Index.jpg b/contents/Database/images/sql-index-intro/Thin-Index-and-Fat-Index.jpg new file mode 100644 index 0000000..4511eb1 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Thin-Index-and-Fat-Index.jpg differ diff --git a/contents/Database/images/sql-index-intro/Three-Star-Index.jpg b/contents/Database/images/sql-index-intro/Three-Star-Index.jpg new file mode 100644 index 0000000..3e14711 Binary files /dev/null and b/contents/Database/images/sql-index-intro/Three-Star-Index.jpg differ diff --git a/contents/Database/images/sql-index-performance/Complicated-Query-with-Order-By.jpg b/contents/Database/images/sql-index-performance/Complicated-Query-with-Order-By.jpg new file mode 100644 index 0000000..1fec1df Binary files /dev/null and b/contents/Database/images/sql-index-performance/Complicated-Query-with-Order-By.jpg differ diff --git a/contents/Database/images/sql-index-performance/Disk-Service-Time.jpg b/contents/Database/images/sql-index-performance/Disk-Service-Time.jpg new file mode 100644 index 0000000..0bb3742 Binary files /dev/null and b/contents/Database/images/sql-index-performance/Disk-Service-Time.jpg differ diff --git a/contents/Database/images/sql-index-performance/Filter-Factor.jpg b/contents/Database/images/sql-index-performance/Filter-Factor.jpg new file mode 100644 index 0000000..eb9f91b Binary files /dev/null and b/contents/Database/images/sql-index-performance/Filter-Factor.jpg differ diff --git a/contents/Database/images/sql-index-performance/Index-Search.jpg b/contents/Database/images/sql-index-performance/Index-Search.jpg new file mode 100644 index 0000000..07afdb7 Binary files /dev/null and b/contents/Database/images/sql-index-performance/Index-Search.jpg differ diff --git a/contents/Database/images/sql-index-performance/Index-Slice-Scan.jpg b/contents/Database/images/sql-index-performance/Index-Slice-Scan.jpg new file mode 100644 index 0000000..4e6112c Binary files /dev/null and b/contents/Database/images/sql-index-performance/Index-Slice-Scan.jpg differ diff --git a/contents/Database/images/sql-index-performance/Index-Table-Touch.jpg b/contents/Database/images/sql-index-performance/Index-Table-Touch.jpg new file mode 100644 index 0000000..7b20b76 Binary files /dev/null and b/contents/Database/images/sql-index-performance/Index-Table-Touch.jpg differ diff --git a/contents/Database/images/sql-index-performance/Local-Response-Time-Calculation.jpg b/contents/Database/images/sql-index-performance/Local-Response-Time-Calculation.jpg new file mode 100644 index 0000000..6ee31eb Binary files /dev/null and b/contents/Database/images/sql-index-performance/Local-Response-Time-Calculation.jpg differ diff --git a/contents/Database/images/sql-index-performance/Local-Response-Time.jpg b/contents/Database/images/sql-index-performance/Local-Response-Time.jpg new file mode 100644 index 0000000..9cbeebd Binary files /dev/null and b/contents/Database/images/sql-index-performance/Local-Response-Time.jpg differ diff --git a/contents/Database/images/sql-index-performance/Proactive-Index-Design.jpg b/contents/Database/images/sql-index-performance/Proactive-Index-Design.jpg new file mode 100644 index 0000000..6b2bec3 Binary files /dev/null and b/contents/Database/images/sql-index-performance/Proactive-Index-Design.jpg differ diff --git a/contents/Database/images/sql-index-performance/QUBE-LRT.jpg b/contents/Database/images/sql-index-performance/QUBE-LRT.jpg new file mode 100644 index 0000000..7bd55cc Binary files /dev/null and b/contents/Database/images/sql-index-performance/QUBE-LRT.jpg differ diff --git a/contents/Database/images/sql-index-performance/SQL-Query-Time-After-Optimization.jpg b/contents/Database/images/sql-index-performance/SQL-Query-Time-After-Optimization.jpg new file mode 100644 index 0000000..bafe708 Binary files /dev/null and b/contents/Database/images/sql-index-performance/SQL-Query-Time-After-Optimization.jpg differ diff --git a/contents/Database/images/sql-index-performance/SQL-Query-Time.jpg b/contents/Database/images/sql-index-performance/SQL-Query-Time.jpg new file mode 100644 index 0000000..5b2b327 Binary files /dev/null and b/contents/Database/images/sql-index-performance/SQL-Query-Time.jpg differ diff --git a/contents/Database/images/sql-index-performance/Semifat-Index-and-Fat-Index.jpg b/contents/Database/images/sql-index-performance/Semifat-Index-and-Fat-Index.jpg new file mode 100644 index 0000000..0fb89ef Binary files /dev/null and b/contents/Database/images/sql-index-performance/Semifat-Index-and-Fat-Index.jpg differ diff --git a/contents/Database/images/sql-index-performance/User-Table.jpg b/contents/Database/images/sql-index-performance/User-Table.jpg new file mode 100644 index 0000000..79d4f0a Binary files /dev/null and b/contents/Database/images/sql-index-performance/User-Table.jpg differ diff --git a/contents/Database/images/transaction/ACID-And-CAP.jpg b/contents/Database/images/transaction/ACID-And-CAP.jpg new file mode 100644 index 0000000..78a48e4 Binary files /dev/null and b/contents/Database/images/transaction/ACID-And-CAP.jpg differ diff --git a/contents/Database/images/transaction/Atomic-Operation.jpg b/contents/Database/images/transaction/Atomic-Operation.jpg new file mode 100644 index 0000000..45ac6e7 Binary files /dev/null and b/contents/Database/images/transaction/Atomic-Operation.jpg differ diff --git a/contents/Database/images/transaction/Atomitc-Transaction-State.jpg b/contents/Database/images/transaction/Atomitc-Transaction-State.jpg new file mode 100644 index 0000000..eef883f Binary files /dev/null and b/contents/Database/images/transaction/Atomitc-Transaction-State.jpg differ diff --git a/contents/Database/images/transaction/Cascading-Rollback.jpg b/contents/Database/images/transaction/Cascading-Rollback.jpg new file mode 100644 index 0000000..e480da6 Binary files /dev/null and b/contents/Database/images/transaction/Cascading-Rollback.jpg differ diff --git a/contents/Database/images/transaction/Compensating-Transaction.jpg b/contents/Database/images/transaction/Compensating-Transaction.jpg new file mode 100644 index 0000000..8f22559 Binary files /dev/null and b/contents/Database/images/transaction/Compensating-Transaction.jpg differ diff --git a/contents/Database/images/transaction/Isolation-Performance.jpg b/contents/Database/images/transaction/Isolation-Performance.jpg new file mode 100644 index 0000000..c7c6f9d Binary files /dev/null and b/contents/Database/images/transaction/Isolation-Performance.jpg differ diff --git a/contents/Database/images/transaction/Logical-Undo-Log.jpg b/contents/Database/images/transaction/Logical-Undo-Log.jpg new file mode 100644 index 0000000..7ffb139 Binary files /dev/null and b/contents/Database/images/transaction/Logical-Undo-Log.jpg differ diff --git a/contents/Database/images/transaction/Nonatomitc-Transaction-State.jpg b/contents/Database/images/transaction/Nonatomitc-Transaction-State.jpg new file mode 100644 index 0000000..d863dab Binary files /dev/null and b/contents/Database/images/transaction/Nonatomitc-Transaction-State.jpg differ diff --git a/contents/Database/images/transaction/Nonrecoverable-Schedule.jpg b/contents/Database/images/transaction/Nonrecoverable-Schedule.jpg new file mode 100644 index 0000000..0459826 Binary files /dev/null and b/contents/Database/images/transaction/Nonrecoverable-Schedule.jpg differ diff --git a/contents/Database/images/transaction/Reasons-for-Allowing-Concurrency.jpg b/contents/Database/images/transaction/Reasons-for-Allowing-Concurrency.jpg new file mode 100644 index 0000000..68eca3e Binary files /dev/null and b/contents/Database/images/transaction/Reasons-for-Allowing-Concurrency.jpg differ diff --git a/contents/Database/images/transaction/Recoverable-Schedule.jpg b/contents/Database/images/transaction/Recoverable-Schedule.jpg new file mode 100644 index 0000000..8e5dec0 Binary files /dev/null and b/contents/Database/images/transaction/Recoverable-Schedule.jpg differ diff --git a/contents/Database/images/transaction/Redo-Logging.jpg b/contents/Database/images/transaction/Redo-Logging.jpg new file mode 100644 index 0000000..9165d12 Binary files /dev/null and b/contents/Database/images/transaction/Redo-Logging.jpg differ diff --git a/contents/Database/images/transaction/Shared-Exclusive-Lock.jpg b/contents/Database/images/transaction/Shared-Exclusive-Lock.jpg new file mode 100644 index 0000000..e85567b Binary files /dev/null and b/contents/Database/images/transaction/Shared-Exclusive-Lock.jpg differ diff --git a/contents/Database/images/transaction/Shared-Lock-and-Atomicity.jpg b/contents/Database/images/transaction/Shared-Lock-and-Atomicity.jpg new file mode 100644 index 0000000..19e2e93 Binary files /dev/null and b/contents/Database/images/transaction/Shared-Lock-and-Atomicity.jpg differ diff --git a/contents/Database/images/transaction/Shutdown-After-Commited.jpg b/contents/Database/images/transaction/Shutdown-After-Commited.jpg new file mode 100644 index 0000000..a939582 Binary files /dev/null and b/contents/Database/images/transaction/Shutdown-After-Commited.jpg differ diff --git a/contents/Database/images/transaction/Timestamps-Record.jpg b/contents/Database/images/transaction/Timestamps-Record.jpg new file mode 100644 index 0000000..a715b28 Binary files /dev/null and b/contents/Database/images/transaction/Timestamps-Record.jpg differ diff --git a/contents/Database/images/transaction/Transaction-Basics.jpg b/contents/Database/images/transaction/Transaction-Basics.jpg new file mode 100644 index 0000000..94b288f Binary files /dev/null and b/contents/Database/images/transaction/Transaction-Basics.jpg differ diff --git a/contents/Database/images/transaction/Transaction-Consistency.jpg b/contents/Database/images/transaction/Transaction-Consistency.jpg new file mode 100644 index 0000000..615a833 Binary files /dev/null and b/contents/Database/images/transaction/Transaction-Consistency.jpg differ diff --git a/contents/Database/images/transaction/Transaction-Cover.jpg b/contents/Database/images/transaction/Transaction-Cover.jpg new file mode 100644 index 0000000..851e7e2 Binary files /dev/null and b/contents/Database/images/transaction/Transaction-Cover.jpg differ diff --git a/contents/Database/images/transaction/Transaction-Isolation-Matrix.jpg b/contents/Database/images/transaction/Transaction-Isolation-Matrix.jpg new file mode 100644 index 0000000..3d5ccb2 Binary files /dev/null and b/contents/Database/images/transaction/Transaction-Isolation-Matrix.jpg differ diff --git a/contents/Database/images/transaction/Transaction-Log.jpg b/contents/Database/images/transaction/Transaction-Log.jpg new file mode 100644 index 0000000..45526f1 Binary files /dev/null and b/contents/Database/images/transaction/Transaction-Log.jpg differ diff --git a/contents/Database/images/transaction/Transaction-Undo-Log.jpg b/contents/Database/images/transaction/Transaction-Undo-Log.jpg new file mode 100644 index 0000000..cf5034f Binary files /dev/null and b/contents/Database/images/transaction/Transaction-Undo-Log.jpg differ diff --git a/contents/Database/leveldb-bigtable.md b/contents/Database/leveldb-bigtable.md new file mode 100644 index 0000000..c942086 --- /dev/null +++ b/contents/Database/leveldb-bigtable.md @@ -0,0 +1,469 @@ +![Bigtable-LevelDB-Cover](images/leveldb-bigtable/Bigtable-LevelDB-Cover.jpg) + +# 浅析 Bigtable 和 LevelDB 的实现 + +在 2006 年的 OSDI 上,Google 发布了名为 [Bigtable: A Distributed Storage System for Structured Data](https://static.googleusercontent.com/media/research.google.com/en//archive/bigtable-osdi06.pdf) 的论文,其中描述了一个用于管理结构化数据的分布式存储系统 - Bigtable 的数据模型、接口以及实现等内容。 + +![leveldb-logo](images/leveldb-bigtable/leveldb-logo.png) + +本文会先对 Bigtable 一文中描述的分布式存储系统进行简单的描述,然后对 Google 开源的 KV 存储数据库 [LevelDB](https://github.com/google/leveldb) 进行分析;LevelDB 可以理解为单点的 Bigtable 的系统,虽然其中没有 Bigtable 中与 tablet 管理以及一些分布式相关的逻辑,不过我们可以通过对 LevelDB 源代码的阅读增加对 Bigtable 的理解。 + +## Bigtable + +Bigtable 是一个用于管理**结构化数据**的分布式存储系统,它有非常优秀的扩展性,可以同时处理上千台机器中的 PB 级别的数据;Google 中的很多项目,包括 Web 索引都使用 Bigtable 来存储海量的数据;Bigtable 的论文中声称它实现了四个目标: + +![Goals-of-Bigtable](images/leveldb-bigtable/Goals-of-Bigtable.jpg) + +在作者看来这些目标看看就好,其实并没有什么太大的意义,所有的项目都会对外宣称它们达到了高性能、高可用性等等特性,我们需要关注的是 Bigtable 到底是如何实现的。 + +### 数据模型 + +Bigtable 与数据库在很多方面都非常相似,但是它提供了与数据库不同的接口,它并没有支持全部的关系型数据模型,反而使用了简单的数据模型,使数据可以被更灵活的控制和管理。 + +在实现中,Bigtable 其实就是一个稀疏的、分布式的、多维持久有序哈希。 + +> A Bigtable is a sparse, distributed, persistent multi-dimensional sorted map. + +它的定义其实也就决定了其数据模型非常简单并且易于实现,我们使用 `row`、`column` 和 `timestamp` 三个字段作为这个哈希的键,值就是一个字节数组,也可以理解为字符串。 + +![Bigtable-DataModel-Row-Column-Timestamp-Value](images/leveldb-bigtable/Bigtable-DataModel-Row-Column-Timestamp-Value.jpg) + +这里最重要的就是 `row` 的值,它的长度最大可以为 64KB,对于同一 `row` 下数据的读写都可以看做是原子的;因为 Bigtable 是按照 `row` 的值使用字典顺序进行排序的,每一段 `row` 的范围都会被 Bigtable 进行分区,并交给一个 tablet 进行处理。 + +### 实现 + +在这一节中,我们将介绍 Bigtable 论文对于其本身实现的描述,其中包含很多内容:tablet 的组织形式、tablet 的管理、读写请求的处理以及数据的压缩等几个部分。 + +#### tablet 的组织形式 + +我们使用类似 B+ 树的三层结构来存储 tablet 的位置信息,第一层是一个单独的 [Chubby](https://static.googleusercontent.com/media/research.google.com/en//archive/chubby-osdi06.pdf) 文件,其中保存了根 tablet 的位置。 + +> Chubby 是一个分布式锁服务,我们可能会在后面的文章中介绍它。 + +![Tablet-Location-Hierarchy](images/leveldb-bigtable/Tablet-Location-Hierarchy.jpg) + +每一个 METADATA tablet 包括根节点上的 tablet 都存储了 tablet 的位置和该 tablet 中 key 的最小值和最大值;每一个 METADATA 行大约在内存中存储了 1KB 的数据,如果每一个 METADATA tablet 的大小都为 128MB,那么整个三层结构可以存储 2^61 字节的数据。 + +#### tablet 的管理 + +既然在整个 Bigtable 中有着海量的 tablet 服务器以及数据的分片 tablet,那么 Bigtable 是如何管理海量的数据呢?Bigtable 与很多的分布式系统一样,使用一个主服务器将 tablet 分派给不同的服务器节点。 + +![Master-Manage-Tablet-Servers-And-Tablets](images/leveldb-bigtable/Master-Manage-Tablet-Servers-And-Tablets.jpg) + +为了减轻主服务器的负载,所有的客户端仅仅通过 Master 获取 tablet 服务器的位置信息,它并不会在每次读写时都请求 Master 节点,而是直接与 tablet 服务器相连,同时客户端本身也会保存一份 tablet 服务器位置的缓存以减少与 Master 通信的次数和频率。 + +#### 读写请求的处理 + +从读写请求的处理,我们其实可以看出整个 Bigtable 中的各个部分是如何协作的,包括日志、memtable 以及 SSTable 文件。 + +![Tablet-Serving](images/leveldb-bigtable/Tablet-Serving.jpg) + +当有客户端向 tablet 服务器发送写操作时,它会先向 tablet 服务器中的日志追加一条记录,在日志成功追加之后再向 memtable 中插入该条记录;这与现在大多的数据库的实现完全相同,通过顺序写向日志追加记录,然后再向数据库随机写,因为随机写的耗时远远大于追加内容,如果直接进行随机写,可能由于发生设备故障造成数据丢失。 + +当 tablet 服务器接收到读操作时,它会在 memtable 和 SSTable 上进行合并查找,因为 memtable 和 SSTable 中对于键值的存储都是字典顺序的,所以整个读操作的执行会非常快。 + +#### 表的压缩 + +随着写操作的进行,memtable 会随着事件的推移逐渐增大,当 memtable 的大小超过一定的阈值时,就会将当前的 memtable 冻结,并且创建一个新的 memtable,被冻结的 memtable 会被转换为一个 SSTable 并且写入到 GFS 系统中,这种压缩方式也被称作 *Minor Compaction*。 + +![Minor-Compaction](images/leveldb-bigtable/Minor-Compaction.jpg) + +每一个 Minor Compaction 都能够创建一个新的 SSTable,它能够有效地降低内存的占用并且降低服务进程异常退出后,过大的日志导致的过长的恢复时间。既然有用于压缩 memtable 中数据的 Minor Compaction,那么就一定有一个对应的 Major Compaction 操作。 + +![Major-Compaction](images/leveldb-bigtable/Major-Compaction.jpg) + +Bigtable 会在**后台周期性**地进行 *Major Compaction*,将 memtable 中的数据和一部分的 SSTable 作为输入,将其中的键值进行归并排序,生成新的 SSTable 并移除原有的 memtable 和 SSTable,新生成的 SSTable 中包含前两者的全部数据和信息,并且将其中一部分标记未删除的信息彻底清除。 + +#### 小结 + +到这里为止,对于 Google 的 Bigtable 论文的介绍就差不多完成了,当然本文只介绍了其中的一部分内容,关于压缩算法的实现细节、缓存以及提交日志的实现等问题我们都没有涉及,想要了解更多相关信息的读者,这里强烈推荐去看一遍 Bigtable 这篇论文的原文 [Bigtable: A Distributed Storage System for Structured Data](https://static.googleusercontent.com/media/research.google.com/en//archive/bigtable-osdi06.pdf) 以增强对其实现的理解。 + +## LevelDB + +文章前面对于 Bigtable 的介绍其实都是对 [LevelDB](https://github.com/google/leveldb) 这部分内容所做的铺垫,当然这并不是说前面的内容就不重要,LevelDB 是对 Bigtable 论文中描述的键值存储系统的单机版的实现,它提供了一个极其高速的键值存储系统,并且由 Bigtable 的作者 [Jeff Dean](https://research.google.com/pubs/jeff.html) 和 [Sanjay Ghemawat](https://research.google.com/pubs/SanjayGhemawat.html) 共同完成,可以说高度复刻了 Bigtable 论文中对于其实现的描述。 + +因为 Bigtable 只是一篇论文,同时又因为其实现依赖于 Google 的一些不开源的基础服务:GFS、Chubby 等等,我们很难接触到它的源代码,不过我们可以通过 LevelDB 更好地了解这篇论文中提到的诸多内容和思量。 + +### 概述 + +LevelDB 作为一个键值存储的『仓库』,它提供了一组非常简单的增删改查接口: + +```cpp +class DB { + public: + virtual Status Put(const WriteOptions& options, const Slice& key, const Slice& value) = 0; + virtual Status Delete(const WriteOptions& options, const Slice& key) = 0; + virtual Status Write(const WriteOptions& options, WriteBatch* updates) = 0; + virtual Status Get(const ReadOptions& options, const Slice& key, std::string* value) = 0; +} +``` + +> `Put` 方法在内部最终会调用 `Write` 方法,只是在上层为调用者提供了两个不同的选择。 + +`Get` 和 `Put` 是 LevelDB 为上层提供的用于读写的接口,如果我们能够对读写的过程有一个非常清晰的认知,那么理解 LevelDB 的实现就不是那么困难了。 + +在这一节中,我们将先通过对读写操作的分析了解整个工程中的一些实现,并在遇到问题和新的概念时进行解释,我们会在这个过程中一步一步介绍 LevelDB 中一些重要模块的实现以达到掌握它的原理的目标。 + +### 从写操作开始 + +首先来看 `Get` 和 `Put` 两者中的写方法: + +```cpp +Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) { + WriteBatch batch; + batch.Put(key, value); + return Write(opt, &batch); +} + +Status DBImpl::Write(const WriteOptions& options, WriteBatch* my_batch) { + ... +} +``` + +正如上面所介绍的,`DB::Put` 方法将传入的参数封装成了一个 `WritaBatch`,然后仍然会执行 `DBImpl::Write` 方法向数据库中写入数据;写入方法 `DBImpl::Write` 其实是一个是非常复杂的过程,包含了很多对上下文状态的判断,我们先来看一个写操作的整体逻辑: + +![LevelDB-Put](images/leveldb-bigtable/LevelDB-Put.jpg) + +从总体上看,LevelDB 在对数据库执行写操作时,会有三个步骤: + +1. 调用 `MakeRoomForWrite` 方法为即将进行的写入提供足够的空间; + + 在这个过程中,由于 memtable 中空间的不足可能会冻结当前的 memtable,发生 Minor Compaction 并创建一个新的 `MemTable` 对象; + + 在某些条件满足时,也可能发生 Major Compaction,对数据库中的 SSTable 进行压缩; +2. 通过 `AddRecord` 方法向日志中追加一条写操作的记录; +3. 再向日志成功写入记录后,我们使用 `InsertInto` 直接插入 memtable 中,完成整个写操作的流程; + +在这里,我们并不会提供 LevelDB 对于 `Put` 方法实现的全部代码,只会展示一份精简后的代码,帮助我们大致了解一下整个写操作的流程: + +```cpp +Status DBImpl::Write(const WriteOptions& options, WriteBatch* my_batch) { + Writer w(&mutex_); + w.batch = my_batch; + + MakeRoomForWrite(my_batch == NULL); + + uint64_t last_sequence = versions_->LastSequence(); + Writer* last_writer = &w; + WriteBatch* updates = BuildBatchGroup(&last_writer); + WriteBatchInternal::SetSequence(updates, last_sequence + 1); + last_sequence += WriteBatchInternal::Count(updates); + + log_->AddRecord(WriteBatchInternal::Contents(updates)); + WriteBatchInternal::InsertInto(updates, mem_); + + versions_->SetLastSequence(last_sequence); + return Status::OK(); +} +``` + +#### 不可变的 memtable + +在写操作的实现代码 `DBImpl::Put` 中,写操作的准备过程 `MakeRoomForWrite` 是我们需要注意的一个方法: + +```cpp +Status DBImpl::MakeRoomForWrite(bool force) { + uint64_t new_log_number = versions_->NewFileNumber(); + WritableFile* lfile = NULL; + env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile); + + delete log_; + delete logfile_; + logfile_ = lfile; + logfile_number_ = new_log_number; + log_ = new log::Writer(lfile); + imm_ = mem_; + has_imm_.Release_Store(imm_); + mem_ = new MemTable(internal_comparator_); + mem_->Ref(); + MaybeScheduleCompaction(); + return Status::OK(); +} +``` + +当 LevelDB 中的 memtable 已经被数据填满导致内存已经快不够用的时候,我们会开始对 memtable 中的数据进行冻结并创建一个新的 `MemTable` 对象。 + +![Immutable-MemTable](images/leveldb-bigtable/Immutable-MemTable.jpg) + +你可以看到,与 Bigtable 中论文不同的是,LevelDB 中引入了一个不可变的 memtable 结构 imm,它的结构与 memtable 完全相同,只是其中的所有数据都是不可变的。 + +![LevelDB-Serving](images/leveldb-bigtable/LevelDB-Serving.jpg) + +在切换到新的 memtable 之后,还可能会执行 `MaybeScheduleCompaction` 来触发一次 Minor Compaction 将 imm 中数据固化成数据库中的 SSTable;imm 的引入能够解决由于 memtable 中数据过大导致压缩时不可写入数据的问题。 + +引入 imm 后,如果 memtable 中的数据过多,我们可以直接将 memtable 指针赋值给 imm,然后创建一个新的 MemTable 实例,这样就可以继续接受外界的写操作,不再需要等待 Minor Compaction 的结束了。 + +#### 日志记录的格式 + +作为一个持久存储的 KV 数据库,LevelDB 一定要有日志模块以支持错误发生时恢复数据,我们想要深入了解 LevelDB 的实现,那么日志的格式是一定绕不开的问题;这里并不打算展示用于追加日志的方法 `AddRecord` 的实现,因为方法中只是实现了对表头和字符串的拼接。 + +日志在 LevelDB 是以块的形式存储的,每一个块的长度都是 32KB,**固定的块长度**也就决定了日志可能存放在块中的任意位置,LevelDB 中通过引入一位 `RecordType` 来表示当前记录在块中的位置: + +```cpp +enum RecordType { + // Zero is reserved for preallocated files + kZeroType = 0, + kFullType = 1, + // For fragments + kFirstType = 2, + kMiddleType = 3, + kLastType = 4 +}; +``` + +日志记录的类型存储在该条记录的头部,其中还存储了 4 字节日志的 CRC 校验、记录的长度等信息: + +![LevelDB-log-format-and-recordtype](images/leveldb-bigtable/LevelDB-log-format-and-recordtype.jpg) + +上图中一共包含 4 个块,其中存储着 6 条日志记录,我们可以通过 `RecordType` 对每一条日志记录或者日志记录的一部分进行标记,并在日志需要使用时通过该信息重新构造出这条日志记录。 + +```cpp +virtual Status Sync() { + Status s = SyncDirIfManifest(); + if (fflush_unlocked(file_) != 0 || + fdatasync(fileno(file_)) != 0) { + s = Status::IOError(filename_, strerror(errno)); + } + return s; +} +``` + +因为向日志中写新记录都是顺序写的,所以它写入的速度非常快,当在内存中写入完成时,也会直接将缓冲区的这部分的内容 `fflush` 到磁盘上,实现对记录的持久化,用于之后的错误恢复等操作。 + +#### 记录的插入 + +当一条数据的记录写入日志时,这条记录仍然无法被查询,只有当该数据写入 memtable 后才可以被查询,而这也是这一节将要介绍的内容,无论是数据的插入还是数据的删除都会向 memtable 中添加一条记录。 + +![LevelDB-Memtable-Key-Value-Format](images/leveldb-bigtable/LevelDB-Memtable-Key-Value-Format.jpg) + +添加和删除的记录的区别就是它们使用了不用的 `ValueType` 标记,插入的数据会将其设置为 `kTypeValue`,删除的操作会标记为 `kTypeDeletion`;但是它们实际上都向 memtable 中插入了一条数据。 + +```cpp +virtual void Put(const Slice& key, const Slice& value) { + mem_->Add(sequence_, kTypeValue, key, value); + sequence_++; +} +virtual void Delete(const Slice& key) { + mem_->Add(sequence_, kTypeDeletion, key, Slice()); + sequence_++; +} +``` + +我们可以看到它们都调用了 memtable 的 `Add` 方法,向其内部的数据结构 skiplist 以上图展示的格式插入数据,这条数据中既包含了该记录的键值、序列号以及这条记录的种类,这些字段会在拼接后存入 skiplist;既然我们并没有在 memtable 中对数据进行删除,那么我们是如何保证每次取到的数据都是最新的呢?首先,在 skiplist 中,我们使用了自己定义的一个 `comparator`: + +```cpp +int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const { + int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey)); + if (r == 0) { + const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8); + const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8); + if (anum > bnum) { + r = -1; + } else if (anum < bnum) { + r = +1; + } + } + return r; +} +``` + +> 比较的两个 key 中的数据可能包含的内容都不完全相同,有的会包含键值、序列号等全部信息,但是例如从 `Get` 方法调用过来的 key 中可能就只包含键的长度、键值和序列号了,但是这并不影响这里对数据的提取,因为我们只从每个 key 的头部提取信息,所以无论是完整的 key/value 还是单独的 key,我们都不会取到 key 之外的任何数据。 + +该方法分别从两个不同的 key 中取出键和序列号,然后对它们进行比较;比较的过程就是使用 `InternalKeyComparator` 比较器,它通过 `user_key` 和 `sequence_number` 进行排序,其中 `user_key` 按照递增的顺序排序、`sequence_number` 按照递减的顺序排序,因为随着数据的插入序列号是不断递增的,所以我们可以保证先取到的都是最新的数据或者删除信息。 + +![LevelDB-MemTable-SkipList](images/leveldb-bigtable/LevelDB-MemTable-SkipList.jpg) + +在序列号的帮助下,我们并不需要对历史数据进行删除,同时也能加快写操作的速度,提升 LevelDB 的写性能。 + +### 数据的读取 + +从 LevelDB 中读取数据其实并不复杂,memtable 和 imm 更像是两级缓存,它们在内存中提供了更快的访问速度,如果能直接从内存中的这两处直接获取到响应的值,那么它们一定是最新的数据。 + +> LevelDB 总会将新的键值对写在最前面,并在数据压缩时删除历史数据。 + +![LevelDB-Read-Processes](images/leveldb-bigtable/LevelDB-Read-Processes.jpg) + +数据的读取是按照 MemTable、Immutable MemTable 以及不同层级的 SSTable 的顺序进行的,前两者都是在内存中,后面不同层级的 SSTable 都是以 `*.ldb` 文件的形式持久存储在磁盘上,而正是因为有着不同层级的 SSTable,所以我们的数据库的名字叫做 LevelDB。 + +精简后的读操作方法的实现代码是这样的,方法的脉络非常清晰,作者相信这里也不需要过多的解释: + +```cpp +Status DBImpl::Get(const ReadOptions& options, const Slice& key, std::string* value) { + LookupKey lkey(key, versions_->LastSequence()); + if (mem_->Get(lkey, value, NULL)) { + // Done + } else if (imm_ != NULL && imm_->Get(lkey, value, NULL)) { + // Done + } else { + versions_->current()->Get(options, lkey, value, NULL); + } + + MaybeScheduleCompaction(); + return Status::OK(); +} +``` + +当 LevelDB 在 memtable 和 imm 中查询到结果时,如果查询到了数据并不一定表示当前的值一定存在,它仍然需要判断 `ValueType` 来确定当前记录是否被删除。 + +#### 多层级的 SSTable + +当 LevelDB 在内存中没有找到对应的数据时,它才会到磁盘中多个层级的 SSTable 中进行查找,这个过程就稍微有一点复杂了,LevelDB 会在多个层级中逐级进行查找,并且不会跳过其中的任何层级;在查找的过程就涉及到一个非常重要的数据结构 `FileMetaData`: + +![FileMetaData](images/leveldb-bigtable/FileMetaData.jpg) + +`FileMetaData` 中包含了整个文件的全部信息,其中包括键的最大值和最小值、允许查找的次数、文件被引用的次数、文件的大小以及文件号,因为所有的 `SSTable` 都是以固定的形式存储在同一目录下的,所以我们可以通过文件号轻松查找到对应的文件。 + +![LevelDB-Level0-Laye](images/leveldb-bigtable/LevelDB-Level0-Layer.jpg) + +查找的顺序就是从低到高了,LevelDB 首先会在 Level0 中查找对应的键。但是,与其他层级不同,Level0 中多个 SSTable 的键的范围有重合部分的,在查找对应值的过程中,会依次查找 Level0 中固定的 4 个 SSTable。 + +![LevelDB-LevelN-Layers](images/leveldb-bigtable/LevelDB-LevelN-Layers.jpg) + +但是当涉及到更高层级的 SSTable 时,因为同一层级的 SSTable 都是没有重叠部分的,所以我们在查找时可以利用已知的 SSTable 中的极值信息 `smallest/largest` 快速查找到对应的 SSTable,再判断当前的 SSTable 是否包含查询的 key,如果不存在,就继续查找下一个层级直到最后的一个层级 `kNumLevels`(默认为 7 级)或者查询到了对应的值。 + +#### SSTable 的『合并』 + +既然 LevelDB 中的数据是通过多个层级的 SSTable 组织的,那么它是如何对不同层级中的 SSTable 进行合并和压缩的呢;与 Bigtable 论文中描述的两种 Compaction 几乎完全相同,LevelDB 对这两种压缩的方式都进行了实现。 + +无论是读操作还是写操作,在执行的过程中都可能调用 `MaybeScheduleCompaction` 来尝试对数据库中的 SSTable 进行合并,当合并的条件满足时,最终都会执行 `BackgroundCompaction` 方法在后台完成这个步骤。 + +![LevelDB-BackgroundCompaction-Processes](images/leveldb-bigtable/LevelDB-BackgroundCompaction-Processes.jpg) + +这种合并分为两种情况,一种是 Minor Compaction,即内存中的数据超过了 memtable 大小的最大限制,改 memtable 被冻结为不可变的 imm,然后执行方法 `CompactMemTable()` 对内存表进行压缩。 + +```cpp +void DBImpl::CompactMemTable() { + VersionEdit edit; + Version* base = versions_->current(); + WriteLevel0Table(imm_, &edit, base); + versions_->LogAndApply(&edit, &mutex_); + DeleteObsoleteFiles(); +} +``` + +`CompactMemTable` 会执行 `WriteLevel0Table` 将当前的 imm 转换成一个 Level0 的 SSTable 文件,同时由于 Level0 层级的文件变多,可能会继续触发一个新的 Major Compaction,在这里我们就需要在这里选择需要压缩的合适的层级: + +```cpp +Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit, Version* base) { + FileMetaData meta; + meta.number = versions_->NewFileNumber(); + Iterator* iter = mem->NewIterator(); + BuildTable(dbname_, env_, options_, table_cache_, iter, &meta); + + const Slice min_user_key = meta.smallest.user_key(); + const Slice max_user_key = meta.largest.user_key(); + int level = base->PickLevelForMemTableOutput(min_user_key, max_user_key); + edit->AddFile(level, meta.number, meta.file_size, meta.smallest, meta.largest); + return Status::OK(); +} +``` + +所有对当前 SSTable 数据的修改由一个统一的 `VersionEdit` 对象记录和管理,我们会在后面介绍这个对象的作用和实现,如果成功写入了就会返回这个文件的元数据 `FileMetaData`,最后调用 `VersionSet` 的方法 `LogAndApply` 将文件中的全部变化如实记录下来,最后做一些数据的清理工作。 + +当然如果是 Major Compaction 就稍微有一些复杂了,不过整理后的 `BackgroundCompaction` 方法的逻辑非常清晰: + +```cpp +void DBImpl::BackgroundCompaction() { + if (imm_ != NULL) { + CompactMemTable(); + return; + } + + Compaction* c = versions_->PickCompaction(); + CompactionState* compact = new CompactionState(c); + DoCompactionWork(compact); + CleanupCompaction(compact); + DeleteObsoleteFiles(); +} +``` + +我们从当前的 `VersionSet` 中找到需要压缩的文件信息,将它们打包存入一个 `Compaction` 对象,该对象需要选择两个层级的 SSTable,低层级的表很好选择,只需要选择大小超过限制的或者查询次数太多的 SSTable;当我们选择了低层级的一个 SSTable 后,就在更高的层级选择与该 SSTable 有重叠键的 SSTable 就可以了,通过 `FileMetaData` 中数据的帮助我们可以很快找到待压缩的全部数据。 + +> 查询次数太多的意思就是,当客户端调用多次 `Get` 方法时,如果这次 `Get` 方法在某个层级的 SSTable 中找到了对应的键,那么就算做上一层级中包含该键的 SSTable 的一次查找,也就是这次查找由于不同层级键的覆盖范围造成了更多的耗时,每个 SSTable 在创建之后的 `allowed_seeks` 都为 100 次,当 `allowed_seeks < 0` 时就会触发该文件的与更高层级和合并,以减少以后查询的查找次数。 + +![LevelDB-Pick-Compactions](images/leveldb-bigtable/LevelDB-Pick-Compactions.jpg) + +LevelDB 中的 `DoCompactionWork` 方法会对所有传入的 SSTable 中的键值使用归并排序进行合并,最后会在高高层级(图中为 Level2)中生成一个新的 SSTable。 + +![LevelDB-After-Compactions](images/leveldb-bigtable/LevelDB-After-Compactions.jpg) + +这样下一次查询 17~40 之间的值时就可以减少一次对 SSTable 中数据的二分查找以及读取文件的时间,提升读写的性能。 + +#### 存储 db 状态的 VersionSet + +LevelDB 中的所有状态其实都是被一个 `VersionSet` 结构所存储的,一个 `VersionSet` 包含一组 `Version` 结构体,所有的 `Version` 包括历史版本都是通过双向链表连接起来的,但是只有一个版本是当前版本。 + +![VersionSet-Version-And-VersionEdit](images/leveldb-bigtable/VersionSet-Version-And-VersionEdit.jpg) + +当 LevelDB 中的 SSTable 发生变动时,它会生成一个 `VersionEdit` 结构,最终执行 `LogAndApply` 方法: + +```cpp +Status VersionSet::LogAndApply(VersionEdit* edit, port::Mutex* mu) { + Version* v = new Version(this); + Builder builder(this, current_); + builder.Apply(edit); + builder.SaveTo(v); + + std::string new_manifest_file; + new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_); + env_->NewWritableFile(new_manifest_file, &descriptor_file_); + + std::string record; + edit->EncodeTo(&record); + descriptor_log_->AddRecord(record); + descriptor_file_->Sync(); + + SetCurrentFile(env_, dbname_, manifest_file_number_); + AppendVersion(v); + + return Status::OK(); +} +``` + +该方法的主要工作是使用当前版本和 `VersionEdit` 创建一个新的版本对象,然后将 `Version` 的变更追加到 MANIFEST 日志中,并且改变数据库中全局当前版本信息。 + +> MANIFEST 文件中记录了 LevelDB 中所有层级中的表、每一个 SSTable 的 Key 范围和其他重要的元数据,它以日志的格式存储,所有对文件的增删操作都会追加到这个日志中。 + +#### SSTable 的格式 + +SSTable 中其实存储的不只是数据,其中还保存了一些元数据、索引等信息,用于加速读写操作的速度,虽然在 Bigtable 的论文中并没有给出 SSTable 的数据格式,不过在 LevelDB 的实现中,我们可以发现 SSTable 是以这种格式存储数据的: + +![SSTable-Format](images/leveldb-bigtable/SSTable-Format.jpg) + +当 LevelDB 读取 SSTable 存在的 `ldb` 文件时,会先读取文件中的 `Footer` 信息。 + +![SSTable-Foote](images/leveldb-bigtable/SSTable-Footer.jpg) + +整个 `Footer` 在文件中占用 48 个字节,我们能在其中拿到 MetaIndex 块和 Index 块的位置,再通过其中的索引继而找到对应值存在的位置。 + +`TableBuilder::Rep` 结构体中就包含了一个文件需要创建的全部信息,包括数据块、索引块等等: + +```cpp +struct TableBuilder::Rep { + WritableFile* file; + uint64_t offset; + BlockBuilder data_block; + BlockBuilder index_block; + std::string last_key; + int64_t num_entries; + bool closed; + FilterBlockBuilder* filter_block; + ... +} +``` + +到这里,我们就完成了对整个数据读取过程的解析了;对于读操作,我们可以理解为 LevelDB 在它内部的『多级缓存』中依次查找是否存在对应的键,如果存在就会直接返回,唯一与缓存不同可能就是,在数据『命中』后,它并不会把数据移动到更近的地方,而是会把数据移到更远的地方来减少下一次的访问时间,虽然这么听起来却是不可思议,不过仔细想一下确实是这样。 + +## 小结 + +在这篇文章中,我们通过对 LevelDB 源代码中读写操作的分析,了解了整个框架的绝大部分实现细节,包括 LevelDB 中存储数据的格式、多级 SSTable、如何进行合并以及管理版本等信息,不过由于篇幅所限,对于其中的一些问题并没有展开详细地进行介绍和分析,例如错误恢复以及缓存等问题;但是对 LevelDB 源代码的阅读,加深了我们对 Bigtable 论文中描述的分布式 KV 存储数据库的理解。 + +LevelDB 的源代码非常易于阅读,也是学习 C++ 语言非常优秀的资源,如果对文章的内容有疑问,可以翻墙后在博客下面的 Disqus 中留言。 + +## Reference + ++ [Bigtable: A Distributed Storage System for Structured Data](https://static.googleusercontent.com/media/research.google.com/en//archive/bigtable-osdi06.pdf) ++ [LevelDB](https://github.com/google/leveldb) ++ [The Chubby lock service for loosely-coupled distributed systems](https://static.googleusercontent.com/media/research.google.com/en//archive/chubby-osdi06.pdf) ++ [LevelDB · Impl](https://github.com/google/leveldb/blob/master/doc/impl.md) ++ [leveldb 中的 SSTable](http://bean-li.github.io/leveldb-sstable/) + + diff --git a/contents/Database/mongodb-to-mysql.md b/contents/Database/mongodb-to-mysql.md new file mode 100644 index 0000000..ab97b5e --- /dev/null +++ b/contents/Database/mongodb-to-mysql.md @@ -0,0 +1,441 @@ +# 如何从 MongoDB 迁移到 MySQL + +最近的一个多月时间其实都在做数据库的迁移工作,我目前在开发的项目其实在上古时代是使用 MySQL 作为主要数据库的,后来由于一些业务上的原因从 MySQL 迁移到了 MongoDB,使用了几个月的时间后,由于数据库服务非常不稳定,再加上无人看管,同时 MongoDB 本身就是无 Schema 的数据库,最后导致数据库的脏数据问题非常严重。目前团队的成员没有较为丰富的 Rails 开发经验,所以还是希望使用 ActiveRecord 加上 Migration 的方式对数据进行一些强限制,保证数据库中数据的合法。 + +![mysql-and-mongodb](images/mongodb-to-mysql/mysql-and-mongodb.png) + +文中会介绍作者在迁移数据库的过程中遇到的一些问题,并为各位读者提供需要**停机**迁移数据库的可行方案,如果需要不停机迁移数据库还是需要别的方案来解决,在这里提供的方案用于百万数据量的 MongoDB,预计的停机时间在两小时左右,如果数据量在千万级别以上,过长的停机时间可能是无法接受的,应该设计不停机的迁移方案;无论如何,作者希望这篇文章能够给想要做数据库迁移的开发者带来一些思路,少走一些坑。 + +## 从关系到文档 + +虽然这篇文章的重点是从 MongoDB 迁移到 MySQL,但是作者还是想简单提一下从 MySQL 到 MongoDB 的迁移,如果我们仅仅是将 MySQL 中的全部数据导入到 MongoDB 中其实是一间比较简单的事情,其中最重要的原因就是 **MySQL 支持的数据类型是 MongoDB 的子集**: + +![mongodb-mysql-datatype-relation](images/mongodb-to-mysql/mongodb-mysql-datatype-relation.png) + +在迁移的过程中可以将 MySQL 中的全部数据以 csv 的格式导出,然后再将所有 csv 格式的数据使用 `mongoimport` 全部导入到 MongoDB 中: + +``` +$ mysqldump -u<username> -p<password> \ + -T <output_directory> \ + --fields-terminated-by ',' \ + --fields-enclosed-by '\"' \ + --fields-escaped-by '\' \ + --no-create-info <database_name> + +$ mongoimport --db <database_name> --collection <collection_name> \ + --type csv \ + --file <data.csv> \ + --headerline +``` + +虽然整个过程看起来只需要两个命令非常简单,但是等到你真要去做的时候你会遇到非常多的问题,作者没有过从 MySQL 或者其他关系型数据库迁移到 MongoDB 的经验,但是 Google 上相关的资料特别多,所以这总是一个有无数前人踩过坑的问题,而前人的经验也能够帮助我们节省很多时间。 + +![mysql-to-mongodb](images/mongodb-to-mysql/mysql-to-mongodb.png) + +> 使用 csv 的方式导出数据在绝大多数的情况都不会出现问题,但是如果数据库中的某些文档中存储的是富文本,那么虽然在导出数据时不会出现问题,最终导入时可能出现一些比较奇怪的错误。 + +## 从文档到关系 + +相比于从 MySQL 到 MongoDB 的迁移,反向的迁移就麻烦了不止一倍,这主要是因为 MongoDB 中的很多数据类型和集合之间的关系在 MySQL 中都并不存在,比如嵌入式的数据结构、数组和哈希等集合类型、多对多关系的实现,很多的问题都不是仅仅能通过数据上的迁移解决的,我们需要在对数据进行迁移之前先对部分数据结构进行重构,本文中的后半部分会介绍需要处理的数据结构和逻辑。 + +![mongodb-mysql-problems-to-be-solved](images/mongodb-to-mysql/mongodb-mysql-problems-to-be-solved.png) + +当我们准备将数据库彻底迁移到 MySQL 之前,需要做一些准备工作,将最后迁移所需要的工作尽可能地减少,保证停机的时间不会太长,准备工作的目标就是尽量消灭工程中复杂的数据结构。 + +### 数据的预处理 + +在进行迁移之前要做很多准备工作,第一件事情是要把所有嵌入的数据结构改成非嵌入式的数据结构: + +![embedded-reference-documents](images/mongodb-to-mysql/embedded-reference-documents.png) + +也就是把所有 `embeds_many` 和 `embeds_one` 的关系都改成 `has_many` 和 `has_one`,同时将 `embedded_in` 都替换成 `belongs_to`,同时我们需要将工程中对应的测试都改成这种引用的关系,然而只改变代码中的关系并没有真正改变 MongoDB 中的数据。 + +```ruby +def embeds_many_to_has_many(parent, child) + child_key_name = child.to_s.underscore.pluralize + parent.collection.find({}).each do |parent_document| + next unless parent_document[child_key_name] + parent_document[child_key_name].each do |child_document| + new_child = child_document.merge "#{parent.to_s.underscore}_id": parent_document['_id'] + child.collection.insert_one new_child + end + end + parent.all.unset(child_key_name.to_sym) +end + +embeds_many_to_has_many(Person, Address) +``` + +我们可以使用上述的代码将关系为嵌入的模型都转换成引用,拍平所有复杂的数据关系,这段代码的运行时间与嵌入关系中的两个模型的数量有关,需要注意的是,MongoDB 中嵌入模型的数据可能因为某些原因出现相同的 `_id` 在插入时会发生冲突导致崩溃,你可以对 `insert_one` 使用 `resuce` 来保证这段代码的运行不会因为上述原因而停止。 + +![embedded-to-reference](images/mongodb-to-mysql/embedded-to-reference.png) + +通过这段代码我们就可以轻松将原有的嵌入关系全部展开变成引用的关系,将嵌入的关系变成引用除了做这两个改变之外,不需要做其他的事情,无论是数据的查询还是模型的创建都不需要改变代码的实现,不过记得为子模型中父模型的外键**添加索引**,否则会导致父模型在获取自己持有的全部子模型时造成**全表扫描**: + +```ruby +class Comment + include Mongoid::Document + index post_id: 1 + belongs_to :post +end +``` + +在处理了 MongoDB 中独有的嵌入式关系之后,我们就需要解决一些复杂的集合类型了,比如数组和哈希,如果我们使用 MySQL5.7 或者 PostgreSQL 的话,其实并不需要对他们进行处理,因为最新版本的 MySQL 和 PostgreSQL 已经提供了对 JSON 的支持,不过作者还是将项目中的数组和哈希都变成了常见的数据结构。 + +在这个可选的过程中,其实并没有什么标准答案,我们可以根据需要将不同的数据转换成不同的数据结构: + +![array-to-string-or-relation](images/mongodb-to-mysql/array-to-string-or-relation.png) + +比如,将数组变成字符串或者一对多关系,将哈希变成当前文档的键值对等等,如何处理这些集合数据其实都要看我们的业务逻辑,在改变这些字段的同时尽量为上层提供一个与原来直接 `.tags` 或者 `.categories` 结果相同的 API: + +```ruby +class Post + ... + def tag_titles + tags.map(&:title) + end + + def split_categories + categories.split(',') + end +end +``` + +这一步其实也是可选的,上述代码只是为了减少其他地方的修改负担,当然如果你想使用 MySQL5.7 或者 PostgreSQL 数据库对 JSON 的支持也没有什么太大的问题,只是在查询集合字段时有一些不方便。 + +### Mongoid 的『小兄弟』们 + +在使用 Mongoid 进行开发期间难免会用到一些相关插件,比如 [mongoid-enum](https://github.com/thetron/mongoid-enum)、[mongoid-slug](https://github.com/mongoid/mongoid-slug) 和 [mongoid-history](https://github.com/mongoid/mongoid-history) 等,这些插件的实现与 ActiveRecord 中具有相同功能的插件在实现上有很大的不同。 + +对于有些插件,比如 mongoid-slug 只是在引入插件的模型的文档中插入了 `_slugs` 字段,我们只需要在进行数据迁移忽略这些添加的字段并将所有的 `#slug` 方法改成 `#id`,不需要在预处理的过程中做其它的改变。而枚举的实现在 Mongoid 的插件和 ActiveRecord 中就截然不同了: + +![mongodb-mysql-enu](images/mongodb-to-mysql/mongodb-mysql-enum.png) + +mongoid-enum 使用字符串和 `_status` 来保存枚举类型的字段,而 ActiveRecord 使用整数和 `status` 表示枚举类型,两者在底层数据结构的存储上有一些不同,我们会在之后的迁移脚本中解决这个问题。 + +![mongoid-activerecord-enum](images/mongodb-to-mysql/mongoid-activerecord-enum.png) + +如果在项目中使用了很多 Mongoid 的插件,由于其实现不同,我们也只能根据不同的插件的具体实现来决定如何对其进行迁移,如果使用了一些支持特殊功能的插件可能很难在 ActiveRecord 中找到对应的支持,在迁移时可以考虑暂时将部分不重要的功能移除。 + +### 主键与 UUID + +我们希望从 MongoDB 迁移到 MySQL 的另一个重要原因就是 MongoDB 每一个文档的主键实在是太过冗长,一个 32 字节的 `_id` 无法给我们提供特别多的信息,只能增加我们的阅读障碍,再加上项目中并没有部署 MongoDB 集群,所以没能享受到用默认的 UUID 生成机制带来的好处。 + +![mongodb-mysql-id](images/mongodb-to-mysql/mongodb-mysql-id.png) + +我们不仅没有享受到 UUID 带来的有点,它还在迁移 MySQL 的过程中为我们带来了很大的麻烦,一方面是因为 ActiveRecord 的默认主键是整数,不支持 32 字节长度的 UUID,如果我们想要不改变 MongoDB 的 UUID,直接迁移到 MySQL 中使用其实也没有什么问题,只是我们要将默认的整数类型的主键变成字符串类型,同时要使用一个 UUID 生成器来保证所有的主键都是根据时间递增的并且不会冲突。 + +如果准备使用 UUID 加生成器的方式,其实会省去很多迁移的时间,不过看起来确实不是特别的优雅,如何选择还是要权衡和评估,但是如果我们选择了使用 `integer` 类型的自增主键时,就需要做很多额外的工作了,首先是为所有的表添加 `uuid` 字段,同时为所有的外键例如 `post_id` 创建对应的 `post_uuid` 字段,通过 `uuid` 将两者关联起来: + +![mysql-before-migrations](images/mongodb-to-mysql/mysql-before-migrations.png) + +在数据的迁移过程中,我们会将原有的 `_id` 映射到 `uuid` 中,`post_id` 映射到 `post_uuid` 上,我们通过保持 `uuid` 和 `post_uuid` 之间的关系保证模型之间的关系没有丢失,在迁移数据的过程中 `id` 和 `post_id` 是完全不存在任何联系的。 + +当我们按照 `_id` 的顺序遍历整个文档,将文档中的数据被插入到表中时,MySQL 会为所有的数据行自动生成的递增的主键 `id`,而 `post_id` 在这时都为空。 + +![mysql-after-migrations](images/mongodb-to-mysql/mysql-after-migrations.png) + +在全部的数据都被插入到 MySQL 之后,我们通过 `#find_by_uuid` 查询的方式将 `uuid` 和 `post_uuid` 中的关系迁移到 `id` 和 `post_id` 中,并将与 `uuid` 相关的字段全部删除,这样我们能够保证模型之间的关系不会消失,并且数据行的相对位置与迁移前完全一致。 + +### 代码的迁移 + +Mongoid 在使用时都是通过 `include` 将相关方法加载到当前模型中的,而 ActiveRecord 是通过继承 `ActiveRecord::Base` 的方式使用的,完成了对数据的预处理,我们就可以对现有模型层的代码进行修改了。 + +首先当然是更改模型的『父类』,把所有的 `Mongoid::Document` 都改成 `ActiveRecord::Base`,然后创建类对应的 Migration 迁移文件: + +```ruby +# app/models/post.rb +class Post < ActiveRecord::Base + validate_presence_of :title, :content +end + +# db/migrate/20170908075625_create_posts.rb +class CreatePosts < ActiveRecord::Migration[5.1] + def change + create_table :posts do |t| + t.string :title, null: false + t.text :content, null: false + t.string :uuid, null: false + + t.timestamps null: false + end + + add_index :posts, :uuid, unique: true + end +end +``` + +> 注意:要为每一张表添加类型为字符串的 `uuid` 字段,同时为 `uuid` 建立唯一索引,以加快通过 `uuid` 建立不同数据模型之间关系的速度。 + +除了建立数据库的迁移文件并修改基类,我们还需要修改一些 `include` 的模块和 Mongoid 中独有的查询,比如使用 `gte` 或者 `lte` 的日期查询和使用正则进行模式匹配的查询,这些查询在 ActiveRecord 中的使用方式与 Mongoid 中完全不同,我们需要通过手写 SQL 来解决这些问题。 + +![mongoid-to-activerecord-model-and-query](images/mongodb-to-mysql/mongoid-to-activerecord-model-and-query.png) + +除此之外,我们也需要处理一些复杂的模型关系,比如 Mongoid 中的 `inverse_of` 在 ActiveRecord 中叫做 `foreign_key` 等等,这些修改其实都并不复杂,只是如果想要将这部分的代码全部处理掉,就需要对业务逻辑进行详细地测试以保证不会有遗留的问题,这也就对我们项目的测试覆盖率有着比较高的要求了,不过我相信绝大多数的 Rails 工程都有着非常好的测试覆盖率,能够保证这一部分代码和逻辑能够顺利迁移,但是如果项目中完全没有测试或者测试覆盖率很低,就只能人肉进行测试或者自求多福了,或者**就别做迁移了,多写点测试再考虑这些重构的事情吧**。 + +### 数据的迁移 + +为每一个模型创建对应的迁移文件并建表其实一个不得不做的体力活,虽然有一些工作我们没法省略,但是我们可以考虑使用自动化的方式为所有的模型添加 `uuid` 字段和索引,同时也为类似 `post_id` 的字段添加相应的 `post_uuid` 列: + +```ruby +class AddUuidColumns < ActiveRecord::Migration[5.1] + def change + Rails.application.eager_load! + ActiveRecord::Base.descendants.map do |klass| + # add `uuid` column and create unique index on `uuid`. + add_column klass.table_name, :uuid, :string, unique: true + add_index klass.table_name, unique: true + + # add `xxx_uuid` columns, ex: `post_uuid`, `comment_uuid` and etc. + uuids = klass.attribute_names + .select { |attr| attr.include? '_id' } + .map { |attr| attr.gsub '_id', '_uuid' } + next unless uuids.present? + uuids.each do |uuid| + add_column klass.table_name, uuid, :string + end + end + end +end +``` + +在添加 `uuid` 列并建立好索引之后,我们就可以开始对数据库进行迁移了,如果我们决定在迁移的过程中改变原有数据的主键,那么我们会将迁移分成两个步骤,数据的迁移和关系的重建,前者仅指将 MongoDB 中的所有数据全部迁移到 MySQL 中对应的表中,并将所有的 `_id` 转换成 `uuid`、`xx_id` 转换成 `xx_uuid`,而后者就是前面提到的:通过 `uuid` 和 `xx_uuid` 的关联重新建立模型之间的关系并在最后删除所有的 `uuid` 字段。 + +我们可以使用如下的代码对数据进行迁移,这段代码从 MongoDB 中遍历某个集合 Collection 中的全部数据,然后将文档作为参数传入 block,然后再分别通过 `DatabaseTransformer#delete_obsolete_columns` 和 `DatabaseTransformer#update_rename_columns` 方法删除部分已有的列、更新一些数据列最后将所有的 `id` 列都变成 `uuid`: + +```ruby +module DatabaseTransformer + def import(collection_name, *obsolete_columns, **rename_columns) + collection = Mongoid::Clients.default.collections.select do |c| + c.namespace == "#{database}.#{collection_name.to_s.pluralize}" + end.first + + unless collection.present? + STDOUT.puts "#{collection_name.to_s.yellow}: skipped" + STDOUT.puts + return + end + + constant = collection_name.to_s.singularize.camelcase.constantize + reset_callbacks constant + + DatabaseTransformer.profiling do + collection_count = collection.find.count + collection.find.each_with_index do |document, index| + document = yield document if block_given? + delete_obsolete_columns document, obsolete_columns + update_rename_columns document, rename_columns + update_id_columns document + + insert_record constant, document + STDOUT.puts "#{index}/#{collection_count}\n" if (index % 1000).zero? + end + end + end +end +``` + +当完成了对文档的各种操作之后,该方法会直接调用 `DatabaseTransformer#insert_record` 将数据插入 MySQL 对应的表中;我们可以直接使用如下的代码将某个 Collection 中的全部文档迁移到 MySQL 中: + +```ruby +transformer = DatabaseTransformer.new 'draven_production' +transformer.import :post, :_slugs, name: :title, _status: :status +``` + +上述代码会在迁移时将集合每一个文档的 `_slugs` 字段全部忽略,同时将 `name` 重命名成 `title`、`_status` 重命名成 `status`,虽然作为枚举类型的字段 mongoid-enum 和 ActiveRecord 的枚举类型完全不同,但是在这里可以直接插入也没有什么问题,ActiveRecord 的模型在创建时会自己处理字符串和整数之间的转换: + +```ruby +def insert_record(constant, params) + model = constant.new params + model.save! validate: false +rescue Exception => exception + STDERR.puts "Import Error: #{exception}" + raise exception +end +``` + +为了加快数据的插入速度,同时避免所有由于插入操作带来的副作用,我们会在数据迁移期间重置所有的回调: + +```ruby +def reset_callbacks(constant) + %i(create save update).each do |callback| + constant.reset_callbacks callback + end +end +``` + +这段代码的作用仅在这个脚本运行的过程中才会生效,不会对工程中的其他地方造成任何的影响;同时,该脚本会在每 1000 个模型插入成功后向标准输出打印当前进度,帮助我们快速发现问题和预估迁移的时间。 + +> 你可以在 [database_transformer.rb](https://gist.github.com/Draveness/10476fe67a10128a37ba27a4c6967d07) 找到完整的数据迁移代码。 + +将所有的数据全部插入到 MySQL 的表之后,模型之间还没有任何显式的关系,我们还需要将通过 `uuid` 连接的模型转换成使用 `id` 的方式,对象之间的关系才能通过点语法直接访问,关系的建立其实非常简单,我们获得当前类所有结尾为 `_uuid` 的属性,然后遍历所有的数据行,根据 `uuid` 的值和 `post_uuid` 属性中的 "post" 部分获取到表名,最终得到对应的关联模型,在这里我们也处理了类似多态的特殊情况: + +```ruby +module RelationBuilder + def build_relations(class_name, polymorphic_associations = [], rename_associations = {}) + uuids = class_name.attribute_names.select { |name| name.end_with? '_uuid' } + + unless uuids.present? + STDOUT.puts "#{class_name.to_s.yellow}: skipped" + STDOUT.puts + return + end + + reset_callbacks class_name + + RelationBuilder.profiling do + models_count = class_name.count + class_name.unscoped.all.each_with_index do |model, index| + update_params = uuids.map do |uuid| + original_association_name = uuid[0...-5] + + association_model = association_model( + original_association_name, + model[uuid], + polymorphic_associations, + rename_associations + ) + + [original_association_name.to_s, association_model] + end.compact + + begin + Hash[update_params].each do |key, value| + model.send "#{key}=", value + end + model.save! validate: false + rescue Exception => e + STDERR.puts e + raise e + end + + STDOUT.puts "#{index}/#{models_count}\n" if (counter % 1000).zero? + end + end + end +end +``` + +在查找到对应的数据行之后就非常简单了,我们调用对应的 `post=` 等方法更新外键最后直接将外键的值保存到数据库中,与数据的迁移过程一样,我们在这段代码的执行过程中也会打印出当前的进度。 + +在初始化 `RelationBuilder` 时,如果我们传入了 `constants`,那么在调用 `RelationBuilder#build!` 时就会重建其中的全部关系,但是如果没有传入就会默认加载 ActiveRecord 中所有的子类,并去掉其中包含 `::` 的模型,也就是 ActiveRecord 中使用 `has_and_belongs_to_many` 创建的中间类,我们会在下一节中介绍如何单独处理多对多关系: + +```ruby +def initialize(constants = []) + if constants.present? + @constants = constants + else + Rails.application.eager_load! + @constants = ActiveRecord::Base.descendants + .reject { |constant| constant.to_s.include?('::') } + end +end +``` + +> 跟关系重建相关的代码可以在 [relation_builder.rb](https://gist.github.com/Draveness/c0798fb1272f483a176fa67741a3f1ee) 找到完整的用于关系迁移的代码。 + +```ruby +builder = RelationBuilder.new([Post, Comment]) +builder.build! +``` + +通过这数据迁移和关系重建两个步骤就已经可以解决绝大部分的数据迁移问题了,但是由于 MongoDB 和 ActiveRecord 中对于多对多关系的处理比较特殊,所以我们需要单独进行解决,如果所有的迁移问题到这里都已经解决了,那么我们就可以使用下面的迁移文件将数据库中与 `uuid` 有关的全部列都删除了: + +```ruby +class RemoveAllUuidColumns < ActiveRecord::Migration[5.1] + def change + Rails.application.eager_load! + ActiveRecord::Base.descendants.map do |klass| + attrs = klass.attribute_names.select { |n| n.include? 'uuid' } + next unless attrs.present? + remove_columns klass.table_name, *attrs + end + end +end +``` + +到这里位置整个迁移的过程就基本完成了,接下来就是跟整个迁移过程中有关的其他事项,例如:对多对关系、测试的重要性等话题。 + +### 多对多关系的处理 + +多对多关系在数据的迁移过程中其实稍微有一些复杂,在 Mongoid 中使用 `has_and_belongs_to_many` 会在相关的文档下添加一个 `tag_ids` 或者 `post_ids` 数组: + +```ruby +# The post document. +{ + "_id" : ObjectId("4d3ed089fb60ab534684b7e9"), + "tag_ids" : [ + ObjectId("4d3ed089fb60ab534684b7f2"), + ObjectId("4d3ed089fb60ab53468831f1") + ], + "title": "xxx", + "content": "xxx" +} +``` + +而 ActiveRecord 中会建立一张单独的表,表的名称是两张表名按照字母表顺序的拼接,如果是 `Post` 和 `Tag`,对应的多对多表就是 `posts_tags`,除了创建多对多表,`has_and_belongs_to_many` 还会创建两个 `ActiveRecord::Base` 的子类 `Tag::HABTM_Posts` 和 `Post::HABTM_Tags`,我们可以使用下面的代码简单实验一下: + +```ruby +require 'active_record' + +class Tag < ActiveRecord::Base; end +class Post < ActiveRecord::Base + has_and_belongs_to_many :tags +end +class Tag < ActiveRecord::Base + has_and_belongs_to_many :posts +end +puts ActiveRecord::Base.descendants +# => [Tag, Post, Post::HABTM_Tags, Tag::HABTM_Posts] +``` + +上述代码打印出了两个 `has_and_belongs_to_many` 生成的类 `Tag::HABTM_Posts` 和 `Post::HABTM_Tags`,它们有着完全相同的表 `posts_tags`,处理多对多关系时,我们只需要在使用 `DatabaseTransformer` 导入表中的所有的数据之后,再通过遍历 `posts_tags` 表中的数据更新多对多的关系表就可以了: + +```ruby +class PostsTag < ActiveRecord::Base; end + +# migrate data from mongodb to mysql. +transformer = DatabaseTransformer.new 'draven_production' +transformer.import :posts_tags + +# establish association between posts and tags. +PostsTag.unscoped.all.each do |model| + post = Post.find_by_uuid model.post_uuid + tag = Tag.find_by_uuid model.tag_uuid + next unless post.present? && tag.present? + model.update_columns post_id: post.id, tag_id: tag.id +end +``` + +所有使用 `has_and_belongs_to_many` 的多对多关系都需要通过上述代码进行迁移,这一步需要在删除数据库中的所有 `uuid` 字段之前完成。 + +### 测试的重要性 + +在真正对线上的服务进行停机迁移之前,我们其实需要对数据库已有的数据进行部分和全量测试,在部分测试阶段,我们可以在本地准备一个数据量为生产环境数据量 1/10 或者 1/100 的 MongoDB 数据库,通过在本地模拟 MongoDB 和 MySQL 的环境进行预迁移,确保我们能够尽快地发现迁移脚本中的错误。 + +![mongodb-pre-migration](images/mongodb-to-mysql/mongodb-pre-migration.png) + +准备测试数据库的办法是通过关系删除一些主要模型的数据行,在删除时可以通过 MongoDB 中的 `dependent: :destroy` 删除相关的模型,这样可以尽可能的保证数据的一致性和完整性,但是在对线上数据库进行迁移之前,我们依然需要对 MongoDB 中的全部数据进行全量的迁移测试,这样可以发现一些更加隐蔽的问题,保证真正上线时可以出现更少的状况。 + +数据库的迁移其实也属于重构,在进行 MongoDB 的数据库迁移之前一定要保证项目有着完善的测试体系和测试用例,这样才能让我们在项目重构之后,确定不会出现我们难以预料的问题,整个项目才是可控的,如果工程中没有足够的测试甚至没有测试,那么就不要再说重构这件事情了 -- **单元测试是重构的基础**。 + +## 总结 + +如何从 MongoDB 迁移到 MySQL 其实是一个工程问题,我们需要在整个过程中不断寻找可能出错的问题,将一个比较复杂的任务进行拆分,在真正做迁移之前尽可能地减少迁移对服务可用性以及稳定性带来的影响。 + +![mysql-and-mongodb-work-together](images/mongodb-to-mysql/mysql-and-mongodb-work-together.png) + +除此之外,MongoDB 和 MySQL 之间的选择也不一定是非此即彼,我们将项目中的大部分数据都迁移到了 MySQL 中,但是将一部分用于计算和分析的数据留在了 MongoDB,这样就可以保证 MongoDB 宕机之后仍然不会影响项目的主要任务,同时,MySQL 的备份和恢复速度也会因为数据库变小而非常迅速。 + +最后一点,测试真的很重要,如果没有测试,没有人能够做到在**修改大量的业务代码的过程中不丢失任何的业务逻辑**,甚至如果没有测试,很多业务逻辑可能在开发的那一天就已经丢失了。 + +如果对文章的内容有疑问或者有 MongoDB 迁移相关的问题,可以在评论中留言,评论系统使用 Disqus 需要梯子。 + +> 原文链接:[如何从 MongoDB 迁移到 MySQL · 面向信仰编程](https://draveness.me/mongodb-to-mysql.html) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) + +## Reference + ++ [How do I migrate data from a MongoDB to MySQL database? · Quora](https://www.quora.com/How-do-I-migrate-data-from-a-MongoDB-to-MySQL-database-Can-it-be-done-in-a-real-time-scenario-What-are-the-pros-and-cons-for-each-migration-Which-one-do-you-advice-What-is-your-experience-Any-reference-DB-expert-who-can-do-it) + diff --git a/contents/Database/mongodb-wiredtiger.md b/contents/Database/mongodb-wiredtiger.md new file mode 100644 index 0000000..5b099f6 --- /dev/null +++ b/contents/Database/mongodb-wiredtiger.md @@ -0,0 +1,220 @@ +# 『浅入浅出』MongoDB 和 WiredTiger + +![MongoDB-Covers](images/mongodb-wiredtiger/MongoDB-Covers.jpg) + +MongoDB 是目前主流的 NoSQL 数据库之一,与关系型数据库和其它的 NoSQL 不同,MongoDB 使用了面向文档的数据存储方式,将数据以类似 JSON 的方式存储在磁盘上,因为项目上的一些历史遗留问题,作者在最近的工作中也不得不经常与 MongoDB 打交道,这也是这篇文章出现的原因。 + +![logo](images/mongodb-wiredtiger/logo.png) + +虽然在之前也对 MongoDB 有所了解,但是真正在项目中大规模使用还是第一次,使用过程中也暴露了大量的问题,不过在这里,我们主要对 MongoDB 中的一些重要概念的原理进行介绍,也会与 MySQL 这种传统的关系型数据库做一个对比,让读者自行判断它们之间的优势和劣势。 + +## 概述 + +MongoDB 虽然也是数据库,但是它与传统的 RDBMS 相比有着巨大的不同,很多开发者都认为或者被灌输了一种思想,MongoDB 这种无 Scheme 的数据库相比 RDBMS 有着巨大的性能提升,这个判断其实是一种误解;因为数据库的性能不止与数据库本身的设计有关系,还与开发者对表结构和索引的设计、存储引擎的选择和业务有着巨大的关系,如果认为**仅进行了数据库的替换就能得到数量级的性能提升**,那还是太年轻了。 + +![its-not-always-simple-banner](images/mongodb-wiredtiger/its-not-always-simple-banner.jpg) + +### 架构 + +现有流行的数据库其实都有着非常相似的架构,MongoDB 其实就与 MySQL 中的架构相差不多,底层都使用了『可插拔』的存储引擎以满足用户的不同需要。 + +![MongoDB-Architecture](images/mongodb-wiredtiger/MongoDB-Architecture.jpg) + +用户可以根据表中的数据特征选择不同的存储引擎,它们可以在同一个 MongoDB 的实例中使用;在最新版本的 MongoDB 中使用了 WiredTiger 作为默认的存储引擎,WiredTiger 提供了不同粒度的并发控制和压缩机制,能够为不同种类的应用提供了最好的性能和存储效率。 + +在不同的存储引擎上层的就是 MongoDB 的数据模型和查询语言了,与关系型数据库不同,由于 MongoDB 对数据的存储与 RDBMS 有较大的差异,所以它创建了一套不同的查询语言;虽然 MongoDB 查询语言非常强大,支持的功能也很多,同时也是可编程的,不过其中包含的内容非常繁杂、API 设计也不是非常优雅,所以还是需要一些学习成本的,对于长时间使用 MySQL 的开发者肯定会有些不习惯。 + +```js +db.collection.updateMany( + <filter>, + <update>, + { + upsert: <boolean>, + writeConcern: <document>, + collation: <document> + } +) +``` + +查询语言的复杂是因为 MongoDB 支持了很多的数据类型,同时每一条数据记录也就是文档有着非常复杂的结构,这点是从设计上就没有办法避免的,所以还需要使用 MongoDB 的开发者花一些时间去学习各种各样的 API。 + +### RDBMS 与 MongoDB + +MongoDB 使用面向文档的的数据模型,导致很多概念都与 RDBMS 有一些差别,虽然从总体上来看两者都有相对应的概念,不过概念之间细微的差别其实也会影响我们对 MongoDB 的理解: + +![Translating-Between-RDBMS-and-MongoDB](images/mongodb-wiredtiger/Translating-Between-RDBMS-and-MongoDB.jpg) + +传统的 RDBMS 其实使用 `Table` 的格式将数据逻辑地存储在一张二维的表中,其中不包括任何复杂的数据结构,但是由于 MongoDB 支持嵌入文档、数组和哈希等多种复杂数据结构的使用,所以它最终将所有的数据以 [BSON](http://bsonspec.org) 的数据格式存储起来。 + +RDBMS 和 MongoDB 中的概念都有着相互对应的关系,数据库、表、行和索引的概念在两中数据库中都非常相似,唯独最后的 `JOIN` 和 `Embedded Document` 或者 `Reference` 有着巨大的差别。这一点差别其实也影响了在使用 MongoDB 时对集合(Collection)Schema 的设计,如果我们在 MongoDB 中遵循了与 RDBMS 中相同的思想对 Collection 进行设计,那么就不可避免的使用很多的 "JOIN" 语句,而 MongoDB 是不支持 "JOIN" 的,在应用内做这种查询的性能非常非常差,在这时使用嵌入式的文档其实就可以解决这种问题了,嵌入式的文档虽然可能会造成很多的数据冗余导致我们在更新时会很痛苦,但是查询时确实非常迅速。 + +```js +{ + _id: <ObjectId1>, + name: "draveness", + books: [ + { + _id: <ObjectId2>, + name: "MongoDB: The Definitive Guide" + }, + { + _id: <ObjectId3>, + name: "High Performance MySQL" + } + ] +} +``` + +在 MongoDB 的使用时,我们一定要忘记很多 RDBMS 中对于表设计的规则,同时想清楚 MongoDB 的优势,仔细思考如何对表进行设计才能利用 MongoDB 提供的诸多特性提升查询的效率。 + +## 数据模型 + +MongoDB 与 RDBMS 之间最大的不同,就是数据模型的设计有着非常明显的差异,数据模型的不同决定了它有着非常不同的特性,存储在 MongoDB 中的数据有着非常灵活的 Schema,我们不需要像 RDBMS 一样,在插入数据之前就决定并且定义表中的数据结构,MongoDB 的结合不对 Collection 的数据结构进行任何限制,但是在实际使用中,同一个 Collection 中的大多数文档都具有类似的结构。 + +![Different-Data-Structure](images/mongodb-wiredtiger/Different-Data-Structure.jpg) + +在为 MongoDB 应用设计数据模型时,如何表示数据模型之间的关系其实是需要开发者需要仔细考虑的,MongoDB 为表示文档之间的关系提供了两种不同的方法:引用和嵌入。 + +### 标准化数据模型 + +引用(Reference)在 MongoDB 中被称为标准化的数据模型,它与 MySQL 的外键非常相似,每一个文档都可以通过一个 `xx_id` 的字段『链接』到其他的文档: + +![Reference-MongoDB](images/mongodb-wiredtiger/Reference-MongoDB.jpg) + +但是 MongoDB 中的这种引用不像 MySQL 中可以直接通过 JOIN 进行查找,我们需要使用额外的查询找到该引用对应的模型,这虽然提供了更多的灵活性,不过由于增加了客户端和 MongoDB 之间的交互次数(Round-Trip)也会导致查询变慢,甚至非常严重的性能问题。 + +MongoDB 中的引用并不会对引用对应的数据模型是否真正存在做出任何的约束,所以如果在应用层级没有对文档之间的关系有所约束,那么就可能会出现引用了指向不存在的文档的问题: + +![Not-Found-Document](images/mongodb-wiredtiger/Not-Found-Document.jpg) + +虽然引用有着比较严重的性能问题并且在数据库层面没有对模型是否被删除加上限制,不过它提供的一些特点是嵌入式的文档无法给予了,当我们需要表示多对多关系或者更加庞大的数据集时,就可以考虑使用标准化的数据模型 — 引用了。 + +### 嵌入式数据模型 + +除了与 MySQL 中非常相似的引用,MongoDB 由于其独特的数据存储方式,还提供了嵌入式的数据模型,嵌入式的数据模型也被认为是不标准的数据模型: + +![Embedded-Data-Models-MongoDB](images/mongodb-wiredtiger/Embedded-Data-Models-MongoDB.jpg) + +因为 MongoDB 使用 BSON 的数据格式对数据进行存储,而嵌入式数据模型中的子文档其实就是父文档中的另一个值,只是其中存储的是一个对象: + +```javascript +{ + _id: <ObjectId1>, + username: "draveness", + age: 20, + contact: [ + { + _id: <ObjectId2>, + email: "i@draveness.me" + } + ] +} +``` + +嵌入式的数据模型允许我们将有相同的关系的信息存储在同一个数据记录中,这样应用就可以更快地对相关的数据进行查询和更新了;当我们的数据模型中有『包含』这样的关系或者模型经常需要与其他模型一起出现(查询)时,比如文章和评论,那么就可以考虑使用嵌入式的关系对数据模型进行设计。 + +总而言之,嵌入的使用让我们在更少的请求中获得更多的相关数据,能够为读操作提供更高的性能,也为在同一个写请求中同时更新相关数据提供了支持。 + +> MongoDB 底层的 WiredTiger 存储引擎能够保证对于同一个文档的操作都是原子的,任意一个写操作都不能原子性地影响多个文档或者多个集合。 + +## 主键和索引 + +在这一节中,我们将主要介绍 MongoDB 中不同类型的索引,当然也包括每个文档中非常重要的字段 `_id`,可以**理解**为 MongoDB 的『主键』,除此之外还会介绍单字段索引、复合索引以及多键索引等类型的索引。 + +MongoDB 中索引的概念其实与 MySQL 中的索引相差不多,无论是底层的数据结构还是基本的索引类型都几乎完全相同,两者之间的区别就在于因为 MongoDB 支持了不同类型的数据结构,所以也理所应当地提供了更多的索引种类。 + +![MongoDB-Indexes](images/mongodb-wiredtiger/MongoDB-Indexes.jpg) + +### 默认索引 + +MySQL 中的每一个数据行都具有一个主键,数据库中的数据都是按照以主键作为键物理地存储在文件中的;除了用于数据的存储,主键由于其特性也能够加速数据库的查询语句。 + +而 MongoDB 中所有的文档也都有一个唯一的 `_id` 字段,在默认情况下所有的文档都使用一个长 12 字节的 `ObjectId` 作为默认索引: + +![MongoDB-ObjectId](images/mongodb-wiredtiger/MongoDB-ObjectId.jpg) + +前四位代表当前 `_id` 生成时的 Unix 时间戳,在这之后是三位的机器标识符和两位的处理器标识符,最后是一个三位的计数器,初始值就是一个随机数;通过这种方式代替递增的 `id` 能够解决分布式的 MongoDB 生成唯一标识符的问题,同时可以在一定程度上保证 `id` 的的增长是递增的。 + +### 单字段索引(Single Field) + +除了 MongoDB 提供的默认 `_id` 字段之外,我们还可以建立其它的单键索引,而且其中不止支持顺序的索引,还支持对索引倒排: + +```javasciprt +db.users.createIndex( { age: -1 } ) +``` + +MySQL8.0 之前的索引都只能是正序排列的,在 8.0 之后才引入了逆序的索引,单一字段索引可以说是 MySQL 中的辅助(Secondary)索引的一个子集,它只是对除了 `_id` 外的任意单一字段建立起正序或者逆序的索引树。 + +![Single-Field-Index](images/mongodb-wiredtiger/Single-Field-Index.jpg) + +### 复合索引(Compound) + +除了单一字段索引这种非常简单的索引类型之外,MongoDB 还支持多个不同字段组成的复合索引(Compound Index),由于 MongoDB 中支持对同一字段的正逆序排列,所以相比于 MySQL 中的辅助索引就会出现更多的情况: + +```javascript +db.users.createIndex( { username: 1, age: -1 } ) +db.users.createIndex( { username: 1, age: 1 } ) +``` + +上面的两个索引是完全不同的,在磁盘上的 B+ 树其实也按照了完全不同的顺序进行存储,虽然 `username` 字段都是升序排列的,但是对于 `age` 来说,两个索引的处理是完全相反的: + +![Compound-Index](images/mongodb-wiredtiger/Compound-Index.jpg) + +这也就造成了在使用查询语句对集合中数据进行查找时,如果约定了正逆序,那么其实是会使用不同的索引的,所以在索引创建时一定要考虑好使用的场景,避免创建无用的索引。 + +### 多键索引(Multikey) + +由于 MongoDB 支持了类似数组的数据结构,所以也提供了名为多键索引的功能,可以将数组中的每一个元素进行索引,索引的创建其实与单字段索引没有太多的区别: + +```javascript +db.collection.createIndex( { address: 1 } ) +``` + +如果一个字段是值是数组,那么在使用上述代码时会自动为这个字段创建一个多键索引,能够加速对数组中元素的查找。 + +### 文本索引(Text) + +文本索引是 MongoDB 为我们提供的另一个比较实用的功能,不过在这里也只是对这种类型的索引提一下,也不打算深入去谈谈这东西的性能如何,如果真的要做全文索引的话,还是推荐使用 Elasticsearch 这种更专业的东西来做,而不是使用 MongoDB 提供的这项功能。 + +## 存储 + +如何存储数据就是一个比较重要的问题,在前面我们已经提到了 MongoDB 与 MySQL 一样都提供了插件化的存储引擎支持,作为 MongoDB 的主要组件之一,存储引擎全权负责了 MongoDB 对数据的管理。 + +![Multiple-Storage-Engines](images/mongodb-wiredtiger/Multiple-Storage-Engines.jpg) + +### WiredTiger + +MongoDB3.2 之后 WiredTiger 就是默认的存储引擎了,如果对各个存储引擎并不了解,那么还是不要改变 MongoDB 的默认存储引擎;它有着非常多的优点,比如拥有效率非常高的缓存机制: + +![WiredTiger-Cache](images/mongodb-wiredtiger/WiredTiger-Cache.jpg) + +WiredTiger 还支持在内存中和磁盘上对索引进行压缩,在压缩时也使用了前缀压缩的方式以减少 RAM 的使用,在后面的文章中我们会详细介绍和分析 WiredTiger 存储引擎是如何对各种数据进行存储的。 + +### Journaling + +为了在数据库宕机保证 MongoDB 中数据的持久性,MongoDB 使用了 Write Ahead Logging 向磁盘上的 journal 文件预先进行写入;除了 journal 日志,MongoDB 还使用检查点(Checkpoint)来保证数据的一致性,当数据库发生宕机时,我们就需要 Checkpoint 和 journal 文件协作完成数据的恢复工作: + +1. 在数据文件中查找上一个检查点的标识符; +2. 在 journal 文件中查找标识符对应的记录; +3. 重做对应记录之后的全部操作; + +MongoDB 会每隔 60s 或者在 journal 数据的写入达到 2GB 时设置一次检查点,当然我们也可以通过在写入时传入 `j: true` 的参数强制 journal 文件的同步。 + +![Checkpoints-Conditions](images/mongodb-wiredtiger/Checkpoints-Conditions.jpg) + +这篇文章并不会介绍 Journal 文件的格式以及相关的内容,作者可能会在之后介绍分析 WiredTiger 的文章中简单分析其存储格式以及一些其它特性。 + +## 总结 + +这篇文章中只是对 MongoDB 的一些基本特性以及数据模型做了简单的介绍,虽然『无限』扩展是 MongoDB 非常重要的特性,但是由于篇幅所限,我们并没有介绍任何跟 MongoDB 集群相关的信息,不过会在之后的文章中专门介绍多实例的 MongoDB 是如何协同工作的。 + +在这里,我想说的是,如果各位读者接收到了类似 MongoDB 比 MySQL 性能好很多的断言,但是在使用 MongoDB 的过程中仍然遵循以往 RDBMS 对数据库的设计方式,那么我相信性能在最终也不会有太大的提升,反而可能会不升反降;只有真正理解 MongoDB 的数据模型,并且根据业务的需要进行设计才能很好地利用类似嵌入式文档等特性并提升 MongoDB 的性能。 + +## References + ++ [MongoDB Architecture](https://www.mongodb.com/mongodb-architecture) ++ [Thinking in Documents: Part 1](https://www.mongodb.com/blog/post/thinking-documents-part-1?jmp=docs) ++ [DB-Engines Ranking](https://db-engines.com/en/ranking) ++ [Data Modeling Introduction](https://docs.mongodb.com/manual/core/data-modeling-introduction/) ++ [Building Applications with MongoDB's Pluggable Storage Engines: Part 1](https://www.mongodb.com/blog/post/building-applications-with-mongodbs-pluggable-storage-engines-part-1?jmp=docs) + diff --git a/contents/Database/mysql.md b/contents/Database/mysql.md new file mode 100644 index 0000000..2577d9c --- /dev/null +++ b/contents/Database/mysql.md @@ -0,0 +1,382 @@ +# 『浅入浅出』MySQL 和 InnoDB + +作为一名开发人员,在日常的工作中会难以避免地接触到数据库,无论是基于文件的 sqlite 还是工程上使用非常广泛的 MySQL、PostgreSQL,但是一直以来也没有对数据库有一个非常清晰并且成体系的认知,所以最近两个月的时间看了几本数据库相关的书籍并且阅读了 MySQL 的官方文档,希望对各位了解数据库的、不了解数据库的有所帮助。 + +![mysql](images/mysql/mysql.png) + + +本文中对于数据库的介绍以及研究都是在 MySQL 上进行的,如果涉及到了其他数据库的内容或者实现会在文中单独指出。 + +## 数据库的定义 + +很多开发者在最开始时其实都对数据库有一个比较模糊的认识,觉得数据库就是一堆数据的集合,但是实际却比这复杂的多,数据库领域中有两个词非常容易混淆,也就是*数据库*和*实例*: + ++ 数据库:物理操作文件系统或其他形式文件类型的集合; ++ 实例:MySQL 数据库由后台线程以及一个共享内存区组成; + +> 对于数据库和实例的定义都来自于 [MySQL 技术内幕:InnoDB 存储引擎](https://book.douban.com/subject/24708143/) 一书,想要了解 InnoDB 存储引擎的读者可以阅读这本书籍。 + +### 数据库和实例 + +在 MySQL 中,实例和数据库往往都是一一对应的,而我们也无法直接操作数据库,而是要通过数据库实例来操作数据库文件,可以理解为数据库实例是数据库为上层提供的一个专门用于操作的接口。 + +![Database - Instance](images/mysql/Database%20-%20Instance.jpg) + +在 Unix 上,启动一个 MySQL 实例往往会产生两个进程,`mysqld` 就是真正的数据库服务守护进程,而 `mysqld_safe` 是一个用于检查和设置 `mysqld` 启动的控制程序,它负责监控 MySQL 进程的执行,当 `mysqld` 发生错误时,`mysqld_safe` 会对其状态进行检查并在合适的条件下重启。 + +### MySQL 的架构 + +MySQL 从第一个版本发布到现在已经有了 20 多年的历史,在这么多年的发展和演变中,整个应用的体系结构变得越来越复杂: + +![Logical-View-of-MySQL-Architecture](images/mysql/Logical-View-of-MySQL-Architecture.jpg) + +最上层用于连接、线程处理的部分并不是 MySQL 『发明』的,很多服务都有类似的组成部分;第二层中包含了大多数 MySQL 的核心服务,包括了对 SQL 的解析、分析、优化和缓存等功能,存储过程、触发器和视图都是在这里实现的;而第三层就是 MySQL 中真正负责数据的存储和提取的存储引擎,例如:[InnoDB](https://en.wikipedia.org/wiki/InnoDB)、[MyISAM](https://en.wikipedia.org/wiki/MyISAM) 等,文中对存储引擎的介绍都是对 InnoDB 实现的分析。 + +## 数据的存储 + +在整个数据库体系结构中,我们可以使用不同的存储引擎来存储数据,而绝大多数存储引擎都以二进制的形式存储数据;这一节会介绍 InnoDB 中对数据是如何存储的。 + +在 InnoDB 存储引擎中,所有的数据都被**逻辑地**存放在表空间中,表空间(tablespace)是存储引擎中最高的存储逻辑单位,在表空间的下面又包括段(segment)、区(extent)、页(page): + +![Tablespace-segment-extent-page-row](images/mysql/Tablespace-segment-extent-page-row.jpg) + +同一个数据库实例的所有表空间都有相同的页大小;默认情况下,表空间中的页大小都为 16KB,当然也可以通过改变 `innodb_page_size` 选项对默认大小进行修改,需要注意的是不同的页大小最终也会导致区大小的不同: + +![Relation Between Page Size - Extent Size](images/mysql/Relation%20Between%20Page%20Size%20-%20Extent%20Size.png) + +从图中可以看出,在 InnoDB 存储引擎中,一个区的大小最小为 1MB,页的数量最少为 64 个。 + +### 如何存储表 + +MySQL 使用 InnoDB 存储表时,会将**表的定义**和**数据索引**等信息分开存储,其中前者存储在 `.frm` 文件中,后者存储在 `.ibd` 文件中,这一节就会对这两种不同的文件分别进行介绍。 + +![frm-and-ibd-file](images/mysql/frm-and-ibd-file.jpg) + +#### .frm 文件 + +无论在 MySQL 中选择了哪个存储引擎,所有的 MySQL 表都会在硬盘上创建一个 `.frm` 文件用来描述表的格式或者说定义;`.frm` 文件的格式在不同的平台上都是相同的。 + +```sql +CREATE TABLE test_frm( + column1 CHAR(5), + column2 INTEGER +); +``` + +当我们使用上面的代码创建表时,会在磁盘上的 `datadir` 文件夹中生成一个 `test_frm.frm` 的文件,这个文件中就包含了表结构相关的信息: + +![frm-file-hex](images/mysql/frm-file-hex.png) + +> MySQL 官方文档中的 [11.1 MySQL .frm File Format](https://dev.mysql.com/doc/internals/en/frm-file-format.html) 一文对于 `.frm` 文件格式中的二进制的内容有着非常详细的表述,在这里就不展开介绍了。 + +#### .ibd 文件 + +InnoDB 中用于存储数据的文件总共有两个部分,一是系统表空间文件,包括 `ibdata1`、`ibdata2` 等文件,其中存储了 InnoDB 系统信息和用户数据库表数据和索引,是所有表公用的。 + +当打开 `innodb_file_per_table` 选项时,`.ibd` 文件就是每一个表独有的表空间,文件存储了当前表的数据和相关的索引数据。 + +### 如何存储记录 + +与现有的大多数存储引擎一样,InnoDB 使用页作为磁盘管理的最小单位;数据在 InnoDB 存储引擎中都是按行存储的,每个 16KB 大小的页中可以存放 2-200 行的记录。 + +当 InnoDB 存储数据时,它可以使用不同的行格式进行存储;MySQL 5.7 版本支持以下格式的行存储方式: + +![Antelope-Barracuda-Row-Format](images/mysql/Antelope-Barracuda-Row-Format.jpg) + +> Antelope 是 InnoDB 最开始支持的文件格式,它包含两种行格式 Compact 和 Redundant,它最开始并没有名字;Antelope 的名字是在新的文件格式 Barracuda 出现后才起的,Barracuda 的出现引入了两种新的行格式 Compressed 和 Dynamic;InnoDB 对于文件格式都会向前兼容,而官方文档中也对之后会出现的新文件格式预先定义好了名字:Cheetah、Dragon、Elk 等等。 + +两种行记录格式 Compact 和 Redundant 在磁盘上按照以下方式存储: + +![COMPACT-And-REDUNDANT-Row-Format](images/mysql/COMPACT-And-REDUNDANT-Row-Format.jpg) + +Compact 和 Redundant 格式最大的不同就是记录格式的第一个部分;在 Compact 中,行记录的第一部分倒序存放了一行数据中列的长度(Length),而 Redundant 中存的是每一列的偏移量(Offset),从总体上上看,Compact 行记录格式相比 Redundant 格式能够减少 20% 的存储空间。 + +#### 行溢出数据 + +当 InnoDB 使用 Compact 或者 Redundant 格式存储极长的 VARCHAR 或者 BLOB 这类大对象时,我们并不会直接将所有的内容都存放在数据页节点中,而是将行数据中的前 768 个字节存储在数据页中,后面会通过偏移量指向溢出页。 + +![Row-Overflo](images/mysql/Row-Overflow.jpg) + +但是当我们使用新的行记录格式 Compressed 或者 Dynamic 时都只会在行记录中保存 20 个字节的指针,实际的数据都会存放在溢出页面中。 + +![Row-Overflow-in-Barracuda](images/mysql/Row-Overflow-in-Barracuda.jpg) + +当然在实际存储中,可能会对不同长度的 TEXT 和 BLOB 列进行优化,不过这就不是本文关注的重点了。 + +> 想要了解更多与 InnoDB 存储引擎中记录的数据格式的相关信息,可以阅读 [InnoDB Record Structure](https://dev.mysql.com/doc/internals/en/innodb-record-structure.html) + +### 数据页结构 + +页是 InnoDB 存储引擎管理数据的最小磁盘单位,而 B-Tree 节点就是实际存放表中数据的页面,我们在这里将要介绍页是如何组织和存储记录的;首先,一个 InnoDB 页有以下七个部分: + +![InnoDB-B-Tree-Node](images/mysql/InnoDB-B-Tree-Node.jpg) + +每一个页中包含了两对 header/trailer:内部的 Page Header/Page Directory 关心的是页的状态信息,而 Fil Header/Fil Trailer 关心的是记录页的头信息。 + +在页的头部和尾部之间就是用户记录和空闲空间了,每一个数据页中都包含 Infimum 和 Supremum 这两个**虚拟**的记录(可以理解为占位符),Infimum 记录是比该页中任何主键值都要小的值,Supremum 是该页中的最大值: + +![Infimum-Rows-Supremum](images/mysql/Infimum-Rows-Supremum.jpg) + +User Records 就是整个页面中真正用于存放行记录的部分,而 Free Space 就是空余空间了,它是一个链表的数据结构,为了保证插入和删除的效率,整个页面并不会按照主键顺序对所有记录进行排序,它会自动从左侧向右寻找空白节点进行插入,行记录在物理存储上并不是按照顺序的,它们之间的顺序是由 `next_record` 这一指针控制的。 + +B+ 树在查找对应的记录时,并不会直接从树中找出对应的行记录,它只能获取记录所在的页,将整个页加载到内存中,再通过 Page Directory 中存储的稀疏索引和 `n_owned`、`next_record` 属性取出对应的记录,不过因为这一操作是在内存中进行的,所以通常会忽略这部分查找的耗时。 + +InnoDB 存储引擎中对数据的存储是一个非常复杂的话题,这一节中也只是对表、行记录以及页面的存储进行一定的分析和介绍,虽然作者相信这部分知识对于大部分开发者已经足够了,但是想要真正消化这部分内容还需要很多的努力和实践。 + +## 索引 + +索引是数据库中非常非常重要的概念,它是存储引擎能够快速定位记录的秘密武器,对于提升数据库的性能、减轻数据库服务器的负担有着非常重要的作用;**索引优化是对查询性能优化的最有效手段**,它能够轻松地将查询的性能提高几个数量级。 + +### 索引的数据结构 + +在上一节中,我们谈了行记录的存储和页的存储,在这里我们就要从更高的层面看 InnoDB 中对于数据是如何存储的;InnoDB 存储引擎在绝大多数情况下使用 B+ 树建立索引,这是关系型数据库中查找最为常用和有效的索引,但是 B+ 树索引并不能找到一个给定键对应的具体值,它只能找到数据行对应的页,然后正如上一节所提到的,数据库把整个页读入到内存中,并在内存中查找具体的数据行。 + +![B+Tree](images/mysql/B+Tree.jpg) + +B+ 树是平衡树,它查找任意节点所耗费的时间都是完全相同的,比较的次数就是 B+ 树的高度;在这里,我们并不会深入分析或者动手实现一个 B+ 树,只是对它的特性进行简单的介绍。 + +### 聚集索引和辅助索引 + +数据库中的 B+ 树索引可以分为聚集索引(clustered index)和辅助索引(secondary index),它们之间的最大区别就是,聚集索引中存放着一条行记录的全部信息,而辅助索引中只包含索引列和一个用于查找对应行记录的『书签』。 + +#### 聚集索引 + +InnoDB 存储引擎中的表都是使用索引组织的,也就是按照键的顺序存放;聚集索引就是按照表中主键的顺序构建一颗 B+ 树,并在叶节点中存放表中的行记录数据。 + +```sql +CREATE TABLE users( + id INT NOT NULL, + first_name VARCHAR(20) NOT NULL, + last_name VARCHAR(20) NOT NULL, + age INT NOT NULL, + PRIMARY KEY(id), + KEY(last_name, first_name, age) + KEY(first_name) +); +``` + +如果使用上面的 SQL 在数据库中创建一张表,B+ 树就会使用 `id` 作为索引的键,并在叶子节点中存储一条记录中的**所有**信息。 + +![Clustered-Index](images/mysql/Clustered-Index.jpg) + +> 图中对 B+ 树的描述与真实情况下 B+ 树中的数据结构有一些差别,不过这里想要表达的主要意思是:聚集索引叶节点中保存的是整条行记录,而不是其中的一部分。 + +聚集索引与表的物理存储方式有着非常密切的关系,所有正常的表应该**有且仅有一个**聚集索引(绝大多数情况下都是主键),表中的所有行记录数据都是按照**聚集索引**的顺序存放的。 + +当我们使用聚集索引对表中的数据进行检索时,可以直接获得聚集索引所对应的整条行记录数据所在的页,不需要进行第二次操作。 + +#### 辅助索引 + +数据库将所有的非聚集索引都划分为辅助索引,但是这个概念对我们理解辅助索引并没有什么帮助;辅助索引也是通过 B+ 树实现的,但是它的叶节点并不包含行记录的全部数据,仅包含索引中的所有键和一个用于查找对应行记录的『书签』,在 InnoDB 中这个书签就是当前记录的主键。 + +辅助索引的存在并不会影响聚集索引,因为聚集索引构成的 B+ 树是数据实际存储的形式,而辅助索引只用于加速数据的查找,所以一张表上往往有多个辅助索引以此来提升数据库的性能。 + +> 一张表一定包含一个聚集索引构成的 B+ 树以及若干辅助索引的构成的 B+ 树。 + +![Secondary-Index](images/mysql/Secondary-Index.jpg) + +如果在表 `users` 中存在一个辅助索引 `(first_name, age)`,那么它构成的 B+ 树大致就是上图这样,按照 `(first_name, age)` 的字母顺序对表中的数据进行排序,当查找到主键时,再通过聚集索引获取到整条行记录。 + +![Clustered-Secondary-Index](images/mysql/Clustered-Secondary-Index.jpg) + +上图展示了一个使用辅助索引查找一条表记录的过程:通过辅助索引查找到对应的主键,最后在聚集索引中使用主键获取对应的行记录,这也是通常情况下行记录的查找方式。 + +### 索引的设计 + +索引的设计其实是一个非常重要的内容,同时也是一个非常复杂的内容;索引的设计与创建对于提升数据库的查询性能至关重要,不过这不是本文想要介绍的内容,有关索引的设计与优化可以阅读 [数据库索引设计与优化](数据库索引设计与优化) 一书,书中提供了一种非常科学合理的方法能够帮助我们在数据库中建立最适合的索引,当然作者也可能会在之后的文章中对索引的设计进行简单的介绍和分析。 + +## 锁 + +我们都知道锁的种类一般分为乐观锁和悲观锁两种,InnoDB 存储引擎中使用的就是悲观锁,而按照锁的粒度划分,也可以分成行锁和表锁。 + +### 并发控制机制 + +乐观锁和悲观锁其实都是并发控制的机制,同时它们在原理上就有着本质的差别; + ++ 乐观锁是一种思想,它其实并不是一种真正的『锁』,它会先尝试对资源进行修改,在写回时判断资源是否进行了改变,如果没有发生改变就会写回,否则就会进行重试,在整个的执行过程中其实都**没有对数据库进行加锁**; ++ 悲观锁就是一种真正的锁了,它会在获取资源前对资源进行加锁,确保同一时刻只有有限的线程能够访问该资源,其他想要尝试获取资源的操作都会进入等待状态,直到该线程完成了对资源的操作并且释放了锁后,其他线程才能重新操作资源; + +虽然乐观锁和悲观锁在本质上并不是同一种东西,一个是一种思想,另一个是一种真正的锁,但是它们都是一种并发控制机制。 + +![Optimistic-Pessimistic-Locks](images/mysql/Optimistic-Pessimistic-Locks.jpg) + +乐观锁不会存在死锁的问题,但是由于更新后验证,所以当**冲突频率**和**重试成本**较高时更推荐使用悲观锁,而需要非常高的**响应速度**并且**并发量**非常大的时候使用乐观锁就能较好的解决问题,在这时使用悲观锁就可能出现严重的性能问题;在选择并发控制机制时,需要综合考虑上面的四个方面(冲突频率、重试成本、响应速度和并发量)进行选择。 + +### 锁的种类 + +对数据的操作其实只有两种,也就是读和写,而数据库在实现锁时,也会对这两种操作使用不同的锁;InnoDB 实现了标准的行级锁,也就是共享锁(Shared Lock)和互斥锁(Exclusive Lock);共享锁和互斥锁的作用其实非常好理解: + ++ **共享锁(读锁)**:允许事务对一条行数据进行读取; ++ **互斥锁(写锁)**:允许事务对一条行数据进行删除或更新; + +而它们的名字也暗示着各自的另外一个特性,共享锁之间是兼容的,而互斥锁与其他任意锁都不兼容: + +![Shared-Exclusive-Lock](images/mysql/Shared-Exclusive-Lock.jpg) + +稍微对它们的使用进行思考就能想明白它们为什么要这么设计,因为共享锁代表了读操作、互斥锁代表了写操作,所以我们可以在数据库中**并行读**,但是只能**串行写**,只有这样才能保证不会发生线程竞争,实现线程安全。 + +### 锁的粒度 + +无论是共享锁还是互斥锁其实都只是对某一个数据行进行加锁,InnoDB 支持多种粒度的锁,也就是行锁和表锁;为了支持多粒度锁定,InnoDB 存储引擎引入了意向锁(Intention Lock),意向锁就是一种表级锁。 + +与上一节中提到的两种锁的种类相似的是,意向锁也分为两种: + ++ **意向共享锁**:事务想要在获得表中某些记录的共享锁,需要在表上先加意向共享锁; ++ **意向互斥锁**:事务想要在获得表中某些记录的互斥锁,需要在表上先加意向互斥锁; + +随着意向锁的加入,锁类型之间的兼容矩阵也变得愈加复杂: + +![Lock-Type-Compatibility-Matrix](images/mysql/Lock-Type-Compatibility-Matrix.jpg) + +意向锁其实不会阻塞全表扫描之外的任何请求,它们的主要目的是为了表示**是否有人请求锁定表中的某一行数据**。 + +> 有的人可能会对意向锁的目的并不是完全的理解,我们在这里可以举一个例子:如果没有意向锁,当已经有人使用行锁对表中的某一行进行修改时,如果另外一个请求要对全表进行修改,那么就需要对所有的行是否被锁定进行扫描,在这种情况下,效率是非常低的;不过,在引入意向锁之后,当有人使用行锁对表中的某一行进行修改之前,会先为表添加意向互斥锁(IX),再为行记录添加互斥锁(X),在这时如果有人尝试对全表进行修改就不需要判断表中的每一行数据是否被加锁了,只需要通过等待意向互斥锁被释放就可以了。 + +### 锁的算法 + +到目前为止已经对 InnoDB 中锁的粒度有一定的了解,也清楚了在对数据库进行读写时会获取不同的锁,在这一小节将介绍锁是如何添加到对应的数据行上的,我们会分别介绍三种锁的算法:Record Lock、Gap Lock 和 Next-Key Lock。 + +#### Record Lock + +记录锁(Record Lock)是加到**索引记录**上的锁,假设我们存在下面的一张表 `users`: + +```sql +CREATE TABLE users( + id INT NOT NULL AUTO_INCREMENT, + last_name VARCHAR(255) NOT NULL, + first_name VARCHAR(255), + age INT, + PRIMARY KEY(id), + KEY(last_name), + KEY(age) +); +``` + +如果我们使用 `id` 或者 `last_name` 作为 SQL 中 `WHERE` 语句的过滤条件,那么 InnoDB 就可以通过索引建立的 B+ 树找到行记录并添加索引,但是如果使用 `first_name` 作为过滤条件时,由于 InnoDB 不知道待修改的记录具体存放的位置,也无法对将要修改哪条记录提前做出判断就会锁定整个表。 + +#### Gap Lock + +记录锁是在存储引擎中最为常见的锁,除了记录锁之外,InnoDB 中还存在间隙锁(Gap Lock),间隙锁是对索引记录中的一段连续区域的锁;当使用类似 `SELECT * FROM users WHERE id BETWEEN 10 AND 20 FOR UPDATE;` 的 SQL 语句时,就会阻止其他事务向表中插入 `id = 15` 的记录,因为整个范围都被间隙锁锁定了。 + +> 间隙锁是存储引擎对于性能和并发做出的权衡,并且只用于某些事务隔离级别。 + +虽然间隙锁中也分为共享锁和互斥锁,不过它们之间并不是互斥的,也就是不同的事务可以同时持有一段相同范围的共享锁和互斥锁,它唯一阻止的就是**其他事务向这个范围中添加新的记录**。 + +#### Next-Key Lock + +Next-Key 锁相比前两者就稍微有一些复杂,它是记录锁和记录前的间隙锁的结合,在 `users` 表中有以下记录: + +```sql ++------+-------------+--------------+-------+ +| id | last_name | first_name | age | +|------+-------------+--------------+-------| +| 4 | stark | tony | 21 | +| 1 | tom | hiddleston | 30 | +| 3 | morgan | freeman | 40 | +| 5 | jeff | dean | 50 | +| 2 | donald | trump | 80 | ++------+-------------+--------------+-------+ +``` + +如果使用 Next-Key 锁,那么 Next-Key 锁就可以在需要的时候锁定以下的范围: + +```sql +(-∞, 21] +(21, 30] +(30, 40] +(40, 50] +(50, 80] +(80, ∞) +``` + +> 既然叫 Next-Key 锁,锁定的应该是当前值和后面的范围,但是实际上却不是,Next-Key 锁锁定的是当前值和前面的范围。 + +当我们更新一条记录,比如 `SELECT * FROM users WHERE age = 30 FOR UPDATE;`,InnoDB 不仅会在范围 `(21, 30]` 上加 Next-Key 锁,还会在这条记录后面的范围 `(30, 40]` 加间隙锁,所以插入 `(21, 40]` 范围内的记录都会被锁定。 + +Next-Key 锁的作用其实是为了解决幻读的问题,我们会在下一节谈事务的时候具体介绍。 + +### 死锁的发生 + +既然 InnoDB 中实现的锁是悲观的,那么不同事务之间就可能会互相等待对方释放锁造成死锁,最终导致事务发生错误;想要在 MySQL 中制造死锁的问题其实非常容易: + +![Deadlocks](images/mysql/Deadlocks.jpg) + +两个会话都持有一个锁,并且尝试获取对方的锁时就会发生死锁,不过 MySQL 也能在发生死锁时及时发现问题,并保证其中的一个事务能够正常工作,这对我们来说也是一个好消息。 + +## 事务与隔离级别 + +在介绍了锁之后,我们再来谈谈数据库中一个非常重要的概念 —— 事务;相信只要是一个合格的软件工程师就对事务的特性有所了解,其中被人经常提起的就是事务的原子性,在数据提交工作时,要么保证所有的修改都能够提交,要么就所有的修改全部回滚。 + +但是事务还遵循包括原子性在内的 ACID 四大特性:原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)和持久性(Durability);文章不会对这四大特性全部展开进行介绍,相信你能够通过 Google 和数据库相关的书籍轻松获得有关它们的概念,本文最后要介绍的就是事务的四种隔离级别。 + +### 几种隔离级别 + +事务的隔离性是数据库处理数据的几大基础之一,而隔离级别其实就是提供给用户用于在性能和可靠性做出选择和权衡的配置项。 + +ISO 和 ANIS SQL 标准制定了四种事务隔离级别,而 InnoDB 遵循了 SQL:1992 标准中的四种隔离级别:`READ UNCOMMITED`、`READ COMMITED`、`REPEATABLE READ` 和 `SERIALIZABLE`;每个事务的隔离级别其实都比上一级多解决了一个问题: + ++ `RAED UNCOMMITED`:使用查询语句不会加锁,可能会读到未提交的行(Dirty Read); ++ `READ COMMITED`:只对记录加记录锁,而不会在记录之间加间隙锁,所以允许新的记录插入到被锁定记录的附近,所以再多次使用查询语句时,可能得到不同的结果(Non-Repeatable Read); ++ `REPEATABLE READ`:多次读取同一范围的数据会返回第一次查询的快照,不会返回不同的数据行,但是可能发生幻读(Phantom Read); ++ `SERIALIZABLE`:InnoDB 隐式地将全部的查询语句加上共享锁,解决了幻读的问题; + +MySQL 中默认的事务隔离级别就是 `REPEATABLE READ`,但是它通过 Next-Key 锁也能够在某种程度上解决幻读的问题。 + +![Transaction-Isolation-Matrix](images/mysql/Transaction-Isolation-Matrix.jpg) + +接下来,我们将数据库中创建如下的表并通过个例子来展示在不同的事务隔离级别之下,会发生什么样的问题: + +```sql +CREATE TABLE test( + id INT NOT NULL, + UNIQUE(id) +); +``` + +### 脏读 + +当事务的隔离级别为 `READ UNCOMMITED` 时,我们在 `SESSION 2` 中插入的**未提交**数据在 `SESSION 1` 中是可以访问的。 + +![Read-Uncommited-Dirty-Read](images/mysql/Read-Uncommited-Dirty-Read.jpg) + +### 不可重复读 + +当事务的隔离级别为 `READ COMMITED` 时,虽然解决了脏读的问题,但是如果在 `SESSION 1` 先查询了一个范围的数据,在这之后 `SESSION 2` 中插入一条数据并且提交了修改,在这时,如果 `SESSION 1` 中再次使用相同的查询语句,就会发现两次查询的结果不一样。 + +![Read-Commited-Non-Repeatable-Read](images/mysql/Read-Commited-Non-Repeatable-Read.jpg) + +不可重复读的原因就是,在 `READ COMMITED` 的隔离级别下,存储引擎不会在查询记录时添加间隙锁,锁定 `id < 5` 这个范围。 + +### 幻读 + +重新开启了两个会话 `SESSION 1` 和 `SESSION 2`,在 `SESSION 1` 中我们查询全表的信息,没有得到任何记录;在 `SESSION 2` 中向表中插入一条数据并提交;由于 `REPEATABLE READ` 的原因,再次查询全表的数据时,我们获得到的仍然是空集,但是在向表中插入同样的数据却出现了错误。 + +![Repeatable-Read-Phantom-Read](images/mysql/Repeatable-Read-Phantom-Read.jpg) + +这种现象在数据库中就被称作幻读,虽然我们使用查询语句得到了一个空的集合,但是插入数据时却得到了错误,好像之前的查询是幻觉一样。 + +在标准的事务隔离级别中,幻读是由更高的隔离级别 `SERIALIZABLE` 解决的,但是它也可以通过 MySQL 提供的 Next-Key 锁解决: + +![Repeatable-with-Next-Key-Lock](images/mysql/Repeatable-with-Next-Key-Lock.jpg) + +`REPERATABLE READ` 和 `READ UNCOMMITED` 其实是矛盾的,如果保证了前者就看不到已经提交的事务,如果保证了后者,就会导致两次查询的结果不同,MySQL 为我们提供了一种折中的方式,能够在 `REPERATABLE READ` 模式下加锁访问已经提交的数据,其本身并不能解决幻读的问题,而是通过文章前面提到的 Next-Key 锁来解决。 + +## 总结 + +> 文章中的内容大都来自于 [高性能 MySQL](https://book.douban.com/subject/23008813/)、[MySQL 技术内幕:InnoDB 存储引擎](https://book.douban.com/subject/24708143/)、[数据库索引设计与优化](https://book.douban.com/subject/26419771/) 以及 MySQL 的 [官方文档](https://dev.mysql.com/doc/)。 + +由于篇幅所限仅能对数据库中一些重要内容进行简单的介绍和总结,文中内容难免有所疏漏,如果对文章内容的有疑问,可以在博客下面评论留言(评论系统使用 Disqus,需要翻墙)。 + +## Reference + ++ [mysqld_safe version different than mysqld?](https://dba.stackexchange.com/questions/35962/mysqld-safe-version-different-than-mysqld) ++ [File Space Management](https://dev.mysql.com/doc/refman/5.7/en/innodb-file-space.html) ++ [Externally Stored Fields in InnoDB](http://mysqlserverteam.com/externally-stored-fields-in-innodb/) ++ [InnoDB Record Structure](https://dev.mysql.com/doc/internals/en/innodb-record-structure.html) ++ [InnoDB Page Structure](https://dev.mysql.com/doc/internals/en/innodb-page-structure.html) ++ [Difference between clustered and nonclustered index](https://stackoverflow.com/questions/5070529/difference-between-clustered-and-nonclustered-index) ++ [InnoDB Locking](https://dev.mysql.com/doc/refman/5.7/en/innodb-locking.html) ++ [乐观锁与悲观锁的区别](http://www.cnblogs.com/Bob-FD/p/3352216.html) ++ [Optimistic concurrency control](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) ++ [MySQL 四种事务隔离级的说明](http://www.cnblogs.com/zhoujinyi/p/3437475.html) + diff --git a/contents/Database/sql-index-intro.md b/contents/Database/sql-index-intro.md new file mode 100644 index 0000000..856fa8a --- /dev/null +++ b/contents/Database/sql-index-intro.md @@ -0,0 +1,176 @@ +# MySQL 索引设计概要 + +在关系型数据库中设计索引其实并不是复杂的事情,很多开发者都觉得设计索引能够提升数据库的性能,相关的知识一定非常复杂。 + +![Index-and-Performance](images/sql-index-intro/Index-and-Performance.jpg) + +然而这种想法是不正确的,索引其实并不是一个多么高深莫测的东西,只要我们掌握一定的方法,理解索引的实现就能在不需要 DBA 的情况下设计出高效的索引。 + +本文会介绍 [数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) 中设计索引的一些方法,让各位读者能够快速的在现有的工程中设计出合适的索引。 + +## 磁盘 IO + +一个数据库必须保证其中存储的所有数据都是可以随时读写的,同时因为 MySQL 中所有的数据其实都是以文件的形式存储在磁盘上的,而从磁盘上**随机访问**对应的数据非常耗时,所以数据库程序和操作系统提供了缓冲池和内存以提高数据的访问速度。 + +![Disk-IO](images/sql-index-intro/Disk-IO.jpg) + +除此之外,我们还需要知道数据库对数据的读取并不是以行为单位进行的,无论是读取一行还是多行,都会将该行或者多行所在的页全部加载进来,然后再读取对应的数据记录;也就是说,读取所耗费的时间与行数无关,只与页数有关。 + +![Page-DatabaseBufferPool](images/sql-index-intro/Page-DatabaseBufferPool.jpg) + +在 MySQL 中,页的大小一般为 16KB,不过也可能是 8KB、32KB 或者其他值,这跟 MySQL 的存储引擎对数据的存储方式有很大的关系,文中不会展开介绍,不过**索引或行记录是否在缓存池中极大的影响了访问索引或者数据的成本**。 + +### 随机读取 + +数据库等待一个页从磁盘读取到缓存池的所需要的成本巨大的,无论我们是想要读取一个页面上的多条数据还是一条数据,都需要消耗**约** 10ms 左右的时间: + +![Disk-Random-IO](images/sql-index-intro/Disk-Random-IO.jpg) + +10ms 的时间在计算领域其实是一个非常巨大的成本,假设我们使用脚本向装了 SSD 的磁盘上顺序写入字节,那么在 10ms 内可以写入大概 3MB 左右的内容,但是数据库程序在 10ms 之内只能将一页的数据加载到数据库缓冲池中,从这里可以看出随机读取的代价是巨大的。 + +![Disk-IO-Total-Time](images/sql-index-intro/Disk-IO-Total-Time.jpg) + +这 10ms 的一次随机读取是按照每秒 50 次的读取计算得到的,其中等待时间为 3ms、磁盘的实际繁忙时间约为 6ms,最终数据页从磁盘传输到缓冲池的时间为 1ms 左右,在对查询进行估算时并不需要准确的知道随机读取的时间,只需要知道估算出的 10ms 就可以了。 + +### 内存读取 + +如果在数据库的**缓存池**中没有找到对应的数据页,那么会去内存中寻找对应的页面: + +![Read-from-Memory](images/sql-index-intro/Read-from-Memory.jpg) + +当对应的页面存在于内存时,数据库程序就会使用内存中的页,这能够将数据的读取时间降低一个数量级,将 10ms 降低到 1ms;MySQL 在执行读操作时,会先从数据库的缓冲区中读取,如果不存在与缓冲区中就会尝试从内存中加载页面,如果前面的两个步骤都失败了,最后就只能执行随机 IO 从磁盘中获取对应的数据页。 + +### 顺序读取 + +从磁盘读取数据并不是都要付出很大的代价,当数据库管理程序一次性从磁盘中**顺序**读取大量的数据时,读取的速度会异常的快,大概在 40MB/s 左右。 + +![Sequential-Reads-from-Disk](images/sql-index-intro/Sequential-Reads-from-Disk.jpg) + +如果一个页面的大小为 4KB,那么 1s 的时间就可以读取 10000 个页,读取一个页面所花费的平均时间就是 0.1ms,相比随机读取的 10ms 已经降低了两个数量级,甚至比内存中读取数据还要快。 + +![Random-to-Sequentia](images/sql-index-intro/Random-to-Sequential.jpg) + +数据页面的顺序读取有两个非常重要的优势: + +1. 同时读取多个界面意味着总时间的消耗会大幅度减少,磁盘的吞吐量可以达到 40MB/s; +2. 数据库管理程序会对一些即将使用的界面进行预读,以减少查询请求的等待和响应时间; + +### 小结 + +数据库查询操作的时间大都消耗在从磁盘或者内存中读取数据的过程,由于随机 IO 的代价巨大,如何在一次数据库查询中减少随机 IO 的次数往往能够大幅度的降低查询所耗费的时间提高磁盘的吞吐量。 + +## 查询过程 + +在上一节中,文章从数据页加载的角度介绍了磁盘 IO 对 MySQL 查询的影响,而在这一节中将介绍 MySQL 查询的执行过程中以及数据库中的数据的特征对最终查询性能的影响。 + +### 索引片(Index Slices) + +索引片其实就是 SQL 查询在执行过程中扫描的一个索引片段,在这个范围中的索引将被顺序扫描,根据索引片包含的列数不同,[数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) 书中对将索引分为宽索引和窄索引: + +![Thin-Index-and-Fat-Index](images/sql-index-intro/Thin-Index-and-Fat-Index.jpg) + +> 主键列 `id` 在所有的 MySQL 索引中都是一定会存在的。 + +对于查询 `SELECT id, username, age FROM users WHERE username="draven"` 来说,(id, username) 就是一个窄索引,因为该索引没有包含存在于 SQL 查询中的 age 列,而 (id, username, age) 就是该查询的一个宽索引了,它**包含这个查询中所需要的全部数据列**。 + +宽索引能够避免二次的随机 IO,而窄索引就需要在对索引进行顺序读取之后再根据主键 id 从主键索引中查找对应的数据: + +![Thin-Index-and-Clustered-Index](images/sql-index-intro/Thin-Index-and-Clustered-Index.jpg) + +对于窄索引,每一个在索引中匹配到的记录行最终都需要执行另外的随机读取从聚集索引中获得剩余的数据,如果结果集非常大,那么就会导致随机读取的次数过多进而影响性能。 + +### 过滤因子 + +从上一小节对索引片的介绍,我们可以看到影响 SQL 查询的除了查询本身还与数据库表中的数据特征有关,如果使用的是窄索引那么对表的随机访问就不可避免,在这时如何让索引片变『薄』就是我们需要做的了。 + +一个 SQL 查询扫描的索引片大小其实是由过滤因子决定的,也就是满足查询条件的记录行数所占的比例: + +![Filter-Facto](images/sql-index-intro/Filter-Factor.jpg) + +对于 users 表来说,sex="male" 就不是一个好的过滤因子,它会选择整张表中一半的数据,所以**在一般情况下**我们最好不要使用 sex 列作为整个索引的第一列;而 name="draven" 的使用就可以得到一个比较好的过滤因子了,它的使用能过滤整个数据表中 99.9% 的数据;当然我们也可以将这三个过滤进行组合,创建一个新的索引 (name, age, sex) 并同时使用这三列作为过滤条件: + +![Combined-Filter-Facto](images/sql-index-intro/Combined-Filter-Factor.jpg) + +> 当三个过滤条件都是等值谓词时,几个索引列的顺序其实是无所谓的,索引列的顺序不会影响同一个 SQL 语句对索引的选择,也就是索引 (name, age, sex) 和 (age, sex, name) 对于上图中的条件来说是完全一样的,这两个索引在执行查询时都有着完全相同的效果。 + +组合条件的过滤因子就可以达到十万分之 6 了,如果整张表中有 10w 行数据,也只需要在扫描薄索引片后进行 6 次随机读取,这种直接使用乘积来计算组合条件的过滤因子其实有一个比较重要的问题:列与列之间不应该有太强的相关性,如果不同的列之间有相关性,那么得到的结果就会比直接乘积得出的结果大一些,比如:所在的城市和邮政编码就有非常强的相关性,两者的过滤因子直接相乘其实与实际的过滤因子会有很大的偏差,不过这在多数情况下都不是太大的问题。 + +对于一张表中的同一个列,不同的值也会有不同的过滤因子,这也就造成了同一列的不同值最终的查询性能也会有很大差别: + +![Same-Columns-Filter-Facto](images/sql-index-intro/Same-Columns-Filter-Factor.jpg) + +当我们评估一个索引是否合适时,需要考虑极端情况下查询语句的性能,比如 0% 或者 50% 等;最差的输入往往意味着最差的性能,在平均情况下表现良好的 SQL 语句在极端的输入下可能就完全无法正常工作,这也是在设计索引时需要注意的问题。 + +总而言之,需要扫描的索引片的大小对查询性能的影响至关重要,而扫描的索引记录的数量,就是总行数与组合条件的过滤因子的乘积,索引片的大小最终也决定了从表中读取数据所需要的时间。 + +### 匹配列与过滤列 + +假设在 users 表中有 name、age 和 (name, sex, age) 三个辅助索引;当 WHERE 条件中存在类似 age = 21 或者 name = "draven" 这种**等值谓词**时,它们都会成为匹配列(Matching Column)用于选择索引树中的数据行,但是当我们使用以下查询时: + +```sql +SELECT * FROM users +WHERE name = "draven" AND sex = "male" AND age > 20; +``` + +虽然我们有 (name, sex, age) 索引包含了上述查询条件中的全部列,但是在这里只有 name 和 sex 两列才是匹配列,MySQL 在执行上述查询时,会选择 name 和 sex 作为匹配列,扫描所有满足条件的数据行,然后将 age 当做过滤列(Filtering Column): + +![Match-Columns-Filter-Columns](images/sql-index-intro/Match-Columns-Filter-Columns.jpg) + +过滤列虽然不能够减少索引片的大小,但是能够减少从表中随机读取数据的次数,所以在索引中也扮演着非常重要的角色。 + +## 索引的设计 + +作者相信文章前面的内容已经为索引的设计提供了充足的理论基础和知识,从总体来看如何减少随机读取的次数是设计索引时需要重视的最重要的问题,在这一节中,我们将介绍 [数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) 一书中归纳出的设计最佳索引的方法。 + +### 三星索引 + +三星索引是对于一个查询语句可能的最好索引,如果一个查询语句的索引是三星索引,那么它只需要进行**一次磁盘的随机读及一个窄索引片的顺序扫描**就可以得到全部的结果集;因此其查询的响应时间比普通的索引会少几个数量级;根据书中对三星索引的定义,我们可以理解为主键索引对于 `WHERE id = 1` 就是一个特殊的三星索引,我们只需要对主键索引树进行一次索引访问并且顺序读取一条数据记录查询就结束了。 + +![Three-Star-Index](images/sql-index-intro/Three-Star-Index.jpg) + +为了满足三星索引中的三颗星,我们分别需要做以下几件事情: + +1. 第一颗星需要取出所有等值谓词中的列,作为索引开头的最开始的列(任意顺序); +2. 第二颗星需要将 ORDER BY 列加入索引中; +3. 第三颗星需要将查询语句剩余的列全部加入到索引中; + +> 三星索引的概念和星级的给定来源于 [数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) 书中第四章三星索引一节。 + +如果对于一个查询语句我们依照上述的三个条件进行设计,那么就可以得到该查询的三星索引,这三颗星中的最后一颗星往往都是最容易获得的,满足第三颗星的索引也就是上面提到的宽索引,能够避免大量的随机 IO,如果我们遵循这个顺序为一个 SQL 查询设计索引那么我们就可以得到一个完美的索引了;这三颗星的获得其实也没有表面上这么简单,每一颗星都有自己的意义: + +![Behind-Three-Star-Index](images/sql-index-intro/Behind-Three-Star-Index.jpg) + +1. 第一颗星不只是将等值谓词的列加入索引,它的作用是减少索引片的大小以减少需要扫描的数据行; +2. 第二颗星用于避免排序,减少磁盘 IO 和内存的使用; +3. 第三颗星用于避免每一个索引对应的数据行都需要进行一次随机 IO 从聚集索引中读取剩余的数据; + +在实际场景中,问题往往没有这么简单,我们虽然可以总能够通过宽索引避免大量的随机访问,但是在一些复杂的查询中我们无法同时获得第一颗星和第二颗星。 + +```sql +SELECT id, name, age FROM users +WHERE age BETWEEN 18 AND 21 + AND city = "Beijing" +ORDER BY name; +``` + +在上述查询中,我们总可以通过增加索引中的列以获得第三颗星,但是如果我们想要获得第一颗星就需要最小化索引片的大小,这时索引的前缀必须为 (city, age),在这时再想获得第三颗星就不可能了,哪怕在 age 的后面添加索引列 name,也会因为 name 在范围索引列 age 后面必须进行一次排序操作,最终得到的索引就是 (city, age, name, id): + +![Different-Stars-Index](images/sql-index-intro/Different-Stars-Index.jpg) + +如果我们需要在内存中避免排序的话,就需要交换 age 和 name 的位置了,在这时就可以得到索引 (city, name, age, id),当一个 SQL 查询中**同时拥有范围谓词和 ORDER BY 时**,无论如何我们都是没有办法获得一个三星索引的,我们能够做的就是在这两者之间做出选择,是牺牲第一颗星还是第二颗星。 + +总而言之,在设计单表的索引时,首先把查询中所有的**等值谓词全部取出**以任意顺序放在索引最前面,在这时,如果索引中同时存在范围索引和 ORDER BY 就需要权衡利弊了,希望最小化扫描的索引片厚度时,应该将**过滤因子最小的范围索引列**加入索引,如果希望避免排序就选择 **ORDER BY 中的全部列**,在这之后就只需要将查询中**剩余的全部列**加入索引了,通过这种固定的方法和逻辑就可以最快地获得一个查询语句的二星或者三星索引了。 + +## 总结 + +在单表上对索引进行设计其实还是非常容易的,只需要遵循固定的套路就能设计出一个理想的三星索引,在这里强烈推荐 [数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) 这本书籍,其中包含了大量与索引设计与优化的相关内容;在之后的文章中读者也会分析介绍书中提供的几种估算方法,来帮助我们通过预估问题设计出更高效的索引。 + +> Follow: [Draveness · GitHub](https://github.com/Draveness) + +## Reference + ++ [数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) ++ [File Space Management](https://dev.mysql.com/doc/refman/5.7/en/innodb-file-space.html) ++ [Inside of Hard Drive - YouTube](https://www.youtube.com/watch?v=9eMWG3fwiEU) ++ [Hard Disk Working | How does a hard disk work | Hard Drive - YouTube](https://www.youtube.com/watch?v=4iaxOUYalJU) + diff --git a/contents/Database/sql-index-performance.md b/contents/Database/sql-index-performance.md new file mode 100644 index 0000000..7ae02e2 --- /dev/null +++ b/contents/Database/sql-index-performance.md @@ -0,0 +1,94 @@ +# MySQL 索引性能分析概要 + +上一篇文章 [MySQL 索引设计概要](http://draveness.me/sql-index-intro.html) 介绍了影响索引设计的几大因素,包括过滤因子、索引片的宽窄与大小以及匹配列和过滤列。在文章的后半部分介绍了 [数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) 一书中,理想的三星索引的设计流程和套路,到目前为止虽然我们掌握了单表索引的设计方法,但是却没有分析预估索引耗时的能力。 + +![Proactive-Index-Design](images/sql-index-performance/Proactive-Index-Design.jpg) + +在本文中,我们将介绍书中提到的两种分析索引性能的方法:基本问题法(BQ)和快速估算上限法(QUBE),这两种方法能够帮助我们快速分析、估算索引的性能,及时发现问题。 + +## 基本问题法 + +当我们需要考虑对现有的 SELECT 查询进行分析时,哪怕没有足够的时间,也应该使用基本问题法对查询进行评估,评估的内容非常简单:现有的索引或者即将添加的索引是否包含了 WHERE 中使用的全部列,也就是对于当前查询来说,是否有一个索引是半宽索引。 + +![Semifat-Index-and-Fat-Index](images/sql-index-performance/Semifat-Index-and-Fat-Index.jpg) + +在上一篇文章中,我们介绍过宽索引和窄索引,窄索引 (username) 其实就叫做半宽索引,其中包含了 WHERE 中的全部的列 username,当前索引的对于该查询只有一颗星,它虽然避免了无效的回表查询造成的随机 IO,但是如果当前的索引的性能仍然无法满足需要,就可以添加 age 将该索引变成宽索引 (username, age) 以此来避免回表访问造成的性能影响;对于上图中的简单查询,索引 (username, age) 其实已经是一个三星索引了,但是对于包含 ORDER BY 或者更加复杂的查询,(username, age) 可能就只是二星索引: + +![Complicated-Query-with-Order-By](images/sql-index-performance/Complicated-Query-with-Order-By.jpg) + +在这时如果该索引仍然不能满足性能的需要,就可以考虑按照上一篇文章 [MySQL 索引设计概要](http://draveness.me/sql-index-intro.html) 中提供的索引设计方法重新设计了。 + +> 虽然基本问题法能够快速解决一些由于索引造成的问题,但是它并不能保证足够的性能,当表中有 (city, username, age) 索引,谓词为 `WHERE username="draveness" AND age="21"` 时,使用基本问题法并不能得出正确的结果。 + +## 快速估算上限法 + +基本问题法非常简单,它能够最短的时间内帮助我们评估一个查询的性能,但是它并不能准确地反映一个索引相关的性能问题,而快速估算上限法就是一种更加准确、复杂的方法了;其目的在于在程序开发期间就能将访问路径缓慢的问题暴露出来,这个估算方法的输出就是本地响应时间(Local Response Time): + +![QUBE-LRT](images/sql-index-performance/QUBE-LRT.jpg) + +本地响应时间就是查询在数据库服务器中的耗时,不包括任何的网络延迟和多层环境的通信时间,仅包括执行查询任务的耗时。 + +### 响应时间 + +本地响应时间等于服务时间和排队时间的总和,一次查询请求需要在数据库中等待 CPU 以及磁盘的响应,也可能会因为其他事务正在对同样的数据进行读写,导致当前查询需要等待锁的获取,不过组成响应时间中的主要部分还是磁盘的服务时间: + +![Local-Response-Time](images/sql-index-performance/Local-Response-Time.jpg) + +QUBE 在计算的过程中会忽略除了磁盘排队时间的其他排队时间,这样能够简化整个评估流程,而磁盘的服务时间主要还是包括同步读写以及异步读几个部分: + +![Disk-Service-Time](images/sql-index-performance/Disk-Service-Time.jpg) + +在排除了上述多个部分的内容,我们得到了一个非常简单的估算过程,整个估算时间的输入仅为随机读和顺序读以及数据获取的三个输入,而它们也是影响查询的主要因素: + +![Local-Response-Time-Calculation](images/sql-index-performance/Local-Response-Time-Calculation.jpg) + +其中数据获取的过程在比较不同的索引对同一查询的影响是不需要考虑的,因为同一查询使用不同的索引也会得到相同的结果集,获取的数据也是完全相同的。 + +### 访问 + +当 MySQL 读取一个索引行或者一个表行时,就会发生一次访问,当使用全表扫描或者扫描索引片时,读取的第一个行就是随机访问,随机访问需要磁盘进行寻道和旋转,所以其代价巨大,而接下来顺序读取的所有行都是通过顺序访问读取的,代价只有随机访问的千分之一。 + +如果大量的顺序读取索引行和表行,在原理上可能会造成一些额外的零星的随机访问,不过这对于整个查询的估算来说其实并不重要;在计算本地响应时间时,仍然会把它们当做顺序访问进行估算。 + +### 示例 + +在这里,我们简单地举一个例子来展示如何计算查询在使用某个索引时所需要的本地响应时间,假设我们有一张 `users` 表,其中有一千万条数据: + +![User-Table](images/sql-index-performance/User-Table.jpg) + +在该 `users` 表中除了主键索引之外,还具有以下 (username, city)、(username, age) 和 (username) 几个辅助索引,当我们使用如下所示的查询时: + +![Filter-Facto](images/sql-index-performance/Filter-Factor.jpg) + +两个查询条件分别有着 0.05% 和 12% 的过滤因子,该查询可以直接使用已有的辅助索引 (username, city),接下来我们根据表中的总行数和过滤因子开始估算这一步骤 SQL 的执行时间: + +![Index-Slice-Scan](images/sql-index-performance/Index-Slice-Scan.jpg) + +该查询在开始时会命中 (username, city) 索引,扫描符合条件的索引片,该索引总共会访问 10,000,000 * 0.05% * 12% = 600 条数据,其中包括 1 次的随机访问和 599 次的顺序访问,因为该索引中的列并不能满足查询的需要,所以对于每一个索引行都会产生一次表的随机访问,以获取剩余列 age 的信息: + +![Index-Table-Touch](images/sql-index-performance/Index-Table-Touch.jpg) + +在这个过程中总共产生了 600 次随机访问,最后取回结果集的过程中也会有 600 次 FETCH 操作,从总体上来看这一次 SQL 查询共进行了 **601 次随机访问**、599 次顺序访问和 600 次 FETCH,根据上一节中的公式我们可以得到这个查询的用时约为 6075.99ms 也就是 6s 左右,这个时间对于绝大多数应用都是无法接受的。 + +![SQL-Query-Time](images/sql-index-performance/SQL-Query-Time.jpg) + +在整个查询的过程中,回表查询的 600 次随机访问成为了这个超级慢的查询的主要贡献,为了解决这个问题,我们只需要添加一个 (username, city, age) 索引或者在已有的 (username, city) 后添加新的 age 列就可以避免 600 次的随机访问: + +![SQL-Query-Time-After-Optimization](images/sql-index-performance/SQL-Query-Time-After-Optimization.jpg) + +(username, city, age) 索引对于该查询其实就是一个三星索引了,有关索引设计的内容可以阅读上一篇文章 [MySQL 索引设计概要](http://draveness.me/sql-index-intro.html) 如果读者有充足的时间依然强烈推荐 [数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) 这本书。 + +## 总结 + +这篇文章是这一年来写的最短的一篇文章了,本来想详细介绍一下 [数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) 书中对于索引性能分析的预估方法,仔细想了一下这部分的内容实在太多,例子也非常丰富,只通过一篇文章很难完整地介绍其中的全部内容,所以只选择了其中的一部分知识点简单介绍,这也是这篇文章叫概要的原因。 + +如果对文章的内容有疑问,可以在评论中留言,评论系统使用 Disqus 需要梯子。 + +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> 原文链接:http://draveness.me/sql-index-performance.html + +## Reference + ++ [数据库索引设计与优化](https://www.amazon.cn/图书/dp/B00ZH27RH0) + + diff --git a/contents/Database/transaction.md b/contents/Database/transaction.md new file mode 100644 index 0000000..01dfa48 --- /dev/null +++ b/contents/Database/transaction.md @@ -0,0 +1,216 @@ +# 『浅入深出』MySQL 中事务的实现 + +在关系型数据库中,事务的重要性不言而喻,只要对数据库稍有了解的人都知道事务具有 ACID 四个基本属性,而我们不知道的可能就是数据库是如何实现这四个属性的;在这篇文章中,我们将对事务的实现进行分析,尝试理解数据库是如何实现事务的,当然我们也会在文章中简单对 MySQL 中对 ACID 的实现进行简单的介绍。 + +![Transaction-Basics](images/transaction/Transaction-Basics.jpg) + +事务其实就是**并发控制的基本单位**;相信我们都知道,事务是一个序列操作,其中的操作要么都执行,要么都不执行,它是一个不可分割的工作单位;数据库事务的 ACID 四大特性是事务的基础,了解了 ACID 是如何实现的,我们也就清除了事务的实现,接下来我们将依次介绍数据库是如何实现这四个特性的。 + +## 原子性 + +在学习事务时,经常有人会告诉你,事务就是一系列的操作,要么全部都执行,要都不执行,这其实就是对事务原子性的刻画;虽然事务具有原子性,但是原子性并不是只与事务有关系,它的身影在很多地方都会出现。 + +![Atomic-Operation](images/transaction/Atomic-Operation.jpg) + +由于操作并不具有原子性,并且可以再分为多个操作,当这些操作出现错误或抛出异常时,整个操作就可能不会继续执行下去,而已经进行的操作造成的副作用就可能造成数据更新的丢失或者错误。 + +事务其实和一个操作没有什么太大的区别,它是一系列的数据库操作(可以理解为 SQL)的集合,如果事务不具备原子性,那么就没办法保证同一个事务中的所有操作都被执行或者未被执行了,整个数据库系统就既不可用也不可信。 + +### 回滚日志 + +想要保证事务的原子性,就需要在异常发生时,对已经执行的操作进行**回滚**,而在 MySQL 中,恢复机制是通过*回滚日志*(undo log)实现的,所有事务进行的修改都会先记录到这个回滚日志中,然后在对数据库中的对应行进行写入。 + +![Transaction-Undo-Log](images/transaction/Transaction-Undo-Log.jpg) + +这个过程其实非常好理解,为了能够在发生错误时撤销之前的全部操作,肯定是需要将之前的操作都记录下来的,这样在发生错误时才可以回滚。 + +回滚日志除了能够在发生错误或者用户执行 `ROLLBACK` 时提供回滚相关的信息,它还能够在整个系统发生崩溃、数据库进程直接被杀死后,当用户再次启动数据库进程时,还能够立刻通过查询回滚日志将之前未完成的事务进行回滚,这也就需要回滚日志必须先于数据持久化到磁盘上,是我们需要先写日志后写数据库的主要原因。 + +回滚日志并不能将数据库物理地恢复到执行语句或者事务之前的样子;它是逻辑日志,当回滚日志被使用时,它只会按照日志**逻辑地**将数据库中的修改撤销掉看,可以**理解**为,我们在事务中使用的每一条 `INSERT` 都对应了一条 `DELETE`,每一条 `UPDATE` 也都对应一条相反的 `UPDATE` 语句。 + +![Logical-Undo-Log](images/transaction/Logical-Undo-Log.jpg) + +在这里,我们并不会介绍回滚日志的格式以及它是如何被管理的,本文重点关注在它到底是一个什么样的东西,究竟解决了、如何解决了什么样的问题,如果想要了解具体实现细节的读者,相信网络上关于回滚日志的文章一定不少。 + +### 事务的状态 + +因为事务具有原子性,所以从远处看的话,事务就是密不可分的一个整体,事务的状态也只有三种:Active、Commited 和 Failed,事务要不就在执行中,要不然就是成功或者失败的状态: + +![Atomitc-Transaction-State](images/transaction/Atomitc-Transaction-State.jpg) + +但是如果放大来看,我们会发现事务不再是原子的,其中包括了很多中间状态,比如部分提交,事务的状态图也变得越来越复杂。 + +![Nonatomitc-Transaction-State](images/transaction/Nonatomitc-Transaction-State.jpg) + +> 事务的状态图以及状态的描述取自 [Database System Concepts](https://www.amazon.com/Database-System-Concepts-Computer-Science/dp/0073523321) 一书中第 14 章的内容。 + ++ Active:事务的初始状态,表示事务正在执行; ++ Partially Commited:在最后一条语句执行之后; ++ Failed:发现事务无法正常执行之后; ++ Aborted:事务被回滚并且数据库恢复到了事务进行之前的状态之后; ++ Commited:成功执行整个事务; + +虽然在发生错误时,整个数据库的状态可以恢复,但是如果我们在事务中执行了诸如:向标准输出打印日志、向外界发出邮件、没有通过数据库修改了磁盘上的内容甚至在事务执行期间发生了转账汇款,那么这些操作作为可见的外部输出都是没有办法回滚的;这些问题都是由应用开发者解决和负责的,在绝大多数情况下,我们都需要在整个事务提交后,再触发类似的无法回滚的操作。 + +![Shutdown-After-Commited](images/transaction/Shutdown-After-Commited.jpg) + +以订票为例,哪怕我们在整个事务结束之后,才向第三方发起请求,由于向第三方请求并获取结果是一个需要较长事件的操作,如果在事务刚刚提交时,数据库或者服务器发生了崩溃,那么我们就非常有可能丢失发起请求这一过程,这就造成了非常严重的问题;而这一点就不是数据库所能保证的,开发者需要在适当的时候查看请求是否被发起、结果是成功还是失败。 + +### 并行事务的原子性 + +到目前为止,所有的事务都只是串行执行的,一直都没有考虑过并行执行的问题;然而在实际工作中,并行执行的事务才是常态,然而并行任务下,却可能出现非常复杂的问题: + +![Nonrecoverable-Schedule](images/transaction/Nonrecoverable-Schedule.jpg) + +当 Transaction1 在执行的过程中对 `id = 1` 的用户进行了读写,但是没有将修改的内容进行提交或者回滚,在这时 Transaction2 对同样的数据进行了读操作并提交了事务;也就是说 Transaction2 是依赖于 Transaction1 的,当 Transaction1 由于一些错误需要回滚时,因为要保证事务的原子性,需要对 Transaction2 进行回滚,但是由于我们已经提交了 Transaction2,所以我们已经没有办法进行回滚操作,在这种问题下我们就发生了问题,[Database System Concepts](https://www.amazon.com/Database-System-Concepts-Computer-Science/dp/0073523321) 一书中将这种现象称为*不可恢复安排*(Nonrecoverable Schedule),那什么情况下是可以恢复的呢? + +> A recoverable schedule is one where, for each pair of transactions Ti and Tj such that Tj reads a data item previously written by Ti , the commit operation of Ti appears before the commit operation of Tj . + +简单理解一下,如果 Transaction2 依赖于事务 Transaction1,那么事务 Transaction1 必须在 Transaction2 提交之前完成提交的操作: + +![Recoverable-Schedule](images/transaction/Recoverable-Schedule.jpg) + +然而这样还不算完,当事务的数量逐渐增多时,整个恢复流程也会变得越来越复杂,如果我们想要从事务发生的错误中恢复,也不是一件那么容易的事情。 + +![Cascading-Rollback](images/transaction/Cascading-Rollback.jpg) + +在上图所示的一次事件中,Transaction2 依赖于 Transaction1,而 Transaction3 又依赖于 Transaction1,当 Transaction1 由于执行出现问题发生回滚时,为了保证事务的原子性,就会将 Transaction2 和 Transaction3 中的工作全部回滚,这种情况也叫做*级联回滚*(Cascading Rollback),级联回滚的发生会导致大量的工作需要撤回,是我们难以接受的,不过如果想要达到**绝对的**原子性,这件事情又是不得不去处理的,我们会在文章的后面具体介绍如何处理并行事务的原子性。 + +## 持久性 + +既然是数据库,那么一定对数据的持久存储有着非常强烈的需求,如果数据被写入到数据库中,那么数据一定能够被安全存储在磁盘上;而事务的持久性就体现在,一旦事务被提交,那么数据一定会被写入到数据库中并持久存储起来。 + +![Compensating-Transaction](images/transaction/Compensating-Transaction.jpg) + +当事务已经被提交之后,就无法再次回滚了,唯一能够撤回已经提交的事务的方式就是创建一个相反的事务对原操作进行『补偿』,这也是事务持久性的体现之一。 + +### 重做日志 + +与原子性一样,事务的持久性也是通过日志来实现的,MySQL 使用重做日志(redo log)实现事务的持久性,重做日志由两部分组成,一是内存中的重做日志缓冲区,因为重做日志缓冲区在内存中,所以它是易失的,另一个就是在磁盘上的重做日志文件,它是持久的。 + +![Redo-Logging](images/transaction/Redo-Logging.jpg) + +当我们在一个事务中尝试对数据进行修改时,它会先将数据从磁盘读入内存,并更新内存中缓存的数据,然后生成一条重做日志并写入重做日志缓存,当事务真正提交时,MySQL 会将重做日志缓存中的内容刷新到重做日志文件,再将内存中的数据更新到磁盘上,图中的第 4、5 步就是在事务提交时执行的。 + +在 InnoDB 中,重做日志都是以 512 字节的块的形式进行存储的,同时因为块的大小与磁盘扇区大小相同,所以重做日志的写入可以保证原子性,不会由于机器断电导致重做日志仅写入一半并留下脏数据。 + +除了所有对数据库的修改会产生重做日志,因为回滚日志也是需要持久存储的,它们也会创建对应的重做日志,在发生错误后,数据库重启时会从重做日志中找出未被更新到数据库磁盘中的日志重新执行以满足事务的持久性。 + +### 回滚日志和重做日志 + +到现在为止我们了解了 MySQL 中的两种日志,回滚日志(undo log)和重做日志(redo log);在数据库系统中,事务的原子性和持久性是由事务日志(transaction log)保证的,在实现时也就是上面提到的两种日志,前者用于对事务的影响进行撤销,后者在错误处理时对已经提交的事务进行重做,它们能保证两点: + +1. 发生错误或者需要回滚的事务能够成功回滚(原子性); +2. 在事务提交后,数据没来得及写会磁盘就宕机时,在下次重新启动后能够成功恢复数据(持久性); + +在数据库中,这两种日志经常都是一起工作的,我们**可以**将它们整体看做一条事务日志,其中包含了事务的 ID、修改的行元素以及修改前后的值。 + +![Transaction-Log](images/transaction/Transaction-Log.jpg) + +一条事务日志同时包含了修改前后的值,能够非常简单的进行回滚和重做两种操作,在这里我们也不会对重做和回滚日志展开进行介绍,可能会在之后的文章谈一谈数据库系统的恢复机制时提到两种日志的使用。 + +## 隔离性 + +其实作者在之前的文章 [『浅入浅出』MySQL 和 InnoDB](http://draveness.me/mysql-innodb.html) 就已经介绍过数据库事务的隔离性,不过问了保证文章的独立性和完整性,我们还会对事务的隔离性进行介绍,介绍的内容可能稍微有所不同。 + +事务的隔离性是数据库处理数据的几大基础之一,如果没有数据库的事务之间没有隔离性,就会发生在 [并行事务的原子性](#并行事务的原子性) 一节中提到的级联回滚等问题,造成性能上的巨大损失。如果所有的事务的执行顺序都是线性的,那么对于事务的管理容易得多,但是允许事务的并行执行却能能够提升吞吐量和资源利用率,并且可以减少每个事务的等待时间。 + +![Reasons-for-Allowing-Concurrency](images/transaction/Reasons-for-Allowing-Concurrency.jpg) + +当多个事务同时并发执行时,事务的隔离性可能就会被违反,虽然单个事务的执行可能没有任何错误,但是从总体来看就会造成数据库的一致性出现问题,而串行虽然能够允许开发者忽略并行造成的影响,能够很好地维护数据库的一致性,但是却会影响事务执行的性能。 + +### 事务的隔离级别 + +所以说数据库的隔离性和一致性其实是一个需要开发者去权衡的问题,为数据库提供什么样的隔离性层级也就决定了数据库的性能以及可以达到什么样的一致性;在 SQL 标准中定义了四种数据库的事务的隔离级别:`READ UNCOMMITED`、`READ COMMITED`、`REPEATABLE READ` 和 `SERIALIZABLE`;每个事务的隔离级别其实都比上一级多解决了一个问题: + ++ `RAED UNCOMMITED`:使用查询语句不会加锁,可能会读到未提交的行(Dirty Read); ++ `READ COMMITED`:只对记录加记录锁,而不会在记录之间加间隙锁,所以允许新的记录插入到被锁定记录的附近,所以再多次使用查询语句时,可能得到不同的结果(Non-Repeatable Read); ++ `REPEATABLE READ`:多次读取同一范围的数据会返回第一次查询的快照,不会返回不同的数据行,但是可能发生幻读(Phantom Read); ++ `SERIALIZABLE`:InnoDB 隐式地将全部的查询语句加上共享锁,解决了幻读的问题; + +以上的所有的事务隔离级别都不允许脏写入(Dirty Write),也就是当前事务更新了另一个事务已经更新但是还未提交的数据,大部分的数据库中都使用了 READ COMMITED 作为默认的事务隔离级别,但是 MySQL 使用了 REPEATABLE READ 作为默认配置;从 RAED UNCOMMITED 到 SERIALIZABLE,随着事务隔离级别变得越来越严格,数据库对于并发执行事务的性能也逐渐下降。 + +![Isolation-Performance](images/transaction/Isolation-Performance.jpg) + +对于数据库的使用者,从理论上说,并不需要知道事务的隔离级别是如何实现的,我们只需要知道这个隔离级别解决了什么样的问题,但是不同数据库对于不同隔离级别的是实现细节在很多时候都会让我们遇到意料之外的坑。 + +如果读者不了解脏读、不可重复读和幻读究竟是什么,可以阅读之前的文章 [『浅入浅出』MySQL 和 InnoDB](http://draveness.me/mysql-innodb.html),在这里我们仅放一张图来展示各个隔离层级对这几个问题的解决情况。 + +![Transaction-Isolation-Matrix](images/transaction/Transaction-Isolation-Matrix.jpg) + +### 隔离级别的实现 + +数据库对于隔离级别的实现就是使用**并发控制机制**对在同一时间执行的事务进行控制,限制不同的事务对于同一资源的访问和更新,而最重要也最常见的并发控制机制,在这里我们将简单介绍三种最重要的并发控制器机制的工作原理。 + +#### 锁 + +锁是一种最为常见的并发控制机制,在一个事务中,我们并不会将整个数据库都加锁,而是只会锁住那些需要访问的数据项, MySQL 和常见数据库中的锁都分为两种,共享锁(Shared)和互斥锁(Exclusive),前者也叫读锁,后者叫写锁。 + +![Shared-Exclusive-Lock](images/transaction/Shared-Exclusive-Lock.jpg) + +读锁保证了读操作可以并发执行,相互不会影响,而写锁保证了在更新数据库数据时不会有其他的事务访问或者更改同一条记录造成不可预知的问题。 + +#### 时间戳 + +除了锁,另一种实现事务的隔离性的方式就是通过时间戳,使用这种方式实现事务的数据库,例如 PostgreSQL 会为每一条记录保留两个字段;*读时间戳*中报错了所有访问该记录的事务中的最大时间戳,而记录行的*写时间戳*中保存了将记录改到当前值的事务的时间戳。 + +![Timestamps-Record](images/transaction/Timestamps-Record.jpg) + +使用时间戳实现事务的隔离性时,往往都会使用乐观锁,先对数据进行修改,在写回时再去判断当前值,也就是时间戳是否改变过,如果没有改变过,就写入,否则,生成一个新的时间戳并再次更新数据,乐观锁其实并不是真正的锁机制,它只是一种思想,在这里并不会对它进行展开介绍。 + +#### 多版本和快照隔离 + +通过维护多个版本的数据,数据库可以允许事务在数据被其他事务更新时对旧版本的数据进行读取,很多数据库都对这一机制进行了实现;因为所有的读操作不再需要等待写锁的释放,所以能够显著地提升读的性能,MySQL 和 PostgreSQL 都对这一机制进行自己的实现,也就是 MVCC,虽然各自实现的方式有所不同,MySQL 就通过文章中提到的回滚日志实现了 MVCC,保证事务并行执行时能够不等待互斥锁的释放直接获取数据。 + +### 隔离性与原子性 + +在这里就需要简单提一下在在原子性一节中遇到的级联回滚等问题了,如果一个事务对数据进行了写入,这时就会获取一个互斥锁,其他的事务就想要获得改行数据的读锁就必须等待写锁的释放,自然就不会发生级联回滚等问题了。 + +![Shared-Lock-and-Atomicity](images/transaction/Shared-Lock-and-Atomicity.jpg) + +不过在大多数的数据库,比如 MySQL 中都使用了 MVCC 等特性,也就是正常的读方法是不需要获取锁的,在想要对读取的数据进行更新时需要使用 `SELECT ... FOR UPDATE` 尝试获取对应行的互斥锁,以保证不同事务可以正常工作。 + +## 一致性 + +作者认为数据库的一致性是一个非常让人迷惑的概念,原因是数据库领域其实包含两个一致性,一个是 ACID 中的一致性、另一个是 CAP 定义中的一致性。 + +![ACID-And-CAP](images/transaction/ACID-And-CAP.jpg) + +这两个数据库的一致性说的**完全不是**一个事情,很多很多人都对这两者的概念有非常深的误解,当我们在讨论数据库的一致性时,一定要清楚上下文的语义是什么,尽量明确的问出我们要讨论的到底是 ACID 中的一致性还是 CAP 中的一致性。 + +### ACID + +数据库对于 ACID 中的一致性的定义是这样的:如果一个事务原子地在一个一致地数据库中独立运行,那么在它执行之后,数据库的状态一定是一致的。对于这个概念,它的第一层意思就是对于数据完整性的约束,包括主键约束、引用约束以及一些约束检查等等,在事务的执行的前后以及过程中不会违背对数据完整性的约束,所有对数据库写入的操作都应该是合法的,并不能产生不合法的数据状态。 + +> A transaction must preserve database consistency - if a transaction is run atomically in isolation starting from a consistent database, the database must again be consistent at the end of the transaction. + +我们可以将事务理解成一个函数,它接受一个外界的 SQL 输入和一个一致的数据库,它一定会返回一个一致的数据库。 + +![Transaction-Consistency](images/transaction/Transaction-Consistency.jpg) + +而第二层意思其实是指逻辑上的对于开发者的要求,我们要在代码中写出正确的事务逻辑,比如银行转账,事务中的逻辑不可能只扣钱或者只加钱,这是应用层面上对于数据库一致性的要求。 + +> Ensuring consistency for an individual transaction is the responsibility of the application programmer who codes the transaction. - [Database System Concepts](https://www.amazon.com/Database-System-Concepts-Computer-Science/dp/0073523321) + +数据库 ACID 中的一致性对事务的要求不止包含对数据完整性以及合法性的检查,还包含应用层面逻辑的正确。 + +CAP 定理中的数据一致性,其实是说分布式系统中的各个节点中对于同一数据的拷贝有着相同的值;而 ACID 中的一致性是指数据库的规则,如果 schema 中规定了一个值必须是唯一的,那么一致的系统必须确保在所有的操作中,该值都是唯一的,由此来看 CAP 和 ACID 对于一致性的定义有着根本性的区别。 + +## 总结 + +事务的 ACID 四大基本特性是保证数据库能够运行的基石,但是完全保证数据库的 ACID,尤其是隔离性会对性能有比较大影响,在实际的使用中我们也会根据业务的需求对隔离性进行调整,除了隔离性,数据库的原子性和持久性相信都是比较好理解的特性,前者保证数据库的事务要么全部执行、要么全部不执行,后者保证了对数据库的写入都是持久存储的、非易失的,而一致性不仅是数据库对本身数据的完整性的要求,同时也对开发者提出了要求 - 写出逻辑正确并且合理的事务。 + +最后,也是最重要的,当别人在将一致性的时候,一定要搞清楚他的上下文,如果对文章的内容有疑问,可以在评论中留言,评论系统使用 Disqus 需要梯子。 + +## References + ++ [Database System Concepts](https://www.amazon.com/Database-System-Concepts-Computer-Science/dp/0073523321) ++ [数据库事务](https://zh.wikipedia.org/wiki/数据库事务) ++ [How does MVCC (Multi-Version Concurrency Control) work](https://vladmihalcea.com/2017/03/01/how-does-mvcc-multi-version-concurrency-control-work/) ++ [How does a relational database work](https://vladmihalcea.com/2017/02/14/how-does-a-relational-database-work/) ++ [Implementing Transaction Processing using Redo Logs](http://www.mathcs.emory.edu/~cheung/Courses/377/Syllabus/10-Transactions/redo-log.html) ++ [Implementing Transaction Processing using Undo Logs](http://www.mathcs.emory.edu/~cheung/Courses/377/Syllabus/10-Transactions/undo-log.html) ++ [Undo/Redo Logging Rules](http://cs.ulb.ac.be/public/_media/teaching/infoh417/05_-_logging-sol-slides.pdf) ++ [MySQL 解密:InnoDB 存储引擎重做日志漫游](https://www.qiancheng.me/post/coding/mysql-001) ++ [ACID 中 C 与 CAP 定理中 C 的区别](http://www.jdon.com/46956) ++ [Disambiguating ACID and CAP](https://www.voltdb.com/blog/2015/10/22/disambiguating-acid-cap/) diff --git "a/contents/FBRetainCycleDetector/iOS \344\270\255\347\232\204 block \346\230\257\345\246\202\344\275\225\346\214\201\346\234\211\345\257\271\350\261\241\347\232\204.md" "b/contents/FBRetainCycleDetector/iOS \344\270\255\347\232\204 block \346\230\257\345\246\202\344\275\225\346\214\201\346\234\211\345\257\271\350\261\241\347\232\204.md" new file mode 100644 index 0000000..8149569 --- /dev/null +++ "b/contents/FBRetainCycleDetector/iOS \344\270\255\347\232\204 block \346\230\257\345\246\202\344\275\225\346\214\201\346\234\211\345\257\271\350\261\241\347\232\204.md" @@ -0,0 +1,390 @@ +# iOS 中的 block 是如何持有对象的 + +> Follow: [Draveness · Github](https://github.com/Draveness) + +Block 是 Objective-C 中笔者最喜欢的特性,它为 Objective-C 这门语言提供了强大的函数式编程能力,而最近苹果推出的很多新的 API 都已经开始原生的支持 block 语法,可见它在 Objective-C 中变得越来越重要。 + +![](images/block.jpg) + +这篇文章并不会详细介绍 block 在内存中到底是以什么形式存在的,主要会介绍 block 是如何持有并且释放对象的。文章中的代码都出自 Facebook 开源的**用于检测循环引用**的框架 [FBRetainCycleDetector](https://github.com/facebook/FBRetainCycleDetector),这是分析该框架文章中的最后一篇,也是笔者觉得最有意思的一部分。 + +> 如果你希望了解 FBRetainCycleDetector 的原理可以阅读[如何在 iOS 中解决循环引用的问题](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/FBRetainCycleDetector/如何在%20iOS%20中解决循环引用的问题.md)以及后续文章。 + +## 为什么会谈到 block + +可能很多读者会有这样的疑问,本文既然是对 `FBRetainCycleDetector` 解析的文章,为什么会提到 block?原因其实很简单,因为在 iOS 开发中大多数的循环引用都是因为 block 使用不当导致的,由于 block 会 retain 它持有的对象,这样就很容易造成循环引用,最终导致内存泄露。 + +在 `FBRetainCycleDetector` 中存在这样一个类 `FBObjectiveCBlock`,这个类的 `- allRetainedObjects` 方法就会返回所有 block 持有的强引用,这也是文章需要关注的重点。 + +```objectivec +- (NSSet *)allRetainedObjects { + NSMutableArray *results = [[[super allRetainedObjects] allObjects] mutableCopy]; + + __attribute__((objc_precise_lifetime)) id anObject = self.object; + + void *blockObjectReference = (__bridge void *)anObject; + NSArray *allRetainedReferences = FBGetBlockStrongReferences(blockObjectReference); + + for (id object in allRetainedReferences) { + FBObjectiveCGraphElement *element = FBWrapObjectGraphElement(self, object, self.configuration); + if (element) { + [results addObject:element]; + } + } + + return [NSSet setWithArray:results]; +} +``` + +这部分代码中的大部分都不重要,只是在开头调用父类方法,在最后将获取的对象包装成一个系列 `FBObjectiveCGraphElement`,最后返回一个数组,也就是当前对象 block 持有的全部强引用了。 + +## Block 是什么? + +对 block 稍微有了解的人都知道,block 其实是一个结构体,其结构大概是这样的: + +```objectivec +struct BlockLiteral { + void *isa; + int flags; + int reserved; + void (*invoke)(void *, ...); + struct BlockDescriptor *descriptor; +}; + +struct BlockDescriptor { + unsigned long int reserved; + unsigned long int size; + void (*copy_helper)(void *dst, void *src); + void (*dispose_helper)(void *src); + const char *signature; +}; +``` + +在 `BlockLiteral` 结构体中有一个 `isa` 指针,而对 `isa`了解的人也都知道,这里的 `isa` 其实指向了一个类,每一个 block 指向的类可能是 `__NSGlobalBlock__`、`__NSMallocBlock__` 或者 `__NSStackBlock__`,但是这些 block,它们继承自一个共同的父类,也就是 `NSBlock`,我们可以使用下面的代码来获取这个类: + +```objectivec +static Class _BlockClass() { + static dispatch_once_t onceToken; + static Class blockClass; + dispatch_once(&onceToken, ^{ + void (^testBlock)() = [^{} copy]; + blockClass = [testBlock class]; + while(class_getSuperclass(blockClass) && class_getSuperclass(blockClass) != [NSObject class]) { + blockClass = class_getSuperclass(blockClass); + } + [testBlock release]; + }); + return blockClass; +} +``` + +Objective-C 中的三种 block `__NSMallocBlock__`、`__NSStackBlock__` 和 `__NSGlobalBlock__` 会在下面的情况下出现: + +| | ARC | 非 ARC | +|------------|:----------------------------:|-----------------------------| +| 捕获外部变量 | `__NSMallocBlock__` <br> `__NSStackBlock__` | `__NSStackBlock__`| +| 未捕获外部变量 | `__NSGlobalBlock__`| `__NSGlobalBlock__` | + + ++ 在 ARC 中,捕获外部了变量的 block 的类会是 `__NSMallocBlock__` 或者 `__NSStackBlock__`,如果 block 被赋值给了某个变量在这个过程中会执行 `_Block_copy` 将原有的 `__NSStackBlock__` 变成 `__NSMallocBlock__`;但是如果 block 没有被赋值给某个变量,那它的类型就是 `__NSStackBlock__`;没有捕获外部变量的 block 的类会是 `__NSGlobalBlock__` 即不在堆上,也不在栈上,它类似 C 语言函数一样会在代码段中。 ++ 在非 ARC 中,捕获了外部变量的 block 的类会是 `__NSStackBlock__`,放置在栈上,没有捕获外部变量的 block 时与 ARC 环境下情况相同。 + +如果我们不断打印一个 block 的 `superclass` 的话最后就会在继承链中找到 `NSBlock` 的身影: + +![block-superclass](images/block-superclass.png) + +然后可以通过这种办法来判断当前对象是不是 block: + +```objectivec +BOOL FBObjectIsBlock(void *object) { + Class blockClass = _BlockClass(); + + Class candidate = object_getClass((__bridge id)object); + return [candidate isSubclassOfClass:blockClass]; +} +``` + +## Block 如何持有对象 + +在这一小节,我们将讨论 block 是**如何持有对象**的,我们会通过对 FBRetainCycleDetector 的源代码进行分析最后尽量详尽地回答这一问题。 + +重新回到文章开头提到的 `- allRetainedObjects` 方法: + +```objectivec +- (NSSet *)allRetainedObjects { + NSMutableArray *results = [[[super allRetainedObjects] allObjects] mutableCopy]; + + __attribute__((objc_precise_lifetime)) id anObject = self.object; + + void *blockObjectReference = (__bridge void *)anObject; + NSArray *allRetainedReferences = FBGetBlockStrongReferences(blockObjectReference); + + for (id object in allRetainedReferences) { + FBObjectiveCGraphElement *element = FBWrapObjectGraphElement(self, object, self.configuration); + if (element) { + [results addObject:element]; + } + } + + return [NSSet setWithArray:results]; +} +``` + +通过函数的符号我们也能够猜测出,上述方法中通过 `FBGetBlockStrongReferences` 获取 block 持有的所有强引用: + +```objectivec +NSArray *FBGetBlockStrongReferences(void *block) { + if (!FBObjectIsBlock(block)) { + return nil; + } + + NSMutableArray *results = [NSMutableArray new]; + + void **blockReference = block; + NSIndexSet *strongLayout = _GetBlockStrongLayout(block); + [strongLayout enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) { + void **reference = &blockReference[idx]; + + if (reference && (*reference)) { + id object = (id)(*reference); + + if (object) { + [results addObject:object]; + } + } + }]; + + return [results autorelease]; +} +``` + +而 `FBGetBlockStrongReferences` 是对另一个私有函数 `_GetBlockStrongLayout` 的封装,也是实现最有意思的部分。 + +### 几个必要的概念 + +在具体介绍 `_GetBlockStrongLayout` 函数的源代码之前,我希望先对其原理有一个简单的介绍,便于各位读者的理解;在这里有三个概念需要介绍,首先是 block 持有的对象都存在的位置。 + +#### 如何持有对象 + +在文章的上面曾经出现过 block 的结构体,不知道各位读者是否还有印象: + +```objectivec +struct BlockLiteral { + void *isa; + int flags; + int reserved; + void (*invoke)(void *, ...); + struct BlockDescriptor *descriptor; + // imported variables +}; +``` + +在每个 block 结构体的下面就会存放当前 block 持有的所有对象,无论强弱。我们可以做一个小实验来验证这个观点,我们在程序中声明这样一个 block: + +```objectivec +NSObject *firstObject = [NSObject new]; +__attribute__((objc_precise_lifetime)) NSObject *object = [NSObject new]; +__weak NSObject *secondObject = object; +NSObject *thirdObject = [NSObject new]; + +__unused void (^block)() = ^{ + __unused NSObject *first = firstObject; + __unused NSObject *second = secondObject; + __unused NSObject *third = thirdObject; +}; +``` + +然后在代码中打一个断点: + +![block-capture-var-layout](images/block-capture-var-layout.png) + + +> 上面代码中 block 由于被变量引用,执行了 `_Block_copy`,所以其类型为 `__NSMallocBlock__`,没有被变量引用的 block 都是 `__NSStackBlock__`。 + +1. 首先打印 block 变量的大小,因为 block 变量其实只是一个指向结构体的指针,所以大小为 8,而结构体的大小为 32; +2. 以 block 的地址为基址,偏移 32,得到一个指针 +3. 使用 `$3[0]` `$3[1]` `$3[2]` 依次打印地址为 `0x1001023b0` `0x1001023b8` `0x1001023c0` 的内容,可以发现它们就是 block 捕获的全部引用,前两个是强引用,最后的是弱引用 + +这可以得出一个结论:block 将其捕获的引用存放在结构体的下面,但是为什么这里的顺序并不是按照引用的顺序呢?接下来增加几个变量,再做另一次实验: + +![block-capture-strong-weak-orde](images/block-capture-strong-weak-order.png) + +在代码中多加入了几个对象之后,block 对持有的对象的布局的顺序依然是**强引用在前、弱引用在后**,我们不妨做一个假设:**block 会将强引用的对象排放在弱引用对象的前面**。但是这个假设能够帮助我们在**只有 block 但是没有上下文信息的情况下**区分哪些是强引用么?我觉得并不能,因为我们没有办法知道它们之间的分界线到底在哪里。 + +#### dispose_helper + +第二个需要介绍的是 `dispose_helper`,这是 `BlockDescriptor` 结构体中的一个指针: + +```objectivec +struct BlockDescriptor { + unsigned long int reserved; // NULL + unsigned long int size; + // optional helper functions + void (*copy_helper)(void *dst, void *src); // IFF (1<<25) + void (*dispose_helper)(void *src); // IFF (1<<25) + const char *signature; // IFF (1<<30) +}; +``` + +上面的结构体中有两个函数指针,`copy_helper` 用于 block 的拷贝,`dispose_helper` 用于 block 的 `dispose` 也就是 block 在析构的时候会调用这个函数指针,销毁自己持有的对象,而这个原理也是区别强弱引用的关键,因为在 `dispose_helper` 会对强引用发送 `release` 消息,对弱引用不会做任何的处理。 + +#### FBBlockStrongRelationDetector + +最后就是用于从 `dispose_helper` 接收消息的类 `FBBlockStrongRelationDetector` 了;它的实例在接受 `release` 消息时,并不会真正的释放,只会将标记 `_strong` 为 YES: + +```objectivec +- (oneway void)release { + _strong = YES; +} + +- (oneway void)trueRelease { + [super release]; +} +``` + +只有真正执行 `trueRelease` 的时候才会向对象发送 `release` 消息。 + +因为这个文件覆写了 `release` 方法,所以要在非 ARC 下编译: + +```objectivec +#if __has_feature(objc_arc) +#error This file must be compiled with MRR. Use -fno-objc-arc flag. +#endif +``` + +如果 block 持有了另一个 block 对象,`FBBlockStrongRelationDetector` 也可以将自身 fake 成为一个假的 block 防止在接收到关于 block 释放的消息时发生 crash: + +```objectivec +struct _block_byref_block; +@interface FBBlockStrongRelationDetector : NSObject { + // __block fakery + void *forwarding; + int flags; //refcount; + int size; + void (*byref_keep)(struct _block_byref_block *dst, struct _block_byref_block *src); + void (*byref_dispose)(struct _block_byref_block *); + void *captured[16]; +} +``` + +该类的实例在初始化时,会设置 `forwarding`、`byref_keep` 和 `byref_dispose`,后两个方法的实现都是空的,只是为了防止 crash: + +```objectivec ++ (id)alloc { + FBBlockStrongRelationDetector *obj = [super alloc]; + + // Setting up block fakery + obj->forwarding = obj; + obj->byref_keep = byref_keep_nop; + obj->byref_dispose = byref_dispose_nop; + + return obj; +} + +static void byref_keep_nop(struct _block_byref_block *dst, struct _block_byref_block *src) {} +static void byref_dispose_nop(struct _block_byref_block *param) {} +``` + +### 获取 block 强引用的对象 + +到现在为止,获取 block 强引用对象所需要的知识都介绍完了,接下来可以对私有方法 `_GetBlockStrongLayout` 进行分析了: + +```objectivec +static NSIndexSet *_GetBlockStrongLayout(void *block) { + struct BlockLiteral *blockLiteral = block; + + if ((blockLiteral->flags & BLOCK_HAS_CTOR) + || !(blockLiteral->flags & BLOCK_HAS_COPY_DISPOSE)) { + return nil; + } + + ... +} +``` + ++ 如果 block 有 Cpp 的构造器/析构器,说明它**持有的对象很有可能没有按照指针大小对齐**,我们很难检测到所有的对象 ++ 如果 block 没有 `dispose` 函数,说明它无法 `retain` 对象,也就是说我们也没有办法测试其强引用了哪些对象 + +```objectivec +static NSIndexSet *_GetBlockStrongLayout(void *block) { + ... + void (*dispose_helper)(void *src) = blockLiteral->descriptor->dispose_helper; + const size_t ptrSize = sizeof(void *); + const size_t elements = (blockLiteral->descriptor->size + ptrSize - 1) / ptrSize; + + void *obj[elements]; + void *detectors[elements]; + + for (size_t i = 0; i < elements; ++i) { + FBBlockStrongRelationDetector *detector = [FBBlockStrongRelationDetector new]; + obj[i] = detectors[i] = detector; + } + + @autoreleasepool { + dispose_helper(obj); + } + ... +} +``` + +1. 从 `BlockDescriptor` 取出 `dispose_helper` 以及 `size`(block 持有的所有对象的大小) +2. 通过 `(blockLiteral->descriptor->size + ptrSize - 1) / ptrSize` 向上取整,获取 block 持有的指针的数量 +3. 初始化两个包含 `elements` 个 `FBBlockStrongRelationDetector` 实例的数组,其中第一个数组用于传入 `dispose_helper`,第二个数组用于检测 `_strong` 是否被标记为 `YES` +4. 在自动释放池中执行 `dispose_helper(obj)`,释放 block 持有的对象 + +```objectivec +static NSIndexSet *_GetBlockStrongLayout(void *block) { + ... + NSMutableIndexSet *layout = [NSMutableIndexSet indexSet]; + + for (size_t i = 0; i < elements; ++i) { + FBBlockStrongRelationDetector *detector = (FBBlockStrongRelationDetector *)(detectors[i]); + if (detector.isStrong) { + [layout addIndex:i]; + } + + [detector trueRelease]; + } + + return layout; +} +``` + +因为 `dispose_helper` 只会调用 `release` 方法,但是这并不会导致我们的 `FBBlockStrongRelationDetector` 实例被释放掉,反而会标记 `_string` 属性,在这里我们只需要判断这个属性的真假,将对应索引加入数组,最后再调用 `trueRelease` 真正的释放对象。 + +我们可以执行下面的代码,分析其工作过程: + +```objectivec +NSObject *firstObject = [NSObject new]; +__attribute__((objc_precise_lifetime)) NSObject *object = [NSObject new]; +__weak NSObject *secondObject = object; +NSObject *thirdObject = [NSObject new]; + +__unused void (^block)() = ^{ + __unused NSObject *first = firstObject; + __unused NSObject *second = secondObject; + __unused NSObject *third = thirdObject; +}; + +FBRetainCycleDetector *detector = [FBRetainCycleDetector new]; +[detector addCandidate:block]; +[detector findRetainCycles]; +``` + +在 `dispose_helper` 调用之前: + +![before-dispose-helpe](images/before-dispose-helper.jpeg) + +`obj` 数组中的每一个位置都存储了 `FBBlockStrongRelationDetector` 的实例,但是在 `dispose_helper` 调用之后: + +![after-dispose-helpe](images/after-dispose-helper.png) + +索引为 4 和 5 处的实例已经被清空了,这里对应的 `FBBlockStrongRelationDetector` 实例的 `strong` 已经被标记为 `YES`、加入到数组中并返回;最后也就获取了所有强引用的索引,同时得到了 block 强引用的对象。 + +## 总结 + +其实最开始笔者对这个 `dispose_helper` 实现的机制并不是特别的肯定,只是有一个猜测,但是在询问了 `FBBlockStrongRelationDetector` 的作者之后,才确定 `dispose_helper` 确实会负责向所有捕获的变量发送 `release` 消息,如果有兴趣可以看这个 [issue](https://github.com/facebook/FBRetainCycleDetector/issues/15)。这部分的代码其实最开始源于 mikeash 大神的 [Circle](https://github.com/mikeash/Circle),不过对于他是如何发现这一点的,笔者并不清楚,如果各位有相关的资料或者合理的解释,可以随时联系我。 + +> Follow: [Draveness · Github](https://github.com/Draveness) + + diff --git a/contents/FBRetainCycleDetector/images/after-dispose-helper.png b/contents/FBRetainCycleDetector/images/after-dispose-helper.png new file mode 100644 index 0000000..f91e481 Binary files /dev/null and b/contents/FBRetainCycleDetector/images/after-dispose-helper.png differ diff --git a/contents/FBRetainCycleDetector/images/before-dispose-helper.jpeg b/contents/FBRetainCycleDetector/images/before-dispose-helper.jpeg new file mode 100644 index 0000000..550c0f0 Binary files /dev/null and b/contents/FBRetainCycleDetector/images/before-dispose-helper.jpeg differ diff --git a/contents/FBRetainCycleDetector/images/block-capture-strong-weak-order.png b/contents/FBRetainCycleDetector/images/block-capture-strong-weak-order.png new file mode 100644 index 0000000..af3420d Binary files /dev/null and b/contents/FBRetainCycleDetector/images/block-capture-strong-weak-order.png differ diff --git a/contents/FBRetainCycleDetector/images/block-capture-var-layout.png b/contents/FBRetainCycleDetector/images/block-capture-var-layout.png new file mode 100644 index 0000000..863498c Binary files /dev/null and b/contents/FBRetainCycleDetector/images/block-capture-var-layout.png differ diff --git a/contents/FBRetainCycleDetector/images/block-superclass.png b/contents/FBRetainCycleDetector/images/block-superclass.png new file mode 100644 index 0000000..583a5e8 Binary files /dev/null and b/contents/FBRetainCycleDetector/images/block-superclass.png differ diff --git a/contents/FBRetainCycleDetector/images/block.jpg b/contents/FBRetainCycleDetector/images/block.jpg new file mode 100644 index 0000000..c2d9d9e Binary files /dev/null and b/contents/FBRetainCycleDetector/images/block.jpg differ diff --git a/FBRetainCycleDetector/images/filtered-ivars.png b/contents/FBRetainCycleDetector/images/filtered-ivars.png similarity index 100% rename from FBRetainCycleDetector/images/filtered-ivars.png rename to contents/FBRetainCycleDetector/images/filtered-ivars.png diff --git a/FBRetainCycleDetector/images/get-ivar-layout.png b/contents/FBRetainCycleDetector/images/get-ivar-layout.png similarity index 100% rename from FBRetainCycleDetector/images/get-ivar-layout.png rename to contents/FBRetainCycleDetector/images/get-ivar-layout.png diff --git a/FBRetainCycleDetector/images/get-ivars.png b/contents/FBRetainCycleDetector/images/get-ivars.png similarity index 100% rename from FBRetainCycleDetector/images/get-ivars.png rename to contents/FBRetainCycleDetector/images/get-ivars.png diff --git a/FBRetainCycleDetector/images/retain-objects.png b/contents/FBRetainCycleDetector/images/retain-objects.png similarity index 100% rename from FBRetainCycleDetector/images/retain-objects.png rename to contents/FBRetainCycleDetector/images/retain-objects.png diff --git "a/FBRetainCycleDetector/\345\246\202\344\275\225\345\234\250 iOS \344\270\255\350\247\243\345\206\263\345\276\252\347\216\257\345\274\225\347\224\250\347\232\204\351\227\256\351\242\230.md" "b/contents/FBRetainCycleDetector/\345\246\202\344\275\225\345\234\250 iOS \344\270\255\350\247\243\345\206\263\345\276\252\347\216\257\345\274\225\347\224\250\347\232\204\351\227\256\351\242\230.md" similarity index 96% rename from "FBRetainCycleDetector/\345\246\202\344\275\225\345\234\250 iOS \344\270\255\350\247\243\345\206\263\345\276\252\347\216\257\345\274\225\347\224\250\347\232\204\351\227\256\351\242\230.md" rename to "contents/FBRetainCycleDetector/\345\246\202\344\275\225\345\234\250 iOS \344\270\255\350\247\243\345\206\263\345\276\252\347\216\257\345\274\225\347\224\250\347\232\204\351\227\256\351\242\230.md" index bab32f5..0c9cbad 100644 --- "a/FBRetainCycleDetector/\345\246\202\344\275\225\345\234\250 iOS \344\270\255\350\247\243\345\206\263\345\276\252\347\216\257\345\274\225\347\224\250\347\232\204\351\227\256\351\242\230.md" +++ "b/contents/FBRetainCycleDetector/\345\246\202\344\275\225\345\234\250 iOS \344\270\255\350\247\243\345\206\263\345\276\252\347\216\257\345\274\225\347\224\250\347\232\204\351\227\256\351\242\230.md" @@ -23,8 +23,8 @@ testObject7.object = testObject2; 这一次分享的内容就是用于检测循环引用的框架 [FBRetainCycleDetector]([https://github.com/facebook/FBRetainCycleDetector]) 我们会分几个部分来分析 FBRetainCycleDetector 是如何工作的: 1. 检测循环引用的基本原理以及过程 -2. [检测涉及 NSObject 对象的循环引用问题](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/FBRetainCycleDetector/检测%20NSObject%20对象持有的强指针.md) -2. 检测涉及 Associated Object 关联对象的循环引用问题 +2. [检测涉及 NSObject 对象的循环引用问题](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/FBRetainCycleDetector/检测%20NSObject%20对象持有的强指针.md) +2. [检测涉及 Associated Object 关联对象的循环引用问题](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/FBRetainCycleDetector/如何实现%20iOS%20中的%20Associated%20Object.md) 3. 检测涉及 Block 的循环引用问题 这是四篇文章中的第一篇,我们会以类 `FBRetainCycleDetector` 的 `- findRetainCycles` 方法为入口,分析其实现原理以及运行过程。 diff --git "a/FBRetainCycleDetector/\345\246\202\344\275\225\345\256\236\347\216\260 iOS \344\270\255\347\232\204 Associated Object.md" "b/contents/FBRetainCycleDetector/\345\246\202\344\275\225\345\256\236\347\216\260 iOS \344\270\255\347\232\204 Associated Object.md" similarity index 95% rename from "FBRetainCycleDetector/\345\246\202\344\275\225\345\256\236\347\216\260 iOS \344\270\255\347\232\204 Associated Object.md" rename to "contents/FBRetainCycleDetector/\345\246\202\344\275\225\345\256\236\347\216\260 iOS \344\270\255\347\232\204 Associated Object.md" index a47851b..c426d5f 100644 --- "a/FBRetainCycleDetector/\345\246\202\344\275\225\345\256\236\347\216\260 iOS \344\270\255\347\232\204 Associated Object.md" +++ "b/contents/FBRetainCycleDetector/\345\246\202\344\275\225\345\256\236\347\216\260 iOS \344\270\255\347\232\204 Associated Object.md" @@ -8,7 +8,7 @@ FBRetainCycleDetector 在对关联对象进行追踪时,修改了底层处理关联对象的两个 C 函数,`objc_setAssociatedObject` 和 `objc_removeAssociatedObjects`,在这里不会分析它是如何修改底层 C 语言函数实现的,如果想要了解相关的内容,可以阅读下面的文章。 -> 关于如何动态修改 C 语言函数实现可以看[动态修改 C 语言函数的实现]([https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/fishhook/动态修改%20C%20语言函数的实现.md])这篇文章,使用的第三方框架是 [fishhook]([https://github.com/facebook/fishhook])。 +> 关于如何动态修改 C 语言函数实现可以看[动态修改 C 语言函数的实现]([https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/fishhook/动态修改%20C%20语言函数的实现.md])这篇文章,使用的第三方框架是 [fishhook]([https://github.com/facebook/fishhook])。 ## FBAssociationManager @@ -212,7 +212,7 @@ NSArray *associations(id object) { ## 总结 -FBRetainCycleDetector 为了追踪某一 `NSObject` 对关联对象的引用,重新实现了关联对象模块,不过其实现与 ObjC 运行时中对关联对象的实现其实所差无几,如果对运行时中的关联对象实现原理有兴趣的话,可以看[关联对象 AssociatedObject 完全解析](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/关联对象%20AssociatedObject%20完全解析.md)这篇文章,它介绍了底层运行时中的关联对象的实现。 +FBRetainCycleDetector 为了追踪某一 `NSObject` 对关联对象的引用,重新实现了关联对象模块,不过其实现与 ObjC 运行时中对关联对象的实现其实所差无几,如果对运行时中的关联对象实现原理有兴趣的话,可以看[关联对象 AssociatedObject 完全解析](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/关联对象%20AssociatedObject%20完全解析.md)这篇文章,它介绍了底层运行时中的关联对象的实现。 这是 FBRetainCycleDetector 系列文章中的第三篇,第四篇也是最后一篇文章会介绍 FBRetainCycleDetector 是如何获取 block 持有的强引用的,这也是我觉得整个框架中实现最精彩的一部分。 diff --git "a/FBRetainCycleDetector/\346\243\200\346\265\213 NSObject \345\257\271\350\261\241\346\214\201\346\234\211\347\232\204\345\274\272\346\214\207\351\222\210.md" "b/contents/FBRetainCycleDetector/\346\243\200\346\265\213 NSObject \345\257\271\350\261\241\346\214\201\346\234\211\347\232\204\345\274\272\346\214\207\351\222\210.md" similarity index 99% rename from "FBRetainCycleDetector/\346\243\200\346\265\213 NSObject \345\257\271\350\261\241\346\214\201\346\234\211\347\232\204\345\274\272\346\214\207\351\222\210.md" rename to "contents/FBRetainCycleDetector/\346\243\200\346\265\213 NSObject \345\257\271\350\261\241\346\214\201\346\234\211\347\232\204\345\274\272\346\214\207\351\222\210.md" index d533a3d..7a142be 100644 --- "a/FBRetainCycleDetector/\346\243\200\346\265\213 NSObject \345\257\271\350\261\241\346\214\201\346\234\211\347\232\204\345\274\272\346\214\207\351\222\210.md" +++ "b/contents/FBRetainCycleDetector/\346\243\200\346\265\213 NSObject \345\257\271\350\261\241\346\214\201\346\234\211\347\232\204\345\274\272\346\214\207\351\222\210.md" @@ -2,7 +2,7 @@ 在上一篇文章中介绍了 `FBRetainCycleDetector` 的基本工作原理,这一篇文章中我们开始分析它是如何从每一个对象中获得它持有的强指针的。 -> 如果没有看第一篇文章这里还是最好看一下,了解一下 `FBRetainCycleDetector` 的工作原理,[如何在 iOS 中解决循环引用的问题](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/FBRetainCycleDetector/如何在%20iOS%20中解决循环引用的问题.md)。 +> 如果没有看第一篇文章这里还是最好看一下,了解一下 `FBRetainCycleDetector` 的工作原理,[如何在 iOS 中解决循环引用的问题](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/FBRetainCycleDetector/如何在%20iOS%20中解决循环引用的问题.md)。 `FBRetainCycleDetector` 获取对象的强指针是通过 `FBObjectiveCObject` 类的 `- allRetainedObjects` 方法,这一方法是通过其父类 `FBObjectiveCGraphElement` 继承过来的,只是内部有着不同的实现。 diff --git a/IQKeyboardManager/images/IQKeyboardManager-Hierarchy.png b/contents/IQKeyboardManager/images/IQKeyboardManager-Hierarchy.png similarity index 100% rename from IQKeyboardManager/images/IQKeyboardManager-Hierarchy.png rename to contents/IQKeyboardManager/images/IQKeyboardManager-Hierarchy.png diff --git a/IQKeyboardManager/images/IQKeyboardManager-hide-keyboard.png b/contents/IQKeyboardManager/images/IQKeyboardManager-hide-keyboard.png similarity index 100% rename from IQKeyboardManager/images/IQKeyboardManager-hide-keyboard.png rename to contents/IQKeyboardManager/images/IQKeyboardManager-hide-keyboard.png diff --git a/IQKeyboardManager/images/IQToolBar.png b/contents/IQKeyboardManager/images/IQToolBar.png similarity index 100% rename from IQKeyboardManager/images/IQToolBar.png rename to contents/IQKeyboardManager/images/IQToolBar.png diff --git a/IQKeyboardManager/images/IQToolBarItem.png b/contents/IQKeyboardManager/images/IQToolBarItem.png similarity index 100% rename from IQKeyboardManager/images/IQToolBarItem.png rename to contents/IQKeyboardManager/images/IQToolBarItem.png diff --git a/IQKeyboardManager/images/UITextView-Notification-IQKeyboardManager.png b/contents/IQKeyboardManager/images/UITextView-Notification-IQKeyboardManager.png similarity index 100% rename from IQKeyboardManager/images/UITextView-Notification-IQKeyboardManager.png rename to contents/IQKeyboardManager/images/UITextView-Notification-IQKeyboardManager.png diff --git a/IQKeyboardManager/images/easiest-integration-demo.png b/contents/IQKeyboardManager/images/easiest-integration-demo.png similarity index 100% rename from IQKeyboardManager/images/easiest-integration-demo.png rename to contents/IQKeyboardManager/images/easiest-integration-demo.png diff --git a/IQKeyboardManager/images/notification-IQKeyboardManager.png b/contents/IQKeyboardManager/images/notification-IQKeyboardManager.png similarity index 100% rename from IQKeyboardManager/images/notification-IQKeyboardManager.png rename to contents/IQKeyboardManager/images/notification-IQKeyboardManager.png diff --git "a/IQKeyboardManager/\343\200\216\351\233\266\350\241\214\344\273\243\347\240\201\343\200\217\350\247\243\345\206\263\351\224\256\347\233\230\351\201\256\346\214\241\351\227\256\351\242\230\357\274\210iOS\357\274\211.md" "b/contents/IQKeyboardManager/\343\200\216\351\233\266\350\241\214\344\273\243\347\240\201\343\200\217\350\247\243\345\206\263\351\224\256\347\233\230\351\201\256\346\214\241\351\227\256\351\242\230\357\274\210iOS\357\274\211.md" similarity index 100% rename from "IQKeyboardManager/\343\200\216\351\233\266\350\241\214\344\273\243\347\240\201\343\200\217\350\247\243\345\206\263\351\224\256\347\233\230\351\201\256\346\214\241\351\227\256\351\242\230\357\274\210iOS\357\274\211.md" rename to "contents/IQKeyboardManager/\343\200\216\351\233\266\350\241\214\344\273\243\347\240\201\343\200\217\350\247\243\345\206\263\351\224\256\347\233\230\351\201\256\346\214\241\351\227\256\351\242\230\357\274\210iOS\357\274\211.md" diff --git a/contents/KVOController/KVOController.md b/contents/KVOController/KVOController.md new file mode 100644 index 0000000..7b8f187 --- /dev/null +++ b/contents/KVOController/KVOController.md @@ -0,0 +1,447 @@ +# 如何优雅地使用 KVO + +KVO 作为 iOS 中一种强大并且有效的机制,为 iOS 开发者们提供了很多的便利;我们可以使用 KVO 来检测对象属性的变化、快速做出响应,这能够为我们在开发强交互、响应式应用以及实现视图和模型的双向绑定时提供大量的帮助。 + +但是在大多数情况下,除非遇到不用 KVO 无法解决的问题,笔者都会尽量避免它的使用,这并不是因为 KVO 有性能问题或者使用场景不多,总重要的原因是 KVO 的使用是在是太 ** **麻烦**了。 + +![trouble](images/trouble.jpg) + +使用 KVO 时,既需要进行**注册成为某个对象属性的观察者**,还要在合适的时间点将自己**移除**,再加上需要**覆写一个又臭又长的方法**,并在方法里**判断这次是不是自己要观测的属性发生了变化**,每次想用 KVO 解决一些问题的时候,作者的第一反应就是头疼,这篇文章会给为 KVO 所苦的开发者提供一种更优雅的解决方案。 + +## 使用 KVO + +不过在介绍如何优雅地使用 KVO 之前,我们先来回忆一下,在通常情况下,我们是如何使用 KVO 进行键值观测的。 + +首先,我们有一个 `Fizz` 类,其中包含一个 `number` 属性,它在初始化时会自动被赋值为 `@0`: + +```objectivec +// Fizz.h +@interface Fizz : NSObject + +@property (nonatomic, strong) NSNumber *number; + +@end + +// Fizz.m +@implementation Fizz + +- (instancetype)init { + if (self = [super init]) { + _number = @0; + } + return self; +} + +@end +``` + +我们想在 `Fizz` 对象中的 `number` 对象发生改变时获得通知得到**新**的和**旧**的值,这时我们就要祭出 `-addObserver:forKeyPath:options:context` 方法来监控 `number` 属性的变化: + +```objectivec +Fizz *fizz = [[Fizz alloc] init]; +[fizz addObserver:self + forKeyPath:@"number" + options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld + context:nil]; +fizz.number = @2; +``` + +在将当前对象 `self `注册成为 `fizz` 的观察者之后,我们需要在当前对象中覆写 `-observeValueForKeyPath:ofObject:change:context:` 方法: + +```objectivec +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context { + if ([keyPath isEqualToString:@"number"]) { + NSLog(@"%@", change); + } +} +``` + +在大多数情况下我们只需要对比 `keyPath` 的值,就可以知道我们到底监控的是哪个对象,但是在更复杂的业务场景下,使用 `context` 上下文以及其它辅助手段才能够帮助我们更加精准地确定被观测的对象。 + +但是当上述代码运行时,虽然可以成功打印出 `change` 字典,但是却会发生崩溃,你会在控制台中看到下面的内容: + +```objectivec +2017-02-26 23:44:19.666 KVOTest[15888:513229] { + kind = 1; + new = 2; + old = 0; +} +2017-02-26 23:44:19.720 KVOTest[15888:513229] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x60800001dd20 of class Fizz was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x60800003d320> ( +<NSKeyValueObservance 0x608000057310: Observer: 0x7fa098f07590, Key path: number, Options: <New: YES, Old: YES, Prior: NO> Context: 0x0, Property: 0x608000057400> +)' +``` + +这是因为 `fizz` 对象没有被其它对象引用,在脱离 `viewDidLoad` 作用于之后就被回收了,然而在 `-dealloc` 时,并没有移除观察者,所以会造成崩溃。 + +我们可以使用下面的代码来验证上面的结论是否正确: + +```objectivec +// Fizz.h +@interface Fizz : NSObject + +@property (nonatomic, strong) NSNumber *number; +@property (nonatomic, weak) NSObject *observer; + +@end + +// Fizz.m +@implementation Fizz + +- (instancetype)init { + if (self = [super init]) { + _number = @0; + } + return self; +} + +- (void)dealloc { + [self removeObserver:self.observer forKeyPath:@"number"]; +} + +@end +``` + +在 `Fizz` 类的接口中添加一个 `observer` 弱引用来持有对象的观察者,并在对象 `-dealloc` 时将它移除,重新运行这段代码,就不会发生崩溃了。 + +![not-crash-with-remove-observer-when-deallo](images/not-crash-with-remove-observer-when-dealloc.png) + +由于没有移除观察者导致崩溃是使用 KVO 时经常会遇到的问题之一,解决办法其实有很多,我们在这里简单介绍一个,使用当前对象持有被观测的对象,并在当前对象 `-dealloc` 时,移除观察者: + +```objectivec +- (void)viewDidLoad { + [super viewDidLoad]; + self.fizz = [[Fizz alloc] init]; + [self.fizz addObserver:self + forKeyPath:@"number" + options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld + context:nil]; + self.fizz.number = @2; +} + +- (void)dealloc { + [self.fizz removeObserver:self forKeyPath:@"number"]; +} +``` + +这也是我们经常使用来避免崩溃的办法,但是在笔者看来也是非常的不优雅,除了上述的崩溃问题,使用 KVO 的过程也非常的别扭和痛苦: + +1. 需要手动**移除观察者**,且移除观察者的**时机必须合适**; +2. 注册观察者的代码和事件发生处的代码上下文不同,**传递上下文**是通过 `void *` 指针; +3. 需要覆写 `-observeValueForKeyPath:ofObject:change:context:` 方法,比较麻烦; +4. 在复杂的业务逻辑中,准确判断被观察者相对比较麻烦,有多个被观测的对象和属性时,需要在方法中写大量的 `if` 进行判断; + +虽然上述几个问题并不影响 KVO 的使用,不过这也足够成为笔者尽量不使用 KVO 的理由了。 + +## 优雅地使用 KVO + +如何优雅地解决上一节提出的几个问题呢?我们在这里只需要使用 Facebook 开源的 [KVOController](https://github.com/facebook/KVOController) 框架就可以优雅地解决这些问题了。 + +如果想要实现同样的业务需求,当使用 KVOController 解决上述问题时,只需要以下代码就可以达到与上一节中**完全相同**的效果: + +```objectivec +[self.KVOController observe:self.fizz + keyPath:@"number" + options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld + block:^(id _Nullable observer, id _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) { + NSLog(@"%@", change); + }]; +``` + +我们可以在任意对象上**获得** `KVOController` 对象,然后调用它的实例方法 `-observer:keyPath:options:block:` 就可以检测某个对象对应的属性了,该方法传入的参数还是非常容易理解的,在 block 中也可以获得所有与 KVO 有关的参数。 + +使用 KVOController 进行键值观测可以说完美地解决了在使用原生 KVO 时遇到的各种问题。 + +1. 不需要手动移除观察者; +2. 实现 KVO 与事件发生处的代码上下文相同,不需要跨方法传参数; +3. 使用 block 来替代方法能够减少使用的复杂度,提升使用 KVO 的体验; +4. 每一个 `keyPath` 会对应一个属性,不需要在 block 中使用 `if` 判断 `keyPath`; + +## KVOController 的实现 + +KVOController 其实是对 Cocoa 中 KVO 的封装,它的实现其实也很简单,整个框架中只有两个实现文件,先来简要看一下 KVOController 如何为所有的 `NSObject` 对象都提供 `-KVOController` 属性的吧。 + +### 分类和 KVOController 的初始化 + +KVOController 不止为 Cocoa Touch 中所有的对象提供了 `-KVOController` 属性还提供了另一个 `KVOControllerNonRetaining` 属性,实现方法就是分类和 ObjC Runtime。 + +```objectivec +@interface NSObject (FBKVOController) + +@property (nonatomic, strong) FBKVOController *KVOController; +@property (nonatomic, strong) FBKVOController *KVOControllerNonRetaining; + +@end +``` + +从名字可以看出 `KVOControllerNonRetaining` 在使用时并不会**持有**被观察的对象,与它相比 `KVOController` 就会持有该对象了。 + +对于 `KVOController` 和 `KVOControllerNonRetaining` 属性来说,其实现都非常简单,对运行时非常熟悉的读者都应该知道使用关联对象就可以轻松实现这一需求。 + +```objectivec +- (FBKVOController *)KVOController { + id controller = objc_getAssociatedObject(self, NSObjectKVOControllerKey); + if (nil == controller) { + controller = [FBKVOController controllerWithObserver:self]; + self.KVOController = controller; + } + return controller; +} + +- (void)setKVOController:(FBKVOController *)KVOController { + objc_setAssociatedObject(self, NSObjectKVOControllerKey, KVOController, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (FBKVOController *)KVOControllerNonRetaining { + id controller = objc_getAssociatedObject(self, NSObjectKVOControllerNonRetainingKey); + if (nil == controller) { + controller = [[FBKVOController alloc] initWithObserver:self retainObserved:NO]; + self.KVOControllerNonRetaining = controller; + } + return controller; +} + +- (void)setKVOControllerNonRetaining:(FBKVOController *)KVOControllerNonRetaining { + objc_setAssociatedObject(self, NSObjectKVOControllerNonRetainingKey, KVOControllerNonRetaining, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} +``` + +两者的 `setter` 方法都只是使用 `objc_setAssociatedObject` 按照键值简单地存一下,而 `getter` 中不同的其实也就是对于 `FBKVOController` 的初始化了。 + +![easy](images/easy.jpg) + +到这里这个整个 FBKVOController 框架中的两个实现文件中的一个就介绍完了,接下来要看一下其中的另一个文件中的类 `KVOController`。 + +#### KVOController 的初始化 + +`KVOController` 是整个框架中提供 KVO 接口的类,作为 KVO 的管理者,其必须持有当前对象所有与 KVO 有关的信息,而在 `KVOController` 中,用于存储这个信息的数据结构就是 `NSMapTable`。 + +![KVOControlle](images/KVOController.png) + +为了使 `KVOController` 达到线程安全,它还必须持有一把 `pthread_mutex_t` 锁,用于在操作 `_objectInfosMap` 时使用。 + +再回到上一节提到的初始化问题,`NSObject` 的属性 `FBKVOController` 和 `KVOControllerNonRetaining` 的区别在于前者会持有观察者,使其引用计数加一。 + +```objectivec +- (instancetype)initWithObserver:(nullable id)observer retainObserved:(BOOL)retainObserved { + self = [super init]; + if (nil != self) { + _observer = observer; + NSPointerFunctionsOptions keyOptions = retainObserved ? NSPointerFunctionsStrongMemory|NSPointerFunctionsObjectPointerPersonality : NSPointerFunctionsWeakMemory|NSPointerFunctionsObjectPointerPersonality; + _objectInfosMap = [[NSMapTable alloc] initWithKeyOptions:keyOptions valueOptions:NSPointerFunctionsStrongMemory|NSPointerFunctionsObjectPersonality capacity:0]; + pthread_mutex_init(&_lock, NULL); + } + return self; +} +``` + +在初始化方法中使用各自的方法对 `KVOController` 对象持有的所有实例变量进行初始化,`KVOController` 和 `KVOControllerNonRetaining` 的区别就体现在生成的 `NSMapTable` 实例时传入的是 `NSPointerFunctionsStrongMemory` 还是 `NSPointerFunctionsWeakMemory` 选项。 + +### KVO 的过程 + +使用 `KVOController` 实现键值观测时,大都会调用实例方法 `-observe:keyPath:options:block` 来注册成为某个对象的观察者,监控属性的变化: + +```objectivec +- (void)observe:(nullable id)object keyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options block:(FBKVONotificationBlock)block { + _FBKVOInfo *info = [[_FBKVOInfo alloc] initWithController:self keyPath:keyPath options:options block:block]; + + [self _observe:object info:info]; +} +``` + +#### 数据结构 _FBKVOInfo + +这个方法中就涉及到另外一个私有的数据结构 `_FBKVOInfo`,这个类中包含着所有与 KVO 有关的信息: + +![_FBKVOInfo](images/_FBKVOInfo.png) + +`_FBKVOInfo` 在 `KVOController` 中充当的作用仅仅是一个数据结构,我们主要用它来存储整个 KVO 过程中所需要的全部信息,其内部没有任何值得一看的代码,需要注意的是,`_FBKVOInfo` 覆写了 `-isEqual:` 方法用于对象之间的判等以及方便 `NSMapTable` 的存储。 + +如果再有点别的什么特别作用的就是,其中的 `state` 表示当前的 KVO 状态,不过在本文中不会具体介绍。 + +```objectivec +typedef NS_ENUM(uint8_t, _FBKVOInfoState) { + _FBKVOInfoStateInitial = 0, + _FBKVOInfoStateObserving, + _FBKVOInfoStateNotObserving, +}; +``` + +#### observe 的过程 + +在使用 `-observer:keyPath:options:block:` 监听某一个对象属性的变化时,该过程的核心调用栈其实还是比较简单: + +![KVOController-Observe-Stack](images/KVOController-Observe-Stack.png) + +我们从栈底开始简单分析一下整个封装 KVO 的过程,其中栈底的方法,也就是我们上面提到的 `-observer:keyPath:options:block:` 初始化了一个名为 `_FBKVOInfo` 的对象: + +```objectivec +- (void)observe:(nullable id)object keyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options block:(FBKVONotificationBlock)block { + _FBKVOInfo *info = [[_FBKVOInfo alloc] initWithController:self keyPath:keyPath options:options block:block]; + [self _observe:object info:info]; +} +``` + +在创建了 `_FBKVOInfo` 之后执行了另一个私有方法 `-_observe:info:`: + +```objectivec +- (void)_observe:(id)object info:(_FBKVOInfo *)info { + pthread_mutex_lock(&_lock); + NSMutableSet *infos = [_objectInfosMap objectForKey:object]; + + _FBKVOInfo *existingInfo = [infos member:info]; + if (nil != existingInfo) { + pthread_mutex_unlock(&_lock); + return; + } + + if (nil == infos) { + infos = [NSMutableSet set]; + [_objectInfosMap setObject:infos forKey:object]; + } + [infos addObject:info]; + pthread_mutex_unlock(&_lock); + + [[_FBKVOSharedController sharedController] observe:object info:info]; +} +``` + +这个私有方法通过自身持有的 `_objectInfosMap` 来判断当前对象、属性以及各种上下文是否已经注册在表中存在了,在这个 `_objectInfosMap` 中保存着对象以及与对象有关的 `_FBKVOInfo` 集合: + +![objectInfosMap](images/objectInfosMap.png) + +在操作了当前 `KVOController` 持有的 `_objectInfosMap` 之后,才会执行私有的 `_FBKVOSharedController` 类的实例方法 `-observe:info:`: + +```objectivec +- (void)observe:(id)object info:(nullable _FBKVOInfo *)info { + pthread_mutex_lock(&_mutex); + [_infos addObject:info]; + pthread_mutex_unlock(&_mutex); + + [object addObserver:self forKeyPath:info->_keyPath options:info->_options context:(void *)info]; + + if (info->_state == _FBKVOInfoStateInitial) { + info->_state = _FBKVOInfoStateObserving; + } else if (info->_state == _FBKVOInfoStateNotObserving) { + [object removeObserver:self forKeyPath:info->_keyPath context:(void *)info]; + } +} +``` + +`_FBKVOSharedController` 才是最终调用 Cocoa 中的 `-observe:forKeyPath:options:context:` 方法开始对属性的监听的地方;同时,在整个应用运行时,只会存在一个 `_FBKVOSharedController` 实例: + +```objectivec ++ (instancetype)sharedController { + static _FBKVOSharedController *_controller = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _controller = [[_FBKVOSharedController alloc] init]; + }); + return _controller; +} +``` + +这个唯一的 `_FBKVOSharedController` 实例会在 KVO 的回调方法中将事件分发给 KVO 的观察者。 + +```objectivec +- (void)observeValueForKeyPath:(nullable NSString *)keyPath + ofObject:(nullable id)object + change:(nullable NSDictionary<NSString *, id> *)change + context:(nullable void *)context { + _FBKVOInfo *info; + pthread_mutex_lock(&_mutex); + info = [_infos member:(__bridge id)context]; + pthread_mutex_unlock(&_mutex); + + FBKVOController *controller = info->_controller; + id observer = controller.observer; + + if (info->_block) { + NSDictionary<NSString *, id> *changeWithKeyPath = change; + if (keyPath) { + NSMutableDictionary<NSString *, id> *mChange = [NSMutableDictionary dictionaryWithObject:keyPath forKey:FBKVONotificationKeyPathKey]; + [mChange addEntriesFromDictionary:change]; + changeWithKeyPath = [mChange copy]; + } + info->_block(observer, object, changeWithKeyPath); + } else if (info->_action) { + [observer performSelector:info->_action withObject:change withObject:object]; + } else { + [observer observeValueForKeyPath:keyPath ofObject:object change:change context:info->_context]; + } +} +``` + +在这个 `-observeValueForKeyPath:ofObject:change:context:` 回调方法中,`_FBKVOSharedController` 会根据 KVO 的信息 `_KVOInfo` 选择不同的方式分发事件,如果观察者没有传入 block 或者选择子,就会调用观察者 KVO 回调方法。 + +![KVOSharedControlle](images/KVOSharedController.png) + +上图就是在使用 KVOController 时,如果一个 KVO 事件触发之后,整个框架是如何对这个事件进行处理以及回调的。 + +### 如何 removeObserver + +在使用 KVOController 时,我们并不需要手动去处理 KVO 观察者的移除,因为所有的 KVO 事件都由私有的 `_KVOSharedController` 来处理; + +![KVOController-Unobserve-Stack](images/KVOController-Unobserve-Stack.png) + +当每一个 `KVOController` 对象被释放时,都会将它自己持有的所有 KVO 的观察者交由 `_KVOSharedController` 的 `-unobserve:infos:` 方法处理: + +```objectivec +- (void)unobserve:(id)object infos:(nullable NSSet<_FBKVOInfo *> *)infos { + pthread_mutex_lock(&_mutex); + for (_FBKVOInfo *info in infos) { + [_infos removeObject:info]; + } + pthread_mutex_unlock(&_mutex); + + for (_FBKVOInfo *info in infos) { + if (info->_state == _FBKVOInfoStateObserving) { + [object removeObserver:self forKeyPath:info->_keyPath context:(void *)info]; + } + info->_state = _FBKVOInfoStateNotObserving; + } +} +``` + +该方法会遍历所有传入的 `_FBKVOInfo`,从其中取出 `keyPath` 并将 `_KVOSharedController` 移除观察者。 + +除了在 `KVOController` 析构时会自动移除观察者,我们也可以通过它的实例方法 `-unobserve:keyPath:` 操作达到相同的效果;不过在调用这个方法时,我们能够得到一个不同的调用栈: + +![KVOController-Unobserve-Object-Stack](images/KVOController-Unobserve-Object-Stack.png) + +功能的实现过程其实都是类似的,都是通过 `-removeObserver:forKeyPath:context:` 方法移除观察者: + +```objectivec +- (void)unobserve:(id)object info:(nullable _FBKVOInfo *)info { + pthread_mutex_lock(&_mutex); + [_infos removeObject:info]; + pthread_mutex_unlock(&_mutex); + + if (info->_state == _FBKVOInfoStateObserving) { + [object removeObserver:self forKeyPath:info->_keyPath context:(void *)info]; + } + info->_state = _FBKVOInfoStateNotObserving; +} +``` + +不过由于这个方法的参数并不是一个数组,所以并不需要使用 `for` 循环,而是只需要将该 `_FBKVOInfo` 对应的 KVO 事件移除就可以了。 + +## 总结 + +KVOController 对于 Cocoa 中 KVO 的封装非常的简洁和优秀,我们只需要调用一个方法就可以完成一个对象的键值观测,同时不需要处理移除观察者等问题,能够降低我们出错的可能性。 + +在笔者看来 KVOController 中唯一不是很优雅的地方就是,需要写出 `object.KVOController` 才可以执行 KVO,如果能将 `KVOController` 换成更短的形式可能看起来更舒服一些: + +```objectivec +[self.kvo observer:keyPath:options:block:]; +``` + +不过这并不是一个比较大的问题,同时也只是笔者自己的看法,况且不影响 KVOController 的使用,所以各位读者也无须太过介意。 + +![](images/you-know.jpg) + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/kvocontroller + diff --git a/contents/KVOController/images/KVOController-Observe-Stack.png b/contents/KVOController/images/KVOController-Observe-Stack.png new file mode 100644 index 0000000..f7fab87 Binary files /dev/null and b/contents/KVOController/images/KVOController-Observe-Stack.png differ diff --git a/contents/KVOController/images/KVOController-Unobserve-Object-Stack.png b/contents/KVOController/images/KVOController-Unobserve-Object-Stack.png new file mode 100644 index 0000000..d29c21b Binary files /dev/null and b/contents/KVOController/images/KVOController-Unobserve-Object-Stack.png differ diff --git a/contents/KVOController/images/KVOController-Unobserve-Stack.png b/contents/KVOController/images/KVOController-Unobserve-Stack.png new file mode 100644 index 0000000..2db80ad Binary files /dev/null and b/contents/KVOController/images/KVOController-Unobserve-Stack.png differ diff --git a/contents/KVOController/images/KVOController.png b/contents/KVOController/images/KVOController.png new file mode 100644 index 0000000..dbf33d6 Binary files /dev/null and b/contents/KVOController/images/KVOController.png differ diff --git a/contents/KVOController/images/KVOSharedController.png b/contents/KVOController/images/KVOSharedController.png new file mode 100644 index 0000000..b3e5741 Binary files /dev/null and b/contents/KVOController/images/KVOSharedController.png differ diff --git a/contents/KVOController/images/_FBKVOInfo.png b/contents/KVOController/images/_FBKVOInfo.png new file mode 100644 index 0000000..ea390b1 Binary files /dev/null and b/contents/KVOController/images/_FBKVOInfo.png differ diff --git a/contents/KVOController/images/easy.jpg b/contents/KVOController/images/easy.jpg new file mode 100644 index 0000000..0372bb4 Binary files /dev/null and b/contents/KVOController/images/easy.jpg differ diff --git a/contents/KVOController/images/kvocontroller-banner.jpg b/contents/KVOController/images/kvocontroller-banner.jpg new file mode 100644 index 0000000..6d40a61 Binary files /dev/null and b/contents/KVOController/images/kvocontroller-banner.jpg differ diff --git a/contents/KVOController/images/not-crash-with-remove-observer-when-dealloc.png b/contents/KVOController/images/not-crash-with-remove-observer-when-dealloc.png new file mode 100644 index 0000000..d36a8b9 Binary files /dev/null and b/contents/KVOController/images/not-crash-with-remove-observer-when-dealloc.png differ diff --git a/contents/KVOController/images/objectInfosMap.png b/contents/KVOController/images/objectInfosMap.png new file mode 100644 index 0000000..a7f65ba Binary files /dev/null and b/contents/KVOController/images/objectInfosMap.png differ diff --git a/contents/KVOController/images/trouble.jpg b/contents/KVOController/images/trouble.jpg new file mode 100644 index 0000000..b93c293 Binary files /dev/null and b/contents/KVOController/images/trouble.jpg differ diff --git a/contents/KVOController/images/you-know.jpg b/contents/KVOController/images/you-know.jpg new file mode 100644 index 0000000..8eb215c Binary files /dev/null and b/contents/KVOController/images/you-know.jpg differ diff --git "a/MBProgressHUD/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- MBProgressHUD.md" "b/contents/MBProgressHUD/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- MBProgressHUD.md" similarity index 100% rename from "MBProgressHUD/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- MBProgressHUD.md" rename to "contents/MBProgressHUD/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- MBProgressHUD.md" diff --git "a/Masonry/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- Masonry.md" "b/contents/Masonry/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- Masonry.md" similarity index 100% rename from "Masonry/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- Masonry.md" rename to "contents/Masonry/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- Masonry.md" diff --git "a/contents/OHHTTPStubs/iOS \345\274\200\345\217\221\344\270\255\344\275\277\347\224\250 NSURLProtocol \346\213\246\346\210\252 HTTP \350\257\267\346\261\202.md" "b/contents/OHHTTPStubs/iOS \345\274\200\345\217\221\344\270\255\344\275\277\347\224\250 NSURLProtocol \346\213\246\346\210\252 HTTP \350\257\267\346\261\202.md" new file mode 100644 index 0000000..cd42abd --- /dev/null +++ "b/contents/OHHTTPStubs/iOS \345\274\200\345\217\221\344\270\255\344\275\277\347\224\250 NSURLProtocol \346\213\246\346\210\252 HTTP \350\257\267\346\261\202.md" @@ -0,0 +1,141 @@ +![](images/intercept.png) + +# iOS 开发中使用 NSURLProtocol 拦截 HTTP 请求 + +这篇文章会提供一种在 Cocoa 层拦截所有 HTTP 请求的方法,其实标题已经说明了拦截 HTTP 请求需要的了解的就是 `NSURLProtocol`。 + +由于文章的内容较长,会分成两部分,这篇文章介绍 `NSURLProtocol` 拦截 HTTP 请求的原理,另一篇文章[如何进行 HTTP Mock(iOS)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/OHHTTPStubs/如何进行%20HTTP%20Mock(iOS).md) + 介绍这个原理在 `OHHTTPStubs` 中的应用,它是如何 Mock(伪造)某个 HTTP 请求对应的响应的。 + +## NSURLProtocol + +`NSURLProtocol` 是苹果为我们提供的 [URL Loading System](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) 的一部分,这是一张从官方文档贴过来的图片: + +![URL-loading-syste](images/URL-loading-system.png) + +官方文档对 `NSURLProtocol` 的描述是这样的: + +> An NSURLProtocol object handles the loading of protocol-specific URL data. The NSURLProtocol class itself is an abstract class that provides the infrastructure for processing URLs with a specific URL scheme. You create subclasses for any custom protocols or URL schemes that your app supports. + +在每一个 HTTP 请求开始时,URL 加载系统创建一个合适的 `NSURLProtocol` 对象处理对应的 URL 请求,而我们需要做的就是写一个继承自 `NSURLProtocol` 的类,并通过 `- registerClass:` 方法注册我们的协议类,然后 URL 加载系统就会在请求发出时使用我们创建的协议对象对该请求进行处理。 + +这样,我们需要解决的核心问题就变成了如何使用 `NSURLProtocol` 来处理所有的网络请求,这里使用苹果官方文档中的 [CustomHTTPProtocol](https://developer.apple.com/library/ios/samplecode/CustomHTTPProtocol/CustomHTTPProtocol.zip) 进行介绍,你可以点击[这里](https://developer.apple.com/library/ios/samplecode/CustomHTTPProtocol/CustomHTTPProtocol.zip)下载源代码。 + +在这个工程中 `CustomHTTPProtocol.m` 是需要重点关注的文件,`CustomHTTPProtocol` 就是 `NSURLProtocol` 的子类: + +```objectivec +@interface CustomHTTPProtocol : NSURLProtocol + +... + +@end +``` + +现在重新回到需要解决的问题,也就是 **如何使用 NSURLProtocol 拦截 HTTP 请求?**,有这个么几个问题需要去解决: + ++ 如何决定哪些请求需要当前协议对象处理? ++ 对当前的请求对象需要进行哪些处理? ++ `NSURLProtocol` 如何实例化? ++ 如何发出 HTTP 请求并且将响应传递给调用者? + +上面的这几个问题其实都可以通过 `NSURLProtocol` 为我们提供的 API 来解决,决定请求是否需要当前协议对象处理的方法是:`+ canInitWithRequest`: + +```objectivec ++ (BOOL)canInitWithRequest:(NSURLRequest *)request { + BOOL shouldAccept; + NSURL *url; + NSString *scheme; + + shouldAccept = (request != nil); + if (shouldAccept) { + url = [request URL]; + shouldAccept = (url != nil); + } + return shouldAccept; +} +``` + +因为项目中的这个方法是大约有 60 多行,在这里只粘贴了其中的一部分,只为了说明该方法的作用:每一次请求都会有一个 `NSURLRequest` 实例,上述方法会拿到所有的请求对象,我们就可以根据对应的请求选择是否处理该对象;而上面的代码只会处理所有 `URL` 不为空的请求。 + +请求经过 `+ canInitWithRequest:` 方法过滤之后,我们得到了所有要处理的请求,接下来需要对请求进行一定的操作,而这都会在 `+ canonicalRequestForRequest:` 中进行,虽然它与 `+ canInitWithRequest:` 方法传入的 request 对象都是一个,但是最好不要在 `+ canInitWithRequest:` 中操作对象,可能会有语义上的问题;所以,我们需要覆写 `+ canonicalRequestForRequest:` 方法提供一个标准的请求对象: + +```objectivec ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} +``` + +这里对请求不做任何修改,直接返回,当然你也可以给这个请求加个 header,只要最后返回一个 `NSURLRequest` 对象就可以。 + +在得到了需要的请求对象之后,就可以初始化一个 `NSURLProtocol` 对象了: + +```objectivec +- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id <NSURLProtocolClient>)client { + return [super initWithRequest:request cachedResponse:cachedResponse client:client]; +} +``` + +在这里直接调用 `super` 的指定构造器方法,实例化一个对象,然后就进入了发送网络请求,获取数据并返回的阶段了: + +```objectivec +- (void)startLoading { + NSURLSession *session = [NSURLSession sessionWithConfiguration:[[NSURLSessionConfiguration alloc] init] delegate:self delegateQueue:nil]; + NSURLSessionDataTask *task = [session dataTaskWithRequest:self.request]; + [task resume]; +} +``` + +> 这里使用简化了 CustomHTTPClient 中的项目代码,可以达到几乎相同的效果。 + +你可以在 `- startLoading` 中使用任何方法来对协议对象持有的 `request` 进行转发,包括 `NSURLSession`、 `NSURLConnection` 甚至使用 AFNetworking 等网络库,只要你能在回调方法中把数据传回 `client`,帮助其正确渲染就可以,比如这样: + +```objectivec +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { + [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; + + completionHandler(NSURLSessionResponseAllow); +} + +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { + [[self client] URLProtocol:self didLoadData:data]; +} +``` + +> 当然这里省略后的代码只会保证大多数情况下的正确执行,只是给你一个对获取响应数据粗略的认知,如果你需要更加详细的代码,我觉得最好还是查看一下 `CustomHTTPProtocol` 中对 HTTP 响应处理的代码,也就是 `NSURLSessionDelegate` 协议实现的部分。 + +`client` 你可以理解为当前网络请求的发起者,所有的 `client` 都实现了 `NSURLProtocolClient` 协议,协议的作用就是在 HTTP 请求发出以及接受响应时向其它对象传输数据: + +```objectivec +@protocol NSURLProtocolClient <NSObject> +... +- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy; + +- (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data; + +- (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol; +... +@end +``` + +当然这个协议中还有很多其他的方法,比如 HTTPS 验证、重定向以及响应缓存相关的方法,你需要在合适的时候调用这些代理方法,对信息进行传递。 + +如果你只是继承了 `NSURLProtocol` 并且实现了上述方法,依然不能达到预期的效果,完成对 HTTP 请求的拦截,你还需要在 URL 加载系统中注册当前类: + +```objectivec +[NSURLProtocol registerClass:self]; +``` + +> 需要注意的是 `NSURLProtocol` 只能拦截 `UIURLConnection`、`NSURLSession` 和 `UIWebView` 中的请求,对于 `WKWebView` 中发出的网络请求也无能为力,如果真的要拦截来自 `WKWebView` 中的请求,还是需要实现 `WKWebView` 对应的 `WKNavigationDelegate`,并在代理方法中获取请求。 +> 无论是 `NSURLProtocol`、`NSURLConnection` 还是 `NSURLSession` 都会走底层的 socket,但是 `WKWebView` 可能由于基于 WebKit,并不会执行 C socket 相关的函数对 HTTP 请求进行处理,具体会执行什么代码暂时不是很清楚,如果对此有兴趣的读者,可以联系笔者一起讨论。 + +## 总结 + +如果你只想了解如何对 HTTP 请求进行拦截,其实看到这里就可以了,不过如果你想应用文章中的内容或者希望了解如何伪造 HTTP 响应,可以看下一篇文章[如何进行 HTTP Mock(iOS)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/OHHTTPStubs/如何进行%20HTTP%20Mock(iOS).md) +。 + +> Follow: [Draveness · Github](https://github.com/Draveness) + +## References +
+ [NSURLProtocol]([http://nshipster.com/nsurlprotocol/]) +[如何进行 HTTP Mock(iOS)](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/OHHTTPStubs/如何进行%20HTTP%20Mock(iOS).md) + diff --git a/contents/OHHTTPStubs/images/OHHTTPStubs-test.png b/contents/OHHTTPStubs/images/OHHTTPStubs-test.png new file mode 100644 index 0000000..95bd2e3 Binary files /dev/null and b/contents/OHHTTPStubs/images/OHHTTPStubs-test.png differ diff --git a/contents/OHHTTPStubs/images/URL-loading-system.png b/contents/OHHTTPStubs/images/URL-loading-system.png new file mode 100644 index 0000000..74bc1ef Binary files /dev/null and b/contents/OHHTTPStubs/images/URL-loading-system.png differ diff --git a/contents/OHHTTPStubs/images/http-mock-test.png b/contents/OHHTTPStubs/images/http-mock-test.png new file mode 100644 index 0000000..c7286fb Binary files /dev/null and b/contents/OHHTTPStubs/images/http-mock-test.png differ diff --git a/contents/OHHTTPStubs/images/intercept.png b/contents/OHHTTPStubs/images/intercept.png new file mode 100644 index 0000000..43291c2 Binary files /dev/null and b/contents/OHHTTPStubs/images/intercept.png differ diff --git "a/contents/OHHTTPStubs/\345\246\202\344\275\225\350\277\233\350\241\214 HTTP Mock\357\274\210iOS\357\274\211.md" "b/contents/OHHTTPStubs/\345\246\202\344\275\225\350\277\233\350\241\214 HTTP Mock\357\274\210iOS\357\274\211.md" new file mode 100644 index 0000000..88f5691 --- /dev/null +++ "b/contents/OHHTTPStubs/\345\246\202\344\275\225\350\277\233\350\241\214 HTTP Mock\357\274\210iOS\357\274\211.md" @@ -0,0 +1,408 @@ +![](images/http-mock-test.png) + +# 如何进行 HTTP Mock(iOS) + +这篇文章会对 [OHHTTPStubs]([https://github.com/AliSoftware/OHHTTPStubs]) 源代码的分析,其实现原理是建立在 `NSURLProtocol` 的基础上的,对这部分内容不了解的读者,可以阅读这篇文章 [iOS 开发中使用 NSURLProtocol 拦截 HTTP 请求](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/OHHTTPStubs/iOS%20开发中使用%20NSURLProtocol%20拦截%20HTTP%20请求.md)了解相关知识,本文中不会介绍拦截 HTTP 请求的原理。 + +### 如何使用 OHHTTPStubs Mock 网络请求 + +HTTP Mock 在测试中非常好用,我们可以在不需要后端 API 的情况下,在本地对 HTTP 请求进行拦截,返回想要的 `json` 数据,而 OHHTTPStubs 就为我们提供了这样一种解决方案。 + +在了解其实现之前,先对 OHHTTPStubs 进行简单的介绍,引入头文件这种事情在这里会直接省略,先来看一下程序的源代码: + +```objectivec +[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest * _Nonnull request) { + return [request.URL.absoluteString isEqualToString:@"https://idont.know"]; +} withStubResponse:^OHHTTPStubsResponse * _Nonnull(NSURLRequest * _Nonnull request) { + NSString *fixture = OHPathForFile(@"example.json", self.class); + return [OHHTTPStubsResponse responseWithFileAtPath:fixture statusCode:200 headers:@{@"Content-Type":@"application/json"}]; +}]; + +AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; +[manager GET:@"https://idont.know" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + NSLog(@"%@", responseObject); + } failure:nil]; +``` + +我们向 `https://idont.know` 这个 URL 发送一个 GET 请求,虽然这个 URL 并不存在,但是这里的代码通过 HTTP stub 成功地模拟了 HTTP 响应: + +![OHHTTPStubs-test](images/OHHTTPStubs-test.png) + +## OHHTTPStubs 的实现 + +在了解了 OHHTTPStubs 的使用之后,我们会对其实现进行分析,它分成四部分进行: + ++ `OHHTTPStubsProtocol` 拦截 HTTP 请求 ++ `OHHTTPStubs` 单例管理 `OHHTTPStubsDescriptor` 实例 ++ `OHHTTPStubsResponse` 伪造 HTTP 响应 ++ 一些辅助功能 + +### OHHTTPStubsProtocol 拦截 HTTP 请求 + +在 OHHTTPStubs 中继承 `NSURLProtocol` 的类就是 `OHHTTPStubsProtocol`,它在 HTTP 请求发出之前对 request 对象进行过滤以及处理: + +```objectivec ++ (BOOL)canInitWithRequest:(NSURLRequest *)request { + return ([OHHTTPStubs.sharedInstance firstStubPassingTestForRequest:request] != nil); +} + +- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)response client:(id<NSURLProtocolClient>)client { + OHHTTPStubsProtocol* proto = [super initWithRequest:request cachedResponse:nil client:client]; + proto.stub = [OHHTTPStubs.sharedInstance firstStubPassingTestForRequest:request]; + return proto; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} +``` + +判断请求是否会被当前协议对象进行处理是需要 `OHHTTPStubs` 的实例方法 `- firstStubPassingTestForRequest:` 的执行的,在这里暂时先不对这个方法进行讨论。 + +接下来就是请求发送的过程 `- startLoading` 方法了,该方法的实现实在是太过于复杂,所以这里分块来分析代码: + +```objectivec +- (void)startLoading { + NSURLRequest* request = self.request; + id<NSURLProtocolClient> client = self.client; + + OHHTTPStubsResponse* responseStub = self.stub.responseBlock(request); + + if (OHHTTPStubs.sharedInstance.onStubActivationBlock) { + OHHTTPStubs.sharedInstance.onStubActivationBlock(request, self.stub, responseStub); + } + + ... +} +``` + +从当前对象中取出 `request` 以及 `client` 对象,如果 `OHHTTPStubs` 的单例中包含 `onStubActivationBlock`,就会执行这里的 block,然后调用 `responseBlock` 获取一个 `OHHTTPStubsResponse` HTTP 响应对象。 + +`OHHTTPStubs` 不只提供了 `onStubActivationBlock` 这一个钩子,还有以下 block: + ++ `+ onStubActivationBlock`:stub 被激活时调用 ++ `+ onStubRedirectBlock`:发生重定向时 ++ `+ afterStubFinishBlock`:在 stub 结束时调用 + +如果响应对象的生成没有遇到任何问题,就会进入处理 Cookie、重定向、发送响应和模拟数据流的过程了。 + +1. 首先是对 Cookie 的处理 + +```objectivec +NSHTTPURLResponse* urlResponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL + statusCode:responseStub.statusCode + HTTPVersion:@"HTTP/1.1" + headerFields:responseStub.httpHeaders]; + +if (request.HTTPShouldHandleCookies && request.URL) { + NSArray* cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:responseStub.httpHeaders forURL:request.URL]; + if (cookies) { + [NSHTTPCookieStorage.sharedHTTPCookieStorage setCookies:cookies forURL:request.URL mainDocumentURL:request.mainDocumentURL]; + } +} +``` + +2. 如果 HTTP 状态码在 300-400 之间,就会处理重定向的问题,调用 `onStubRedirectBlock` 进行需要的回调 + +```objectivec +NSString* redirectLocation = (responseStub.httpHeaders)[@"Location"]; +NSURL* redirectLocationURL = redirectLocation ? [NSURL URLWithString:redirectLocation] : nil; + +if (((responseStub.statusCode > 300) && (responseStub.statusCode < 400)) && redirectLocationURL) { + NSURLRequest* redirectRequest = [NSURLRequest requestWithURL:redirectLocationURL]; + [self executeOnClientRunLoopAfterDelay:responseStub.requestTime block:^{ + if (!self.stopped) { + [client URLProtocol:self wasRedirectedToRequest:redirectRequest redirectResponse:urlResponse]; + if (OHHTTPStubs.sharedInstance.onStubRedirectBlock) { + OHHTTPStubs.sharedInstance.onStubRedirectBlock(request, redirectRequest, self.stub, responseStub); + } + } + }]; +} +``` + +3. 最后这里有一些复杂,我们根据 `stub` 中存储的 `responseTime` 来模拟响应的一个延迟时间,然后使用 `- streamDataForClient:withStubResponse:completion:` 来模拟数据以 `NSData` 的形式分块发送回 `client` 的过程,最后调用 `afterStubFinishBlock`。 + +```objectivec +[self executeOnClientRunLoopAfterDelay:responseStub.requestTime block:^{ + if (!self.stopped) { + [client URLProtocol:self didReceiveResponse:urlResponse cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + if(responseStub.inputStream.streamStatus == NSStreamStatusNotOpen) { + [responseStub.inputStream open]; + } + [self streamDataForClient:client + withStubResponse:responseStub + completion:^(NSError * error) { + [responseStub.inputStream close]; + NSError *blockError = nil; + if (error==nil) { + [client URLProtocolDidFinishLoading:self]; + } else { + [client URLProtocol:self didFailWithError:responseStub.error]; + blockError = responseStub.error; + } + if (OHHTTPStubs.sharedInstance.afterStubFinishBlock) { + OHHTTPStubs.sharedInstance.afterStubFinishBlock(request, self.stub, responseStub, blockError); + } + }]; + } +}]; +``` + +当然如果在生成 `responseStub` 的时候发生了错误,也会进行类似的操作,在延迟一定时间(模拟网络延迟)后执行 block 并传入各种参数: + +```objectivec +[self executeOnClientRunLoopAfterDelay:responseStub.responseTime block:^{ + if (!self.stopped) { + [client URLProtocol:self didFailWithError:responseStub.error]; + if (OHHTTPStubs.sharedInstance.afterStubFinishBlock) { + OHHTTPStubs.sharedInstance.afterStubFinishBlock(request, self.stub, responseStub, responseStub.error); + } + } +}]; +``` + +#### 模拟数据流 + +因为在客户端接收数据时,所有的 `NSData` 并不是一次就涌入客户端的,而是分块加载打包解码的,尤其是在我们执行下载操作时,有时几 MB 的文件不可能同时到达服务端,而 `- startLoading` 中调用的 `- streamDataForClient:withStubResponse:completion:` 方法就是为了模拟数据流,分块向服务端发送数据,不过这部分的处理涉及到一个私有的结构体 `OHHTTPStubsStreamTimingInfo`: + +```objectivec +typedef struct { + NSTimeInterval slotTime; + double chunkSizePerSlot; + double cumulativeChunkSize; +} OHHTTPStubsStreamTimingInfo; +``` + +这个结构体包含了关于发送数据流的信息: + ++ `slotTime`:两次发送 `NSData` 的间隔时间 ++ `chunkSizePerSlot`:每块数据流大小 ++ `cumulativeChunkSize`:已发送的数据流大小 + +模拟数据流的过程需要两个方法的支持,其中一个方法做一些预加载工作: + +```objectivec +- (void)streamDataForClient:(id<NSURLProtocolClient>)client + withStubResponse:(OHHTTPStubsResponse*)stubResponse + completion:(void(^)(NSError * error))completion { + if ((stubResponse.dataSize>0) && stubResponse.inputStream.hasBytesAvailable && (!self.stopped)) { + OHHTTPStubsStreamTimingInfo timingInfo = { + .slotTime = kSlotTime, + .cumulativeChunkSize = 0 + }; + + if(stubResponse.responseTime < 0) { + timingInfo.chunkSizePerSlot = (fabs(stubResponse.responseTime) * 1000) * timingInfo.slotTime; + } else if (stubResponse.responseTime < kSlotTime) { + timingInfo.chunkSizePerSlot = stubResponse.dataSize; + timingInfo.slotTime = stubResponse.responseTime; + } else { + timingInfo.chunkSizePerSlot = ((stubResponse.dataSize/stubResponse.responseTime) * timingInfo.slotTime); + } + + [self streamDataForClient:client + fromStream:stubResponse.inputStream + timingInfo:timingInfo + completion:completion]; + } else { + if (completion) completion(nil); + } +} +``` + +该方法将生成的 `OHHTTPStubsStreamTimingInfo` 信息传入下一个实例方法 `- streamDataForClient:fromStream:timingInfo:completion:`: + +```objectivec +- (void)streamDataForClient:(id<NSURLProtocolClient>)client fromStream:(NSInputStream*)inputStream timingInfo:(OHHTTPStubsStreamTimingInfo)timingInfo completion:(void(^)(NSError * error))completion { + if (inputStream.hasBytesAvailable && (!self.stopped)) { + double cumulativeChunkSizeAfterRead = timingInfo.cumulativeChunkSize + timingInfo.chunkSizePerSlot; + NSUInteger chunkSizeToRead = floor(cumulativeChunkSizeAfterRead) - floor(timingInfo.cumulativeChunkSize); + timingInfo.cumulativeChunkSize = cumulativeChunkSizeAfterRead; + + if (chunkSizeToRead == 0) { + [self executeOnClientRunLoopAfterDelay:timingInfo.slotTime block:^{ + [self streamDataForClient:client fromStream:inputStream + timingInfo:timingInfo completion:completion]; + }]; + } else { + uint8_t* buffer = (uint8_t*)malloc(sizeof(uint8_t)*chunkSizeToRead); + NSInteger bytesRead = [inputStream read:buffer maxLength:chunkSizeToRead]; + if (bytesRead > 0) { + NSData * data = [NSData dataWithBytes:buffer length:bytesRead]; + [self executeOnClientRunLoopAfterDelay:((double)bytesRead / (double)chunkSizeToRead) * timingInfo.slotTime block:^{ + [client URLProtocol:self didLoadData:data]; + [self streamDataForClient:client fromStream:inputStream + timingInfo:timingInfo completion:completion]; + }]; + } else { + if (completion) completion(inputStream.streamError); + } + free(buffer); + } + } else { + if (completion) completion(nil); + } +} +``` + ++ 上述方法会先计算 `chunkSizeToRead`,也就是接下来要传递给 `client` 的数据长度 ++ 从 `NSInputStream` 中读取对应长度的数据 ++ 通过 `- executeOnClientRunLoopAfterDelay:block:` 模拟数据传输的延时 ++ 使用 `- URLProtocol:didLoadData:` 代理方法将数据传回 `client` + +OHHTTPStubs 通过上面的两个方法很好的模拟了 HTTP 响应由于网络造成的延迟以及数据分块到达客户端的特点。 + +### OHHTTPStubs 以及 OHHTTPStubsDescriptor 对 stub 的管理 + +`OHHTTPStubs` 遵循单例模式,其主要作用就是提供便利的 API 并持有一个 `OHHTTPStubsDescriptor` 数组,对 stub 进行管理。 + +`OHHTTPStubs` 提供的类方法 `+ stubRequestsPassingTest:withStubResponse:` 会添加一个 `OHHTTPStubsDescriptor ` 的实例到 `OHHTTPStubsDescriptor` 数组中: + +```objectivec ++ (id<OHHTTPStubsDescriptor>)stubRequestsPassingTest:(OHHTTPStubsTestBlock)testBlock + withStubResponse:(OHHTTPStubsResponseBlock)responseBlock { + OHHTTPStubsDescriptor* stub = [OHHTTPStubsDescriptor stubDescriptorWithTestBlock:testBlock + responseBlock:responseBlock]; + [OHHTTPStubs.sharedInstance addStub:stub]; + return stub; +} +``` + +该类主要有两种方法,一种方法用于管理持有的 HTTP stub,比如说: + ++ `+ (BOOL)removeStub:(id<OHHTTPStubsDescriptor>)stubDesc` ++ `+ (void)removeAllStubs` ++ `- (void)addStub:(OHHTTPStubsDescriptor*)stubDesc` ++ `- (BOOL)removeStub:(id<OHHTTPStubsDescriptor>)stubDesc` ++ `- (void)removeAllStubs` + +这些方法都是用来操作单例持有的数组的,而另一种方法用来设置相应事件发生时的回调: + ++ `+ (void)onStubActivation:( nullable void(^)(NSURLRequest* request, id<OHHTTPStubsDescriptor> stub, OHHTTPStubsResponse* responseStub) )block` ++ `+ (void)onStubRedirectResponse:( nullable void(^)(NSURLRequest* request, NSURLRequest* redirectRequest, id<OHHTTPStubsDescriptor> stub, OHHTTPStubsResponse* responseStub) )block` ++ `+ (void)afterStubFinish:( nullable void(^)(NSURLRequest* request, id<OHHTTPStubsDescriptor> stub, OHHTTPStubsResponse* responseStub, NSError* error) )block` + +类中最重要的实例方法就是 `- firstStubPassingTestForRequest:`,它遍历自己持有的全部 stub,通过 `testBlock` 的调用返回第一个符合条件的 stub: + +```objectivec +- (OHHTTPStubsDescriptor*)firstStubPassingTestForRequest:(NSURLRequest*)request { + OHHTTPStubsDescriptor* foundStub = nil; + @synchronized(_stubDescriptors) { + for(OHHTTPStubsDescriptor* stub in _stubDescriptors.reverseObjectEnumerator) { + if (stub.testBlock(request)) { + foundStub = stub; + break; + } + } + } + return foundStub; +} +``` + +相比之下 `OHHTTPStubsDescriptor` 仅仅作为一个保存信息的类,其职能相对单一、实现相对简单: + +```objectivec +@interface OHHTTPStubsDescriptor : NSObject <OHHTTPStubsDescriptor> +@property(atomic, copy) OHHTTPStubsTestBlock testBlock; +@property(atomic, copy) OHHTTPStubsResponseBlock responseBlock; +@end + +@implementation OHHTTPStubsDescriptor + ++ (instancetype)stubDescriptorWithTestBlock:(OHHTTPStubsTestBlock)testBlock + responseBlock:(OHHTTPStubsResponseBlock)responseBlock { + OHHTTPStubsDescriptor* stub = [OHHTTPStubsDescriptor new]; + stub.testBlock = testBlock; + stub.responseBlock = responseBlock; + return stub; +} + +@end +``` + +两个属性以及一个方法构成了 `OHHTTPStubsDescriptor` 类的全部实现。 + +### OHHTTPStubsResponse 伪造 HTTP 响应 + +`OHHTTPStubsResponse` 类为请求提供了相应所需要的各种参数,HTTP 状态码、请求时间以及数据的输入流也就是用于模拟网络请求的 `inputStream`。 + +指定构造器 `- initWithFileURL:statusCode:headers:` 完成了对这些参数的配置: + +```objectivec +- (instancetype)initWithInputStream:(NSInputStream*)inputStream dataSize:(unsigned long long)dataSize statusCode:(int)statusCode headers:(nullable NSDictionary*)httpHeaders { + if (self = [super init]) { + _inputStream = inputStream; + _dataSize = dataSize; + _statusCode = statusCode; + NSMutableDictionary * headers = [NSMutableDictionary dictionaryWithDictionary:httpHeaders]; + static NSString *const ContentLengthHeader = @"Content-Length"; + if (!headers[ContentLengthHeader]) { + headers[ContentLengthHeader] = [NSString stringWithFormat:@"%llu",_dataSize]; + } + _httpHeaders = [NSDictionary dictionaryWithDictionary:headers]; + } + return self; +} +``` + +同时,该类也提供了非常多的便利构造器以及类方法帮助我们实例化 `OHHTTPStubsResponse`,整个类中的所有构造方法大都会调用上述构造器;只是会传入不同的参数: + +```objectivec +- (instancetype)initWithFileURL:(NSURL *)fileURL statusCode:(int)statusCode headers:(nullable NSDictionary *)httpHeaders { + NSNumber *fileSize; + NSError *error; + const BOOL success __unused = [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:&error]; + + return [self initWithInputStream:[NSInputStream inputStreamWithURL:fileURL] dataSize:[fileSize unsignedLongLongValue] statusCode:statusCode headers:httpHeaders]; +} +``` + +比如 `- initWithFileURL:statusCode:headers:` 方法就会从文件中读取数据,然后构造一个数据输入流。 + +### 其他内容 + +使用 `NSURLProtocol` 拦截 HTTP 请求时会有一个非常严重的问题,如果发出的是 POST 请求,请求的 body 会在到达 OHHTTPStubs 时被重置为空,也就是我们无法直接在 `testBlock` 中获取其 `HTTPBody`;所以,我们只能通过通过方法调剂在设置 `HTTPBody` 时,进行备份: + +```objectivec +typedef void(*OHHHTTPStubsSetterIMP)(id, SEL, id); +static OHHHTTPStubsSetterIMP orig_setHTTPBody; + +static void OHHTTPStubs_setHTTPBody(id self, SEL _cmd, NSData* HTTPBody) { + if (HTTPBody) { + [NSURLProtocol setProperty:HTTPBody forKey:OHHTTPStubs_HTTPBodyKey inRequest:self]; + } + orig_setHTTPBody(self, _cmd, HTTPBody); +} +@interface NSMutableURLRequest (HTTPBodyTesting) @end + +@implementation NSMutableURLRequest (HTTPBodyTesting) + ++ (void)load { + orig_setHTTPBody = (OHHHTTPStubsSetterIMP)OHHTTPStubsReplaceMethod(@selector(setHTTPBody:), (IMP)OHHTTPStubs_setHTTPBody, [NSMutableURLRequest class], NO); +} + +@end +``` + +除了对于 `HTTPBody` 的备份之外,OHHTTPStubs 还提供了一些用于从文件中获取数据的 C 函数: + +```objectivec +NSString* __nullable OHPathForFile(NSString* fileName, Class inBundleForClass); +NSString* __nullable OHPathForFileInBundle(NSString* fileName, NSBundle* bundle); +NSString* __nullable OHPathForFileInDocumentsDir(NSString* fileName); +NSBundle* __nullable OHResourceBundle(NSString* bundleBasename, Class inBundleForClass); +``` + +这些 C 语言函数能够帮助我们构造 HTTP 响应。 + +## 总结 + +如果阅读过上一篇文章中的内容,理解这里的实现原理也不是什么太大的问题。在需要使用到 HTTP mock 进行测试时,使用 OHHTTPStubs 还是很方便的,当然现在也有很多其他的 HTTP stub 框架,不过实现基本上都是基于 `NSURLProtocol` 的。 + +> Follow: [Draveness · Github](https://github.com/Draveness) + + diff --git a/contents/ProtocolKit/images/protocol-demo.jpeg b/contents/ProtocolKit/images/protocol-demo.jpeg new file mode 100644 index 0000000..c54254c Binary files /dev/null and b/contents/ProtocolKit/images/protocol-demo.jpeg differ diff --git a/contents/ProtocolKit/images/protocol-recordings.jpeg b/contents/ProtocolKit/images/protocol-recordings.jpeg new file mode 100644 index 0000000..abe924c Binary files /dev/null and b/contents/ProtocolKit/images/protocol-recordings.jpeg differ diff --git "a/contents/ProtocolKit/\345\246\202\344\275\225\345\234\250 Objective-C \344\270\255\345\256\236\347\216\260\345\215\217\350\256\256\346\211\251\345\261\225.md" "b/contents/ProtocolKit/\345\246\202\344\275\225\345\234\250 Objective-C \344\270\255\345\256\236\347\216\260\345\215\217\350\256\256\346\211\251\345\261\225.md" new file mode 100644 index 0000000..2512ff2 --- /dev/null +++ "b/contents/ProtocolKit/\345\246\202\344\275\225\345\234\250 Objective-C \344\270\255\345\256\236\347\216\260\345\215\217\350\256\256\346\211\251\345\261\225.md" @@ -0,0 +1,339 @@ +# 如何在 Objective-C 中实现协议扩展 + +![protocol-recordings](images/protocol-recordings.jpeg) + +Swift 中的协议扩展为 iOS 开发带来了非常多的可能性,它为我们提供了一种类似多重继承的功能,帮助我们减少一切可能导致重复代码的地方。 + +## 关于 Protocol Extension + +在 Swift 中比较出名的 Then 就是使用了协议扩展为所有的 `AnyObject` 添加方法,而且不需要调用 runtime 相关的 API,其实现简直是我见过最简单的开源框架之一: + +```swift +public protocol Then {} + +extension Then where Self: AnyObject { + public func then(@noescape block: Self -> Void) -> Self { + block(self) + return self + } +} + +extension NSObject: Then {} +``` + +只有这么几行代码,就能为所有的 `NSObject` 添加下面的功能: + +```swift +let titleLabel = UILabel().then { + $0.textColor = .blackColor() + $0.textAlignment = .Center +} +``` + +这里没有调用任何的 runtime 相关 API,也没有在 `NSObject` 中进行任何的方法声明,甚至 `protocol Then {}` 协议本身都只有一个大括号,整个 Then 框架就是基于协议扩展来实现的。 + +在 Objective-C 中同样有协议,但是这些协议只是相当于接口,遵循某个协议的类只表明实现了这些接口,每个类都需要**对这些接口有单独的实现**,这就很可能会导致重复代码的产生。 + +而协议扩展可以调用协议中声明的方法,以及 `where Self: AnyObject` 中的 `AnyObject` 的类/实例方法,这就大大提高了可操作性,便于开发者写出一些意想不到的扩展。 + +> 如果读者对 Protocol Extension 兴趣或者不了解协议扩展,可以阅读最后的 [Reference](#reference) 了解相关内容。 + +## ProtocolKit + +其实协议扩展的强大之处就在于它能为遵循协议的类添加一些方法的实现,而不只是一些接口,而今天为各位读者介绍的 [ProtocolKit]([https://github.com/forkingdog/ProtocolKit]) 就实现了这一功能,为遵循协议的类添加方法。 + +### ProtocolKit 的使用 + +我们先来看一下如何使用 ProtocolKit,首先定义一个协议: + +```objectivec +@protocol TestProtocol + +@required + +- (void)fizz; + +@optional + +- (void)buzz; + +@end +``` + +在协议中定义了两个方法,必须实现的方法 `fizz` 以及可选实现 `buzz`,然后使用 ProtocolKit 提供的接口 `defs` 来定义协议中方法的实现了: + +```objectivec +@defs(TestProtocol) + +- (void)buzz { + NSLog(@"Buzz"); +} + +@end +``` + +这样所有遵循 `TestProtocol` 协议的对象都可以调用 `buzz` 方法,哪怕它们没有实现: + +![protocol-demo](images/protocol-demo.jpeg) + +上面的 `XXObject` 虽然没有实现 `buzz` 方法,但是该方法仍然成功执行了。 + +### ProtocolKit 的实现 + +ProtocolKit 的主要原理仍然是 runtime 以及宏的;通过宏的使用来**隐藏类的声明以及实现的代码**,然后在 main 函数运行之前,**将类中的方法实现加载到内存**,使用 runtime 将实现**注入到目标类**中。 + +> 如果你对上面的原理有所疑惑也不是太大的问题,这里只是给你一个 ProtocolKit 原理的简单描述,让你了解它是如何工作的。 + +ProtocolKit 中有两条重要的执行路线: + ++ `_pk_extension_load` 将协议扩展中的方法实现加载到了内存 ++ `_pk_extension_inject_entry` 负责将扩展协议注入到实现协议的类 + +#### 加载实现 + +首先要解决的问题是如何将方法实现加载到内存中,这里可以先了解一下上面使用到的 `defs` 接口,它其实只是一个调用了其它宏的**超级宏**~~这名字是我编的~~: + +```objectivec +#define defs _pk_extension + +#define _pk_extension($protocol) _pk_extension_imp($protocol, _pk_get_container_class($protocol)) + +#define _pk_extension_imp($protocol, $container_class) \ + protocol $protocol; \ + @interface $container_class : NSObject <$protocol> @end \ + @implementation $container_class \ + + (void)load { \ + _pk_extension_load(@protocol($protocol), $container_class.class); \ + } \ + +#define _pk_get_container_class($protocol) _pk_get_container_class_imp($protocol, __COUNTER__) +#define _pk_get_container_class_imp($protocol, $counter) _pk_get_container_class_imp_concat(__PKContainer_, $protocol, $counter) +#define _pk_get_container_class_imp_concat($a, $b, $c) $a ## $b ## _ ## $c +``` + +> 使用 `defs` 作为接口的是因为它是一个保留的 keyword,Xcode 会将它渲染成与 `@property` 等其他关键字相同的颜色。 + +上面的这一坨宏并不需要一个一个来分析,只需要看一下最后展开会变成什么: + +```objectivec +@protocol TestProtocol; + +@interface __PKContainer_TestProtocol_0 : NSObject <TestProtocol> + +@end + +@implementation __PKContainer_TestProtocol_0 + ++ (void)load { + _pk_extension_load(@protocol(TestProtocol), __PKContainer_TestProtocol_0.class); +} +``` + +根据上面宏的展开结果,这里可以介绍上面的一坨宏的作用: + ++ `defs` 这货没什么好说的,只是 `_pk_extension` 的别名,为了提供一个更加合适的名字作为接口 ++ `_pk_extension` 向 `_pk_extension_imp ` 中传入 `$protocol` 和 `_pk_get_container_class($protocol)` 参数 + + `_pk_get_container_class` 的执行生成一个类名,上面生成的类名就是 `__PKContainer_TestProtocol_0`,这个类名是 `__PKContainer_`、 `$protocol` 和 `__COUNTER__` 拼接而成的(`__COUNTER__` 只是一个计数器,可以理解为每次调用时加一) ++ `_pk_extension_imp` 会以传入的类名生成一个遵循当前 `$protocol` 协议的类,然后在 `+ load` 方法中执行 `_pk_extension_load` 加载扩展协议 + +通过宏的运用成功隐藏了 `__PKContainer_TestProtocol_0` 类的声明以及实现,还有 `_pk_extension_load` 函数的调用: + +```objectivec +void _pk_extension_load(Protocol *protocol, Class containerClass) { + + pthread_mutex_lock(&protocolsLoadingLock); + + if (extendedProtcolCount >= extendedProtcolCapacity) { + size_t newCapacity = 0; + if (extendedProtcolCapacity == 0) { + newCapacity = 1; + } else { + newCapacity = extendedProtcolCapacity << 1; + } + allExtendedProtocols = realloc(allExtendedProtocols, sizeof(*allExtendedProtocols) * newCapacity); + extendedProtcolCapacity = newCapacity; + } + + ... + + pthread_mutex_unlock(&protocolsLoadingLock); +} +``` + +ProtocolKit 使用了 `protocolsLoadingLock` 来保证静态变量 `allExtendedProtocols` 以及 `extendedProtcolCount` `extendedProtcolCapacity` 不会因为线程竞争导致问题: + ++ `allExtendedProtocols` 用于保存所有的 `PKExtendedProtocol` 结构体 ++ 后面的两个变量确保数组不会越界,并在数组满的时候,将内存占用地址翻倍 + +方法的后半部分会在静态变量中寻找或创建传入的 `protocol` 对应的 `PKExtendedProtocol` 结构体: + +```objectivec +size_t resultIndex = SIZE_T_MAX; +for (size_t index = 0; index < extendedProtcolCount; ++index) { + if (allExtendedProtocols[index].protocol == protocol) { + resultIndex = index; + break; + } +} + +if (resultIndex == SIZE_T_MAX) { + allExtendedProtocols[extendedProtcolCount] = (PKExtendedProtocol){ + .protocol = protocol, + .instanceMethods = NULL, + .instanceMethodCount = 0, + .classMethods = NULL, + .classMethodCount = 0, + }; + resultIndex = extendedProtcolCount; + extendedProtcolCount++; +} + +_pk_extension_merge(&(allExtendedProtocols[resultIndex]), containerClass); +``` + +这里调用的 `_pk_extension_merge` 方法非常重要,不过在介绍 `_pk_extension_merge` 之前,首先要了解一个用于保存协议扩展信息的私有结构体 `PKExtendedProtocol`: + +```objectivec +typedef struct { + Protocol *__unsafe_unretained protocol; + Method *instanceMethods; + unsigned instanceMethodCount; + Method *classMethods; + unsigned classMethodCount; +} PKExtendedProtocol; +``` + +`PKExtendedProtocol` 结构体中保存了协议的指针、实例方法、类方法、实例方法数以及类方法数用于框架记录协议扩展的状态。 + +回到 `_pk_extension_merge` 方法,它会将新的扩展方法追加到 `PKExtendedProtocol` 结构体的数组 `instanceMethods` 以及 `classMethods` 中: + +```objectivec +void _pk_extension_merge(PKExtendedProtocol *extendedProtocol, Class containerClass) { + // Instance methods + unsigned appendingInstanceMethodCount = 0; + Method *appendingInstanceMethods = class_copyMethodList(containerClass, &appendingInstanceMethodCount); + Method *mergedInstanceMethods = _pk_extension_create_merged(extendedProtocol->instanceMethods, + extendedProtocol->instanceMethodCount, + appendingInstanceMethods, + appendingInstanceMethodCount); + free(extendedProtocol->instanceMethods); + extendedProtocol->instanceMethods = mergedInstanceMethods; + extendedProtocol->instanceMethodCount += appendingInstanceMethodCount; + + // Class methods + ... +} +``` + +> 因为类方法的追加与实例方法几乎完全相同,所以上述代码省略了向结构体中的类方法追加方法的实现代码。 + +实现中使用 `class_copyMethodList` 从 `containerClass` 拉出方法列表以及方法数量;通过 `_pk_extension_create_merged` 返回一个合并之后的方法列表,最后在更新结构体中的 `instanceMethods` 以及 `instanceMethodCount` 成员变量。 + +`_pk_extension_create_merged` 只是重新 `malloc` 一块内存地址,然后使用 `memcpy` 将所有的方法都复制到了这块内存地址中,最后返回首地址: + +```objectivec +Method *_pk_extension_create_merged(Method *existMethods, unsigned existMethodCount, Method *appendingMethods, unsigned appendingMethodCount) { + + if (existMethodCount == 0) { + return appendingMethods; + } + unsigned mergedMethodCount = existMethodCount + appendingMethodCount; + Method *mergedMethods = malloc(mergedMethodCount * sizeof(Method)); + memcpy(mergedMethods, existMethods, existMethodCount * sizeof(Method)); + memcpy(mergedMethods + existMethodCount, appendingMethods, appendingMethodCount * sizeof(Method)); + return mergedMethods; +} +``` + +这一节的代码从使用宏生成的类中抽取方法实现,然后以结构体的形式加载到内存中,等待之后的方法注入。 + +#### 注入方法实现 + +注入方法的时间点在 main 函数执行之前议实现的注入并不是在 `+ load` 方法 `+ initialize` 方法调用时进行的,而是使用的编译器指令(compiler directive) `__attribute__((constructor))` 实现的: + +```objectivec +__attribute__((constructor)) static void _pk_extension_inject_entry(void); +``` + +使用上述编译器指令的函数会在 shared library 加载的时候执行,也就是 main 函数之前,可以看 StackOverflow 上的这个问题 [How exactly does __attribute__((constructor)) work?](http://stackoverflow.com/questions/2053029/how-exactly-does-attribute-constructor-work)。 + +```objectivec +__attribute__((constructor)) static void _pk_extension_inject_entry(void) { + #1:加锁 + unsigned classCount = 0; + Class *allClasses = objc_copyClassList(&classCount); + + @autoreleasepool { + for (unsigned protocolIndex = 0; protocolIndex < extendedProtcolCount; ++protocolIndex) { + PKExtendedProtocol extendedProtcol = allExtendedProtocols[protocolIndex]; + for (unsigned classIndex = 0; classIndex < classCount; ++classIndex) { + Class class = allClasses[classIndex]; + if (!class_conformsToProtocol(class, extendedProtcol.protocol)) { + continue; + } + _pk_extension_inject_class(class, extendedProtcol); + } + } + } + #2:解锁并释放 allClasses、allExtendedProtocols +} +``` + +`_pk_extension_inject_entry` 会在 main 执行之前遍历内存中的**所有** `Class`(整个遍历过程都是在一个自动释放池中进行的),如果某个类遵循了`allExtendedProtocols` 中的协议,调用 `_pk_extension_inject_class` 向类中注射(inject)方法实现: + +```objectivec +static void _pk_extension_inject_class(Class targetClass, PKExtendedProtocol extendedProtocol) { + + for (unsigned methodIndex = 0; methodIndex < extendedProtocol.instanceMethodCount; ++methodIndex) { + Method method = extendedProtocol.instanceMethods[methodIndex]; + SEL selector = method_getName(method); + + if (class_getInstanceMethod(targetClass, selector)) { + continue; + } + + IMP imp = method_getImplementation(method); + const char *types = method_getTypeEncoding(method); + class_addMethod(targetClass, selector, imp, types); + } + + #1: 注射类方法 +} +``` + +如果类中没有实现该实例方法就会通过 runtime 中的 `class_addMethod` 注射该实例方法;而类方法的注射有些不同,因为类方法都是保存在元类中的,而一些类方法由于其特殊地位最好不要改变其原有实现,比如 `+ load` 和 `+ initialize` 这两个类方法就比较特殊,如果想要了解这两个方法的相关信息,可以在 [Reference](#reference) 中查看相关的信息。 + +```objectivec +Class targetMetaClass = object_getClass(targetClass); +for (unsigned methodIndex = 0; methodIndex < extendedProtocol.classMethodCount; ++methodIndex) { + Method method = extendedProtocol.classMethods[methodIndex]; + SEL selector = method_getName(method); + + if (selector == @selector(load) || selector == @selector(initialize)) { + continue; + } + if (class_getInstanceMethod(targetMetaClass, selector)) { + continue; + } + + IMP imp = method_getImplementation(method); + const char *types = method_getTypeEncoding(method); + class_addMethod(targetMetaClass, selector, imp, types); +} +``` + +实现上的不同仅仅在获取元类、以及跳过 `+ load` 和 `+ initialize` 方法上。 + +## 总结 + +ProtocolKit 通过宏和 runtime 实现了类似协议扩展的功能,其实现代码总共也只有 200 多行,还是非常简洁的;在另一个叫做 [libextobjc](https://github.com/jspahrsummers/libextobjc) 的框架中也实现了类似的功能,有兴趣的读者可以查看 [EXTConcreteProtocol.h · libextobjc]([https://github.com/jspahrsummers/libextobjc/blob/master/contents/extobjc/EXTConcreteProtocol.h]) 这个文件。 + +## Reference + ++ [Protocols · Apple Doc](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift\_Programming\_Language/Extensions.html#//apple\_ref/doc/uid/TP40014097-CH24-ID151) ++ [EXTConcreteProtocol.h · libextobjc](https://github.com/jspahrsummers/libextobjc/blob/master/contents/extobjc/EXTConcreteProtocol.h) ++ [\_\_attribute__ · NSHipster](http://nshipster.com/__attribute__/) ++ [你真的了解 load 方法么?](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/你真的了解%20load%20方法么?.md) ++ [懒惰的 initialize 方法](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/懒惰的%20initialize%20方法.md) + + diff --git a/contents/Rails/activerecord.md b/contents/Rails/activerecord.md new file mode 100644 index 0000000..ac3acca --- /dev/null +++ b/contents/Rails/activerecord.md @@ -0,0 +1,1684 @@ +# 全面理解 ActiveRecord + +最近事情并不是特别多,看了一些数据库相关的书籍,最后想到自己并不了解每天都在用的 ActiveRecord,对于它是如何创建模型、建立关系、执行 SQL 查询以及完成数据库迁移的,作者一直都有着自己的猜测,但是真正到源代码中去寻找答案一直都是没有做过的。 + +![activerecord-architecture](images/activerecord/activerecord-architecture.png) + +我们可以将 ActiveRecord 理解为一个不同 SQL 数据库的 Wrapper,同时为上层提供一种简洁、优雅的 API 或者说 DSL,能够极大得减轻开发者的负担并提升工作效率。 + +文章分四个部分介绍了 ActiveRecord 中的重要内容,模型的创建过程、Scope 和查询的实现、模型关系的实现以及最后的 Migrations 任务的实现和执行过程,各个模块之间没有太多的关联,由于文章内容比较多,如果读者只对某一部分的内容感兴趣,可以只挑选一部分进行阅读。 + +## 模型的创建过程 + +在这篇文章中,我们会先分析阅读 ActiveRecord 是如何创建模型并将数据插入到数据库中的,由于 ActiveRecord 的源码变更非常迅速,这里使用的 ActiveRecord 版本是 v5.1.4,如果希望重现文中对方法的追踪过程可以 checkout 到 v5.1.4 的标签上并使用如下所示的命令安装指定版本的 ActiveRecord: + +```shell +$ gem install activerecord -v '5.1.4' +``` + +### 引入 ActiveRecord + +在正式开始使用 [pry](https://github.com/pry/pry) 对方法进行追踪之前,我们需要现在 pry 中 `require` 对应的 gem,并且创建一个用于追踪的模型类: + +```ruby +pry(main)> require 'active_record' +=> true +pry(main)> class Post < ActiveRecord::Base; end +=> nil +``` + +这个步骤非常的简单,这里也不多说什么了,只是创建了一个继承自 `ActiveRecord::Base` 的类 `Post`,虽然我们并没有在数据库中创建对应的表结构,不过目前来说已经够用了。 + +### 从 Post.create 开始 + +使用过 ActiveRecord 的人都知道,当我们使用 `Post.create` 方法的时候就会在数据库中创建一条数据记录,所以在这里我们就将该方法作为入口一探究竟: + +```ruby +pry(main)> $ Post.create + +From: lib/active_record/persistence.rb @ line 29: +Owner: ActiveRecord::Persistence::ClassMethods + +def create(attributes = nil, &block) + if attributes.is_a?(Array) + attributes.collect { |attr| create(attr, &block) } + else + object = new(attributes, &block) + object.save + object + end +end +``` + +> `$` 是 pry 为我们提供的用于查看方法源代码的工具,这篇文章中会省略 `$` 方法的一部分输出,还可能会对方法做一些简化减少理解方法实现时的干扰。 + +通过 pry 的输出,我们可以在 ActiveRecord 的 `lib/active_record/persistence.rb` 文件中找到 `ActiveRecord::Base.create` 方法的实现,如果传入的参数是一个 `Hash`,该方法会先后执行 `ActiveRecord::Base.new` 和 `ActiveRecord::Base#save!` 创建一个新的对象并保存。 + +#### 使用 pry 追踪 #save! + +`ActiveRecord::Base.new` 在大多数情况下都会调用父类的 `#initialize` 方法初始化实例,所以没有什么好说的,而 `ActiveRecord::Base#save!` 方法就做了很多事情: + +```ruby +pry(main)> $ ActiveRecord::Base#save! + +From: lib/active_record/suppressor.rb @ line 45: +Owner: ActiveRecord::Suppressor + +def save!(*) # :nodoc: + SuppressorRegistry.suppressed[self.class.name] ? true : super +end +``` + +首先是使用 `SuppressorRegistry` 来判断是否需要对当前的存取请求进行抑制,然后执行 `super` 方法,由于从上述代码中没有办法知道这里的 `super` 到底是什么,所以我们就需要通过 `.ancestors` 方法看看 `ActiveRecord::Base` 到底有哪些父类了: + +```ruby +pry(main)> ActiveRecord::Base.ancestors +=> [ActiveRecord::Base, + ActiveRecord::Suppressor, + ... + ActiveRecord::Persistence, + ActiveRecord::Core, + ActiveSupport::ToJsonWithActiveSupportEncoder, + Object, + ... + Kernel, + BasicObject] + +pry(main)> ActiveRecord::Base.ancestors.count +=> 65 +``` + +使用 `.ancestors` 方法,你就可以看到整个方法调用链上包含 64 个父类,在这时简单的使用 pry 就已经不能帮助我们理解方法的调用过程了,因为 pry 没法查看当前的方法在父类中是否存在,我们需要从工程中分析哪些类的 `#save!` 方法在整个过程中被执行了并根据上述列表排出它们执行的顺序;经过分析,我们得到如下的结果: + +![activerecord-base-save](images/activerecord/activerecord-base-save.png) + +从 `ActiveRecord::Suppressor` 到 `ActiveRecord::Persistence` 一共有五个 module 实现了 `#save!` 方法,上面我们已经知道了 `ActiveRecord::Suppressor#save!` 模块提供了对保存的抑制功能,接下来将依次看后四个方法都在保存模型的过程中做了什么。 + +#### 事务的执行 + +从名字就可以看出 `ActiveRecord::Transactions` 主要是为数据库事务提供支持,并在数据库事务的不同阶段执行不同的回调,这个 module 中的 `#save!` 方法仅在 `#with_transaction_returning_status` 的 block 中执行了 `super`: + +```ruby +module ActiveRecord + module Transactions + def save!(*) #:nodoc: + with_transaction_returning_status { super } + end + end +end +``` + +`#with_transaction_returning_status` 方法会运行外部传入的 block 通过 `super` 执行父类的 `#save!` 方法: + +```ruby +def with_transaction_returning_status + status = nil + self.class.transaction do + add_to_transaction + begin + status = yield + rescue ActiveRecord::Rollback + clear_transaction_record_state + status = nil + end + + raise ActiveRecord::Rollback unless status + end + status +ensure + if @transaction_state && @transaction_state.committed? + clear_transaction_record_state + end +end +``` + +通过上述方法,我们将所有的 SQL 请求都包装在了一个 `.transaction` 中,开启一个新的数据库事务并在其中执行请求,在这里统一处理一些跟事务回滚以及异常相关的逻辑,同时 `ActiveRecord::Transactions` 又能为当前的模型添加一些回调的支持: + +```ruby +module ActiveRecord + module Transactions + included do + define_callbacks :commit, :rollback, + :before_commit, + :before_commit_without_transaction_enrollment, + :commit_without_transaction_enrollment, + :rollback_without_transaction_enrollment, + scope: [:kind, :name] + end + end +end +``` + +开发者就能够在模型中根据需要注册回调用来监听各种数据库事务相关的事件,绝大多数的事务最终都会在 `ActiveRecord::ConnectionAdapters::Transaction#within_new_transaction` 方法中执行: + +```ruby +def within_new_transaction(options = {}) + @connection.lock.synchronize do + begin + transaction = begin_transaction options + yield + rescue Exception => error + if transaction + rollback_transaction + after_failure_actions(transaction, error) + end + raise + ensure + unless error + if Thread.current.status == "aborting" + rollback_transaction if transaction + else + begin + commit_transaction + rescue Exception + rollback_transaction(transaction) unless transaction.state.completed? + raise + end + end + end + end + end +end +``` + +上述方法虽然看起来非常复杂,但是方法的逻辑还是还是非常清晰的,如果事务没有抛出任何的异常,就可以将上述代码简化成以下的几行代码: + +```ruby +def within_new_transaction(options = {}) + @connection.lock.synchronize do + begin_transaction options + yield + commit_transaction + end + end +end +``` + +我们可以看到,经过一系列的方法调用最后会在数据库中执行 `BEGIN`、SQL 语句和 `COMMIT` 来完成数据的持久化。 + +#### 追踪属性的重置 + +当 `ActiveRecord::Transactions#save!` 通过 `super` 将方法抛给上层之后,就由 `ActiveRecord::AttributesMethod::Dirty` 来处理了: + +```ruby +def save!(*) + super.tap do + changes_applied + end +end +``` + +如果 `#save!` 最终执行成功,在这个阶段会将所有模型改变的标记全部清除,对包括 `@changed_attributes`、`@mutation_tracker` 在内的实例变量全部重置,为追踪下一次模型的修改做准备。 + +#### 字段的验证 + +沿着整个继承链往下走,下一个被执行的模块就是 `ActiveRecord::Validations` 了,正如这么模块名字所暗示的,我们在这里会对模型中的字段进行验证: + +```ruby +def save!(options = {}) + perform_validations(options) ? super : raise_validation_error +end +``` + +上述代码使用 `#perform_validations` 方法验证模型中的全部字段,以此来保证所有的字段都符合我们的预期: + +```ruby +def perform_validations(options = {}) + options[:validate] == false || valid?(options[:context]) +end +``` + +在这个方法中我们可以看到如果在调用 `save!` 方法时,传入了 `validate: false` 所有的验证就都会被跳过,我们通过 `#valid?` 来判断当前的模型是否合法,而这个方法的执行过程其实也包含两个过程: + +```ruby +module ActiveRecord + module Validations + def valid?(context = nil) + context ||= default_validation_context + output = super(context) + errors.empty? && output + end + end +end + +module ActiveModel + module Validations + def valid?(context = nil) + current_context, self.validation_context = validation_context, context + errors.clear + run_validations! + ensure + self.validation_context = current_context + end + end +end +``` + +由于 `ActiveModel::Validations` 是 `ActiveRecord::Validations` 的『父类』,所以在 `ActiveRecord::Validations` 执行 `#valid?` 方法时,最终会执行父类 `#run_validations` 运行全部的验证回调。 + +```ruby +module ActiveModel + module Validations + def run_validations! + _run_validate_callbacks + errors.empty? + end + end +end +``` + +通过上述方法的实现,我们可以发现验证是否成功其实并不是通过我们在 `validate` 中传入一个返回 `true/false` 的方法决定的,而是要向当前模型的 `errors` 中添加更多的错误: + +```ruby +class Invoice < ApplicationRecord + validate :active_customer + + def active_customer + errors.add(:customer_id, "is not active") unless customer.active? + end +end +``` + +在这个过程中执行的另一个方法 `#_run_validate_callbacks` 其实是通过 `ActiveSupport::Callbacks` 提供的 `#define_callbacks` 方法动态生成的,所以我们没有办法在工程中搜索到: + +```ruby +def define_callbacks(*names) + options = names.extract_options! + + names.each do |name| + name = name.to_sym + set_callbacks name, CallbackChain.new(name, options) + module_eval <<-RUBY, __FILE__, __LINE__ + 1 + def _run_#{name}_callbacks(&block) + run_callbacks #{name.inspect}, &block + end + + def self._#{name}_callbacks + get_callbacks(#{name.inspect}) + end + + def self._#{name}_callbacks=(value) + set_callbacks(#{name.inspect}, value) + end + + def _#{name}_callbacks + __callbacks[#{name.inspect}] + end + RUBY + end +end +``` + +在这篇文章中,我们只需要知道该 `#save!` 在合适的时机运行了正确的回调就可以了,在后面的文章(可能)中会详细介绍整个 callbacks 的具体执行流程。 + +#### 数据的持久化 + +`#save!` 的调用栈最顶端就是 `ActiveRecord::Persistence#save!` 方法: + +```ruby +def save!(*args, &block) + create_or_update(*args, &block) || raise(RecordNotSaved.new("Failed to save the record", self)) +end + +def create_or_update(*args, &block) + _raise_readonly_record_error if readonly? + result = new_record? ? _create_record(&block) : _update_record(*args, &block) + result != false +end +``` + +在这个方法中,我们执行了 `#create_or_update` 以及 `#_create_record` 两个方法来创建模型: + +```ruby +def _create_record(attribute_names = self.attribute_names) + attributes_values = arel_attributes_with_values_for_create(attribute_names) + new_id = self.class.unscoped.insert attributes_values + self.id ||= new_id if self.class.primary_key + @new_record = false + yield(self) if block_given? + id +end +``` + +在这个私有方法中开始执行数据的插入操作了,首先是通过 `ActiveRecord::AttributeMethods#arel_attributes_with_values_for_create` 方法获取一个用于插入数据的字典,其中包括了数据库中的表字段和对应的待插入值。 + +![database-statement-insert](images/activerecord/database-statement-insert.png) + +而下面的 `.insert` 方法就会将这个字典转换成 SQL 语句,经过上图所示的调用栈最终到不同的数据库中执行语句并返回最新的主键。 + +### 小结 + +从整个模型的创建过程中,我们可以看到 ActiveRecord 对于不同功能的组织非常优雅,每一个方法都非常简短并且易于阅读,通过对应的方法名和模块名我们就能够明确的知道这个东西是干什么的,对于同一个方法的不同执行逻辑也分散了不同的模块中,最终使用 module 加上 include 的方式组织起来,如果要对某个方法添加一些新的逻辑也可以通过增加更多的 module 达到目的。 + +通过对源代码的阅读,我们可以看到对于 ActiveRecord 来说,`#create` 和 `#save!` 方法的执行路径其实是差不多的,只是在细节上有一些不同之处。 + +![actual-callstack-for-activerecord-base-save](images/activerecord/actual-callstack-for-activerecord-base-save.png) + +虽然模型或者说数据行的创建过程最终会从子类一路执行到父类的 `#save!` 方法,但是逻辑的**处理顺序**并不是按照从子类到父类执行的,我们可以通过上图了解不同模块的真正执行过程。 + +## Scope 和查询的实现 + +除了模型的插入、创建和迁移模块,ActiveRecord 中还有另一个非常重要的模块,也就是 Scope 和查询;为什么同时介绍这两个看起来毫不相干的内容呢?这是因为 Scope 和查询是完全分不开的一个整体,在 ActiveRecord 的实现中,两者有着非常紧密的联系。 + +### ActiveRecord::Relation + +对 ActiveRecord 稍有了解的人都知道,在使用 ActiveRecord 进行查询时,所有的查询方法其实都会返回一个 `#{Model}::ActiveRecord_Relation` 类的对象,比如 `User.all`: + +```ruby +pry(main)> User.all.class +=> User::ActiveRecord_Relation +``` + +在这里使用 pry 来可以帮助我们快速理解整个过程到底都发生了什么事情: + +```ruby +pry(main)> $ User.all + +From: lib/active_record/scoping/named.rb @ line 24: +Owner: ActiveRecord::Scoping::Named::ClassMethods + +def all + if current_scope + current_scope.clone + else + default_scoped + end +end +``` + +`#all` 方法中的注释中也写着它会返回一个 `ActiveRecord::Relation` 对象,它其实可以理解为 ActiveRecord 查询体系中的单位元,它的调用并不改变当前查询;而如果我们使用 pry 去看其他的方法例如 `User.where` 的时候: + +```ruby +pry(main)> $ User.where + +From: lib/active_record/querying.rb @ line 10: +Owner: ActiveRecord::Querying + +delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :left_joins, :left_outer_joins, :or, + :where, :rewhere, :preload, :eager_load, :includes, :from, :lock, :readonly, :extending, + :having, :create_with, :distinct, :references, :none, :unscope, :merge, to: :all +``` + +从这里我们可以看出,真正实现为 `User` 类方法的只有 `.all`,其他的方法都会代理给 `all` 方法,在 `.all` 方法返回的对象上执行: + +![active-record-relation-delegation](images/activerecord/active-record-relation-delegation.png) + +所有直接在类上调用的方法都会先执行 `#all`,也就是说下面的几种写法是完全相同的: + +```ruby +User .where(name: 'draven') +User.all.where(name: 'draven') +User.all.where(name: 'draven').all +``` + +当我们了解了 `.where == .all + #where` 就可以再一次使用 pry 来查找真正被 ActiveRecord 实现的 `#where` 方法: + +```ruby +pry(main)> $ User.all.where + +From: lib/active_record/relation/query_methods.rb @ line 599: +Owner: ActiveRecord::QueryMethods + +def where(opts = :chain, *rest) + if :chain == opts + WhereChain.new(spawn) + elsif opts.blank? + self + else + spawn.where!(opts, *rest) + end +end +``` + +在分析查询的过程中,我们会选择几个常见的方法作为入口,尽可能得覆盖较多的查询相关的代码,增加我们对 ActiveRecord 的理解和认识。 + +### 从 User.all 开始 + +再来看一下上面看到的 `ActiveRecord::Relation.all` 方法,无论是 `#current_scope` 还是 `#default_scoped` 其实返回的都是当前的 `ActiveRecord` 对象: + +```ruby +def all + if current_scope + current_scope.clone + else + default_scoped + end +end +``` + +#### current_scope 和 default_scope + +如果当前没有 `#current_scope` 那么,就会调用 `#default_scoped` 返回响应的结果,否则就会 clone 当前对象并返回,可以简单举一个例子证明这里的猜测: + +```ruby +pry(main)> User.current_scope +=> nil +pry(main)> User.all.current_scope + User Load (0.1ms) SELECT "users".* FROM "users" +=> [] +pry(main)> User.all.current_scope.class +=> User::ActiveRecord_Relation +``` + +`.current_scope` 是存储在位于线程变量的 `ScopeRegistry` 中,它其实就是当前的查询语句的上下文,存储着这一次链式调用造成的全部副作用: + +```ruby +def current_scope(skip_inherited_scope = false) + ScopeRegistry.value_for(:current_scope, self, skip_inherited_scope) +end +``` + +而 `.default_scoped` 就是在当前查询链刚开始时执行的第一个方法,因为在执行第一个查询方法之前 `.current_scope` 一定为空: + +```ruby +def default_scoped(scope = relation) + build_default_scope(scope) || scope +end + +def build_default_scope(base_rel = nil) + return if abstract_class? + + if default_scopes.any? + base_rel ||= relation + evaluate_default_scope do + default_scopes.inject(base_rel) do |default_scope, scope| + scope = scope.respond_to?(:to_proc) ? scope : scope.method(:call) + default_scope.merge(base_rel.instance_exec(&scope)) + end + end + end +end +``` + +当我们在 Rails 的模型层中使用 `.default_scope` 定义一些默认的上下文时,所有的 block 都换被转换成 `Proc` 对象最终添加到 `default_scopes` 数组中: + +```ruby +def default_scope(scope = nil) # :doc: + scope = Proc.new if block_given? + # ... + self.default_scopes += [scope] +end +``` + +上面提到的 `.build_default_scope` 方法其实只是在 `default_scopes` 数组不为空时,将当前的 `Relation` 对象和数组中的全部 scope 一一 `#merge` 并返回一个新的 `Relation` 对象。 + +#### ActiveRecord::Relation 对象 + +`.default_scoped` 方法的参数 `scope` 其实就有一个默认值 `#relation`,这个默认值其实就是一个 `Relation` 类的实例: + +```ruby +def relation + relation = Relation.create(self, arel_table, predicate_builder) + + if finder_needs_type_condition? && !ignore_default_scope? + relation.where(type_condition).create_with(inheritance_column.to_s => sti_name) + else + relation + end +end +``` + +`Relation.create` 对象的创建过程其实比较复杂,我们只需要知道经过 ActiveRecord 一系列的疯狂操作,最终会将几个参数传入 `.new` 方法初始化一个 `ActiveRecord::Relation` 实例: + +```ruby +class Relation + def initialize(klass, table, predicate_builder, values = {}) + @klass = klass + @table = table + @values = values + @offsets = {} + @loaded = false + @predicate_builder = predicate_builder + end +end +``` + +当执行的是 `#all`、`.all` 或者绝大多数查询方法时,都会直接将这个初始化的对象返回来接受随后的链式调用。 + +### where 方法 + +相比于 `#all`、`#where` 查询的实现就复杂多了,不像 `#all` 会返回一个默认的 `Relation` 对象,`#where` 由 `WhereClause` 以及 `WhereClauseFactory` 等类共同处理;在 `#where` 的最正常的执行路径中,它会执行 `#where!` 方法: + +```ruby +def where(opts = :chain, *rest) + if :chain == opts + WhereChain.new(spawn) + elsif opts.blank? + self + else + spawn.where!(opts, *rest) + end +end + +def where!(opts, *rest) + opts = sanitize_forbidden_attributes(opts) + references!(PredicateBuilder.references(opts)) if Hash === opts + self.where_clause += where_clause_factory.build(opts, rest) + self +end +``` + +> `#spawn` 其实就是对当前的 `Relation` 对象进行 `#clone`。 + +查询方法 `#where!` 中的四行代码只有一行代码是我们需要关注的,该方法调用 `WhereClauseFactory#build` 生成一条 where 查询并存储到当前对象的 `where_clause` 中,在这个过程中并不会生成 SQL,而是会生成一个 `WhereClause` 对象,其中存储着 SQL 节点树: + +```ruby +pry(main)> User.where(name: 'draven').where_clause +=> #<ActiveRecord::Relation::WhereClause:0x007fe5a10bf2c8 + @binds= + [#<ActiveRecord::Relation::QueryAttribute:0x007fe5a10bf4f8 + @name="name", + @original_attribute=nil, + @type=#<ActiveModel::Type::String:0x007fe59d33f2e0 @limit=nil, @precision=nil, @scale=nil>, + @value_before_type_cast="draven">], + @predicates= + [#<Arel::Nodes::Equality:0x007fe5a10bf368 + @left= + #<struct Arel::Attributes::Attribute + relation= + #<Arel::Table:0x007fe59cc87830 + @name="users", + @table_alias=nil, + @type_caster= + #<ActiveRecord::TypeCaster::Map:0x007fe59cc87bf0 + @types= + User(id: integer, avatar: string, nickname: string, wechat: string, name: string, gender: integer, school: string, grade: string, major: string, completed: boolean, created_at: datetime, updated_at: datetime, mobile: string, admin: boolean)>>, + name="name">, + @right=#<Arel::Nodes::BindParam:0x007fe5a10bf520>>]> +``` + +> [Arel](https://github.com/rails/arel) 是一个 Ruby 的 SQL 抽象语法树的管理器,ActiveRecord 查询的过程都是惰性的,在真正进入数据库查询之前,查询条件都是以语法树的形式存储的。 + +在这里不像展开介绍 SQL 语法树的生成过程,因为过程比较复杂,详细分析也没有太大的意义。 + +### order 方法 + +除了 `#where` 方法之外,在这里还想简单介绍一下另外一个常用的方法 `#order`: + +```ruby +def order(*args) + check_if_method_has_arguments!(:order, args) + spawn.order!(*args) +end + +def order!(*args) + preprocess_order_args(args) + self.order_values += args + self +end +``` + +该方法的调用栈与 `#where` 非常相似,在调用栈中都会执行另一个带有 `!` 的方法,也都会向自己持有的某个『属性』追加一些参数,参数的处理也有点复杂,在这里简单看一看就好: + +```ruby +def preprocess_order_args(order_args) + order_args.map! do |arg| + klass.send(:sanitize_sql_for_order, arg) + end + order_args.flatten! + validate_order_args(order_args) + + references = order_args.grep(String) + references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact! + references!(references) if references.any? + + # if a symbol is given we prepend the quoted table name + order_args.map! do |arg| + case arg + when Symbol + arel_attribute(arg).asc + when Hash + arg.map { |field, dir| + case field + when Arel::Nodes::SqlLiteral + field.send(dir.downcase) + else + arel_attribute(field).send(dir.downcase) + end + } + else + arg + end + end.flatten! +end +``` + +同样的,`#order` 方法的使用也会向 `order_values` 数组中添加对应的语法元素: + +```ruby +pry(main)> User.order(name: :desc).order_values +=> [#<Arel::Nodes::Descending:0x007fe59ce4f190 + @expr= + #<struct Arel::Attributes::Attribute + relation= + #<Arel::Table:0x007fe59cc87830 + @name="users", + @table_alias=nil, + @type_caster= + #<ActiveRecord::TypeCaster::Map:0x007fe59cc87bf0 + @types= + User(id: integer, avatar: string, nickname: string, wechat: string, name: string, gender: integer, school: string, grade: string, major: string, completed: boolean, created_at: datetime, updated_at: datetime, mobile: string, admin: boolean)>>, + name=:name>>] +``` + +在这个方法的返回值中,我们也能看到与 Arel 相关的各种节点,可以大致理解上述语法树的作用。 + +### 语法树的存储 + +无论是 `#where` 还是 `#order` 方法,它们其实都会向当前的 `Relation` 对象中追加相应的语法树节点,而除了上述的两个方法之外 `#from`、`#distinct`、`#lock`、`#limit` 等等,几乎所有的查询方法都会改变 `Relation` 中的某个值,然而所有的值其实都是通过 `@values` 这个实例变量存储的: + +![activerecord-relation-value-methods](images/activerecord/activerecord-relation-value-methods.png) + +`@values` 中存储的值分为三类,`SINGLE_VALUE`、`MULTI_VALUE` 和 `CLAUSE`,这三类属性会按照下面的规则存储在 `@values` 中: + +```ruby +Relation::VALUE_METHODS.each do |name| + method_name = \ + case name + when *Relation::MULTI_VALUE_METHODS then "#{name}_values" + when *Relation::SINGLE_VALUE_METHODS then "#{name}_value" + when *Relation::CLAUSE_METHODS then "#{name}_clause" + end + class_eval <<-CODE, __FILE__, __LINE__ + 1 + def #{method_name} # def includes_values + get_value(#{name.inspect}) # get_value(:includes) + end # end + + def #{method_name}=(value) # def includes_values=(value) + set_value(#{name.inspect}, value) # set_value(:includes, value) + end # end + CODE +end +``` + +各种不同的值在最后都会按照一定的命名规则,存储在这个 `@values` 字典中: + +```ruby +def get_value(name) + @values[name] || default_value_for(name) +end + +def set_value(name, value) + assert_mutability! + @values[name] = value +end +``` + +如果我们直接在一个查询链中访问 `#values` 方法可以获得其中存储的所有查询条件: + +```ruby +pry(main)> User.where(name: 'draven').order(name: :desc).values +=> {:references=>[], + :where=> + #<ActiveRecord::Relation::WhereClause:0x007fe59d14d860>, + :order=> + [#<Arel::Nodes::Descending:0x007fe59d14cd98>]} +``` + +很多 ActiveRecord 的使用者其实在使用的过程中都感觉在各种链式方法调用时没有改变任何事情,所有的方法都可以任意组合进行链式调用,其实每一个方法的调用都会对 `@values` 中存储的信息进行了修改,只是 ActiveRecord 很好地将它隐藏了幕后,让我们没有感知到它的存在。 + +### scope 方法 + +相比于 `.default_scope` 这个类方法只是改变了当前模型中的 `default_scopes` 数组,另一个方法 `.scope` 会为当前类定义一个新的类方法: + +```ruby +From: lib/active_record/scoping/named.rb @ line 155: +Owner: ActiveRecord::Scoping::Named::ClassMethods + +def scope(name, body, &block) + extension = Module.new(&block) if block + + if body.respond_to?(:to_proc) + singleton_class.send(:define_method, name) do |*args| + scope = all.scoping { instance_exec(*args, &body) } + scope = scope.extending(extension) if extension + scope || all + end + else + singleton_class.send(:define_method, name) do |*args| + scope = all.scoping { body.call(*args) } + scope = scope.extending(extension) if extension + scope || all + end + end +end +``` + +上述方法会直接在当前类的单类上通过 `define_methods` 为当前类定义类方法,定义的方法会在上面提到的 `.all` 的返回结果上执行 `#scoping`,存储当前执行的上下文,执行传入的 block,再恢复 `current_scope`: + +```ruby +def scoping + previous, klass.current_scope = klass.current_scope(true), self + yield +ensure + klass.current_scope = previous +end +``` + +在这里其实有一个可能很多人从来没用过的特性,就是在 `.scope` 方法中传入一个 block: + +```ruby +class User + scope :male, -> { where gender: :male } do + def twenty + where age: 20 + end + end +end + +pry(main)> User.male.twenty +#=> <#User:0x007f98f3d61c38> +pry(main)> User.twenty +#=> NoMethodError: undefined method `twenty' for #<Class:0x007f98f5c7b2b8> +pry(main)> User.female.twenty +#=> NoMethodError: undefined method `twenty' for #<User::ActiveRecord_Relation:0x007f98f5d950e0> +``` + +这个传入的 block 只会在当前 `Relation` 对象的单类上添加方法,如果我们想定义一些不想在其他作用域使用的方法就可以使用这种方式: + +```ruby +def extending(*modules, &block) + if modules.any? || block + spawn.extending!(*modules, &block) + else + self + end +end + +def extending!(*modules, &block) + modules << Module.new(&block) if block + modules.flatten! + self.extending_values += modules + extend(*extending_values) if extending_values.any? + self +end +``` + +而 `extending` 方法的实现确实与我们预期的一样,创建了新的 `Module` 对象之后,直接使用 `#extend` 将其中的方法挂载当前对象的单类上。 + +### 小结 + +到这里为止,我们对 ActiveRecord 中查询的分析就已经比较全面了,从最终要的 `Relation` 对象,到常见的 `#all`、`#where` 和 `#order` 方法,到 ActiveRecord 对语法树的存储,如何与 Arel 进行协作,在最后我们也介绍了 `.scope` 方法的工作原理,对于其它方法或者功能的实现其实也都大同小异,在这里就不展开细谈了。 + +## 模型的关系 + +作为一个关系型数据库的 ORM,ActiveRecord 一定要提供对模型之间关系的支持,它为模型之间的关系建立提供了四个类方法 `has_many`、`has_one`、`belongs_to` 和 `has_and_belongs_to_many`,在文章的这一部分,我们会从上面几个方法中选择一部分介绍 ActiveRecord 是如何建立模型之间的关系的。 + +![activerecord-associations](images/activerecord/activerecord-associations.png) + +### Association 和继承链 + +首先来看 `.has_many` 方法是如何实现的,我们可以通过 pry 直接找到该方法的源代码: + +```ruby +pry(main)> $ User.has_many + +From: lib/active_record/associations.rb @ line 1401: +Owner: ActiveRecord::Associations::ClassMethods + +def has_many(name, scope = nil, options = {}, &extension) + reflection = Builder::HasMany.build(self, name, scope, options, &extension) + Reflection.add_reflection self, name, reflection +end +``` + +整个 `.has_many` 方法的实现也只有两行代码,总共涉及两个类 `Builder::HasMany` 和 `Reflection`,其中前者用于创建新的 `HasMany` 关系,后者负责将关系添加到当前类中。 + +`HasMany` 类的实现其实非常简单,但是它从父类和整个继承链中继承了很多方法: + +![activerecord-hasmany-ancestors](images/activerecord/activerecord-hasmany-ancestors.png) + +我们暂时先忘记 `.has_many` 方法的实现,先来看一下这里涉及的两个非常重要的类都是如何工作的,首先是 `Association` 以及它的子类;在 ActiveRecord 的实现中,我们其实能够找到四种关系的 Builder,它们有着非常清晰简单的继承关系: + +![activerecord-ancestor-builders](images/activerecord/activerecord-ancestor-builders.png) + +在这里定义的 `.build` 方法其实实现也很清晰,它通过调用当前抽象类 `Association` 或者子类的响应方法完成一些建立关系必要的工作: + +```ruby +def self.build(model, name, scope, options, &block) + extension = define_extensions model, name, &block + reflection = create_reflection model, name, scope, options, extension + define_accessors model, reflection + define_callbacks model, reflection + define_validations model, reflection + reflection +end +``` + +其中包括创建用于操作、查询和管理当前关系扩展 Module 的 `.define_extensions` 方法,同时也会使用 `.create_reflection` 创建一个用于检查 ActiveRecord 类的关系的 `Reflection` 对象,我们会在下一节中展开介绍,在创建了 `Reflection` 后,我们会根据传入的模型和 `Reflection` 对象为当前的类,例如 `User` 定义属性存取方法、回调以及验证: + +```ruby +def self.define_accessors(model, reflection) + mixin = model.generated_association_methods + name = reflection.name + define_readers(mixin, name) + define_writers(mixin, name) +end + +def self.define_readers(mixin, name) + mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 + def #{name}(*args) + association(:#{name}).reader(*args) + end + CODE +end + +def self.define_writers(mixin, name) + mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 + def #{name}=(value) + association(:#{name}).writer(value) + end + CODE +end +``` + +存取方法还是通过 Ruby 的元编程能力定义的,在这里通过 `.class_eval` 方法非常轻松地就能在当前的模型中定义方法,关于回调和验证的定义在这里就不在展开介绍了。 + +### Reflection 和继承链 + +`Reflection` 启用了检查 ActiveRecord 类和对象的关系和聚合的功能,它能够在 Builder 中使用为 ActiveRecord 中的类创建对应属性和方法。 + +与 `Association` 一样,ActiveRecord 中的不同关系也有不同的 `Reflection`,根据不同的关系和不同的配置,ActiveRecord 中建立了一套 Reflection 的继承体系与数据库中的不同关系一一对应: + +![activerecord-reflections](images/activerecord/activerecord-reflections.png) + +当我们在上面使用 `.has_many` 方法时,会通过 `.create_reflection` 创建一个 `HasManyReflection` 对象: + +```ruby +def self.create_reflection(model, name, scope, options, extension = nil) + if scope.is_a?(Hash) + options = scope + scope = nil + end + + validate_options(options) + scope = build_scope(scope, extension) + ActiveRecord::Reflection.create(macro, name, scope, options, model) +end +``` + +`Reflection#create` 方法是一个工厂方法,它会根据传入的 `macro` 和 `options` 中的值选择合适的类实例化: + +```ruby +def self.create(macro, name, scope, options, ar) + klass = \ + case macro + when :composed_of + AggregateReflection + when :has_many + HasManyReflection + when :has_one + HasOneReflection + when :belongs_to + BelongsToReflection + else + raise "Unsupported Macro: #{macro}" + end + + reflection = klass.new(name, scope, options, ar) + options[:through] ? ThroughReflection.new(reflection) : reflection +end +``` + +这个创建的 `Reflection` 在很多时候都有非常重要的作用,在创建存储方法、回调和验证时,都需要将这个对象作为参数传入提供一定的支持,起到了数据源和提供 Helper 方法的作用。 + +在整个定义方法、属性以及回调的工作完成之后,会将当前的对象以 `name` 作为键存储到自己持有的一个 `_reflections` 字典中: + +```ruby +# class_attribute :_reflections, instance_writer: false + +def self.add_reflection(ar, name, reflection) + ar.clear_reflections_cache + ar._reflections = ar._reflections.merge(name.to_s => reflection) +end +``` + +这个字典中存储着所有在当前类中使用 `has_many`、`has_one`、`belongs_to` 等方法定义的关系对应的映射。 + +### 一对多关系 + +一对多关系的这一节会分别介绍两个极其重要的方法 `.has_many` 和 `.belongs_to` 的实现;在这里,会先通过 `.has_many` 关系了解它是如何通过覆写父类方法定制自己的特性的,之后会通过 `.belongs_to` 研究 getter/setter 方法的调用栈。 + +![one-to-many-association](images/activerecord/one-to-many-association.png) + +一对多关系在数据库的模型之间非常常见,而这两个方法在 ActiveRecord 也经常成对出现。 + +#### has_many + +当我们对构建关系模块的两大支柱都已经有所了解之后,再来看这几个常用的方法就没有太多的难度了,首先来看一下一对多关系中的『多』是怎么实现的: + +```ruby +def has_many(name, scope = nil, options = {}, &extension) + reflection = Builder::HasMany.build(self, name, scope, options, &extension) + Reflection.add_reflection self, name, reflection +end +``` + +由于已经对 `Reflection.add_reflection` 方法的实现有所了解,所以这里直接看 `.has_many` 调用的 `Builder::HasMany.build` 方法的实现就可以知道这个类方法究竟做了什么,: + +```ruby +def self.build(model, name, scope, options, &block) + extension = define_extensions model, name, &block + reflection = create_reflection model, name, scope, options, extension + define_accessors model, reflection + define_callbacks model, reflection + define_validations model, reflection + reflection +end +``` + +在这里执行的 `.build` 方法与抽象类中的方法实现完全相同,子类并没有覆盖父类实现的方法,我们来找一下 `.define_accessors`、`.define_callbacks` 和 `.define_validations` 三个方法在 has_many 关系中都做了什么。 + +`HasMany` 作为 has_many 关系的 Builder 类,其本身并没有实现太多的方法,只是对一些关系选项有一些自己独有的声明: + +```ruby +module ActiveRecord::Associations::Builder + class HasMany < CollectionAssociation + def self.macro + :has_many + end + + def self.valid_options(options) + super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors] + end + + def self.valid_dependent_options + [:destroy, :delete_all, :nullify, :restrict_with_error, :restrict_with_exception] + end + end +end +``` + +由于本身 has_many 关系中的读写方法都是对集合的操作,所以首先覆写了 `.define_writers` 和 `.define_readers` 两个方法生成了另外一组操作 id 的 getter/setter 方法: + +```ruby +def self.define_readers(mixin, name) + super + + mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 + def #{name.to_s.singularize}_ids + association(:#{name}).ids_reader + end + CODE +end + +def self.define_writers(mixin, name) + super + + mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 + def #{name.to_s.singularize}_ids=(ids) + association(:#{name}).ids_writer(ids) + end + CODE +end +``` + +has_many 关系在 `CollectionAssociation` 和 `HasManyAssociation` 中实现的几个方法 `#reader`、`#writer`、`#ids_reader` 和 `#ids_writer` 其实还是比较复杂的,在这里就跳过不谈了。 + +而 `.define_callbacks` 和 `.define_extensions` 其实都大同小异,在作者看来没有什么值得讲的,has_many 中最重要的部分还是读写方法的实现过程,不过由于篇幅所限这里就不多说了。 + +#### belongs_to + +在一对多关系中,经常与 has_many 对应的关系 belongs_to 其实实现和调用栈也几乎完全相同: + +```ruby +def belongs_to(name, scope = nil, options = {}) + reflection = Builder::BelongsTo.build(self, name, scope, options) + Reflection.add_reflection self, name, reflection +end +``` + +但是与 has_many 比较大的不同是 `Builder::BelongsTo` 通过继承的父类定义了很多用于创建新关系的方法: + +```ruby +def self.define_accessors(model, reflection) + super + mixin = model.generated_association_methods + name = reflection.name + define_constructors(mixin, name) if reflection.constructable? + mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 + def reload_#{name} + association(:#{name}).force_reload_reader + end + CODE +end + +def self.define_constructors(mixin, name) + mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 + def build_#{name}(*args, &block) + association(:#{name}).build(*args, &block) + end + def create_#{name}(*args, &block) + association(:#{name}).create(*args, &block) + end + def create_#{name}!(*args, &block) + association(:#{name}).create!(*args, &block) + end + CODE +end +``` + +其他的部分虽然实现上也与 has_many 有着非常大的不同,但是原理基本上完全一致,不过在这里我们可以来看一下 belongs_to 关系创建的两个方法 `association` 和 `association=` 究竟是如何对数据库进行操作的。 + +```ruby +class Topic < ActiveRecord::Base + has_many :subtopics +end + +class Subtopic < ActiveRecord::Base + belongs_to :topic +end +``` + +假设我们有着如上所示的两个模型,它们之间是一对多关系,我们以这对模型为例先来看一下 `association` 这个读方法的调用栈。 + +![callstack-for-belongs-to-association-gette](images/activerecord/callstack-for-belongs-to-association-getter.png) + +通过我们对源代码和调用栈的阅读,我们可以发现其实如下的所有方法调用在大多数情况下是完全等价的,假设我们已经持有了一个 `Subtopic` 对象: + +```ruby +subtopic = Subtopic.first #=> #<Subtopic:0x007ff513f67768> + +subtopic.topic +subtopic.association(:topic).reader +subtopic.association(:topic).target +subtopic.association(:topic).load_target +subtopic.association(:topic).send(:find_target) +``` + +上述的五种方式都可以获得当前 `Subtopic` 对象的 belongs_to 关系对应的 `Topic` 数据行,而最后一个方法 `#find_target` 其实也就是真正创建、绑定到最后执行查询 SQL 的方法: + +```ruby +pry(main)> $ subtopic.association(:topic).find_target + +From: lib/active_record/associations/singular_association.rb @ line 38: +Owner: ActiveRecord::Associations::SingularAssociation + +def find_target + return scope.take if skip_statement_cache? + + conn = klass.connection + sc = reflection.association_scope_cache(conn, owner) do + StatementCache.create(conn) { |params| + as = AssociationScope.create { params.bind } + target_scope.merge(as.scope(self, conn)).limit(1) + } + end + + binds = AssociationScope.get_bind_values(owner, reflection.chain) + sc.execute(binds, klass, conn) do |record| + set_inverse_instance record + end.first +rescue ::RangeError + nil +end +``` + +我们已经对 `association` 方法的实现有了非常清楚的认知了,下面再来过一下 `association=` 方法的实现,首先还是来看一下 setter 方法的调用栈: + +![callstack-for-belongs-to-association-sette](images/activerecord/callstack-for-belongs-to-association-setter.png) + +相比于 getter 的调用栈,setter 方法的调用栈都复杂了很多,在研究 setter 方法实现的过程中我们一定要记住这个方法并不会改变数据库中对应的数据行,只会改变当前对应的某个属性,经过对调用栈和源代码的分析,我们可以有以下的结论:假设现在有一个 `Subtopic` 对象和一个新的 `Topic` 实例,那么下面的一系列操作其实是完全相同的: + +```ruby +subtopic = Subtopic.first #=> #<Subtopic:0x007ff513f67768> +new_topic = Topic.first #=> #<Topic:0x007ff514b24cb8> + +subtopic.topic = new_topic +subtopic.topic_id = new_topic.id +subtopic.association(:topic).writer(new_topic) +subtopic.association(:topic).replace(new_topic) +subtopic.association(:topic).replace_keys(new_topic) +subtopic.association(:topic).owner[:topic_id] = new_topic.id +subtopic[:topic_id] = new_topic.id +subtopic.write_attribute(:topic_id, new_topic.id) +``` + +虽然这些方法最后返回的结果可能有所不同,但是它们最终都会将 `subtopic` 对象的 `topic_id` 属性更新成 `topic.id`,上面的方法中有简单的,也有复杂的,不过都能达到相同的目的;我相信如果读者亲手创建上述的关系并使用 pry 查看源代码一定会对 getter 和 setter 的执行过程有着非常清楚的认识。 + +### 多对多关系 habtm + +无论是 has_many 还是 belongs_to 其实都是一个 ORM 原生需要支持的关系,但是 habtm(has_and_belongs_to_many) 却是 ActiveRecord 为我们提供的一个非常方便的语法糖,哪怕是并没有 `.has_and_belongs_to_many` 这个方法,我们也能通过 `.has_many` 实现多对多关系,得到与前者完全等价的效果,只是实现的过程稍微麻烦一些。 + +在这一小节中,我们想要了解 habtm 这个语法糖是如何工作的,它是如何将现有的关系组成更复杂的 habtm 的多对多关系的;想要了解它的工作原理,我们自然要分析它的源代码: + +```ruby +def has_and_belongs_to_many(name, scope = nil, **options, &extension) + builder = Builder::HasAndBelongsToMany.new name, self, options + join_model = ActiveSupport::Deprecation.silence { builder.through_model } + const_set join_model.name, join_model + private_constant join_model.name + + habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self) + middle_reflection = builder.middle_reflection join_model + Builder::HasMany.define_callbacks self, middle_reflection + Reflection.add_reflection self, middle_reflection.name, middle_reflection + middle_reflection.parent_reflection = habtm_reflection + + # ... + + hm_options = {} + hm_options[:through] = middle_reflection.name + hm_options[:source] = join_model.right_reflection.name + + # ... + + ActiveSupport::Deprecation.silence { has_many name, scope, hm_options, &extension } + _reflections[name.to_s].parent_reflection = habtm_reflection +end +``` + +> 在这里,我们对该方法的源代码重新进行组织和排序,方法的作用与 v5.1.4 中的完全相同。 + +上述方法在最开始先创建了一个 `HasAndBelongsToMany` 的 Builder 实例,然后在 block 中执行了这个 Builder 的 `#through_model` 方法: + +```ruby +def through_model + habtm = JoinTableResolver.build lhs_model, association_name, options + + join_model = Class.new(ActiveRecord::Base) { + class << self; + attr_accessor :left_model + attr_accessor :name + attr_accessor :table_name_resolver + attr_accessor :left_reflection + attr_accessor :right_reflection + end + + # ... + } + + join_model.name = "HABTM_#{association_name.to_s.camelize}" + join_model.table_name_resolver = habtm + join_model.left_model = lhs_model + join_model.add_left_association :left_side, anonymous_class: lhs_model + join_model.add_right_association association_name, belongs_to_options(options) + join_model +end +``` + +`#through_model` 方法会返回一个新的继承自 `ActiveRecord::Base` 的类,我们通过一下的例子来说明一下这里究竟做了什么,假设在我们的工程中定义了如下的两个类: + +```ruby +class Post < ActiveRecord::Base + has_and_belongs_to_many :tags +end + +class Tag < ActiveRecord::Base + has_and_belongs_to_many :posts +end +``` + +它们每个类都通过 `.has_and_belongs_to_many` 创建了一个 `join_model` 类,这两个类都是在当前类的命名空间下的: + +```ruby +class Post::HABTM_Posts < ActiveRecord::Base; end +class Tags::HABTM_Posts < ActiveRecord::Base; end +``` + +除了在当前类的命名空间下定义两个新的类之外,`#through_model` 方法还通过 `#add_left_association` 和 `#add_right_association` 为创建的私有类添加了两个 `.belongs_to` 方法的调用: + +```ruby +join_model = Class.new(ActiveRecord::Base) { + # ... + + def self.add_left_association(name, options) + belongs_to name, required: false, **options + self.left_reflection = _reflect_on_association(name) + end + + def self.add_right_association(name, options) + rhs_name = name.to_s.singularize.to_sym + belongs_to rhs_name, required: false, **options + self.right_reflection = _reflect_on_association(rhs_name) + end +} +``` + +所以在这里,每一个 HABTM 类中都通过 `.belongs_to` 增加了两个对数据库表中对应列的映射: + +```ruby +class Post::HABTM_Posts < ActiveRecord::Base + belongs_to :post_id, required: false + belongs_to :tag_id, required: false +end + +class Tags::HABTM_Posts < ActiveRecord::Base + belongs_to :tag_id, required: false + belongs_to :post_id, required: false +end +``` + +看到这里,你可能会认为既然有两个模型,那么应该会有两张表分别对应这两个模型,但是实际情况却不是这样。 + +![habtm-association-table-name](images/activerecord/habtm-association-table-name.png) + + +ActiveRecord 通过覆写这两个类的 `.table_name` 方法,使用一个 `JoinTableResolver` 来解决不同的模型拥有相同的数据库表的问题: + +```ruby +class Migration + module JoinTable + def join_table_name(table_1, table_2) + ModelSchema.derive_join_table_name(table_1, table_2).to_sym + end + end +end + +module ModelSchema + def self.derive_join_table_name(first_table, second_table) + [first_table.to_s, second_table.to_s].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').tr("\0", "_") + end +end +``` + +在默认的 `join_table` 规则中,两张表会按照字母顺序排序,最后通过 `_` 连接到一起,但是如果两张表有着完全相同的前缀,比如 music_artists 和 music_records 两张表,它们连接的结果就是 music_artists_records,公共的前缀会被删除,这种情况经常发生在包含命名空间的模型中,例如:`Music::Artist`。 + +当我们已经通过多对多关系的 Builder 创建了一个中间模型之后,就会建立两个 `Reflection` 对象: + +```ruby +habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self) +middle_reflection = builder.middle_reflection join_model +Builder::HasMany.define_callbacks self, middle_reflection +Reflection.add_reflection self, middle_reflection.name, middle_reflection +middle_reflection.parent_reflection = habtm_reflection +``` + +其中一个对象是 `HasAndBelongsToManyReflection` 实例,表示当前的多对多关系,另一个对象是 `#middle_reflection` 方法返回的 `HasMany`,表示当前的类与 `join_model` 之间有一个一对多关系,这个关系是隐式的,不过我们可以通过下面的代码来『理解』它: + +```ruby +class Post < ActiveRecord::Base + # has_and_belongs_to_many :posts + # = + has_many :posts_tag + # + + # ... +end +``` + +上述的代码构成了整个多对多关系的一部分,而另一部分由下面的代码来处理,当模型持有了一个跟中间模型相关的一对多关系之后,就会创建另一个以中间模型为桥梁 has_many 关系: + +```ruby +hm_options = {} +hm_options[:through] = middle_reflection.name +hm_options[:source] = join_model.right_reflection.name + +ActiveSupport::Deprecation.silence { has_many name, scope, hm_options, &extension } +``` + +这里还是使用 `Post` 和 `Tag` 这两个模型之间的关系举例子,通过上述代码,我们会在两个类中分别建立如下的关系: + +```ruby +class Post < ActiveRecord::Base + # has_many :posts_tag + has_many :tags, through: :posts_tag, source: :tag +end + +class Tag < ActiveRecord::Base + # has_many :tags_post + has_many :post, through: :tags_post, source: :post +end +``` + +通过两个隐式的 has_many 关系,两个显示的 has_many 就能够通过 `through` 和 `source` 间接找到自己对应的多个数据行,而从开发者的角度来看,整个工程中只使用了一行代码 `has_and_belongs_to_many :models`,其他的工作完全都是隐式的。 + +![many-to-many-associations](images/activerecord/many-to-many-associations.png) + +由于关系型数据库其实并没有物理上的多对多关系,只有在逻辑上才能实现多对多,所以对于每一个模型来说,它实现的都是一对多关系;只有从整体来看,通过 `PostsTags` 第三张表的引入,我们实现的才是从 `Post` 到 `Tag` 之间的多对多关系。 + +### 小结 + +ActiveRecord 对关系的支持其实非常全面,从最常见的一对一、一对多关系,再到多对多关系,都有着非常优雅、简洁的实现,虽然这一小节中没能全面的介绍所有关系的实现,但是对整个模块中重要类和整体架构的介绍已经非常具体了;不得不感叹 ActiveRecord 对多对多关系方法 `has_and_belongs_to_many` 的实现非常整洁,我们在分析其实现时也非常顺畅。 + +## Migrations 任务和执行过程 + +Migrations(迁移)是 ActiveRecord 提供的一种用于更改数据库 Schema 的方式,它提供了可以直接操作数据库的 DSL,这样我们就不需要自己去手写所有的 SQL 来更新数据库中的表结构了。 + +![activerecord-migrations](images/activerecord/activerecord-migrations.png) + +每一个 Migration 都具有一个唯一的时间戳,每次进行迁移时都会在现有的数据库中执行当前 Migration 文件的 DSL 更新数据库 Schema 得到新的数据库版本。而想要理解 Migrations 是如何工作的,就需要知道 `#create_table`、`#add_column` 等 DSL 是怎么实现的。 + +### Migration[5.1] + +我在使用 ActiveRecord 提供的数据库迁移的时候一直都特别好奇 `Migration[5.1]` 后面跟着的这个 `[5.1]` 是个什么工作原理,看了源代码之后我才知道: + +```ruby +class Migration + def self.[](version) + Compatibility.find(version) + end +end +``` + +`.[]` 是 `ActiveRecord::Migration` 的类方法,它通过执行 `Compatibility.find` 来判断当前的代码中使用的数据库迁移版本是否与 gem 中的版本兼容: + +```ruby +class Current < Migration +end +``` + +`compatibility.rb` 在兼容性方面做了很多事情,保证 ActiveRecord 中的迁移都是可以向前兼容的,在这里也就不准备介绍太多了。 + +### 从 rake db:migrate 开始 + +作者在阅读迁移部分的源代码时最开始以 `Migration` 类作为入口,结果发现这并不是一个好的选择,最终也没能找到定义 DSL 的位置,所以重新选择了 `rake db:migrate` 作为入口分析迁移的实现;通过对工程目录的分析,很快就能发现 ActiveRecord 中所有的 rake 命令都位于 `lib/railties/database.rake` 文件中,在文件中也能找到 `db:migrate` 对应的 rake 任务: + +```ruby +db_namespace = namespace :db do + desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)." + task migrate: [:environment, :load_config] do + ActiveRecord::Tasks::DatabaseTasks.migrate + db_namespace["_dump"].invoke + end +end +``` + +上述代码中的 `DatabaseTasks` 类就包含在 `lib/active_record/tasks` 目录中的 `database_tasks.rb` 文件里: + +```ruby +lib/active_record/tasks/ +├── database_tasks.rb +├── mysql_database_tasks.rb +├── postgresql_database_tasks.rb +└── sqlite_database_tasks.rb +``` + +`#migrate` 方法就是 `DatabaseTasks` 的一个实例方法,同时 ActiveRecord 通过 `extend self` 将 `#migrate` 方法添加到了当前类的单类上,成为了当前类的类方法: + +```ruby +module Tasks + module DatabaseTasks + extend self + + def migrate + raise "Empty VERSION provided" if ENV["VERSION"] && ENV["VERSION"].empty? + + version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil + scope = ENV["SCOPE"] + Migrator.migrate(migrations_paths, version) do |migration| + scope.blank? || scope == migration.scope + end + ActiveRecord::Base.clear_cache! + end + end +end +``` + +#### 『迁移器』Migrator + +迁移任务中主要使用了 `Migrator.migrate` 方法,通过传入迁移文件的路径和期望的迁移版本对数据库进行迁移: + +```ruby +class Migrator#:nodoc: + class << self + def migrate(migrations_paths, target_version = nil, &block) + case + when target_version.nil? + up(migrations_paths, target_version, &block) + when current_version == 0 && target_version == 0 + [] + when current_version > target_version + down(migrations_paths, target_version, &block) + else + up(migrations_paths, target_version, &block) + end + end + end +end +``` + +在默认情况下,显然我们是不会传入目标的数据库版本的,也就是 `target_version.nil? == true`,这时会执行 `.up` 方法,对数据库向『上』迁移: + +```ruby +def up(migrations_paths, target_version = nil) + migrations = migrations(migrations_paths) + migrations.select! { |m| yield m } if block_given? + + new(:up, migrations, target_version).migrate +end +``` + +#### 方法调用栈 + +通过 `.new` 方法 ActiveRecord 初始化了一个新的 `Migrator` 实例,然后执行了 `Migrator#migrate`,在整个迁移执行的过程中,我们有以下的方法调用栈: + +![rake-db-migrate](images/activerecord/rake-db-migrate.png) + +在整个迁移过程的调用栈中,我们会关注以下的四个部分,首先是 `Migrator#migrate_without_lock` 方法: + +```ruby +def migrate_without_lock + if invalid_target? + raise UnknownMigrationVersionError.new(@target_version) + end + + result = runnable.each do |migration| + execute_migration_in_transaction(migration, @direction) + end + + record_environment + result +end +``` + +这个方法其实并没有那么重要,但是这里调用了 `Migrator#runnable` 方法,这个无参的方法返回了所有需要运行的 `Migration` 文件,`Migrator#runnable` 是如何选择需要迁移的文件是作者比较想要了解的,也是作者认为比较重要的地方: + +```ruby +def runnable + runnable = migrations[start..finish] + if up? + runnable.reject { |m| ran?(m) } + else + runnable.pop if target + runnable.find_all { |m| ran?(m) } + end +end + +def ran?(migration) + migrated.include?(migration.version.to_i) +end +``` + +通过对这个方法的阅读的分析,我们可以看到,如果迁移模式是 `:up`,那么就会选择所有未迁移的文件,也就是说在这时**迁移文件的选择与创建的顺序是无关的**。 + +#### 迁移的执行 + +当我们通过 `#runnable` 获得了整个待运行的迁移文件数组之后,就可以遍历所有的文件一次执行 `Migrator#execute_migrate_in_transaction` 方法了,在调用栈的最后会执行 `Migration#exec_migration`: + +```ruby +def exec_migration(conn, direction) + @connection = conn + if respond_to?(:change) + if direction == :down + revert { change } + else + change + end + else + send(direction) + end +ensure + @connection = nil +end +``` + +到这里就能与我们平时在 `Migration` 中实现的 `#change`、`#up` 和 `#down` 连到一起,逻辑也走通了;上述代码的逻辑还是很清晰的,如果当前的 `Migratoin` 实现了 `#change` 方法就会根据 `direction` 选择执行 `#change` 还是 `#revert + #change`,否则就会按照迁移的方向执行对应的方法。 + +### Migrations 的 DSL + +在数据迁移的模块执行的 Migration 文件中包含的都是 ActiveRecord 提供的 DSL 语法,这部分语法包含两部分,一部分是 Schema 相关的 DSL `schema_statements.rb`,其中包括表格的创建和删除以及一些用于辅助 Schema 创建的 `#column_exists?` 等方法,另一部分是表定义相关的 DSL `schema_definitions.rb`,其中包括处理表结构的 `TableDefinition` 类和抽象代表一张数据库中表的 `Table` 类。 + +#### 抽象适配器 + +在整个 `connection_adapters` 的子模块中,绝大多数模块在三大 SQL 数据库,MySQL、PostgreSQL 和 sqlite3 中都有着各自的实现: + +```ruby +lib/active_record/connection_adapters +├── abstract +│   ├── connection_pool.rb +│   ├── database_limits.rb +│   ├── database_statements.rb +│   ├── query_cache.rb +│   ├── quoting.rb +│   ├── savepoints.rb +│   ├── schema_creation.rb +│   ├── schema_definitions.rb +│   ├── schema_dumper.rb +│   ├── schema_statements.rb +│   └── transaction.rb +├── mysql +│   ├── column.rb +│   ├── database_statements.rb +│   ├── explain_pretty_printer.rb +│   ├── quoting.rb +│   ├── schema_creation.rb +│   ├── schema_definitions.rb +│   ├── schema_dumper.rb +│   ├── schema_statements.rb +│   └── type_metadata.rb +├── postgresql +│   └── ... +├── sqlite3 +│   └── ... +├── abstract_adapter.rb +├── ... +└── sqlite3_adapter.rb +``` + +不过这三个数据库的所有子模块都继承自 `AbstractAdapter` 下面对应的子模块,以获得一些三者共用的能力,包括数据库、Schema 的声明与管理等功能。 + +![abstract-adapter-and-much-more](images/activerecord/abstract-adapter-and-much-more.png) + +通过 `AbstractAdapter` 抽离出的公用功能,我们可以通过新的适配器随时适配其他的 SQL 数据库。 + +#### Schema DSL + +数据库的 Schema DSL 部分就包含我们经常使用的 `#create_table`、`#rename_table` 以及 `#add_column` 这些需要表名才能执行的方法,在这里以最常见的 `#create_table` 为例,简单分析一下这部分代码的实现: + +```ruby +def create_table(table_name, comment: nil, **options) + td = create_table_definition table_name, options[:temporary], options[:options], options[:as], comment: comment + + yield td if block_given? + + execute schema_creation.accept td +end +``` + +首先,在创建表时先通过 `#create_table_definition` 方法创建一个新的 `TableDefinition` 实例,然后将这个实例作为参数传入 block: + +```ruby +create_table :users do |t| +end +``` + +在 block 对这个 `TableDefinition` 对象一顿操作后,会通过 `SchemaCreation#accept` 方法获得一个用于在数据库中,能够创建表的 SQL 语句: + +```ruby +def accept(o) + m = @cache[o.class] ||= "visit_#{o.class.name.split('::').last}" + send m, o +end + +def visit_TableDefinition(o) + create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE #{quote_table_name(o.name)} " + + statements = o.columns.map { |c| accept c } + statements << accept(o.primary_keys) if o.primary_keys + + create_sql << "(#{statements.join(', ')})" if statements.present? + add_table_options!(create_sql, table_options(o)) + create_sql << " AS #{@conn.to_sql(o.as)}" if o.as + create_sql +end +``` + +`SchemaCreation` 类就是一个接受各种各样的 `TableDefinition`、`PrimaryKeyDefinition` 对象返回 SQL 的一个工具,可以将 `SchemaCreation` 理解为一个表结构的解释器;最后的 `#execute` 会在数据库中执行 SQL 改变数据库中的表结构。 + +在 `SchemaStatements` 中定义的其它方法的实现也都是大同小异,比如 `#drop_table` 其实都是删除数据库中的某张表: + +```ruby +def drop_table(table_name, options = {}) + execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}" +end +``` + +#### 表定义 DSL + +`SchemaStatements` 中定义的方法,参数大都包含 `table_name`,而另一个类 `TableDefinitions` 就包含了直接对表操作的 DSL: + +```ruby +create_table :foo do |t| + puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition" +end +``` + +当我们在 `#create_table` 中使用例如 `#string`、`#integer` 等方法时,所有的方法都会通过元编程的魔法最终执行 `TableDefinition#column` 改变表的定义: + +```ruby +module ColumnMethods + [ + :bigint, + # ... + :integer, + :string, + :text, + :time, + :timestamp, + :virtual, + ].each do |column_type| + module_eval <<-CODE, __FILE__, __LINE__ + 1 + def #{column_type}(*args, **options) + args.each { |name| column(name, :#{column_type}, options) } + end + CODE + end + alias_method :numeric, :decimal +end +``` + +`#column` 方法非常神奇,它从各处收集有关当前表的定义,最终为表中的每一个字段创建一个 `ColumnDefinition` 实例,并存储到自己持有的 `@columns_hash` 中: + +```ruby +def column(name, type, options = {}) + name = name.to_s + type = type.to_sym if type + options = options.dup + + index_options = options.delete(:index) + index(name, index_options.is_a?(Hash) ? index_options : {}) if index_options + @columns_hash[name] = new_column_definition(name, type, options) + self +end + +def new_column_definition(name, type, **options) + type = aliased_types(type.to_s, type) + options[:primary_key] ||= type == :primary_key + options[:null] = false if options[:primary_key] + create_column_definition(name, type, options) +end + +def create_column_definition(name, type, options) + ColumnDefinition.new(name, type, options) +end +``` + +除了 `ColumnDefinition` 之外,在 ActiveRecord 中还存在 `PrimaryKeyDefinition`、`IndexDefinition` 等等类和结构体用于表示数据库中的某一种元素。 + +表结构在最后会被 `SchemaCreation` 类的 `#accept` 方法展开,最后在数据库中执行。 + +### 小结 + +到这里整个 Migrations 部分的实现就已经阅读分析完了,整个『模块』包含两个部分,一部分是 rake 任务执行 DSL 代码的过程,另一部分是 DSL 的实现,两部分的结合最终构成了整个 Migrations 模块的全部内容。 + +ActiveRecord 对于 Migration 迁移机制的设计确实很好的解决数据库中的表结构不断变更的问题,同时因为所有的 Migration 文件都在版本控制中管理,我们也能够随时还原数据库中的表结构。 + +## 总结 + +文章对 ActiveRecord 中涉及的很多问题都进行了分析和介绍,包括模型的创建、查询以及关系,还包括数据库表迁移的实现,本来想将文中的几个部分分开进行介绍,但是写着写着就懒得分开了,如果对文章的内容有疑问,请在博客下面的 Disqus 评论系统中留言,需要翻墙。 + +> 原文链接:[理解 ActiveRecord](https://draveness.me/activerecord.html) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) + + diff --git a/contents/Rails/images/activerecord/15079789320881.jpg b/contents/Rails/images/activerecord/15079789320881.jpg new file mode 100644 index 0000000..7257a5e Binary files /dev/null and b/contents/Rails/images/activerecord/15079789320881.jpg differ diff --git a/contents/Rails/images/activerecord/15079789363342.jpg b/contents/Rails/images/activerecord/15079789363342.jpg new file mode 100644 index 0000000..7257a5e Binary files /dev/null and b/contents/Rails/images/activerecord/15079789363342.jpg differ diff --git a/contents/Rails/images/activerecord/abstract-adapter-and-much-more.png b/contents/Rails/images/activerecord/abstract-adapter-and-much-more.png new file mode 100644 index 0000000..f8535c8 Binary files /dev/null and b/contents/Rails/images/activerecord/abstract-adapter-and-much-more.png differ diff --git a/contents/Rails/images/activerecord/active-record-relation-delegation.png b/contents/Rails/images/activerecord/active-record-relation-delegation.png new file mode 100644 index 0000000..724fac3 Binary files /dev/null and b/contents/Rails/images/activerecord/active-record-relation-delegation.png differ diff --git a/contents/Rails/images/activerecord/activemodel-validators.png b/contents/Rails/images/activerecord/activemodel-validators.png new file mode 100644 index 0000000..d69b1af Binary files /dev/null and b/contents/Rails/images/activerecord/activemodel-validators.png differ diff --git a/contents/Rails/images/activerecord/activerecord-ancestor-builders.png b/contents/Rails/images/activerecord/activerecord-ancestor-builders.png new file mode 100644 index 0000000..bd2f166 Binary files /dev/null and b/contents/Rails/images/activerecord/activerecord-ancestor-builders.png differ diff --git a/contents/Rails/images/activerecord/activerecord-architecture.png b/contents/Rails/images/activerecord/activerecord-architecture.png new file mode 100644 index 0000000..ea1a0d3 Binary files /dev/null and b/contents/Rails/images/activerecord/activerecord-architecture.png differ diff --git a/contents/Rails/images/activerecord/activerecord-associations.png b/contents/Rails/images/activerecord/activerecord-associations.png new file mode 100644 index 0000000..b203cb3 Binary files /dev/null and b/contents/Rails/images/activerecord/activerecord-associations.png differ diff --git a/contents/Rails/images/activerecord/activerecord-base-save.png b/contents/Rails/images/activerecord/activerecord-base-save.png new file mode 100644 index 0000000..a887e8f Binary files /dev/null and b/contents/Rails/images/activerecord/activerecord-base-save.png differ diff --git a/contents/Rails/images/activerecord/activerecord-hasmany-ancestors.png b/contents/Rails/images/activerecord/activerecord-hasmany-ancestors.png new file mode 100644 index 0000000..63438c7 Binary files /dev/null and b/contents/Rails/images/activerecord/activerecord-hasmany-ancestors.png differ diff --git a/contents/Rails/images/activerecord/activerecord-migrations.png b/contents/Rails/images/activerecord/activerecord-migrations.png new file mode 100644 index 0000000..a72dd3c Binary files /dev/null and b/contents/Rails/images/activerecord/activerecord-migrations.png differ diff --git a/contents/Rails/images/activerecord/activerecord-reflections.png b/contents/Rails/images/activerecord/activerecord-reflections.png new file mode 100644 index 0000000..5bfdfbd Binary files /dev/null and b/contents/Rails/images/activerecord/activerecord-reflections.png differ diff --git a/contents/Rails/images/activerecord/activerecord-relation-value-methods.png b/contents/Rails/images/activerecord/activerecord-relation-value-methods.png new file mode 100644 index 0000000..a254b85 Binary files /dev/null and b/contents/Rails/images/activerecord/activerecord-relation-value-methods.png differ diff --git a/contents/Rails/images/activerecord/actual-callstack-for-activerecord-base-save.png b/contents/Rails/images/activerecord/actual-callstack-for-activerecord-base-save.png new file mode 100644 index 0000000..140e177 Binary files /dev/null and b/contents/Rails/images/activerecord/actual-callstack-for-activerecord-base-save.png differ diff --git a/contents/Rails/images/activerecord/callstack-for-belongs-to-association-getter.png b/contents/Rails/images/activerecord/callstack-for-belongs-to-association-getter.png new file mode 100644 index 0000000..e4d06fe Binary files /dev/null and b/contents/Rails/images/activerecord/callstack-for-belongs-to-association-getter.png differ diff --git a/contents/Rails/images/activerecord/callstack-for-belongs-to-association-setter.png b/contents/Rails/images/activerecord/callstack-for-belongs-to-association-setter.png new file mode 100644 index 0000000..88010b3 Binary files /dev/null and b/contents/Rails/images/activerecord/callstack-for-belongs-to-association-setter.png differ diff --git a/contents/Rails/images/activerecord/database-statement-insert.png b/contents/Rails/images/activerecord/database-statement-insert.png new file mode 100644 index 0000000..1da4a7f Binary files /dev/null and b/contents/Rails/images/activerecord/database-statement-insert.png differ diff --git a/contents/Rails/images/activerecord/habtm-association-table-name.png b/contents/Rails/images/activerecord/habtm-association-table-name.png new file mode 100644 index 0000000..e87b4c3 Binary files /dev/null and b/contents/Rails/images/activerecord/habtm-association-table-name.png differ diff --git a/contents/Rails/images/activerecord/many-to-many-associations.png b/contents/Rails/images/activerecord/many-to-many-associations.png new file mode 100644 index 0000000..8f32cb6 Binary files /dev/null and b/contents/Rails/images/activerecord/many-to-many-associations.png differ diff --git a/contents/Rails/images/activerecord/one-to-many-association.png b/contents/Rails/images/activerecord/one-to-many-association.png new file mode 100644 index 0000000..125a88c Binary files /dev/null and b/contents/Rails/images/activerecord/one-to-many-association.png differ diff --git a/contents/Rails/images/activerecord/rake-db-migrate.png b/contents/Rails/images/activerecord/rake-db-migrate.png new file mode 100644 index 0000000..550857b Binary files /dev/null and b/contents/Rails/images/activerecord/rake-db-migrate.png differ diff --git a/contents/ReactiveObjC/RACChannel.md b/contents/ReactiveObjC/RACChannel.md new file mode 100644 index 0000000..69834f9 --- /dev/null +++ b/contents/ReactiveObjC/RACChannel.md @@ -0,0 +1,280 @@ +# RAC 中的双向数据绑定 RACChannel + +之前讲过了 ReactiveCocoa 中的一对一的单向数据流 `RACSignal` 和一对多的单向数据流 `RACMulticastConnection`,这一篇文章分析的是一对一的双向数据流 `RACChannel`。 + +![What-is-RACChanne](images/RACChannel/What-is-RACChannel.png) + +`RACChannel` 其实是一个相对比较复杂的类,但是,对其有一定了解之后合理运用的话,会在合适的业务中提供非常强大的支持能够极大的简化业务代码。 + +## RACChannel 简介 + +`RACChannel` 可以被理解为一个双向的连接,这个连接的两端都是 `RACSignal` 实例,它们可以向彼此发送消息,如果我们在视图和模型之间通过 `RACChannel` 建立这样的连接: + +![Connection-Between-View-Mode](images/RACChannel/Connection-Between-View-Model.png) + +那么从模型发出的消息,最后会发送到视图上;反之,用户对视图进行的操作最后也会体现在模型上。这种通信方式的实现是基于信号的,`RACChannel` 内部封装了两个 `RACChannelTerminal` 对象,它们都是 `RACSignal` 的子类: + +![RACChannel-Interface](images/RACChannel/RACChannel-Interface.png) + +对模型进行的操作最后都会发送给 `leadingTerminal` 再通过内部的实现发送给 `followingTerminal`,由于视图是 `followingTerminal` 的订阅者,所以消息最终会发送到视图上。 + +![Messages-Send-From-Mode](images/RACChannel/Messages-Send-From-Model.png) + +在上述情况下,`leadingTerminal` 的订阅者(模型)并不会收到消息,它的订阅者(视图)只会在 `followingTerminal` 收到消息时才会接受到新的值。 + +同时,`RACChannel` 的绑定都是双向的,视图收到用户的动作,例如点击等事件时,会将消息发送给 `followingTerminal`,而 `followingTerminal` 并**不会**将消息发送给自己的订阅者(视图),而是会发送给 `leadingTerminal`,并通过 `leadingTerminal` 发送给其订阅者,即模型。 + +![Terminals-Between-View-Mode](images/RACChannel/Terminals-Between-View-Model.png) + +上图描述了信息在 `RACChannel` 之间的传递过程,无论是模型属性的改变还是用户对视图进行的操作都会通过这两个 `RACChannelTerminal` 传递到另一端;同时,由于消息不会发送给自己的订阅者,所以不会造成信息的循环发送。 + +## RACChannel 和 RACChannelTerminal + +`RACChannel` 和 `RACChannelTerminal` 的关系非常密切,前者可以理解为一个网络连接,后者可以理解为 `socket`,表示网络连接的一端,下图描述了 `RACChannel` 与网络连接中概念的一一对应关系。 + +![Channel-And-Network-Connection](images/RACChannel/Channel-And-Network-Connection.png) + ++ 在客户端使用 `write` 向 `socket` 中发送消息时,`socket` 的持有者客户端不会收到消息,只有在 `socket` 上调用 `read` 的服务端才会收到消息;反之亦然。 ++ 在模型使用 `sendNext` 向`leadingTerminal` 中发送消息时,`leadingTerminal` 的订阅者模型不会收到消息,只有在 `followingTerminal` 上调用 `subscribe` 的视图才会收到消息;反之亦然。 + +### RACChannelTerminal 的实现 + +为什么向 `RACChannelTerminal` 发送消息,它的订阅者获取不到?先来看一下它在头文件中的定义: + +```objectivec +@interface RACChannelTerminal : RACSignal <RACSubscriber> +@end +``` + +`RACChannelTerminal` 是一个信号的子类,同时它还遵循了 `RACSubscriber` 协议,也就是可以向它调用 `-sendNext:` 等方法;`RAChannelTerminal` 中持有了两个对象: + +![RACChannelTerminal-Interface](images/RACChannel/RACChannelTerminal-Interface.png) + +在初始化时,需要传入 `values` 和 `otherTerminal` 这两个属性,其中 `values` 表示当前断点,`otherTerminal` 表示远程端点: + +```objectivec +- (instancetype)initWithValues:(RACSignal *)values otherTerminal:(id<RACSubscriber>)otherTerminal { + self = [super init]; + _values = values; + _otherTerminal = otherTerminal; + return self; +} +``` + +当然,作为 `RACSignal` 的子类,`RACChannelTerminal` 必须覆写 `-subscribe:` 方法: + +```objectivec +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + return [self.values subscribe:subscriber]; +} +``` + +在订阅者调用 `-subscribeNext:` 等方法发起订阅时,实际上订阅的是当前端点;如果向当前端点发送消息,会被转发到远程端点上,而这也就是当前端点的订阅者不会接收到向当前端点发送消息的原因: + +```objectivec +- (void)sendNext:(id)value { + [self.otherTerminal sendNext:value]; +} +- (void)sendError:(NSError *)error { + [self.otherTerminal sendError:error]; +} +- (void)sendCompleted { + [self.otherTerminal sendCompleted]; +} +``` + +### RACChannel 的初始化 + +我们在任何情况下都不应该直接使用 `-init` 方法初始化 `RACChannelTerminal` 的实例,而是应该以创建 `RACChannel` 的方式生成它: + +```objectivec +- (instancetype)init { + self = [super init]; + + RACReplaySubject *leadingSubject = [RACReplaySubject replaySubjectWithCapacity:0]; + RACReplaySubject *followingSubject = [RACReplaySubject replaySubjectWithCapacity:1]; + + [[leadingSubject ignoreValues] subscribe:followingSubject]; + [[followingSubject ignoreValues] subscribe:leadingSubject]; + + _leadingTerminal = [[RACChannelTerminal alloc] initWithValues:leadingSubject otherTerminal:followingSubject]; + _followingTerminal = [[RACChannelTerminal alloc] initWithValues:followingSubject otherTerminal:leadingSubject]; + + return self; +} +``` + +两个 `RACChannelTerminal` 中包装的其实是两个 `RACSubject` 热信号,它们既可以作为订阅者,也可以接收其他对象发送的消息;我们并不希望 `leadingSubject` 有任何的初始值,但是我们需要 `error` 和 `completed` 信息可以被重播。 + +![Sending-Errors-And-Completed-Messages](images/RACChannel/Sending-Errors-And-Completed-Messages.png) + +通过 `-ignoreValues` 和 `-subscribe:` 方法,`leadingSubject` 和 `followingSubject` 两个热信号中产生的错误会互相发送,这是为了防止连接的两端一边发生了错误,另一边还继续工作的情况的出现。 + +在初始化方法的最后,生成两个 `RACChannelTerminal` 实例的过程就不多说了。 + +## RACChannel 与 UIKit 组件 + +如果在整个 ReactiveCocoa 工程中搜索 `RACChannel`,你会发现以下的 UIKit 组件都与 `RACChannel` 有着非常密切的关系: + +![RACChannel-Hierachy](images/RACChannel/RACChannel-Hierachy.png) + +UIKit 中的这些组件都提供了使用 `RACChannel` 的接口,用以降低数据双向绑定的复杂度,我们以 `UITextField` 为例,它在分类的接口中提供了 `rac_newTextChannel` 方法: + +```objectivec +- (RACChannelTerminal *)rac_newTextChannel { + return [self rac_channelForControlEvents:UIControlEventAllEditingEvents key:@keypath(self.text) nilValue:@""]; +} +``` + +上述方法用于返回一个一端绑定 `UIControlEventAllEditingEvents` 事件的 `RACChannelTerminal` 对象。 + +![UITextField-RACChannel-Interface](images/RACChannel/UITextField-RACChannel-Interface.png) + +`UIControlEventAllEditingEvents` 事件发生时,它会将自己的 `text` 属性作为信号发送到 `followingTerminal -> leadingTerminal` 管道中,最后发送给 `leadingTerminal` 的订阅者。 + +在 `rac_newTextChannel` 中调用的方法 `-rac_channelForControlEvents:key:nilValue:` 是一个 `UIControl` 的私有方法: + +```objectivec +- (RACChannelTerminal *)rac_channelForControlEvents:(UIControlEvents)controlEvents key:(NSString *)key nilValue:(id)nilValue { + key = [key copy]; + RACChannel *channel = [[RACChannel alloc] init]; + + RACSignal *eventSignal = [[[self + rac_signalForControlEvents:controlEvents] + mapReplace:key] + takeUntil:[[channel.followingTerminal + ignoreValues] + catchTo:RACSignal.empty]]; + [[self + rac_liftSelector:@selector(valueForKey:) withSignals:eventSignal, nil] + subscribe:channel.followingTerminal]; + + RACSignal *valuesSignal = [channel.followingTerminal + map:^(id value) { + return value ?: nilValue; + }]; + [self rac_liftSelector:@selector(setValue:forKey:) withSignals:valuesSignal, [RACSignal return:key], nil]; + + return channel.leadingTerminal; +} +``` + +这个方法为所有的 `UIControl` 子类,包括 `UITextField`、`UISegmentedControl` 等等,它的主要作用就是当传入的 `controlEvents` 事件发生时,将 UIKit 组件的属性 `key` 发送到返回的 `RACChannelTerminal` 实例中;同时,在向返回的 `RACChannelTerminal` 实例中发送消息时,也会自动更新 UIKit 组件的属性。 + +上面的代码在初始化 `RACChannel` 之后做了两件事情,首先是在 `UIControlEventAllEditingEvents` 事件发生时,将 `text` 属性发送到 `followingTerminal` 中: + +```objectivec +RACSignal *eventSignal = [[[self + rac_signalForControlEvents:controlEvents] + mapReplace:key] + takeUntil:[[channel.followingTerminal + ignoreValues] + catchTo:RACSignal.empty]]; +[[self + rac_liftSelector:@selector(valueForKey:) withSignals:eventSignal, nil] + subscribe:channel.followingTerminal]; +``` + +第二个是在 `followingTerminal` 接收到来自 `leadingTerminal` 的消息时,更新 `UITextField` 的 `text` 属性。 + +```objectivec +RACSignal *valuesSignal = [channel.followingTerminal + map:^(id value) { + return value ?: nilValue; + }]; +[self rac_liftSelector:@selector(setValue:forKey:) withSignals:valuesSignal, [RACSignal return:key], nil]; +``` + +这两件事情都是通过 `-rac_liftSelector:withSignals:` 方法来完成的,不过,我们不会在这篇文章中介绍这个方法。 + +## RACChannel 与 KVO + +`RACChannel` 不仅为 UIKit 组件提供了接口,还为键值观测提供了 `RACKVOChannel` 来高效地完成双向绑定;`RACKVOChannel` 是 `RACChannel` 的子类: + +![RACKVOChanne](images/RACChannel/RACKVOChannel.png) + +在 `RACKVOChannel` 提供的接口中,我们一般都会使用 `RACChannelTo` 来观测某一个对象的对应属性,三个参数依次为对象、属性和默认值: + +```objectivec +RACChannelTerminal *integerChannel = RACChannelTo(self, integerProperty, @42); +``` + +而 `RACChannelTo` 是 `RACKVOChannel` 头文件中的一个宏,上面的表达式可以展开成为: + +```objectivec +RACChannelTerminal *integerChannel = [[RACKVOChannel alloc] initWithTarget:self keyPath:@"integerProperty" nilValue:@42][@"followingTerminal"]; +``` + +该宏初始化了一个 `RACKVOChannel` 对象,并通过方括号的方式获取其中的 `followingTerminal`,这种获取类属性的方式是通过覆写以下的两个方法实现的: + +```objectivec +- (RACChannelTerminal *)objectForKeyedSubscript:(NSString *)key { + RACChannelTerminal *terminal = [self valueForKey:key]; + return terminal; +} + +- (void)setObject:(RACChannelTerminal *)otherTerminal forKeyedSubscript:(NSString *)key { + RACChannelTerminal *selfTerminal = [self objectForKeyedSubscript:key]; + [otherTerminal subscribe:selfTerminal]; + [[selfTerminal skip:1] subscribe:otherTerminal]; +} +``` + +又由于覆写了这两个方法,在 `-setObject:forKeyedSubscript:` 时会自动调用 `-subscribe:` 方法完成双向绑定,所以我们可以使用 `=` 来对两个 `RACKVOChannel` 进行双向绑定: + +```objectivec +RACChannelTo(view, property) = RACChannelTo(model, property); + +[[RACKVOChannel alloc] initWithTarget:view keyPath:@"property" nilValue:nil][@"followingTerminal"] = [[RACKVOChannel alloc] initWithTarget:model keyPath:@"property" nilValue:nil][@"followingTerminal"]; +``` + +以上的两种方式是完全等价的,它们都会在对方的属性更新时更新自己的属性。 + +![RACChannelTo-Model-Vie](images/RACChannel/RACChannelTo-Model-View.png) + +实现的方式其实与 `RACChannel` 差不多,这里不会深入到代码中进行介绍,与 `RACChannel` 的区别是,`RACKVOChannel` 并没有暴露出 `leadingTerminal` 而是 `followingTerminal`: + +![RACChannelTo-And-Property](images/RACChannel/RACChannelTo-And-Property.png) + +## RACChannel 实战 + +这一小节通过一个简单的例子来解释如何使用 `RACChannel` 进行双向数据绑定。 + +![TextField-With-Channe](images/RACChannel/TextField-With-Channel.gif) + +在整个视图上有两个 `UITextField`,我们想让这两个 `UITextField` `text` 的值相互绑定,在一个 `UITextField` 编辑时也改变另一个 `UITextField` 中的内容: + +```objectivec +@property (weak, nonatomic) IBOutlet UITextField *textField; +@property (weak, nonatomic) IBOutlet UITextField *anotherTextField; +``` + +实现的过程非常简单,分别获取两个 `UITextField` 的 `rac_newTextChannel` 属性,并让它们订阅彼此的内容: + +```objectivec +[self.textField.rac_newTextChannel subscribe:self.anotherTextField.rac_newTextChannel]; +[self.anotherTextField.rac_newTextChannel subscribe:self.textField.rac_newTextChannel]; +``` + +这样在使用两个文本输入框时就能达到预期的效果了,这是一个非常简单的例子,可以得到如下的结构图。 + +![Two-UITextField-With-RACChanne](images/RACChannel/Two-UITextField-With-RACChannel.png) + +两个 `UITextField` 通过 `RACChannel` 互相影响,在对方属性更新时同时更新自己的属性。 + +## 总结 + +`RACChannel` 非常适合于视图和模型之间的双向绑定,在对方的属性或者状态更新时及时通知自己,达到预期的效果;我们可以使用 ReactiveCocoa 中内置的很多与 `RACChannel` 有关的方法,来获取开箱即用的 `RACChannelTerminal`,当然也可以使用 `RACChannelTo` 通过 `RACKVOChannel` 来快速绑定类与类的属性。 + +## References + ++ [Bi-directional Data Bindings in ReactiveCocoa with RACChannel](https://spin.atomicobject.com/2015/05/04/bi-directional-data-bindings-reactivecocoa/) ++ [ReactiveCocoa 核心元素与信号流](http://tech.meituan.com/ReactiveCocoaSignalFlow.html) + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/racchannel + + diff --git a/contents/ReactiveObjC/RACCommand.md b/contents/ReactiveObjC/RACCommand.md new file mode 100644 index 0000000..72e3673 --- /dev/null +++ b/contents/ReactiveObjC/RACCommand.md @@ -0,0 +1,427 @@ +# 优雅的 RACCommand + +![raccommad-cove](images/RACCommand/raccommad-cover.jpg) + +`RACCommand` 是一个在 ReactiveCocoa 中比较复杂的类,大多数使用 ReactiveCocoa 的人,尤其是初学者并不会经常使用它。 + +在很多情况下,虽然使用 `RACSignal` 和 `RACSubject` 就能解决绝大部分问题,但是 `RACCommand` 的使用会为我们带来巨大的便利,尤其是在与副作用相关的操作中。 + +![What-is-RACCommand](images/RACCommand/What-is-RACCommand.png) + +> 文章中不会讨论 `RACCommand` 中的并行执行问题,也就是忽略了 `allowsConcurrentExecution` 以及 `allowsConcurrentExecutionSubject` 的存在,不过它们确实在 `RACCommand` 中非常重要,这里只是为了减少不必要的干扰因素。 + +## RACCommand 简介 + +与前面几篇文章中介绍的 `RACSignal` 等元素不同,`RACCommand` 并不表示数据流,它只是一个继承自 `NSObject` 的类,但是它却可以用来创建和订阅用于响应某些事件的信号。 + +```objectivec +@interface RACCommand<__contravariant InputType, __covariant ValueType> : NSObject + +@end +``` + +它本身并不是一个 `RACStream` 或者 `RACSignal` 的子类,而是一个用于管理 `RACSignal` 的创建与订阅的类。 + +在 ReactiveCocoa 中的 FrameworkOverview 部分对 `RACCommand` 有这样的解释: + +> A command, represented by the RACCommand class, creates and subscribes to a signal in response to some action. This makes it easy to perform side-effecting work as the user interacts with the app. + +在用于与 UIKit 组件进行交互或者执行包含副作用的操作时,`RACCommand` 能够帮助我们更快的处理并且响应任务,减少编码以及工程的复杂度。 + +## RACCommand 的初始化与执行 + +在 `-initWithSignalBlock:` 方法的方法签名上,你可以看到在每次 `RACCommand` 初始化时都会传入一个类型为 `RACSignal<ValueType> * (^)(InputType _Nullable input)` 的 `signalBlock`: + +```objectivec +- (instancetype)initWithSignalBlock:(RACSignal<ValueType> * (^)(InputType _Nullable input))signalBlock; +``` + +输入为 `InputType` 返回值为 `RACSignal<ValueType> *`,而 `InputType` 也就是在调用 `-execute:` 方法时传入的对象: + +```objectivec +- (RACSignal<ValueType> *)execute:(nullable InputType)input; +``` + +这也就是 `RACCommand` 将外部变量(或『副作用』)传入 ReactiveCocoa 内部的方法,你可以理解为 `RACCommand` 将外部的变量 `InputType` 转换成了使用 `RACSignal` 包裹的 `ValueType` 对象。 + +![Execute-For-RACCommand](images/RACCommand/Execute-For-RACCommand.png) + +我们以下面的代码为例,先来看一下 `RACCommand` 是如何工作的: + +```objectivec +RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSNumber * _Nullable input) { + return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + NSInteger integer = [input integerValue]; + for (NSInteger i = 0; i < integer; i++) { + [subscriber sendNext:@(i)]; + } + [subscriber sendCompleted]; + return nil; + }]; +}]; +[[command.executionSignals switchToLatest] subscribeNext:^(id _Nullable x) { + NSLog(@"%@", x); +}]; + +[command execute:@1]; +[RACScheduler.mainThreadScheduler afterDelay:0.1 + schedule:^{ + [command execute:@2]; + }]; +[RACScheduler.mainThreadScheduler afterDelay:0.2 + schedule:^{ + [command execute:@3]; + }]; +``` + +首先使用 `-initWithSignalBlock:` 方法创建一个 `RACCommand` 的对象,传入一个类型为 `InputType -> RACSignal<ValueType>` 的 block,这个信号根据输入会发送对应次数的消息,如果运行上面的代码,会打印出: + +```objectivec +0 +0 +1 +0 +1 +2 +``` + +> `-switchToLatest` 方法只能操作**信号的信号**。 + +每次 `executionSignals` 中发送了新的信号时,`switchToLatest` 方法返回的信号都会订阅这个最新的信号,这里也就保证了每次都会打印出最新的信号中的值。 + +![Multiple-Executes](images/RACCommand/Multiple-Executes.png) + +在上面代码中还有最后一个问题需要回答,为什么要使用 `RACScheduler.mainThreadScheduler` 延迟调用之后的 `-execute:` 方法?由于在默认情况下 `RACCommand` 都是不支持并发操作的,需要在上一次命令执行之后才可以发送下一次操作,否则就会返回错误信号 `RACErrorSignal`,这些错误可以通过订阅 `command.errors` 获得。 + +如果使用如下的方式执行几次 `-execute:` 方法: + +```objectivec +[command execute:@1]; +[command execute:@2]; +[command execute:@3]; +``` + +笔者相信,不出意外的话,你只能在控制台中看到输出 `0`。 + +### 最重要的内部『信号』 + +`RACCommand` 中最重要的内部『信号』就是 `addedExecutionSignalsSubject`: + +```objectivec +@property (nonatomic, strong, readonly) RACSubject *addedExecutionSignalsSubject; +``` + +这个 `RACSubject` 对象通过各种操作衍生了几乎所有 `RACCommand` 中的其他信号,我们会在下一节中具体介绍; + +既然 `addedExecutionSignalsSubject` 是一个 `RACSubject`,它不能在创建时预设好对订阅者发送的消息,它会在哪里接受数据并推送给订阅者呢?答案就在 `-execute:` 方法中: + +```objectivec +- (RACSignal *)execute:(id)input { + BOOL enabled = [[self.immediateEnabled first] boolValue]; + if (!enabled) { + NSError *error = [NSError errorWithDomain:RACCommandErrorDomain code:RACCommandErrorNotEnabled userInfo:@{ + NSLocalizedDescriptionKey: NSLocalizedString(@"The command is disabled and cannot be executed", nil), + RACUnderlyingCommandErrorKey: self + }]; + + return [RACSignal error:error]; + } + + RACSignal *signal = self.signalBlock(input); + RACMulticastConnection *connection = [[signal + subscribeOn:RACScheduler.mainThreadScheduler] + multicast:[RACReplaySubject subject]]; + + [self.addedExecutionSignalsSubject sendNext:connection.signal]; + + [connection connect]; + return [connection.signal setNameWithFormat:@"%@ -execute: %@", self, RACDescription(input)]; +} +``` + +在方法中这里你也能看到连续几次执行 `-execute:` 方法不能成功的原因:每次执行这个方法时,都会从另一个信号 `immediateEnabled` 中读取是否能执行当前命令的 `BOOL` 值,如果不可以执行的话,就直接返回 `RACErrorSignal`。 + +![Execute-on-RACCommand](images/RACCommand/Execute-on-RACCommand.png) + +> `-execute:` 方法是唯一一个为 `addedExecutionSignalsSubject` 生产信息的方法。 + +在执行 `signalBlock` 返回一个 `RACSignal` 之后,会将当前信号包装成一个 `RACMulticastConnection`,然后调用 `-sendNext:` 方法发送到 `addedExecutionSignalsSubject` 上,执行 `-connect` 方法订阅原有的信号,最后返回。 + +### 复杂的初始化 + +与简单的 `-execute:` 方法相比,`RACCommand` 的初始化方法就复杂多了,虽然我们在方法中传入了 `signalBlock`,但是 `-initWithEnabled:signalBlock:` 方法只是对这个 block 进行了简单的 `copy`,真正使用这个 block 的还是上一节中的 `-execute:` 方法中。 + +由于 `RACCommand` 在初始化方法中初始化了七个高阶信号,它的实现非常复杂: + +```objectivec +- (instancetype)initWithEnabled:(RACSignal *)enabledSignal signalBlock:(RACSignal<id> * (^)(id input))signalBlock { + self = [super init]; + + _addedExecutionSignalsSubject = [RACSubject new]; + _signalBlock = [signalBlock copy]; + + _executionSignals = ...; + _errors = ...; + RACSignal *immediateExecuting = ...; + _executing = ...; + RACSignal *moreExecutionsAllowed = ...; + _immediateEnabled =...; + _enabled = ...; + + return self; +} +``` + +这一小节并不能完全介绍全部的七个信号的实现,只会介绍其中的 `immediateExecuting` 和 `moreExecutionsAllowed` 两个临时信号,剩下的信号都会在下一节中分析。 + +#### 表示当前有操作执行的信号 + +首先是 `immediateExecuting` 信号: + +```objectivec +RACSignal *immediateExecuting = [[[[self.addedExecutionSignalsSubject + flattenMap:^(RACSignal *signal) { + return [[[signal + catchTo:[RACSignal empty]] + then:^{ + return [RACSignal return:@-1]; + }] + startWith:@1]; + }] + scanWithStart:@0 reduce:^(NSNumber *running, NSNumber *next) { + return @(running.integerValue + next.integerValue); + }] + map:^(NSNumber *count) { + return @(count.integerValue > 0); + }] + startWith:@NO]; +``` + +`immediateExecuting` 是一个用于表示当前是否有任务执行的信号,如果输入的 `addedExecutionSignalsSubject` 等价于以下的信号: + +```objectivec +[RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + [subscriber sendNext:[RACSignal error:[NSError errorWithDomain:@"Error" code:1 userInfo:nil]]]; + [subscriber sendNext:[RACSignal return:@1]]; + [subscriber sendNext:[RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + [RACScheduler.mainThreadScheduler afterDelay:1 + schedule:^ + { + [subscriber sendCompleted]; + }]; + return nil; + }]]; + [subscriber sendNext:[RACSignal return:@3]]; + [subscriber sendCompleted]; + return nil; +}]; +``` + +> 在本文的所有章节中都会假设输入的 `addedExecutionSignalsSubject` 信号跟上面的代码返回的完全相同。 + +那么,最后生成的高阶信号 `immediateExecuting` 如下: + +![immediateExecuting-Signal-in-RACCommand](images/RACCommand/immediateExecuting-Signal-in-RACCommand.png) + +1. `-catchTo:` 将所有的错误转换成 `RACEmptySignal` 信号; +2. `-flattenMap:` 将每一个信号的开始和结束的时间点转换成 `1` 和 `-1` 两个信号; +3. `-scanWithStart:reduce:` 从 `0` 开始累加原有的信号; +4. `-map:` 将大于 `1` 的信号转换为 `@YES`; +5. `-startWith:` 在信号序列最前面加入 `@NO`,表示在最开始时,没有任何动作在执行。 + +`immediateExecuting` 使用几个 `RACSignal` 的操作成功将原有的信号流转换成了表示是否有操作执行的信号流。 + +#### 表示是否允许更多操作执行的信号 + +相比于 `immediateExecuting` 信号的复杂,`moreExecutionsAllowed` 就简单多了: + +```objectivec +RACSignal *moreExecutionsAllowed = [RACSignal + if:[self.allowsConcurrentExecutionSubject startWith:@NO] + then:[RACSignal return:@YES] + else:[immediateExecuting not]]; +``` + +因为文章中不准备介绍与并发执行有关的内容,所以这里的 `then` 语句永远不会执行,既然 `RACCommand` 不支持并行操作,那么这段代码就非常好理解了,当前 `RACCommand` 能否执行操作就是 `immediateExecuting` 取反: + +![MoreExecutionAllowed-Signa](images/RACCommand/MoreExecutionAllowed-Signal.png) + +到这里所有初始化方法中的临时信号就介绍完了,在下一节中会继续介绍初始化方法中的其它高阶信号。 + +## RACCommand 接口中的高阶信号 + +每一个 `RACCommand` 对象中都管理着多个信号,它在接口中暴露出的四个信号是这一节关注的重点: + +![RACCommand-Interface](images/RACCommand/RACCommand-Interface.png) + +这一小节会按照顺序图中从上到下的顺序介绍 `RACCommand` 接口中暴露出来的信号,同时会涉及一些为了生成这些信号的中间产物。 + +### executionSignals + +`executionSignals` 是 `RACCommand` 中最重要的信号;从类型来看,它是一个**包含信号的信号**,在每次执行 `-execute:` 方法时,最终都会向 `executionSignals` 中传入一个最新的信号。 + +虽然它最重要,但是`executionSignals` 是这个几个高阶信号中实现最简单的: + +```objectivec +_executionSignals = [[[self.addedExecutionSignalsSubject + map:^(RACSignal *signal) { + return [signal catchTo:[RACSignal empty]]; + }] + deliverOn:RACScheduler.mainThreadScheduler] + setNameWithFormat:@"%@ -executionSignals", self]; +``` + +它只是将信号中的所有的错误 `NSError` 转换成了 `RACEmptySignal` 对象,并派发到主线程上。 + +![Execution-Signals](images/RACCommand/Execution-Signals.png) + +如果你只订阅了 `executionSignals`,那么其实你不会收到任何的错误,所有的错误都会以 `-sendNext:` 的形式被发送到 `errors` 信号中,这会在后面详细介绍。 + +### executing + +`executing` 是一个表示当前是否有任务执行的信号,这个信号使用了在上一节中介绍的临时变量作为数据源: + +```objectivec +_executing = [[[[[immediateExecuting + deliverOn:RACScheduler.mainThreadScheduler] + startWith:@NO] + distinctUntilChanged] + replayLast] + setNameWithFormat:@"%@ -executing", self]; +``` + +这里对 `immediateExecuting` 的变换还是非常容易理解的: + +![Executing-Signa](images/RACCommand/Executing-Signal.png) + +最后的 `replayLast` 方法将原有的信号变成了容量为 `1` 的 `RACReplaySubject` 对象,这样在每次有订阅者订阅 `executing` 信号时,都只会发送最新的状态,因为订阅者并不关心过去的 `executing` 的值。 + +### enabled + +`enabled` 信号流表示当前的命令是否可以再次被执行,也就是 `-execute:` 方法能否可以成功执行新的任务;该信号流依赖于另一个私有信号 `immediateEnabled`: + +```objectivec +RACSignal *enabledSignal = [RACSignal return:@YES]; + +_immediateEnabled = [[[[RACSignal + combineLatest:@[ enabledSignal, moreExecutionsAllowed ]] + and] + takeUntil:self.rac_willDeallocSignal] + replayLast]; +``` + +虽然这个信号的实现比较简单,不过它同时与三个信号有关,`enabledSignal`、`moreExecutionsAllowed` 以及 `rac_willDeallocSignal`: + +![Immediate-Enabled-Signa](images/RACCommand/Immediate-Enabled-Signal.png) + +虽然图中没有体现出方法 `-takeUntil:self.rac_willDeallocSignal` 的执行,不过你需要知道,这个信号在当前 `RACCommand` 执行 `dealloc` 之后就不会再发出任何消息了。 + +而 `enabled` 信号其实与 `immediateEnabled` 相差无几: + +```objectivec +_enabled = [[[[[self.immediateEnabled + take:1] + concat:[[self.immediateEnabled skip:1] deliverOn:RACScheduler.mainThreadScheduler]] + distinctUntilChanged] + replayLast] + setNameWithFormat:@"%@ -enabled", self]; +``` + +从名字你可以看出来,`immediateEnabled` 在每次原信号发送消息时都会重新计算,而 `enabled` 调用了 `-distinctUntilChanged` 方法,所以如果连续几次值相同就不会再次发送任何消息。 + +除了调用 `-distinctUntilChanged` 的区别之外,你可以看到 `enabled` 信号在最开始调用了 `-take:`和 `-concat:` 方法: + +```objectivec +[[self.immediateEnabled + take:1] + concat:[[self.immediateEnabled skip:1] deliverOn:RACScheduler.mainThreadScheduler]] +``` + +虽然序列并没有任何的变化,但是在这种情况下,`enabled` 信号流中的第一个值会在订阅线程上到达,剩下的所有的值都会在主线程上派发;如果你知道,在一般情况下,我们都会使用 `enabled` 信号来控制 UI 的改变(例如 `UIButton`),相信你就会明白这么做的理由了。 + +### errors + +错误信号是 `RACCommand` 中比较简单的信号;为了保证 `RACCommand` 对此执行 `-execute:` 方法也可以继续运行,我们只能将所有的错误以其它的形式发送到 `errors` 信号中,防止向 `executionSignals` 发送错误信号后,`executionSignals` 信号就会中止的问题。 + +我们使用如下的方式创建 `errors` 信号: + +```objectivec +RACMulticastConnection *errorsConnection = [[[self.addedExecutionSignalsSubject + flattenMap:^(RACSignal *signal) { + return [[signal + ignoreValues] + catch:^(NSError *error) { + return [RACSignal return:error]; + }]; + }] + deliverOn:RACScheduler.mainThreadScheduler] + publish]; + +_errors = [errorsConnection.signal setNameWithFormat:@"%@ -errors", self]; +[errorsConnection connect]; +``` + +信号的创建过程是把所有的错误消息重新打包成 `RACErrorSignal` 并在主线程上进行派发: + +![Errors-Signals](images/RACCommand/Errors-Signals.png) + +使用者只需要调用 `-subscribeNext:` 就可以从这个信号中获取所有执行过程中发生的错误。 + +## RACCommand 的使用 + +`RACCommand` 非常适合封装网络请求,我们可以使用下面的代码封装一个网络请求: + +```objectivec +RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id _Nullable input) { + return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + NSURL *url = [NSURL URLWithString:@"http://localhost:3000"]; + AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url]; + NSString *URLString = [NSString stringWithFormat:@"/api/products/%@", input ?: @1]; + NSURLSessionDataTask *task = [manager GET:URLString parameters:nil progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + [subscriber sendNext:responseObject]; + [subscriber sendCompleted]; + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + [subscriber sendError:error]; + }]; + return [RACDisposable disposableWithBlock:^{ + [task cancel]; + }]; + }]; +}]; +``` + +上面的 `RACCommand` 对象可以通过 `-execute:` 方法执行,同时,订阅 `executionSignals` 以及 `errors` 来获取网络请求的结果。 + +```objectivec +[[command.executionSignals switchToLatest] subscribeNext:^(id _Nullable x) { + NSLog(@"%@", x); +}]; +[command.errors subscribeNext:^(NSError * _Nullable x) { + NSLog(@"%@", x); +}]; +[command execute:@1]; +``` + +向方法 `-execute:` 中传入了 `@1` 对象,从服务器中获取了 `id = 1` 的商品对象;当然,我们也可以传入不同的 `id` 来获取不同的模型,所有的网络请求以及 JSON 转换模型的逻辑都可以封装到这个 `RACCommand` 的 block 中,外界只是传入一个 `id`,最后就从 `executionSignals` 信号中获取了开箱即用的对象。 + +## 总结 + +使用 `RACCommand` 能够优雅地将包含副作用的操作和与副作用无关的操作分隔起来;整个 `RACCommand` 相当于一个黑箱,从 `-execute:` 方法中获得输入,最后以向信号发送消息的方式,向订阅者推送结果。 + +![RACCommand-Side-Effect](images/RACCommand/RACCommand-Side-Effect.png) + +这种执行任务的方式就像是一个函数,根据输入的不同,有着不同的输出,非常适合与 UI、网络操作的相关的任务,这也是 `RACCommand` 的设计的优雅之处。 + +## References + ++ [ReactiveCocoa Essentials: Understanding and Using RACCommand](http://codeblog.shape.dk/blog/2013/12/05/reactivecocoa-essentials-understanding-and-using-raccommand/) ++ [ReactiveCocoa 中 RACCommand 底层实现分析](https://halfrost.com/reactivecocoa_raccommand/) + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/raccommand + + diff --git a/contents/ReactiveObjC/RACDelegateProxy.md b/contents/ReactiveObjC/RACDelegateProxy.md new file mode 100644 index 0000000..df90970 --- /dev/null +++ b/contents/ReactiveObjC/RACDelegateProxy.md @@ -0,0 +1,432 @@ +# 从代理到 RACSignal + +ReactiveCocoa 将 Cocoa 中的 Target-Action、KVO、通知中心以及代理等设计模式都桥接到了 RAC 的世界中,我们在随后的几篇文章中会介绍 RAC 如何做到了上面的这些事情,而本篇文章会介绍 ReactiveCocoa 是如何把**代理**转换为信号的。 + +![Delegate-To-RACSigna](images/RACDelegateProxy/Delegate-To-RACSignal.png) + +## RACDelegateProxy + +从代理转换成信号所需要的核心类就是 `RACDelegateProxy`,这是一个设计的非常巧妙的类;虽然在类的头文件中,它被标记为私有类,但是我们仍然可以使用 `-initWithProtocol:` 方法直接初始化该类的实例。 + +```objectivec +- (instancetype)initWithProtocol:(Protocol *)protocol { + self = [super init]; + class_addProtocol(self.class, protocol); + _protocol = protocol; + return self; +} +``` + +从初始化方法中,我们可以看出 `RACDelegateProxy` 是一个包含实例变量 `_protocol` 的类: + +![RACDelegateProxy](images/RACDelegateProxy/RACDelegateProxy.png) + +在整个 `RACDelegateProxy` 类的实现中,你都不太能看出与这个实例变量 `_protocol` 的关系;稍微对 iOS 有了解的人可能都知道,在 Cocoa 中有一个非常特别的根类 `NSProxy`,而从它的名字我们也可以推断出来,`NSProxy` 一般用于实现代理(主要是对消息进行转发),但是 ReactiveCocoa 中这个 `delegate` 的代理 `RACDelegateProxy` 并没有继承这个 `NSProxy` 根类: + +```objectivec +@interface RACDelegateProxy : NSObject + +@end +``` + +那么 `RACDelegateProxy` 是如何作为 Cocoa 中组件的代理,并为原生组件添加 `RACSignal` 的支持呢?我们以 `UITableView` 为例来展示 `RACDelegateProxy` 是如何与 UIKit 组件互动的,我们需要实现的是以下功能: + +![RACDelegateProxy-UITableVie](images/RACDelegateProxy/RACDelegateProxy-UITableView.gif) + +在点击所有的 `UITableViewCell` 时都会自动取消点击状态,通常情况下,我们可以直接在代理方法 `-tableView:didSelectRowAtIndexPath:` 中执行 `-deselectRowAtIndexPath:animated:` 方法: + +```objectivec +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { + [tableView deselectRowAtIndexPath:indexPath animated:YES]; +} +``` + +使用信号的话相比而言就比较麻烦了: + +```objectivec +RACDelegateProxy *proxy = [[RACDelegateProxy alloc] initWithProtocol:@protocol(UITableViewDelegate)]; +objc_setAssociatedObject(self, _cmd, proxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +proxy.rac_proxiedDelegate = self; +[[proxy rac_signalForSelector:@selector(tableView:didSelectRowAtIndexPath:)] + subscribeNext:^(RACTuple *value) { + [value.first deselectRowAtIndexPath:value.second animated:YES]; + }]; +self.tableView.delegate = (id<UITableViewDelegate>)proxy; +``` + +1. 初始化 `RACDelegateProxy` 实例,传入 `UITableViewDelegate` 协议,并将实例存入视图控制器以**确保实例不会被意外释放**造成崩溃; +2. 设置代理的 `rac_proxiedDelegate` 属性为视图控制器; +3. 使用 `-rac_signalForSelector:` 方法生成一个 `RACSignal`,在 `-tableView:didSelectRowAtIndexPath:` 方法调用时将方法的参数打包成 `RACTuple` 向信号中发送新的 `next` 消息; +4. 重新设置 `UITableView` 的代理; + +在 `UITableViewDelgate` 中的代理方法执行时,实际上会被 `RACDelegateProxy` 拦截,并根据情况决定是处理还是转发: + +![UITableViewDelegate-With-RACDelegateProxy](images/RACDelegateProxy/UITableViewDelegate-With-RACDelegateProxy.png) + +如果 `RACDelegateProxy` 实现了该代理方法就会交给它处理,如:`-tableView:didSelectRowAtIndexPath:`;否则,当前方法就会被转发到原 `delegate` 上,在这里就是 `UIViewController` 对象。 + +`RACDelegateProxy` 中有两个值得特别注意的问题,一是 `RACDelegateProxy` 是如何进行消息转发的,有事如何将自己无法实现的消息交由原代理处理,第二是 `RACDelegateProxy` 如何通过方法 `-rac_signalForSelector:` 在原方法调用时以 `RACTuple` 的方式发送到 `RACSignal` 上。 + +## 消息转发的实现 + +首先,我们来看 `RACDelegateProxy` 是如何在无法响应方法时,将方法转发给原有的代理的;`RACDelegateProxy` 通过覆写几个方法来实现,最关键的就是 `-forwardInvocation:` 方法: + +```objectivec +- (void)forwardInvocation:(NSInvocation *)invocation { + [invocation invokeWithTarget:self.rac_proxiedDelegate]; +} +``` + +当然,作为消息转发流程的一部分 `-methodSignatureForSelector:` 方法也需要在 `RACDelegateProxy` 对象中实现: + +```objectivec +- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { + struct objc_method_description methodDescription = protocol_getMethodDescription(_protocol, selector, NO, YES); + if (methodDescription.name == NULL) { + methodDescription = protocol_getMethodDescription(_protocol, selector, YES, YES); + if (methodDescription.name == NULL) return [super methodSignatureForSelector:selector]; + } + return [NSMethodSignature signatureWithObjCTypes:methodDescription.types]; +} +``` + +我们会从协议的方法中尝试获取其中的可选方法和必须实现的方法,最终获取方法的签名 `NSMethodSignature` 对象。 + +整个方法决议和消息转发的过程如下图所示,在整个方法决议和消息转发的过程中 Objective-C 运行时会再次提供执行该方法的机会。 + +![Message-Forwarding](images/RACDelegateProxy/Message-Forwarding.png) + +例子中的代理方法最后也被 `-forwardInvocation:` 方法成功的转发到了 `UITableView` 的原代理上。 + +## 从代理到信号 + +在 `RACDelegateProxy` 中的另一个非常神奇的方法就是将某一个代理方法转换成信号的 `-signalForSelector:`: + +```objectivec +- (RACSignal *)signalForSelector:(SEL)selector { + return [self rac_signalForSelector:selector fromProtocol:_protocol]; +} + +- (RACSignal *)rac_signalForSelector:(SEL)selector fromProtocol:(Protocol *)protocol { + return NSObjectRACSignalForSelector(self, selector, protocol); +} +``` + +该方法会在传入的协议方法被调用时,将协议方法中的所有参数以 `RACTuple` 的形式发送到返回的信号上,使用者可以通过订阅这个信号来获取所有的参数;而方法 `NSObjectRACSignalForSelector` 的实现还是比较复杂的。 + +```objectivec +static RACSignal *NSObjectRACSignalForSelector(NSObject *self, SEL selector, Protocol *protocol) { + SEL aliasSelector = RACAliasForSelector(selector); + + RACSubject *subject = objc_getAssociatedObject(self, aliasSelector); + if (subject != nil) return subject; + + Class class = RACSwizzleClass(self); + subject = [RACSubject subject]; + objc_setAssociatedObject(self, aliasSelector, subject, OBJC_ASSOCIATION_RETAIN); + + Method targetMethod = class_getInstanceMethod(class, selector); + if (targetMethod == NULL) { + const char *typeEncoding; + if (protocol == NULL) { + typeEncoding = RACSignatureForUndefinedSelector(selector); + } else { + struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + if (methodDescription.name == NULL) { + methodDescription = protocol_getMethodDescription(protocol, selector, YES, YES); + } + typeEncoding = methodDescription.types; + } + class_addMethod(class, selector, _objc_msgForward, typeEncoding); + } else if (method_getImplementation(targetMethod) != _objc_msgForward) { + const char *typeEncoding = method_getTypeEncoding(targetMethod); + + class_addMethod(class, aliasSelector, method_getImplementation(targetMethod), typeEncoding); + class_replaceMethod(class, selector, _objc_msgForward, method_getTypeEncoding(targetMethod)); + } + return subject; +} +``` + +这个 C 函数总共做了两件非常重要的事情,第一个是将传入的选择子对应的实现变为 `_objc_msgForward`,也就是在调用该方法时,会直接进入消息转发流程,第二是用 `RACSwizzleClass` 调剂当前类的一些方法。 + +![NSObjectRACSignalForSelecto](images/RACDelegateProxy/NSObjectRACSignalForSelector.png) + +### 从 selector 到 _objc_msgForward + +我们具体看一下这部分代码是如何实现的,在修改选择子对应的实现之前,我们会先做一些准备工作: + +```objectivec +SEL aliasSelector = RACAliasForSelector(selector); + +RACSubject *subject = objc_getAssociatedObject(self, aliasSelector); +if (subject != nil) return subject; + +Class class = RACSwizzleClass(self); + +subject = [RACSubject subject]; +objc_setAssociatedObject(self, aliasSelector, subject, OBJC_ASSOCIATION_RETAIN); + +Method targetMethod = class_getInstanceMethod(class, selector); +``` + +1. 获取选择子的别名,在这里我们通过为选择子加前缀 `rac_alias_` 来实现; +2. 尝试以 `rac_alias_selector` 为键获取一个热信号 `RACSubject`; +3. 使用 `RACSwizzleClass` 调剂当前类的一些方法(我们会在下一节中介绍); +4. 从当前类中获取目标方法的结构体 `targetMethod`; + +在进行了以上的准备工作之后,我们就开始修改选择子对应的实现了,整个的修改过程会分为三种情况: + +![Swizzle-objc_msgForward](images/RACDelegateProxy/Swizzle-objc_msgForward.png) + +下面会按照这三种情况依次介绍在不同情况下,如何将对应选择子的实现改为 `_objc_msgForward` 完成消息转发的。 + +#### targetMethod == NULL && protocol == NULL + +在找不到选择子对应的方法并且没有传入协议时,这时执行的代码最为简单: + +```objectivec +typeEncoding = RACSignatureForUndefinedSelector(selector); +class_addMethod(class, selector, _objc_msgForward, typeEncoding); +``` + +我们会通过 `RACSignatureForUndefinedSelector` 生成一个当前方法默认的类型编码。 + +> 对类型编码不了解的可以阅读苹果的官方文档 [Type Encodings · Apple Developer](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html),其中详细解释了类型编码是什么,它在整个 Objective-C 运行时有什么作用。 + +```objectivec +static const char *RACSignatureForUndefinedSelector(SEL selector) { + const char *name = sel_getName(selector); + NSMutableString *signature = [NSMutableString stringWithString:@"v@:"]; + + while ((name = strchr(name, ':')) != NULL) { + [signature appendString:@"@"]; + name++; + } + + return signature.UTF8String; +} +``` + +该方法在生成类型编码时,会按照 `:` 的个数来为 `v@:` 这个类型编码添加 `@` 字符;简单说明一下它的意思,ReactiveCocoa 默认所有的方法的返回值类型都为空 `void`,都会传入 `self` 以及当前方法的选择子 `SEL`,它们的类型编码可以在下图中找到,分别是 `v@:`;而 `@` 代表 `id` 类型,也就是我们默认代理方法中的所有参数都是 `NSObject` 类型的。 + +![TypeEncoding](images/RACDelegateProxy/TypeEncoding.png) + +生成了类型编码之后,由于我们并没有在当前类中找到该选择子对应的方法,所以会使用 `class_addMethod` 为当前类提供一个方法的实现,直接将当前选择子的实现改为 `_objc_msgForward`。 + +![Selector-To-ObjC-Message-Forward](images/RACDelegateProxy/Selector-To-ObjC-Message-Forward.png) + +#### targetMethod == NULL && protocol != NULL + +当类中不存在当前选择子对应的方法 `targetMethod`,但是向当前函数中传入了协议时,我们会尝试从协议中获取方法描述: + +```objectivec +struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES); + +if (methodDescription.name == NULL) { + methodDescription = protocol_getMethodDescription(protocol, selector, YES, YES); +} +typeEncoding = methodDescription.types; +class_addMethod(class, selector, _objc_msgForward, typeEncoding); +``` + +这里会使用 `protocol_getMethodDescription` 两次从协议中获取可选和必须实现的方法的描述,并从结构体中拿出类型编码,最后为类添加这个之前不存在的方法: + +![Selector-To-ObjC-Message-Forward](images/RACDelegateProxy/Selector-To-ObjC-Message-Forward.png) + +在这种情况下,其最后的结果与上一种的完全相同,因为它们都是对不存在该方法,只需要获得方法的类型编码并将实现添加为 `_objc_msgForward`,交给消息转发流程进行处理即可。 + +#### targetMethod != NULL + +在目标方法的实现不为空并且它的实现并不是 `_objc_msgForward` 时,我们就会进入以下流程修改原有方法的实现: + +```objectivec +const char *typeEncoding = method_getTypeEncoding(targetMethod); + +class_addMethod(class, aliasSelector, method_getImplementation(targetMethod), typeEncoding); +class_replaceMethod(class, selector, _objc_msgForward, method_getTypeEncoding(targetMethod)); +``` + +同样,我们需要获得目标方法的方法签名、添加 `aliasSelector` 这个新方法,最后在修改原方法的实现到 `_objc_msgForward`。 + +![Selector-To-ObjC-Message-Forward-With-RACSelecto](images/RACDelegateProxy/Selector-To-ObjC-Message-Forward-With-RACSelector.png) + +上图展示了在目标方法不为空并且其实现不为 `_objc_msgForward` 时,`NSObjectRACSignalForSelector` 是如何修改原方法实现的。 + +### 调剂类的方法 + +`NSObjectRACSignalForSelector` 在修改原选择子方法实现的之前就已经修改了当前类很多方法的实现: + ++ `-methodSignatureForSelector:` ++ `-class` ++ `-respondsToSelector` ++ `-forwardInvocation:` + +整个调剂方法的过程 `RACSwizzleClass` 还是比较复杂的,我们可以分三部分看下面的代码: + +```objectivec +static Class RACSwizzleClass(NSObject *self) { + Class statedClass = self.class; + Class baseClass = object_getClass(self); + + NSString *className = NSStringFromClass(baseClass); + const char *subclassName = [className stringByAppendingString:RACSubclassSuffix].UTF8String; + Class subclass = objc_getClass(subclassName); + + if (subclass == nil) { + subclass = objc_allocateClassPair(baseClass, subclassName, 0); + if (subclass == nil) return nil; + + RACSwizzleForwardInvocation(subclass); + RACSwizzleRespondsToSelector(subclass); + RACSwizzleGetClass(subclass, statedClass); + RACSwizzleGetClass(object_getClass(subclass), statedClass); + RACSwizzleMethodSignatureForSelector(subclass); + + objc_registerClassPair(subclass); + } + object_setClass(self, subclass); + return subclass; +} +``` + +1. 从当前类 `RACDelegateProxy` 衍生出一个子类 `RACDelegateProxy_RACSelectorSignal`; +2. 调用各种 `RACSwizzleXXX` 方法修改当前子类的一些表现; +3. 将 `RACDelegateProxy` 对象的类设置成自己,这样就会在查找方法时,找到 `RACDelegateProxy_RACSelectorSignal` 中的实现; + +在修改的几个方法中最重要的就是 `-forwardInvocation:`: + +```objectivec +static void RACSwizzleForwardInvocation(Class class) { + SEL forwardInvocationSEL = @selector(forwardInvocation:); + Method forwardInvocationMethod = class_getInstanceMethod(class, forwardInvocationSEL); + + void (*originalForwardInvocation)(id, SEL, NSInvocation *) = NULL; + if (forwardInvocationMethod != NULL) { + originalForwardInvocation = (__typeof__(originalForwardInvocation))method_getImplementation(forwardInvocationMethod); + } + + id newForwardInvocation = ^(id self, NSInvocation *invocation) { + BOOL matched = RACForwardInvocation(self, invocation); + if (matched) return; + + if (originalForwardInvocation == NULL) { + [self doesNotRecognizeSelector:invocation.selector]; + } else { + originalForwardInvocation(self, forwardInvocationSEL, invocation); + } + }; + + class_replaceMethod(class, forwardInvocationSEL, imp_implementationWithBlock(newForwardInvocation), "v@:@"); +} +``` + +这个方法中大部分的内容都是平淡无奇的,在新的 `-forwardInvocation:` 方法中,执行的 `RACForwardInvocation` 是实现整个消息转发的关键内容: + +```objectivec +static BOOL RACForwardInvocation(id self, NSInvocation *invocation) { + SEL aliasSelector = RACAliasForSelector(invocation.selector); + RACSubject *subject = objc_getAssociatedObject(self, aliasSelector); + + Class class = object_getClass(invocation.target); + BOOL respondsToAlias = [class instancesRespondToSelector:aliasSelector]; + if (respondsToAlias) { + invocation.selector = aliasSelector; + [invocation invoke]; + } + + if (subject == nil) return respondsToAlias; + + [subject sendNext:invocation.rac_argumentsTuple]; + return YES; +} +``` + +在 `-rac_signalForSelector:` 方法返回的 `RACSignal` 上接收到的参数信号,就是从这个方法发送过去的,新的实现 `RACForwardInvocation` 改变了原有的 `selector` 到 `aliasSelector`,然后使用 `-invoke` 完成该调用,而所有的参数会以 `RACTuple` 的方式发送到信号上。 + +像其他的方法 `-respondToSelector:` 等等,它们的实现就没有这么复杂并且重要了: + +```objectivec +id newRespondsToSelector = ^ BOOL (id self, SEL selector) { + Method method = rac_getImmediateInstanceMethod(class, selector); + + if (method != NULL && method_getImplementation(method) == _objc_msgForward) { + SEL aliasSelector = RACAliasForSelector(selector); + if (objc_getAssociatedObject(self, aliasSelector) != nil) return YES; + } + + return originalRespondsToSelector(self, respondsToSelectorSEL, selector); +}; +``` + +`rac_getImmediateInstanceMethod` 从当前类获得方法的列表,并从中找到与当前 `selector` 同名的方法 `aliasSelector`,然后根据不同情况判断方法是否存在。 + +对 `class` 的修改,是为了让对象对自己的身份『说谎』,因为我们子类化了 `RACDelegateProxy`,并且重新设置了对象的类,将所有的方法都转发到了这个子类上,如果不修改 `class` 方法,那么当开发者使用它自省时就会得到错误的类,而这是我们不希望看到的。 + +```objectivec +static void RACSwizzleGetClass(Class class, Class statedClass) { + SEL selector = @selector(class); + Method method = class_getInstanceMethod(class, selector); + IMP newIMP = imp_implementationWithBlock(^(id self) { + return statedClass; + }); + class_replaceMethod(class, selector, newIMP, method_getTypeEncoding(method)); +} +``` + +在最后我们会对获得方法签名的 `-methodSignatureForSelector:` 方法进行修改: + +```objectivec +IMP newIMP = imp_implementationWithBlock(^(id self, SEL selector) { + Class actualClass = object_getClass(self); + Method method = class_getInstanceMethod(actualClass, selector); + if (method == NULL) { + struct objc_super target = { + .super_class = class_getSuperclass(class), + .receiver = self, + }; + NSMethodSignature * (*messageSend)(struct objc_super *, SEL, SEL) = (__typeof__(messageSend))objc_msgSendSuper; + return messageSend(&target, @selector(methodSignatureForSelector:), selector); + } + + char const *encoding = method_getTypeEncoding(method); + return [NSMethodSignature signatureWithObjCTypes:encoding]; +}); +``` + +在方法不存在时,通过 `objc_msgSendSuper` 调用父类的 `-methodSignatureForSelector:` 方法获取方法签名。 + +## 方法调用的过程 + +在一般情况下,Objective-C 中某一消息被发送到一个对象时,它会先获取当前对象对应的类,然后从类的选择子表查找该方法对应的实现并执行。 + +![Selector-To-IMP](images/RACDelegateProxy/Selector-To-IMP.png) + +与正常的方法实现查找以及执行过程的简单不同,如果我们对某一个方法调用了 `-rac_signalForSelector:` 方法,那么对于同一个对象对应的类的所有方法,它们的执行过程会变得非常复杂: + +![After-Call-RACSignalForSelecto](images/RACDelegateProxy/After-Call-RACSignalForSelector.png) + +1. 由于当前对象对应的类已经被改成了 `Subclass`,即 `Class_RACSelectorSignal`,所以会在子类中查找方法的实现; +2. 方法对应的实现已经被改成了 `-forwardInvocation:`,会直接进入消息转发流程中处理; +3. 根据传入的选择子获取同名选择子 `rac_alias_selector`; +4. 拿到当前 `NSInvocation` 对象中 `target` 的类,判断是否可以响应该选择子; +5. 将 `NSInvocation` 对象中的选择子改为 `rac_alias_selector` 并执行其实现; +6. 从 `NSInvocation` 对象中获取参数并打包成 `RACTuple`,以 `next` 消息的形式发送到持有的 `RACSubject` 热信号上; + +这时所有的订阅者才会在该方法被调用时收到消息,完成相应的任务。 + +## 总结 + +ReactiveCocoa 使用了一种非常神奇的办法把原有的代理模式成功的桥接到 `RACSignal` 的世界中,并为我们提供了 `RACDelegateProxy` 这一接口,能够帮助我们以信号的形式监听所有的代理方法,可以用 block 的形式去代替原有的方法,为我们减少一些工作量。 + +## References + ++ [Type Encodings · Apple Developer](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html) + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/racdelegateproxy + + diff --git a/contents/ReactiveObjC/RACMulticastConnection.md b/contents/ReactiveObjC/RACMulticastConnection.md new file mode 100644 index 0000000..c86a6af --- /dev/null +++ b/contents/ReactiveObjC/RACMulticastConnection.md @@ -0,0 +1,289 @@ +# 用于多播的 RACMulticastConnection + +ReactiveCocoa 中的信号信号在默认情况下都是冷的,每次有新的订阅者订阅信号时都会执行信号创建时传入的 block;这意味着对于任意一个订阅者,所需要的数据都会**重新计算**,这在大多数情况下都是开发者想看到的情况,但是这在信号中的 block 有副作用或者较为昂贵时就会有很多问题。 + +![RACMulticastConnection](images/RACMulticastConnection/RACMulticastConnection.png) + +我们希望有一种模型能够将冷信号转变成热信号,并在合适的时间触发,向所有的订阅者发送消息;而今天要介绍的 `RACMulticastConnection` 就是用于解决上述问题的。 + +## RACMulticastConnection 简介 + +`RACMulticastConnection` 封装了将一个信号的订阅分享给多个订阅者的思想,它的每一个对象都持有两个 `RACSignal`: + +![RACMulticastConnection-Interface](images/RACMulticastConnection/RACMulticastConnection-Interface.png) + +一个是私有的源信号 `sourceSignal`,另一个是用于广播的信号 `signal`,其实是一个 `RACSubject` 对象,不过对外只提供 `RACSignal` 接口,用于使用者通过 `-subscribeNext:` 等方法进行订阅。 + +## RACMulticastConnection 的初始化 + +`RACMulticastConnection` 有一个非常简单的初始化方法 `-initWithSourceSignal:subject:`,不过这个初始化方法是私有的: + +```objectivec +- (instancetype)initWithSourceSignal:(RACSignal *)source subject:(RACSubject *)subject { + self = [super init]; + + _sourceSignal = source; + _serialDisposable = [[RACSerialDisposable alloc] init]; + _signal = subject; + + return self; +} +``` + +在 `RACMulticastConnection` 的头文件的注释中,对它的初始化有这样的说明: + +> Note that you shouldn't create RACMulticastConnection manually. Instead use -[RACSignal publish] or -[RACSignal multicast:]. + +我们不应该直接使用 `-initWithSourceSignal:subject:` 来初始化一个对象,我们应该通过 `RACSignal` 的实例方法初始化 `RACMulticastConnection` 实例。 + +```objectivec +- (RACMulticastConnection *)publish { + RACSubject *subject = [RACSubject subject]; + RACMulticastConnection *connection = [self multicast:subject]; + return connection; +} + +- (RACMulticastConnection *)multicast:(RACSubject *)subject { + RACMulticastConnection *connection = [[RACMulticastConnection alloc] initWithSourceSignal:self subject:subject]; + return connection; +} +``` + +这两个方法 `-publish` 和 `-multicast:` 都是对初始化方法的封装,并且都会返回一个 `RACMulticastConnection` 对象,传入的 `sourceSignal` 就是当前信号,`subject` 就是用于对外广播的 `RACSubject` 对象。 + +## RACSignal 和 RACMulticastConnection + +网络请求在客户端其实是一个非常昂贵的操作,也算是多级缓存中最慢的一级,在使用 ReactiveCocoa 处理业务需求中经常会遇到下面的情况: + +```objectivec +RACSignal *requestSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + NSLog(@"Send Request"); + NSURL *url = [NSURL URLWithString:@"http://localhost:3000"]; + AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url]; + NSString *URLString = [NSString stringWithFormat:@"/api/products/1"]; + NSURLSessionDataTask *task = [manager GET:URLString parameters:nil progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + [subscriber sendNext:responseObject]; + [subscriber sendCompleted]; + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + [subscriber sendError:error]; + }]; + return [RACDisposable disposableWithBlock:^{ + [task cancel]; + }]; +}]; + +[requestSignal subscribeNext:^(id _Nullable x) { + NSLog(@"product: %@", x); +}]; + +[requestSignal subscribeNext:^(id _Nullable x) { + NSNumber *productId = [x objectForKey:@"id"]; + NSLog(@"productId: %@", productId); +}]; +``` + +通过订阅发出网络请求的信号经常会被多次订阅,以满足不同 UI 组件更新的需求,但是以上代码却有非常严重的问题。 + +![RACSignal-And-Subscribe](images/RACMulticastConnection/RACSignal-And-Subscribe.png) + +每一次在 `RACSignal` 上执行 `-subscribeNext:` 以及类似方法时,都会发起一次新的网络请求,我们希望避免这种情况的发生。 + +为了解决上述问题,我们使用了 `-publish` 方法获得一个多播对象 `RACMulticastConnection`,更改后的代码如下: + +```objectivec +RACMulticastConnection *connection = [[RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + NSLog(@"Send Request"); + ... +}] publish]; + +[connection.signal subscribeNext:^(id _Nullable x) { + NSLog(@"product: %@", x); +}]; +[connection.signal subscribeNext:^(id _Nullable x) { + NSNumber *productId = [x objectForKey:@"id"]; + NSLog(@"productId: %@", productId); +}]; + +[connection connect]; +``` + +在这个例子中,我们使用 `-publish` 方法生成实例,订阅者不再订阅源信号,而是订阅 `RACMulticastConnection` 中的 `RACSubject` 热信号,最后通过 `-connect` 方法触发源信号中的任务。 + +![RACSignal-RACMulticastConnection-Connect](images/RACMulticastConnection/RACSignal-RACMulticastConnection-Connect.png) + +> 对于热信号不了解的读者,可以阅读这篇文章 [『可变』的热信号 RACSubject](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/ReactiveObjC/RACSubject.md)。 + +### publish 和 multicast 方法 + +我们再来看一下 `-publish` 和 `-multicast:` 这两个方法的实现: + +```objectivec +- (RACMulticastConnection *)publish { + RACSubject *subject = [RACSubject subject]; + RACMulticastConnection *connection = [self multicast:subject]; + return connection; +} + +- (RACMulticastConnection *)multicast:(RACSubject *)subject { + RACMulticastConnection *connection = [[RACMulticastConnection alloc] initWithSourceSignal:self subject:subject]; + return connection; +} +``` + +当 `-publish` 方法调用时相当于向 `-multicast:` 传入了 `RACSubject`。 + +![publish-and-multicast](images/RACMulticastConnection/publish-and-multicast.png) + +`-publish` 只是对 `-multicast:` 方法的简单封装,它们都是通过 `RACMulticastConnection` 私有的初始化方法 `-initWithSourceSignal:subject:` 创建一个新的实例。 + +在使用 `-multicast:` 方法时,传入的信号其实就是用于广播的信号;这个信号必须是一个 `RACSubject` 本身或者它的子类: + +![RACSubject - Subclasses](images/RACMulticastConnection/RACSubject%20-%20Subclasses.png) + +传入 `-multicast:` 方法的一般都是 `RACSubject` 或者 `RACReplaySubject` 对象。 + +### 订阅源信号的时间点 + +订阅 `connection.signal` 中的数据流时,其实只是向多播对象中的热信号 `RACSubject` 持有的数组中加入订阅者,而这时刚刚创建的 `RACSubject` 中并没有任何的消息。 + +![SubscribeNext-To-RACSubject-Before-Connect](images/RACMulticastConnection/SubscribeNext-To-RACSubject-Before-Connect.png) + +只有在调用 `-connect` 方法之后,`RACSubject` 才会**订阅**源信号 `sourceSignal`。 + +```objectivec +- (RACDisposable *)connect { + self.serialDisposable.disposable = [self.sourceSignal subscribe:_signal]; + return self.serialDisposable; +} +``` + +这时源信号的 `didSubscribe` 代码块才会执行,向 `RACSubject` 推送消息,消息向下继续传递到 `RACSubject` 所有的订阅者中。 + +![Values-From-RACSignal-To-Subscribers](images/RACMulticastConnection/Values-From-RACSignal-To-Subscribers.png) + +`-connect` 方法通过 `-subscribe:` 实际上建立了 `RACSignal` 和 `RACSubject` 之间的连接,这种方式保证了 `RACSignal` 中的 `didSubscribe` 代码块只执行了一次。 + +所有的订阅者不再订阅原信号,而是订阅 `RACMulticastConnection` 持有的热信号 `RACSubject`,实现对冷信号的一对多传播。 + +在 `RACMulticastConnection` 中还有另一个用于连接 `RACSignal` 和 `RACSubject` 信号的 `-autoconnect` 方法: + +```objectivec +- (RACSignal *)autoconnect { + __block volatile int32_t subscriberCount = 0; + return [RACSignal + createSignal:^(id<RACSubscriber> subscriber) { + OSAtomicIncrement32Barrier(&subscriberCount); + RACDisposable *subscriptionDisposable = [self.signal subscribe:subscriber]; + RACDisposable *connectionDisposable = [self connect]; + + return [RACDisposable disposableWithBlock:^{ + [subscriptionDisposable dispose]; + if (OSAtomicDecrement32Barrier(&subscriberCount) == 0) { + [connectionDisposable dispose]; + } + }]; + }]; +} +``` + +它保证了在 `-autoconnect` 方法返回的对象被第一次订阅时,就会建立源信号与热信号之间的连接。 + +### 使用 RACReplaySubject 订阅源信号 + +虽然使用 `-publish` 方法已经能够解决大部分问题了,但是在 `-connect` 方法调用之后才订阅的订阅者并不能收到消息。 + +如何才能保存 `didSubscribe` 执行过程中发送的消息,并在 `-connect` 调用之后也可以收到消息?这时,我们就要使用 `-multicast:` 方法和 `RACReplaySubject` 来完成这个需求了。 + +```objectivec +RACSignal *sourceSignal = [RACSignal createSignal:...]; +RACMulticastConnection *connection = [sourceSignal multicast:[RACReplaySubject subject]]; +[connection.signal subscribeNext:^(id _Nullable x) { + NSLog(@"product: %@", x); +}]; +[connection connect]; +[connection.signal subscribeNext:^(id _Nullable x) { + NSNumber *productId = [x objectForKey:@"id"]; + NSLog(@"productId: %@", productId); +}]; +``` + +除了使用上述的代码,也有一个更简单的方式创建包含 `RACReplaySubject` 对象的 `RACMulticastConnection`: + +```objectivec +RACSignal *signal = [[RACSignal createSignal:...] replay]; +[signal subscribeNext:^(id _Nullable x) { + NSLog(@"product: %@", x); +}]; +[signal subscribeNext:^(id _Nullable x) { + NSNumber *productId = [x objectForKey:@"id"]; + NSLog(@"productId: %@", productId); +}]; +``` + +`-replay` 方法和 `-publish` 差不多,只是内部封装的热信号不同,并在方法调用时就连接原信号: + +```objectivec +- (RACSignal *)replay { + RACReplaySubject *subject = [RACReplaySubject subject]; + RACMulticastConnection *connection = [self multicast:subject]; + [connection connect]; + return connection.signal; +} +``` + +除了 `-replay` 方法,`RACSignal` 中还定义了与 `RACMulticastConnection` 中相关的其它 `-replay` 方法: + +```objectivec +- (RACSignal<ValueType> *)replay; +- (RACSignal<ValueType> *)replayLast; +- (RACSignal<ValueType> *)replayLazily; +``` + +三个方法都会在 `RACMulticastConnection` 初始化时传入一个 `RACReplaySubject` 对象,不过却有一点细微的差别: + +![Difference-Between-Replay-Methods](images/RACMulticastConnection/Difference-Between-Replay-Methods.png) + +相比于 `-replay` 方法,`-replayLast` 方法生成的 `RACMulticastConnection` 中热信号的容量为 `1`: + +```objectivec +- (RACSignal *)replayLast { + RACReplaySubject *subject = [RACReplaySubject replaySubjectWithCapacity:1]; + RACMulticastConnection *connection = [self multicast:subject]; + [connection connect]; + return connection.signal; +} +``` + +而 `replayLazily` 会在返回的信号被**第一次订阅**时,才会执行 `-connect` 方法: + +```objectivec +- (RACSignal *)replayLazily { + RACMulticastConnection *connection = [self multicast:[RACReplaySubject subject]]; + return [RACSignal + defer:^{ + [connection connect]; + return connection.signal; + }]; +} +``` + +## 总结 + +`RACMulticastConnection` 在处理冷热信号相互转换时非常好用,在 `RACSignal` 中也提供了很多将原有的冷信号通过 `RACMulticastConnection` 转换成热信号的方法。 + +![RACMulticastConnection](images/RACMulticastConnection/RACMulticastConnection.png) + +在遇到冷信号中的行为有副作用后者非常昂贵时,我们就可以使用这些方法将单播变成多播,提高执行效率,减少副作用。 + +## References + ++ [『可变』的热信号 RACSubject](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/ReactiveObjC/RACSubject.md) ++ [细说 ReactiveCocoa 的冷信号与热信号](http://williamzang.com/blog/2015/08/18/talk-about-reactivecocoas-cold-signal-and-hot-signal/) + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/racconnection + diff --git a/contents/ReactiveObjC/RACScheduler.md b/contents/ReactiveObjC/RACScheduler.md new file mode 100644 index 0000000..d72a26b --- /dev/null +++ b/contents/ReactiveObjC/RACScheduler.md @@ -0,0 +1,287 @@ +# 理解 RACScheduler 的实现 + +`RACScheduler` 是一个线性执行队列,ReactiveCocoa 中的信号可以在 `RACScheduler` 上执行任务、发送结果;它的实现并不复杂,由多个简单的方法和类组成整个 `RACScheduler` 模块,是整个 ReactiveCocoa 中非常易于理解的部分。 + +## RACScheduler 简介 + +`RACScheduler` 作为 ReactiveCocoa 中唯一的用于调度的模块,它包含很多个性化的子类: + +![RACScheduler-Subclasses](images/RACScheduler/RACScheduler-Subclasses.png) + +`RACScheduler` 类的内部只有一个用于追踪标记和 debug 的属性 `name`,头文件和实现文件中的其它内容都是各种各样的方法;我们可以把其中的方法分为两类,一类是用于初始化 `RACScheduler` 实例的初始化方法: + +![RACScheduler-Initializers](images/RACScheduler/RACScheduler-Initializers.png) + +另一类就是用于调度、执行任务的 `+schedule:` 等方法: + +![RACScheduler-Schedule](images/RACScheduler/RACScheduler-Schedule.png) + +在图中都省略了一些参数缺省的方法,以及一些调用其他方法的调度方法或者初始化方法,用以减少我们分析和理解整个 `RACScheduler` 类的难度。 + +在 `RACScheduler` 中,大部分的调度方法都是需要子类覆写,它本身只提供少数的功能,比如递归 block 的执行: + +```objectivec +- (RACDisposable *)scheduleRecursiveBlock:(RACSchedulerRecursiveBlock)recursiveBlock { + RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable]; + [self scheduleRecursiveBlock:[recursiveBlock copy] addingToDisposable:disposable]; + return disposable; +} +``` + +该方法会递归的执行传入的 `recursiveBlock`,使用的方式非常简单: + +```objectivec +[scheduler scheduleRecursiveBlock:^(void (^reschedule)(void)) { + if (needTerminated) return; + + // do something + + reschedule(); +}]; +``` + +如果需要递归就执行方法中的 `reschedule()`,就会再次执行当前的 block;`-scheduleRecursiveBlock:` 中调用的 `-scheduleRecursiveBlock:addingToDisposable:` 实现比较复杂: + +```objectivec +- (void)scheduleRecursiveBlock:(RACSchedulerRecursiveBlock)recursiveBlock addingToDisposable:(RACCompoundDisposable *)disposable { + ... + RACDisposable *schedulingDisposable = [self schedule:^{ + void (^reallyReschedule)(void) = ^{ + [self scheduleRecursiveBlock:recursiveBlock addingToDisposable:disposable]; + }; + + recursiveBlock(^{ + reallyReschedule(); + }); + }]; + ... +} +``` + +> 方法使用了 `NSLock` 保证在并发情况下并不会出现任何问题,不过在这里展示的代码中,我们将它省略了,一并省略的还有 `RACDisposable` 相关的代码,以保证整个方法逻辑的清晰,方法的原实现可以查看这里 [RACScheduler.m#L130-L187](https://github.com/ReactiveCocoa/ReactiveObjC/blob/9164a24abfbb7d6b2280d78f9c9308a9842bfcfe/ReactiveObjC/RACScheduler.m#L130-L187)。 + +在每次执行 `recursiveBlock` 时,都会传入一个 `reallyReschedule` 用于递归执行传入的 block。 + +其他的方法包括 `+schedule:`、`+after:schedule:` 以及 `after:repeatingEvery:withLeeway:schedule:` 方法都需要子类覆写: + +```objectivec +- (RACDisposable *)schedule:(void (^)(void))block; +- (RACDisposable *)after:(NSDate *)date schedule:(void (^)(void))block; +- (RACDisposable *)after:(NSDate *)date repeatingEvery:(NSTimeInterval)interval withLeeway:(NSTimeInterval)leeway schedule:(void (^)(void))block { + NSCAssert(NO, @"%@ must be implemented by subclasses.", NSStringFromSelector(_cmd)); + return nil; +} +``` + +而接下来我们就按照初始化方法的顺序依次介绍 `RACScheduler` 的子类了。 + +### RACImmediateScheduler + +`RACImmediateScheduler` 是一个会立即执行传入的代码块的调度器,我们可以使用 `RACScheduler` 的类方法 `+immediateScheduler` 返回一个它的实例: + +```objectivec ++ (RACScheduler *)immediateScheduler { + static dispatch_once_t onceToken; + static RACScheduler *immediateScheduler; + dispatch_once(&onceToken, ^{ + immediateScheduler = [[RACImmediateScheduler alloc] init]; + }); + return immediateScheduler; +} +``` + +由于 `RACImmediateScheduler` 是一个私有类,全局只能通过该方法返回它的实例,所以整个程序的运行周期内,我们通过『合法』手段只能获得唯一一个单例。 + +作为 `RACScheduler` 的子类,它必须对父类的调度方法进行覆写,不过因为本身的职能原因,`RACImmediateScheduler` 对于父类的覆写还是非常简单的: + +```objectivec +- (RACDisposable *)schedule:(void (^)(void))block { + block(); + return nil; +} + +- (RACDisposable *)after:(NSDate *)date schedule:(void (^)(void))block { + [NSThread sleepUntilDate:date]; + block(); + return nil; +} + +- (RACDisposable *)after:(NSDate *)date repeatingEvery:(NSTimeInterval)interval withLeeway:(NSTimeInterval)leeway schedule:(void (^)(void))block { + NSCAssert(NO, @"+[RACScheduler immediateScheduler] does not support %@.", NSStringFromSelector(_cmd)); + return nil; +} +``` + ++ `+schedule` 方法会立刻执行传入的 block; ++ `+after:schedule:` 方法会将当前线程休眠到指定时间后执行 block; ++ 而对于 `+after:repeatingEvery:withLeeway:schedule:` 方法就干脆不支持。 + +这确实非常符合 `RACImmediateScheduler` 类的名字以及功能,虽然没有要求对递归执行 block 的方法进行覆写,不过它依然做了这件事情: + +```objectivec +- (RACDisposable *)scheduleRecursiveBlock:(RACSchedulerRecursiveBlock)recursiveBlock { + for (__block NSUInteger remaining = 1; remaining > 0; remaining--) { + recursiveBlock(^{ + remaining++; + }); + } + return nil; +} +``` + +实现的过程非常简洁,甚至没有什么值得解释的地方了。 + +### RACTargetQueueScheduler + +`RACTargetQueueScheduler` 继承自 `RACQueueScheduler`,但是由于后者是抽象类,我们并不会直接使用它,它只是为前者提供必要的方法支持,将一部分逻辑抽离出来: + +![RACTargetQueueSchedule](images/RACScheduler/RACTargetQueueScheduler.png) + +这里我们先简单看一下 `RACTargetQueueScheduler` 的实现,整个 `RACTargetQueueScheduler` 类中只有一个初始化方法: + +```objectivec +- (instancetype)initWithName:(NSString *)name targetQueue:(dispatch_queue_t)targetQueue { + dispatch_queue_t queue = dispatch_queue_create(name.UTF8String, DISPATCH_QUEUE_SERIAL); + dispatch_set_target_queue(queue, targetQueue); + return [super initWithName:name queue:queue]; +} +``` + +初始化方法 `-initWithName:targetQueue:` 使用 `dispatch_queue_create` 创建了一个串行队列,然后通过 `dispatch_set_target_queue` 根据传入的 `targetQueue` 设置队列的优先级,最后调用父类的指定构造器完成整个初始化过程。 + +`RACTargetQueueScheduler` 在使用时,将待执行的任务加入一个私有的串行队列中,其优先级与传入的 `targetQueue` 完全相同;不过提到 `RACTargetQueueScheduler` 中队列的优先级,对 GCD 稍有了解的人应该都知道在 GCD 中有着四种不同优先级的全局并行队列,而在 `RACScheduler` 中也有一一对应的枚举类型: + +![RACScheduler-Priority](images/RACScheduler/RACScheduler-Priority.png) + +在使用 `+schedulerWithPriority:` 方法创建 `RACTargetQueueScheduler` 时,就需要传入上面的优先级,方法会通过 GCD 的内置方法 `dispatch_get_global_queue` 获取全局的并行队列,最终返回一个新的实例。 + +```objectivec ++ (RACScheduler *)schedulerWithPriority:(RACSchedulerPriority)priority name:(NSString *)name { + return [[RACTargetQueueScheduler alloc] initWithName:name targetQueue:dispatch_get_global_queue(priority, 0)]; +} +``` + +在 `RACScheduler` 接口中另一个获得主线程调度器的方法 `+mainThreadScheduler`,其实现也是返回一个 `RACTargetQueueScheduler` 对象: + +```objectivec ++ (RACScheduler *)mainThreadScheduler { + static dispatch_once_t onceToken; + static RACScheduler *mainThreadScheduler; + dispatch_once(&onceToken, ^{ + mainThreadScheduler = [[RACTargetQueueScheduler alloc] initWithName:@"org.reactivecocoa.ReactiveObjC.RACScheduler.mainThreadScheduler" targetQueue:dispatch_get_main_queue()]; + }); + + return mainThreadScheduler; +} +``` + +与前者不同的是,后者通过单例模式每次调用时返回一个相同的主线程队列。 + +#### 抽象类 RACQueueScheduler + +在我们对 `RACTargetQueueScheduler` 有一定了解之后,再看它的抽象类就非常简单了;`RACImmediateScheduler` 会立即执行传入的任务,而 `RACQueueScheduler` 其实就是对 GCD 的封装,相信各位读者从它的子类的实现就可以看出来。 + +`RACQueueScheduler` 对三个需要覆写的方法都进行了重写,其实现完全基于 GCD,以 `-schedule:` 方法为例: + +```objectivec +- (RACDisposable *)schedule:(void (^)(void))block { + RACDisposable *disposable = [[RACDisposable alloc] init]; + + dispatch_async(self.queue, ^{ + if (disposable.disposed) return; + [self performAsCurrentScheduler:block]; + }); + + return disposable; +} +``` + +使用 `dispatch_async` 方法直接将需要执行的任务**异步派发**到它所持有的队列上;而 `-after:schedule:` 方法的实现相信各位读者也能猜到: + +```objectivec +- (RACDisposable *)after:(NSDate *)date schedule:(void (^)(void))block { + RACDisposable *disposable = [[RACDisposable alloc] init]; + + dispatch_after([self.class wallTimeWithDate:date], self.queue, ^{ + if (disposable.disposed) return; + [self performAsCurrentScheduler:block]; + }); + + return disposable; +} +``` + +哪怕不使用 `RACScheduler`,我们也能够想到利用 `dispatch_after` 完成一些需要延迟执行的任务,最后的 `+after:repeatingEvery:withLeeway:schedule:` 方法的实现就稍微复杂一些了: + +```objectivec +- (RACDisposable *)after:(NSDate *)date repeatingEvery:(NSTimeInterval)interval withLeeway:(NSTimeInterval)leeway schedule:(void (^)(void))block { + uint64_t intervalInNanoSecs = (uint64_t)(interval * NSEC_PER_SEC); + uint64_t leewayInNanoSecs = (uint64_t)(leeway * NSEC_PER_SEC); + + dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue); + dispatch_source_set_timer(timer, [self.class wallTimeWithDate:date], intervalInNanoSecs, leewayInNanoSecs); + dispatch_source_set_event_handler(timer, block); + dispatch_resume(timer); + + return [RACDisposable disposableWithBlock:^{ + dispatch_source_cancel(timer); + }]; +} +``` + +方法使用 `dispatch_source_t` 以及定时器,完成了每隔一段时间需要执行任务的需求。 + +### RACSubscriptionScheduler + +最后的 `RACSubscriptionScheduler` 是 ReactiveCocoa 中一个比较特殊的调度器,所有 ReactiveCocoa 中的订阅事件都会在 `RACSubscriptionScheduler` 调度器上进行;而它是通过封装两个调度器实现的: + +![RACSubscriptionSchedule](images/RACScheduler/RACSubscriptionScheduler.png) + +> `backgroundScheduler` 是一个优先级为 `RACSchedulerPriorityDefault` 的串行队列。 + +`RACSubscriptionScheduler` 本身不提供任何的调度功能,它会根据当前状态选择持有的两个调度器中的一个执行任务;首先判断当前线程是否存在 `currentScheduler`,如果不存在的话才会在 `backgroundScheduler` 执行任务。 + +```objectivec +- (RACDisposable *)schedule:(void (^)(void))block { + if (RACScheduler.currentScheduler == nil) return [self.backgroundScheduler schedule:block]; + block(); + return nil; +} + +- (RACDisposable *)after:(NSDate *)date schedule:(void (^)(void))block { + RACScheduler *scheduler = RACScheduler.currentScheduler ?: self.backgroundScheduler; + return [scheduler after:date schedule:block]; +} + +- (RACDisposable *)after:(NSDate *)date repeatingEvery:(NSTimeInterval)interval withLeeway:(NSTimeInterval)leeway schedule:(void (^)(void))block { + RACScheduler *scheduler = RACScheduler.currentScheduler ?: self.backgroundScheduler; + return [scheduler after:date repeatingEvery:interval withLeeway:leeway schedule:block]; +} +``` + +`RACSubscriptionScheduler` 作为一个私有类,我们并不能直接在 ReactiveCocoa 外部使用它,需要通过私有方法 `+subscriptionScheduler` 获取这个调度器: + +```objectivec ++ (RACScheduler *)subscriptionScheduler { + static dispatch_once_t onceToken; + static RACScheduler *subscriptionScheduler; + dispatch_once(&onceToken, ^{ + subscriptionScheduler = [[RACSubscriptionScheduler alloc] init]; + }); + + return subscriptionScheduler; +} +``` + +## 总结 + +`RACScheduler` 在某些方面与 GCD 中的队列十分相似,与 GCD 中的队列不同的有两点,第一,它可以通过 `RACDisposable` 对执行中的任务进行取消,第二是 `RACScheduler` 中任务的执行都是线性的;与此同时 `RACScheduler` 也与 `NSOperationQueue` 非常类似,但是它并不支持对调度的任务进行**重排序**以及实现任务与任务之间的**依赖**关系。 + +## References + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/racscheduler + diff --git a/contents/ReactiveObjC/RACSequence.md b/contents/ReactiveObjC/RACSequence.md new file mode 100644 index 0000000..4e35871 --- /dev/null +++ b/contents/ReactiveObjC/RACSequence.md @@ -0,0 +1,462 @@ +# Pull-Driven 的数据流 RACSequence + +ReactiveCocoa 在设计上很大程度借鉴了 Reactive Extension 中的概念,可以说 ReactiveCocoa 是 Rx 在 Objective-C 语言中的实现。 + +在 Rx 中主要的两个概念*信号*和*序列*都在 ReactiveCocoa 中有着相对应的组件 `RACSignal` 和 `RACSequence`,上一篇文章已经对前者有一个简单的介绍,而这篇文章主要会介绍后者,也就是 `RACSequence`。 + +## Push-Driven & Pull-Driven + +虽然这篇文章主要介绍 `RACSequence`,但是在介绍它之前,笔者想先就推驱动(push-driven)和拉驱动(pull-driven)这两个概念做一点简单的说明。 + +`RACSignal` 和 `RACSequence` 都是 `RACStream` 的子类,它们不仅共享了来自父类的很多方法,也都表示数据流。 + +![RACSignal - RACSequence](./images/RACSequence/RACSignal%20-%20RACSequence.png) + +`RACSignal` 和 `RACSequence` 最大区别就是: + ++ `RACSignal` 是推驱动的,也就是在每次信号中的出现新的数据时,所有的订阅者都会自动接受到最新的值; ++ `RACSequence` 作为推驱动的数据流,在改变时并不会通知使用当前序列的对象,只有使用者再次从这个 `RACSequence` 对象中获取数据才能更新,它的更新是需要使用者自己拉取的。 + +由于拉驱动在数据改变时,并不会主动推送给『订阅者』,所以往往适用于简化集合类对象等操作,相比于推驱动,它的适应场合较少。 + +![Usage for RACSignal - RACSequence Copy](./images/RACSequence/Usage%20for%20RACSignal%20-%20RACSequence%20Copy.png) + +> 图片中的内容来自 [Reactive​Cocoa · NSHipster](http://nshipster.com/reactivecocoa/) 中。 + +## 预加载与延迟加载 + +在 `RACSequence` 中还涉及到另外一对概念,也就是预加载和延迟加载(也叫懒加载);如果你之前学习过 Lisp 这门编程语言,那么你一定知道 Lisp 中有两种列表,一种是正常的列表 List,另一种叫做流 Stream,这两者的主要区别就是**流的加载是延迟加载的**,只有在真正使用数据时才会计算数据的内容。 + +![List-and-Strea](./images/RACSequence/List-and-Stream.png) + +> 由于流是懒加载的,这也就是说它可以**表示无穷长度的列表**。 + +Stream 由两部分组成,分别是 `head` 和 `tail`,两者都是在访问时才会计算,在上图前者是一个数字,而后者会是另一个 Stream 或者 `nil`。 + +```objectivec +@interface RACSequence<__covariant ValueType> : RACStream <NSCoding, NSCopying, NSFastEnumeration> + +@property (nonatomic, strong, readonly, nullable) ValueType head; +@property (nonatomic, strong, readonly, nullable) RACSequence<ValueType> *tail; + +@end +``` + +`RACSequence` 头文件的中定义能够帮助我们更好理解递归的序列以及 `head` 和 `tail` 的概念,`head` 是一个值,`tail` 是一个 `RACSequence` 对象。 + +## RACSequence 简介 + +了解了几个比较重要的概念之后,就可以进入正题了,先看一下在 ReactiveCocoa 中,`RACSequence` 都有哪些子类: + +![RACSequence - Subclasses](./images/RACSequence/RACSequence%20-%20Subclasses.png) + +`RACSequence` 总共有九个子类,这篇文章不会覆盖其中所有的内容,只会简单介绍其中的几个;不过,我们先从父类 `RACSequence` 开始。 + +### return 和 bind 方法 + +与介绍 `RACSignal` 时一样,这里我们先介绍两个 `RACSequence` 必须覆写的方法,第一个就是 `+return:` + +```objectivec ++ (RACSequence *)return:(id)value { + return [RACUnarySequence return:value]; +} +``` + +`+return:` 方法用到了 `RACSequence` 的子类 `RACUnarySequence` 私有类,这个类在外界是不可见的,其实现非常简单,只是将原来的 `value` 包装成了一个简单的 `RACUnarySequence` 对象: + +```objectivec ++ (RACUnarySequence *)return:(id)value { + RACUnarySequence *sequence = [[self alloc] init]; + sequence.head = value; + return [sequence setNameWithFormat:@"+return: %@", RACDescription(value)]; +} +``` + +这样在访问 `head` 时可以获取到传入的 `value`;在访问 `tail` 时只需要返回 `nil`: + +```objectivec +- (RACSequence *)tail { + return nil; +} +``` + +整个 `RACUnarySequence` 也只是对 `value` 简单封装成一个 `RACSequence` 对象而已: + +![RACUnarySequence](./images/RACSequence/RACUnarySequence.png) + +相比于 `+return:` 方法的简单实现,`-bind:` 的实现就复杂多了: + +```objectivec +- (RACSequence *)bind:(RACSequenceBindBlock (^)(void))block { + RACSequenceBindBlock bindBlock = block(); + return [[self bind:bindBlock passingThroughValuesFromSequence:nil] setNameWithFormat:@"[%@] -bind:", self.name]; +} +``` + +首先是对 `-bind:` 方法进行一次转发,将控制权交给 `-bind:passingThroughValuesFromSequence:` 方法中: + +```objectivec +- (RACSequence *)bind:(RACSequenceBindBlock)bindBlock passingThroughValuesFromSequence:(RACSequence *)passthroughSequence { + __block RACSequence *valuesSeq = self; + __block RACSequence *current = passthroughSequence; + __block BOOL stop = NO; + + RACSequence *sequence = [RACDynamicSequence sequenceWithLazyDependency:^ id { + while (current.head == nil) { + if (stop) return nil; + id value = valuesSeq.head; + if (value == nil) { + stop = YES; + return nil; + } + current = (id)bindBlock(value, &stop); + if (current == nil) { + stop = YES; + return nil; + } + + valuesSeq = valuesSeq.tail; + } + return nil; + } headBlock:^(id _) { + return current.head; + } tailBlock:^ id (id _) { + if (stop) return nil; + + return [valuesSeq bind:bindBlock passingThroughValuesFromSequence:current.tail]; + }]; + + sequence.name = self.name; + return sequence; +} +``` + +这个非常复杂的方法实际作用就是创建了一个私有类 `RACDynamicSequence` 对象,使用的初始化方法也都是私有的 `+sequenceWithLazyDependency:headBlock:tailBlock:`: + +```objectivec ++ (RACSequence *)sequenceWithLazyDependency:(id (^)(void))dependencyBlock headBlock:(id (^)(id dependency))headBlock tailBlock:(RACSequence *(^)(id dependency))tailBlock { + RACDynamicSequence *seq = [[RACDynamicSequence alloc] init]; + seq.headBlock = [headBlock copy]; + seq.tailBlock = [tailBlock copy]; + seq.dependencyBlock = [dependencyBlock copy]; + seq.hasDependency = YES; + return seq; +} +``` + +在使用 `RACDynamicSequence` 中的元素时,无论是 `head` 还是 `tail` 都会用到在初始化方法中传入的三个 block: + +```objectivec +- (id)head { + @synchronized (self) { + id untypedHeadBlock = self.headBlock; + if (untypedHeadBlock == nil) return _head; + + if (self.hasDependency) { + if (self.dependencyBlock != nil) { + _dependency = self.dependencyBlock(); + self.dependencyBlock = nil; + } + + id (^headBlock)(id) = untypedHeadBlock; + _head = headBlock(_dependency); + } else { + id (^headBlock)(void) = untypedHeadBlock; + _head = headBlock(); + } + + self.headBlock = nil; + return _head; + } +} +``` + +`head` 的计算依赖于 `self.headBlock` 和 `self.dependencyBlock`; + +而 `tail` 的计算也依赖于 `self.headBlock` 和 `self.dependencyBlock`,只是 `tail` 会执行 `tailBlock` 返回另一个 `RACDynamicSequence` 的实例: + +```objectivec +^ id (id _) { + return [valuesSeq bind:bindBlock passingThroughValuesFromSequence:current.tail]; +} +``` + +这里通过一段代码更好的了解 `-bind:` 方法是如何使用的: + +```objectivec +RACSequence *sequence = [RACSequence sequenceWithHeadBlock:^id _Nullable{ + return @1; +} tailBlock:^RACSequence * _Nonnull{ + return [RACSequence sequenceWithHeadBlock:^id _Nullable{ + return @2; + } tailBlock:^RACSequence * _Nonnull{ + return [RACSequence return:@3]; + }]; +}]; +RACSequence *bindSequence = [sequence bind:^RACSequenceBindBlock _Nonnull{ + return ^(NSNumber *value, BOOL *stop) { + NSLog(@"RACSequenceBindBlock: %@", value); + value = @(value.integerValue * 2); + return [RACSequence return:value]; + }; +}]; +NSLog(@"sequence: head = (%@), tail=(%@)", sequence.head, sequence.tail); +NSLog(@"BindSequence: head = (%@), tail=(%@)", bindSequence.head, bindSequence.tail); +``` + +在上面的代码中,我们使用 `+sequenceWithHeadBlock:tailBlock:` 这个唯一暴露出来的初始化方法创建了一个如下图所示的 `RACSequence`: + +![RACSequence-Instance](./images/RACSequence/RACSequence-Instance.png) + +> 图中展示了完整的 `RACSequence` 对象的值,其中的内容暂时都是 `unresolved` 的。 + +上述代码在运行之后,会打印出如下内容: + +```objectivec +sequence: head = (1), tail=(<RACDynamicSequence: 0x60800009eb40>{ name = , head = (unresolved), tail = (unresolved) }) +RACSequenceBindBlock: 1 +BindSequence: head = (2), tail=(<RACDynamicSequence: 0x608000282940>{ name = , head = (unresolved), tail = (unresolved) }) +``` + +无论是 `sequence` 还是 `bindSequence`,其中的 `tail` 部分都是一个 `RACDynamicSequence` 对象,并且其中的 `head` 和 `tail` 部分都是 `unresolved`。 + +![Unsolved-RACSequence-Instance](./images/RACSequence/Unsolved-RACSequence-Instance.png) + +在上面的代码中 `RACSequenceBindBlock` 的执行也是惰性的,只有在获取 `bindSequence.head` 时,才会执行将数字转换成 `RACUnarySequence` 对象,最后通过 `head` 属性取出来。 + +### lazySequence 和 eagerSequence + +上一节的代码中展示的所有序列都是惰性的,而在整个 ReactiveCocoa 中,所有的 `RACSequence` 对象在**默认情况**下都是惰性的,序列中的值只有在真正需要使用时才会被展开,在其他时间都是 **unresolved**。 + +`RACSequence` 中定义了两个分别获取 `lazySequence` 和 `eagerSequence` 的属性: + +```objectivec +@property (nonatomic, copy, readonly) RACSequence<ValueType> *eagerSequence; +@property (nonatomic, copy, readonly) RACSequence<ValueType> *lazySequence; +``` + +> 笔者一直认为在大多数情况下,在客户端上的惰性求值都是没有太多意义的,如果一个序列的**长度没有达到比较庞大的数量级或者说计算量比较小**,我们完全都可以使用贪婪求值(Eager Evaluation)的方式尽早获得结果; +> +> 同样,在数量级和计算量不需要考虑时,我们也不需要考虑是否应该设计成哪种求值方式,只需要使用默认行为。 + +与上一节相同,在这里使用相同的代码创建一个 `RACSequence` 对象: + +```objectivec +RACSequence *sequence = [RACSequence sequenceWithHeadBlock:^id _Nullable{ + return @1; +} tailBlock:^RACSequence * _Nonnull{ + return [RACSequence sequenceWithHeadBlock:^id _Nullable{ + return @2; + } tailBlock:^RACSequence * _Nonnull{ + return [RACSequence return:@3]; + }]; +}]; + +NSLog(@"Lazy: %@", sequence.lazySequence); +NSLog(@"Eager: %@", sequence.eagerSequence); +NSLog(@"Lazy: %@", sequence.lazySequence); +``` + +然后分别三次打印出当前对象的 `lazySequence` 和 `eagerSequence` 中的值: + +```objectivec +Lazy: <RACDynamicSequence: 0x608000097160> +{ name = , head = (unresolved), tail = (unresolved) } +Eager: <RACEagerSequence: 0x600000035de0> +{ name = , array = ( + 1, + 2, + 3 +) } +Lazy: <RACDynamicSequence: 0x608000097160> +{ name = , head = 1, tail = <RACDynamicSequence: 0x600000097070> + { name = , head = 2, tail = <RACUnarySequence: 0x600000035f00> + { name = , head = 3 } } } +``` + +在第一调用 `sequence.lazySequence` 时,因为元素没有被使用,惰性序列的 `head` 和 `tail` 都为 unresolved;而在 `sequence.eagerSequence` 调用后,访问了序列中的所有元素,在这之后再打印 `sequence.lazySequence` 中的值就都不是 unresolved 的了。 + +![RACSequence-Status-Before-And-After-Executed](./images/RACSequence/RACSequence-Status-Before-And-After-Executed.png) + +这种情况的出现不难理解,不过因为 `lazySequence` 和 `eagerSequence` 是 `RACSequence` 的方法,所以我们可以在任意子类的实例包括 `RACEagerSequence` 和非惰性序列上调用它们,这就会出现以下的多种情况: + +![EagerSequence - LazySequence](./images/RACSequence/EagerSequence%20-%20LazySequence.png) + +总而言之,调用过 `eagerSequence` 的序列的元素已经不再是 `unresolved` 了,哪怕再调用 `lazySequence` 方法,读者可以自行实验验证这里的结论。 + +### 操作 RACSequence + +`RACStream` 为 `RACSequence` 提供了很多基本的操作,`-map:`、`-filter:`、`-ignore:` 等等,因为这些方法的实现都基于 `-bind:`,而 `-bind:` 方法的执行是惰性的,所以在调用上述方法之后返回的 `RACSequence` 中所有的元素都是 unresolved 的,需要在访问之后才会计算并展开: + +```objectivec +RACSequence *sequence = [@[@1, @2, @3].rac_sequence map:^id _Nullable(NSNumber * _Nullable value) { + return @(value.integerValue * value.integerValue); +}]; +NSLog(@"%@", sequence); -> <RACDynamicSequence: 0x60800009ad10>{ name = , head = (unresolved), tail = (unresolved) } +NSLog(@"%@", sequence.eagerSequence); -> <RACEagerSequence: 0x60800002bfc0>{ name = , array = (1, 4, 9) } +``` + +除了从 `RACStream` 中继承的一些方法,在 `RACSequence` 类中也有一些自己实现的方法,比如说 `-foldLeftWithStart:reduce:` 方法: + +```objectivec +- (id)foldLeftWithStart:(id)start reduce:(id (^)(id, id))reduce { + if (self.head == nil) return start; + + for (id value in self) { + start = reduce(start, value); + } + + return start; +} +``` + +使用简单的 `for` 循环,将序列中的数据进行『折叠』,最后返回一个结果: + +```objectivec +RACSequence *sequence = @[@1, @2, @3].rac_sequence; +NSNumber *sum = [sequence foldLeftWithStart:0 reduce:^id _Nullable(NSNumber * _Nullable accumulator, NSNumber * _Nullable value) { + return @(accumulator.integerValue + value.integerValue); +}]; +NSLog(@"%@", sum); +``` + +与上面方法相似的是 `-foldRightWithStart:reduce:` 方法,从右侧开始向左折叠整个序列,虽然过程有一些不同,但是结果还是一样的。 + +![FoldLeft - FoldRight](./images/RACSequence/FoldLeft%20-%20FoldRight.png) + +从两次方法的调用栈上来看,就能看出两者实现过程的明显区别: + +![Call-Stacks-of-FoldLeft-FoldRight](./images/RACSequence/Call-Stacks-of-FoldLeft-FoldRight.png) + ++ `foldLeft` 由于其实现是通过 `for` 循环遍历序列,所以调用栈不会展开,在循环结束之后就返回了,调用栈中只有当前方法; ++ `foldRight` 的调用栈**递归**的调用自己,直到出现了边界条件 `self.tail == nil` 后停止,左侧的调用栈也是其调用栈最深的时候,在这时调用栈的规模开始按照箭头方向缩小,直到方法返回。 + +在源代码中,你也可以看到方法在创建 `RACSequence` 的 block 中递归调用了当前的方法: + +```objectivec +- (id)foldRightWithStart:(id)start reduce:(id (^)(id, RACSequence *))reduce { + if (self.head == nil) return start; + + RACSequence *rest = [RACSequence sequenceWithHeadBlock:^{ + if (self.tail) { + return [self.tail foldRightWithStart:start reduce:reduce]; + } else { + return start; + } + } tailBlock:nil]; + + return reduce(self.head, rest); +} +``` + +### RACSequence 与 RACSignal + +虽然 `RACSequence` 与 `RACSignal` 有很多不同,但是在 ReactiveCocoa 中 `RACSequence` 与 `RACSignal` 却可以双向转换。 + +![Transform Between RACSequence - RACSigna](./images/RACSequence/Transform%20Between%20RACSequence%20-%20RACSignal.png) + +#### 将 RACSequence 转换成 RACSignal + +将 `RACSequence` 转换成 `RACSignal` 对象只需要调用一个方法。 + +![Transform-RACSequence-To-RACSigna](./images/RACSequence/Transform-RACSequence-To-RACSignal.png) + +分析其实现之前先看一下如何使用 `-signal` 方法将 `RACSequence` 转换成 `RACSignal` 对象的: + +```objectivec +RACSequence *sequence = @[@1, @2, @3].rac_sequence; +RACSignal *signal = sequence.signal; +[signal subscribeNext:^(id _Nullable x) { + NSLog(@"%@", x); +}]; +``` + +其实过程非常简单,原序列 `@[@1, @2, @3]` 中的元素会按照次序发送,可以理解为依次调用 `-sendNext:`,它可以等价于下面的代码: + +```objectivec +RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + [subscriber sendNext:@1]; + [subscriber sendNext:@2]; + [subscriber sendNext:@3]; + [subscriber sendCompleted]; + return nil; +}]; +[signal subscribeNext:^(id _Nullable x) { + NSLog(@"%@", x); +}]; +``` + +`-signal` 方法的实现依赖于另一个实例方法 `-signalWithScheduler:`,它会在一个 `RACScheduler` 对象上发送序列中的所有元素: + +```objectivec +- (RACSignal *)signal { + return [[self signalWithScheduler:[RACScheduler scheduler]] setNameWithFormat:@"[%@] -signal", self.name]; +} + +- (RACSignal *)signalWithScheduler:(RACScheduler *)scheduler { + return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) { + __block RACSequence *sequence = self; + + return [scheduler scheduleRecursiveBlock:^(void (^reschedule)(void)) { + if (sequence.head == nil) { + [subscriber sendCompleted]; + return; + } + [subscriber sendNext:sequence.head]; + sequence = sequence.tail; + reschedule(); + }]; + }] setNameWithFormat:@"[%@] -signalWithScheduler: %@", self.name, scheduler]; +} +``` + +`RACScheduler` 并不是这篇文章准备介绍的内容,这里的代码其实相当于递归调用了 `reschedule` block,不断向 `subscriber` 发送 `-sendNext:`,直到 `RACSequence` 为空为止。 + +#### 将 RACSignal 转换成 RACSequence + +反向转换 `RACSignal` 的过程相比之下就稍微复杂一点了,我们需要连续调用两个方法,才能将它转换成 `RACSequence`。 + +![Transform RACSignal to RACSequence](./images/RACSequence/Transform%20RACSignal%20to%20RACSequence.png) + +通过一段代码来看转换过程是如何进行的: + +```objectivec +RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + [subscriber sendNext:@1]; + [subscriber sendNext:@2]; + [subscriber sendNext:@3]; + [subscriber sendCompleted]; + return nil; +}]; +NSLog(@"%@", signal.toArray.rac_sequence); +``` + +运行上面的代码,会得到一个如下的 `RACArraySequence` 对象: + +```objectivec +<RACArraySequence: 0x608000024e80>{ name = , array = ( + 1, + 2, + 3 +) } +``` + +在这里不想过多介绍其实现原理,我们只需要知道这里使用了 `RACStream` 提供的操作『收集』了信号发送过程中的发送的所有对象 `@1`、`@2`、`@3` 就可以了。 + +## 总结 + +相比于 `RACSignal` 来说,虽然 `RACSequence` 有很多的子类,但是它的用途和实现复杂度都少很多,这主要是因为它是 Pull-Driven 的,只有在使用时才会更新,所以我们一般只会使用 `RACSequence` 操作数据流,使用 `map`、`filter`、`flattenMap` 等方法快速操作数据。 + +## References + ++ [Reactive​Cocoa · NSHipster](http://nshipster.com/reactivecocoa/) ++ [What is the difference between RACSequence and RACSignal](http://stackoverflow.com/questions/28952900/what-is-the-difference-between-racsequence-and-racsignal) ++ [ReactiveCocoa Design Patterns](http://rcdp.io/Signal.html) + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/racsignal + + diff --git a/contents/ReactiveObjC/RACSignal.md b/contents/ReactiveObjC/RACSignal.md new file mode 100644 index 0000000..bc1c3de --- /dev/null +++ b/contents/ReactiveObjC/RACSignal.md @@ -0,0 +1,879 @@ +# 『状态』驱动的世界:ReactiveCocoa + +![RACSignal-Banner](./images/RACSignal/RACSignal-Banner.png) + +这篇以及之后的文章主要会对 ReactiveObjc v2.1.2 的实现进行分析,从最简单的例子中了解 ReactiveCocoa 的工作原理以及概念,也是笔者个人对于 RAC 学习的总结与理解。本文主要会围绕 RAC 中核心概念 `RACSignal` 展开,详细了解其底层实现。 + +## 状态驱动 + +2015 年的夏天的时候,做了几个简单的开源框架,想做点其它更有意思的框架却没什么思路,就开始看一些跟编程没有太大关系的书籍。 + +![out-of-contro](./images/RACSignal/out-of-control.jpg) + +其中一本叫做《失控》给了我很大的启发,其中有一则故事是这样的: + +> 布鲁克斯开展了一个雄心勃勃的研究生课题项目,研发更接近昆虫而非恐龙的机器人。 +> +> 布鲁克斯的设想在一个叫「成吉思」的机巧装置上成形。成吉思有橄榄球大小,像只蟑螂似的。布鲁克斯把他的精简理念发挥到了极致。小成吉思有 6 条腿却没有一丁点儿可以称为「脑」的东西。所有 12 个电机和 21 个传感器分布在没有中央处理器的可解耦网络上。然而这 12 个充当肌肉的电机和 21 个传感器之间的交互作用居然产生了令人惊叹的复杂性和类似生命体的行为。 > +> 成吉思的每条小细腿都在自顾自地工作,和其余的腿毫无关系。每条腿都通过自己的一组神经元——一个微型处理器——来控制其动作。每条腿只需管好自己!对成吉思来说,走路是一个团队合作项目,至少有六个小头脑在工作。它体内其余更微小的脑力则负责腿与腿之间的通讯。昆虫学家说这正是蚂蚁和蟑螂的解决之道——这些爬行昆虫的足肢上的神经元负责为该足肢进行思考。 +> +> ------ 《失控》第三章·第二节 快速、廉价、失控 + + +书中对于机器人的介绍比较冗长,在这里就简单总结一下:机器人的每一条腿都单独进行工作,通过传感器感应的**状态**做出响应: + ++ 如果腿抬起来了,那么它要落下去; ++ 如果腿在向前动,要让另外五条腿距离它远一点; + +这种去中心化的方式,简化了整个系统的构造,使得各个组件只需要关心状态,以及状态对应的动作;不再需要一个中枢系统来组织、管理其它的组件,并负责大多数的业务逻辑。这种自底向下的、状态驱动的构建方式能够使用多个较小的组件,减少臃肿的中枢出现的可能性,从而降低系统的复杂度。 + +## ReactiveCocoa 与信号 + +ReactiveCocoa 对于状态的理解与《失控》一书中十分类似,将原有的各种设计模式,包括代理、Target/Action、通知中心以及观察者模式各种『输入』,都抽象成了信号(也可以理解为状态流)让单一的组件能够对自己的响应动作进行控制,简化了视图控制器的负担。 + +在 ReactiveCocoa 中最重要的信号,也就是 `RACSignal` 对象是这一篇文章介绍的核心;文章中主要会介绍下面的代码片段出现的内容: + +```objectivec +RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + [subscriber sendNext:@1]; + [subscriber sendNext:@2]; + [subscriber sendCompleted]; + return [RACDisposable disposableWithBlock:^{ + NSLog(@"dispose"); + }]; +}]; +[signal subscribeNext:^(id _Nullable x) { + NSLog(@"%@", x); +}]; +``` + +在上述代码执行时,会在控制台中打印出以下内容: + +```c +1 +2 +dispose +``` + +代码片段基本都是围绕 `RACSignal` 类进行的,文章会分四部分对上面的代码片段的工作流程进行简单的介绍: + ++ 简单了解 `RACSignal` ++ 信号的创建 ++ 信号的订阅与发送 ++ 订阅的回收过程 + +## RACSignal 简介 + +`RACSignal` 其实是抽象类 `RACStream` 的子类,在整个 ReactiveObjc 工程中有另一个类 `RACSequence` 也继承自抽象类 `RACStream`: + +![RACSignal-Hierachy](./images/RACSignal/RACSignal-Hierachy.png) + +`RACSignal` 可以说是 ReactiveCocoa 中的核心类,也是最重要的概念,整个框架围绕着 `RACSignal` 的概念进行组织,对 `RACSignal` 最简单的理解就是它表示一连串的状态: + +![What-is-RACSigna](./images/RACSignal/What-is-RACSignal.png) + +在状态改变时,对应的订阅者 `RACSubscriber` 就会收到通知执行相应的指令,在 ReactiveCocoa 的世界中所有的消息都是通过信号的方式来传递的,原有的设计模式都会简化为一种模型,这篇文章作为 ReactiveCocoa 系列的第一篇文章并不会对这些问题进行详细的展开和介绍,只会对 `RACSignal` 使用过程的原理进行简单的分析。 + +这一小节会对 `RACStream` 以及 `RACSignal` 中与 `RACStream` 相关的部分进行简单的介绍。 + +### RACStream + +`RACStream` 作为抽象类本身不提供方法的实现,其实现内部原生提供的而方法都是抽象方法,会在调用时直接抛出异常: + +```objectivec ++ (__kindof RACStream *)empty { + NSString *reason = [NSString stringWithFormat:@"%@ must be overridden by subclasses", NSStringFromSelector(_cmd)]; + @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:reason userInfo:nil]; +} + +- (__kindof RACStream *)bind:(RACStreamBindBlock (^)(void))block; ++ (__kindof RACStream *)return:(id)value; +- (__kindof RACStream *)concat:(RACStream *)stream; +- (__kindof RACStream *)zipWith:(RACStream *)stream; +``` + +![RACStream-AbstractMethod](./images/RACSignal/RACStream-AbstractMethod.png) + +上面的这些抽象方法都需要子类覆写,不过 `RACStream` 在 `Operations` 分类中使用上面的抽象方法提供了丰富的内容,比如说 `-flattenMap:` 方法: + +```objectivec +- (__kindof RACStream *)flattenMap:(__kindof RACStream * (^)(id value))block { + Class class = self.class; + + return [[self bind:^{ + return ^(id value, BOOL *stop) { + id stream = block(value) ?: [class empty]; + NSCAssert([stream isKindOfClass:RACStream.class], @"Value returned from -flattenMap: is not a stream: %@", stream); + + return stream; + }; + }] setNameWithFormat:@"[%@] -flattenMap:", self.name]; +} +``` + +其他方法比如 `-skip:`、`-take:`、`-ignore:` 等等实例方法都构建在这些抽象方法之上,只要子类覆写了所有抽象方法就能自动获得所有的 `Operation` 分类中的方法。 + +![RACStream-Operation](./images/RACSignal/RACStream-Operation.png) + +### RACSignal 与 Monad + +> 如果你对 Monad 有所了解,那么你应该知道 `bind` 和 `return` 其实是 Monad 中的概念,但 Monad 并不是本篇文章所覆盖的内容,并不会具体解释它到底是什么。 + +ReactiveCocoa 框架中借鉴了很多其他平台甚至语言中的概念,包括微软中的 Reactive Extension 以及 Haskell 中的 Monad,`RACStream` 提供的抽象方法中的 `+return:` 和 `-bind:` 就与 Haskell 中 Monad 完全一样。 + +> 很多人都说 Monad 只是一个自函子范畴上的一个幺半群而已;在笔者看来这种说法虽然是正确的,不过也很扯淡,这句话解释了还是跟没解释一样,如果有人再跟你用这句话解释 Monad,我觉得你最好的回应就是买一本范畴论糊他一脸。如果真的想了解 Haskell 中的 Monad 到底是什么?可以从代码的角度入手,多写一些代码就明白了,这个概念理解起来其实根本没什么困难的,当然也可以看一下 [A Fistful of Monads](http://learnyouahaskell.com/a-fistful-of-monads),写写其中的代码,会对 Monad 有自己的认知,当然,请不要再写一篇解释 Monad 的教程了(手动微笑)。 + +首先来看一下 `+return` 方法的 [实现](https://github.com/ReactiveCocoa/ReactiveObjC/blob/1180ab256000573ef82141e5d40e9b9c35dfd69c/ReactiveObjC/RACSignal.m#L89-L91): + +```objectivec ++ (RACSignal *)return:(id)value { + return [RACReturnSignal return:value]; +} +``` + +该方法接受一个 `NSObject` 对象,并返回一个 `RACSignal` 的实例,它会将一个 UIKit 世界的对象 `NSObject` 转换成 ReactiveCocoa 中的 `RACSignal`: + +![RACSignal-Return](./images/RACSignal/RACSignal-Return.png) + +而 `RACReturnSignal` 也仅仅是把 `NSObject` 对象包装一下,并没有做什么复杂的事情: + +```objectivec ++ (RACSignal *)return:(id)value { + RACReturnSignal *signal = [[self alloc] init]; + signal->_value = value; + return signal; +} +``` + +但是 `-bind:` 方法的 [实现](https://github.com/ReactiveCocoa/ReactiveObjC/blob/1180ab256000573ef82141e5d40e9b9c35dfd69c/ReactiveObjC/RACSignal.m#L93-L176) 相比之下就十分复杂了: + +```objectivec +- (RACSignal *)bind:(RACSignalBindBlock (^)(void))block { + return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) { + RACSignalBindBlock bindingBlock = block(); + return [self subscribeNext:^(id x) { + BOOL stop = NO; + id signal = bindingBlock(x, &stop); + + if (signal != nil) { + [signal subscribeNext:^(id x) { + [subscriber sendNext:x]; + } error:^(NSError *error) { + [subscriber sendError:error]; + } completed:^{ + [subscriber sendCompleted]; + }]; + } + if (signal == nil || stop) { + [subscriber sendCompleted]; + } + } error:^(NSError *error) { + [subscriber sendError:error]; + } completed:^{ + [subscriber sendCompleted]; + }]; + }] setNameWithFormat:@"[%@] -bind:", self.name]; +} +``` + +> 笔者在这里对 `-bind:` 方法进行了大量的省略,省去了其中对各种 `RACDisposable` 的处理过程。 + +`-bind:` 方法会在原信号每次发出消息时,都执行 `RACSignalBindBlock` 对原有的信号中的消息进行**变换**生成一个新的信号: + +![RACSignal-Bind](./images/RACSignal/RACSignal-Bind.png) + +> 在原有的 `RACSignal` 对象上调用 `-bind:` 方法传入 `RACSignalBindBlock`,图示中的右侧就是具体的执行过程,原信号在变换之后变成了新的蓝色的 `RACSignal` 对象。 + +`RACSignalBindBlock` 可以简单理解为一个接受 `NSObject` 对象返回 `RACSignal` 对象的函数: + +```objectivec +typedef RACSignal * _Nullable (^RACSignalBindBlock)(id _Nullable value, BOOL *stop); +``` + +其函数签名可以理解为 `id -> RACSignal`,然而这种函数是无法直接对 `RACSignal` 对象进行变换的;不过通过 `-bind:` 方法就可以使用这种函数操作 `RACSignal`,其实现如下: + +1. 将 `RACSignal` 对象『解包』出 `NSObject` 对象; +2. 将 `NSObject` 传入 `RACSignalBindBlock` 返回 `RACSignal`。 + +如果在不考虑 `RACSignal` 会发出错误或者完成信号时,`-bind:` 可以简化为更简单的形式: + +```objectivec +- (RACSignal *)bind:(RACSignalBindBlock (^)(void))block { + return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) { + RACSignalBindBlock bindingBlock = block(); + return [self subscribeNext:^(id x) { + BOOL stop = NO; + [bindingBlock(x, &stop) subscribeNext:^(id x) { + [subscriber sendNext:x]; + }]; + }]; + }] setNameWithFormat:@"[%@] -bind:", self.name]; +} +``` + +调用 `-subscribeNext:` 方法订阅当前信号,将信号中的状态解包,然后将原信号中的状态传入 `bindingBlock` 中并订阅返回的新的信号,将生成的新状态 `x` 传回原信号的订阅者。 + +这里通过两个简单的例子来了解 `-bind:` 方法的作用: + +```objectivec +RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + [subscriber sendNext:@1]; + [subscriber sendNext:@2]; + [subscriber sendNext:@3]; + [subscriber sendNext:@4]; + [subscriber sendCompleted]; + return nil; +}]; +RACSignal *bindSignal = [signal bind:^RACSignalBindBlock _Nonnull{ + return ^(NSNumber *value, BOOL *stop) { + value = @(value.integerValue * value.integerValue); + return [RACSignal return:value]; + }; +}]; +[signal subscribeNext:^(id _Nullable x) { + NSLog(@"signal: %@", x); +}]; +[bindSignal subscribeNext:^(id _Nullable x) { + NSLog(@"bindSignal: %@", x); +}]; +``` + +上面的代码中直接使用了 `+return:` 方法将 `value` 打包成了 `RACSignal *` 对象: + +![Before-After-Bind-RACSigna](./images/RACSignal/Before-After-Bind-RACSignal.png) + +> 在 BindSignal 中的每一个数字其实都是由一个 `RACSignal` 包裹的,这里没有画出,在下一个例子中,读者可以清晰地看到其中的区别。 + +上图简要展示了变化前后的信号中包含的状态,在运行上述代码时,会在终端中打印出: + +```objectivec +signal: 1 +signal: 2 +signal: 3 +signal: 4 +bindSignal: 1 +bindSignal: 4 +bindSignal: 9 +bindSignal: 16 +``` + +这是一个最简单的例子,直接使用 `-return:` 打包 `NSObject` 返回一个 `RACSignal`,接下来用一个更复杂的例子来帮助我们更好的了解 `-bind:` 方法: + +```objectivec +RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + [subscriber sendNext:@1]; + [subscriber sendNext:@2]; + [subscriber sendCompleted]; + return nil; +}]; +RACSignal *bindSignal = [signal bind:^RACSignalBindBlock _Nonnull{ + return ^(NSNumber *value, BOOL *stop) { + NSNumber *returnValue = @(value.integerValue * value.integerValue); + return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + for (NSInteger i = 0; i < value.integerValue; i++) [subscriber sendNext:returnValue]; + [subscriber sendCompleted]; + return nil; + }]; + }; +}]; +[bindSignal subscribeNext:^(id _Nullable x) { + NSLog(@"%@", x); +}]; +``` + +下图相比上面例子中的图片更能精确的表现出 `-bind:` 方法都做了什么: + +![Before-After-Bind-RACSignal-Complicated](./images/RACSignal/Before-After-Bind-RACSignal-Complicated.png) + +信号中原有的状态经过 `-bind:` 方法中传入 `RACSignalBindBlock` 的处理实际上返回了**多个** `RACSignal`。 + +在源代码的注释中清楚地写出了方法的实现过程: + +1. 订阅原信号中的值; +2. 将原信号发出的值传入 `RACSignalBindBlock` 进行转换; +3. 如果 `RACSignalBindBlock` 返回一个信号,就会订阅该信号并将信号中的所有值传给订阅者 `subscriber`; +4. 如果 `RACSignalBindBlock` 请求终止信号就会向**原**信号发出 `-sendCompleted` 消息; +5. 当**所有**信号都完成时,会向订阅者发送 `-sendCompleted`; +6. 无论何时,如果信号发出错误,都会向订阅者发送 `-sendError:` 消息。 + +如果想要了解 `-bind:` 方法在执行的过程中是如何处理订阅的清理和销毁的,可以阅读文章最后的 [-bind: 中对订阅的销毁]() 部分。 + +## 信号的创建 + +信号的创建过程十分简单,`-createSignal:` 是推荐的创建信号的方法,方法其实只做了一次转发: + +```objectivec ++ (RACSignal *)createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe { + return [RACDynamicSignal createSignal:didSubscribe]; +} + ++ (RACSignal *)createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe { + RACDynamicSignal *signal = [[self alloc] init]; + signal->_didSubscribe = [didSubscribe copy]; + return [signal setNameWithFormat:@"+createSignal:"]; +} +``` + +该方法其实只是创建了一个 `RACDynamicSignal` 实例并保存了传入的 `didSubscribe` 代码块,在每次有订阅者订阅当前信号时,都会执行一遍,向订阅者发送消息。 + +### RACSignal 类簇 + +虽然 `-createSignal:` 的方法签名上返回的是 `RACSignal` 对象的实例,但是实际上这里返回的是 `RACDynamicSignal`,也就是 `RACSignal` 的子类;同样,在 ReactiveCocoa 中也有很多其他的 `RACSignal` 子类。 + +使用类簇的方式设计的 `RACSignal` 在创建实例时可能会返回 `RACDynamicSignal`、`RACEmptySignal`、`RACErrorSignal` 和 `RACReturnSignal` 对象: + +![RACSignal-Subclasses](./images/RACSignal/RACSignal-Subclasses.png) + +其实这几种子类并没有对原有的 `RACSignal` 做出太大的改变,它们的创建过程也不是特别的复杂,只需要调用 `RACSignal` 不同的类方法: + +![RACSignal-Instantiate-Object](./images/RACSignal/RACSignal-Instantiate-Object.png) + +`RACSignal` 只是起到了一个代理的作用,最后的实现过程还是会指向对应的子类: + +```objectivec ++ (RACSignal *)error:(NSError *)error { + return [RACErrorSignal error:error]; +} + ++ (RACSignal *)empty { + return [RACEmptySignal empty]; +} + ++ (RACSignal *)return:(id)value { + return [RACReturnSignal return:value]; +} +``` + +以 `RACReturnSignal` 的创建过程为例: + +```objectivec ++ (RACSignal *)return:(id)value { + RACReturnSignal *signal = [[self alloc] init]; + signal->_value = value; + return signal; +} +``` + +这个信号的创建过程和 `RACDynamicSignal` 的初始化过程一样,都非常简单;只是将传入的 `value` 简单保存一下,在有其他订阅者 `-subscribe:` 时,向订阅者发送 `value`: + +```objectivec +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + return [RACScheduler.subscriptionScheduler schedule:^{ + [subscriber sendNext:self.value]; + [subscriber sendCompleted]; + }]; +} +``` + +`RACEmptySignal` 和 `RACErrorSignal` 的创建过程也异常的简单,只是对传入的数据进行简单的存储,然后在订阅时发送出来: + +```objectivec +// RACEmptySignal ++ (RACSignal *)empty { + return [[[self alloc] init] setNameWithFormat:@"+empty"]; +} + +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + return [RACScheduler.subscriptionScheduler schedule:^{ + [subscriber sendCompleted]; + }]; +} + +// RACErrorSignal ++ (RACSignal *)error:(NSError *)error { + RACErrorSignal *signal = [[self alloc] init]; + signal->_error = error; + return signal; +} + +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + return [RACScheduler.subscriptionScheduler schedule:^{ + [subscriber sendError:self.error]; + }]; +} +``` + +这两个创建过程的唯一区别就是一个发送的是『空值』,另一个是 `NSError` 对象。 + +## 信号的订阅与信息的发送 + +ReactiveCocoa 中信号的订阅与信息的发送过程主要是由 `RACSubscriber` 类来处理的,而这也是信号的处理过程中最重要的一部分,这一小节会先分析整个工作流程,之后会深入代码的实现。 + +![RACSignal-Subcribe-Process](./images/RACSignal/RACSignal-Subcribe-Process.png) + +在信号创建之后调用 `-subscribeNext:` 方法返回一个 `RACDisposable`,然而这不是这一流程关心的重点,在订阅过程中生成了一个 `RACSubscriber` 对象,向这个对象发送消息 `-sendNext:` 时,就会向所有的订阅者发送消息。 + +### 信号的订阅 + +信号的订阅与 `-subscribe:` 开头的一系列方法有关: + +![RACSignal-Subscribe-Methods](./images/RACSignal/RACSignal-Subscribe-Methods.png) + +订阅者可以选择自己想要感兴趣的信息类型 `next/error/completed` 进行关注,并在对应的信息发生时调用 block 进行处理回调。 + +所有的方法其实只是对 `nextBlock`、`completedBlock` 以及 `errorBlock` 的组合,这里以其中最长的 `-subscribeNext:error:completed:` 方法的实现为例(也只需要介绍这一个方法): + +```objectivec +- (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock error:(void (^)(NSError *error))errorBlock completed:(void (^)(void))completedBlock { + RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:errorBlock completed:completedBlock]; + return [self subscribe:o]; +} +``` + +> 方法中传入的所有 block 参数都应该是非空的。 + +拿到了传入的 block 之后,使用 `+subscriberWithNext:error:completed:` 初始化一个 `RACSubscriber` 对象的实例: + +```objectivec ++ (instancetype)subscriberWithNext:(void (^)(id x))next error:(void (^)(NSError *error))error completed:(void (^)(void))completed { + RACSubscriber *subscriber = [[self alloc] init]; + + subscriber->_next = [next copy]; + subscriber->_error = [error copy]; + subscriber->_completed = [completed copy]; + + return subscriber; +} +``` + +在拿到这个对象之后,调用 `RACSignal` 的 `-subscribe:` 方法传入订阅者对象: + +```objectivec +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + NSCAssert(NO, @"This method must be overridden by subclasses"); + return nil; +} +``` + +`RACSignal` 类中其实并没有实现这个实例方法,需要在上文提到的四个子类对这个方法进行覆写,这里仅分析 `RACDynamicSignal` 中的方法: + +```objectivec +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable]; + subscriber = [[RACPassthroughSubscriber alloc] initWithSubscriber:subscriber signal:self disposable:disposable]; + + RACDisposable *schedulingDisposable = [RACScheduler.subscriptionScheduler schedule:^{ + RACDisposable *innerDisposable = self.didSubscribe(subscriber); + [disposable addDisposable:innerDisposable]; + }]; + + [disposable addDisposable:schedulingDisposable]; + + return disposable; +} +``` + +> 这里暂时不需要关注与 `RACDisposable` 有关的任何内容,我们会在下一节中详细介绍。 + +`RACPassthroughSubscriber` 就像它的名字一样,只是对上面创建的订阅者对象进行简单的包装,将所有的消息转发给内部的 `innerSubscriber`,也就是传入的 `RACSubscriber` 对象: + +```objectivec +- (instancetype)initWithSubscriber:(id<RACSubscriber>)subscriber signal:(RACSignal *)signal disposable:(RACCompoundDisposable *)disposable { + self = [super init]; + + _innerSubscriber = subscriber; + _signal = signal; + _disposable = disposable; + + [self.innerSubscriber didSubscribeWithDisposable:self.disposable]; + return self; +} +``` + +如果直接简化 `-subscribe:` 方法的实现,你可以看到一个看起来极为敷衍的代码: + +```objectivec +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + return self.didSubscribe(subscriber); +} +``` + +方法只是执行了在创建信号时传入的 `RACSignalBindBlock`: + +```objectivec +[RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + [subscriber sendNext:@1]; + [subscriber sendNext:@2]; + [subscriber sendCompleted]; + return [RACDisposable disposableWithBlock:^{ + NSLog(@"dispose"); + }]; +}]; +``` + +总而言之,信号的订阅过程就是初始化 `RACSubscriber` 对象,然后执行 `didSubscribe` 代码块的过程。 + +![Principle-of-Subscribing-Signals](./images/RACSignal/Principle-of-Subscribing-Signals.png) + +### 信息的发送 + +在 `RACSignalBindBlock` 中,订阅者可以根据自己的兴趣选择自己想要订阅哪种消息;我们也可以按需发送三种消息: + +![RACSignal-Subcription-Messages-Sending](./images/RACSignal/RACSignal-Subcription-Messages-Sending.png) + +而现在只需要简单看一下这三个方法的实现,就能够明白信息的发送过程了(真是没啥好说的,不过为了~~凑字数~~完整性): + +```objectivec +- (void)sendNext:(id)value { + @synchronized (self) { + void (^nextBlock)(id) = [self.next copy]; + if (nextBlock == nil) return; + + nextBlock(value); + } +} +``` + +`-sendNext:` 只是将方法传入的值传入 `nextBlock` 再调用一次,并没有什么值得去分析的地方,而剩下的两个方法实现也差不多,会调用对应的 block,在这里就省略了。 + +## 订阅的回收过程 + +在创建信号时,我们向 `-createSignal:` 方法中传入了 `didSubscribe` 信号,这个 block 在执行结束时会返回一个 `RACDisposable` 对象,用于在订阅结束时进行必要的清理,同样也可以用于取消因为订阅创建的**正在执行**的任务。 + +而处理这些事情的核心类就是 `RACDisposable` 以及它的子类: + +![RACDisposable-And-Subclasses](./images/RACSignal/RACDisposable-And-Subclasses.png) + +> 这篇文章中主要关注的是左侧的三个子类,当然 `RACDisposable` 的子类不止这三个,还有用于处理 KVO 的 `RACKVOTrampoline`,不过在这里我们不会讨论这个类的实现。 + +### RACDisposable + +在继续分析讨论订阅的回收过程之前,笔者想先对 `RACDisposable` 进行简要的剖析和介绍: + +![RACDisposable](./images/RACSignal/RACDisposable.png) + +类 `RACDisposable` 是以 `_disposeBlock` 为核心进行组织的,几乎所有的方法以及属性其实都是对 `_disposeBlock` 进行的操作。 + +#### 关于 _disposeBlock 中的 self + +> 这一小节的内容是可选的,跳过不影响整篇文章阅读的连贯性。 + +`_disposeBlock` 是一个私有的指针变量,当 `void (^)(void)` 类型的 block 被传入之后都会转换成 CoreFoundation 中的类型并以 `void *` 的形式存入 `_disposeBlock` 中: + +```objectivec + ++ (instancetype)disposableWithBlock:(void (^)(void))block { + return [[self alloc] initWithBlock:block]; +} + +- (instancetype)initWithBlock:(void (^)(void))block { + self = [super init]; + + _disposeBlock = (void *)CFBridgingRetain([block copy]); + OSMemoryBarrier(); + + return self; +} +``` + +奇怪的是,`_disposeBlock` 中不止会存储代码块 block,还有可能存储桥接之后的 `self`: + +```objectivec +- (instancetype)init { + self = [super init]; + + _disposeBlock = (__bridge void *)self; + OSMemoryBarrier(); + + return self; +} +``` + +这里,刚开始看到可能会觉得比较奇怪,有两个疑问需要解决: + +1. 为什么要提供一个 `-init` 方法来初始化 `RACDisposable` 对象? +2. 为什么要向 `_disposeBlock` 中传入当前对象? + +对于 `RACDisposable` 来说,虽然一个不包含 `_disposeBlock` 的对象没什么太多的意义,但是对于 `RACSerialDisposable` 等子类来说,却不完全是这样,因为 `RACSerialDisposable` 在 `-dispose` 时,并不需要执行 `disposeBlock`,这样就浪费了内存和 CPU 时间;但是同时我们需要一个合理的方法准确地判断当前对象的 `isDisposed`: + +```objectivec +- (BOOL)isDisposed { + return _disposeBlock == NULL; +} +``` + +所以,使用向 `_disposeBlock` 中传入 `NULL` 的方式来判断 `isDisposed`;在 `-init` 调用时传入 `self` 而不是 `NULL` 防止状态被误判,这样就在不引入其他实例变量、增加对象的设计复杂度的同时,解决了这两个问题。 + +如果仍然不理解上述的两个问题,在这里举一个错误的例子,如果 `_disposeBlock` 在使用时只传入 `NULL` 或者 `block`,那么在 `RACCompoundDisposable` 初始化时,是应该向 `_disposeBlock` 中传入什么呢? + ++ 传入 `NULL` 会导致在初始化之后 `isDisposed == YES`,然而当前对象根本没有被回收; ++ 传入 `block` 会导致无用的 block 的执行,浪费内存以及 CPU 时间; + +这也就是为什么要引入 `self` 来作为 `_disposeBlock` 内容的原因。 + +#### -dispose: 方法的实现 + +这个只有不到 20 行的 `-dispose:` 方法已经是整个 `RACDisposable` 类中最复杂的方法了: + +```objectivec +- (void)dispose { + void (^disposeBlock)(void) = NULL; + + while (YES) { + void *blockPtr = _disposeBlock; + if (OSAtomicCompareAndSwapPtrBarrier(blockPtr, NULL, &_disposeBlock)) { + if (blockPtr != (__bridge void *)self) { + disposeBlock = CFBridgingRelease(blockPtr); + } + + break; + } + } + + if (disposeBlock != nil) disposeBlock(); +} +``` + +但是其实它的实现也没有复杂到哪里去,从 `_disposeBlock` 实例变量中调用 `CFBridgingRelease` 取出一个 `disposeBlock`,然后执行这个 block,整个方法就结束了。 + +### RACSerialDisposable + +`RACSerialDisposable` 是一个用于持有 `RACDisposable` 的容器,它一次只能持有一个 `RACDisposable` 的实例,并可以原子地换出容器中保存的对象: + +```objectivec +- (RACDisposable *)swapInDisposable:(RACDisposable *)newDisposable { + RACDisposable *existingDisposable; + BOOL alreadyDisposed; + + pthread_mutex_lock(&_mutex); + alreadyDisposed = _disposed; + if (!alreadyDisposed) { + existingDisposable = _disposable; + _disposable = newDisposable; + } + pthread_mutex_unlock(&_mutex); + + if (alreadyDisposed) { + [newDisposable dispose]; + return nil; + } + + return existingDisposable; +} +``` + +线程安全的 `RACSerialDisposable` 使用 `pthred_mutex_t` 互斥锁来保证在访问关键变量时不会出现线程竞争问题。 + +`-dispose` 方法的处理也十分简单: + +```objectivec +- (void)dispose { + RACDisposable *existingDisposable; + + pthread_mutex_lock(&_mutex); + if (!_disposed) { + existingDisposable = _disposable; + _disposed = YES; + _disposable = nil; + } + pthread_mutex_unlock(&_mutex); + + [existingDisposable dispose]; +} +``` + +使用锁保证线程安全,并在内部的 `_disposable` 换出之后在执行 `-dispose` 方法对订阅进行处理。 + +### RACCompoundDisposable + +与 `RACSerialDisposable` 只负责一个 `RACDisposable` 对象的释放不同;`RACCompoundDisposable` 同时负责多个 `RACDisposable` 对象的释放。 + +相比于只管理一个 `RACDisposable` 对象的 `RACSerialDisposable`,`RACCompoundDisposable` 由于管理多个对象,其实现更加复杂,而且为了**性能和内存占用之间的权衡**,其实现方式是通过持有两个实例变量: + +```objectivec +@interface RACCompoundDisposable () { + ... + RACDisposable *_inlineDisposables[RACCompoundDisposableInlineCount]; + + CFMutableArrayRef _disposables; + ... +} +``` + +在对象持有的 `RACDisposable` 不超过 `RACCompoundDisposableInlineCount` 时,都会存储在 `_inlineDisposables` 数组中,而更多的实例都会存储在 `_disposables` 中: + +![RACCompoundDisposable](./images/RACSignal/RACCompoundDisposable.png) + +`RACCompoundDisposable` 在使用 `-initWithDisposables:`初始化时,会初始化两个 `RACDisposable` 的位置用于加速销毁订阅的过程,同时为了不浪费内存空间,在默认情况下只占用两个位置: + +```objectivec +- (instancetype)initWithDisposables:(NSArray *)otherDisposables { + self = [self init]; + + [otherDisposables enumerateObjectsUsingBlock:^(RACDisposable *disposable, NSUInteger index, BOOL *stop) { + self->_inlineDisposables[index] = disposable; + if (index == RACCompoundDisposableInlineCount - 1) *stop = YES; + }]; + + if (otherDisposables.count > RACCompoundDisposableInlineCount) { + _disposables = RACCreateDisposablesArray(); + + CFRange range = CFRangeMake(RACCompoundDisposableInlineCount, (CFIndex)otherDisposables.count - RACCompoundDisposableInlineCount); + CFArrayAppendArray(_disposables, (__bridge CFArrayRef)otherDisposables, range); + } + + return self; +} +``` + +如果传入的 `otherDisposables` 多于 `RACCompoundDisposableInlineCount`,就会创建一个新的 `CFMutableArrayRef` 引用,并将剩余的 `RACDisposable` 全部传入这个数组中。 + +在 `RACCompoundDisposable` 中另一个值得注意的方法就是 `-addDisposable:` + +```objectivec +- (void)addDisposable:(RACDisposable *)disposable { + if (disposable == nil || disposable.disposed) return; + + BOOL shouldDispose = NO; + + pthread_mutex_lock(&_mutex); + { + if (_disposed) { + shouldDispose = YES; + } else { + for (unsigned i = 0; i < RACCompoundDisposableInlineCount; i++) { + if (_inlineDisposables[i] == nil) { + _inlineDisposables[i] = disposable; + goto foundSlot; + } + } + + if (_disposables == NULL) _disposables = RACCreateDisposablesArray(); + CFArrayAppendValue(_disposables, (__bridge void *)disposable); + foundSlot:; + } + } + pthread_mutex_unlock(&_mutex); + if (shouldDispose) [disposable dispose]; +} +``` + +在向 `RACCompoundDisposable` 中添加新的 `RACDisposable` 对象时,会先尝试在 `_inlineDisposables` 数组中寻找空闲的位置,如果没有找到,就会加入到 `_disposables` 中;但是,在添加 `RACDisposable` 的过程中也难免遇到当前 `RACCompoundDisposable` 已经 `dispose` 的情况,而这时就会直接 `-dispose` 刚刚加入的对象。 + +### 订阅的销毁过程 + +在了解了 ReactiveCocoa 中与订阅销毁相关的类,我们就可以继续对 `-bind:` 方法的分析了,之前在分析该方法时省略了 `-bind:` 在执行过程中是如何处理订阅的清理和销毁的,所以会省略对于正常值和错误的处理过程,首先来看一下简化后的代码: + +```objectivec +- (RACSignal *)bind:(RACSignalBindBlock (^)(void))block { + return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) { + RACSignalBindBlock bindingBlock = block(); + __block volatile int32_t signalCount = 1; + RACCompoundDisposable *compoundDisposable = [RACCompoundDisposable compoundDisposable]; + + void (^completeSignal)(RACDisposable *) = ... + void (^addSignal)(RACSignal *) = ... + + RACSerialDisposable *selfDisposable = [[RACSerialDisposable alloc] init]; + [compoundDisposable addDisposable:selfDisposable]; + RACDisposable *bindingDisposable = [self subscribeNext:^(id x) { + BOOL stop = NO; + id signal = bindingBlock(x, &stop); + + if (signal != nil) addSignal(signal); + if (signal == nil || stop) { + [selfDisposable dispose]; + completeSignal(selfDisposable); + } + } completed:^{ + completeSignal(selfDisposable); + }]; + selfDisposable.disposable = bindingDisposable; + return compoundDisposable; + }] setNameWithFormat:@"[%@] -bind:", self.name]; +} +``` + +在简化的代码中,订阅的清理是由一个 `RACCompoundDisposable` 的实例负责的,向这个实例中添加 `RACSerialDisposable` 以及 `RACDisposable` 对象,并在 `RACCompoundDisposable` 销毁时销毁。 + +`completeSignal` 和 `addSignal` 两个 block 主要负责处理新创建信号的清理工作: + +```objectivec +void (^completeSignal)(RACDisposable *) = ^(RACDisposable *finishedDisposable) { + if (OSAtomicDecrement32Barrier(&signalCount) == 0) { + [subscriber sendCompleted]; + [compoundDisposable dispose]; + } else { + [compoundDisposable removeDisposable:finishedDisposable]; + } +}; + +void (^addSignal)(RACSignal *) = ^(RACSignal *signal) { + OSAtomicIncrement32Barrier(&signalCount); + RACSerialDisposable *selfDisposable = [[RACSerialDisposable alloc] init]; + [compoundDisposable addDisposable:selfDisposable]; + RACDisposable *disposable = [signal completed:^{ + completeSignal(selfDisposable); + }]; + selfDisposable.disposable = disposable; +}; +``` + +先通过一个例子来看一下 `-bind:` 方法调用之后,订阅是如何被清理的: + +```objectivec +RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + [subscriber sendNext:@1]; + [subscriber sendNext:@2]; + [subscriber sendCompleted]; + return [RACDisposable disposableWithBlock:^{ + NSLog(@"Original Signal Dispose."); + }]; +}]; +RACSignal *bindSignal = [signal bind:^RACSignalBindBlock _Nonnull{ + return ^(NSNumber *value, BOOL *stop) { + NSNumber *returnValue = @(value.integerValue); + return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { + for (NSInteger i = 0; i < value.integerValue; i++) [subscriber sendNext:returnValue]; + [subscriber sendCompleted]; + return [RACDisposable disposableWithBlock:^{ + NSLog(@"Binding Signal Dispose."); + }]; + }]; + }; +}]; +[bindSignal subscribeNext:^(id _Nullable x) { + NSLog(@"%@", x); +}]; +``` + +在每个订阅创建以及所有的值发送之后,订阅就会被就地销毁,调用 `disposeBlock`,并从 `RACCompoundDisposable` 实例中移除: + +```objectivec +1 +Binding Signal Dispose. +2 +2 +Binding Signal Dispose. +Original Signal Dispose. +``` + +原订阅的销毁时间以及绑定信号的控制是由 `SignalCount` 控制的,其表示 `RACCompoundDisposable` 中的 `RACSerialDisposable` 实例的个数,在每次有新的订阅被创建时都会向 `RACCompoundDisposable` 加入一个新的 `RACSerialDisposable`,并在订阅发送结束时从数组中移除,整个过程用图示来表示比较清晰: + +![RACSignal-Bind-Disposable](./images/RACSignal/RACSignal-Bind-Disposable.png) + +> 紫色的 `RACSerialDisposable` 为原订阅创建的对象,灰色的为新信号订阅的对象。 + +## 总结 + +这是整个 ReactiveCocoa 源代码分析系列文章的第一篇,想写一个跟这个系列有关的代码已经很久了,文章中对于 `RACSignal` 进行了一些简单的介绍,项目中绝大多数的方法都是很简洁的,行数并不多,代码的组织方式也很易于理解。虽然没有太多让人意外的东西,不过整个工程还是很值得阅读的。 + +## References + ++ [A Fistful of Monads](http://learnyouahaskell.com/a-fistful-of-monads) ++ [What is (functional) reactive programming?](http://stackoverflow.com/questions/1028250/what-is-functional-reactive-programming/1030631#1030631) + +## 方法实现对照表 + +| 方法 | 实现 | +| :-: | :-: | +| `+return:` | [RACSignal.m#L89-L91](https://github.com/ReactiveCocoa/ReactiveObjC/blob/1180ab256000573ef82141e5d40e9b9c35dfd69c/ReactiveObjC/RACSignal.m#L89-L91)| +|  `-bind:` | [RACSignal.m#L93-176](https://github.com/ReactiveCocoa/ReactiveObjC/blob/1180ab256000573ef82141e5d40e9b9c35dfd69c/ReactiveObjC/RACSignal.m#L93-L176) | + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/racsignal + + diff --git a/contents/ReactiveObjC/RACSubject.md b/contents/ReactiveObjC/RACSubject.md new file mode 100644 index 0000000..ae49c42 --- /dev/null +++ b/contents/ReactiveObjC/RACSubject.md @@ -0,0 +1,430 @@ +# 『可变』的热信号 RACSubject + +在 ReactiveCocoa 中除了不可变的信号 `RACSignal`,也有用于桥接非 RAC 代码到 ReactiveCocoa 世界的『可变』信号 `RACSubject`。 + +![“Mutable” RACSignal — RACSubject](images/RACSubject/%E2%80%9CMutable%E2%80%9D%20RACSignal%20%E2%80%94%20RACSubject.png) + +`RACSubject` 到底是什么?根据其字面意思,可以将它理解为一个可以订阅的主题,我们在订阅主题之后,向主题发送新的消息时,**所有**的订阅者都会接收到最新的消息。 + +但是这么解释确实有点晦涩,也不易于理解,ReactiveCocoa 团队对 `RACSubject` 的解释是,`RACSubject` 其实就是一个可以**手动**控制的信号(感觉这么解释更难理解了)。 + +> A subject, represented by the RACSubject class, is a signal that can be manually controlled. + +## RACSubject 简介 + +`RACSubject` 是 `RACSignal` 的子类,与 `RACSignal` 以及 `RACSequence` 有着众多的类簇不同,`RACSubject` 在整个工程中并没有多少子类;不过,在大多数情况下,我们也只会使用 `RACSubject` 自己或者 `RACReplaySubject`。 + +![RACSubject - Subclasses](images/RACSubject/RACSubject%20-%20Subclasses.png) + +相比于 `RACSignal` 丰富的头文件 ,`RACSubject` 对外的接口并没有提供太多的方法: + +```objectivec +@interface RACSubject : RACSignal <RACSubscriber> + ++ (instancetype)subject; + +@end +``` + +唯一提供的接口就是用于返回一个新实例的 `+subject` 方法;除此之外,在笔者看来它与 `RACSignal` 最大的不同就是:`RACSubject` 实现了 `RACSubscriber` 协议,也就是下面的这些方法: + +```objectivec +@protocol RACSubscriber <NSObject> +@required + +- (void)sendNext:(nullable id)value; +- (void)sendError:(nullable NSError *)error; +- (void)sendCompleted; +- (void)didSubscribeWithDisposable:(RACCompoundDisposable *)disposable; + +@end +``` + +我们并不能在一个 `RACSignal` 对象上执行这些方法,只能在创建信号的 block 里面向遵循 `RACSubscriber` 协议的对象发送新的值或者错误,这也是 `RACSubject` 和父类最大的不同:在 `RACSubject` 实例初始化之后,也可以通过这个实例向所有的订阅者发送消息。 + +## 冷信号与热信号 + +提到 `RACSubject` 就不得不提 ReactiveCocoa 中的另一对概念,冷信号和热信号。 + +> 其实解释这两者之间区别的文章已经很多了,我相信各位读者能找到很多的资料,在这里就简单介绍一下冷热信号的概念,如果想要了解更多的内容可以在 [References](#references) 中找到更多的文章。 + +对于冷热信号概念,我们借用 Rx 中的描述: + +![Hot-Signal-And-Cold-Signa](images/RACSubject/Hot-Signal-And-Cold-Signal.png) + +> Cold signal is sequences that are passive and start producing notifications on request (when subscribed to), and hot signal is sequences that are active and produce notifications regardless of subscriptions. ---- [Hot and Cold observables](http://www.introtorx.com/content/v1.0.10621.0/14_HotAndColdObservables.html) + +冷信号是被动的,只会在被订阅时向订阅者发送通知;热信号是主动的,它会在任意时间发出通知,与订阅者的订阅时间无关。 + +也就是说冷信号所有的订阅者会在订阅时收到完全相同的序列;而订阅热信号之后,只会收到在订阅之后发出的序列。 + +> 热信号的订阅者能否收到消息取决于订阅的时间。 + +热信号在我们生活中有很多的例子,比如订阅杂志时并不会把之前所有的期刊都送到我们手中,只会接收到订阅之后的期刊;而对于冷信号的话,举一个不恰当的例子,每一年的高考考生在『订阅』高考之后,收到往年所有的试卷,并在高考之后会取消订阅。 + +## 热信号 RACSubject + +在 ReactiveCocoa 中,我们使用 `RACSignal` 来表示冷信号,也就是每一个订阅者在订阅信号时都会收到完整的序列;`RACSubject` 用于表示热信号,订阅者接收到多少值取决于它订阅的时间。 + +前面的文章中已经对 `RACSignal` 冷信号有了很多的介绍,这里也就不会多说了;这一小节主要的内容是想通过一个例子,简单展示 `RACSubject` 的订阅者收到的内容与订阅时间的关系: + +```objectivec +RACSubject *subject = [RACSubject subject]; + +// Subscriber 1 +[subject subscribeNext:^(id _Nullable x) { + NSLog(@"1st Sub: %@", x); +}]; +[subject sendNext:@1]; + +// Subscriber 2 +[subject subscribeNext:^(id _Nullable x) { + NSLog(@"2nd Sub: %@", x); +}]; +[subject sendNext:@2]; + +// Subscriber 3 +[subject subscribeNext:^(id _Nullable x) { + NSLog(@"3rd Sub: %@", x); +}]; +[subject sendNext:@3]; +[subject sendCompleted]; +``` + +这里以图的方式来展示整个订阅与订阅者接收消息的过程: + +![Track-RACSubject-Subscription-Process](images/RACSubject/Track-RACSubject-Subscription-Process.png) + +从图中我们可以清楚的看到,几个订阅者根据**订阅时间**的不同收到了不同的数字序列,`RACSubject` 是**时间相关**的,它在发送消息时只会向已订阅的订阅者推送消息。 + +## RACSubject 的实现 + +`RACSubject` 的实现并不复杂,它『可变』的特性都来源于持有的订阅者数组 `subscribers`,在每次执行 `subscribeNext:error:completed:` 一类便利方法时,都会将传入的 `id<RACSubscriber>` 对象加入数组: + +```objectivec +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable]; + subscriber = [[RACPassthroughSubscriber alloc] initWithSubscriber:subscriber signal:self disposable:disposable]; + + NSMutableArray *subscribers = self.subscribers; + @synchronized (subscribers) { + [subscribers addObject:subscriber]; + } + + [disposable addDisposable:[RACDisposable disposableWithBlock:^{ + @synchronized (subscribers) { + NSUInteger index = [subscribers indexOfObjectWithOptions:NSEnumerationReverse passingTest:^ BOOL (id<RACSubscriber> obj, NSUInteger index, BOOL *stop) { + return obj == subscriber; + }]; + + if (index != NSNotFound) [subscribers removeObjectAtIndex:index]; + } + }]]; + + return disposable; +} +``` + +订阅的过程分为三个部分: + +1. 初始化一个 `RACPassthroughSubscriber` 实例; +2. 将 `subscriber` 加入 `RACSubject` 持有的数组中; +3. 创建一个 `RACDisposable` 对象,在当前 `subscriber` 销毁时,将自身从数组中移除。 + +![Send-Subscibe-to-RACSubject](images/RACSubject/Send-Subscibe-to-RACSubject.png) + +`-subscribe:` 将所有遵循 `RACSubscriber` 协议的对象全部加入当前 `RACSubject` 持有的数组 `subscribers` 中。 + +在上一节的例子中,我们能对 `RACSubject` 发送 `-sendNext:` 等消息也都取决于它实现了 `RACSubscriber` 协议: + +```objectivec +- (void)sendNext:(id)value { + [self enumerateSubscribersUsingBlock:^(id<RACSubscriber> subscriber) { + [subscriber sendNext:value]; + }]; +} + +- (void)sendError:(NSError *)error { + [self.disposable dispose]; + + [self enumerateSubscribersUsingBlock:^(id<RACSubscriber> subscriber) { + [subscriber sendError:error]; + }]; +} + +- (void)sendCompleted { + [self.disposable dispose]; + + [self enumerateSubscribersUsingBlock:^(id<RACSubscriber> subscriber) { + [subscriber sendCompleted]; + }]; +} +``` + +`RACSubject` 会在自身接受到这些方法时,下发给持有的全部的 `subscribers`。 + +![Send-Messages-to-RACSubject](images/RACSubject/Send-Messages-to-RACSubject.png) + +代码中的 `-enumerateSubscribersUsingBlock:` 只是一个使用 `for` 循环遍历 `subscribers` 的安全方法: + +```objectivec +- (void)enumerateSubscribersUsingBlock:(void (^)(id<RACSubscriber> subscriber))block { + NSArray *subscribers; + @synchronized (self.subscribers) { + subscribers = [self.subscribers copy]; + } + + for (id<RACSubscriber> subscriber in subscribers) { + block(subscriber); + } +} +``` + +`RACSubject` 就是围绕一个 `NSMutableArray` 数组实现的,实现还是非常简单的,只是在需要访问 `subscribers` 的方法中使用 `@synchronized` 避免线程竞争。 + +```objectivec +@interface RACSubject () + +@property (nonatomic, strong, readonly) NSMutableArray *subscribers; + +@end +``` + +`RACSubject` 提供的初始化类方法 `+subject` 也只是初始化了几个成员变量: + +```objectivec ++ (instancetype)subject { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (self == nil) return nil; + + _disposable = [RACCompoundDisposable compoundDisposable]; + _subscribers = [[NSMutableArray alloc] initWithCapacity:1]; + + return self; +} +``` + +至此,对于 `RACSubject` 的分析就结束了,接下来会分析更多的子类。 + +## RACBehaviorSubject 与 RACReplaySubject + +这一节会介绍 `RACSubject` 的两个子类 `RACBehaviorSubject` 和 `RACReplaySubject`,前者在订阅时会向订阅者发送最新的消息,后者在订阅之后**可以**重新发送之前的**所有**消息序列。 + +### RACBehaviorSubject + +先来介绍两者中实现较简单的 `RACBehaviorSubject`,它在内部会保存一个 `currentValue` 对象,也就是最后一次发送的消息: + +```objectivec +@interface RACBehaviorSubject () + +@property (nonatomic, strong) id currentValue; + +@end +``` + +在每次执行 `-sendNext:` 时,都会对 `RACBehaviorSubject` 中保存的 `currentValue` 进行更新,并使用父类的 `-sendNext:` 方法,向所有的订阅者发送最新的消息: + +```objectivec +- (void)sendNext:(id)value { + @synchronized (self) { + self.currentValue = value; + [super sendNext:value]; + } +} +``` + +`RACBehaviorSubject` 最重要的特性就是在订阅时,向最新的订阅者发送之前的消息,这是通过覆写 `-subscribe:` 方法实现的。 + +在调用子类的 `-subscribe:` 方法之后,会在 `subscriber` 对象上执行 `-sendNext:` 方法: + +```objectivec +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + RACDisposable *subscriptionDisposable = [super subscribe:subscriber]; + + RACDisposable *schedulingDisposable = [RACScheduler.subscriptionScheduler schedule:^{ + @synchronized (self) { + [subscriber sendNext:self.currentValue]; + } + }]; + + return [RACDisposable disposableWithBlock:^{ + [subscriptionDisposable dispose]; + [schedulingDisposable dispose]; + }]; +} +``` + +接下来,通过一个简单的例子来演示 `RACBehaviorSubject` 到底是如何工作的: + +```objectivec +RACBehaviorSubject *subject = [RACBehaviorSubject subject]; + +[subject subscribeNext:^(id _Nullable x) { + NSLog(@"1st Sub: %@", x); +}]; +[subject sendNext:@1]; + +[subject subscribeNext:^(id _Nullable x) { + NSLog(@"2nd Sub: %@", x); +}]; +[subject sendNext:@2]; + +[subject subscribeNext:^(id _Nullable x) { + NSLog(@"3rd Sub: %@", x); +}]; +[subject sendNext:@3]; +[subject sendCompleted]; +``` + +上面的代码其实与 `RACSubject` 一节中的代码差不多,只将 `RACSubject` 转换成了 `RACBehaviorSubject` 对象。 + +![Track-RACBehaviorSubject-Subscription-Process](images/RACSubject/Track-RACBehaviorSubject-Subscription-Process.png) + +在每次订阅者订阅 `RACBehaviorSubject` 之后,都会向该订阅者发送**最新**的消息,这也就是 `RACBehaviorSubject` 最重要的行为。 + +`RACBehaviorSubject` 有一个用于创建包含默认值的类方法 `+behaviorSubjectWithDefaultValue:`,如果将上面的第一行代码改成: + +```objectivec +RACBehaviorSubject *subject = [RACBehaviorSubject behaviorSubjectWithDefaultValue:@0]; +``` + +那么在第一个订阅者刚订阅 `RACBehaviorSubject` 时就会收到 `@0` 对象。 + +![Track-RACBehaviorSubject-Subscription-Process-With-Default-Value](images/RACSubject/Track-RACBehaviorSubject-Subscription-Process-With-Default-Value.png) + +### RACReplaySubject + +`RACReplaySubject` 相当于一个自带 `buffer` 的 `RACBehaviorSubject`,它可以在每次有新的订阅者订阅之后发送之前的全部消息。 + +```objectivec +@interface RACReplaySubject () + +@property (nonatomic, assign, readonly) NSUInteger capacity; +@property (nonatomic, strong, readonly) NSMutableArray *valuesReceived; + +@end +``` + +实现的方式是通过持有一个 `valuesReceived` 的数组和能够存储的对象的上限 `capacity`,默认值为: + +```objectivec +const NSUInteger RACReplaySubjectUnlimitedCapacity = NSUIntegerMax; +``` + +当然你可以用 `+replaySubjectWithCapacity:` 初始化一个其它大小的 `RACReplaySubject` 对象: + +```objectivec ++ (instancetype)replaySubjectWithCapacity:(NSUInteger)capacity { + return [(RACReplaySubject *)[self alloc] initWithCapacity:capacity]; +} + +- (instancetype)initWithCapacity:(NSUInteger)capacity { + self = [super init]; + + _capacity = capacity; + _valuesReceived = (capacity == RACReplaySubjectUnlimitedCapacity ? [NSMutableArray array] : [NSMutableArray arrayWithCapacity:capacity]); + + return self; +} +``` + +在每次调用 `-sendNext:` 方法发送消息时,都会将其加入 `valuesReceived` 数组中,并踢出之前的元素: + +```objectivec +- (void)sendNext:(id)value { + @synchronized (self) { + [self.valuesReceived addObject:value ?: RACTupleNil.tupleNil]; + [super sendNext:value]; + + if (self.capacity != RACReplaySubjectUnlimitedCapacity && self.valuesReceived.count > self.capacity) { + [self.valuesReceived removeObjectsInRange:NSMakeRange(0, self.valuesReceived.count - self.capacity)]; + } + } +} +``` + +需要注意的有两点,一是对 `valuesReceived` 的数组的操作必须使用 `@synchronized` 加锁;第二,如果 `value` 为空的话,也需要将其转换成 `RACTupleNil.tupleNil` 对象进行保存。 + +![Send-Messages-to-RACReplaySubject](images/RACSubject/Send-Messages-to-RACReplaySubject.png) + +`-sendError:` 和 `-sendCompleted` 方法都会标记对应 `flag`,即 `hasCompleted` 和 `hasError`,这里就不介绍了;同样的,`RACReplaySubject` 也覆写了 `-subscribe:` 方法,在每次有订阅者订阅时重新发送所有的序列: + +```objectivec +- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber { + RACCompoundDisposable *compoundDisposable = [RACCompoundDisposable compoundDisposable]; + + RACDisposable *schedulingDisposable = [RACScheduler.subscriptionScheduler schedule:^{ + @synchronized (self) { + for (id value in self.valuesReceived) { + if (compoundDisposable.disposed) return; + + [subscriber sendNext:(value == RACTupleNil.tupleNil ? nil : value)]; + } + + if (compoundDisposable.disposed) return; + + if (self.hasCompleted) { + [subscriber sendCompleted]; + } else if (self.hasError) { + [subscriber sendError:self.error]; + } else { + RACDisposable *subscriptionDisposable = [super subscribe:subscriber]; + [compoundDisposable addDisposable:subscriptionDisposable]; + } + } + }]; + + [compoundDisposable addDisposable:schedulingDisposable]; + + return compoundDisposable; +} +``` + +我们仍然使用上一节中的例子来展示 `RACReplaySubject` 是如何工作的,只修改第一行代码: + +```objectivec +RACReplaySubject *subject = [RACReplaySubject subject]; + +[subject subscribeNext:^(id _Nullable x) { + NSLog(@"1st Subscriber: %@", x); +}]; +[subject sendNext:@1]; + +[subject subscribeNext:^(id _Nullable x) { + NSLog(@"2nd Subscriber: %@", x); +}]; +[subject sendNext:@2]; + +[subject subscribeNext:^(id _Nullable x) { + NSLog(@"3rd Subscriber: %@", x); +}]; +[subject sendNext:@3]; +[subject sendCompleted]; +``` + +运行这段代码之后,会得到如下图的结果: + +![Track-RACReplaySubject-Subscription-Process](images/RACSubject/Track-RACReplaySubject-Subscription-Process.png) + +所有订阅 `RACReplaySubject` 的对象(默认行为)都能获得完整的序列,而这个特性在与 `RACMulticastConnection` 一起使用也有着巨大威力,我们会在之后的文章中介绍。 + +## 总结 + +`RACSubject` 在 `RACSignal` 对象之上进行了简单的修改,将原有的冷信号改造成了热信号,将不可变变成了可变。 + +虽然 `RACSubject` 的实现并不复杂,只是存储了一个遵循 `RACSubscriber` 协议的对象列表以及所有的消息,但是在解决实际问题时却能够很好地解决很多与网络操作相关的问题。 + +## References + ++ [细说 ReactiveCocoa 的冷信号与热信号](http://williamzang.com/blog/2015/08/18/talk-about-reactivecocoas-cold-signal-and-hot-signal/) ++ [Hot and Cold observables](http://www.introtorx.com/content/v1.0.10621.0/14_HotAndColdObservables.html) + +> Github Repo:[iOS-Source-Code-Analyze](https://github.com/draveness/iOS-Source-Code-Analyze) +> +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/racsubject diff --git a/contents/ReactiveObjC/images/RACChannel/Channel-And-Network-Connection.png b/contents/ReactiveObjC/images/RACChannel/Channel-And-Network-Connection.png new file mode 100644 index 0000000..0188009 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/Channel-And-Network-Connection.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/Connection-Between-View-Model.png b/contents/ReactiveObjC/images/RACChannel/Connection-Between-View-Model.png new file mode 100644 index 0000000..f1e612c Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/Connection-Between-View-Model.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/English-Channel-banner.jpg b/contents/ReactiveObjC/images/RACChannel/English-Channel-banner.jpg new file mode 100644 index 0000000..406e692 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/English-Channel-banner.jpg differ diff --git a/contents/ReactiveObjC/images/RACChannel/Messages-Send-From-Model.png b/contents/ReactiveObjC/images/RACChannel/Messages-Send-From-Model.png new file mode 100644 index 0000000..3ac1159 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/Messages-Send-From-Model.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/RACChannel-Hierachy.png b/contents/ReactiveObjC/images/RACChannel/RACChannel-Hierachy.png new file mode 100644 index 0000000..0df96d8 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/RACChannel-Hierachy.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/RACChannel-Interface.png b/contents/ReactiveObjC/images/RACChannel/RACChannel-Interface.png new file mode 100644 index 0000000..a4bb7a3 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/RACChannel-Interface.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/RACChannelTerminal-Interface.png b/contents/ReactiveObjC/images/RACChannel/RACChannelTerminal-Interface.png new file mode 100644 index 0000000..c1392e9 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/RACChannelTerminal-Interface.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/RACChannelTo-And-Property.png b/contents/ReactiveObjC/images/RACChannel/RACChannelTo-And-Property.png new file mode 100644 index 0000000..f4a765a Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/RACChannelTo-And-Property.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/RACChannelTo-Model-View.png b/contents/ReactiveObjC/images/RACChannel/RACChannelTo-Model-View.png new file mode 100644 index 0000000..da3055c Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/RACChannelTo-Model-View.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/RACKVOChannel.png b/contents/ReactiveObjC/images/RACChannel/RACKVOChannel.png new file mode 100644 index 0000000..28022fa Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/RACKVOChannel.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/Sending-Errors-And-Completed-Messages.png b/contents/ReactiveObjC/images/RACChannel/Sending-Errors-And-Completed-Messages.png new file mode 100644 index 0000000..411b2ba Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/Sending-Errors-And-Completed-Messages.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/Terminals-Between-View-Model.png b/contents/ReactiveObjC/images/RACChannel/Terminals-Between-View-Model.png new file mode 100644 index 0000000..6e31cd9 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/Terminals-Between-View-Model.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/TextField-With-Channel.gif b/contents/ReactiveObjC/images/RACChannel/TextField-With-Channel.gif new file mode 100644 index 0000000..0d93980 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/TextField-With-Channel.gif differ diff --git a/contents/ReactiveObjC/images/RACChannel/Two-UITextField-With-RACChannel.png b/contents/ReactiveObjC/images/RACChannel/Two-UITextField-With-RACChannel.png new file mode 100644 index 0000000..d2d8ec4 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/Two-UITextField-With-RACChannel.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/UITextField-RACChannel-Interface.png b/contents/ReactiveObjC/images/RACChannel/UITextField-RACChannel-Interface.png new file mode 100644 index 0000000..267cd65 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/UITextField-RACChannel-Interface.png differ diff --git a/contents/ReactiveObjC/images/RACChannel/What-is-RACChannel.png b/contents/ReactiveObjC/images/RACChannel/What-is-RACChannel.png new file mode 100644 index 0000000..2740c14 Binary files /dev/null and b/contents/ReactiveObjC/images/RACChannel/What-is-RACChannel.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/Errors-Signals.png b/contents/ReactiveObjC/images/RACCommand/Errors-Signals.png new file mode 100644 index 0000000..94b106a Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/Errors-Signals.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/Execute-For-RACCommand.png b/contents/ReactiveObjC/images/RACCommand/Execute-For-RACCommand.png new file mode 100644 index 0000000..a1cd88f Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/Execute-For-RACCommand.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/Execute-on-RACCommand.png b/contents/ReactiveObjC/images/RACCommand/Execute-on-RACCommand.png new file mode 100644 index 0000000..deddaf2 Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/Execute-on-RACCommand.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/Executing-Signal.png b/contents/ReactiveObjC/images/RACCommand/Executing-Signal.png new file mode 100644 index 0000000..a7ee1d1 Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/Executing-Signal.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/Execution-Signals.png b/contents/ReactiveObjC/images/RACCommand/Execution-Signals.png new file mode 100644 index 0000000..550eccb Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/Execution-Signals.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/Immediate-Enabled-Signal.png b/contents/ReactiveObjC/images/RACCommand/Immediate-Enabled-Signal.png new file mode 100644 index 0000000..bd6e057 Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/Immediate-Enabled-Signal.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/Interact-Between-UI-And-RACCommand.png b/contents/ReactiveObjC/images/RACCommand/Interact-Between-UI-And-RACCommand.png new file mode 100644 index 0000000..2c9c289 Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/Interact-Between-UI-And-RACCommand.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/MoreExecutionAllowed-Signal.png b/contents/ReactiveObjC/images/RACCommand/MoreExecutionAllowed-Signal.png new file mode 100644 index 0000000..ebb0a7d Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/MoreExecutionAllowed-Signal.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/Multiple-Executes.png b/contents/ReactiveObjC/images/RACCommand/Multiple-Executes.png new file mode 100644 index 0000000..6902084 Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/Multiple-Executes.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/RACCommand-Interface.png b/contents/ReactiveObjC/images/RACCommand/RACCommand-Interface.png new file mode 100644 index 0000000..7d9f94d Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/RACCommand-Interface.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/RACCommand-Side-Effect.png b/contents/ReactiveObjC/images/RACCommand/RACCommand-Side-Effect.png new file mode 100644 index 0000000..cf91aa0 Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/RACCommand-Side-Effect.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/What-is-RACCommand.png b/contents/ReactiveObjC/images/RACCommand/What-is-RACCommand.png new file mode 100644 index 0000000..2c9c289 Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/What-is-RACCommand.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/immediateExecuting-Signal-in-RACCommand.png b/contents/ReactiveObjC/images/RACCommand/immediateExecuting-Signal-in-RACCommand.png new file mode 100644 index 0000000..9a34a90 Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/immediateExecuting-Signal-in-RACCommand.png differ diff --git a/contents/ReactiveObjC/images/RACCommand/raccommad-cover.jpg b/contents/ReactiveObjC/images/RACCommand/raccommad-cover.jpg new file mode 100644 index 0000000..dc011fe Binary files /dev/null and b/contents/ReactiveObjC/images/RACCommand/raccommad-cover.jpg differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/After-Call-RACSignalForSelector.png b/contents/ReactiveObjC/images/RACDelegateProxy/After-Call-RACSignalForSelector.png new file mode 100644 index 0000000..96de284 Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/After-Call-RACSignalForSelector.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/Delegate-To-RACSignal.png b/contents/ReactiveObjC/images/RACDelegateProxy/Delegate-To-RACSignal.png new file mode 100644 index 0000000..928c83e Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/Delegate-To-RACSignal.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/Message-Forwarding.png b/contents/ReactiveObjC/images/RACDelegateProxy/Message-Forwarding.png new file mode 100644 index 0000000..bf823af Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/Message-Forwarding.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/NSObjectRACSignalForSelector.png b/contents/ReactiveObjC/images/RACDelegateProxy/NSObjectRACSignalForSelector.png new file mode 100644 index 0000000..ebab3c7 Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/NSObjectRACSignalForSelector.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/RACDelegateProxy-UITableView.gif b/contents/ReactiveObjC/images/RACDelegateProxy/RACDelegateProxy-UITableView.gif new file mode 100644 index 0000000..e28a316 Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/RACDelegateProxy-UITableView.gif differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/RACDelegateProxy.png b/contents/ReactiveObjC/images/RACDelegateProxy/RACDelegateProxy.png new file mode 100644 index 0000000..b45d90e Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/RACDelegateProxy.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/Selector-To-IMP.png b/contents/ReactiveObjC/images/RACDelegateProxy/Selector-To-IMP.png new file mode 100644 index 0000000..4609dc1 Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/Selector-To-IMP.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/Selector-To-ObjC-Message-Forward-With-RACSelector.png b/contents/ReactiveObjC/images/RACDelegateProxy/Selector-To-ObjC-Message-Forward-With-RACSelector.png new file mode 100644 index 0000000..69520a3 Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/Selector-To-ObjC-Message-Forward-With-RACSelector.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/Selector-To-ObjC-Message-Forward.png b/contents/ReactiveObjC/images/RACDelegateProxy/Selector-To-ObjC-Message-Forward.png new file mode 100644 index 0000000..5368ac9 Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/Selector-To-ObjC-Message-Forward.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/Swizzle-objc_msgForward.png b/contents/ReactiveObjC/images/RACDelegateProxy/Swizzle-objc_msgForward.png new file mode 100644 index 0000000..f3146fc Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/Swizzle-objc_msgForward.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/TypeEncoding.png b/contents/ReactiveObjC/images/RACDelegateProxy/TypeEncoding.png new file mode 100644 index 0000000..76571e2 Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/TypeEncoding.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/UITableViewDelegate-With-RACDelegateProxy.png b/contents/ReactiveObjC/images/RACDelegateProxy/UITableViewDelegate-With-RACDelegateProxy.png new file mode 100644 index 0000000..d401eb2 Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/UITableViewDelegate-With-RACDelegateProxy.png differ diff --git a/contents/ReactiveObjC/images/RACDelegateProxy/delegate-banner.jpg b/contents/ReactiveObjC/images/RACDelegateProxy/delegate-banner.jpg new file mode 100644 index 0000000..7c68144 Binary files /dev/null and b/contents/ReactiveObjC/images/RACDelegateProxy/delegate-banner.jpg differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/Difference-Between-Replay-Methods.png b/contents/ReactiveObjC/images/RACMulticastConnection/Difference-Between-Replay-Methods.png new file mode 100644 index 0000000..8fb44f8 Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/Difference-Between-Replay-Methods.png differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/RACMulticastConnection-Interface.png b/contents/ReactiveObjC/images/RACMulticastConnection/RACMulticastConnection-Interface.png new file mode 100644 index 0000000..8b5ea3c Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/RACMulticastConnection-Interface.png differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/RACMulticastConnection.png b/contents/ReactiveObjC/images/RACMulticastConnection/RACMulticastConnection.png new file mode 100644 index 0000000..78fc92f Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/RACMulticastConnection.png differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/RACSignal-And-Subscribe.png b/contents/ReactiveObjC/images/RACMulticastConnection/RACSignal-And-Subscribe.png new file mode 100644 index 0000000..b46d82a Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/RACSignal-And-Subscribe.png differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/RACSignal-RACMulticastConnection-Connect.png b/contents/ReactiveObjC/images/RACMulticastConnection/RACSignal-RACMulticastConnection-Connect.png new file mode 100644 index 0000000..034ac13 Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/RACSignal-RACMulticastConnection-Connect.png differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/RACSubject - Subclasses.png b/contents/ReactiveObjC/images/RACMulticastConnection/RACSubject - Subclasses.png new file mode 100644 index 0000000..4dfe482 Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/RACSubject - Subclasses.png differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/SubscribeNext-To-RACSubject-Before-Connect.png b/contents/ReactiveObjC/images/RACMulticastConnection/SubscribeNext-To-RACSubject-Before-Connect.png new file mode 100644 index 0000000..dc1a540 Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/SubscribeNext-To-RACSubject-Before-Connect.png differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/Values-From-RACSignal-To-Subscribers.png b/contents/ReactiveObjC/images/RACMulticastConnection/Values-From-RACSignal-To-Subscribers.png new file mode 100644 index 0000000..5eea888 Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/Values-From-RACSignal-To-Subscribers.png differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/connection-banner.jpg b/contents/ReactiveObjC/images/RACMulticastConnection/connection-banner.jpg new file mode 100644 index 0000000..c995135 Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/connection-banner.jpg differ diff --git a/contents/ReactiveObjC/images/RACMulticastConnection/publish-and-multicast.png b/contents/ReactiveObjC/images/RACMulticastConnection/publish-and-multicast.png new file mode 100644 index 0000000..ab78439 Binary files /dev/null and b/contents/ReactiveObjC/images/RACMulticastConnection/publish-and-multicast.png differ diff --git a/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Initializers.png b/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Initializers.png new file mode 100644 index 0000000..bc824d4 Binary files /dev/null and b/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Initializers.png differ diff --git a/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Priority.png b/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Priority.png new file mode 100644 index 0000000..e6f1a63 Binary files /dev/null and b/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Priority.png differ diff --git a/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Schedule.png b/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Schedule.png new file mode 100644 index 0000000..e7bb551 Binary files /dev/null and b/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Schedule.png differ diff --git a/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Subclasses.png b/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Subclasses.png new file mode 100644 index 0000000..07a37dd Binary files /dev/null and b/contents/ReactiveObjC/images/RACScheduler/RACScheduler-Subclasses.png differ diff --git a/contents/ReactiveObjC/images/RACScheduler/RACSubscriptionScheduler.png b/contents/ReactiveObjC/images/RACScheduler/RACSubscriptionScheduler.png new file mode 100644 index 0000000..3a4ee7b Binary files /dev/null and b/contents/ReactiveObjC/images/RACScheduler/RACSubscriptionScheduler.png differ diff --git a/contents/ReactiveObjC/images/RACScheduler/RACTargetQueueScheduler.png b/contents/ReactiveObjC/images/RACScheduler/RACTargetQueueScheduler.png new file mode 100644 index 0000000..510a24a Binary files /dev/null and b/contents/ReactiveObjC/images/RACScheduler/RACTargetQueueScheduler.png differ diff --git a/contents/ReactiveObjC/images/RACScheduler/schedule-header.jpg b/contents/ReactiveObjC/images/RACScheduler/schedule-header.jpg new file mode 100644 index 0000000..832d9f3 Binary files /dev/null and b/contents/ReactiveObjC/images/RACScheduler/schedule-header.jpg differ diff --git a/contents/ReactiveObjC/images/RACSequence/Call-Stacks-of-FoldLeft-FoldRight.png b/contents/ReactiveObjC/images/RACSequence/Call-Stacks-of-FoldLeft-FoldRight.png new file mode 100644 index 0000000..7407147 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/Call-Stacks-of-FoldLeft-FoldRight.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/EagerSequence - LazySequence.png b/contents/ReactiveObjC/images/RACSequence/EagerSequence - LazySequence.png new file mode 100644 index 0000000..62dd798 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/EagerSequence - LazySequence.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/FoldLeft - FoldRight.png b/contents/ReactiveObjC/images/RACSequence/FoldLeft - FoldRight.png new file mode 100644 index 0000000..d42eaae Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/FoldLeft - FoldRight.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/List-and-Stream.png b/contents/ReactiveObjC/images/RACSequence/List-and-Stream.png new file mode 100644 index 0000000..a257588 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/List-and-Stream.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/RACSequence - Subclasses.png b/contents/ReactiveObjC/images/RACSequence/RACSequence - Subclasses.png new file mode 100644 index 0000000..7654797 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/RACSequence - Subclasses.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/RACSequence-Instance.png b/contents/ReactiveObjC/images/RACSequence/RACSequence-Instance.png new file mode 100644 index 0000000..7db1a98 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/RACSequence-Instance.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/RACSequence-Status-Before-And-After-Executed.png b/contents/ReactiveObjC/images/RACSequence/RACSequence-Status-Before-And-After-Executed.png new file mode 100644 index 0000000..fbd0f76 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/RACSequence-Status-Before-And-After-Executed.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/RACSignal - RACSequence.png b/contents/ReactiveObjC/images/RACSequence/RACSignal - RACSequence.png new file mode 100644 index 0000000..a71c218 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/RACSignal - RACSequence.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/RACUnarySequence.png b/contents/ReactiveObjC/images/RACSequence/RACUnarySequence.png new file mode 100644 index 0000000..8003a47 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/RACUnarySequence.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/ReactiveCocoa - RACSequence.png b/contents/ReactiveObjC/images/RACSequence/ReactiveCocoa - RACSequence.png new file mode 100644 index 0000000..eb6d095 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/ReactiveCocoa - RACSequence.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/Transform Between RACSequence - RACSignal.png b/contents/ReactiveObjC/images/RACSequence/Transform Between RACSequence - RACSignal.png new file mode 100644 index 0000000..31e1e5b Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/Transform Between RACSequence - RACSignal.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/Transform RACSignal to RACSequence.png b/contents/ReactiveObjC/images/RACSequence/Transform RACSignal to RACSequence.png new file mode 100644 index 0000000..9860e66 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/Transform RACSignal to RACSequence.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/Transform-RACSequence-To-RACSignal.png b/contents/ReactiveObjC/images/RACSequence/Transform-RACSequence-To-RACSignal.png new file mode 100644 index 0000000..51c1f22 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/Transform-RACSequence-To-RACSignal.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/Unsolved-RACSequence-Instance.png b/contents/ReactiveObjC/images/RACSequence/Unsolved-RACSequence-Instance.png new file mode 100644 index 0000000..f1816c7 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/Unsolved-RACSequence-Instance.png differ diff --git a/contents/ReactiveObjC/images/RACSequence/Usage for RACSignal - RACSequence Copy.png b/contents/ReactiveObjC/images/RACSequence/Usage for RACSignal - RACSequence Copy.png new file mode 100644 index 0000000..0f30630 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSequence/Usage for RACSignal - RACSequence Copy.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/Before-After-Bind-RACSignal-Complicated.png b/contents/ReactiveObjC/images/RACSignal/Before-After-Bind-RACSignal-Complicated.png new file mode 100644 index 0000000..5b7ce28 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/Before-After-Bind-RACSignal-Complicated.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/Before-After-Bind-RACSignal.png b/contents/ReactiveObjC/images/RACSignal/Before-After-Bind-RACSignal.png new file mode 100644 index 0000000..7af5a9a Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/Before-After-Bind-RACSignal.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/Principle-of-Subscribing-Signals.png b/contents/ReactiveObjC/images/RACSignal/Principle-of-Subscribing-Signals.png new file mode 100644 index 0000000..5bb266b Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/Principle-of-Subscribing-Signals.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACCompoundDisposable.png b/contents/ReactiveObjC/images/RACSignal/RACCompoundDisposable.png new file mode 100644 index 0000000..996e6ea Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACCompoundDisposable.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACDisposable-And-Subclasses.png b/contents/ReactiveObjC/images/RACSignal/RACDisposable-And-Subclasses.png new file mode 100644 index 0000000..125cb74 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACDisposable-And-Subclasses.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACDisposable.png b/contents/ReactiveObjC/images/RACSignal/RACDisposable.png new file mode 100644 index 0000000..3b8ab63 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACDisposable.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Banner.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Banner.png new file mode 100644 index 0000000..bf127a9 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Banner.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Bind-Disposable.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Bind-Disposable.png new file mode 100644 index 0000000..f7e6ebe Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Bind-Disposable.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Bind.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Bind.png new file mode 100644 index 0000000..bee3511 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Bind.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Hierachy.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Hierachy.png new file mode 100644 index 0000000..00e8848 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Hierachy.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Instantiate-Object.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Instantiate-Object.png new file mode 100644 index 0000000..9087f60 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Instantiate-Object.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Return.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Return.png new file mode 100644 index 0000000..2d5e90c Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Return.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Subclasses.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Subclasses.png new file mode 100644 index 0000000..d016624 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Subclasses.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Subcribe-Process.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Subcribe-Process.png new file mode 100644 index 0000000..4cc0255 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Subcribe-Process.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Subcription-Messages-Sending.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Subcription-Messages-Sending.png new file mode 100644 index 0000000..677a9e1 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Subcription-Messages-Sending.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACSignal-Subscribe-Methods.png b/contents/ReactiveObjC/images/RACSignal/RACSignal-Subscribe-Methods.png new file mode 100644 index 0000000..e50cf9c Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACSignal-Subscribe-Methods.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACStream-AbstractMethod.png b/contents/ReactiveObjC/images/RACSignal/RACStream-AbstractMethod.png new file mode 100644 index 0000000..f4b332f Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACStream-AbstractMethod.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/RACStream-Operation.png b/contents/ReactiveObjC/images/RACSignal/RACStream-Operation.png new file mode 100644 index 0000000..bd683e8 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/RACStream-Operation.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/What-is-RACSignal.png b/contents/ReactiveObjC/images/RACSignal/What-is-RACSignal.png new file mode 100644 index 0000000..ca16b54 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/What-is-RACSignal.png differ diff --git a/contents/ReactiveObjC/images/RACSignal/out-of-control.jpg b/contents/ReactiveObjC/images/RACSignal/out-of-control.jpg new file mode 100644 index 0000000..870d5fe Binary files /dev/null and b/contents/ReactiveObjC/images/RACSignal/out-of-control.jpg differ diff --git a/contents/ReactiveObjC/images/RACSubject/Hot-Signal-And-Cold-Signal.png b/contents/ReactiveObjC/images/RACSubject/Hot-Signal-And-Cold-Signal.png new file mode 100644 index 0000000..b0c936c Binary files /dev/null and b/contents/ReactiveObjC/images/RACSubject/Hot-Signal-And-Cold-Signal.png differ diff --git a/contents/ReactiveObjC/images/RACSubject/RACSubject - Subclasses.png b/contents/ReactiveObjC/images/RACSubject/RACSubject - Subclasses.png new file mode 100644 index 0000000..4dfe482 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSubject/RACSubject - Subclasses.png differ diff --git a/contents/ReactiveObjC/images/RACSubject/Send-Messages-to-RACReplaySubject.png b/contents/ReactiveObjC/images/RACSubject/Send-Messages-to-RACReplaySubject.png new file mode 100644 index 0000000..5ef54f3 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSubject/Send-Messages-to-RACReplaySubject.png differ diff --git a/contents/ReactiveObjC/images/RACSubject/Send-Messages-to-RACSubject.png b/contents/ReactiveObjC/images/RACSubject/Send-Messages-to-RACSubject.png new file mode 100644 index 0000000..d532538 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSubject/Send-Messages-to-RACSubject.png differ diff --git a/contents/ReactiveObjC/images/RACSubject/Send-Subscibe-to-RACSubject.png b/contents/ReactiveObjC/images/RACSubject/Send-Subscibe-to-RACSubject.png new file mode 100644 index 0000000..cdaf768 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSubject/Send-Subscibe-to-RACSubject.png differ diff --git a/contents/ReactiveObjC/images/RACSubject/Track-RACBehaviorSubject-Subscription-Process-With-Default-Value.png b/contents/ReactiveObjC/images/RACSubject/Track-RACBehaviorSubject-Subscription-Process-With-Default-Value.png new file mode 100644 index 0000000..46c04a7 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSubject/Track-RACBehaviorSubject-Subscription-Process-With-Default-Value.png differ diff --git a/contents/ReactiveObjC/images/RACSubject/Track-RACBehaviorSubject-Subscription-Process.png b/contents/ReactiveObjC/images/RACSubject/Track-RACBehaviorSubject-Subscription-Process.png new file mode 100644 index 0000000..2452ef2 Binary files /dev/null and b/contents/ReactiveObjC/images/RACSubject/Track-RACBehaviorSubject-Subscription-Process.png differ diff --git a/contents/ReactiveObjC/images/RACSubject/Track-RACReplaySubject-Subscription-Process.png b/contents/ReactiveObjC/images/RACSubject/Track-RACReplaySubject-Subscription-Process.png new file mode 100644 index 0000000..b64962e Binary files /dev/null and b/contents/ReactiveObjC/images/RACSubject/Track-RACReplaySubject-Subscription-Process.png differ diff --git a/contents/ReactiveObjC/images/RACSubject/Track-RACSubject-Subscription-Process.png b/contents/ReactiveObjC/images/RACSubject/Track-RACSubject-Subscription-Process.png new file mode 100644 index 0000000..cdf80ea Binary files /dev/null and b/contents/ReactiveObjC/images/RACSubject/Track-RACSubject-Subscription-Process.png differ diff --git "a/contents/ReactiveObjC/images/RACSubject/\342\200\234Mutable\342\200\235 RACSignal \342\200\224 RACSubject.png" "b/contents/ReactiveObjC/images/RACSubject/\342\200\234Mutable\342\200\235 RACSignal \342\200\224 RACSubject.png" new file mode 100644 index 0000000..3a1f4b1 Binary files /dev/null and "b/contents/ReactiveObjC/images/RACSubject/\342\200\234Mutable\342\200\235 RACSignal \342\200\224 RACSubject.png" differ diff --git a/contents/Redis/images/I:O-Multiplexing-Model.png b/contents/Redis/images/I:O-Multiplexing-Model.png new file mode 100644 index 0000000..a1a6d34 Binary files /dev/null and b/contents/Redis/images/I:O-Multiplexing-Model.png differ diff --git a/contents/Redis/images/ae-module.jpg b/contents/Redis/images/ae-module.jpg new file mode 100644 index 0000000..4dad920 Binary files /dev/null and b/contents/Redis/images/ae-module.jpg differ diff --git a/contents/Redis/images/blocking-io.png b/contents/Redis/images/blocking-io.png new file mode 100644 index 0000000..9c84b83 Binary files /dev/null and b/contents/Redis/images/blocking-io.png differ diff --git a/contents/Redis/images/eventloop-file-event-in-redis.png b/contents/Redis/images/eventloop-file-event-in-redis.png new file mode 100644 index 0000000..12b6f35 Binary files /dev/null and b/contents/Redis/images/eventloop-file-event-in-redis.png differ diff --git a/contents/Redis/images/process-end.png b/contents/Redis/images/process-end.png new file mode 100644 index 0000000..b60b559 Binary files /dev/null and b/contents/Redis/images/process-end.png differ diff --git a/contents/Redis/images/process-time-event.png b/contents/Redis/images/process-time-event.png new file mode 100644 index 0000000..da3fbba Binary files /dev/null and b/contents/Redis/images/process-time-event.png differ diff --git a/contents/Redis/images/process-time-events-in-redis.png b/contents/Redis/images/process-time-events-in-redis.png new file mode 100644 index 0000000..de2e7d3 Binary files /dev/null and b/contents/Redis/images/process-time-events-in-redis.png differ diff --git a/contents/Redis/images/redis-choose-io-function.jpg b/contents/Redis/images/redis-choose-io-function.jpg new file mode 100644 index 0000000..8ed15bd Binary files /dev/null and b/contents/Redis/images/redis-choose-io-function.jpg differ diff --git a/contents/Redis/images/redis-cli-banner.jpg b/contents/Redis/images/redis-cli-banner.jpg new file mode 100644 index 0000000..5bc7816 Binary files /dev/null and b/contents/Redis/images/redis-cli-banner.jpg differ diff --git a/contents/Redis/images/redis-client-process-commands.jpg b/contents/Redis/images/redis-client-process-commands.jpg new file mode 100644 index 0000000..16e9ff3 Binary files /dev/null and b/contents/Redis/images/redis-client-process-commands.jpg differ diff --git a/contents/Redis/images/redis-client-server.jpg b/contents/Redis/images/redis-client-server.jpg new file mode 100644 index 0000000..a2f0b6a Binary files /dev/null and b/contents/Redis/images/redis-client-server.jpg differ diff --git a/contents/Redis/images/redis-eventloop-logo.jpg b/contents/Redis/images/redis-eventloop-logo.jpg new file mode 100644 index 0000000..3be5879 Binary files /dev/null and b/contents/Redis/images/redis-eventloop-logo.jpg differ diff --git a/contents/Redis/images/redis-eventloop-proces-event.png b/contents/Redis/images/redis-eventloop-proces-event.png new file mode 100644 index 0000000..36973ba Binary files /dev/null and b/contents/Redis/images/redis-eventloop-proces-event.png differ diff --git a/contents/Redis/images/redis-lldb-cmd.png b/contents/Redis/images/redis-lldb-cmd.png new file mode 100644 index 0000000..0093a1a Binary files /dev/null and b/contents/Redis/images/redis-lldb-cmd.png differ diff --git a/contents/Redis/images/redis-lldb-nwritten.png b/contents/Redis/images/redis-lldb-nwritten.png new file mode 100644 index 0000000..853b2d9 Binary files /dev/null and b/contents/Redis/images/redis-lldb-nwritten.png differ diff --git a/contents/Redis/images/redis-lldb-read.png b/contents/Redis/images/redis-lldb-read.png new file mode 100644 index 0000000..2b21a2f Binary files /dev/null and b/contents/Redis/images/redis-lldb-read.png differ diff --git a/contents/Redis/images/redis-reactor-pattern.png b/contents/Redis/images/redis-reactor-pattern.png new file mode 100644 index 0000000..c4801e8 Binary files /dev/null and b/contents/Redis/images/redis-reactor-pattern.png differ diff --git a/contents/Redis/images/redis-resp-data-byte.jpg b/contents/Redis/images/redis-resp-data-byte.jpg new file mode 100644 index 0000000..1cf432c Binary files /dev/null and b/contents/Redis/images/redis-resp-data-byte.jpg differ diff --git a/contents/Redis/images/redis-resp-type-and-examples.jpg b/contents/Redis/images/redis-resp-type-and-examples.jpg new file mode 100644 index 0000000..da2a89d Binary files /dev/null and b/contents/Redis/images/redis-resp-type-and-examples.jpg differ diff --git a/contents/Redis/images/reids-eventloop.png b/contents/Redis/images/reids-eventloop.png new file mode 100644 index 0000000..e862312 Binary files /dev/null and b/contents/Redis/images/reids-eventloop.png differ diff --git a/contents/Redis/redis-cli.md b/contents/Redis/redis-cli.md new file mode 100644 index 0000000..8015089 --- /dev/null +++ b/contents/Redis/redis-cli.md @@ -0,0 +1,496 @@ +# Redis 是如何处理命令的(客户端) + +在使用 Redis 的过程中经常会好奇,在 Redis-Cli 中键入 `SET KEY MSG` 并回车之后,Redis 客户端和服务是如何对命令进行解析处理的,而在内部的实现过程是什么样的。 + +这两篇文章会分别介绍 Redis 客户端和服务端分别对命令是如何处理的,本篇文章介绍的是 Redis 客户端如何处理输入的命令、向服务发送命令以及取得服务端回复并输出到终端等过程。 + +![redis-client-serve](images/redis-client-server.jpg) + +文章中会将 Redis 服务看做一个输入为 Redis 命令,输出为命令执行结果的黑箱,对从命令到结果的过程不做任何解释,只会着眼于客户端的逻辑,也就是上图中的 1 和 4 两个过程。 + +## 从 main 函数开始 + +与其它的 C 语言框架/服务类似,Redis 的客户端 `redis-cli` 也是从 `main` 函数开始执行的,位于 `redis-cli.c` 文件的最后: + +```c +int main(int argc, char **argv) { + ... + if (argc == 0 && !config.eval) { + repl(); + } + ... +} +``` + +在一般情况下,Redis 客户端都会进入 `repl` 模式,对输入进行解析; + +> Redis 中有好多模式,包括:Latency、Slave、Pipe、Stat、Scan、LRU test 等等模式,不过这些模式都不是这篇文章关注的重点,我们只会关注最常见的 repl 模式。 + +```c +static void repl(void) { + char *line; + int argc; + sds *argv; + + ... + + while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { + if (line[0] != '\0') { + argv = cliSplitArgs(line,&argc); + + if (argv == NULL) { + printf("Invalid argument(s)\n"); + continue; + } + if (strcasecmp(argv[0],"???") == 0) { + ... + } else { + issueCommandRepeat(argc, argv, 1); + } + } + } + exit(0); +} +``` + +在上述代码中,我们省略了大量的实现细节,只保留整个 `repl` 中循环的主体部分,方便进行理解和分析,在 `while` 循环中的条件你可以看到 `linenoise` 方法的调用,通过其中的 `prompt` 和 `not connected> ` 可以判断出,这里向终端中输出了提示符,同时会调用 `fgets` 从标准输入中读取字符串: + +```c +127.0.0.1:6379> +``` + +全局搜一下 `config.prompt` 不难发现这一行代码,也就是控制命令行提示的 `prompt`: + +```c +anetFormatAddr(config.prompt, sizeof(config.prompt),config.hostip, config.hostport); +``` + +接下来执行的 `cliSplitArgs` 函数会将 `line` 中的字符串分割成几个不同的参数,然后根据字符串 `argv[0]` 的不同执行的命令,在这里省略了很多原有的代码: + +```c +if (strcasecmp(argv[0],"quit") == 0 || + strcasecmp(argv[0],"exit") == 0) +{ + exit(0); +} else if (argv[0][0] == ':') { + cliSetPreferences(argv,argc,1); + continue; +} else if (strcasecmp(argv[0],"restart") == 0) { + ... +} else if (argc == 3 && !strcasecmp(argv[0],"connect")) { + ... +} else if (argc == 1 && !strcasecmp(argv[0],"clear")) { +} else { + issueCommandRepeat(argc, argv, 1); +} +``` + +在遇到 `quit`、`exit` 等跟**客户端状态有关的命令**时,就会直接执行相应的代码;否则就会将命令和参数 `issueCommandRepeat` 函数。 + +### 追踪一次命令的执行 + +> Redis Commit: `790310d89460655305bd615bc442eeaf7f0f1b38` +> +> lldb: lldb-360.1.65 +> +> macOS 10.11.6 + +在继续分析 `issueCommandRepeat` 之前,我们先对 Redis 中的这部分代码进行调试追踪,在使用 `make` 编译了 Redis 源代码,启动 `redis-server` 之后;启动 lldb 对 Redis 客户端进行调试: + +```shell +$ lldb src/redis-cli +(lldb) target create "src/redis-cli" +Current executable set to 'src/redis-cli' (x86_64). +(lldb) b redis-cli.c:1290 +Breakpoint 1: where = redis-cli`repl + 228 at redis-cli.c:1290, address = 0x0000000100008cd4 +(lldb) process launch +Process 8063 launched: '~/redis/src/redis-cli' (x86_64) +127.0.0.1:6379> +``` + +在 `redis-cli.c:1290` 也就是下面这行代码的地方打断点之后: + +```c +-> 1290 if (line[0] != '\0') { +``` + +执行 `process launch` 启动 `redis-cli`,然后输入 `SET KEY MSG` 回车以及 Ctrl-C: + +> 在 lldb 中调试时,回车的输入经常会有问题,在这里输入 Ctrl-C 进入信号处理器,在通过 continue 命令进入断点: + +```c +127.0.0.1:6379> SET KEY MSG +^C +8063 stopped +* thread #1: tid = 0xa95147, 0x00007fff90923362 libsystem_kernel.dylib`read + 10, stop reason = signal SIGSTOP + frame #0: 0x00007fff90923362 libsystem_kernel.dylib`read + 10 +libsystem_kernel.dylib`read: +-> 0x7fff90923362 <+10>: jae 0x7fff9092336c ; <+20> + 0x7fff90923364 <+12>: movq %rax, %rdi + 0x7fff90923367 <+15>: jmp 0x7fff9091c7f2 ; cerror + 0x7fff9092336c <+20>: retq +(lldb) c +Process 8063 resuming + +Process 8063 stopped +* thread #1: tid = 0xa95147, 0x0000000100008cd4 redis-cli`repl + 228 at redis-cli.c:1290, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 + frame #0: 0x0000000100008cd4 redis-cli`repl + 228 at redis-cli.c:1290 + 1287 + 1288 cliRefreshPrompt(); + 1289 while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { +-> 1290 if (line[0] != '\0') { + 1291 argv = cliSplitArgs(line,&argc); + 1292 if (history) linenoiseHistoryAdd(line); + 1293 if (historyfile) linenoiseHistorySave(historyfile); +(lldb) +``` + +输入两次 `n` 之后,打印 `argv` 和 `argc` 的值: + +```c +(lldb) p argc +(int) $1 = 3 +(lldb) p *argv +(sds) $2 = 0x0000000100106cc3 "SET" +(lldb) p *(argv+1) +(sds) $3 = 0x0000000100106ce3 "KEY" +(lldb) p *(argv+2) +(sds) $4 = 0x0000000100106cf3 "MSG" +(lldb) p line +(char *) $5 = 0x0000000100303430 "SET KEY MSG\n" +``` + +`cliSplitArgs` 方法成功将 `line` 中的字符串分隔成字符串参数,在多次执行 `n` 之后,进入 `issueCommandRepeat` 方法: + +```c +-> 1334 issueCommandRepeat(argc-skipargs, argv+skipargs, repeat); +``` + +## 对输入命令的处理 + +上一阶段执行 `issueCommandRepeat` 的函数调用栈中,会发现 Redis 并不会直接把所有的命令发送到服务端: + +```c +issueCommandRepeat + cliSendCommand + redisAppendCommandArgv + redisFormatCommandArgv + __redisAppendCommand +``` + +而是会在 `redisFormatCommandArgv` 中对所有的命令进行格式化处理,将字符串转换为符合 RESP 协议的数据。 + +### RESP 协议 + +Redis 客户端与 Redis 服务进行通讯时,会使用名为 **RESP**(REdis Serialization Protocol) 的协议,它的使用非常简单,并且可以序列化多种数据类型包括整数、字符串以及数组等。 + +对于 RESP 协议的详细介绍可以看官方文档中的 [Redis Protocol specification](https://redis.io/topics/protocol),在这里对这个协议进行简单的介绍。 + +在将不同的数据类型序列化时,会使用第一个 byte 来表示当前数据的数据类型,以便在客户端或服务器在处理时能恢复原来的数据格式。 + +![redis-resp-data-byte](images/redis-resp-data-byte.jpg) + +举一个简单的例子,字符串 `OK` 以及错误`Error Message` 等不同种类的信息的 RESP 表示如下: + +![redis-resp-type-and-examples](images/redis-resp-type-and-examples.jpg) + +在这篇文章中我们需要简单了解的就是 RESP “数据格式”的**第一个字节用来表示数据类型**,然后**逻辑上属于不同部分的内容通过 CRLF(\r\n)分隔**。 + +### 数据格式的转换 + +在 `redisFormatCommandArgv` 方法中几乎没有需要删减的代码,所有的命令都会以字符串数组的形式发送到客户端: + +```c +int redisFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen) { + char *cmd = NULL; + int pos; + size_t len; + int totlen, j; + + totlen = 1+intlen(argc)+2; + for (j = 0; j < argc; j++) { + len = argvlen ? argvlen[j] : strlen(argv[j]); + totlen += bulklen(len); + } + + cmd = malloc(totlen+1); + if (cmd == NULL) + return -1; + + pos = sprintf(cmd,"*%d\r\n",argc); + for (j = 0; j < argc; j++) { + len = argvlen ? argvlen[j] : strlen(argv[j]); + pos += sprintf(cmd+pos,"$%zu\r\n",len); + memcpy(cmd+pos,argv[j],len); + pos += len; + cmd[pos++] = '\r'; + cmd[pos++] = '\n'; + } + assert(pos == totlen); + cmd[pos] = '\0'; + + *target = cmd; + return totlen; +} +``` + +`SET KEY MSG` 这一命令,经过这个方法的处理会变成: + +```c +*3\r\n$3\r\nSET\r\n$3\r\nKEY\r\n$3\r\nMSG\r\n +``` + +你可以这么理解上面的结果: + +```c +*3\r\n + $3\r\nSET\r\n + $3\r\nKEY\r\n + $3\r\nMSG\r\n +``` + +这是一个由三个字符串组成的数组,数组中的元素是 `SET`、`KEY` 以及 `MSG` 三个字符串。 + +如果在这里打一个断点并输出 `target` 中的内容: + +![redis-lldb-cmd](images/redis-lldb-cmd.png) + +到这里就完成了对输入命令的格式化,在格式化之后还会将当前命令写入全局的 `redisContext` 的 `write` 缓冲区 `obuf` 中,也就是在上面的缓冲区看到的第二个方法: + +```c +int __redisAppendCommand(redisContext *c, const char *cmd, size_t len) { + sds newbuf; + + newbuf = sdscatlen(c->obuf,cmd,len); + if (newbuf == NULL) { + __redisSetError(c,REDIS_ERR_OOM,"Out of memory"); + return REDIS_ERR; + } + + c->obuf = newbuf; + return REDIS_OK; +} +``` + +### redisContext + +再继续介绍下一部分之前需要简单介绍一下 `redisContext` 结构体: + +```c +typedef struct redisContext { + int err; + char errstr[128]; + int fd; + int flags; + char *obuf; + redisReader *reader; +} redisContext; +``` + +每一个 `redisContext` 的结构体都表示一个 Redis 客户端对服务的连接,而这个上下文会在每一个 redis-cli 中作为静态变量仅保存一个: + +```c +static redisContext *context; +``` + +`obuf` 中包含了客户端未写到服务端的数据;而 `reader` 是用来处理 RESP 协议的结构体;`fd` 就是 Redis 服务对应的文件描述符;其他的内容就不多做解释了。 + +到这里,对命令的格式化处理就结束了,接下来就到了向服务端发送命令的过程了。 + +## 向服务器发送命令 + +与对输入命令的处理差不多,向服务器发送命令的方法也在 `issueCommandRepeat` 的调用栈中,而且藏得更深,如果不仔细阅读源代码其实很难发现: + +```c +issueCommandRepeat + cliSendCommand + cliReadReply + redisGetReply + redisBufferWrite +``` + +Redis 在 `redisGetReply` 中完成对命令的发送: + +```c +int redisGetReply(redisContext *c, void **reply) { + int wdone = 0; + void *aux = NULL; + + if (aux == NULL && c->flags & REDIS_BLOCK) { + do { + if (redisBufferWrite(c,&wdone) == REDIS_ERR) + return REDIS_ERR; + } while (!wdone); + + ... + } while (aux == NULL); + } + + if (reply != NULL) *reply = aux; + return REDIS_OK; +} +``` + +上面的代码向 `redisBufferWrite` 函数中传递了全局的静态变量 `redisContext`,其中的 `obuf` 中存储了没有向 Redis 服务发送的命令: + +```c +int redisBufferWrite(redisContext *c, int *done) { + int nwritten; + + if (sdslen(c->obuf) > 0) { + nwritten = write(c->fd,c->obuf,sdslen(c->obuf)); + if (nwritten == -1) { + if ((errno == EAGAIN && !(c->flags & REDIS_BLOCK)) || (errno == EINTR)) { + } else { + __redisSetError(c,REDIS_ERR_IO,NULL); + return REDIS_ERR; + } + } else if (nwritten > 0) { + if (nwritten == (signed)sdslen(c->obuf)) { + sdsfree(c->obuf); + c->obuf = sdsempty(); + } else { + sdsrange(c->obuf,nwritten,-1); + } + } + } + if (done != NULL) *done = (sdslen(c->obuf) == 0); + return REDIS_OK; +} +``` + +代码的逻辑其实十分清晰,调用 `write` 向 Redis 服务代表的文件描述符发送写缓冲区 `obuf` 中的数据,然后根据返回值做出相应的处理,如果命令发送成功就会清空 `obuf` 并将 `done` 指针标记为真,然后返回,这样就完成了向服务器发送命令这一过程。 + +![redis-lldb-nwritten](images/redis-lldb-nwritten.png) + +## 获取服务器回复 + +其实获取服务器回复和上文中的发送命令过程基本上差不多,调用栈也几乎完全一样: + +```c +issueCommandRepeat + cliSendCommand + cliReadReply + redisGetReply + redisBufferRead + redisGetReplyFromReader + cliFormatReplyRaw + fwrite +``` + +同样地,在 `redisGetReply` 中获取服务器的响应: + +```c +int redisGetReply(redisContext *c, void **reply) { + int wdone = 0; + void *aux = NULL; + + if (aux == NULL && c->flags & REDIS_BLOCK) { + do { + if (redisBufferWrite(c,&wdone) == REDIS_ERR) + return REDIS_ERR; + } while (!wdone); + + do { + if (redisBufferRead(c) == REDIS_ERR) + return REDIS_ERR; + if (redisGetReplyFromReader(c,&aux) == REDIS_ERR) + return REDIS_ERR; + } while (aux == NULL); + } + + if (reply != NULL) *reply = aux; + return REDIS_OK; +} +``` + +在 `redisBufferWrite` 成功发送命令并返回之后,就会开始等待服务端的回复,总共分为两个部分,一是使用 `redisBufferRead` 从服务端读取原始格式的回复(符合 RESP 协议): + +```c +int redisBufferRead(redisContext *c) { + char buf[1024*16]; + int nread; + + nread = read(c->fd,buf,sizeof(buf)); + if (nread == -1) { + if ((errno == EAGAIN && !(c->flags & REDIS_BLOCK)) || (errno == EINTR)) { + } else { + __redisSetError(c,REDIS_ERR_IO,NULL); + return REDIS_ERR; + } + } else if (nread == 0) { + __redisSetError(c,REDIS_ERR_EOF,"Server closed the connection"); + return REDIS_ERR; + } else { + if (redisReaderFeed(c->reader,buf,nread) != REDIS_OK) { + __redisSetError(c,c->reader->err,c->reader->errstr); + return REDIS_ERR; + } + } + return REDIS_OK; +} +``` + +在 `read` 从文件描述符中成功读取数据并返回之后,我们可以打印 `buf` 中的内容: + +![redis-lldb-read](images/redis-lldb-read.png) + +刚刚向 `buf` 中写入的数据还需要经过 `redisReaderFeed` 方法的处理,截取正确的长度;然后存入 `redisReader` 中: + +```c +int redisReaderFeed(redisReader *r, const char *buf, size_t len) { + sds newbuf; + + if (buf != NULL && len >= 1) { + if (r->len == 0 && r->maxbuf != 0 && sdsavail(r->buf) > r->maxbuf) { + sdsfree(r->buf); + r->buf = sdsempty(); + r->pos = 0; + assert(r->buf != NULL); + } + + newbuf = sdscatlen(r->buf,buf,len); + if (newbuf == NULL) { + __redisReaderSetErrorOOM(r); + return REDIS_ERR; + } + + r->buf = newbuf; + r->len = sdslen(r->buf); + } + + return REDIS_OK; +} +``` + +最后的 `redisGetReplyFromReader` 方法会从 `redisContext` 中取出 `reader`,然后反序列化 RESP 对象,最后打印出来。 + +![process-end](images/process-end.png) + +当我们从终端的输出中看到了 OK 以及这个命令的执行的时间时,`SET KEY MSG` 这一命令就已经处理完成了。 + +## 总结 + +处理命令的过程在客户端还是比较简单的: + +1. 在一个 `while` 循环中,输出提示符; +2. 接收到输入命令时,对输入命令进行格式化处理; +3. 通过 `write` 发送到 Redis 服务,并调用 `read` 阻塞当前进程直到服务端返回为止; +4. 对服务端返回的数据反序列化; +5. 将结果打印到终端。 + +用一个简单的图表示,大概是这样的: + +![redis-client-process-commands](images/redis-client-process-commands.jpg) + +## References + ++ [Redis Protocol specification](https://redis.io/topics/protocol) ++ [Redis 和 I/O 多路复用](http://draveness.me/redis-io-multiplexing/) ++ [Redis 中的事件循环](http://draveness.me/redis-eventloop) + + +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/redis-cli + diff --git a/contents/Redis/redis-eventloop.md b/contents/Redis/redis-eventloop.md new file mode 100644 index 0000000..cf72789 --- /dev/null +++ b/contents/Redis/redis-eventloop.md @@ -0,0 +1,330 @@ +# Redis 中的事件循环 + +在目前的很多服务中,由于需要持续接受客户端或者用户的输入,所以需要一个事件循环来等待并处理外部事件,这篇文章主要会介绍 Redis 中的事件循环是如何处理事件的。 + +在文章中,我们会先从 Redis 的实现中分析事件是如何被处理的,然后用更具象化的方式了解服务中的不同模块是如何交流的。 + +## aeEventLoop + +在分析具体代码之前,先了解一下在事件处理中处于核心部分的 `aeEventLoop` 到底是什么: + +![reids-eventloop](./images/reids-eventloop.png) + +`aeEventLoop` 在 Redis 就是负责保存待处理文件事件和时间事件的结构体,其中保存大量事件执行的上下文信息,同时持有三个事件数组: + ++ `aeFileEvent` ++ `aeTimeEvent` ++ `aeFiredEvent` + +`aeFileEvent` 和 `aeTimeEvent` 中会存储监听的文件事件和时间事件,而最后的 `aeFiredEvent` 用于存储待处理的文件事件,我们会在后面的章节中介绍它们是如何工作的。 + +### Redis 服务中的 EventLoop + +在 `redis-server` 启动时,首先会初始化一些 redis 服务的配置,最后会调用 `aeMain` 函数陷入 `aeEventLoop` 循环中,等待外部事件的发生: + +```c +int main(int argc, char **argv) { + ... + + aeMain(server.el); +} +``` + +`aeMain` 函数其实就是一个封装的 `while` 循环,循环中的代码会一直运行直到 `eventLoop` 的 `stop` 被设置为 `true`: + +```c +void aeMain(aeEventLoop *eventLoop) { + eventLoop->stop = 0; + while (!eventLoop->stop) { + if (eventLoop->beforesleep != NULL) + eventLoop->beforesleep(eventLoop); + aeProcessEvents(eventLoop, AE_ALL_EVENTS); + } +} +``` + +它会不停尝试调用 `aeProcessEvents` 对可能存在的多种事件进行处理,而 `aeProcessEvents` 就是实际用于处理事件的函数: + +```c +int aeProcessEvents(aeEventLoop *eventLoop, int flags) { + int processed = 0, numevents; + + if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0; + + if (eventLoop->maxfd != -1 || + ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) { + struct timeval *tvp; + + #1:计算 I/O 多路复用的等待时间 tvp + + numevents = aeApiPoll(eventLoop, tvp); + for (int j = 0; j < numevents; j++) { + aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd]; + int mask = eventLoop->fired[j].mask; + int fd = eventLoop->fired[j].fd; + int rfired = 0; + + if (fe->mask & mask & AE_READABLE) { + rfired = 1; + fe->rfileProc(eventLoop,fd,fe->clientData,mask); + } + if (fe->mask & mask & AE_WRITABLE) { + if (!rfired || fe->wfileProc != fe->rfileProc) + fe->wfileProc(eventLoop,fd,fe->clientData,mask); + } + processed++; + } + } + if (flags & AE_TIME_EVENTS) processed += processTimeEvents(eventLoop); + return processed; +} +``` + +上面的代码省略了 I/O 多路复用函数的等待时间,不过不会影响我们对代码的理解,整个方法大体由两部分代码组成,一部分处理文件事件,另一部分处理时间事件。 + +> Redis 中会处理两种事件:时间事件和文件事件。 + +### 文件事件 + +在一般情况下,`aeProcessEvents` 都会先**计算最近的时间事件发生所需要等待的时间**,然后调用 `aeApiPoll` 方法在这段时间中等待事件的发生,在这段时间中如果发生了文件事件,就会优先处理文件事件,否则就会一直等待,直到最近的时间事件需要触发: + +```c +numevents = aeApiPoll(eventLoop, tvp); +for (j = 0; j < numevents; j++) { + aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd]; + int mask = eventLoop->fired[j].mask; + int fd = eventLoop->fired[j].fd; + int rfired = 0; + + if (fe->mask & mask & AE_READABLE) { + rfired = 1; + fe->rfileProc(eventLoop,fd,fe->clientData,mask); + } + if (fe->mask & mask & AE_WRITABLE) { + if (!rfired || fe->wfileProc != fe->rfileProc) + fe->wfileProc(eventLoop,fd,fe->clientData,mask); + } + processed++; +} +``` + +文件事件如果绑定了对应的读/写事件,就会执行对应的对应的代码,并传入事件循环、文件描述符、数据以及掩码: + +```c +fe->rfileProc(eventLoop,fd,fe->clientData,mask); +fe->wfileProc(eventLoop,fd,fe->clientData,mask); +``` + +其中 `rfileProc` 和 `wfileProc` 就是在文件事件被创建时传入的函数指针: + +```c +int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, aeFileProc *proc, void *clientData) { + aeFileEvent *fe = &eventLoop->events[fd]; + + if (aeApiAddEvent(eventLoop, fd, mask) == -1) + return AE_ERR; + fe->mask |= mask; + if (mask & AE_READABLE) fe->rfileProc = proc; + if (mask & AE_WRITABLE) fe->wfileProc = proc; + fe->clientData = clientData; + if (fd > eventLoop->maxfd) + eventLoop->maxfd = fd; + return AE_OK; +} +``` + +需要注意的是,传入的 `proc` 函数会在对应的 `mask` 位事件发生时执行。 + +### 时间事件 + +在 Redis 中会发生两种时间事件: + ++ 一种是定时事件,每隔一段时间会执行一次; ++ 另一种是非定时事件,只会在某个时间点执行一次; + +时间事件的处理在 `processTimeEvents` 中进行,我们会分三部分分析这个方法的实现: + +```c +static int processTimeEvents(aeEventLoop *eventLoop) { + int processed = 0; + aeTimeEvent *te, *prev; + long long maxId; + time_t now = time(NULL); + + if (now < eventLoop->lastTime) { + te = eventLoop->timeEventHead; + while(te) { + te->when_sec = 0; + te = te->next; + } + } + eventLoop->lastTime = now; +``` + +由于对系统时间的调整会影响当前时间的获取,进而影响时间事件的执行;如果系统时间先被设置到了未来的时间,又设置成正确的值,这就会导致**时间事件会随机延迟一段时间执行**,也就是说,时间事件不会按照预期的安排尽早执行,而 `eventLoop` 中的 `lastTime` 就是用于检测上述情况的变量: + +```c +typedef struct aeEventLoop { + ... + time_t lastTime; /* Used to detect system clock skew */ + ... +} aeEventLoop; +``` + +如果发现了系统时间被改变(小于上次 `processTimeEvents` 函数执行的开始时间),就会强制所有时间事件尽早执行。 + +```c + prev = NULL; + te = eventLoop->timeEventHead; + maxId = eventLoop->timeEventNextId-1; + while(te) { + long now_sec, now_ms; + long long id; + + if (te->id == AE_DELETED_EVENT_ID) { + aeTimeEvent *next = te->next; + if (prev == NULL) + eventLoop->timeEventHead = te->next; + else + prev->next = te->next; + if (te->finalizerProc) + te->finalizerProc(eventLoop, te->clientData); + zfree(te); + te = next; + continue; + } +``` + +Redis 处理时间事件时,不会在当前循环中直接移除不再需要执行的事件,而是会在当前循环中将时间事件的 `id` 设置为 `AE_DELETED_EVENT_ID`,然后再下一个循环中删除,并执行绑定的 `finalizerProc`。 + +```c + aeGetTime(&now_sec, &now_ms); + if (now_sec > te->when_sec || + (now_sec == te->when_sec && now_ms >= te->when_ms)) + { + int retval; + + id = te->id; + retval = te->timeProc(eventLoop, id, te->clientData); + processed++; + if (retval != AE_NOMORE) { + aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms); + } else { + te->id = AE_DELETED_EVENT_ID; + } + } + prev = te; + te = te->next; + } + return processed; +} +``` + +在移除不需要执行的时间事件之后,我们就开始通过比较时间来判断是否需要调用 `timeProc` 函数,`timeProc` 函数的返回值 `retval` 为时间事件执行的时间间隔: + ++ `retval == AE_NOMORE`:将时间事件的 `id` 设置为 `AE_DELETED_EVENT_ID`,等待下次 `aeProcessEvents` 执行时将事件清除; ++ `retval != AE_NOMORE`:修改当前时间事件的执行时间并重复利用当前的时间事件; + +以使用 `aeCreateTimeEvent` 一个创建的简单时间事件为例: + +```c +aeCreateTimeEvent(config.el,1,showThroughput,NULL,NULL) +``` + +时间事件对应的函数 `showThroughput` 在每次执行时会返回一个数字,也就是该事件发生的时间间隔: + +```c +int showThroughput(struct aeEventLoop *eventLoop, long long id, void *clientData) { + ... + float dt = (float)(mstime()-config.start)/1000.0; + float rps = (float)config.requests_finished/dt; + printf("%s: %.2f\r", config.title, rps); + fflush(stdout); + return 250; /* every 250ms */ +} +``` + +这样就不需要重新 `malloc` 一块相同大小的内存,提高了时间事件处理的性能,并减少了内存的使用量。 + +我们对 Redis 中对时间事件的处理以流程图的形式简单总结一下: + +![process-time-event](./images/process-time-event.png) + +创建时间事件的方法实现其实非常简单,在这里不想过多分析这个方法,唯一需要注意的就是时间事件的 `id` 跟数据库中的大多数主键都是递增的: + +```c +long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds, + aeTimeProc *proc, void *clientData, + aeEventFinalizerProc *finalizerProc) { + long long id = eventLoop->timeEventNextId++; + aeTimeEvent *te; + + te = zmalloc(sizeof(*te)); + if (te == NULL) return AE_ERR; + te->id = id; + aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms); + te->timeProc = proc; + te->finalizerProc = finalizerProc; + te->clientData = clientData; + te->next = eventLoop->timeEventHead; + eventLoop->timeEventHead = te; + return id; +} +``` + +## 事件的处理 + +> 上一章节我们已经从代码的角度对 Redis 中事件的处理有一定的了解,在这里,我想从更高的角度来观察 Redis 对于事件的处理是怎么进行的。 + +整个 Redis 服务在启动之后会陷入一个巨大的 while 循环,不停地执行 `processEvents` 方法处理文件事件 fe 和时间事件 te 。 + +> 有关 Redis 中的 I/O 多路复用模块可以看这篇文章 [Redis 和 I/O 多路复用](http://draveness.me/redis-io-multiplexing/)。 + +当文件事件触发时会被标记为 “红色” 交由 `processEvents` 方法处理,而时间事件的处理都会交给 `processTimeEvents` 这一子方法: + +![redis-eventloop-proces-event](./images/redis-eventloop-proces-event.png) + +在每个事件循环中 Redis 都会先处理文件事件,然后再处理时间事件直到整个循环停止,`processEvents` 和 `processTimeEvents` 作为 Redis 中发生事件的消费者,每次都会从“事件池”中拉去待处理的事件进行消费。 + +### 文件事件的处理 + +由于文件事件触发条件较多,并且 OS 底层实现差异性较大,底层的 I/O 多路复用模块使用了 `eventLoop->aeFiredEvent` 保存对应的文件描述符以及事件,将信息传递给上层进行处理,并抹平了底层实现的差异。 + +整个 I/O 多路复用模块在事件循环看来就是一个输入事件、输出 `aeFiredEvent` 数组的一个黑箱: + +![eventloop-file-event-in-redis](./images/eventloop-file-event-in-redis.png) + +在这个黑箱中,我们使用 `aeCreateFileEvent`、 `aeDeleteFileEvent` 来添加删除需要监听的文件描述符以及事件。 + +在对应事件发生时,当前单元格会“变色”表示发生了可读(黄色)或可写(绿色)事件,调用 `aeApiPoll` 时会把对应的文件描述符和事件放入 `aeFiredEvent` 数组,并在 `processEvents` 方法中执行事件对应的回调。 + +### 时间事件的处理 + +时间事件的处理相比文件事件就容易多了,每次 `processTimeEvents` 方法调用时都会对整个 `timeEventHead` 数组进行遍历: + +![process-time-events-in-redis](./images/process-time-events-in-redis.png) + +遍历的过程中会将时间的触发时间与当前时间比较,然后执行时间对应的 `timeProc`,并根据 `timeProc` 的返回值修改当前事件的参数,并在下一个循环的遍历中移除不再执行的时间事件。 + +## 总结 + +> 笔者对于文章中两个模块的展示顺序考虑了比较久的时间,最后还是觉得,目前这样的顺序更易于理解。 + +Redis 对于事件的处理方式十分精巧,通过传入函数指针以及返回值的方式,将时间事件移除的控制权交给了需要执行的处理器 `timeProc`,在 `processTimeEvents` 设置 `aeApiPoll` 超时时间也十分巧妙,充分地利用了每一次事件循环,防止过多的无用的空转,并且保证了该方法不会阻塞太长时间。 + +事件循环的机制并不能时间事件准确地在某一个时间点一定执行,往往会比实际约定处理的时间稍微晚一些。 + +## Reference + ++ [Redis Event Library](https://redis.io/topics/internals-rediseventlib) ++ [Redis Core Implementation](http://key-value-stories.blogspot.com/2015/01/redis-core-implementation.html) ++ [Redis 和 I/O 多路复用](http://draveness.me/redis-io-multiplexing/) ++ [Redis 设计与实现](http://redisbook.com) + +## 其它 + +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/redis-eventloop + + diff --git a/contents/Redis/redis-io-multiplexing.md b/contents/Redis/redis-io-multiplexing.md new file mode 100644 index 0000000..bc869d3 --- /dev/null +++ b/contents/Redis/redis-io-multiplexing.md @@ -0,0 +1,298 @@ +# Redis 和 I/O 多路复用 + +最近在看 UNIX 网络编程并研究了一下 Redis 的实现,感觉 Redis 的源代码十分适合阅读和分析,其中 I/O 多路复用(mutiplexing)部分的实现非常干净和优雅,在这里想对这部分的内容进行简单的整理。 + +## 几种 I/O 模型 + +为什么 Redis 中要使用 I/O 多路复用这种技术呢? + +首先,Redis 是跑在单线程中的,所有的操作都是按照顺序线性执行的,但是由于读写操作等待用户输入或输出都是阻塞的,所以 I/O 操作在一般情况下往往不能直接返回,这会导致某一文件的 I/O 阻塞导致整个进程无法对其它客户提供服务,而 **I/O 多路复用**就是为了解决这个问题而出现的。 + +### Blocking I/O + +先来看一下传统的阻塞 I/O 模型到底是如何工作的:当使用 `read` 或者 `write` 对某一个**文件描述符(File Descriptor 以下简称 FD)**进行读写时,如果当前 FD 不可读或不可写,整个 Redis 服务就不会对其它的操作作出响应,导致整个服务不可用。 + +这也就是传统意义上的,也就是我们在编程中使用最多的阻塞模型: + +![blocking-io](images/blocking-io.png) + +阻塞模型虽然开发中非常常见也非常易于理解,但是由于它会影响其他 FD 对应的服务,所以在需要处理多个客户端任务的时候,往往都不会使用阻塞模型。 + +### I/O 多路复用 + +> 虽然还有很多其它的 I/O 模型,但是在这里都不会具体介绍。 + +阻塞式的 I/O 模型并不能满足这里的需求,我们需要一种效率更高的 I/O 模型来支撑 Redis 的多个客户(redis-cli),这里涉及的就是 I/O 多路复用模型了: + +![I:O-Multiplexing-Mode](images/I:O-Multiplexing-Model.png) + +在 I/O 多路复用模型中,最重要的函数调用就是 `select`,该方法的能够同时监控多个文件描述符的可读可写情况,当其中的某些文件描述符可读或者可写时,`select` 方法就会返回可读以及可写的文件描述符个数。 + +> 关于 `select` 的具体使用方法,在网络上资料很多,这里就不过多展开介绍了; +> +> 与此同时也有其它的 I/O 多路复用函数 `epoll/kqueue/evport`,它们相比 `select` 性能更优秀,同时也能支撑更多的服务。 + +## Reactor 设计模式 + +Redis 服务采用 Reactor 的方式来实现文件事件处理器(每一个网络连接其实都对应一个文件描述符) + +![redis-reactor-pattern](images/redis-reactor-pattern.png) + +文件事件处理器使用 I/O 多路复用模块同时监听多个 FD,当 `accept`、`read`、`write` 和 `close` 文件事件产生时,文件事件处理器就会回调 FD 绑定的事件处理器。 + +虽然整个文件事件处理器是在单线程上运行的,但是通过 I/O 多路复用模块的引入,实现了同时对多个 FD 读写的监控,提高了网络通信模型的性能,同时也可以保证整个 Redis 服务实现的简单。 + +## I/O 多路复用模块 + +I/O 多路复用模块封装了底层的 `select`、`epoll`、`avport` 以及 `kqueue` 这些 I/O 多路复用函数,为上层提供了相同的接口。 + +![ae-module](images/ae-module.jpg) + +在这里我们简单介绍 Redis 是如何包装 `select` 和 `epoll` 的,简要了解该模块的功能,整个 I/O 多路复用模块抹平了不同平台上 I/O 多路复用函数的差异性,提供了相同的接口: + ++ `static int aeApiCreate(aeEventLoop *eventLoop)` ++ `static int aeApiResize(aeEventLoop *eventLoop, int setsize)` ++ `static void aeApiFree(aeEventLoop *eventLoop)` ++ `static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask)` ++ `static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) ` ++ `static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp)` + +同时,因为各个函数所需要的参数不同,我们在每一个子模块内部通过一个 `aeApiState` 来存储需要的上下文信息: + +```c +// select +typedef struct aeApiState { + fd_set rfds, wfds; + fd_set _rfds, _wfds; +} aeApiState; + +// epoll +typedef struct aeApiState { + int epfd; + struct epoll_event *events; +} aeApiState; +``` + +这些上下文信息会存储在 `eventLoop` 的 `void *state` 中,不会暴露到上层,只在当前子模块中使用。 + +### 封装 select 函数 + +> `select` 可以监控 FD 的可读、可写以及出现错误的情况。 + +在介绍 I/O 多路复用模块如何对 `select` 函数封装之前,先来看一下 `select` 函数使用的大致流程: + +```c +int fd = /* file descriptor */ + +fd_set rfds; +FD_ZERO(&rfds); +FD_SET(fd, &rfds) + +for ( ; ; ) { + select(fd+1, &rfds, NULL, NULL, NULL); + if (FD_ISSET(fd, &rfds)) { + /* file descriptor `fd` becomes readable */ + } +} +``` + +1. 初始化一个可读的 `fd_set` 集合,保存需要监控可读性的 FD; +2. 使用 `FD_SET` 将 `fd` 加入 `rfds`; +3. 调用 `select` 方法监控 `rfds` 中的 FD 是否可读; +4. 当 `select` 返回时,检查 FD 的状态并完成对应的操作。 + +而在 Redis 的 `ae_select` 文件中代码的组织顺序也是差不多的,首先在 `aeApiCreate` 函数中初始化 `rfds` 和 `wfds`: + +```c +static int aeApiCreate(aeEventLoop *eventLoop) { + aeApiState *state = zmalloc(sizeof(aeApiState)); + if (!state) return -1; + FD_ZERO(&state->rfds); + FD_ZERO(&state->wfds); + eventLoop->apidata = state; + return 0; +} +``` + +而 `aeApiAddEvent` 和 `aeApiDelEvent` 会通过 `FD_SET` 和 `FD_CLR` 修改 `fd_set` 中对应 FD 的标志位: + +```c +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + if (mask & AE_READABLE) FD_SET(fd,&state->rfds); + if (mask & AE_WRITABLE) FD_SET(fd,&state->wfds); + return 0; +} +``` + +整个 `ae_select` 子模块中最重要的函数就是 `aeApiPoll`,它是实际调用 `select` 函数的部分,其作用就是在 I/O 多路复用函数返回时,将对应的 FD 加入 `aeEventLoop` 的 `fired` 数组中,并返回事件的个数: + +```c +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + int retval, j, numevents = 0; + + memcpy(&state->_rfds,&state->rfds,sizeof(fd_set)); + memcpy(&state->_wfds,&state->wfds,sizeof(fd_set)); + + retval = select(eventLoop->maxfd+1, + &state->_rfds,&state->_wfds,NULL,tvp); + if (retval > 0) { + for (j = 0; j <= eventLoop->maxfd; j++) { + int mask = 0; + aeFileEvent *fe = &eventLoop->events[j]; + + if (fe->mask == AE_NONE) continue; + if (fe->mask & AE_READABLE && FD_ISSET(j,&state->_rfds)) + mask |= AE_READABLE; + if (fe->mask & AE_WRITABLE && FD_ISSET(j,&state->_wfds)) + mask |= AE_WRITABLE; + eventLoop->fired[numevents].fd = j; + eventLoop->fired[numevents].mask = mask; + numevents++; + } + } + return numevents; +} +``` + +### 封装 epoll 函数 + +Redis 对 `epoll` 的封装其实也是类似的,使用 `epoll_create` 创建 `epoll` 中使用的 `epfd`: + +```c +static int aeApiCreate(aeEventLoop *eventLoop) { + aeApiState *state = zmalloc(sizeof(aeApiState)); + + if (!state) return -1; + state->events = zmalloc(sizeof(struct epoll_event)*eventLoop->setsize); + if (!state->events) { + zfree(state); + return -1; + } + state->epfd = epoll_create(1024); /* 1024 is just a hint for the kernel */ + if (state->epfd == -1) { + zfree(state->events); + zfree(state); + return -1; + } + eventLoop->apidata = state; + return 0; +} +``` + +在 `aeApiAddEvent` 中使用 `epoll_ctl` 向 `epfd` 中添加需要监控的 FD 以及监听的事件: + +```c +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + struct epoll_event ee = {0}; /* avoid valgrind warning */ + /* If the fd was already monitored for some event, we need a MOD + * operation. Otherwise we need an ADD operation. */ + int op = eventLoop->events[fd].mask == AE_NONE ? + EPOLL_CTL_ADD : EPOLL_CTL_MOD; + + ee.events = 0; + mask |= eventLoop->events[fd].mask; /* Merge old events */ + if (mask & AE_READABLE) ee.events |= EPOLLIN; + if (mask & AE_WRITABLE) ee.events |= EPOLLOUT; + ee.data.fd = fd; + if (epoll_ctl(state->epfd,op,fd,&ee) == -1) return -1; + return 0; +} +``` + +由于 `epoll` 相比 `select` 机制略有不同,在 `epoll_wait` 函数返回时并不需要遍历所有的 FD 查看读写情况;在 `epoll_wait` 函数返回时会提供一个 `epoll_event` 数组: + +```c +typedef union epoll_data { + void *ptr; + int fd; /* 文件描述符 */ + uint32_t u32; + uint64_t u64; +} epoll_data_t; + +struct epoll_event { + uint32_t events; /* Epoll 事件 */ + epoll_data_t data; +}; +``` + +> 其中保存了发生的 `epoll` 事件(`EPOLLIN`、`EPOLLOUT`、`EPOLLERR` 和 `EPOLLHUP`)以及发生该事件的 FD。 + +`aeApiPoll` 函数只需要将 `epoll_event` 数组中存储的信息加入 `eventLoop` 的 `fired` 数组中,将信息传递给上层模块: + +```c +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + int retval, numevents = 0; + + retval = epoll_wait(state->epfd,state->events,eventLoop->setsize, + tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1); + if (retval > 0) { + int j; + + numevents = retval; + for (j = 0; j < numevents; j++) { + int mask = 0; + struct epoll_event *e = state->events+j; + + if (e->events & EPOLLIN) mask |= AE_READABLE; + if (e->events & EPOLLOUT) mask |= AE_WRITABLE; + if (e->events & EPOLLERR) mask |= AE_WRITABLE; + if (e->events & EPOLLHUP) mask |= AE_WRITABLE; + eventLoop->fired[j].fd = e->data.fd; + eventLoop->fired[j].mask = mask; + } + } + return numevents; +} +``` + +### 子模块的选择 + +因为 Redis 需要在多个平台上运行,同时为了最大化执行的效率与性能,所以会根据编译平台的不同选择不同的 I/O 多路复用函数作为子模块,提供给上层统一的接口;在 Redis 中,我们通过宏定义的使用,合理的选择不同的子模块: + +```c +#ifdef HAVE_EVPORT +#include "ae_evport.c" +#else + #ifdef HAVE_EPOLL + #include "ae_epoll.c" + #else + #ifdef HAVE_KQUEUE + #include "ae_kqueue.c" + #else + #include "ae_select.c" + #endif + #endif +#endif +``` + +因为 `select` 函数是作为 POSIX 标准中的系统调用,在不同版本的操作系统上都会实现,所以将其作为保底方案: + +![redis-choose-io-function](images/redis-choose-io-function.jpg) + +Redis 会优先选择时间复杂度为 $O(1)$ 的 I/O 多路复用函数作为底层实现,包括 Solaries 10 中的 `evport`、Linux 中的 `epoll` 和 macOS/FreeBSD 中的 `kqueue`,上述的这些函数都使用了内核内部的结构,并且能够服务几十万的文件描述符。 + +但是如果当前编译环境没有上述函数,就会选择 `select` 作为备选方案,由于其在使用时会扫描全部监听的描述符,所以其时间复杂度较差 $O(n)$,并且只能同时服务 1024 个文件描述符,所以一般并不会以 `select` 作为第一方案使用。 + +## 总结 + +Redis 对于 I/O 多路复用模块的设计非常简洁,通过宏保证了 I/O 多路复用模块在不同平台上都有着优异的性能,将不同的 I/O 多路复用函数封装成相同的 API 提供给上层使用。 + +整个模块使 Redis 能以单进程运行的同时服务成千上万个文件描述符,避免了由于多进程应用的引入导致代码实现复杂度的提升,减少了出错的可能性。 + +## Reference + ++ [Select-Man-Pages](http://man7.org/linux/man-pages/man2/select.2.html) ++ [Reactor-Pattern](https://en.wikipedia.org/wiki/Reactor_pattern) ++ [epoll vs kqueue](https://people.eecs.berkeley.edu/~sangjin/2012/12/21/epoll-vs-kqueue.html) + +## 其它 + +> Follow: [Draveness · GitHub](https://github.com/Draveness) +> +> Source: http://draveness.me/redis-io-multiplexing + + diff --git a/contents/Ruby/images/sidekiq/Async-Schedule.jpg b/contents/Ruby/images/sidekiq/Async-Schedule.jpg new file mode 100644 index 0000000..cbac454 Binary files /dev/null and b/contents/Ruby/images/sidekiq/Async-Schedule.jpg differ diff --git a/contents/Ruby/images/sidekiq/Client-Push-Item.jpg b/contents/Ruby/images/sidekiq/Client-Push-Item.jpg new file mode 100644 index 0000000..1062962 Binary files /dev/null and b/contents/Ruby/images/sidekiq/Client-Push-Item.jpg differ diff --git a/contents/Ruby/images/sidekiq/Client-Redis-Sidekiq-Worker.jpg b/contents/Ruby/images/sidekiq/Client-Redis-Sidekiq-Worker.jpg new file mode 100644 index 0000000..d08de7d Binary files /dev/null and b/contents/Ruby/images/sidekiq/Client-Redis-Sidekiq-Worker.jpg differ diff --git a/contents/Ruby/images/sidekiq/Job-in-Redis.jpg b/contents/Ruby/images/sidekiq/Job-in-Redis.jpg new file mode 100644 index 0000000..c79a7a2 Binary files /dev/null and b/contents/Ruby/images/sidekiq/Job-in-Redis.jpg differ diff --git a/contents/Ruby/images/sidekiq/Launcher-Poller-Manager-Processors.jpg b/contents/Ruby/images/sidekiq/Launcher-Poller-Manager-Processors.jpg new file mode 100644 index 0000000..e696d16 Binary files /dev/null and b/contents/Ruby/images/sidekiq/Launcher-Poller-Manager-Processors.jpg differ diff --git a/contents/Ruby/images/sidekiq/Middlewares-Client-Redis-Sidekiq-Worker.jpg b/contents/Ruby/images/sidekiq/Middlewares-Client-Redis-Sidekiq-Worker.jpg new file mode 100644 index 0000000..aad305e Binary files /dev/null and b/contents/Ruby/images/sidekiq/Middlewares-Client-Redis-Sidekiq-Worker.jpg differ diff --git a/contents/Ruby/images/sidekiq/Perform-async-in-Redis.jpg b/contents/Ruby/images/sidekiq/Perform-async-in-Redis.jpg new file mode 100644 index 0000000..f3b98cb Binary files /dev/null and b/contents/Ruby/images/sidekiq/Perform-async-in-Redis.jpg differ diff --git a/contents/Ruby/images/sidekiq/Redis-Sidekiq-Poller.jpg b/contents/Ruby/images/sidekiq/Redis-Sidekiq-Poller.jpg new file mode 100644 index 0000000..52f8c30 Binary files /dev/null and b/contents/Ruby/images/sidekiq/Redis-Sidekiq-Poller.jpg differ diff --git a/contents/Ruby/images/sidekiq/Redis-Sorted-Set.jpg b/contents/Ruby/images/sidekiq/Redis-Sorted-Set.jpg new file mode 100644 index 0000000..597a0ed Binary files /dev/null and b/contents/Ruby/images/sidekiq/Redis-Sorted-Set.jpg differ diff --git a/contents/Ruby/images/sidekiq/Sidekiq-Arch.jpg b/contents/Ruby/images/sidekiq/Sidekiq-Arch.jpg new file mode 100644 index 0000000..1c2bda2 Binary files /dev/null and b/contents/Ruby/images/sidekiq/Sidekiq-Arch.jpg differ diff --git a/contents/Ruby/images/sidekiq/Sidekiq-Cover.jpg b/contents/Ruby/images/sidekiq/Sidekiq-Cover.jpg new file mode 100644 index 0000000..89db8d3 Binary files /dev/null and b/contents/Ruby/images/sidekiq/Sidekiq-Cover.jpg differ diff --git a/contents/Ruby/images/sidekiq/Sidekiq-Middlewares.jpg b/contents/Ruby/images/sidekiq/Sidekiq-Middlewares.jpg new file mode 100644 index 0000000..7630a76 Binary files /dev/null and b/contents/Ruby/images/sidekiq/Sidekiq-Middlewares.jpg differ diff --git a/contents/Ruby/images/sidekiq/Sidekiq-Multi-Processes.jpg b/contents/Ruby/images/sidekiq/Sidekiq-Multi-Processes.jpg new file mode 100644 index 0000000..8af8b1c Binary files /dev/null and b/contents/Ruby/images/sidekiq/Sidekiq-Multi-Processes.jpg differ diff --git a/contents/Ruby/images/sidekiq/sidekiq-logo.png b/contents/Ruby/images/sidekiq/sidekiq-logo.png new file mode 100644 index 0000000..703e98e Binary files /dev/null and b/contents/Ruby/images/sidekiq/sidekiq-logo.png differ diff --git a/contents/Ruby/sidekiq.md b/contents/Ruby/sidekiq.md new file mode 100644 index 0000000..4601dfd --- /dev/null +++ b/contents/Ruby/sidekiq.md @@ -0,0 +1,656 @@ +# Sidekiq 如何处理异步任务 + +[Sidekiq](https://github.com/mperham/sidekiq) 是 Ruby 和 Rails 项目中常用的后台任务处理系统,其本身提供的 API 十分简洁,源代码也非常易于阅读,是一个轻量级的异步处理组件;虽然其本身没有提供太多复杂的功能,但是它的使用和部署非常简单。在这篇文章中,我们将对 Sidekiq 的实现原理进行介绍和分析。 + +![Sidekiq-Cove](images/sidekiq/Sidekiq-Cover.jpg) + +文章中并不会详细介绍 Sidekiq 的使用,也并不是一篇 Sidekiq 的教程,在这里我们会介绍任务的入队过程、Sidekiq 任务在 Redis 中的存储方式和消费者对任务的处理过程,除此之外,文章将介绍 Sidekiq 中间件的实现以及任务重试的原理。 + +## 概述 + +在具体分析介绍 Sidekiq 的实现原理之前,我们需要对整个组件的使用过程进行概述,保证我们对 Sidekiq 的结构有一个总体上的了解。 + +```ruby +class HardWorker + include Sidekiq::Worker + def perform(name, count) + # do something + end +end + +HardWorker.perform_async('bob', 5) +``` + +在这里,我们直接照搬 Sidekiq Wiki 中 [Getting Started](https://github.com/mperham/sidekiq/wiki/Getting-Started) 部分的代码简单展示下它是如何使用的,当我们执行 `HardWorker.perform_async` 方法时,Sidekiq 的 Worker 会将一个异步任务以 JSON 的形式将相关的信息加入 Redis 中并等待消费者对任务的拉取和处理。 + +![Sidekiq-Arch](images/sidekiq/Sidekiq-Arch.jpg) + +Sidekiq 的消费者有三个部分组成,分别是 `Manager`、`Processor` 和 `Poller`;他们三者会相互协作共同完成对 Redis 中任务消费的过程。 + +> 需要注意的是,Sidekiq 中的 `Sidekiq::Worker` 并不是真正用于处理任务的 Worker,负责执行执行任务的类型其实是 `Sidekiq::Processor`;在文章中,当我们提到 Sidekiq Worker 时,其实说的是 `Sidekiq::Processor`,当我们使用了形如 `Sidekiq::Worker` 或者 `Worker` 的形式时,我们说的就是对应的类。 + +## 异步任务的入队 + +当我们对需要异步执行的任务调用类似 `Worker.perform_async` 的方法时,Sidekiq 其实并不会真正去创建一个 `HardWorker` 等 `Worker` 的对象,它实际上会调用 `Worker.client_push` 方法并将当前的 `class` 和 `args` 参数传进去,也就是需要异步执行的类和参数: + +```ruby +def perform_async(*args) + client_push('class'.freeze => self, 'args'.freeze => args) +end +``` + +除了 `Worker.perform_async` 之外,`Worker` 还提供了另外一对用于**在一段时间之后或者某个时间点**执行相应任务的方法 `Worker.perform_at` 和 `Worker.perform_in`: + +```ruby +def perform_in(interval, *args) + int = interval.to_f + now = Time.now.to_f + ts = (int < 1_000_000_000 ? now + int : int) + item = { 'class'.freeze => self, 'args'.freeze => args, 'at'.freeze => ts } + item.delete('at'.freeze) if ts <= now + client_push(item) +end +alias_method :perform_at, :perform_in +``` + +为了使用同一个接口支持两种不同的安排方式(时间点和多久之后),方法内部对传入的 `internal` 进行了判断,当 `interval.to_f < 1_000_000_000` 时就会在一段时间之后执行任务,否则就会以时间点的方式执行任务,虽然 `Worker.perform_at` 和 `Worker.perform_in` 是完全相同的方法,不过我们在使用时还是尽量遵循方法的语义选择两者中更符合逻辑的方法。 + +![Client-Push-Item](images/sidekiq/Client-Push-Item.jpg) + +两种创建异步任务的方式,最终都执行了 `Worker.client_push` 方法并传入了一个哈希,其中可能包含以上三个部分的内容;在方法的实现中,它获取了上下文中的 Redis 池并将传入的 `item` 对象传入 Redis 中: + +```ruby +def client_push(item) + pool = Thread.current[:sidekiq_via_pool] || get_sidekiq_options['pool'.freeze] || Sidekiq.redis_pool + item.keys.each do |key| + item[key.to_s] = item.delete(key) + end + Sidekiq::Client.new(pool).push(item) +end +``` + +简单整理一下,从 `Worker.perform_async` 方法到 `Client#push` 方法整个过程都在对即将加入到 Redis 中队列的哈希进行操作,从添加 `at` 字段到字符串化、再到 `Client#normalize_item` 方法中添加 `jid` 和 `created_at` 字段。 + +```ruby +def push(item) + normed = normalize_item(item) + payload = process_single(item['class'.freeze], normed) + + if payload + raw_push([payload]) + payload['jid'.freeze] + end +end +``` + +所有添加异步任务的方法最终都调用了私有方法 `Client#raw_push` 以及 `Client#atomic_push` 向 Redis 中添加数据,在这时会有两种不同的情况发生,当异步任务需要在未来的某一时间点进行安排时,它会加入 Redis 的一个有序集合: + +```ruby +def atomc_push(conn, payloads) + if payloads.first['at'.freeze] + conn.zadd('schedule'.freeze, payloads.map do |hash| + at = hash.delete('at'.freeze).to_s + [at, Sidekiq.dump_json(hash)] + end) + else + # ... + end +end +``` + +在这个有序集合中,Sidekiq 理所应当地将 `schedule` 作为权重,而其他的全部字段都以 JSON 的格式作为负载传入;但是当 Sidekiq 遇到需要立即执行的异步任务时,实现就有一些不同了: + +```ruby +def atomc_push(conn, payloads) + if payloads.first['at'.freeze] + # ... + else + q = payloads.first['queue'.freeze] + now = Time.now.to_f + to_push = payloads.map do |entry| + entry['enqueued_at'.freeze] = now + Sidekiq.dump_json(entry) + end + conn.sadd('queues'.freeze, q) + conn.lpush("queue:#{q}", to_push) + end +end +``` + +除了设置当前任务的入队时间 `enqueued_at` 之外,Sidekiq 将队列加入到一个大队列 `queues` 的集合中,并且将负载直接推到 `"queue:#{q}"` 数组中等待消费者的拉取,我们稍微梳理一下两种安排异步队列方法的调用过程: + +![Async-Schedule](images/sidekiq/Async-Schedule.jpg) + +### Redis 中的存储 + +无论是立即执行还是需要安排的异步任务都会进入 Redis 的队列中,但是它们之间还是有一些区别的,`Worker.perform_in/at` 会将任务以 `[at, args]` 的形式加入到 `schedules` 有序集中,而 +`Worker.perform_async` 将负载加入到指定的队列,并向整个 Sidekiq 的队列集合 `queues` 中添加该队列。 + +![Perform-async-in-Redis](images/sidekiq/Perform-async-in-Redis.jpg) + +所有的 `payload` 中都包含了一个异步任务需要执行的全部信息,包括该任务的执行的队列 `queue`、异步队列的类 `class`、参数 `args` 以及 `sidekiq_options` 中的全部参数。 + +![Job-in-Redis](images/sidekiq/Job-in-Redis.jpg) + +除了上述参数,一个异步任务还包含诸如 `created_at`、`enqueued_at` 等信息,也有一个通过 `SecureRandom.hex(12)` 生成的任务唯一标识符 `jid`。 + +## Sidekiq 的启动过程 + +作者对于 Sidekiq 印象最深刻的就是它在命令行启动的时候输出的一个字符画,我们能在 `cli.rb` 的 `Cli.banner` 方法中找到这个字符画: + +``` + m, + `$b + .ss, $$: .,d$ + `$$P,d$P' .,md$P"' + ,$$$$$bmmd$$$P^' + .d$$$$$$$$$$P' + $$^' `"^$$$' ____ _ _ _ _ + $: ,$$: / ___|(_) __| | ___| | _(_) __ _ + `b :$$ \___ \| |/ _` |/ _ \ |/ / |/ _` | + $$: ___) | | (_| | __/ <| | (_| | + $$ |____/|_|\__,_|\___|_|\_\_|\__, | + .d$$ |_| +``` + +这一节也将介绍 Sidekiq 的启动过程,在 `bin` 文件夹中的 sidekiq 文件包含的内容就是在命令行执行 `sidekiq` 时执行的代码: + +```ruby +begin + cli = Sidekiq::CLI.instance + cli.parse + cli.run +rescue => e + # ... +end +``` + +这里的代码就是创建了一个 `CLI` 对象,执行 `CLI#parse` 方法对参数进行解析,最后调用 `CLI#run` 方法: + +```ruby +def run + print_banner + + self_read, self_write = IO.pipe + # ... + + launcher = Sidekiq::Launcher.new(options) + begin + launcher.run + while readable_io = IO.select([self_read]) + signal = readable_io.first[0].gets.strip + handle_signal(signal) + end + rescue Interrupt + launcher.stop + end +end +``` + +### 从 Launcher 到 Manager + +`CLI#run` 在执行最开始就会打印 banner,也就是我们在每次启动 Sidekiq 时看到的字符画,而在之后会执行 `Launcher#run` 运行用于处理异步任务的 `Processor` 等对象。 + +![Launcher-Poller-Manager-Processors](images/sidekiq/Launcher-Poller-Manager-Processors.jpg) + +每一个 `Launcher` 都会启动一个 `Manager` 对象和一个 `Poller`,其中 `Manager` 同时管理了多个 `Processor` 对象,这些不同的类之间有着如上图所示的关系。 + +```ruby +def run + @thread = safe_thread("heartbeat", &method(:start_heartbeat)) + @poller.start + @manager.start +end +``` + +`Manager` 会在初始化时根据传入的 `concurrency` 的值创建对应数量的 `Processor`,默认的并行数量为 25;当执行 `Manager#start` 时,就会启动对应数量的**线程**和处理器开始对任务进行处理: + +```ruby +class Manager + def start + @workers.each do |x| + x.start + end + end +end + +class Processor + def start + @thread ||= safe_thread("processor", &method(:run)) + end +end +``` + +从 `Launcher` 的启动到现在只是一个调用 `initialize` 和 `start` 方法的过程,再加上 Sidekiq 源代码非常简单,所以阅读起没有丝毫的难度,也就不做太多的解释了。 + +### 并行模型 + +当处理器开始执行 `Processor#run` 方法时,就开始对所有的任务进行处理了;从总体来看,Sidekiq 使用了多线程的模型对任务进行处理,每一个 `Processor` 都是使用了 `safe_thread` 方法在一个新的线程里面运行的: + +```ruby +def safe_thread(name, &block) + Thread.new do + Thread.current['sidekiq_label'.freeze] = name + watchdog(name, &block) + end +end +``` + +在使用 Sidekiq 时,我们也会在不同的机器上开启多个 Sidekiq Worker,也就是说 Sidekiq 可以以多进程、多线程的方式运行,同时处理大量的异步任务。 + +![Sidekiq-Multi-Processes](images/sidekiq/Sidekiq-Multi-Processes.jpg) + +到目前为止,我们已经分析了异步任务的入队以及 Sidekiq Worker 的启动过程了,接下来即将分析 Sidekiq 对异步任务的处理过程。 + +### 『主题』的订阅 + +作为一个 Sidekiq Worker 进程,它在启动时就会决定选择订阅哪些『主题』去执行,比如当我们使用下面的命令时: + +```sh +> sidekiq -q critical,2 -q default +``` + +`CLI#parse` 方法会对传入的 `-q` 参数进行解析,但是当执行 `sidekiq` 命令却没有传入队列参数时,Sidekiq 只会订阅 `default` 队列中的任务: + +```ruby +def parse(args=ARGV) + # ... + validate! + # ... +end + +def validate! + options[:queues] << 'default' if options[:queues].empty? +end +``` + +同时,默认情况下的队列的优先级都为 `1`,高优先级的队列在当前的任务中可以得到更多的执行机会,实现的方法是通过增加同一个 `queues` 集合中高优先级队列的数量,我们可以在 `CLI#parse_queue` 中找到实现这一功能的代码: + +```ruby +def parse_queue(opts, q, weight=nil) + [weight.to_i, 1].max.times do + (opts[:queues] ||= []) << q + end + opts[:strict] = false if weight.to_i > 0 +end +``` + +到这里,其实我们就完成了设置过程中 Sidekiq Worker 『主题』订阅的功能了,我们将在后面 [执行任务](#执行任务) 的部分具体介绍 Sidekiq 是如何使用这些参数的。 + +## 异步任务的处理 + +从异步任务的入队一节中,我们可以清楚地看到使用 `#perform_async` 和 `#perform_in` 两种方法创建的数据结构 `payload` 最终以不同的方式进入了 Redis 中,所以在这里我们将异步任务的处理分为定时任务和『立即』任务两个部分,分别对它们不同的处理方式进行分析。 + +### 定时任务 + +Sidekiq 使用 `Scheduled::Poller` 对 Redis 中 `schedules` 有序集合中的负载进行处理,其中包括 `retry` 和 `schedule` 两个有序集合中的内容。 + +![Redis-Sorted-Set](images/sidekiq/Redis-Sorted-Set.jpg) + +在 `Poller` 被 `Scheduled::Poller` 启动时会调用 `#start` 方法开始对上述两个有序集合轮训,`retry` 中包含了所有重试的任务,而 `schedule` 就是被安排到指定时间执行的定时任务了: + +```ruby +def start + @thread ||= safe_thread("scheduler") do + initial_wait + while !@done + enqueue + wait + end + end +end +``` + +`Scheduled::Poller#start` 方法内部执行了一个 `while` 循环,在循环内部也只包含入队和等待两个操作,用于入队的方法最终调用了 `Scheduled::Poll::Enq#enqueue_jobs` 方法: + +```ruby +def enqueue_jobs(now=Time.now.to_f.to_s, sorted_sets=SETS) + Sidekiq.redis do |conn| + sorted_sets.each do |sorted_set| + while job = conn.zrangebyscore(sorted_set, '-inf'.freeze, now, :limit => [0, 1]).first do + if conn.zrem(sorted_set, job) + Sidekiq::Client.push(Sidekiq.load_json(job)) + end + end + end + end +end +``` + +传入的 `SETS` 其实就是 `retry` 和 `schedule` 构成的数组,在上述方法中,Sidekiq 通过一个 `Redis#zrangebyscore` 和 `Redis#zrem` 将集合中小于当前时间的任务全部加到立即任务中,最终调用是在前面已经提到过的 `Client#push` 方法将任务推到指定的队列中。 + +![Redis-Sidekiq-Poller](images/sidekiq/Redis-Sidekiq-Poller.jpg) + +由于 `Scheduled::Poller` 并不是不停地对 Redis 中的数据进行处理的,因为当前进程一直都在执行 `Poller#enqueue` 其实是一个非常低效的方式,所以 Sidekiq 会在每次执行 `Poller#enqueue` 之后,执行 `Poller#wait` 方法,随机等待一段时间: + +```ruby +def wait + @sleeper.pop(random_poll_interval) + # ... +end + +def random_poll_interval + poll_interval_average * rand + poll_interval_average.to_f / 2 +end +``` + +随机等待时间的范围在 `[0.5 * poll_interval_average, 1.5 * poll_interval_average]` 之间;通过随机的方式,Sidekiq 可以避免在多个线程处理任务时,短时间内 Redis 接受大量的请求发生延迟等问题,能够保证从长期来看 Redis 接受的请求数是平均的;同时因为 `Scheduled::Poller` 使用了 `#enqueue` 加 `#wait` 对 Redis 中的数据进行消费,所以没有办法保证任务会在指定的时间点执行,**执行的时间一定比安排的时间要晚**,这也是我们在使用 Sidekiq 时需要注意的。 + +> 随机等待的时间其实不止与 `poll_interval_average` 有关,在默认情况下,它是当前进程数的 15 倍,在有 30 个 Sidekiq 线程时,每个线程会每隔 225 ~ 675s 的时间请求一次。 + +### 执行任务 + +定时任务是由 `Scheduled::Poller` 进行处理的,将其中需要执行的异步任务加入到指定的队列中,而这些任务最终都会在 `Processor#run` 真正被执行: + +```ruby +def run + begin + while !@done + process_one + end + @mgr.processor_stopped(self) + rescue Exception => ex + # ... + end +end +``` + +当处理结束或者发生异常时会调用 `Manager#processor_stopped` 或者 `Manager#processor_died` 方法对 `Processor` 进行处理;在处理任务时其实也分为两个部分,也就是 `#fetch` 和 `#process` 两个方法: + +```ruby +def process_one + @job = fetch + process(@job) if @job + @job = nil +end +``` + +我们先来看一下整个方法的调用栈,任务的获取从 `Processor#process_one` 一路调用下来,直到 `BasicFetch#retrive_work` 返回了 `UnitOfWork` 对象,返回的对象会经过分发最后执行对应类的 `#perform` 传入参数真正运行该任务: + +``` +Processor#process_one +├── Processor#fetch +│   └── Processor#get_one +│      └── BasicFetch#retrive_work +│      ├── Redis#brpop +│      └── UnitOfWork#new +└── Processor#process +    ├── Processor#dispatch +    ├── Processor#execute_job +    └── Worker#perform +``` + +对于任务的获取,我们需要关注的就是 `BasicFetch#retrive_work` 方法,他会从 Redis 中相应队列的有序数组中 `Redis#brpop` 出一个任务,然后封装成 `UnitOfWork` 对象后返回。 + +```ruby +def retrieve_work + work = Sidekiq.redis { |conn| conn.brpop(*queues_cmd) } + UnitOfWork.new(*work) if work +end +``` + +`#queues_cmd` 这个实例方法其实就用到了在主题的订阅一节中的 `queues` 参数,该参数会在 `Processor` 初始化是创建一个 `BasicFetch` 策略对象,最终在 `BasicFetch#queues_cmd` 方法调用时返回一个类似下面的数组: + +```ruby +queue:high +queue:high +queue:high +queue:low +queue:low +queue:default +``` + +这样就可以实现了队列的优先级这一个功能了,返回的 `UnitOfWork` 其实是一个通过 `Struct.new` 创建的结构体,它会在 `Processor#process` 方法中作为资源被处理: + +```ruby +def process(work) + jobstr = work.job + queue = work.queue_name + + begin + # ... + + job_hash = Sidekiq.load_json(jobstr) + dispatch(job_hash, queue) do |worker| + Sidekiq.server_middleware.invoke(worker, job_hash, queue) do + execute_job(worker, cloned(job_hash['args'.freeze])) + end + end + rescue Exception => ex + # ... + end +end +``` + +该方法对任务的执行其实总共有四个步骤: + +1. 将 Redis 中存储的字符串加载为 JSON; +2. 执行 `Processor#dispatch` 方法并在内部提供方法重试等功能,同时也实例化一个 `Sidekiq::Worker` 对象; +3. 依次执行服务端的中间件,可能会对参数进行更新; +4. 调用 `Processor#execute_job` 方法执行任务; + +而最后调用的时用于执行任务的方法 `Processor#execute_job`,它的实现也是到目前为止最为简单的方法之一了: + +```ruby +def execute_job(worker, cloned_args) + worker.perform(*cloned_args) +end +``` + +该方法在**线程**中执行了客户端创建的 `Worker` 类的实例方法 `#perform` 并传入了经过两侧中间件处理后的参数。 + +### 小结 + +到目前为止,Sidekiq Worker 对任务的消费过程就是圆满的了,从客户端创建一个拥有 `#perform` 方法的 `Worker` 到消费者去执行该方法形成了一个闭环,完成了对任务的调度。 + +![Client-Redis-Sidekiq-Worker](images/sidekiq/Client-Redis-Sidekiq-Worker.jpg) + +Sidekiq 是一个非常轻量级的任务调度系统,它使用 Redis 作为整个系统的消息队列,在两侧分别建立了生产者和消费者的模块,不过除了这几个比较重要的模块,Sidekiq 中还有一些功能是我们无法忽略的,比如中间件、兼容 ActiveJob 甚至是测试的实现,都是我们需要去了解的;接下来,我们将介绍和分析主干之外的『分叉』功能。 + +## 中间件 + +中间件模块是 Sidekiq 为我们在整个任务的处理流程提供的两个钩子,一个是在客户端的钩子,另一个在 Sidekiq Worker 中。 + +![Middlewares-Client-Redis-Sidekiq-Worker](images/sidekiq/Middlewares-Client-Redis-Sidekiq-Worker.jpg) + +中间件的使用其实非常简单,我们默认所有的中间件都会拥有一个实例方法 `#call` 并接受 `worker`、`job` 和 `queue` 三个参数,在使用时也只需要直接调用 `Chain#add` 方法将其加入数组就可以了: + +```ruby +class AcmeCo::MyMiddleware + def call(worker, job, queue) + # ... + end +end + +# config/initializers/sidekiq.rb +Sidekiq.configure_server do |config| + config.server_middleware do |chain| + chain.add AcmeCo::MyMiddleware + end +end +``` + +Sidekiq 将中间件分为了客户端和服务端两个部分,这两个部分的中间件其实并不是严格意义上的在执行之前,由于执行时间点的不同,导致它们有不同的功能: + ++ 服务端中间件是『包围』了任务执行过程的,我们可以在中间件中使用 `begin`、`rescue` 语句,这样当任务出现问题时,我们就可以拿到异常了; ++ 客户端中间件在任务即将被推入 Redis 之前运行,它能够阻止任务进入 Redis 并且允许我们在任务入队前对其进行修改和停止; + +当我们对 Sidekiq 中间的使用都有一定的了解时,就可以开始分析中间件的实现了。 + +### 实现 + +无论是异步任务真正进入队列之前,还是在客户端处理,跟任务有关的信息都会先通过一个预处理流程,客户端和服务端两个中间件的链式调用都使用 `Middleware::Chain` 中的类进行处理的: + +```ruby +class Chain + include Enumerable + attr_reader :entries + + def initialize + @entries = [] + yield self if block_given? + end + + def remove(klass); end + def add(klass, *args); end + def prepend(klass, *args); end + def insert_before(oldklass, newklass, *args); end + def insert_after(oldklass, newklass, *args); end +end +``` + +每一个 `Middleware::Chain` 中都包含一系列的 `Entry`,其中存储了中间件的相关信息,无论是客户端还是服务端都会在执行之前对每一个异步任务的参数执行 `invoke` 方法调用 `Middleware::Chain` 对象中的所有中间件: + +```ruby +def invoke(*args) + chain = retrieve.dup + traverse_chain = lambda do + if chain.empty? + yield + else + chain.shift.call(*args, &traverse_chain) + end + end + traverse_chain.call +end + +``` + +`Chain#invoke` 会对其持有的每一个中间件都执行 `#call` 方法,中间件都可以对异步任务的参数进行改变或者进行一些记录日志等操作,最后执行传入的 block 并返回结果。 + +![Sidekiq-Middlewares](images/sidekiq/Sidekiq-Middlewares.jpg) + +当异步队列入队时,就会执行 `Client#process_single` 方法调用 Sidekiq 载入中的全部中间件最后返回新的 `item` 对象: + +```ruby +def process_single(worker_class, item) + queue = item['queue'.freeze] + middleware.invoke(worker_class, item, queue, @redis_pool) do + item + end +end +``` + +每一个 Sidekiq Worker 在处理中间件时也基本遵循相同的逻辑,如 `#process` 方法先先执行各种中间件,最后再运行 block 中的内容。 + +```ruby +def process(work) + jobstr = work.job + queue = work.queue_name + + begin + # ... + + job_hash = Sidekiq.load_json(jobstr) + Sidekiq.server_middleware.invoke(worker, job_hash, queue) do + execute_job(worker, cloned(job_hash['args'.freeze])) + end + rescue Exception => ex + # ... + end +end +``` + +在 `#execute_job` 方法执行期间,由于异步任务可能抛出异常,在这时,我们注册的中间件就可以根据情况对异常进行捕获并选择是否对异常进行处理或者抛给上层了。 + +## 任务的重试 + +Sidekiq 中任务的重试是由 `JobRetry` 负责的,`Prcessor` 中的 `#dispatch` 方法中调用了 `JobRetry#global` 方法捕获在异步任务执行过程中发生的错误: + +```ruby +def dispatch(job_hash, queue) + pristine = cloned(job_hash) + + # ... + @retrier.global(pristine, queue) do + klass = constantize(job_hash['class'.freeze]) + worker = klass.new + worker.jid = job_hash['jid'.freeze] + @retrier.local(worker, pristine, queue) do + yield worker + end + end +end +``` + +任务的执行过程分别调用了两个 `JobRetry` 的方法 `#global` 和 `#local`,这两个方法在实现上差不多,都将执行异步任务的 block 包在了一个 `begin`、`rescue` 中,选择在合适的时间重试: + +```ruby +def local(worker, msg, queue) + yield +# ... +rescue Exception => e + raise Sidekiq::Shutdown if exception_caused_by_shutdown?(e) + + if msg['retry'] == nil + msg['retry'] = worker.class.get_sidekiq_options['retry'] + end + + raise e unless msg['retry'] + attempt_retry(worker, msg, queue, e) + raise Skip +end +``` + +如果我们在定义 `Worker` 时就禁用了重试,那么在这里就会直接抛出上层的异常,否则就会进入 `#attempt_retry` 方法安排任务进行重试: + +```ruby +def attempt_retry(worker, msg, queue, exception) + max_retry_attempts = retry_attempts_from(msg['retry'], @max_retries) + + msg['queue'] = if msg['retry_queue'] + msg['retry_queue'] + else + queue + end + + count = if msg['retry_count'] + msg['retried_at'] = Time.now.to_f + msg['retry_count'] += 1 + else + msg['failed_at'] = Time.now.to_f + msg['retry_count'] = 0 + end + + if count < max_retry_attempts + delay = delay_for(worker, count, exception) + retry_at = Time.now.to_f + delay + payload = Sidekiq.dump_json(msg) + Sidekiq.redis do |conn| + conn.zadd('retry', retry_at.to_s, payload) + end + else + retries_exhausted(worker, msg, exception) + end +end +``` + +在上面其实我们提到过,`Poller` 每次会从两个有序集合 `retry` 和 `schedule` 中查找到时的任务加入到对应的队列中,在 `#attempt_retry` 方法中,就可以找到看到 `retry` 队列中的元素是如何加入的了。 + +当任务的重试次数超过了限定的重试次数之后,就会执行 `#retries_exhausted` 以及 `# send_to_morgue` 这一方法,将任务的负载加入 `DeadSet` 对象中: + +```ruby +def send_to_morgue(msg) + payload = Sidekiq.dump_json(msg) + DeadSet.new.kill(payload) +end +``` + +这样整个任务的重试过程就结束了,Sidekiq 使用 `begin`、`rescue` 捕获整个流程中出现的异常,并根据传入的 `retry_count` 参数进行重试,调度过程还是非常简洁也非常容易理解的。 + +## 总结 + +作为一个 Ruby 社区中广泛被使用的异步任务处理的依赖,它的实现是很简单的并且其源代码非常易于阅读,整体的架构也非常清晰。 + +![Middlewares-Client-Redis-Sidekiq-Worker](images/sidekiq/Middlewares-Client-Redis-Sidekiq-Worker.jpg) + +使用键值的内存数据库 Redis 作为客户端和 Worker 之间的桥梁,Redis 的使用简化了 Sidekiq 的很多逻辑,同时对中间件的支持也使其有着良好的扩展性,不过正其实现简单,所以例如任务取消以及定时任务这种比较常见的功能其本身都没有实现,有的是 Sidekiq 本身设计问题导致的,有的需要另外的插件,不过在绝大多数情况下,Sidekiq 都能完全满足我们的需要,解决绝大多数的问题。 + +> Follow: [Draveness · GitHub](https://github.com/Draveness) + +## References + ++ [Sidekiq](https://github.com/mperham/sidekiq) ++ [Sidekiq 任务调度流程分析](https://ruby-china.org/topics/31470) + + diff --git "a/SDWebImage/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- SDWebImage.md" "b/contents/SDWebImage/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- SDWebImage.md" similarity index 98% rename from "SDWebImage/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- SDWebImage.md" rename to "contents/SDWebImage/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- SDWebImage.md" index 5dd27a7..394654c 100644 --- "a/SDWebImage/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- SDWebImage.md" +++ "b/contents/SDWebImage/iOS \346\272\220\344\273\243\347\240\201\345\210\206\346\236\220 --- SDWebImage.md" @@ -48,7 +48,7 @@ placeholderImage:(UIImage *)placeholder; ``` -这一方法为入口研究一下 `SDWebImage` 是怎样工作的. 我们打开上面这段方法的实现代码 [UIImageView+WebCache.m](https://github.com/rs/SDWebImage/blob/master/SDWebImage/UIImageView%2BWebCache.m) +这一方法为入口研究一下 `SDWebImage` 是怎样工作的. 我们打开上面这段方法的实现代码 [UIImageView+WebCache.m](https://github.com/rs/SDWebImage/blob/master/contents/SDWebImage/UIImageView%2BWebCache.m) 当然你也可以 `git clone git@github.com:rs/SDWebImage.git` 到本地来查看. @@ -192,7 +192,7 @@ dispatch_main_sync_safe(^{ ###SDWebImageManager -在 [SDWebImageManager.h](https://github.com/rs/SDWebImage/blob/master/SDWebImage/SDWebImageManager.h) 中你可以看到关于 `SDWebImageManager` 的描述: +在 [SDWebImageManager.h](https://github.com/rs/SDWebImage/blob/master/contents/SDWebImage/SDWebImageManager.h) 中你可以看到关于 `SDWebImageManager` 的描述: > The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). You can use this class directly to benefit from web image downloading with caching in another context than a UIView. @@ -313,7 +313,7 @@ operation.cancelBlock = ^{ ###SDWebImageCache -[SDWebImageCache.h](https://github.com/rs/SDWebImage/blob/master/SDWebImage/SDImageCache.h) 这个类在源代码中有这样的注释: +[SDWebImageCache.h](https://github.com/rs/SDWebImage/blob/master/contents/SDWebImage/SDImageCache.h) 这个类在源代码中有这样的注释: > SDImageCache maintains a memory cache and an optional disk cache. @@ -365,7 +365,7 @@ if (diskImage) { ###SDWebImageDownloader -按照之前的惯例, 我们先来看一下 [SDWebImageDownloader.h](https://github.com/rs/SDWebImage/blob/master/SDWebImage/SDWebImageDownloader.h) 中对这个类的描述. +按照之前的惯例, 我们先来看一下 [SDWebImageDownloader.h](https://github.com/rs/SDWebImage/blob/master/contents/SDWebImage/SDWebImageDownloader.h) 中对这个类的描述. > Asynchronous downloader dedicated and optimized for image loading. diff --git a/contents/architecture/images/controller/Binder-View-ViewModel.jpg b/contents/architecture/images/controller/Binder-View-ViewModel.jpg new file mode 100644 index 0000000..90fb060 Binary files /dev/null and b/contents/architecture/images/controller/Binder-View-ViewModel.jpg differ diff --git a/contents/architecture/images/controller/Controller-Only.jpg b/contents/architecture/images/controller/Controller-Only.jpg new file mode 100644 index 0000000..ef53f45 Binary files /dev/null and b/contents/architecture/images/controller/Controller-Only.jpg differ diff --git a/contents/architecture/images/controller/Controller-RootView.jpg b/contents/architecture/images/controller/Controller-RootView.jpg new file mode 100644 index 0000000..b7dc015 Binary files /dev/null and b/contents/architecture/images/controller/Controller-RootView.jpg differ diff --git a/contents/architecture/images/controller/Coupling-View-And-Model.jpg b/contents/architecture/images/controller/Coupling-View-And-Model.jpg new file mode 100644 index 0000000..9141e47 Binary files /dev/null and b/contents/architecture/images/controller/Coupling-View-And-Model.jpg differ diff --git a/contents/architecture/images/controller/Eager-Lazy-Initialization.jpg b/contents/architecture/images/controller/Eager-Lazy-Initialization.jpg new file mode 100644 index 0000000..150b9a0 Binary files /dev/null and b/contents/architecture/images/controller/Eager-Lazy-Initialization.jpg differ diff --git a/contents/architecture/images/controller/MVC-MVVM-MVP.jpg b/contents/architecture/images/controller/MVC-MVVM-MVP.jpg new file mode 100644 index 0000000..914cd9f Binary files /dev/null and b/contents/architecture/images/controller/MVC-MVVM-MVP.jpg differ diff --git a/contents/architecture/images/controller/MVC-in-iOS.jpg b/contents/architecture/images/controller/MVC-in-iOS.jpg new file mode 100644 index 0000000..4f6f7fe Binary files /dev/null and b/contents/architecture/images/controller/MVC-in-iOS.jpg differ diff --git a/contents/architecture/images/controller/Model-View-Controller.jpg b/contents/architecture/images/controller/Model-View-Controller.jpg new file mode 100644 index 0000000..4b130b9 Binary files /dev/null and b/contents/architecture/images/controller/Model-View-Controller.jpg differ diff --git a/contents/architecture/images/controller/Model-View-VIewModel.jpg b/contents/architecture/images/controller/Model-View-VIewModel.jpg new file mode 100644 index 0000000..04b657b Binary files /dev/null and b/contents/architecture/images/controller/Model-View-VIewModel.jpg differ diff --git a/contents/architecture/images/controller/UINavigationController-UITabBarController.jpg b/contents/architecture/images/controller/UINavigationController-UITabBarController.jpg new file mode 100644 index 0000000..6b7e651 Binary files /dev/null and b/contents/architecture/images/controller/UINavigationController-UITabBarController.jpg differ diff --git a/contents/architecture/images/controller/UITableView-DataSource.jpg b/contents/architecture/images/controller/UITableView-DataSource.jpg new file mode 100644 index 0000000..9de850e Binary files /dev/null and b/contents/architecture/images/controller/UITableView-DataSource.jpg differ diff --git a/contents/architecture/images/model/404.gif b/contents/architecture/images/model/404.gif new file mode 100644 index 0000000..fb5e4b8 Binary files /dev/null and b/contents/architecture/images/model/404.gif differ diff --git a/contents/architecture/images/model/Abstract-Manager.png b/contents/architecture/images/model/Abstract-Manager.png new file mode 100644 index 0000000..54d0a09 Binary files /dev/null and b/contents/architecture/images/model/Abstract-Manager.png differ diff --git a/contents/architecture/images/model/Abstract-Request.jpg b/contents/architecture/images/model/Abstract-Request.jpg new file mode 100644 index 0000000..c961a52 Binary files /dev/null and b/contents/architecture/images/model/Abstract-Request.jpg differ diff --git a/contents/architecture/images/model/Abstract-Request.png b/contents/architecture/images/model/Abstract-Request.png new file mode 100644 index 0000000..a0f28bd Binary files /dev/null and b/contents/architecture/images/model/Abstract-Request.png differ diff --git a/contents/architecture/images/model/Dynamic-Static.png b/contents/architecture/images/model/Dynamic-Static.png new file mode 100644 index 0000000..20ab21e Binary files /dev/null and b/contents/architecture/images/model/Dynamic-Static.png differ diff --git a/contents/architecture/images/model/JSON-Model.jpg b/contents/architecture/images/model/JSON-Model.jpg new file mode 100644 index 0000000..1bec2ef Binary files /dev/null and b/contents/architecture/images/model/JSON-Model.jpg differ diff --git a/contents/architecture/images/model/JSON-to-Model.jpg b/contents/architecture/images/model/JSON-to-Model.jpg new file mode 100644 index 0000000..ef44ed1 Binary files /dev/null and b/contents/architecture/images/model/JSON-to-Model.jpg differ diff --git a/contents/architecture/images/model/MVCS-Architecture.png b/contents/architecture/images/model/MVCS-Architecture.png new file mode 100644 index 0000000..1a86ce4 Binary files /dev/null and b/contents/architecture/images/model/MVCS-Architecture.png differ diff --git a/contents/architecture/images/model/Manager-And-Request.jpg b/contents/architecture/images/model/Manager-And-Request.jpg new file mode 100644 index 0000000..b00f6ed Binary files /dev/null and b/contents/architecture/images/model/Manager-And-Request.jpg differ diff --git a/contents/architecture/images/model/Model-And-Dictioanry.jpg b/contents/architecture/images/model/Model-And-Dictioanry.jpg new file mode 100644 index 0000000..a7de03f Binary files /dev/null and b/contents/architecture/images/model/Model-And-Dictioanry.jpg differ diff --git a/contents/architecture/images/model/Model-in-Client.jpg b/contents/architecture/images/model/Model-in-Client.jpg new file mode 100644 index 0000000..dc40f70 Binary files /dev/null and b/contents/architecture/images/model/Model-in-Client.jpg differ diff --git a/contents/architecture/images/model/Relation-Between-Database-And-Model.jpg b/contents/architecture/images/model/Relation-Between-Database-And-Model.jpg new file mode 100644 index 0000000..1033a67 Binary files /dev/null and b/contents/architecture/images/model/Relation-Between-Database-And-Model.jpg differ diff --git a/contents/architecture/images/model/Server-MVC.jpg b/contents/architecture/images/model/Server-MVC.jpg new file mode 100644 index 0000000..86dffee Binary files /dev/null and b/contents/architecture/images/model/Server-MVC.jpg differ diff --git a/contents/architecture/images/model/Service-And-API.jpg b/contents/architecture/images/model/Service-And-API.jpg new file mode 100644 index 0000000..4605caa Binary files /dev/null and b/contents/architecture/images/model/Service-And-API.jpg differ diff --git a/contents/architecture/images/model/client-black-box.jpg b/contents/architecture/images/model/client-black-box.jpg new file mode 100644 index 0000000..231465e Binary files /dev/null and b/contents/architecture/images/model/client-black-box.jpg differ diff --git a/contents/architecture/images/model/web-black-box.jpg b/contents/architecture/images/model/web-black-box.jpg new file mode 100644 index 0000000..85bcc24 Binary files /dev/null and b/contents/architecture/images/model/web-black-box.jpg differ diff --git a/contents/architecture/images/mvx/Binder-View-ViewModel.jpg b/contents/architecture/images/mvx/Binder-View-ViewModel.jpg new file mode 100644 index 0000000..90fb060 Binary files /dev/null and b/contents/architecture/images/mvx/Binder-View-ViewModel.jpg differ diff --git a/contents/architecture/images/mvx/Essential-Dependencies-in-MVC.jpg b/contents/architecture/images/mvx/Essential-Dependencies-in-MVC.jpg new file mode 100644 index 0000000..4de88f6 Binary files /dev/null and b/contents/architecture/images/mvx/Essential-Dependencies-in-MVC.jpg differ diff --git a/contents/architecture/images/mvx/Essential-Dependencies-in-Passive-View.jpg b/contents/architecture/images/mvx/Essential-Dependencies-in-Passive-View.jpg new file mode 100644 index 0000000..8415514 Binary files /dev/null and b/contents/architecture/images/mvx/Essential-Dependencies-in-Passive-View.jpg differ diff --git "a/contents/architecture/images/mvx/MVC-\005in-Rails-with-different-view.jpg" "b/contents/architecture/images/mvx/MVC-\005in-Rails-with-different-view.jpg" new file mode 100644 index 0000000..d58714a Binary files /dev/null and "b/contents/architecture/images/mvx/MVC-\005in-Rails-with-different-view.jpg" differ diff --git a/contents/architecture/images/mvx/MVC-1979.jpg b/contents/architecture/images/mvx/MVC-1979.jpg new file mode 100644 index 0000000..fba8359 Binary files /dev/null and b/contents/architecture/images/mvx/MVC-1979.jpg differ diff --git a/contents/architecture/images/mvx/MVC-App-Arch.jpg b/contents/architecture/images/mvx/MVC-App-Arch.jpg new file mode 100644 index 0000000..7387d04 Binary files /dev/null and b/contents/architecture/images/mvx/MVC-App-Arch.jpg differ diff --git a/contents/architecture/images/mvx/MVC-MVC.jpg b/contents/architecture/images/mvx/MVC-MVC.jpg new file mode 100644 index 0000000..566a8ea Binary files /dev/null and b/contents/architecture/images/mvx/MVC-MVC.jpg differ diff --git a/contents/architecture/images/mvx/MVC-MVVM-MVP.jpg b/contents/architecture/images/mvx/MVC-MVVM-MVP.jpg new file mode 100644 index 0000000..914cd9f Binary files /dev/null and b/contents/architecture/images/mvx/MVC-MVVM-MVP.jpg differ diff --git a/contents/architecture/images/mvx/MVC-Web-App.jpg b/contents/architecture/images/mvx/MVC-Web-App.jpg new file mode 100644 index 0000000..879b7d6 Binary files /dev/null and b/contents/architecture/images/mvx/MVC-Web-App.jpg differ diff --git a/contents/architecture/images/mvx/MVC-in-ASP.NET.png b/contents/architecture/images/mvx/MVC-in-ASP.NET.png new file mode 100644 index 0000000..9e1c4e2 Binary files /dev/null and b/contents/architecture/images/mvx/MVC-in-ASP.NET.png differ diff --git a/contents/architecture/images/mvx/MVC-in-Wikipedia.jpg b/contents/architecture/images/mvx/MVC-in-Wikipedia.jpg new file mode 100644 index 0000000..5d54d8e Binary files /dev/null and b/contents/architecture/images/mvx/MVC-in-Wikipedia.jpg differ diff --git a/contents/architecture/images/mvx/MVC-with-ASP.NET.jpg b/contents/architecture/images/mvx/MVC-with-ASP.NET.jpg new file mode 100644 index 0000000..8e357fa Binary files /dev/null and b/contents/architecture/images/mvx/MVC-with-ASP.NET.jpg differ diff --git a/contents/architecture/images/mvx/MVC-with-Rails.jpg b/contents/architecture/images/mvx/MVC-with-Rails.jpg new file mode 100644 index 0000000..c489b2c Binary files /dev/null and b/contents/architecture/images/mvx/MVC-with-Rails.jpg differ diff --git a/contents/architecture/images/mvx/MVC-with-Spring.jpg b/contents/architecture/images/mvx/MVC-with-Spring.jpg new file mode 100644 index 0000000..f9ce7be Binary files /dev/null and b/contents/architecture/images/mvx/MVC-with-Spring.jpg differ diff --git a/contents/architecture/images/mvx/MVC-with-iOS.jpg b/contents/architecture/images/mvx/MVC-with-iOS.jpg new file mode 100644 index 0000000..be9dc83 Binary files /dev/null and b/contents/architecture/images/mvx/MVC-with-iOS.jpg differ diff --git a/contents/architecture/images/mvx/Main-Controller.jpg b/contents/architecture/images/mvx/Main-Controller.jpg new file mode 100644 index 0000000..d5162c3 Binary files /dev/null and b/contents/architecture/images/mvx/Main-Controller.jpg differ diff --git a/contents/architecture/images/mvx/Main-View-in-MVP.jpg b/contents/architecture/images/mvx/Main-View-in-MVP.jpg new file mode 100644 index 0000000..25f7e22 Binary files /dev/null and b/contents/architecture/images/mvx/Main-View-in-MVP.jpg differ diff --git a/contents/architecture/images/mvx/Model-View-ViewModel.jpg b/contents/architecture/images/mvx/Model-View-ViewModel.jpg new file mode 100644 index 0000000..04b657b Binary files /dev/null and b/contents/architecture/images/mvx/Model-View-ViewModel.jpg differ diff --git a/contents/architecture/images/mvx/Observer-Synchronization.jpg b/contents/architecture/images/mvx/Observer-Synchronization.jpg new file mode 100644 index 0000000..9064ca9 Binary files /dev/null and b/contents/architecture/images/mvx/Observer-Synchronization.jpg differ diff --git a/contents/architecture/images/mvx/PM-View-Domain-Object.jpg b/contents/architecture/images/mvx/PM-View-Domain-Object.jpg new file mode 100644 index 0000000..2d84685 Binary files /dev/null and b/contents/architecture/images/mvx/PM-View-Domain-Object.jpg differ diff --git a/contents/architecture/images/mvx/PM-and-MVVM.jpg b/contents/architecture/images/mvx/PM-and-MVVM.jpg new file mode 100644 index 0000000..3d6934a Binary files /dev/null and b/contents/architecture/images/mvx/PM-and-MVVM.jpg differ diff --git a/contents/architecture/images/mvx/PassIve-View.jpg b/contents/architecture/images/mvx/PassIve-View.jpg new file mode 100644 index 0000000..0aeea60 Binary files /dev/null and b/contents/architecture/images/mvx/PassIve-View.jpg differ diff --git a/contents/architecture/images/mvx/Passive-Model.jpg b/contents/architecture/images/mvx/Passive-Model.jpg new file mode 100644 index 0000000..7d2a7b8 Binary files /dev/null and b/contents/architecture/images/mvx/Passive-Model.jpg differ diff --git a/contents/architecture/images/mvx/Passive-View-with-Tags.jpg b/contents/architecture/images/mvx/Passive-View-with-Tags.jpg new file mode 100644 index 0000000..3882e95 Binary files /dev/null and b/contents/architecture/images/mvx/Passive-View-with-Tags.jpg differ diff --git a/contents/architecture/images/mvx/Presentation-Domain.jpg b/contents/architecture/images/mvx/Presentation-Domain.jpg new file mode 100644 index 0000000..78b58d8 Binary files /dev/null and b/contents/architecture/images/mvx/Presentation-Domain.jpg differ diff --git a/contents/architecture/images/mvx/Presentation-Model.jpg b/contents/architecture/images/mvx/Presentation-Model.jpg new file mode 100644 index 0000000..09543dd Binary files /dev/null and b/contents/architecture/images/mvx/Presentation-Model.jpg differ diff --git a/contents/architecture/images/mvx/Standard-MVC.jpg b/contents/architecture/images/mvx/Standard-MVC.jpg new file mode 100644 index 0000000..55fa495 Binary files /dev/null and b/contents/architecture/images/mvx/Standard-MVC.jpg differ diff --git a/contents/architecture/images/mvx/Standard-MVP.jpg b/contents/architecture/images/mvx/Standard-MVP.jpg new file mode 100644 index 0000000..ac880e8 Binary files /dev/null and b/contents/architecture/images/mvx/Standard-MVP.jpg differ diff --git a/contents/architecture/images/mvx/Supervising-Controller-With-Tag.jpg b/contents/architecture/images/mvx/Supervising-Controller-With-Tag.jpg new file mode 100644 index 0000000..b375df8 Binary files /dev/null and b/contents/architecture/images/mvx/Supervising-Controller-With-Tag.jpg differ diff --git a/contents/architecture/images/mvx/Supervising-Controller.jpg b/contents/architecture/images/mvx/Supervising-Controller.jpg new file mode 100644 index 0000000..c5ebeaf Binary files /dev/null and b/contents/architecture/images/mvx/Supervising-Controller.jpg differ diff --git a/contents/architecture/images/view/Android-View-Tree.jpg b/contents/architecture/images/view/Android-View-Tree.jpg new file mode 100644 index 0000000..496aa81 Binary files /dev/null and b/contents/architecture/images/view/Android-View-Tree.jpg differ diff --git a/contents/architecture/images/view/AutoLayout.jpg b/contents/architecture/images/view/AutoLayout.jpg new file mode 100644 index 0000000..3638fa0 Binary files /dev/null and b/contents/architecture/images/view/AutoLayout.jpg differ diff --git a/contents/architecture/images/view/Frame-And-Components.jpg b/contents/architecture/images/view/Frame-And-Components.jpg new file mode 100644 index 0000000..d058a17 Binary files /dev/null and b/contents/architecture/images/view/Frame-And-Components.jpg differ diff --git a/contents/architecture/images/view/Node-Delegate-Filter.jpg b/contents/architecture/images/view/Node-Delegate-Filter.jpg new file mode 100644 index 0000000..fb4e1b2 Binary files /dev/null and b/contents/architecture/images/view/Node-Delegate-Filter.jpg differ diff --git a/contents/architecture/images/view/Node-Delegate-UIView.jpg b/contents/architecture/images/view/Node-Delegate-UIView.jpg new file mode 100644 index 0000000..c87cc7e Binary files /dev/null and b/contents/architecture/images/view/Node-Delegate-UIView.jpg differ diff --git a/contents/architecture/images/view/UIStackView.jpg b/contents/architecture/images/view/UIStackView.jpg new file mode 100644 index 0000000..b595c65 Binary files /dev/null and b/contents/architecture/images/view/UIStackView.jpg differ diff --git a/contents/architecture/images/view/UIView-And-Subclasses.jpg b/contents/architecture/images/view/UIView-And-Subclasses.jpg new file mode 100644 index 0000000..2082c8f Binary files /dev/null and b/contents/architecture/images/view/UIView-And-Subclasses.jpg differ diff --git a/contents/architecture/images/view/animation.gif b/contents/architecture/images/view/animation.gif new file mode 100644 index 0000000..e5c9f08 Binary files /dev/null and b/contents/architecture/images/view/animation.gif differ diff --git a/contents/architecture/images/view/html-css.jpg b/contents/architecture/images/view/html-css.jpg new file mode 100644 index 0000000..664c4fd Binary files /dev/null and b/contents/architecture/images/view/html-css.jpg differ diff --git a/contents/architecture/images/view/lottie.jpg b/contents/architecture/images/view/lottie.jpg new file mode 100644 index 0000000..9d5c15e Binary files /dev/null and b/contents/architecture/images/view/lottie.jpg differ diff --git a/contents/architecture/images/view/texture.png b/contents/architecture/images/view/texture.png new file mode 100644 index 0000000..d1e84d6 Binary files /dev/null and b/contents/architecture/images/view/texture.png differ diff --git a/contents/architecture/images/view/vue.jpg b/contents/architecture/images/view/vue.jpg new file mode 100644 index 0000000..3f1dc7c Binary files /dev/null and b/contents/architecture/images/view/vue.jpg differ diff --git a/contents/architecture/images/view/vue.png b/contents/architecture/images/view/vue.png new file mode 100644 index 0000000..74389d8 Binary files /dev/null and b/contents/architecture/images/view/vue.png differ diff --git a/contents/architecture/mvx-controller.md b/contents/architecture/mvx-controller.md new file mode 100644 index 0000000..15c509c --- /dev/null +++ b/contents/architecture/mvx-controller.md @@ -0,0 +1,591 @@ +# 谈谈 MVX 中的 Controller + ++ [谈谈 MVX 中的 Model](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-model.md) ++ [谈谈 MVX 中的 View](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-view.md) ++ [谈谈 MVX 中的 Controller](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-controller.md) ++ [浅谈 MVC、MVP 和 MVVM 架构模式](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx.md) + +> Follow GitHub: [Draveness](https://github.com/Draveness) + +在前两篇文章中,我们已经对 iOS 中的 Model 层以及 View 层进行了分析,划分出了它们的具体职责,其中 Model 层除了负责数据的持久存储、缓存工作,还要负责所有 HTTP 请求的发出等工作;而对于 View 层的职责,我们并没有做出太多的改变,有的只是细分其内部的视图种类,以及分离 `UIView` 不应该具有的属性和功能。 + +> 如果想要具体了解笔者对 Model 层以及 View 层的理解和设计,这是前面两篇文章的链接:[谈谈 MVX 中的 Model 层](http://draveness.me/mvx-model.html)、[谈谈 MVX 中的 View 层](http://draveness.me/mvx-view.html) + +这是 MVX 系列的第三篇文章,而这篇文章准备介绍整个 MVX 中无法避免的话题,也就是 X 这一部分。 + +## X 是什么 + +在进入正题之前,我们首先要知道这里的 X 到底是什么?无论是在 iOS 开发领域还是其它的领域,造出了一堆又一堆的名词,除了我们最常见的 MVC 和 MVVM 以及 Android 中的 MVP 还有一些其他的奇奇怪怪的名词。 + +![MVC-MVVM-MVP](images/controller/MVC-MVVM-MVP.jpg) + +模型层和视图层是整个客户端应用不可分割的一部分,它们的职责非常清楚,一个用于处理本地数据的获取以及存储,另一个用于展示内容、接受用户的操作与事件;在这种情况下,整个应用中的其它功能和逻辑就会被自然而然的扔到 X 层中。 + +这个 X 在 MVC 中就是 Controller 层、在 MVVM 中就是 ViewModel 层,而在 MVP 中就是 Presenter 层,这篇文章介绍的就是 MVC 中的控制器层 Controller。 + +## 臃肿的 Controller + +从 Cocoa Touch 框架使用十年以来,iOS 开发者就一直遵循框架中的设计,使用 Model-View-Controller 的架构模式开发 iOS 应用程序,下面也是对 iOS 中 MVC 的各层交互的最简单的说明。 + +![Model-View-Controlle](images/controller/Model-View-Controller.jpg) + +iOS 中的 Model 层大多为 `NSObject` 的子类,也就是一个简单的对象;所有的 View 层对象都是 `UIView` 的子类;而 Controller 层的对象都是 `UIViewController` 的实例。 + +我们在这一节中主要是介绍 `UIViewController` 作为 Controller 层中的最重要的对象,它具有哪些职责,它与 Model 以及 View 层是如何进行交互的。 + +总体来说,Controller 层要负责以下的问题(包括但不仅限于): + +1. 管理根视图的生命周期和应用生命周期 +1. 负责将视图层的 `UIView` 对象添加到持有的根视图上; +2. 负责处理用户行为,比如 `UIButton` 的点击以及手势的触发; +3. 储存当前界面的状态; +4. 处理界面之间的跳转; +3. 作为 `UITableView` 以及其它容器视图的代理以及数据源; +4. 负责 HTTP 请求的发起; + +除了上述职责外,`UIViewController` 对象还可能需要处理**业务逻辑**以及各种复杂的动画,这也就是为什么在 iOS 应用中的 Controller 层都非常庞大、臃肿的原因了,而 MVVM、MVP 等架构模式的目的之一就是减少单一 Controller 中的代码。 + +### 管理生命周期 + +Controller 层作为整个 MVC 架构模式的中枢,承担着非常重要的职责,不仅要与 Model 以及 View 层进行交互,还有通过 AppDelegate 与诸多的应用生命周期打交道。 + +```objectivec +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions; +- (void)applicationWillResignActive:(UIApplication *)application; +- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler; +``` + +虽然与应用生命周期沟通的工作并不在单独的 Controller 中,但是 `self.window.rootController` 作为整个应用程序界面的入口,还是需要在 AppDelegate 中进行设置。 + +除此之外,由于每一个 `UIViewController` 都持有一个视图对象,所以每一个 `UIViewController` 都需要负责这个根视图的加载、布局以及生命周期的管理,包括: + +```objectivec +- (void)loadView; + +- (void)viewWillLayoutSubviews; +- (void)viewDidLayoutSubviews; + +- (void)viewDidLoad; +- (void)viewWillAppear:(BOOL)animated; +- (void)viewDidAppear:(BOOL)animated; +``` + +除了负责应用生命周期和视图生命周期,控制器还要负责展示内容和布局。 + +### 负责展示内容和布局 + +由于每一个 `UIViewController` 都持有一个 `UIView` 的对象,所以视图层的对象想要出现在屏幕上,必须成为这个根视图的子视图,也就是说视图层完全没有办法脱离 `UIViewController` 而单独存在,其一方面是因为 `UIViewController` 隐式的承担了应用中路由的工作,处理界面之间的跳转,另一方面就是 `UIViewController` 的设计导致了所有的视图必须加在其根视图上才能工作。 + +![Controller-RootVie](images/controller/Controller-RootView.jpg) + +我们来看一段 `UIViewController` 中关于视图层的简单代码: + +```objectivec +- (void)viewDidLoad { + [super viewDidLoad]; + [self setupUI]; +} + +- (void)setupUI { + _backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"backgroundView"]]; + + _registerButton = [[UIButton alloc] init]; + [_registerButton setTitle:@"注册" forState:UIControlStateNormal]; + [_registerButton setTitleColor:UIColorFromRGB(0x00C3F3) forState:UIControlStateNormal]; + [_registerButton addTarget:self action:@selector(registerButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; + + [self.view addSubview:_backgroundView]; + [self.view addSubview:_registerButton]; + + [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) { + make.edges.mas_equalTo(self.view); + }]; + [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) { + make.size.mas_equalTo(CGSizeMake(140, 45)); + make.bottom.mas_equalTo(self.view).offset(-25); + make.left.mas_equalTo(self.view).offset(32); + }]; +} +``` + +在这个欢迎界面以及大多数界面中,由于视图层的代码非常简单,我们很多情况下并不会去写一个单独的 `UIView` 类,而是将全部的视图层代码丢到了 `UIViewController` 中,这种情况下甚至也没有 Model 层,Controller 承担了全部的工作。 + +![Controller-Only](images/controller/Controller-Only.jpg) + +上述的代码对视图进行了初始化,将需要展示的视图加到了自己持有的根视图中,然后对这些视图进行简单的布局。 + +当然我们也可以将视图的初始化单独放到一个类中,不过仍然需要处理 `DRKBackgroundView` 视图的布局等问题。 + +```objectivec +- (void)setupUI { + DRKBackgroundView *backgroundView = [[DRKBackgroundView alloc] init]; + [backgroundView.registerButton addTarget:self action:@selector(registerButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; + + [self.view addSubview:backgroundView]; + + [backgroundView mas_makeConstraints:^(MASConstraintMaker *make) { + make.edges.mas_equalTo(self.view); + }]; +} +``` + +`UIViewController` 的这种中心化的设计虽然简单,不过也导致了很多代码没有办法真正解耦,视图层必须依赖于 `UIViewController` 才能展示。 + +#### 惰性初始化 + +当然,很多人在 Controller 中也会使用惰性初始化的方式生成 Controller 中使用的视图,比如: + +```objectivec +@interface ViewController () + +@property (nonatomic, strong) UIImageView *backgroundView; + +@end + +@implementation ViewController + +- (UIImageView *)backgroundView { + if (!_backgroundView) { + _backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"backgroundView"]]; + } + return _backgroundView; +} + +@end +``` + +这样在 `-viewDidLoad` 方法中就可以直接处理视图的视图层级以及布局工作: + +```objectivec +- (void)viewDidLoad { + [super viewDidLoad]; + + [self.view addSubview:self.backgroundView]; + + [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) { + make.edges.mas_equalTo(self.view); + }]; +} +``` + +惰性初始化的方法与其他方法其实并没有什么绝对的优劣,两者的选择只是对于代码规范的一种选择,我们所需要做的,只是在同一个项目中将其中一种做法坚持到底。 + +### 处理用户行为 + +在 `UIViewController` 中处理用户的行为是经常需要做的事情,这部分代码不能放到视图层或者其他地方的原因是,用户的行为经常需要与 Controller 的上下文有联系,比如,界面的跳转需要依赖于 `UINavigationController` 对象: + +```objectivec +- (void)registerButtonTapped:(UIButton *)button { + RegisterViewController *registerViewController = [[RegisterViewController alloc] init]; + [self.navigationController pushViewController:registerViewController animated:YES]; +} +``` + +而有的用户行为需要改变模型层的对象、持久存储数据库中的数据或者发出网络请求,主要因为我们要秉承着 MVC 的设计理念,避免 Model 层和 View 层的直接耦合。 + +### 存储当前界面的状态 + +在 iOS 中,我们经常需要处理表视图,而在现有的大部分表视图在加载内容时都会进行分页,使用下拉刷新和上拉加载的方式获取新的条目,而这就需要在 Controller 层保存当前显示的页数: + +```objectivec +@interface TableViewController () + +@property (nonatomic, assign) NSUInteger currentPage; + +@end +``` + +只有保存在了当前页数的状态,才能在下次请求网络数据时传入合适的页数,最后获得正确的资源,当然哪怕当前页数是可以计算出来的,比如通过当前的 Model 对象的数和每页个 Model 数,在这种情况下,我们也需要在当前 Controller 中 Model 数组的值。 + +```objectivec +@interface TableViewController () + +@property (nonatomic, strong) NSArray<Model *> *models; + +@end +``` + +在 MVC 的设计中,这种保存当前页面状态的需求是存在的,在很多复杂的页面中,我们也需要维护大量的状态,这也是 Controller 需要承担的重要职责之一。 + +### 处理界面之间的跳转 + +由于 Cocoa Touch 提供了 `UINavigationController` 和 `UITabBarController` 这两种容器 Controller,所以 iOS 中界面跳转的这一职责大部分都落到了 Controller 上。 + +![UINavigationController-UITabBarControlle](images/controller/UINavigationController-UITabBarController.jpg) + +iOS 中总共有三种界面跳转的方式: + ++ `UINavigationController` 中使用 push 和 pop 改变栈顶的 `UIViewController` 对象; ++ `UITabBarController` 中点击各个 `UITabBarItem` 实现跳转; ++ 使用所有的 `UIViewController` 实例都具有的 `-presentViewController:animated:completion` 方法; + +因为所有的 `UIViewController` 的实例都可以通过 `navigationController` 这一属性获取到最近的 `UINavigationController` 对象,所以我们不可避免的要在 Controller 层对界面之间的跳转进行操作。 + +> 当然,我们也可以引入 Router 路由对 `UIViewController` 进行注册,在访问合适的 URL 时,通过根 `UINavigationController` 进行跳转,不过这不是本篇文章想要说明的内容。 + +`UINavigationController` 提供的 API 还是非常简单的,我们可以直接使用 `-pushViewController:animated:` 就可以进行跳转。 + +```objectivec +RegisterViewController *registerViewController = [[RegisterViewController alloc] init]; +[self.navigationController pushViewController:registerViewController animated:YES]; +``` + +### 作为数据源以及代理 + +很多 Cocoa Touch 中视图层都是以代理的形式为外界提供接口的,其中最为典型的例子就是 `UITableView` 和它的数据源协议 `UITableViewDataSource` 和代理 `UITableViewDelegate`。 + +这是因为 `UITableView` 作为视图层的对象,需要根据 Model 才能知道自己应该展示什么内容,所以在早期的很多视图层组件都是用了代理的形式,从 Controller 或者其他地方获取需要展示的数据。 + +```objectivec +#pragma mark - UITableViewDataSource + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + return self.models.count; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath]; + Model *model = self.models[indexPath.row]; + [cell setupWithModel:model]; + return cell; +} +``` + +上面就是使用 `UITableView` 时经常需要的方法。 + +很多文章中都提供了一种用于减少 Controller 层中代理方法数量的技巧,就是使用一个单独的类作为 `UITableView` 或者其他视图的代理: + +```objectivec +self.tableView.delegate = anotherObject; +self.tableView.dataSource = anotherObject; +``` + +然而在笔者看来这种办法并没有什么太大的用处,只是将代理方法挪到了一个其他的地方,如果这个代理方法还依赖于当前 `UIViewController` 实例的上下文,还要向这个对象中传入更多的对象,反而让原有的 MVC 变得更加复杂了。 + +### 负责 HTTP 请求的发起 + +当用户的行为触发一些事件时,比如下拉刷新、更新 Model 的属性等等,Controller 就需要通过 Model 层提供的接口向服务端发出 HTTP 请求,这一过程其实非常简单,但仍然是 Controller 层的职责,也就是响应用户事件,并且更新 Model 层的数据。 + +```objectivec +- (void)registerButtonTapped:(UIButton *)button { + LoginManager *manager = [LoginManager manager]; + manager.countryCode = _registerPanelView.countryCode; + ... + [manager startWithSuccessHandler:^(CCStudent *user) { + self.currentUser = user; + ... + } failureHandler:^(NSError *error) { + ... + }]; +} +``` + +当按钮被点击时 `LoginManager` 就会执行 `-startWithSuccessHandler:failureHandler:` 方法发起请求,并在请求结束后执行回调,更新 Model 的数据。 + +### 小结 + +iOS 中 Controller 层的职责一直都逃不开与 View 层和 Model 层的交互,因为其作用就是视图层的用户行为进行处理并更新视图的内容,同时也会改变模型层中的数据、使用 HTTP 请求向服务端请求新的数据等作用,其功能就是处理整个应用中的业务逻辑和规则。 + +但是由于 iOS 中 Controller 的众多职责,单一的 `UIViewController` 类可能会有上千行的代码,使得非常难以管理和维护,我们也希望在 iOS 中引入新的架构模式来改变 Controller 过于臃肿这一现状。 + +## 几点建议 + +Controller 层作为 iOS 应用中重要的组成部分,在 MVC 以及类似的架构下,笔者对于 Controller 的设计其实没有太多立竿见影的想法。作为应用中处理绝大多数逻辑的 Controller 其实很难简化其中代码的数量;我们能够做的,也是只对其中的代码进行一定的规范以提高它的可维护性,在这里,笔者有几点对于 Controller 层如何设计的建议,供各位读者参考。 + +### 不要把 DataSource 提取出来 + +iOS 中的 `UITableView` 和 `UICollectionView` 等需要 `dataSource` 的视图对象十分常见,在一些文章中会提议将数据源的实现单独放到一个对象中。 + +```objectivec +void (^configureCell)(PhotoCell*, Photo*) = ^(PhotoCell* cell, Photo* photo) { + cell.label.text = photo.name; +}; +photosArrayDataSource = [[ArrayDataSource alloc] initWithItems:photos + cellIdentifier:PhotoCellIdentifier + configureCellBlock:configureCell]; +self.tableView.dataSource = photosArrayDataSource; +``` + +在 [Lighter View Controllers](https://www.objc.io/issues/1-view-controllers/lighter-view-controllers/) 一文中就建议可以将数据源协议的实现方法放到 `ArrayDataSource` 对象中: + +```objectivec +@implementation ArrayDataSource + +- (id)itemAtIndexPath:(NSIndexPath*)indexPath { + return items[(NSUInteger)indexPath.row]; +} + +- (NSInteger)tableView:(UITableView*)tableView + numberOfRowsInSection:(NSInteger)section { + return items.count; +} + +- (UITableViewCell*)tableView:(UITableView*)tableView + cellForRowAtIndexPath:(NSIndexPath*)indexPath { + id cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier + forIndexPath:indexPath]; + id item = [self itemAtIndexPath:indexPath]; + configureCellBlock(cell,item); + return cell; +} + +@end +``` + +做出这种建议的理由是:单独的 `ArrayDataSource` 类可以更方便的进行测试,同时,展示一个数组的对象是表视图中非常常见的需求,而 `ArrayDataSource` 能够将这种需求抽象出来并进行重用,也可以达到减轻视图控制器负担的最终目的,但是在笔者看来,上述做法并没有起到**实质性**效果,只是简单的将视图控制器中的一部分代码*移到了*别的位置而已,还会因为增加了额外的类使 Controller 的维护变得更加的复杂。 + +![UITableView-DataSource](images/controller/UITableView-DataSource.jpg) + +让每一个 Controller 作为 `UITableView` 对象的代理和数据源其实是没有任何问题的,将这些方法移出 Controller 并不能解决实际的问题。 + +### 属性和实例变量的选择 + +文章的前面曾经提到过在很多的 iOS 应用中,Controller 由于持有一个根视图 `UIView` 对象,所以需要负责展示内容以及布局,很多 iOS 开发者都把一些模块的视图层代码放到了控制器中,但是无论是将视图层代码放到控制器中,还是新建一个单独的视图类都需要对视图以及子视图进行初始化和布局。 + +在对视图进行初始化和布局时,我们有两种选择,一种是使用实例变量的方式主动对视图对象进行初始化,另一种是使用属性 `@property` 对视图对象进行惰性初始化。 + +![Eager-Lazy-Initialization](images/controller/Eager-Lazy-Initialization.jpg) + +虽然上述两种代码在结果上几乎是等价的,但是笔者更加偏好两者之中的后者,它将各个视图属性的初始化放到了各个属性的 getter 方法中,能够将代码在逻辑上分块还是比较清晰的。这两种方法其实只是不同的 taste,有些人会坚持将不需要暴露的变量都写成 `_xxx` 的形式,有些人更喜欢后者这种分散的写法,这些都不是什么太大的问题,而且很多人担心的性能问题其实也根本不是问题,重要的是我们要在同一个项目中坚持同一种写法,并且保证只有同一个风格的代码合入主分支。 + +### 把业务逻辑移到 Model 层 + +控制器中有很多代码和逻辑其实与控制器本身并没有太多的关系,比如: + +```objectivec +@implementation ViewController + +- (NSString *)formattedPostCreatedAt { + NSDateFormatter *format = [[NSDateFormatter alloc] init]; + [format setDateFormat:@"MMM dd, yyyy HH:mm"]; + return [format stringFromDate:self.post.createdAt]; +} + +@end +``` + +在 [谈谈 MVX 中的 Model 层](http://draveness.me/mvx-model.html) 一文中,我们曾经分析过,上述逻辑其实应该属于 Model 层,作为 `Post` 的一个实例方法: + +```objectivec +@implementation Post + +- (NSString *)formattedCreatedAt { + NSDateFormatter *format = [[NSDateFormatter alloc] init]; + [format setDateFormat:@"MMM dd, yyyy HH:mm"]; + return [format stringFromDate:self.createdAt]; +} + +@end +``` + +这一条建议是从一些经典的后端 MVC 框架中学习的,Rails 提倡 *Fat Model, Skinny Controller* 就是希望开发者将 Model 相关的业务逻辑都放到 Model 层中,以减轻 Controller 层的负担。 + +### 把视图层代码移到 View 层 + +因为 UIKit 框架设计的原因,Controller 和 View 层是强耦合的,每一个 `UIViewController` 都会持有一个 `UIView` 视图对象,这也是导致我们将很多的视图层代码直接放在 Controller 层的原因。 + +![MVC-in-iOS](images/controller/MVC-in-iOS.jpg) + +这种做法在当前模块的视图层比较简单时,笔者觉得没有任何的问题,虽然破坏了经典的 MVC 的架构图,但是也不是什么问题;不过,当视图层的视图对象非常多的时候,大量的配置和布局代码就会在控制器中占据大量的位置,我们可以将整个视图层的代码都移到一个单独的 `UIView` 子类中。 + +```objectivec +// RegisterView.h +@interface RegisterView : UIView + +@property (nonatomic, strong) UITextField *phoneNumberTextField; +@property (nonatomic, strong) UITextField *passwordTextField; + +@end + +// RegisterView.m +@implementation RegisterView + +- (instancetype)initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame]) { + [self addSubview:self.phoneNumberTextField]; + [self addSubview:self.passwordTextField]; + + [self.phoneNumberTextField mas_makeConstraints:^(MASConstraintMaker *make) { + ... + }]; + [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) { + ... + }]; + } + return self; +} + +- (UITextField *)phoneNumberTextField { + if (!_phoneNumberTextField) { + _phoneNumberTextField = [[UITextField alloc] init]; + _phoneNumberTextField.font = [UIFont systemFontOfSize:16]; + } + return _phoneNumberTextField; +} + +- (UITextField *)passwordTextField { + if (!_passwordTextField) { + _passwordTextField = [[UITextField alloc] init]; + ... + } + return _passwordTextField; +} + +@end +``` + +而 Controller 需要持有该视图对象,并将自己持有的根视图替换成该视图对象: + +```objectivec +@interface ViewController () + +@property (nonatomic, strong) RegisterView *view; + +@end + +@implementation ViewController + +@dynamic view; + +- (void)loadView { + self.view = [[RegisterView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; +} + +- (void)viewDidLoad { + [super viewDidLoad]; +} + +@end +``` + +在 `UIViewController` 对象中,我们可以通过覆写 `-loadView` 方法改变其本身持有的视图对象,并使用新的 `@property` 声明以及 `@dynamic` 改变 Controller 持有的根视图,这样我们就把视图层的配置和布局代码从控制器中完全分离了。 + +### 使用 pragma 或 extension 分割代码块 + +在很多时候,我们对于 Controller 中上千行的代码是非常绝望的,不熟悉这个模块的开发者想要在里面快速找到自己想要的信息真的是非常的麻烦,尤其是如果一个 `UIViewController` 中的代码没有被组织好的话,那分析起来更是异常头疼。 + +我们既然没有把上千行的代码瞬间变没的方法,那就只能想想办法在现有的代码上进行美化了,办法其实很简单,就是将具有相同功能的代码分块并使用 `pragma` 预编译指定或者 `MARK` 加上 `extension` 对代码块进行分割。 + +这里给一个简单的例子, + +```objectivec +@implementation ViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + [self setupUI]; +} + +- (void)layoutSubviews { } + +#pragma mark - UI + +- (void)setupUI {} + +#pragma mark - UITableViewDataSource + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + return 1; +} +... + +#pragma mark - UITableViewDelegate + +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { + return 100.0; +} +... + +#pragma mark - Callback + +- (void)buttonTapped:(UIButton *)button {} +- (void)gestureTriggered:(UIGestureRecognizer *)gesture {} +- (void)keyboardWillShow:(NSNotification *)noti {} + +#pragma mark - Getter/Setter + +- (NSString *)string { return _string; } +- (void)setString:(NSString*)string { _string = string; } + +#pragma mark - Helper + +- (void)helperMethod {} + +@end +``` + +一个 `UIViewController` 大体由上面这些部分组成: + ++ 生命周期以及一些需要 `override` 的方法 ++ 视图层代码的初始化 ++ 各种数据源和代理协议的实现 ++ 事件、手势和通知的回调 ++ 实例变量的存取方法 ++ 一些其他的 Helper 方法 + +在 Objective-C 的工程中,我们使用 `pragma` 预编译指令来对 `UIViewController` 中的;在 Swift 中,我们可以使用 `extension` 加上 `MARK` 来对代码进行分块: + +```swift +class ViewController: UIViewController {} + +// MARK: - UI +extension ViewController {} + +// MARK: - UITableViewDataSource +extension ViewController: UITableViewDataSource {} + +// MARK: - UITableViewDelegate +extension ViewController: UITableViewDelegate {} + +// MARK: - Callback +extension ViewController {} + +// MARK: - Getter/Setter +extension ViewController {} + +// MARK: - Helper +extension ViewController {} +``` + +上述方法是一种在控制器层分割代码块的方法,它们的顺序并不是特别的重要,最重要的还是要在不同的控制器中保持上述行为的一致性,将合理的方法放到合适的代码块中。 + +### 耦合的 View 和 Model 层 + +很多的 iOS 项目中都会为 `UIView` 添加一个绑定 Model 对象的方法,比如说: + +```objectivec +@implementation UIView (Model) + +- (void)setupWithModel:(id)model {} + +@end +``` + +这个方法也可能叫做 `-bindWithModel:` 或者其他名字,其作用就是根据传入的 Model 对象更新当前是视图中的各种状态,比如 `UILabel` 中的文本、`UIImageView` 中的图片等等。 + +有了上述分类,我们可以再任意的 `UIView` 的子类中覆写该方法: + +```objectivec +- (void)setupWithModel:(Model *)model { + self.imageView.image = model.image; + self.label.text = model.name; +} +``` + +这种做法其实是将原本 Controller 做的事情放到了 View 中,由视图层来负责如何展示模型对象;虽然它能够减少 Controller 中的代码,但是也导致了 View 和 Model 的耦合。 + +![Coupling-View-And-Mode](images/controller/Coupling-View-And-Model.jpg) + +对于 MVC 架构模式中,Model、View 和 Controller 之间的交互没有明确的规则,但是视图和模型之间的耦合会导致视图层代码很难复用;因为这样设计的视图层都依赖于外部的模型对象,所以**如果同一个视图需要显示多种类型的模型时就会遇到问题**。 + +视图和模型之间解耦是通过控制器来处理的,控制器获取模型对象并取出其中的属性一一装填到视图中,也就是将 `-setupWithModel:` 方法中的代码从视图层移到控制器层中,并在视图类中暴露合适的接口。 + +## 总结 + +本文虽然对 Controller 层的职责进行了分析,但是由于 Controller 在 MVC 中所处的位置,如果不脱离 MVC 架构模式,那么 Controller 的职责很难简化,只能在代码规范和职责划分上进行限制,而在下一篇文章中我们会详细讨论 MVC 以及衍化出来的 MVP 以及 MVVM 到底是什么、以及它们有什么样的差异。 + +## Reference + ++ [Lighter View Controllers](https://www.objc.io/issues/1-view-controllers/lighter-view-controllers/) + + diff --git a/contents/architecture/mvx-model.md b/contents/architecture/mvx-model.md new file mode 100644 index 0000000..d89f792 --- /dev/null +++ b/contents/architecture/mvx-model.md @@ -0,0 +1,571 @@ +# 谈谈 MVX 中的 Model + ++ [谈谈 MVX 中的 Model](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-model.md) ++ [谈谈 MVX 中的 View](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-view.md) ++ [谈谈 MVX 中的 Controller](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-controller.md) ++ [浅谈 MVC、MVP 和 MVVM 架构模式](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx.md) + +> Follow GitHub: [Draveness](https://github.com/Draveness) + + +## 常见的 Model 层 + +在大多数 iOS 的项目中,Model 层只是一个单纯的数据结构,你可以看到的绝大部分模型都是这样的: + +```swift +struct User { + enum Gender: String { + case male = "male" + case female = "female" + } + let name: String + let email: String + let age: Int + let gender: Gender +} +``` + +模型起到了定义一堆『坑』的作用,只是一个简单的模板,并没有参与到实际的业务逻辑,只是在模型层进行了一层**抽象**,将服务端发回的 JSON 或者说 `Dictionary` 对象中的字段一一取出并装填到预先定义好的模型中。 + +![JSON-to-Mode](images/model/JSON-to-Model.jpg) + +我们可以将这种模型层中提供的对象理解为『即开即用』的 `Dictionary` 实例;在使用时,可以直接从模型中取出属性,省去了从 `Dictionary` 中抽出属性以及验证是否合法的过程。 + +```swift +let user = User... + +nameLabel.text = user.name +emailLabel.text = user.email +ageLabel.text = "\(user.age)" +genderLabel.text = user.gender.rawValue +``` + +### JSON -> Model + +使用 Swift 将 `Dictionary` 转换成模型,在笔者看来其实是一件比较麻烦的事情,主要原因是 Swift 作为一个号称类型安全的语言,有着使用体验非常差的 Optional 特性,从 `Dictionary` 中取出的值都是不一定存在的,所以如果需要纯手写这个过程其实还是比较麻烦的。 + +```swift +extension User { + init(json: [String: Any]) { + let name = json["name"] as! String + let email = json["email"] as! String + let age = json["age"] as! Int + let gender = Gender(rawValue: json["gender"] as! String)! + self.init(name: name, email: email, age: age, gender: gender) + } +} +``` + +这里为 `User` 模型创建了一个 extension 并写了一个简单的模型转换的初始化方法,当我们从 JSON 对象中取值时,得到的都是 Optional 对象;而在大多数情况下,我们都没有办法直接对 Optional 对象进行操作,这就非常麻烦了。 + +#### 麻烦的 Optional + +在 Swift 中遇到无法立即使用的 Optional 对象时,我们可以会使用 `!` 默认将字典中取出的值当作非 Optional 处理,但是如果服务端发回的数据为空,这里就会直接崩溃;当然,也可使用更加安全的 `if let` 对 Optional 对象进行解包(unwrap)。 + +```swift +extension User { + init?(json: [String: Any]) { + if let name = json["name"] as? String, + let email = json["email"] as? String, + let age = json["age"] as? Int, + let genderString = json["gender"] as? String, + let gender = Gender(rawValue: genderString) { + self.init(name: name, email: email, age: age, gender: gender) + } + return nil + } +} +``` + +上面的代码看起来非常的丑陋,而正是因为上面的情况在 Swift 中非常常见,所以社区在 Swift 2.0 中引入了 `guard` 关键字来优化代码的结构。 + +```swift +extension User { + init?(json: [String: Any]) { + guard let name = json["name"] as? String, + let email = json["email"] as? String, + let age = json["age"] as? Int, + let genderString = json["gender"] as? String, + let gender = Gender(rawValue: genderString) else { + return nil + } + self.init(name: name, email: email, age: age, gender: gender) + } +} +``` + +不过,上面的代码在笔者看来,并没有什么本质的区别,不过使用 `guard` 对错误的情况进行提前返回确实是一个非常好的编程习惯。 + +#### 不关心空值的 OC + +为什么 Objective-C 中没有这种问题呢?主要原因是在 OC 中所有的对象其实都是 Optional 的,我们也并不在乎对象是否为空,因为在 OC 中**向 nil 对象发送消息并不会造成崩溃,Objective-C 运行时仍然会返回 nil 对象**。 + +> 这虽然在一些情况下会造成一些问题,比如,当 `nil` 导致程序发生崩溃时,比较难找到程序中 `nil` 出现的原始位置,但是却保证了程序的灵活性,笔者更倾向于 Objective-C 中的做法,不过这也就见仁见智了。 + +OC 作为动态语言,这种设计思路其实还是非常优秀的,它避免了大量由于对象不存在导致无法完成方法调用造成的崩溃;同时,作为开发者,我们往往都不需要考虑 `nil` 的存在,所以使用 OC 时写出的模型转换的代码都相对好看很多。 + +```objectivec +// User.h +typedef NS_ENUM(NSUInteger, Gender) { + Male = 0, + Female = 1, +}; + +@interface User: NSObject + +@property (nonatomic, strong) NSString *email; +@property (nonatomic, strong) NSString *name; +@property (nonatomic, assign) NSUInteger age; +@property (nonatomic, assign) Gender gender; + +@end + +// User.m +@implementation User + +- (instancetype)initWithJSON:(NSDictionary *)json { + if (self = [super init]) { + self.email = json[@"email"]; + self.name = json[@"name"]; + self.age = [json[@"age"] integerValue]; + self.gender = [json[@"gender"] integerValue]; + } + return self; +} + +@end +``` + +当然,在 OC 中也有很多优秀的 JSON 转模型的框架,如果我们使用 YYModel 这种开源框架,其实只需要写一个 `User` 类的定义就可以获得 `-yy_modelWithJSON:` 等方法来初始化 `User` 对象: + +```objectivec +User *user = [User yy_modelWithJSON:json]; +``` + +而这也是通过 Objective-C 强大的运行时特性做到的。 + +> 除了 YYModel,我们也可以使用 Mantle 等框架在 OC 中解决 JSON 到模型的转换的问题。 + +#### 元编程能力 + +从上面的代码,我们可以看出:Objective-C 和 Swift 对于相同功能的处理,却有较大差别的实现。这种情况的出现主要原因是语言的设计思路导致的;Swift 一直*鼓吹*自己有着较强的安全性,能够写出更加稳定可靠的应用程序,而安全性来自于 Swift 语言的设计哲学;由此看来静态类型、安全和动态类型、元编程能力(?)看起来是比较难以共存的。 + +> 其实很多静态编程语言,比如 C、C++ 和 Rust 都通过宏实现了比较强大的元编程能力,虽然 Swift 也通过模板在元编程支持上做了一些微小的努力,不过到目前来看( 3.0 )还是远远不够的。 + +![Dynamic-Stati](images/model/Dynamic-Static.png) + +OC 中对于 `nil` 的处理能够减少我们在编码时的工作量,不过也对工程师的代码质量提出了考验。我们需要思考 `nil` 的出现会不会带来崩溃,是否会导致行为的异常、增加应用崩溃的风险以及不确定性,而这也是 Swift 引入 Optional 这一概念来避免上述问题的初衷。 + +相比而言,笔者还是更喜欢强大的元编程能力,这样可以减少大量的重复工作并且提供更多的可能性,与提升工作效率相比,牺牲一些安全性还是可以接受的。 + +### 网络服务 Service 层 + +现有的大多数应用都会将网路服务组织成单独的一层,所以有时候你会看到所谓的 MVCS 架构模式,它其实只是在 MVC 的基础上加上了一个服务层(Service),而在 iOS 中常见的 MVC 架构模式也都可以理解为 MVCS 的形式,当引入了 Service 层之后,整个数据的获取以及处理的流程是这样的: + +![MVCS-Architecture](images/model/MVCS-Architecture.png) + +1. 大多数情况下服务的发起都是在 Controller 中进行的; +2. 然后会在 HTTP 请求的回调中交给模型层处理 JSON 数据; +3. 返回开箱即用的对象交还给 Controller 控制器; +4. 最后由 View 层展示服务端返回的数据; + +不过按理来说服务层并不属于模型层,为什么要在这里进行介绍呢?这是因为 **Service 层其实与 Model 层之间的联系非常紧密**;网络请求返回的结果决定了 Model 层该如何设计以及该有哪些功能模块,而 Service 层的设计是与后端的 API 接口的设计强关联的,这也是我们谈模型层的设计无法绕过的坑。 + +iOS 中的 Service 层大体上有两种常见的组织方式,其中一种是命令式的,另一种是声明式的。 + +#### 命令式 + +命令式的 Service 层一般都会为每一个或者一组 API 写一个专门用于 HTTP 请求的 Manager 类,在这个类中,我们会在每一个静态方法中使用 AFNetworking 或者 Alamofire 等网络框架发出 HTTP 请求。 + +```objectivec +import Foundation +import Alamofire + +final class UserManager { + static let baseURL = "http://localhost:3000" + static let usersBaseURL = "\(baseURL)/users" + + static func allUsers(completion: @escaping ([User]) -> ()) { + let url = "\(usersBaseURL)" + Alamofire.request(url).responseJSON { response in + if let jsons = response.result.value as? [[String: Any]] { + let users = User.users(jsons: jsons) + completion(users) + } + } + } + + static func user(id: Int, completion: @escaping (User) -> ()) { + let url = "\(usersBaseURL)/\(id)" + Alamofire.request(url).responseJSON { response in + if let json = response.result.value as? [String: Any], + let user = User(json: json) { + completion(user) + } + } + } +} +``` + +在这个方法中,我们完成了网络请求、数据转换 JSON、JSON 转换到模型以及最终使用 `completion` 回调的过程,调用 Service 服务的 Controller 可以直接从回调中使用构建好的 Model 对象。 + +```objectivec +UserManager.user(id: 1) { user in + self.nameLabel.text = user.name + self.emailLabel.text = user.email + self.ageLabel.text = "\(user.age)" + self.genderLabel.text = user.gender.rawValue +} +``` + +#### 声明式 + +使用声明式的网络服务层与命令式的方法并没有本质的不同,它们最终都调用了底层的一些网络库的 API,这种网络服务层中的请求都是以配置的形式实现的,需要对原有的命令式的请求进行一层封装,也就是说所有的参数 `requestURL`、`method` 和 `parameters` 都应该以配置的形式声明在每一个 `Request` 类中。 + +![Abstract-Request](images/model/Abstract-Request.jpg) + +如果是在 Objective-C 中,一般会定义一个抽象的基类,并让所有的 Request 都继承它;但是在 Swift 中,我们可以使用协议以及协议扩展的方式实现这一功能。 + +```swift +protocol AbstractRequest { + var requestURL: String { get } + var method: HTTPMethod { get } + var parameters: Parameters? { get } +} + +extension AbstractRequest { + func start(completion: @escaping (Any) -> Void) { + Alamofire.request(requestURL, method: self.method).responseJSON { response in + if let json = response.result.value { + completion(json) + } + } + } +} +``` + +在 `AbstractRequest` 协议中,我们定义了发出一个请求所需要的全部参数,并在协议扩展中实现了 `start(completion:)` 方法,这样实现该协议的类都可以直接调用 `start(completion:)` 发出网络请求。 + +```swift +final class AllUsersRequest: AbstractRequest { + let requestURL = "http://localhost:3000/users" + let method = HTTPMethod.get + let parameters: Parameters? = nil +} + +final class FindUserRequest: AbstractRequest { + let requestURL: String + let method = HTTPMethod.get + let parameters: Parameters? = nil + + init(id: Int) { + self.requestURL = "http://localhost:3000/users/\(id)" + } +} +``` + +我们在这里写了两个简单的 `Request` 类 `AllUsersRequest` 和 `FindUserRequest`,它们两个一个负责获取所有的 `User` 对象,一个负责从服务端获取指定的 `User`;在使用上面的声明式 Service 层时也与命令式有一些不同: + +```swift +FindUserRequest(id: 1).start { json in + if let json = json as? [String: Any], + let user = User(json: json) { + print(user) + } +} +``` + +因为在 Swift 中,我们没法将 JSON 在 Service 层转换成模型对象,所以我们不得不在 `FindUserRequest` 的回调中进行类型以及 JSON 转模型等过程;又因为 HTTP 请求可能依赖其他的参数,所以在使用这种形式请求资源时,我们需要在初始化方法传入参数。 + +#### 命令式 vs 声明式 + +现有的 iOS 开发中的网络服务层一般都是使用这两种组织方式,我们一般会按照**资源**或者**功能**来划分命令式中的 `Manager` 类,而声明式的 `Request` 类与实际请求是一对一的关系。 + +![Manager-And-Request](images/model/Manager-And-Request.jpg) + +这两种网络层的组织方法在笔者看来没有高下之分,无论是 `Manager` 还是 `Request` 的方式,尤其是后者由于一个类只对应一个 API 请求,在整个 iOS 项目变得异常复杂时,就会导致**网络层类的数量剧增**。 + +这个问题并不是不可以接受的,在大多数项目中的网络请求就是这么做的,虽然在查找实际的请求类时有一些麻烦,不过只要遵循一定的**命名规范**还是可以解决的。 + +### 小结 + +现有的 MVC 下的 Model 层,其实只起到了对数据结构定义的作用,它将服务端返回的 JSON 数据,以更方便使用的方式包装了一下,这样呈现给上层的就是一些即拆即用的『字典』。 + +![Model-And-Dictioanry](images/model/Model-And-Dictioanry.jpg) + +单独的 Model 层并不能返回什么关键的作用,它只有与网络服务层 Service 结合在一起的时候才能发挥更重要的能力。 + +![Service-And-API](images/model/Service-And-API.jpg) + +而网络服务 Service 层是对 HTTP 请求的封装,其实现形式有两种,一种是命令式的,另一种是声明式的,这两种实现的方法并没有绝对的优劣,遵循合适的形式设计或者重构现有的架构,随着应用的开发与迭代,为上层提供相同的接口,保持一致性才是设计 Service 层最重要的事情。 + +## 服务端的 Model 层 + +虽然文章是对客户端中 Model 层进行分析和介绍,但是在客户端大规模使用 MVC 架构模式之前,服务端对于 MVC 的使用早已有多年的历史,而移动端以及 Web 前端对于架构的设计是近年来才逐渐被重视。 + +因为客户端的应用变得越来越复杂,动辄上百万行代码的巨型应用不断出现,以前流水线式的开发已经没有办法解决现在的开发、维护工作,所以合理的架构设计成为客户端应用必须要重视的事情。 + +这一节会以 Ruby on Rails 中 Model 层的设计为例,分析在经典的 MVC 框架中的 Model 层是如何与其他模块进行交互的,同时它又担任了什么样的职责。 + +### Model 层的职责 + +Rails 中的 Model 层主要承担着以下两大职责: + +1. 使用数据库存储并管理 Web 应用的数据; +2. 包含 Web 应用**所有**的业务逻辑; + +除了上述两大职责之外,Model 层还会存储应用的状态,同时,由于它对用户界面一无所知,所以它不依赖于任何视图的状态,这也使得 Model 层的代码可以复用。 + +Model 层的两大职责决定了它在整个 MVC 框架的位置: + +![Server-MV](images/model/Server-MVC.jpg) + +因为 Model 是对数据库中表的映射,所以当 Controller 向 Model 层请求数据时,它会从数据库中获取相应的数据,然后对数据进行加工最后返回给 Controller 层。 + +#### 数据库 + +Model 层作为数据库中表的映射,它就需要实现两部分功能: + +1. 使用合理的方式对数据库进行迁移和更新; +2. 具有数据库的绝大部分功能,包括最基础的增删改查; + +在这里我们以 Rails 的 ActiveRecord 为例,简单介绍这两大功能是如何工作的。 + +ActiveRecord 为数据库的迁移和更新提供了一种名为 Migration 的机制,它可以被理解为一种 DSL,对数据库中的表的字段、类型以及约束进行描述: + +```ruby +class CreateProducts < ActiveRecord::Migration[5.0] + def change + create_table :products do |t| + t.string :name + t.text :description + end + end +end +``` + +上面的 Ruby 代码创建了一个名为 `Products` 表,其中包含三个字段 `name`、`description` 以及一个默认的主键 `id`,然而在上述文件生成时,数据库中对应的表还不存在,当我们在命令行中执行 `rake db:migrate` 时,才会执行下面的 SQL 语句生成一张表: + +```sql +CREATE TABLE products ( + id int(11) DEFAULT NULL auto_increment PRIMARY KEY + name VARCHAR(255), + description text, +); +``` + +同样地,如果我们想要更新数据库中的表的字段,也需要创建一个 Migration 文件,ActiveRecord 会为我们直接生成一个 SQL 语句并在数据库中执行。 + +ActiveRecord 对数据库的增删改查功能都做了相应的实现,在使用它进行数据库查询时,会生成一条 SQL 语句,在数据库中执行,并将执行的结果初始化成一个 Model 的实例并返回: + +```ruby +user = User.find(10) +# => SELECT * FROM users WHERE (users.id = 10) LIMIT 1 +``` + +这就是 ActiveRecord 作为 Model 层的 ORM 框架解决两个关键问题的方式,其最终结果都是生成一条 SQL 语句并扔到数据库中执行。 + +![Relation-Between-Database-And-Mode](images/model/Relation-Between-Database-And-Model.jpg) + +总而言之,Model 层为调用方屏蔽了所有与数据库相关的底层细节,使开发者不需要考虑如何手写 SQL 语句,只需要关心原生的代码,能够极大的降低出错的概率;但是,由于 SQL 语句都由 Model 层负责处理生成,它并不会根据业务帮助我们优化 SQL 查询语句,所以在遇到数据量较大时,其性能难免遇到各种问题,我们仍然需要手动优化查询的 SQL 语句。 + +#### Controller + +Model 与数据库之间的关系其实大多数都与数据的存储查询有关,而与 Controller 的关系就不是这样了,在 Rails 这个 MVC 框架中,提倡将业务逻辑放到 Model 层进行处理,也就是所谓的: + +> Fat Models, skinny controllers. + +这种说法形成的原因是,在绝大部分的 MVC 框架中,Controller 的作用都是将请求代理给 Model 去完成,它本身并不包含任何的业务逻辑,任何实际的查询、更新和删除操作都不应该在 Controller 层直接进行,而是要讲这些操作交给 Model 去完成。 + +```ruby +class UsersController + def show + @user = User.find params[:id] + end +end +``` + +这也就是为什么在后端应用中设计合理的 Controller 实际上并没有多少行代码,因为大多数业务逻辑相关的代码都会放到 Model 层。 + +Controller 的作用更像是胶水,将 Model 层中获取的模型传入 View 层中,渲染 HTML 或者返回 JSON 数据。 + +### 小结 + +虽然服务端对于应用架构的设计已经有了很长时间的沉淀,但是由于客户端和服务端的职责截然不同,我们可以从服务端借鉴一些设计,但是并不应该照搬后端应用架构设计的思路。 + +服务端重数据,如果把整个 Web 应用看做一个黑箱,那么它的输入就是用户发送的数据,发送的形式无论是遵循 HTTP 协议也好还是其它协议也好,它们都是数据。 + +![web-black-box](images/model/web-black-box.jpg) + +在服务端拿到数据后对其进行处理、加工以及存储,最后仍然以数据的形式返回给用户。 + +而客户端重展示,其输入就是用户的行为触发的事件,而输出是用户界面: + +![client-black-box](images/model/client-black-box.jpg) + +也就是说,用户的行为在客户端应用中得到响应,并更新了用户界面 GUI。总而言之: + +> 客户端重展示,服务端重数据。 + +这也是在设计客户端 Model 层时需要考虑的重要因素。 + +## 理想中的 Model 层 + +在上面的两个小节中,分别介绍了 iOS 中现有的 Model 层以及服务端的 Model 层是如何使用的,并且介绍了它们的职责,在这一章节中,我们准备介绍笔者对于 Model 层的看法以及设计。 + +### 明确职责 + +在具体讨论 Model 层设计之前,肯定要明确它的职责,它应该做什么、不应该做什么以及需要为外界提供什么样的接口和功能。 + +客户端重展示,无论是 Web、iOS 还是 Android,普通用户应该**无法直接接触到服务端**,如果一个软件系统的使用非常复杂,并且让**普通**用户**直接**接触到服务端的各种报错、提示,比如 404 等等,那么这个软件的设计可能就是不合理的。 + +> 这里加粗了普通和直接两个词,如果对这句话有疑问,请多读几遍 :) +> 专业的错误信息在软件工程师介入排错时非常有帮助,这种信息应当放置在不明显的角落。 + +![404](images/model/404.gif) + +作为软件工程师或者设计师,应该为用户提供更加合理的界面以及展示效果,比如,使用*您所浏览的网页不存在*来描述或者代替只有从事软件开发行业的人才了解的 404 或者 500 等错误是更为**合适**的方式。 + +上面的例子主要是为了说明客户端的最重要的职责,将**数据合理地展示给用户**,从这里我们可以领会到,Model 层虽然重要,但是却不是客户端最为复杂的地方,它只是起到了一个将服务端数据『映射』到客户端的作用,这个映射的过程就是获取数据的过程,也决定了 Model 层在 iOS 应用中的位置。 + +![Model-in-Client](images/model/Model-in-Client.jpg) + +那么这样就产生了几个非常重要的问题和子问题: + ++ 数据如何获取? + + 在何时获取数据? + + 如何存储服务端的数据? ++ 数据如何展示? + + 应该为上层提供什么样的接口? + +### Model 层 += Service 层? + +首先,我们来解决数据获取的问题,在 iOS 客户端常见的 Model 层中,数据的获取都不是由 Model 层负责的,而是由一个单独的 Service 层进行处理,然而经常这么组织网络请求并不是一个非常优雅的办法: + +1. 如果按照 API 组织 Service 层,那么网络请求越多,整个项目的 Service 层的类的数量就会越庞大; +2. 如果按照资源组织 Service 层,那么为什么不把 Service 层中的代码直接扔到 Model 层呢? + +既然 HTTP 请求都以获取相应的资源为目标,那么以 Model 层为中心来组织 Service 层并没有任何语义和理解上的问题。 + +如果服务端的 API 严格地按照 RESTful 的形式进行设计,那么就可以在客户端的 Model 层建立起一一对应的关系,拿最基本的几个 API 请求为例: + +```swift +extension RESTful { + static func index(completion: @escaping ([Self]) -> ()) + + static func show(id: Int, completion: @escaping (Self?) -> ()) + + static func create(params: [String: Any], completion: @escaping (Self?) -> ()) + + static func update(id: Int, params: [String: Any], completion: @escaping (Self?) -> ()) + + static func delete(id: Int, completion: @escaping () -> ()) +} +``` + +我们在 Swift 中通过 Protocol Extension 的方式为所有遵循 `RESTful` 协议的模型添加基本的 CRUD 方法,那么 `RESTful` 协议本身又应该包含什么呢? + +```swift +protocol RESTful { + init?(json: [String: Any]) + static var url: String { get } +} +``` + +RESTful 协议本身也十分简单,一是 JSON 转换方法,也就是如何将服务器返回的 JSON 数据转换成对应的模型,另一个是资源的 `url` + +> 对于这里的 `url`,我们可以遵循约定优于配置的原则,通过反射获取一个**默认**的资源链接,从而简化原有的 `RESTful` 协议,但是这里为了简化代码并没有使用这种方法。 + +```swift +extension User: RESTful { + static var url: String { + return "http://localhost:3000/users" + } + + init?(json: [String: Any]) { + guard let id = json["id"] as? Int, + let name = json["name"] as? String, + let email = json["email"] as? String, + let age = json["age"] as? Int, + let genderValue = json["gender"] as? Int, + let gender = Gender(rawInt: genderValue) else { + return nil + } + self.init(id: id, name: name, email: email, age: age, gender: gender) + } +} +``` + +在 `User` 模型遵循上述协议之后,我们就可以简单的通过它的静态方法来对服务器上的资源进行一系列的操作。 + +```swift +User.index { users in + // users +} + +User.create(params: ["name": "Stark", "email": "example@email.com", "gender": 0, "age": 100]) { user in + // user +} +``` + +当然 RESTful 的 API 接口仍然需要服务端提供支持,不过以 Model 取代 Service 作为 HTTP 请求的发出者确实是可行的。 + +#### 问题 + +虽然上述的方法简化了 Service 层,但是在真正使用时确实会遇到较多的限制,比如,用户需要对另一用户进行关注或者取消关注操作,这样的 API 如果要遵循 RESTful 就需要使用以下的方式进行设计: + +```swift +POST /api/users/1/follows +DELETE /api/users/1/follows +``` + +这种情况就会导致在当前的客户端的 Model 层没法建立合适的抽象,因为 `follows` 并不是一个真实存在的模型,它只代表两个用户之间的关系,所以在当前所设计的模型层中没有办法实现上述的功能,还需要引入 Service 层,来对服务端中的每一个 Controller 的 action 进行抽象,在这里就不展开讨论了。 + +对 Model 层网络服务的设计,与服务端的设计有着非常大的关联,如果能够对客户端和服务端之间的 API 进行严格规范,那么对于设计出简洁、优雅的网络层还是有巨大帮助的。 + +### 缓存与持久存储 + +客户端的持久存储其实与服务端的存储天差地别,客户端中保存的各种数据更准确的说其实是**缓存**,既然是缓存,那么它在客户端应用中的地位并不是极其重要、非他不可的;正相反,很多客户端应用没有缓存也运行的非常好,它并不是一个必要的功能,只是能够提升用户体验而已。 + +虽然客户端的存储只是缓存,但是在目前的大型应用中,也确实需要这种缓存,有以下几个原因: + ++ 能够快速为用户提供可供浏览的内容; ++ 在网络情况较差或者无网络时,也能够为用户提供兜底数据; + +以上的好处其实都是从用户体验的角度说的,不过缓存确实能够提高应用的质量。 + +在 iOS 中,持久存储虽然不是一个必要的功能,但是苹果依然为我们提供了不是那么好用的 Core Data 框架,但这并不是这篇文章需要介绍和讨论的内容。 + +目前的绝大多数 Model 框架,其实提供的都只是**硬编码**的数据库操作能力,或者提供的 API 不够优雅,原因是虽然 Swift 语法比 Objective-C 更加简洁,但是缺少元编程能力是它的硬伤。 + +熟悉 ActiveRecord 的开发者应该都熟悉下面的使用方式: + +```ruby +User.find_by_name "draven" +``` + +在 Swift 中通过现有的特性很难提供这种 API,所以很多情况下只能退而求其次,继承 `NSObject` 并且使用 `dynamic` 关键字记住 Objective-C 的特性实现一些功能: + +```objectivec +class User: Object { + dynamic var name = "" + dynamic var age = 0 +} +``` + +这确实是一种解决办法,但是并不是特别的优雅,如果我们在编译器间获得模型信息,然后使用这些信息生成代码就可以解决这些问题了,这种方法同时也能够在 Xcode 编译器中添加代码提示。 + +### 上层接口 + +Model 层为上层提供提供的接口其实就是自身的一系列属性,只是将服务器返回的 JSON 经过处理和类型转换,变成了即拆即用的数据。 + +![JSON-Mode](images/model/JSON-Model.jpg) + +上层与 Model 层交互有两种方式,一是通过 Model 层调用 HTTP 请求,异步获取模型数据,另一种就是通过 Model 暴露出来的属性进行存取,而底层数据库会在 Model 属性更改时发出网络请求并且修改对应的字段。 + +## 总结 + +虽然客户端的 Model 层与服务端的 Model 层有着相同的名字,但是客户端的 Model 层由于处理的是缓存,对本地的数据库中的表进行迁移、更改并不是一个必要的功能,在本地表字段进行大规模修改时,只需要删除全部表中的内容,并重新创建即可,只要不影响服务端的数据就不是太大的问题。 + +iOS 中的 Model 层不应该是一个单纯的数据结构,它应该起到发出 HTTP 请求、进行字段验证以及持久存储的职责,同时为上层提供网络请求的方法以及字段作为接口,为视图的展示提供数据源的作用。我们应该将更多的与 Model 层有关的业务逻辑移到 Model 中以控制 Controller 的复杂性。 + diff --git a/contents/architecture/mvx-view.md b/contents/architecture/mvx-view.md new file mode 100644 index 0000000..a655288 --- /dev/null +++ b/contents/architecture/mvx-view.md @@ -0,0 +1,447 @@ +# 谈谈 MVX 中的 View + ++ [谈谈 MVX 中的 Model](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-model.md) ++ [谈谈 MVX 中的 View](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-view.md) ++ [谈谈 MVX 中的 Controller](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-controller.md) ++ [浅谈 MVC、MVP 和 MVVM 架构模式](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx.md) + +> Follow GitHub: [Draveness](https://github.com/Draveness) + +这是谈谈 MVX 系列的第二篇文章,上一篇文章中对 iOS 中 Model 层的设计进行了简要的分析;而在这里,我们会对 MVC 中的视图层进行讨论,谈一谈现有的视图层有着什么样的问题,如何在框架的层面上去改进,同时与服务端的视图层进行对比,分析它们的差异。 + +## UIKit + +UIKit 是 Cocoa Touch 中用于构建和管理应用的用户界面的框架,其中几乎包含着与 UI 相关的全部功能,而我们今天想要介绍的其实是 UIKit 中与视图相关的一部分,也就是 `UIView` 以及相关类。 + +`UIView` 可以说是 iOS 中用于渲染和展示内容的最小单元,作为开发者能够接触到的大多数属性和方法也都由 `UIView` 所提供,比如最基本的布局方式 frame 就是通过 `UIView` 的属性所控制,在 Cocoa Touch 中的所有布局系统最终都会转化为 CFRect 并通过 frame 的方式完成最终的布局。 + +![Frame-And-Components](images/view/Frame-And-Components.jpg) + +`UIView` 作为 UIKit 中极为重要的类,它的 API 以及设计理念决定了整个 iOS 的视图层该如何工作,这也是理解视图层之前必须要先理解 `UIView` 的原因。 + +### UIView + +在 UIKit 中,除了极少数用于展示的类不继承自 `UIView` 之外,几乎所有类的父类或者或者祖先链中一定会存在 `UIView`。 + +![UIView-And-Subclasses](images/view/UIView-And-Subclasses.jpg) + +我们暂且抛开不继承自 `UIView` 的 `UIBarItem` 类簇不提,先通过一段代码分析一下 `UIView` 具有哪些特性。 + +```objectivec +UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"backgoundImage"]]; +UIImageView *logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo"]]; + +UIButton *loginButton = [[UIButton alloc] init]; +[loginButton setTitle:@"登录" forState:UIControlStateNormal]; +[loginButton setTitleColor:UIColorFromRGB(0xFFFFFF) forState:UIControlStateNormal]; +[loginButton.titleLabel setFont:[UIFont boldSystemFontOfSize:18]]; +[loginButton setBackgroundColor:UIColorFromRGB(0x00C3F3)]; + +[self.view addSubview:backgroundView]; +[backgroundView addSubview:logoView]; +[backgroundView addSubview:loginButton]; +``` + +`UIView` 作为视图层大部分元素的根类,提供了两个非常重要的特性: + ++ 由于 `UIView` 具有 `frame` 属性,所以为所有继承自 `UIView` 的类提供了绝对布局相关的功能,也就是在 Cocoa Touch 中,所有的视图元素都可以通过 `frame` 设置自己在父视图中的绝对布局; ++ `UIView` 在接口中提供了操作和管理视图层级的属性和方法,比如 `superview`、`subviews` 以及 `-addSubview:` 等方法; + + ```objectivec + @interface UIView (UIViewHierarchy) + + @property (nullable, nonatomic, readonly) UIView *superview; + @property (nonatomic, readonly, copy) NSArray<__kindof UIView *> *subviews; + + - (void)addSubview:(UIView *)view; + + ... + + @end + ``` + + 也就是说 **UIView 和它所有的子类都可以拥有子视图,成为容器并包含其他 UIView 的实例**。 + + ```objectivec + [self.view addSubview:backgroundView]; + [backgroundView addSubview:logoView]; + [backgroundView addSubview:loginButton]; + ``` + +这种使用 `UIView` 同时为子类提供默认的 `frame` 布局以及子视图支持的方式在一定程度上能够降低视图模型的复杂度:因为所有的视图都是一个容器,所以在开发时不需要区分视图和容器,但是这种方式虽然带来了一些方便,但是也不可避免地带来了一些问题。 + +### UIView 与布局 + +在早期的 Cocoa Touch 中,整个视图层的布局都只是通过 `frame` 属性来完成的(绝对布局),一方面是因为在 iPhone5 之前,iOS 应用需要适配的屏幕尺寸非常单一,完全没有适配的兼容问题,所以使用单一的 `frame` 布局方式完全是可行的。 + +但是在目前各种屏幕尺寸的种类暴增的情况下,就很难使用 `frame` 对所有的屏幕进行适配,在这时苹果就引入了 Auto Layout 采用相对距离为视图层的元素进行布局。 + +![AutoLayout](images/view/AutoLayout.jpg) + +不过,这算是苹果比较失败的一次性尝试,主要是因为使用 Auto Layout 对视图进行布局实在太过复杂,所以刚出来的时候也不温不火,很少有人使用,直到 Masonry 的出现使得编写 Auto Layout 代码没有那么麻烦和痛苦才普及起来。 + +但是由于 Auto Layout 的工作原理实际上是解 N 元一次方程组,所以在遇到复杂视图时,会遇到非常严重的性能问题,如果想要了解相关的问题的话,可以阅读 [从 Auto Layout 的布局算法谈性能](http://draveness.me/layout-performance.html) 这篇文章,在这里就不再赘述了。 + +然而 Auto Layout 的相对布局虽然能够在*一定程度上*解决适配**屏幕大小和尺寸接近的**适配问题,比如 iPhone4s、iPhone5、iPhone6 Plus 等移动设备,或者iPad 等平板设备。但是,Auto Layout 不能通过一套代码打通 iPhone 和 iPad 之间布局方式的差异,只能通过代码中的 if 和 else 进行判断。 + +在这种背景下,苹果做了很多的尝试,比如说 [Size-Class-Specific Layout](https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/Size-ClassSpecificLayout.html),Size Class 将屏幕的长宽分为三种: + ++ Compact ++ Regular ++ Any + +这样就出现了最多 3 x 3 的组合,比如屏幕宽度为 Compact 高度为 Regular 等等,它与 Auto Layout 一起工作省去了一些 if 和 else 的条件判断,但是从实际效果上来说,它的用处并不是特别大,而且使用代码来做 Size Class 的相关工作依然非常困难。 + +除了 Auto Layout 和 Size Class 之外,苹果在 iOS9 还推出了 `UIStackView` 来增加 iOS 中的布局方式和手段,这是一种类似 flexbox 的布局方式。 + +虽然 `UIStackView` 可以起到一定的作用,但是由于大多数 iOS 应用都要求对设计稿进行严格还原并且其 API 设计相对啰嗦,开发者同时也习惯了使用 Auto Layout 的开发方式,在惯性的驱动下,`UIStackView` 应用的也不是非常广泛。 + +![UIStackVie](images/view/UIStackView.jpg) + +不过现在很多跨平台的框架都是用类似 `UIStackView` 的方式进行布局,比如 React Native、Weex 等,其内部都使用 Facebook 开源的 Yoga。 + +> 由于 flexbox 以及类似的布局方式在其他平台上都有类似的实现,并且其应用确实非常广泛,笔者认为随着工具的完善,这种布局方式会逐渐进入 iOS 开发者的工具箱中。 + +三种布局方式 `frame`、Auto Layout 以及 `UIStackView` 其实最终布局都会使用 `frame`,其他两种方式 Auto Layout 和 `UIStackView` 都会将代码*描述*的布局转换成 `frame` 进行。 + +#### 布局机制的混用 + +Auto Layout 和 `UIStackView` 的出现虽然为布局提供了一些方便,但是也增加了布局系统的复杂性。 + +因为在 iOS 中几乎所有的视图都继承自 `UIView`,这样也同时继承了 `frame` 属性,在使用 Auto Layout 和 `UIStackView` 时,并没有禁用 `frame` 布局,所以在混用却没有掌握技巧时可能会有一些比较奇怪的问题。 + +其实,在混用 Auto Layout 和 `frame` 时遇到的大部分奇怪的问题都是因为 [translatesAutoresizingMaskIntoConstraints](https://developer.apple.com/reference/uikit/uiview/1622572-translatesautoresizingmaskintoco) 属性没有被正确设置的原因。 + +> If this property’s value is true, the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask. This also lets you modify the view’s size and location using the view’s frame, bounds, or center properties, allowing you to create a static, frame-based layout within Auto Layout. + +在这里就不详细解释该属性的作用和使用方法了。 + +#### 对动画的影响 + +在 Auto Layout 出现之前,由于一切布局都是使用 `frame` 工作的,所以在 iOS 中完成对动画的编写十分容易。 + +```objectivec +UIView.animate(withDuration: 1.0) { + view.frame = CGRect(x: 10, y: 10, width: 200, height: 200) +} +``` + +而当大部分的 iOS 应用都转而使用 Auto Layout 之后,对于视图大小、位置有关的动画就比较麻烦了: + +```objectivec +topConstraint.constant = 10 +leftConstraint.constant = 10 +heightConstraint.constant = 200 +widthConstraint.constant = 200 +UIView.animate(withDuration: 1.0) { + view.layoutIfNeeded() +} +``` + +我们需要对视图上的约束对象一一修改并在最后调用 `layoutIfNeeded` 方法才可以完成相同的动画。由于 Auto Layout 对动画的支持并不是特别的优秀,所以在很多时候笔者在使用 Auto Layout 的视图上,都会使用 `transform` 属性来改变视图的位置,这样虽然也没有那么的优雅,不过也是一个比较方便的解决方案。 + +![lottie](images/view/lottie.jpg) + +### frame 的问题 + +每一个 `UIView` 的 `frame` 属性其实都是一个 `CGRect` 结构体,这个结构体展开之后有四个组成部分: + ++ origin + + x + + y ++ size + + width + + height + +当我们设置一个 `UIView` 对象的 `frame` 属性时,其实是同时设置了它在父视图中的位置和它的大小,从这里可以获得一条比较重要的信息: + +> iOS 中所有的 `UIView` 对象都是使用 `frame` 布局的,否则 `frame` 中的 `origin` 部分就失去了意义。 + +但是如果为 `UIStackView` 中的视图设置 `frame` 的话,这个属性就完全没什么作用了,比如下面的代码: + +```objectivec +UIStackView *stackView = [[UIStackView alloc] init]; +stackView.frame = self.view.frame; +[self.view addSubview:stackView]; + +UIView *greenView = [[UIView alloc] init]; +greenView.backgroundColor = [UIColor greenColor]; +greenView.frame = CGRectMake(0, 0, 100, 100); +[stackView addArrangedSubview:greenView]; + +UIView *redView = [[UIView alloc] init]; +redView.backgroundColor = [UIColor redColor]; +redView.frame = CGRectMake(0, 0, 100, 100); +[stackView addArrangedSubview:redView]; +``` + +`frame` 属性在 `UIStackView` 上基本上就完全失效了,我们还需要使用约束来控制 `UIStackView` 中视图的大小,不过如果你要使用 `frame` 属性来查看视图在父视图的位置和大小,在恰当的时机下是可行的。 + +#### 谈谈 origin + +但是 `frame` 的不正确使用会导致视图之间的耦合,如果内部视图设置了自己在父视图中的 `origin`,但是父视图其实并不会使用直接 `frame` 布局该怎么办?比如,父视图是一个 `UIStackView`,它就会重写子视图的 `origin` 甚至是没有正确设置的 `size` 属性。 + +最重要的是 `UIView` 上 `frame` 的设计导致了视图之间可能会有较强的耦合,因为**子视图不应该知道自己在父视图中的位置**,它应该只关心自己的大小。 + +也就是作为一个简单的 `UIView` 它应该只能设置自己的 `size` 而不是 `origin`,因为父视图可能是一个 `UIStackView` 也可能是一个 `UITableView` 甚至是一个扇形的视图也不是不可能,所以**位置这一信息并不是子视图应该关心的**。 + +如果视图设置了自己的 `origin` 其实也就默认了自己的父视图一定是使用 `frame` 进行布局的,而一旦依赖于外部的信息,它就很难进行复用了。 + +#### 再谈 size + +关于视图大小的确认,其实也是有一些问题的,因为视图在布局时确实可能依赖于父视图的大小,或者更确切的说是需要父视图提供一个可供布局的大小,然后让子视图通过这个 `CGSize` 返回一个自己需要的大小给父视图。 + +![texture](images/view/texture.png) + +这种计算视图大小的方式,其实比较像 [Texture](https://github.com/TextureGroup/Texture) 也就是原来的 AsyncDisplayKit 中对于布局系统的实现。 + +父视图通过调用子视图的 `-layoutSpecThatFits:` 方法获取子视图布局所需要的大小,而子视图通过父视图传入的 `CGSizeRange` 来设置自己的大小。 + +```objectivec +- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize + ... +} +``` + +通过这种方式,子视图对父视图一无所知,它不知道父视图的任何属性,只通过 `-layoutSpecThatFits:` 方法传入的参数进行布局,实现了解耦以及代码复用。 + +### 小结 + +由于确实需要对多尺寸的屏幕进行适配,苹果推出 Auto Layout 和 `UIStackView` 的初衷也没有错,但是在笔者看来,因为绝大部分视图都继承自 `UIView`,所以在很多情况下并没有对开发者进行强限制,比如在使用 `UIStackView` 时只能使用 flexbox 式的布局,在使用 Auto Layout 时也只能使用约束对视图进行布局等等,所以在很多时候会带来一些不必要的问题。 + +同时 `UIView` 中的 `frame` 属性虽然在一开始能够很好的解决的布局的问题,但是随着布局系统变得越来越复杂,使得很多 UI 组件在与非 `frame` 布局的容器同时使用时产生了冲突,最终破坏了良好的封装性。 + +到目前为止 iOS 中的视图层的问题主要就是 `UIView` 作为视图层中的上帝类,提供的 `frame` 布局系统不能良好的和其他布局系统工作,在一些时候 `frame` 属性完全成为了摆设。 + +## 其他平台对视图层的设计 + +在接下来的文章中,我们会介绍和分析其他平台 Android、Web 前端以及后端是如何对视图层进行设计的。 + +### Android 与 View + +与 iOS 上使用命令式的风格生成界面不同,Android 使用声明式的 XML 对界面进行描述,在这里举一个最简单的例子: + +```xml +<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:app="http://schemas.android.com/apk/res-auto" + xmlns:tools="http://schemas.android.com/tools" + android:layout_width="match_parent" + android:layout_height="match_parent" + tools:context="com.example.draveness.myapplication.DisplayMessageActivity"> + + <TextView + android:id="@+id/textView" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginTop="16dp" + android:text="TextView" + app:layout_constraintLeft_toLeftOf="parent" + app:layout_constraintRight_toRightOf="parent" + app:layout_constraintTop_toTopOf="parent" /> + +</android.support.constraint.ConstraintLayout> +``` + +> 整个 XML 文件同时描述了视图的结构和样式,而这也是 Android 对于视图层的设计方式,将结构和样式混合在一个文件中。 + +我们首先来分析一下上述代码的结构,整个 XML 文件中只有两个元素,如果我们去掉其中所有的属性,整个界面的元素就是这样的: + +```xml +<ConstraintLayout> + <TextView/> +</ConstraintLayout> +``` + +由一个 `ConstraintLayout` 节点包含一个 `TextView` 节点。 + +#### View 和 ViewGroup + +我们再来看一个 Android 中稍微复杂的视图结构: + +```xml +<LinearLayout> + <RelativeLayout> + <ImageView/> + <LinearLayout> + <TextView/> + <TextView/> + </LinearLayout> + </RelativeLayout> + <View/> +</LinearLayout> +``` + +上面的 XML 代码描述了一个更加复杂的视图树,这里通过一张图更清晰地展示该视图表示的结构: + +![Android-View-Tree](images/view/Android-View-Tree.jpg) + +我们可以发现,Android 的视图其实分为两类: + ++ 一类是不能有子节点的视图,比如 `View`、`ImageView` 和 `TextView` 等; ++ 另一类是可以有子节点的视图,比如 `LinearLayout` 和 `RelativeLayout` 等; + +在 Android 中,这两类的前者都是 `View` 的子类,也就是视图;后者是 `ViewGroup` 的子类,它主要充当视图的容器,与它的子节点以树形的结构形成了一个层次结构。 + +这种分离视图和容器的方式很好的分离了职责,将管理和控制子视图的功能划分给了 `ViewGroup`,将显示内容的职责抛给了 `View` 对各个功能进行了合理的拆分。 + +子视图的布局属性只有在父视图为特定 `ViewGroup` 时才会激活,否则就会忽略在 XML 中声明的属性。 + +#### 混合的结构与样式 + +在使用 XML 或者类 XML 的这种文本来描述视图层的内容时,总会遇到一种无法避免的争论:样式到底应该放在哪里?上面的例子显然说明了 Android 对于这一问题的选择,也就是将样式放在 XML 结构中。 + +这一章节中并不会讨论样式到底应该放在哪里这一问题,我们会在后面的章节中具体讨论,将样式放在 XML 结构中和单独使用各自的优缺点。 + +### Web 前端 + +随着 Web 前端应用变得越来越复杂,在目前的大多数 Web 前端项目的实践中,我们已经会使用前后端分离方式开发 Web 应用,而 Web 前端也同时包含 Model、View 以及 Controller 三部分,不再通过服务端直接生成前端的 HTML 代码了。 + +![html-css](images/view/html-css.jpg) + +现在最流行的 Web 前端框架有三个,分别是 React、Vue 和 Angular。不过,这篇文章会以最根本的 HTML 和 CSS 为例,简单介绍 Web 前端中的视图层是如何工作的。 + +```html +<div> + <h1 class="text-center">Header</h1> +</div> + +.text-center { + text-align: center; +} +``` + +在 HTML 中其实并没有视图和容器这种概念的划分,绝大多数的元素节点都可以包含子节点,只有少数的无内容标签,比如说 `br`、`hr`、`img`、`input`、`link` 以及 `meta` 才不会**解析**自己的子节点。 + +#### 分离的结构与样式 + +与 Android 在定义视图时,使用混合的结构与样式不同,Web 前端在视图层中,采用 HTML 与 CSS 分离,即结构与样式分离的方式进行设计;虽然在 HTML 中,我们也可以使用 `style` 将 CSS 代码写在视图层的结构中,不过在一般情况下,我们并不会这么做。 + +```html +<body style="background-color:powderblue;"> +</body> +``` + +### 结构与样式 + +在这一章节中,我们会对结构与样式组织方式之间的优劣进行简单的讨论。 + +Android 和 Web 前端使用不同的方式对视图层的结构和样式进行组织,前者使用混合的方式,后者使用分离的结构和样式。 + +相比于分离的组织方式,混合的组织方式有以下的几个优点: + ++ 不需要实现元素选择器,降低视图层解析器实现的复杂性; ++ 元素的样式是内联的,对于元素的样式的定义一目了然,不需要考虑样式的继承等复杂特性; + +分离的组织方式却正相反: + ++ 元素选择器的实现,增加了 CSS 样式代码的复用性,不需要多次定义相同的样式; ++ 将 CSS 代码从结构中抽离能够增强 HTML 的可读性,可以非常清晰、直观的了解 HTML 的层级结构; + +对于结构与样式,不同的组织方式能够带来不同的收益,这也是在设计视图层时需要考虑的事情,我们没有办法在使用一种组织方式时获得两种方式的优点,只能尽可能权衡利弊,选择最合适的方法。 + +### 后端的视图层 + +这一章节将会研究一下后端视图层的设计,不过在真正开始分析其视图层设计之前,我们需要考虑一个问题,后端的视图层到底是什么?它有客户端或者 Web 前端中的**用于展示内容**视图层么? + +这其实是一个比较难以回答的问题,不过严格意义上的后端是没有用于展示内容的视图层的,也就是为客户端提供 API 接口的后端,它们的视图层,其实就是用于返回 JSON 的模板。 + +```ruby +json.extract! user, :id, :mobile, :nickname, :gender, :created_at, :updated_at +json.url user_url user, format: :json +``` + +在 Ruby on Rails 中一般都是类似于上面的 jbuilder 代码。拥有视图层的后端应用大多都是使用了模板引擎技术,直接为 HTTP 请求返回渲染之后的 HTML 和 CSS 等前端代码。 + +总而言是,使用了模板引擎的后端应用其实是混合了 Web 前端和后端,整个服务的视图层其实就是 Web 前端的代码;而现在的大多数 Web 应用,由于遵循了前后端分离的设计,两者之间的通信都使用约定好的 API 接口,所以后端的视图层其实就是单纯的用于渲染 JSON 的代码,比如 Rails 中的 jbuilder。 + +## 理想中的视图层 + +iOS 中理想的视图层需要解决两个最关键的问题: + +1. 细分 `UIView` 的职责,将其分为视图和容器两类,前者负责展示内容,后者负责对子视图进行布局; +2. 去除整个视图层对于 `frame` 属性的依赖,不对外提供 `frame` 接口,每个视图只能知道自己的大小; + +解决上述两个问题的办法就是封装原有的 `UIView` 类,使用组合模式为外界提供合适的接口。 + +![Node-Delegate-UIVie](images/view/Node-Delegate-UIView.jpg) + +### 细分 UIView 的职责 + +`Node` 会作为 `UIView` 的代理,同时也作为整个视图层新的根类,它将屏蔽掉外界与 `UIView` 层级操作的有关方法,比如说:`-addSubview:` 等,同时,它也会屏蔽掉 `frame` 属性,这样每一个 `Node` 类的实例就只能设置自己的大小了。 + +```swift +public class Node: Buildable { + public typealias Element = Node + public let view: UIView = UIView() + + @discardableResult + public func size(_ size: CGSize) -> Element { + view.size = size + return self + } +} +``` + +上面的代码简单说明了这一设计的实现原理,我们可以理解为 `Node` 作为 `UIView` 的透明代理,它不提供任何与视图层级相关的方法以及 `frame` 属性。 + +![Node-Delegate-Filte](images/view/Node-Delegate-Filter.jpg) + +### 容器的实现 + +除了添加一个用于展示内容的 `Node` 类,我们还需要一个 `Container` 的概念,提供为管理子视图的 API 和方法,在这里,我们添加了一个空的 `Container` 协议: + +```swift +public protocol Container { } +``` + +利用这个协议,我们构建一个 iOS 中最简单的容器 `AbsoluteContainer`,内部使用 `frame` 对子视图进行布局,它应该为外界提供添加子视图的接口,在这里就是 `build(closure:)` 方法: + +```swift +public class AbsoluteContainer: Node, Container { + typealias Element = AbsoluteContainer + @discardableResult + public func build(closure: () -> Node) -> Relation<AbsoluteContainer> { + let node = closure() + view.addSubview(node.view) + return Relation<AbsoluteContainer>(container: self, node: node) + } +} +``` + +该方法会在调用后返回一个 `Relation` 对象,这主要是因为在这种设计下的 `origin` 或者 `center` 等属性不再是 `Node` 的一个接口,它应该是 `Node` 节点出现在 `AbsoluteContainer` 时的产物,也就是说,只有在这两者同时出现时,才可以使用这些属性更新 `Node` 节点的位置: + +```swift +public class Relation<Container> { + public let container: Container + public let node: Node + + public init(container: Container, node: Node) { + self.container = container + self.node = node + } +} + +public extension Relation where Container == AbsoluteContainer { + @discardableResult + public func origin(_ origin: CGPoint) -> Relation { + node.view.origin = origin + return self + } +} +``` + +这样就完成了对于 `UIView` 中视图层级和位置功能的剥离,同时使用透明代理以及 `Relation` 为 `Node` 提供其他用于设置视图位置的接口。 + +> 这一章节中的代码都来自于 [Mineral](https://github.com/Draveness/Mineral),如果对代码有兴趣的读者,可以下载自行查看。 + +## 总结 + +Cocoa Touch 中的 UIKit 对视图层的设计在一开始确实是没有问题的,主要原因是在 iOS 早期的布局方式并不复杂,只有单一的 `frame` 布局,而这种方式也恰好能够满足整个平台对于 iOS 应用开发的需要,但是随着屏幕尺寸的增多,苹果逐渐引入的其它布局方式与原有的体系发生了一些冲突,导致在开发时可能遇到奇怪的问题,而这也是本文想要解决的,将原有属于 `UIView` 的职责抽离出来,提供更合理的抽象。 + +## References + ++ [从 Auto Layout 的布局算法谈性能](http://draveness.me/layout-performance.html) ++ [Understanding Auto Layout](https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/index.html#//apple_ref/doc/uid/TP40010853-CH7-SW1) ++ [Size-Class-Specific Layout](https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/Size-ClassSpecificLayout.html) ++ [translatesAutoresizingMaskIntoConstraints](https://developer.apple.com/reference/uikit/uiview/1622572-translatesautoresizingmaskintoco) + diff --git a/contents/architecture/mvx.md b/contents/architecture/mvx.md new file mode 100644 index 0000000..3f370ac --- /dev/null +++ b/contents/architecture/mvx.md @@ -0,0 +1,393 @@ +# 浅谈 MVC、MVP 和 MVVM 架构模式 + ++ [谈谈 MVX 中的 Model](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-model.md) ++ [谈谈 MVX 中的 View](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-view.md) ++ [谈谈 MVX 中的 Controller](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx-controller.md) ++ [浅谈 MVC、MVP 和 MVVM 架构模式](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/architecture/mvx.md) + +> Follow GitHub: [Draveness](https://github.com/Draveness) + +这是 MVX 系列的第四篇文章,在前面的文章中,我们先后介绍了 MVC 架构模式中的 Model、View 和 Controller 的现状,对比了其他平台中的设计,最后给出了作者理想中的结构。 + +而在这一篇文章中,作者会依次介绍 MVC、MVP 以及 MVVM 架构模式以及不同平台对它们的使用;虽然参考了诸多资料,不过文中观点难免掺入作者的主观意见,作者也希望文中的错误与不足之处能被各位读者指出。 + +![MVC-MVVM-MVP](images/mvx/MVC-MVVM-MVP.jpg) + +前面的几篇文章中重点都是介绍 iOS 平台上的 Model、View 和 Controller 如何设计,而这篇文章会对目前 GUI 应用中的 MVC、MVP 和 MVVM 架构模式进行详细地介绍。 + +## MVC + +在整个 GUI 编程领域,MVC 已经拥有将近 50 年的历史了。早在几十年前,Smalltalk-76 就对 MVC 架构模式进行了实现,在随后的几十年历史中,MVC 产生了很多的变种,例如:HMVC、MVA、MVP、MVVM 和其它将 MVC 运用于其它不同领域的模式。 + +### 早期的 MVC + +而本文的内容就是从 MVC 开始的,作为最出名并且应用最广泛的架构模式,MVC 并没有一个**明确的**定义,网上流传的 MVC 架构图也是形态各异,作者查阅了很多资料也没有办法确定到底什么样的架构图才是**标准的** MVC 实现。 + +![MVC-1979](images/mvx/MVC-1979.jpg) + +设计 MVC 的重要目的就是在人的心智模型与计算机的模型之间建立一个桥梁,而 MVC 能够解决这一问题并**为用户提供直接看到信息和操作信息的功能**。 + +> 更早的概念类似 Model-View-Editor(MVE)这里就不再提及了,感兴趣的读者可以阅读这篇论文 [Thing-Model-View-Editor](http://heim.ifi.uio.no/~trygver/1979/mvc-1/1979-05-MVC.pdf) 了解更多的信息。 + +### 混乱的 MVC 架构 + +作者相信,稍有编程经验的开发者就对 MVC 有所了解,至少也是听过 MVC 的名字。作者也一直都认为绝大多数人对于 MVC 理解的概念都一样,很多人对于 MVVM 的实现有很大争论,说遵循什么什么架构的是 MVVM,MVVM 有什么组件、没有什么组件,而对于 MVC 仿佛没有那么大的疑问,这其实却不然。 + +#### ASP.NET MVC + +在最近的几个月,作者发现不同人对于 MVC 的理解有巨大的差异,这是 [ASP.NET MVC Overview](https://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx) 一文中对于 MVC 模式描述的示意图。 + +![MVC-with-ASP.NET](images/mvx/MVC-with-ASP.NET.jpg) + +图片中并没有对 Model、View 和 Controller 三者之间如何交互进行说明,有的也只是几个箭头。我们应该可以这么简单地理解: + +1. 控制器负责管理视图和模型; +2. 视图负责展示模型中的内容; + +> 由于文章没有明确对这三个箭头的含义进行解释,所以在这里也仅作推断,无法确认原作者的意思。 + +#### Spring MVC + +与 ASP.NET 不同,Spring MVC 对于 MVC 架构模式的实现就更加复杂了,增加了一个用于分发请求、管理视图的 DispatchServlet: + +![MVC-with-Spring](images/mvx/MVC-with-Spring.jpg) + +在这里不再介绍 Spring MVC 对于 HTTP 请求的处理流程,我们对其中 Model、View 和 Controller 之间的关系进行简单的分析: + +1. 通过 DispatchServlet 将控制器层和视图层完全解耦; +2. 视图层和模型层之间没有直接关系,只有间接关系,通过控制器对模型进行查询、返回给 DispatchServlet 后再传递至视图层; + +虽然 Spring MVC 也声称自己遵循 MVC 架构模式,但是这里的 MVC 架构模式和 ASP.NET 中却有很大的不同。 + +#### iOS MVC + +iOS 客户端中的 Cocoa Touch 自古以来就遵循 MVC 架构模式,不过 Cocoa Touch 中的 MVC 与 ASP.NET 和 Spring 中的 MVC 截然不同。 + +![MVC-with-iOS](images/mvx/MVC-with-iOS.jpg) + +在 iOS 中,由于 `UIViewController` 类持有一个根视图 `UIView`,所以视图层与控制器层是紧密耦合在一起的,这也是 iOS 项目经常遇到视图控制器非常臃肿的重要原因之一。 + +#### Rails MVC + +Rails 作为著名的 MVC 框架,视图层和模型层没有直接的耦合,而是通过控制器作为中间人对信息进行传递: + +![MVC-with-Rails](images/mvx/MVC-with-Rails.jpg) + +这种 MVC 的设计分离了视图层和模型层之间的耦合,作为承担数据存储功能的模型层,可以通过控制器同时为多种不同的视图提供数据: + +![MVC-in-Rails-with-different-view](images/mvx/MVC-%05in-Rails-with-different-view.jpg) + +控制器根据用户发出的 HTTP 请求,从模型中取出相同的数据,然后传给不同的视图以渲染出不同的结果。Rails 中的 MVC 架构模式能够很好地将用于展示的视图和用于存储数据的数据库进行分离,两者之间通过控制器解耦,能够实现同一数据库对应多种视图的架构。 + +#### 维基百科中的 MVC + +除了上述框架中的 MVC 架构模式,还有一些其它的书籍或者资料对于 MVC 也有着不同的解释,比如维基百科的 [Model-view-controller](https://en.wikipedia.org/wiki/Model–view–controller) 条目,该条目是我们在 Google 搜索 [MVC](https://www.google.com/search?q=MVC) 时能够出现的前几个条目,这也是维基百科中的架构图能够出现在这篇文章中的原因 —— 有着广泛的受众。 + +![MVC-in-Wikipedia](images/mvx/MVC-in-Wikipedia.jpg) + +维基百科中对于 MVC 架构模式交互图的描述其实相比上面的图片还都是比较清晰的,这主要是因为它对架构图中的箭头进行了详细的说明,指出了这个关系到底表示什么。 + +1. 视图被用户看到; +2. 用户使用控制器; +3. 控制器操作模型; +4. 模型更新视图; + +虽然说整个架构图的逻辑是可以说的通的,不过相比于前面的架构图总是感觉有一些奇怪,而在这幅图片中,视图和控制器之间是毫无关系的,这与前面见到的所有 MVC 架构模式都完全不同,作者也不清楚这幅图来源是什么、为什么这么画,放在这里也仅作参考。 + +### 『标准』的 MVC + +到底什么才是标准的 MVC 这个问题,到现在作者也没有一个**确切的**答案;不过多个框架以及书籍对 MVC 的理解有一点是完全相同的,也就是它们都将整个应用分成 Model、View 和 Controller 三个部分,而这些组成部分其实也有着几乎相同的职责。 + ++ 视图:管理作为位图展示到屏幕上的图形和文字输出; ++ 控制器:翻译用户的输入并依照用户的输入操作模型和视图; ++ 模型:管理应用的行为和数据,响应数据请求(经常来自视图)和更新状态的指令(经常来自控制器); + +> 上述内容出自 [Applications Programming in Smalltalk-80: How to use Model-View-Controller (MVC)](http://www.dgp.toronto.edu/~dwigdor/teaching/csc2524/2012_F/papers/mvc.pdf) 一文。 + +作者所理解的真正 MVC 架构模式其实与 ASP.NET 中对于 MVC 的设计完全相同: + +![Standard-MV](images/mvx/Standard-MVC.jpg) + +控制器负责对模型中的数据进行更新,而视图向模型中请求数据;当有用户的行为触发操作时,会有控制器更新模型,并通知视图进行更新,在这时视图向模型请求新的数据,而这就是**作者所理解的**标准 MVC 模式下,Model、View 和 Controller 之间的协作方式。 + +#### 依赖关系 + +虽然我们对 MVC 中的各个模块的交互不是特别了解,但是三者之间的依赖关系却是非常明确的;在 MVC 中,模型层可以单独工作,而视图层和控制器层都依赖与模型层中的数据。 + +![Essential-Dependencies-in-MVC](images/mvx/Essential-Dependencies-in-MVC.jpg) + +> 虽然如上图所示,视图和控制器之间没有相互依赖,不过因为视图和控制器之间的依赖并不常用,所以图中将视图和控制器之间的依赖省略了。 + +#### 分离展示层 + +在 Martin Fowler 对于 Model-View-Controller 的描述中,MVC 最重要的概念就是分离展示层 [Separated Presentation](https://www.martinfowler.com/eaaDev/SeparatedPresentation.html),如何在领域对象(Domain Object)和我们在屏幕上看到的 GUI 元素进行划分是 MVC 架构模式中最核心的问题。 + +GUI 应用程序由于其需要展示内容的特点,分为两个部分:一部分是用于展示内容的展示层(Presentation Layer),另一部分包含领域和数据逻辑的领域层(Domain Layer)。 + +![Presentation-Domain](images/mvx/Presentation-Domain.jpg) + +展示层依赖于领域层中存储的数据,而领域层对于展示层一无所知,领域层其实也是 MVC 模式中的模型层,而展示层可以理解为 VC 部分。 + +MVC 最重要的目的并不是规定各个模块应该如何交互和联系,而是将原有的混乱的应用程序划分出合理的层级,把一团混乱的代码,按照展示层和领域层分成两个部分;在这时,领域层中的领域对象由于其自身特点不需要对展示层有任何了解,可以同时为不同的展示层工作。 + +#### 观察者同步 + +除了分离展示层,MVC 还与观察者同步 [Observer Synchronization](https://www.martinfowler.com/eaaDev/MediatedSynchronization.html) 关系紧密。因为在 MVC 模式中,模型可以单独工作,同时它对使用模型中数据的视图和控制器一无所知,为了保持模型的独立性,我们需要一种机制,当模型发生改变时,能够同时更新多个视图和控制器的内容;在这时,就需要以观察者同步的方式解决这个问题。 + +![Observer-Synchronization](images/mvx/Observer-Synchronization.jpg) + +我们将所有需要实时更新的组件注册成为模型的观察者,在模型的属性发生变化时,通过观察者模式推送给所有注册的观察者(视图和控制器)。 + +当多个视图共享相同的数据时,观察者同步是一个非常关键的模式,它能够在对这些视图不知情的前提下,同时通知多个视图;通过观察者模式,我们可以非常容易地创建一个依赖于同一模型的视图。 + +观察者同步或者说观察者模式的主要缺点就是:由于事件触发的隐式行为可能导致很难查找问题的来源并影响其解决,不过虽然它有着这样的缺点,但是观察者同步这一机制仍然成为 MVC 以及其衍生架构模式中非常重要的一部分。 + +#### 占主导地位的控制器 + +MVC 架构模式的三个组成部分:Model、View 和 Controller 中最重要的就是控制器,它承担了整个架构中的大部分业务逻辑,同时在用户请求到达或者事件发生时都会首先通知控制器并由它来决定如何响应这次请求或者事件。 + +![Main-Controlle](images/mvx/Main-Controller.jpg) + +在 MVC 中,所有的用户请求都会首先交给控制器,再由控制器来决定如何响应用户的输入,无论是更新模型中的信息还是渲染相应的视图,都是通过控制器来决定的;也就是说,在 MVC 中,控制器占据主导地位,它决定用户的输入是如何被处理的。 + +#### 被动的模型 + +在绝大多数的 MVC 架构模式中,模型都不会主动向视图或者控制器推送消息;模型都是被动的,它只存储整个应用中的数据,而信息的获取和更新都是由控制器来驱动的。 + +![Passive-Mode](images/mvx/Passive-Model.jpg) + +但是当模型中的数据发生变化时,却需要通过一些方式通知对应的视图进行更新,在这种情况下其实也不需要模型**主动**将数据变化的消息推送给视图;因为所有对于模型层的改变都是**由用户的操作导致的**,而用户的操作都是通过控制器来处理的,所以只需要在控制器改变模型时,将更新的信息发送给视图就可以了;当然,我们也可以通过**观察者模式**向未知的观察者发送通知,以保证状态在不同模块之间能够保持同步。 + +作为被动的模型层,它对于视图和控制器的存在并不知情,只是向外部提供接口并响应视图和控制器对于数据的请求和更新操作。 + +#### MVC + MVC + +目前的大多数应用程序都非常复杂并且同时包含客户端和服务端,两者分开部署但同时又都遵循 MVC 或者衍生的架构模式;过去的 Web 应用由于并不复杂,前端和服务端往往都部署在同一台服务器上,比如说使用 erb 模板引擎的 Rails 或者使用 jsp 的 Java 等等;这时的 Web 应用都遵循 MVC 架构模式: + +![MVC-Web-App](images/mvx/MVC-Web-App.jpg) + +> 上图的 MVC 架构模式的通信方式与标准的 MVC 中不同,上图以 Rails 为例展示其中的 MVC 是如何工作的,其中的 HTML、CSS 和 Javascript 代码就是视图层,控制器负责视图的渲染并且操作模型,模型中包含部分业务逻辑并负责管理数据库。 + +过去的 Web 应用的非常简单,而现在的应用程序都非常复杂,而整个应用程序无论是 Web 还是客户端其实都包含两个部分,也就是前端/客户端和后端;先抛开后端不谈,无论是 Web 前端、iOS 还是 Android 都遵循 MVC 架构模式或者它的变种。 + +![MVC-App-Arch](images/mvx/MVC-App-Arch.jpg) + +在实际情况下,单独的 iOS、Android 和 Web 应用往往不能单独工作,这些客户端应用需要与服务端一起工作;当前端/客户端与后端一同工作时,其实分别『部署』了两个不同的应用,这两个应用都遵循 MVC 架构模式: + +![MVC-MV](images/mvx/MVC-MVC.jpg) + +客户端和服务器通过网络进行连接,并组成了一个更大的 MVC 架构;从这个角度来看,服务端的模型层才存储了真正的数据,而客户端的模型层只不过是一个存储在客户端设备中的本地缓存和临时数据的集合;同理,服务端的视图层也不是整个应用的视图层,用于为用户展示数据的视图层位于客户端,也就是整个架构的最顶部;中间的五个部分,也就是从低端的模型层到最上面的视图共同组成了整个应用的控制器,将模型中的数据以合理的方式传递给最上层的视图层用于展示。 + +## MVP + +MVP 架构模式是 MVC 的一个变种,很多框架都自称遵循 MVC 架构模式,但是它们实际上却实现了 MVP 模式;MVC 与 MVP 之间的区别其实并不明显,作者认为两者之间最大的区别就是 MVP 中使用 Presenter 对视图和模型进行了解耦,它们彼此都对对方一无所知,沟通都通过 Presenter 进行。 + +MVP 作为一个比较有争议的架构模式,在维基百科的 [Model-view-presenter](https://en.wikipedia.org/wiki/Model–view–presenter) 词条中被描述为 MVC 设计模式的变种(derivation),自上个世纪 90 年代出现在 IBM 之后,随着不断的演化,虽然有着很多分支,不过 Martin Fowler 对 MVP 架构模式的定义最终被广泛接受和讨论。 + +![Standard-MVP](images/mvx/Standard-MVP.jpg) + +在 MVP 中,Presenter 可以理解为松散的控制器,其中包含了视图的 UI 业务逻辑,所有从视图发出的事件,都会通过代理给 Presenter 进行处理;同时,Presenter 也通过视图暴露的接口与其进行通信。 + +目前常见的 MVP 架构模式其实都是它的变种:[Passive View](https://www.martinfowler.com/eaaDev/PassiveScreen.html) 和 [Supervising Controller](https://www.martinfowler.com/eaaDev/SupervisingPresenter.html),接下来的内容也是围绕这两种变种进行展开的。 + +### 被动视图 + +MVP 的第一个主要变种就是被动视图(Passive View);顾名思义,在该变种的架构模式中,视图层是被动的,它本身不会改变自己的任何的状态,所有的状态都是通过 Presenter 来间接改变的。 + +![PassIve-Vie](images/mvx/PassIve-View.jpg) + +被动的视图层就像前端中的 HTML 和 CSS 代码,只负责展示视图的结构和内容,本身不具有任何的逻辑: + +```swift +<article class="post"> + <header class="post-header"> + <h2 class="post-title"><a href="/mvx-controller.html">谈谈 MVX 中的 Controller</a></h2> + </header> + <section class="post-excerpt"> + <p>在前两篇文章中,我们已经对 iOS 中的 Model 层以及 View 层进行了分析,划分出了它们的具体职责,其中 Model 层除了负责数据的持久存储、缓存工作,还要负责所有 HTTP... <a class="read-more" href="/mvx-controller.html">»</a></p> + </section> + <footer class="post-meta"> + <img class="author-thumb" src="/assets/images/draven.png" alt="Author image" nopin="nopin" /> + <a href='/author/draveness'>Draveness</a> + <time class="post-date" datetime="2017-06-23">23 Jun 2017</time> + </footer> +</article> +``` + +#### 依赖关系 + +视图成为了完全被动的并且不再根据模型来更新视图本身的内容,也就是说,不同于 MVC 中的依赖关系;在被动视图中,视图层对于模型层没有任何的依赖: + +![Essential-Dependencies-in-Passive-Vie](images/mvx/Essential-Dependencies-in-Passive-View.jpg) + +因为视图层不依赖与其他任何层级也就最大化了视图层的可测试性,同时也将视图层和模型层进行了合理的分离,两者不再相互依赖。 + +#### 通信方式 + +被动视图的示意图中一共有四条线,用于表示 Model、View 和 Presenter 之间的通信: + +![Passive-View-with-Tags](images/mvx/Passive-View-with-Tags.jpg) + +1. 当视图接收到来自用户的事件时,会将事件转交给 Presenter 进行处理; +2. 被动的视图向外界暴露接口,当需要更新视图时 Presenter 通过视图暴露的接口更新视图的内容; +3. Presenter 负责对模型进行操作和更新,在需要时取出其中存储的信息; +4. 当模型层改变时,可以将改变的信息发送给**观察者** Presenter; + +在 MVP 的变种被动视图中,模型的操作以及视图的更新都仅通过 Presenter 作为中间人进行。 + +### 监督控制器 + +与被动视图中状态同步都需要**显式**的操作不同,监督控制器(Supervising Controller)就将部分需要显式同步的操作变成了隐式的: + +![Supervising-Controller](images/mvx/Supervising-Controller.jpg) + +在监督控制器中,视图层接管了一部分视图逻辑,主要内容就是同步**简单的**视图和模型的状态;而监督控制器就需要负责响应用户的输入以及一部分更加复杂的视图、模型状态同步工作。 + +对于用户输入的处理,监督控制器的做法与标准 MVP 中的 Presenter 完全相同;但是对于视图、模型的同步工作,监督控制器会尽可能地将所有简单的属性**以数据绑定的形式声明在视图层中**,类似于 Vue 中双向绑定的简化版本: + +```html +<a v-bind:href="url"></a> +``` + +剩下的无法通过上述方式直接绑定的属性就需要通过监督控制器来操作和更新了。 + +#### 通信方式 + +监督控制器中的视图和模型层之间增加了两者之间的耦合,也就增加了整个架构的复杂性: + +![Supervising-Controller-With-Tag](images/mvx/Supervising-Controller-With-Tag.jpg) + +视图和监督控制器、模型与监督控制器的关系与被动视图中两者与 Presenter 的关系几乎相同,视图和模型之间新增的依赖就是数据绑定的产物;视图通过声明式的语法与模型中的简单属性进行绑定,当模型发生改变时,会通知其观察者视图作出相应的更新。 + +通过这种方式能够减轻监督控制器的负担,减少其中简单的代码,将一部分逻辑交由视图进行处理;这样也就导致了视图同时可以被 Presenter 和数据绑定两种方式更新,相比于被动视图,监督控制器的方式也降低了视图的可测试性和封装性。 + +### 占主导地位的视图 + +无论是在被动视图还是监督控制器版本的 MVP 架构模式中,视图层在整个架构中都是占主导地位的: + +![Main-View-in-MVP](images/mvx/Main-View-in-MVP.jpg) + +在 MVC 中,控制器负责**以不同的视图响应客户端请求的不同动作**;然而,不同于 MVC 模式,MVP 中视图将所有的动作交给 Presenter 进行处理;MVC 中的所有的动作都对应着一个控制器的方法调用,Web 应用中的每一个动作都是对某一个 URL 进行的操作,控制器根据访问的路由和方法(GET 等)对数据进行操作,最终选择正确的视图进行返回。 + +MVC 中控制器返回的视图没有直接绑定到模型上,它仅仅被控制器渲染并且是完全无状态的,其中不包含任何的逻辑,但是 MVP 中的视图**必须要将对应的事件代理给 Presenter 执行**,否则事件就无法被响应。 + +另一个 MVP 与 MVC 之间的重大区别就是,MVP(Passive View)中的视图和模型是完全解耦的,它们对于对方的存在完全不知情,这也是区分 MVP 和 MVC 的一个比较容易的方法。 + +> 上述内容取自 [What are MVP and MVC and what is the difference? · Stack Overflow](https://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference) 中的 Model-View-Controller 部分。 + +## MVVM + +相较于 MVC 和 MVP 模式,MVVM 在定义上就明确得多,同时,维基百科上对于 [Model-View-ViewModel](https://en.wikipedia.org/wiki/Model–view–viewmodel) 的词条也没有歧义;不过,在谈 MVVM 架构模式之前,我们需要先了解它是如何发展和演变的。 + +### MVVM 的演变 + +早在 2004 年,Martin Fowler 发表了一篇名为 [Presentation Model](https://www.martinfowler.com/eaaDev/PresentationModel.html) (以下简称为 PM 模式)的文章,PM 模式与 MVP 比较相似,它从视图层中分离了行为和状态;PM 模式中创建了一个视图的抽象,叫做 Presentation Model,而视图也成为了这个模型的『渲染』结果。 + +![PM-and-MVV](images/mvx/PM-and-MVVM.jpg) + +2005 年,John Gossman 在他的博客上公布了 [Introduction to Model/View/ViewModel pattern for building WPF apps](https://blogs.msdn.microsoft.com/johngossman/2005/10/08/introduction-to-modelviewviewmodel-pattern-for-building-wpf-apps/) 一文。MVVM 与 Martin Fowler 所说的 PM 模式其实是完全相同的,Fowler 提出的 PM 模式是一种与平台无关的创建视图抽象的方法,而 Gossman 的 MVVM 是专门用于 WPF 框架来简化用户界面的创建的模式;我们可以认为 **MVVM 是在 WPF 平台上对于 PM 模式的实现**。 + +> 有兴趣的读者可以阅读 [Introduction to Model/View/ViewModel pattern for building WPF apps](https://blogs.msdn.microsoft.com/johngossman/2005/10/08/introduction-to-modelviewviewmodel-pattern-for-building-wpf-apps/ · MSDN) 获得更多与 MVVM 演化的相关信息。 + +### 展示模型 + +> 本节大部分内容都节选自 Martin Fowler 的 [Presentation Model](https://www.martinfowler.com/eaaDev/PresentationModel.html) 一文。 + +既然 MVVM 是展示模型 [Presentation Model](https://www.martinfowler.com/eaaDev/PresentationModel.html) 的一个实现,那么在介绍 Model-View-ViewModel 之前,我们就需要了解 PM 模式到底是什么。 + +在 MVC 一节中曾经有过对展示层和领域层进行分离的讨论,而 PM 模式就与分离展示层 [Separated Presentation](https://www.martinfowler.com/eaaDev/SeparatedPresentation.html) 有一定的关系。 + +作为 Martin Fowler 在 2004 年提出的概念,Presentation Model 到今天其实也是非常先进的,PM 模式将视图中的全部状态和行为放到一个单独的展示模型中,协调领域对象(模型)并且为视图层提供一个接口。 + +在监督控制器中,视图层与模型层中的一些简单属性进行绑定,在模型属性变化时直接更新视图,而 PM 通过引入展示模型将**模型层中的数据与复杂的业务逻辑封装成属性与简单的数据同时暴露给视图,让视图和展示模型中的属性进行同步**。 + +![Presentation-Mode](images/mvx/Presentation-Model.jpg) + +展示模型中包含所有的视图渲染需要的动态信息,包括视图的内容(text、color)、组件是否启用(enable),除此之外还会将一些方法暴露给视图用于某些事件的响应。 + +#### 状态的同步 + +展示模型对于模型层的操作以及为视图层暴露接口都是非常容易的,在整个 PM 模式中,最为麻烦的就是视图和展示模型状态的同步。 + +因为展示模型是视图的抽象,其中包含了视图的状态(属性)和行为(动作),视图的行为可能很少发生改变,但是视图状态的改变就是非常常见的了,那么同步视图和展示模型的代码应该放哪里就是一个需要考虑的问题了。 + +到目前为止,我们能够防止状态同步代码的地方其实只有两个,也就是视图和展示模型;如果将同步的代码放在视图中,那么可能会影响视图的测试,不过由于现在的大部分客户端程序完全没有测试,这一点其实也影响不大;如果将代码放在展示模型中,实际上就为展示模型增加了视图的依赖,导致不同层级之间的耦合。 + +> 在作者看来这两种选择其实都影响并不大,反正我们的应用中并没有测试嘛。 + +#### 展示模型与其他模块的关系 + +在 PM 模式中,同一个展示模型可以与多个领域对象交互,多个视图可以使用相同的展示模型,但是每一个视图只能持有一个展示模型。 + +![PM-View-Domain-Object](images/mvx/PM-View-Domain-Object.jpg) + +PM 模式中不同层级之间的关系还是非常容易理解的,在这里就不做具体解释了。 + +### MVVM 与 WPF + +MVVM 架构模式是微软在 2005 年诞生的,从诞生一开始就与 WPF 框架的联系非常紧密,在这一节中,我们将介绍 MVVM 模式是如何遵循 PM 模式实现的,WPF 作为微软用于处理 GUI 软件的框架,提供了一套非常优雅的解决方案。 + +![Model-View-ViewModel](images/mvx/Model-View-ViewModel.jpg) + +从 Model-View-ViewModel 这个名字来看,它由三个部分组成,也就是 Model、View 和 ViewModel;其中视图模型(ViewModel)其实就是 PM 模式中的展示模型,在 MVVM 中叫做视图模型。 + +除了我们非常熟悉的 Model、View 和 ViewModel 这三个部分,在 MVVM 的实现中,还引入了**隐式的**一个 Binder 层,而声明式的数据和命令的绑定在 MVVM 模式中就是通过它完成的。 + +![Binder-View-ViewModel](images/mvx/Binder-View-ViewModel.jpg) + +在实现 PM 模式时,我们需要处理视图和展示模型之间状态的同步,也就是 MVVM 中的视图和视图模型,我们使用隐式的 Binder 和 XAML 文件来完成视图和视图模型两者之间的双向绑定: + +```xml +<Window x:Class ="WPFDataBinding.MainWindow" Title="MainWindow" Height="350" Width="604"> + <Grid> + <Label Name="nameLabel" Margin="2">_Name:</Label> + <TextBox Name="nameText" Grid.Column="1" Margin="2" + Text="{Binding Name}"/> + <Label Name="ageLabel" Margin="2" Grid.Row ="1">_Age:</Label> + <TextBox Name="ageText" Grid.Column="1" Grid.Row ="1" Margin ="2" + Text="{Binding Age}"/> + </Grid> +</Window> +``` + +在 WPF 中我们可以使用 Binding 关键字在 XAML 中完成双向绑定,当 `TextBox` 中的文字更新时,Binder 也会更新 ViewModel 中对应属性 `Name` 或者 `Age` 的值。 + +我们可以说 MVVM 将视图和展示模型之间的同步代码放到了视图层(XAML)中,也可以说通过隐式的方法实现了状态的同步。 + +无论是 MVVM 还是 Presentation Model,其中最重要的不是如何同步视图和展示模型/视图模型之间的状态,是使用观察者模式、双向绑定还是其它的机制都不是整个模式中最重要的部分,最为关键的是**展示模型/视图模型创建了一个视图的抽象,将视图中的状态和行为抽离出一个新的抽象**,这才是 MVVM 和 PM 中需要注意的。 + +## 总结 + +从 MVC 架构模式到 MVVM,从分离展示层到展示模型层,经过几十年的发展和演变,MVC 架构模式出现了各种各样的变种,并在不同的平台上有着自己的实现。 + +在架构模式的选用时,我们往往没有太多的发言权,主要因为平台本身往往对应用层有着自己的设计,我们在开发客户端或者前端应用时,只需要遵循平台固有的设计就可以完成应用的开发;不过,在有些时候,由于工程变得庞大、业务逻辑变得异常复杂,我们也可以考虑在原有的架构之上实现一个新的架构以满足工程上的需要。 + +各种架构模式的作用就是分离关注,将属于不同模块的功能分散到合适的位置中,同时尽量降低各个模块的相互依赖并且减少需要联系的胶水代码。文中对于 MVC、MVP 和 MVVM 架构模式的描述很难不掺杂作者的主观意见,如果对文章中的内容有疑问,欢迎提出不同的意见进行讨论。 + +## Reference + ++ [MVC Index](http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html) ++ [The Model-View-Controller (MVC) Its Past and Present](http://heim.ifi.uio.no/~trygver/2003/javazone-jaoo/MVC_pattern.pdf) ++ [The evolution of the Dolphin Smalltalk MVP application framework](http://www.object-arts.com/downloads/papers/TwistingTheTriad.PDF) ++ [MVP: Model-View-Presenter · The Taligent Programming Model for C++ and Java](http://www.wildcrest.com/Potel/Portfolio/mvp.pdf) ++ [Implementing the Model-View-ViewModel Pattern · MSDN](https://msdn.microsoft.com/en-us/library/ff798384.aspx) ++ [GUI Architectures · Martin Fowler](https://martinfowler.com/eaaDev/uiArchs.html) ++ [GUI 应用程序架构的十年变迁](https://zhuanlan.zhihu.com/p/26799645) ++ [Elm Architecture Tutorial · GitHub](https://github.com/evancz/elm-architecture-tutorial/) ++ [Presentation Model · Martin Fowler](https://martinfowler.com/eaaDev/PresentationModel.html) ++ [Model-view-controller · Wikipedia](https://en.wikipedia.org/wiki/Model–view–controller) ++ [Model-view-presenter · Wikipedia](https://en.wikipedia.org/wiki/Model–view–presenter) ++ [Model-view-viewmodel · Wikipedia](https://en.wikipedia.org/wiki/Model–view–viewmodel) ++ [Thing-Model-View-Editor](http://heim.ifi.uio.no/~trygver/1979/mvc-1/1979-05-MVC.pdf) ++ [ASP.NET MVC Overview · MSDN](https://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx) ++ [Intermediate Rails: Understanding Models, Views and Controllers](https://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/) ++ [Passive View · Martin Fowler](https://www.martinfowler.com/eaaDev/PassiveScreen.html) ++ [Supervising Controller · Martin Fowler](https://www.martinfowler.com/eaaDev/SupervisingPresenter.html) ++ [Applications Programming in Smalltalk-80: How to use Model-View-Controller (MVC)](http://www.dgp.toronto.edu/~dwigdor/teaching/csc2524/2012_F/papers/mvc.pdf) ++ [What are MVP and MVC and what is the difference? · Stack Overflow](https://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference) ++ [Model-View-Presenter Pattern](http://webclientguidance.codeplex.com/wikipage?title=ModelViewPresenterPatternDescription&referringTitle=MVPDocumentation) ++ [Patterns - WPF Apps With The Model-View-ViewModel Design Pattern · MSDN](https://msdn.microsoft.com/en-us/magazine/dd419663.aspx) ++ [Introduction to Model/View/ViewModel pattern for building WPF apps](https://blogs.msdn.microsoft.com/johngossman/2005/10/08/introduction-to-modelviewviewmodel-pattern-for-building-wpf-apps/ · MSDN) ++ [设计模式](https://en.wikipedia.org/wiki/Design_Patterns) + + diff --git a/fishhook/images/fishbook-printf.png b/contents/fishhook/images/fishbook-printf.png similarity index 100% rename from fishhook/images/fishbook-printf.png rename to contents/fishhook/images/fishbook-printf.png diff --git a/fishhook/images/fishhook-before-after.png b/contents/fishhook/images/fishhook-before-after.png similarity index 100% rename from fishhook/images/fishhook-before-after.png rename to contents/fishhook/images/fishhook-before-after.png diff --git a/fishhook/images/fishhook-hello-breakpoint.png b/contents/fishhook/images/fishhook-hello-breakpoint.png similarity index 100% rename from fishhook/images/fishhook-hello-breakpoint.png rename to contents/fishhook/images/fishhook-hello-breakpoint.png diff --git a/fishhook/images/fishhook-hello.png b/contents/fishhook/images/fishhook-hello.png similarity index 100% rename from fishhook/images/fishhook-hello.png rename to contents/fishhook/images/fishhook-hello.png diff --git a/fishhook/images/fishhook-imp.png b/contents/fishhook/images/fishhook-imp.png similarity index 100% rename from fishhook/images/fishhook-imp.png rename to contents/fishhook/images/fishhook-imp.png diff --git a/fishhook/images/fishhook-mach-o.png b/contents/fishhook/images/fishhook-mach-o.png similarity index 100% rename from fishhook/images/fishhook-mach-o.png rename to contents/fishhook/images/fishhook-mach-o.png diff --git a/fishhook/images/fishhook-result.png b/contents/fishhook/images/fishhook-result.png similarity index 100% rename from fishhook/images/fishhook-result.png rename to contents/fishhook/images/fishhook-result.png diff --git a/fishhook/images/fishhook-symbol.png b/contents/fishhook/images/fishhook-symbol.png similarity index 100% rename from fishhook/images/fishhook-symbol.png rename to contents/fishhook/images/fishhook-symbol.png diff --git "a/fishhook/\345\212\250\346\200\201\344\277\256\346\224\271 C \350\257\255\350\250\200\345\207\275\346\225\260\347\232\204\345\256\236\347\216\260.md" "b/contents/fishhook/\345\212\250\346\200\201\344\277\256\346\224\271 C \350\257\255\350\250\200\345\207\275\346\225\260\347\232\204\345\256\236\347\216\260.md" similarity index 100% rename from "fishhook/\345\212\250\346\200\201\344\277\256\346\224\271 C \350\257\255\350\250\200\345\207\275\346\225\260\347\232\204\345\256\236\347\216\260.md" rename to "contents/fishhook/\345\212\250\346\200\201\344\277\256\346\224\271 C \350\257\255\350\250\200\345\207\275\346\225\260\347\232\204\345\256\236\347\216\260.md" diff --git a/images/AFURLResponseSerialization.png b/contents/images/AFURLResponseSerialization.png similarity index 100% rename from images/AFURLResponseSerialization.png rename to contents/images/AFURLResponseSerialization.png diff --git a/images/PendingInitializeMap.png b/contents/images/PendingInitializeMap.png similarity index 100% rename from images/PendingInitializeMap.png rename to contents/images/PendingInitializeMap.png diff --git a/images/afnetworking-arch.png b/contents/images/afnetworking-arch.png similarity index 100% rename from images/afnetworking-arch.png rename to contents/images/afnetworking-arch.png diff --git a/images/afnetworking-logo.png b/contents/images/afnetworking-logo.png similarity index 100% rename from images/afnetworking-logo.png rename to contents/images/afnetworking-logo.png diff --git a/images/afnetworking-plist.png b/contents/images/afnetworking-plist.png similarity index 100% rename from images/afnetworking-plist.png rename to contents/images/afnetworking-plist.png diff --git a/images/banner.png b/contents/images/banner.png similarity index 100% rename from images/banner.png rename to contents/images/banner.png diff --git a/images/blockskit.png b/contents/images/blockskit.png similarity index 100% rename from images/blockskit.png rename to contents/images/blockskit.png diff --git a/images/logo.png b/contents/images/logo.png similarity index 100% rename from images/logo.png rename to contents/images/logo.png diff --git a/images/obj-method-struct.png b/contents/images/obj-method-struct.png similarity index 100% rename from images/obj-method-struct.png rename to contents/images/obj-method-struct.png diff --git a/images/objc-ao-associateobjcect.png b/contents/images/objc-ao-associateobjcect.png similarity index 100% rename from images/objc-ao-associateobjcect.png rename to contents/images/objc-ao-associateobjcect.png diff --git a/images/objc-ao-isa-struct.png b/contents/images/objc-ao-isa-struct.png similarity index 100% rename from images/objc-ao-isa-struct.png rename to contents/images/objc-ao-isa-struct.png diff --git a/images/objc-ao-warning-category-property.png b/contents/images/objc-ao-warning-category-property.png similarity index 100% rename from images/objc-ao-warning-category-property.png rename to contents/images/objc-ao-warning-category-property.png diff --git a/images/objc-autorelease-AutoreleasePoolPage-linked-list.png b/contents/images/objc-autorelease-AutoreleasePoolPage-linked-list.png similarity index 100% rename from images/objc-autorelease-AutoreleasePoolPage-linked-list.png rename to contents/images/objc-autorelease-AutoreleasePoolPage-linked-list.png diff --git a/images/objc-autorelease-AutoreleasePoolPage.png b/contents/images/objc-autorelease-AutoreleasePoolPage.png similarity index 100% rename from images/objc-autorelease-AutoreleasePoolPage.png rename to contents/images/objc-autorelease-AutoreleasePoolPage.png diff --git a/images/objc-autorelease-after-insert-to-page.png b/contents/images/objc-autorelease-after-insert-to-page.png similarity index 100% rename from images/objc-autorelease-after-insert-to-page.png rename to contents/images/objc-autorelease-after-insert-to-page.png diff --git a/images/objc-autorelease-breakpoint-main.png b/contents/images/objc-autorelease-breakpoint-main.png similarity index 100% rename from images/objc-autorelease-breakpoint-main.png rename to contents/images/objc-autorelease-breakpoint-main.png diff --git a/images/objc-autorelease-main-cpp-struct.png b/contents/images/objc-autorelease-main-cpp-struct.png similarity index 100% rename from images/objc-autorelease-main-cpp-struct.png rename to contents/images/objc-autorelease-main-cpp-struct.png diff --git a/images/objc-autorelease-main-cpp.png b/contents/images/objc-autorelease-main-cpp.png similarity index 100% rename from images/objc-autorelease-main-cpp.png rename to contents/images/objc-autorelease-main-cpp.png diff --git a/images/objc-autorelease-main.png b/contents/images/objc-autorelease-main.png similarity index 100% rename from images/objc-autorelease-main.png rename to contents/images/objc-autorelease-main.png diff --git a/images/objc-autorelease-page-in-memory.png b/contents/images/objc-autorelease-page-in-memory.png similarity index 100% rename from images/objc-autorelease-page-in-memory.png rename to contents/images/objc-autorelease-page-in-memory.png diff --git a/images/objc-autorelease-pop-stack.png b/contents/images/objc-autorelease-pop-stack.png similarity index 100% rename from images/objc-autorelease-pop-stack.png rename to contents/images/objc-autorelease-pop-stack.png diff --git a/images/objc-autorelease-pop-string.png b/contents/images/objc-autorelease-pop-string.png similarity index 100% rename from images/objc-autorelease-pop-string.png rename to contents/images/objc-autorelease-pop-string.png diff --git a/images/objc-autorelease-print-pool-content.png b/contents/images/objc-autorelease-print-pool-content.png similarity index 100% rename from images/objc-autorelease-print-pool-content.png rename to contents/images/objc-autorelease-print-pool-content.png diff --git a/images/objc-hashtable-copy-class-list.png b/contents/images/objc-hashtable-copy-class-list.png similarity index 100% rename from images/objc-hashtable-copy-class-list.png rename to contents/images/objc-hashtable-copy-class-list.png diff --git a/images/objc-hashtable-hash-state-init.png b/contents/images/objc-hashtable-hash-state-init.png similarity index 100% rename from images/objc-hashtable-hash-state-init.png rename to contents/images/objc-hashtable-hash-state-init.png diff --git a/images/objc-hashtable-hashstate-next.gif b/contents/images/objc-hashtable-hashstate-next.gif similarity index 100% rename from images/objc-hashtable-hashstate-next.gif rename to contents/images/objc-hashtable-hashstate-next.gif diff --git a/images/objc-hashtable-insert-empty.gif b/contents/images/objc-hashtable-insert-empty.gif similarity index 100% rename from images/objc-hashtable-insert-empty.gif rename to contents/images/objc-hashtable-insert-empty.gif diff --git a/images/objc-hashtable-insert-many.gif.gif b/contents/images/objc-hashtable-insert-many.gif.gif similarity index 100% rename from images/objc-hashtable-insert-many.gif.gif rename to contents/images/objc-hashtable-insert-many.gif.gif diff --git a/images/objc-hashtable-insert-one.gif.gif b/contents/images/objc-hashtable-insert-one.gif.gif similarity index 100% rename from images/objc-hashtable-insert-one.gif.gif rename to contents/images/objc-hashtable-insert-one.gif.gif diff --git a/images/objc-hashtable-instrument.png b/contents/images/objc-hashtable-instrument.png similarity index 100% rename from images/objc-hashtable-instrument.png rename to contents/images/objc-hashtable-instrument.png diff --git a/images/objc-hashtable-nsarray-instrument.png b/contents/images/objc-hashtable-nsarray-instrument.png similarity index 100% rename from images/objc-hashtable-nsarray-instrument.png rename to contents/images/objc-hashtable-nsarray-instrument.png diff --git a/images/objc-initialize-breakpoint-lookup-imp-or-forward.png b/contents/images/objc-initialize-breakpoint-lookup-imp-or-forward.png similarity index 100% rename from images/objc-initialize-breakpoint-lookup-imp-or-forward.png rename to contents/images/objc-initialize-breakpoint-lookup-imp-or-forward.png diff --git a/images/objc-initialize-breakpoint.png b/contents/images/objc-initialize-breakpoint.png similarity index 100% rename from images/objc-initialize-breakpoint.png rename to contents/images/objc-initialize-breakpoint.png diff --git a/images/objc-initialize-class_rw_t_-bits-flag.png b/contents/images/objc-initialize-class_rw_t_-bits-flag.png similarity index 100% rename from images/objc-initialize-class_rw_t_-bits-flag.png rename to contents/images/objc-initialize-class_rw_t_-bits-flag.png diff --git a/images/objc-initialize-print-initialize.png b/contents/images/objc-initialize-print-initialize.png similarity index 100% rename from images/objc-initialize-print-initialize.png rename to contents/images/objc-initialize-print-initialize.png diff --git a/images/objc-initialize-print-nothing.png b/contents/images/objc-initialize-print-nothing.png similarity index 100% rename from images/objc-initialize-print-nothing.png rename to contents/images/objc-initialize-print-nothing.png diff --git a/images/objc-initialize-print-selector.png b/contents/images/objc-initialize-print-selector.png similarity index 100% rename from images/objc-initialize-print-selector.png rename to contents/images/objc-initialize-print-selector.png diff --git a/images/objc-isa-class-diagram.png b/contents/images/objc-isa-class-diagram.png similarity index 100% rename from images/objc-isa-class-diagram.png rename to contents/images/objc-isa-class-diagram.png diff --git a/images/objc-isa-class-object.png b/contents/images/objc-isa-class-object.png similarity index 100% rename from images/objc-isa-class-object.png rename to contents/images/objc-isa-class-object.png diff --git a/images/objc-isa-class-pointer.png b/contents/images/objc-isa-class-pointer.png similarity index 100% rename from images/objc-isa-class-pointer.png rename to contents/images/objc-isa-class-pointer.png diff --git a/images/objc-isa-isat-bits-has-css-dtor.png b/contents/images/objc-isa-isat-bits-has-css-dtor.png similarity index 100% rename from images/objc-isa-isat-bits-has-css-dtor.png rename to contents/images/objc-isa-isat-bits-has-css-dtor.png diff --git a/images/objc-isa-isat-bits.png b/contents/images/objc-isa-isat-bits.png similarity index 100% rename from images/objc-isa-isat-bits.png rename to contents/images/objc-isa-isat-bits.png diff --git a/images/objc-isa-isat-class-highlight-bits.png b/contents/images/objc-isa-isat-class-highlight-bits.png similarity index 100% rename from images/objc-isa-isat-class-highlight-bits.png rename to contents/images/objc-isa-isat-class-highlight-bits.png diff --git a/images/objc-isa-isat.png b/contents/images/objc-isa-isat.png similarity index 100% rename from images/objc-isa-isat.png rename to contents/images/objc-isa-isat.png diff --git a/images/objc-isa-meta-class.png b/contents/images/objc-isa-meta-class.png similarity index 100% rename from images/objc-isa-meta-class.png rename to contents/images/objc-isa-meta-class.png diff --git a/images/objc-isa-print-class-object.png b/contents/images/objc-isa-print-class-object.png similarity index 100% rename from images/objc-isa-print-class-object.png rename to contents/images/objc-isa-print-class-object.png diff --git a/images/objc-isa-print-cls.png b/contents/images/objc-isa-print-cls.png similarity index 100% rename from images/objc-isa-print-cls.png rename to contents/images/objc-isa-print-cls.png diff --git a/images/objc-isa-print-object.png b/contents/images/objc-isa-print-object.png similarity index 100% rename from images/objc-isa-print-object.png rename to contents/images/objc-isa-print-object.png diff --git a/images/objc-load-break-after-add-breakpoint.png b/contents/images/objc-load-break-after-add-breakpoint.png similarity index 100% rename from images/objc-load-break-after-add-breakpoint.png rename to contents/images/objc-load-break-after-add-breakpoint.png diff --git a/images/objc-load-diagram.png b/contents/images/objc-load-diagram.png similarity index 100% rename from images/objc-load-diagram.png rename to contents/images/objc-load-diagram.png diff --git a/images/objc-load-image-binary.png b/contents/images/objc-load-image-binary.png similarity index 100% rename from images/objc-load-image-binary.png rename to contents/images/objc-load-image-binary.png diff --git a/images/objc-load-print-image-info.png b/contents/images/objc-load-print-image-info.png similarity index 100% rename from images/objc-load-print-image-info.png rename to contents/images/objc-load-print-image-info.png diff --git a/images/objc-load-print-load.png b/contents/images/objc-load-print-load.png similarity index 100% rename from images/objc-load-print-load.png rename to contents/images/objc-load-print-load.png diff --git a/images/objc-load-producer-consumer-diagram.png b/contents/images/objc-load-producer-consumer-diagram.png similarity index 100% rename from images/objc-load-producer-consumer-diagram.png rename to contents/images/objc-load-producer-consumer-diagram.png diff --git a/images/objc-load-symbolic-breakpoint.png b/contents/images/objc-load-symbolic-breakpoint.png similarity index 100% rename from images/objc-load-symbolic-breakpoint.png rename to contents/images/objc-load-symbolic-breakpoint.png diff --git a/images/objc-message-add-imp-to-cache.png b/contents/images/objc-message-add-imp-to-cache.png similarity index 100% rename from images/objc-message-add-imp-to-cache.png rename to contents/images/objc-message-add-imp-to-cache.png diff --git a/images/objc-message-after-flush-cache-trap-in-lookup-again.png b/contents/images/objc-message-after-flush-cache-trap-in-lookup-again.png similarity index 100% rename from images/objc-message-after-flush-cache-trap-in-lookup-again.png rename to contents/images/objc-message-after-flush-cache-trap-in-lookup-again.png diff --git a/images/objc-message-after-flush-cache.png b/contents/images/objc-message-after-flush-cache.png similarity index 100% rename from images/objc-message-after-flush-cache.png rename to contents/images/objc-message-after-flush-cache.png diff --git a/images/objc-message-before-flush-cache.png b/contents/images/objc-message-before-flush-cache.png similarity index 100% rename from images/objc-message-before-flush-cache.png rename to contents/images/objc-message-before-flush-cache.png diff --git a/images/objc-message-cache-struct.png b/contents/images/objc-message-cache-struct.png similarity index 100% rename from images/objc-message-cache-struct.png rename to contents/images/objc-message-cache-struct.png diff --git a/images/objc-message-core.png b/contents/images/objc-message-core.png similarity index 100% rename from images/objc-message-core.png rename to contents/images/objc-message-core.png diff --git a/images/objc-message-find-selector-before-init.png b/contents/images/objc-message-find-selector-before-init.png similarity index 100% rename from images/objc-message-find-selector-before-init.png rename to contents/images/objc-message-find-selector-before-init.png diff --git a/images/objc-message-first-call-hello.png b/contents/images/objc-message-first-call-hello.png similarity index 100% rename from images/objc-message-first-call-hello.png rename to contents/images/objc-message-first-call-hello.png diff --git a/images/objc-message-objc-msgSend-with-cache.gif b/contents/images/objc-message-objc-msgSend-with-cache.gif similarity index 100% rename from images/objc-message-objc-msgSend-with-cache.gif rename to contents/images/objc-message-objc-msgSend-with-cache.gif diff --git a/images/objc-message-run-after-add-cache.png b/contents/images/objc-message-run-after-add-cache.png similarity index 100% rename from images/objc-message-run-after-add-cache.png rename to contents/images/objc-message-run-after-add-cache.png diff --git a/images/objc-message-selector-undefined.png b/contents/images/objc-message-selector-undefined.png similarity index 100% rename from images/objc-message-selector-undefined.png rename to contents/images/objc-message-selector-undefined.png diff --git a/images/objc-message-selector.png b/contents/images/objc-message-selector.png similarity index 100% rename from images/objc-message-selector.png rename to contents/images/objc-message-selector.png diff --git a/images/objc-message-step-in-cache-getimp.png b/contents/images/objc-message-step-in-cache-getimp.png similarity index 100% rename from images/objc-message-step-in-cache-getimp.png rename to contents/images/objc-message-step-in-cache-getimp.png diff --git a/images/objc-message-wrong-step-in.gif b/contents/images/objc-message-wrong-step-in.gif similarity index 100% rename from images/objc-message-wrong-step-in.gif rename to contents/images/objc-message-wrong-step-in.gif diff --git a/images/objc-message-youtube-preview.jpg b/contents/images/objc-message-youtube-preview.jpg similarity index 100% rename from images/objc-message-youtube-preview.jpg rename to contents/images/objc-message-youtube-preview.jpg diff --git a/images/objc-method-after-compile.png b/contents/images/objc-method-after-compile.png similarity index 100% rename from images/objc-method-after-compile.png rename to contents/images/objc-method-after-compile.png diff --git a/images/objc-method-after-methodizeClass.png b/contents/images/objc-method-after-methodizeClass.png similarity index 100% rename from images/objc-method-after-methodizeClass.png rename to contents/images/objc-method-after-methodizeClass.png diff --git a/images/objc-method-after-realize-breakpoint.png b/contents/images/objc-method-after-realize-breakpoint.png similarity index 100% rename from images/objc-method-after-realize-breakpoint.png rename to contents/images/objc-method-after-realize-breakpoint.png diff --git a/images/objc-method-after-realize-class.png b/contents/images/objc-method-after-realize-class.png similarity index 100% rename from images/objc-method-after-realize-class.png rename to contents/images/objc-method-after-realize-class.png diff --git a/images/objc-method-before-realize.png b/contents/images/objc-method-before-realize.png similarity index 100% rename from images/objc-method-before-realize.png rename to contents/images/objc-method-before-realize.png diff --git a/images/objc-method-breakpoint-before-set-rw.png b/contents/images/objc-method-breakpoint-before-set-rw.png similarity index 100% rename from images/objc-method-breakpoint-before-set-rw.png rename to contents/images/objc-method-breakpoint-before-set-rw.png diff --git a/images/objc-method-class-data-bits-t.png b/contents/images/objc-method-class-data-bits-t.png similarity index 100% rename from images/objc-method-class-data-bits-t.png rename to contents/images/objc-method-class-data-bits-t.png diff --git a/images/objc-method-class.png b/contents/images/objc-method-class.png similarity index 100% rename from images/objc-method-class.png rename to contents/images/objc-method-class.png diff --git a/images/objc-method-class_data_bits_t.png b/contents/images/objc-method-class_data_bits_t.png similarity index 100% rename from images/objc-method-class_data_bits_t.png rename to contents/images/objc-method-class_data_bits_t.png diff --git a/images/objc-method-compile-class.png b/contents/images/objc-method-compile-class.png similarity index 100% rename from images/objc-method-compile-class.png rename to contents/images/objc-method-compile-class.png diff --git a/images/objc-method-lldb-breakpoint.png b/contents/images/objc-method-lldb-breakpoint.png similarity index 100% rename from images/objc-method-lldb-breakpoint.png rename to contents/images/objc-method-lldb-breakpoint.png diff --git a/images/objc-method-lldb-print-before-realize.png b/contents/images/objc-method-lldb-print-before-realize.png similarity index 100% rename from images/objc-method-lldb-print-before-realize.png rename to contents/images/objc-method-lldb-print-before-realize.png diff --git a/images/objc-method-lldb-print-method-list.png b/contents/images/objc-method-lldb-print-method-list.png similarity index 100% rename from images/objc-method-lldb-print-method-list.png rename to contents/images/objc-method-lldb-print-method-list.png diff --git a/images/objc-method-print-class-struct-after-realize.png b/contents/images/objc-method-print-class-struct-after-realize.png similarity index 100% rename from images/objc-method-print-class-struct-after-realize.png rename to contents/images/objc-method-print-class-struct-after-realize.png diff --git a/images/objc-method-target.png b/contents/images/objc-method-target.png similarity index 100% rename from images/objc-method-target.png rename to contents/images/objc-method-target.png diff --git a/images/objc-rr-isa-struct.png b/contents/images/objc-rr-isa-struct.png similarity index 100% rename from images/objc-rr-isa-struct.png rename to contents/images/objc-rr-isa-struct.png diff --git "a/libextobjc/\345\246\202\344\275\225\345\234\250 Objective-C \347\232\204\347\216\257\345\242\203\344\270\213\345\256\236\347\216\260 defer.md" "b/contents/libextobjc/\345\246\202\344\275\225\345\234\250 Objective-C \347\232\204\347\216\257\345\242\203\344\270\213\345\256\236\347\216\260 defer.md" similarity index 100% rename from "libextobjc/\345\246\202\344\275\225\345\234\250 Objective-C \347\232\204\347\216\257\345\242\203\344\270\213\345\256\236\347\216\260 defer.md" rename to "contents/libextobjc/\345\246\202\344\275\225\345\234\250 Objective-C \347\232\204\347\216\257\345\242\203\344\270\213\345\256\236\347\216\260 defer.md" diff --git a/contents/objc/README.md b/contents/objc/README.md new file mode 100644 index 0000000..cbc0df4 --- /dev/null +++ b/contents/objc/README.md @@ -0,0 +1,15 @@ +# objc 源代码阅读 + +当前文件夹下的 objc-runtime 工程,是我在阅读 objc 源代码时所使用的版本,你可以 clone 整个仓库来进行调试,原工程地址为 [objc-runtime](https://github.com/RetVal/objc-runtime)。 + + ++ ObjC 源代码 + + [从 NSObject 的初始化了解 isa](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/从%20NSObject%20的初始化了解%20isa.md) + + [深入解析 ObjC 中方法的结构](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/深入解析%20ObjC%20中方法的结构.md) + + [从源代码看 ObjC 中消息的发送](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/从源代码看%20ObjC%20中消息的发送.md) + + [你真的了解 load 方法么?](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/你真的了解%20load%20方法么?.md) + + [懒惰的 initialize](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/懒惰的%20initialize%20方法.md) + + [自动释放池的前世今生](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/自动释放池的前世今生.md) + + [黑箱中的 retain 和 release](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/黑箱中的%20retain%20和%20release.md) + + diff --git "a/objc/\344\270\212\345\217\244\346\227\266\344\273\243 Objective-C \344\270\255\345\223\210\345\270\214\350\241\250\347\232\204\345\256\236\347\216\260.md" "b/contents/objc/\344\270\212\345\217\244\346\227\266\344\273\243 Objective-C \344\270\255\345\223\210\345\270\214\350\241\250\347\232\204\345\256\236\347\216\260.md" similarity index 99% rename from "objc/\344\270\212\345\217\244\346\227\266\344\273\243 Objective-C \344\270\255\345\223\210\345\270\214\350\241\250\347\232\204\345\256\236\347\216\260.md" rename to "contents/objc/\344\270\212\345\217\244\346\227\266\344\273\243 Objective-C \344\270\255\345\223\210\345\270\214\350\241\250\347\232\204\345\256\236\347\216\260.md" index aa30d9d..9389b9d 100644 --- "a/objc/\344\270\212\345\217\244\346\227\266\344\273\243 Objective-C \344\270\255\345\223\210\345\270\214\350\241\250\347\232\204\345\256\236\347\216\260.md" +++ "b/contents/objc/\344\270\212\345\217\244\346\227\266\344\273\243 Objective-C \344\270\255\345\223\210\345\270\214\350\241\250\347\232\204\345\256\236\347\216\260.md" @@ -690,7 +690,7 @@ NXHashTable *NXCreateHashTable (NXHashTablePrototype prototype, unsigned capacit ![objc-hashtable-nsarray-instrument](../images/objc-hashtable-nsarray-instrument.png) -导致这一现象的原始可能是:在将原数组中的内容移入新数组时,**临时变量申请了大量的内存控件**。 +导致这一现象的原始可能是:在将原数组中的内容移入新数组时,**临时变量申请了大量的内存空间**。 > 在之后关于 CoreFoundation 源代码分析的文中会介绍它们是怎么实现的。 @@ -702,7 +702,7 @@ NXHashTable *NXCreateHashTable (NXHashTablePrototype prototype, unsigned capacit static NXHashTable *realized_class_hash = nil; ``` -我么可以使用 `objc_copyClassList` 获取类的数组: +我们可以使用 `objc_copyClassList` 获取类的数组: ```objectivec Class * diff --git "a/objc/\344\273\216 NSObject \347\232\204\345\210\235\345\247\213\345\214\226\344\272\206\350\247\243 isa.md" "b/contents/objc/\344\273\216 NSObject \347\232\204\345\210\235\345\247\213\345\214\226\344\272\206\350\247\243 isa.md" similarity index 98% rename from "objc/\344\273\216 NSObject \347\232\204\345\210\235\345\247\213\345\214\226\344\272\206\350\247\243 isa.md" rename to "contents/objc/\344\273\216 NSObject \347\232\204\345\210\235\345\247\213\345\214\226\344\272\206\350\247\243 isa.md" index d06f047..06b3e2e 100644 --- "a/objc/\344\273\216 NSObject \347\232\204\345\210\235\345\247\213\345\214\226\344\272\206\350\247\243 isa.md" +++ "b/contents/objc/\344\273\216 NSObject \347\232\204\345\210\235\345\247\213\345\214\226\344\272\206\350\247\243 isa.md" @@ -12,7 +12,6 @@ struct objc_object { 当 ObjC 为一个对象分配内存,初始化实例变量后,在这些对象的实例变量的结构体中的第一个就是 `isa`。 -<p align='center'> ![objc-isa-class-object](../images/objc-isa-class-object.png) > 所有继承自 `NSObject` 的类实例化后的对象都会包含一个类型为 `isa_t` 的结构体。 @@ -40,14 +39,12 @@ struct objc_class : objc_object { 当**实例方法**被调用时,它要通过自己持有的 `isa` 来查找对应的类,然后在这里的 `class_data_bits_t` 结构体中查找对应方法的实现。同时,每一个 `objc_class` 也有一个**指向自己的父类的指针** `super_class` 用来查找继承的方法。 -> 关于如何在 `class_data_bits_t` 中查找对应方法会在之后的文章中讲到。这里只需要知道,它会在这个结构体中查找到对应方法的实现就可以了。[深入解析 ObjC 中方法的结构](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/深入解析%20ObjC%20中方法的结构.md) +> 关于如何在 `class_data_bits_t` 中查找对应方法会在之后的文章中讲到。这里只需要知道,它会在这个结构体中查找到对应方法的实现就可以了。[深入解析 ObjC 中方法的结构](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/深入解析%20ObjC%20中方法的结构.md) -<p align='center'> ![objc-isa-class-pointer](../images/objc-isa-class-pointer.png) 但是,这样就有一个问题,类方法的实现又是如何查找并且调用的呢?这时,就需要引入*元类*来保证无论是类还是对象都能**通过相同的机制查找方法的实现**。 -<p align='center'> ![objc-isa-meta-class](../images/objc-isa-meta-class.png) @@ -58,7 +55,6 @@ struct objc_class : objc_object { 下面这张图介绍了对象,类与元类之间的关系,笔者认为已经觉得足够清晰了,所以不在赘述。 -<p align='center'> ![](../images/objc-isa-class-diagram.png) > 图片来自 [objc_explain_Classes_and_metaclasses](http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html) @@ -111,7 +107,6 @@ union isa_t { `isa_t` 是一个 `union` 类型的结构体,对 `union` 不熟悉的读者可以看这个 stackoverflow 上的[回答](http://stackoverflow.com/questions/252552/why-do-we-need-c-unions). 也就是说其中的 `isa_t`、`cls`、 `bits` 还有结构体共用同一块地址空间。而 `isa` 总共会占据 64 位的内存空间(决定于其中的结构体) -<p align='center'> ![objc-isa-isat](../images/objc-isa-isat.png) ```objectivec @@ -173,7 +168,6 @@ inline void objc_object::initIsa(Class cls, bool indexed, bool hasCxxDtor) 我们可以把它转换成二进制的数据,然后看一下哪些属性对应的位被这行代码初始化了(标记为红色): -<p align='center'> ![objc-isa-isat-bits](../images/objc-isa-isat-bits.png) 从图中了解到,在使用 `ISA_MAGIC_VALUE` 设置 `isa_t` 结构体之后,实际上只是设置了 `indexed` 以及 `magic` 这两部分的值。 @@ -224,7 +218,6 @@ inline void objc_object::initIsa(Class cls, bool indexed, bool hasCxxDtor) isa.has_cxx_dtor = hasCxxDtor; ``` -<p align='center'> ![objc-isa-isat-bits-has-css-dto](../images/objc-isa-isat-bits-has-css-dtor.png) ### `shiftcls` @@ -242,7 +235,6 @@ isa.shiftcls = (uintptr_t)cls >> 3; 而 ObjC 中的类指针的地址后三位也为 0,在 `_class_createInstanceFromZone` 方法中打印了调用这个方法传入的类指针: -<p align='center'> ![objc-isa-print-cls](../images/objc-isa-print-cls.png) 可以看到,这里打印出来的**所有类指针十六进制地址的最后一位都为 8 或者 0**。也就是说,类指针的后三位都为 0,所以,我们在上面存储 `Class` 指针时右移三位是没有问题的。 @@ -253,7 +245,6 @@ isa.shiftcls = (uintptr_t)cls >> 3; 如果再尝试打印对象指针的话,会发现所有对象内存地址的**后四位**都是 0,说明 ObjC 在初始化内存时是以 16 个字节对齐的, 分配的内存地址后四位都是 0。 -<p align='center'> ![objc-isa-print-object](../images/objc-isa-print-object.png) > 使用整个指针大小的内存来存储 `isa` 指针有些浪费,尤其在 64 位的 CPU 上。在 `ARM64` 运行的 iOS 只使用了 33 位作为指针(与结构体中的 33 位无关,Mac OS 上为 47 位),而剩下的 31 位用于其它目的。类的指针也同样根据字节对齐了,每一个类指针的地址都能够被 8 整除,也就是使最后 3 bits 为 0,为 `isa` 留下 34 位用于性能的优化。 @@ -263,7 +254,6 @@ isa.shiftcls = (uintptr_t)cls >> 3; 我尝试运行了下面的代码将 `NSObject` 的类指针和对象的 `isa` 打印出来,具体分析一下 -<p align='center'> ![objc-isa-print-class-object](../images/objc-isa-print-class-object.png) ``` diff --git "a/objc/\344\273\216\346\272\220\344\273\243\347\240\201\347\234\213 ObjC \344\270\255\346\266\210\346\201\257\347\232\204\345\217\221\351\200\201.md" "b/contents/objc/\344\273\216\346\272\220\344\273\243\347\240\201\347\234\213 ObjC \344\270\255\346\266\210\346\201\257\347\232\204\345\217\221\351\200\201.md" similarity index 96% rename from "objc/\344\273\216\346\272\220\344\273\243\347\240\201\347\234\213 ObjC \344\270\255\346\266\210\346\201\257\347\232\204\345\217\221\351\200\201.md" rename to "contents/objc/\344\273\216\346\272\220\344\273\243\347\240\201\347\234\213 ObjC \344\270\255\346\266\210\346\201\257\347\232\204\345\217\221\351\200\201.md" index 7af5783..24f8734 100644 --- "a/objc/\344\273\216\346\272\220\344\273\243\347\240\201\347\234\213 ObjC \344\270\255\346\266\210\346\201\257\347\232\204\345\217\221\351\200\201.md" +++ "b/contents/objc/\344\273\216\346\272\220\344\273\243\347\240\201\347\234\213 ObjC \344\270\255\346\266\210\346\201\257\347\232\204\345\217\221\351\200\201.md" @@ -10,10 +10,10 @@ 2. `[receiver message]` 会被翻译为 `objc_msgSend(receiver, @selector(message))` 3. 在消息的响应链中**可能**会调用 `- resolveInstanceMethod:` `- forwardInvocation:` 等方法 4. 关于选择子 SEL 的知识 - + > 如果对于上述的知识不够了解,可以看一下这篇文章 [Objective-C Runtime](http://tech.glowing.com/cn/objective-c-runtime/),但是其中关于 `objc_class` 的结构体的代码已经过时了,不过不影响阅读以及理解。 -5. 方法在内存中存储的位置,[深入解析 ObjC 中方法的结构](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/深入解析%20ObjC%20中方法的结构.md)(可选) +5. 方法在内存中存储的位置,[深入解析 ObjC 中方法的结构](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/深入解析%20ObjC%20中方法的结构.md)(可选) > 文章中不会刻意区别方法和函数、消息传递和方法调用之间的区别。 @@ -26,7 +26,6 @@ 由于这个系列的文章都是对 Objective-C 源代码的分析,所以会**从 Objective-C 源代码中分析并合理地推测一些关于消息传递的问题**。 -<p align='center'> ![objc-message-core](../images/objc-message-core.png) ## 关于 @selector() 你需要知道的 @@ -87,7 +86,6 @@ int main(int argc, const char * argv[]) { 在主函数任意位置打一个断点, 比如 `-> [object hello];` 这里,然后在 lldb 中输入: -<p align='center'> ![objc-message-selecto](../images/objc-message-selector.png) 这里面我们打印了两个选择子的地址` @selector(hello)` 以及 `@selector(undefined_hello_method)`,需要注意的是: @@ -96,7 +94,6 @@ int main(int argc, const char * argv[]) { 如果我们修改程序的代码: -<p align='center'> ![objc-message-selector-undefined](../images/objc-message-selector-undefined.png) 在这里,由于我们在代码中显示地写出了 `@selector(undefined_hello_method)`,所以在 lldb 中再次打印这个 `sel` 内存地址跟之前相比有了很大的改变。 @@ -111,7 +108,6 @@ int main(int argc, const char * argv[]) { 在运行时初始化之前,打印 `hello` 选择子的的内存地址: -<p align='center'> ![objc-message-find-selector-before-init](../images/objc-message-find-selector-before-init.png) ## message.h 文件 @@ -119,10 +115,10 @@ int main(int argc, const char * argv[]) { Objective-C 中 `objc_msgSend` 的实现并没有开源,它只存在于 `message.h` 这个头文件中。 ```objectivec -/** +/** * @note When it encounters a method call, the compiler generates a call to one of the * functions \c objc_msgSend, \c objc_msgSend_stret, \c objc_msgSendSuper, or \c objc_msgSendSuper_stret. - * Messages sent to an object’s superclass (using the \c super keyword) are sent using \c objc_msgSendSuper; + * Messages sent to an object’s superclass (using the \c super keyword) are sent using \c objc_msgSendSuper; * other messages are sent using \c objc_msgSend. Methods that have data structures as return values * are sent using \c objc_msgSendSuper_stret and \c objc_msgSend_stret. */ @@ -177,7 +173,6 @@ int main(int argc, const char * argv[]) { 在调用 `hello` 方法的这一行打一个断点,当我们尝试进入(Step in)这个方法只会直接跳入这个方法的实现,而不会进入 `objc_msgSend`: -<p align='center'> ![objc-message-wrong-step-in](../images/objc-message-wrong-step-in.gif) 因为 `objc_msgSend` 是一个私有方法,我们没有办法进入它的实现,但是,我们却可以在 `objc_msgSend` 的调用栈中“截下”这个函数调用的过程。 @@ -188,7 +183,6 @@ int main(int argc, const char * argv[]) { 在 `objc-runtime-new.mm` 文件中有一个函数 `lookUpImpOrForward`,这个函数的作用就是查找方法的实现,于是运行程序,在运行到 `hello` 这一行时,激活 `lookUpImpOrForward` 函数中的断点。 -<p align='center'> <a href="https://youtu.be/bCdjdI4VhwQ" target="_blank"><img src='../images/objc-message-youtube-preview.jpg'></a> > 由于转成 gif 实在是太大了,笔者试着用各种方法生成动图,然而效果也不是很理想,只能贴一个 Youtube 的视频链接,不过对于能够翻墙的开发者们,应该也不是什么问题吧(手动微笑) @@ -203,7 +197,6 @@ int main(int argc, const char * argv[]) { 在 `-> [object hello]` 这里增加一个断点,**当程序运行到这一行时**,再向 `lookUpImpOrForward` 函数的第一行添加断点,确保是捕获 `@selector(hello)` 的调用栈,而不是调用其它选择子的调用栈。 -<p align='center'> ![objc-message-first-call-hello](../images/objc-message-first-call-hello.png) 由图中的变量区域可以了解,传入的选择子为 `"hello"`,对应的类是 `XXObject`。所以我们可以确信这就是当调用 `hello` 方法时执行的函数。在 Xcode 左侧能看到方法的调用栈: @@ -221,7 +214,7 @@ int main(int argc, const char * argv[]) { ```objectivec IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls) { - return lookUpImpOrForward(cls, sel, obj, + return lookUpImpOrForward(cls, sel, obj, YES/*initialize*/, NO/*cache*/, YES/*resolver*/); } ``` @@ -291,12 +284,10 @@ imp = cache_getImp(cls, sel); if (imp) goto done; ``` -<p align='center'> ![objc-message-cache-struct](../images/objc-message-cache-struct.png) 不过 `cache_getImp` 的实现目测是不开源的,同时也是汇编写的,在我们尝试 step in 的时候进入了如下的汇编代码。 -<p align='center'> ![objc-message-step-in-cache-getimp](../images/objc-message-step-in-cache-getimp.png) 它会进入一个 `CacheLookup` 的标签,获取实现,使用汇编的原因还是因为要加速整个实现查找的过程,其原理推测是在类的 `cache` 中寻找对应的实现,只是做了一些性能上的优化。 @@ -316,8 +307,8 @@ if (meth) { ```objectivec static method_t *getMethodNoSuper_nolock(Class cls, SEL sel) { - for (auto mlists = cls->data()->methods.beginLists(), - end = cls->data()->methods.endLists(); + for (auto mlists = cls->data()->methods.beginLists(), + end = cls->data()->methods.endLists(); mlists != end; ++mlists) { @@ -336,7 +327,7 @@ static method_t *search_method_list(const method_list_t *mlist, SEL sel) { int methodListIsFixedUp = mlist->isFixedUp(); int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t); - + if (__builtin_expect(methodListIsFixedUp && methodListHasExpectedSize, 1)) { return findMethodInSortedMethodList(sel, mlist); } else { @@ -434,11 +425,11 @@ void _class_resolveMethod(Class cls, SEL sel, id inst) { if (! cls->isMetaClass()) { _class_resolveInstanceMethod(cls, sel, inst); - } + } else { _class_resolveClassMethod(cls, sel, inst); - if (!lookUpImpOrNil(cls, sel, inst, - NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) + if (!lookUpImpOrNil(cls, sel, inst, + NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) { _class_resolveInstanceMethod(cls, sel, inst); } @@ -450,7 +441,7 @@ void _class_resolveMethod(Class cls, SEL sel, id inst) ```objectivec static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst) { - if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls, + if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls, NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) { // 没有找到 resolveInstanceMethod: 方法,直接返回。 return; @@ -460,7 +451,7 @@ static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst) { bool resolved = msg(cls, SEL_resolveInstanceMethod, sel); // 缓存结果,以防止下次在调用 resolveInstanceMethod: 方法影响性能。 - IMP imp = lookUpImpOrNil(cls, sel, inst, + IMP imp = lookUpImpOrNil(cls, sel, inst, NO/*initialize*/, YES/*cache*/, NO/*resolver*/); } ``` @@ -486,7 +477,6 @@ cache_fill(cls, sel, imp, inst); 这样就结束了整个方法第一次的调用过程,缓存没有命中,但是在当前类的方法列表中找到了 `hello` 方法的实现,调用了该方法。 -<p align='center'> ![objc-message-first-call-hello](../images/objc-message-first-call-hello.png) @@ -507,7 +497,6 @@ int main(int argc, const char * argv[]) { 然后在第二次调用 `hello` 方法时,加一个断点: -<p align='center'> ![objc-message-objc-msgSend-with-cache](../images/objc-message-objc-msgSend-with-cache.gif) `objc_msgSend` 并没有走 `lookupImpOrForward` 这个方法,而是直接结束,打印了另一个 `hello` 字符串。 @@ -518,7 +507,6 @@ int main(int argc, const char * argv[]) { 好,现在重新运行程序至第二个 `hello` 方法调用之前: -<p align='center'> ![objc-message-before-flush-cache](../images/objc-message-before-flush-cache.png) 打印缓存中 bucket 的内容: @@ -568,12 +556,10 @@ int main(int argc, const char * argv[]) { } ``` -<p align='center'> ![objc-message-after-flush-cache](../images/objc-message-after-flush-cache.png) 这样 `XXObject` 中就不存在 `hello` 方法对应实现的缓存了。然后继续运行程序: -<p align='center'> ![objc-message-after-flush-cache-trap-in-lookup-again](../images/objc-message-after-flush-cache-trap-in-lookup-again.png) 虽然第二次调用 `hello` 方法,但是因为我们清除了 `hello` 的缓存,所以,会再次进入 `lookupImpOrForward` 方法。 @@ -604,12 +590,10 @@ int main(int argc, const char * argv[]) { 在第一个 `hello` 方法调用之前将实现加入缓存: -<p align='center'> ![objc-message-add-imp-to-cache](../images/objc-message-add-imp-to-cache.png) 然后继续运行代码: -<p align='center'> ![objc-message-run-after-add-cache](../images/objc-message-run-after-add-cache.png) 可以看到,我们虽然没有改变 `hello` 方法的实现,但是在 **objc_msgSend** 的消息发送链路中,使用错误的缓存实现 `cached_imp` 拦截了实现的查找,打印出了 `Cached Hello`。 @@ -625,7 +609,7 @@ int main(int argc, const char * argv[]) { 这篇文章与其说是讲 ObjC 中的消息发送的过程,不如说是讲方法的实现是如何查找的。 Objective-C 中实现查找的路径还是比较符合直觉的: - + 1. 缓存命中 2. 查找当前类的缓存及方法 3. 查找父类的缓存及方法 @@ -636,10 +620,8 @@ Objective-C 中实现查找的路径还是比较符合直觉的: ## 参考资料 -+ [深入解析 ObjC 中方法的结构](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/深入解析%20ObjC%20中方法的结构.md) ++ [深入解析 ObjC 中方法的结构](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/深入解析%20ObjC%20中方法的结构.md) + [Objective-C Runtime](http://tech.glowing.com/cn/objective-c-runtime/) + [Let's Build objc_msgSend](https://www.mikeash.com/pyblog/friday-qa-2012-11-16-lets-build-objc_msgsend.html) Follow: [@Draveness](https://github.com/Draveness) - - diff --git "a/objc/\344\275\240\347\234\237\347\232\204\344\272\206\350\247\243 load \346\226\271\346\263\225\344\271\210\357\274\237.md" "b/contents/objc/\344\275\240\347\234\237\347\232\204\344\272\206\350\247\243 load \346\226\271\346\263\225\344\271\210\357\274\237.md" similarity index 96% rename from "objc/\344\275\240\347\234\237\347\232\204\344\272\206\350\247\243 load \346\226\271\346\263\225\344\271\210\357\274\237.md" rename to "contents/objc/\344\275\240\347\234\237\347\232\204\344\272\206\350\247\243 load \346\226\271\346\263\225\344\271\210\357\274\237.md" index a8135eb..60dd61e 100644 --- "a/objc/\344\275\240\347\234\237\347\232\204\344\272\206\350\247\243 load \346\226\271\346\263\225\344\271\210\357\274\237.md" +++ "b/contents/objc/\344\275\240\347\234\237\347\232\204\344\272\206\350\247\243 load \346\226\271\346\263\225\344\271\210\357\274\237.md" @@ -52,7 +52,7 @@ int main(int argc, const char * argv[]) { 代码总共只实现了一个 `XXObject` 的 `+ load` 方法,主函数中也没有任何的东西: -<p align='center'>![objc-load-print-load](../images/objc-load-print-load.png) +![objc-load-print-load](../images/objc-load-print-load.png) 虽然在主函数中什么方法都没有调用,但是运行之后,依然打印了 `XXObject load` 字符串,也就是说调用了 `+ load` 方法。 @@ -62,13 +62,13 @@ int main(int argc, const char * argv[]) { > 注意这里 `+` 和 `[` 之间没有空格 -<p align='center'>![objc-load-symbolic-breakpoint](../images/objc-load-symbolic-breakpoint.png) +![objc-load-symbolic-breakpoint](../images/objc-load-symbolic-breakpoint.png) > 为什么要加一个符号断点呢?因为这样看起来比较高级。 重新运行程序。这时,代码会停在 `NSLog(@"XXObject load");` 这一行的实现上: -<p align='center'>![objc-load-break-after-add-breakpoint](../images/objc-load-break-after-add-breakpoint.png) +![objc-load-break-after-add-breakpoint](../images/objc-load-break-after-add-breakpoint.png) 左侧的调用栈很清楚的告诉我们,哪些方法被调用了: @@ -128,7 +128,7 @@ load_images(enum dyld_image_states state, uint32_t infoCount, 这里就会遇到一个问题:镜像到底是什么,我们用一个断点打印出所有加载的镜像: -<p align='center'>![objc-load-print-image-info](../images/objc-load-print-image-info.png) +![objc-load-print-image-info](../images/objc-load-print-image-info.png) 从控制台输出的结果大概就是这样的,我们可以看到镜像并不是一个 Objective-C 的代码文件,它应该是一个 target 的编译产物。 @@ -160,7 +160,7 @@ load_images(enum dyld_image_states state, uint32_t infoCount, 但是如果进入最下面的这个目录,会发现它是一个**可执行文件**,它的运行结果与 Xcode 中的运行结果相同: -<p align='center'>![objc-load-image-binary](../images/objc-load-image-binary.png) +![objc-load-image-binary](../images/objc-load-image-binary.png) ### 准备 + load 方法 @@ -267,7 +267,7 @@ void call_load_methods(void) 方法的调用流程大概是这样的: -<p align='center'>![objc-load-diagra](../images/objc-load-diagram.png) +![objc-load-diagra](../images/objc-load-diagram.png) 其中 `call_class_loads` 会从一个待加载的类列表 `loadable_classes` 中寻找对应的类,然后找到 `@selector(load)` 的实现并执行。 @@ -310,7 +310,7 @@ ObjC 对于加载的管理,主要使用了两个列表,分别是 `loadable_c 方法的调用过程也分为两个部分,准备 `load` 方法和调用 `load` 方法,我更觉得这两个部分比较像生产者与消费者: -<p align='center'>![objc-load-producer-consumer-diagra](../images/objc-load-producer-consumer-diagram.png) +![objc-load-producer-consumer-diagra](../images/objc-load-producer-consumer-diagram.png) `add_class_to_loadable_list` 方法负责将类加入 `loadable_classes` 集合,而 `call_class_loads` 负责消费集合中的元素。 diff --git "a/objc/\345\205\263\350\201\224\345\257\271\350\261\241 AssociatedObject \345\256\214\345\205\250\350\247\243\346\236\220.md" "b/contents/objc/\345\205\263\350\201\224\345\257\271\350\261\241 AssociatedObject \345\256\214\345\205\250\350\247\243\346\236\220.md" similarity index 99% rename from "objc/\345\205\263\350\201\224\345\257\271\350\261\241 AssociatedObject \345\256\214\345\205\250\350\247\243\346\236\220.md" rename to "contents/objc/\345\205\263\350\201\224\345\257\271\350\261\241 AssociatedObject \345\256\214\345\205\250\350\247\243\346\236\220.md" index cfc3acb..059cd09 100644 --- "a/objc/\345\205\263\350\201\224\345\257\271\350\261\241 AssociatedObject \345\256\214\345\205\250\350\247\243\346\236\220.md" +++ "b/contents/objc/\345\205\263\350\201\224\345\257\271\350\261\241 AssociatedObject \345\256\214\345\205\250\350\247\243\346\236\220.md" @@ -457,7 +457,7 @@ inline void objc_object::setHasAssociatedObjects() { ![objc-ao-isa-struct](../images/objc-ao-isa-struct.png) -> 如果想要了解关于 isa 的知识,可以阅读[从 NSObject 的初始化了解 isa](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/从%20NSObject%20的初始化了解%20isa.md) +> 如果想要了解关于 isa 的知识,可以阅读[从 NSObject 的初始化了解 isa](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/从%20NSObject%20的初始化了解%20isa.md) ### objc_getAssociatedObject diff --git "a/contents/objc/\345\257\271\350\261\241\346\230\257\345\246\202\344\275\225\345\210\235\345\247\213\345\214\226\347\232\204\357\274\210iOS\357\274\211.md" "b/contents/objc/\345\257\271\350\261\241\346\230\257\345\246\202\344\275\225\345\210\235\345\247\213\345\214\226\347\232\204\357\274\210iOS\357\274\211.md" new file mode 100644 index 0000000..0bb16a1 --- /dev/null +++ "b/contents/objc/\345\257\271\350\261\241\346\230\257\345\246\202\344\275\225\345\210\235\345\247\213\345\214\226\347\232\204\357\274\210iOS\357\274\211.md" @@ -0,0 +1,157 @@ +# 对象是如何初始化的(iOS) + +在之前,我们已经讨论了非常多的问题了,关于 objc 源代码系列的文章也快结束了,其实关于对象是如何初始化的这篇文章本来是我要写的第一篇文章,但是由于有很多前置内容不得不说,所以留到了这里。 + +`+ alloc` 和 `- init` 这一对我们在 iOS 开发中每天都要用到的初始化方法一直困扰着我, 于是笔者仔细研究了一下 objc 源码中 `NSObject` 如何进行初始化。 + +在具体分析对象的初始化过程之前,我想先放出结论,以免文章中的细枝末节对读者的理解有所影响;整个对象的初始化过程其实只是**为一个分配内存空间,并且初始化 isa_t 结构体的过程**。 + +## alloc 方法分析 + +先来看一下 `+ alloc` 方法的调用栈(在调用栈中省略了很多不必要的方法的调用): + +```objectivec +id _objc_rootAlloc(Class cls) +└── static id callAlloc(Class cls, bool checkNil, bool allocWithZone=false) + └── id class_createInstance(Class cls, size_t extraBytes) + └── id _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone, bool cxxConstruct, size_t *outAllocatedSize) + ├── size_t instanceSize(size_t extraBytes) + ├── void *calloc(size_t, size_t) + └── inline void objc_object::initInstanceIsa(Class cls, bool hasCxxDtor) +``` + +这个调用栈中的方法涉及了多个文件中的代码,在下面的章节中会对调用的方法逐步进行分析,如果这个调用栈让你觉得很头疼,也不是什么问题。 + +### alloc 的实现 + +```objectivec ++ (id)alloc { + return _objc_rootAlloc(self); +} +``` + +`alloc` 方法的实现真的是非常的简单, 它直接调用了另一个私有方法 `id _objc_rootAlloc(Class cls)` + +```objectivec +id _objc_rootAlloc(Class cls) { + return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/); +} +``` + +这就是上帝类 `NSObject` 对 `callAlloc` 的实现,我们省略了非常多的代码,展示了最常见的执行路径: + +```objectivec +static id callAlloc(Class cls, bool checkNil, bool allocWithZone=false) { + id obj = class_createInstance(cls, 0); + return obj; +} + +id class_createInstance(Class cls, size_t extraBytes) { + return _class_createInstanceFromZone(cls, extraBytes, nil); +} +``` + +对象初始化中最重要的操作都在 `_class_createInstanceFromZone` 方法中执行: + +```objectivec +static id _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone, bool cxxConstruct = true, size_t *outAllocatedSize = nil) { + size_t size = cls->instanceSize(extraBytes); + + id obj = (id)calloc(1, size); + if (!obj) return nil; + obj->initInstanceIsa(cls, hasCxxDtor); + + return obj; +} +``` + +### 对象的大小 + +在使用 `calloc` 为对象分配一块内存空间之前,我们要先获取对象在内存的大小: + +```objectivec +size_t instanceSize(size_t extraBytes) { + size_t size = alignedInstanceSize() + extraBytes; + if (size < 16) size = 16; + return size; +} + +uint32_t alignedInstanceSize() { + return word_align(unalignedInstanceSize()); +} + +uint32_t unalignedInstanceSize() { + assert(isRealized()); + return data()->ro->instanceSize; +} +``` + +实例大小 `instanceSize` 会存储在类的 `isa_t` 结构体中,然后经过对齐最后返回。 + +> Core Foundation 需要所有的对象的大小都必须大于或等于 16 字节。 + +在获取对象大小之后,直接调用 `calloc` 函数就可以为对象分配内存空间了。 + +### isa 的初始化 + +在对象的初始化过程中除了使用 `calloc` 来分配内存之外,还需要根据类初始化 `isa_t` 结构体: + +```objectivec +inline void objc_object::initIsa(Class cls, bool indexed, bool hasCxxDtor) { + if (!indexed) { + isa.cls = cls; + } else { + isa.bits = ISA_MAGIC_VALUE; + isa.has_cxx_dtor = hasCxxDtor; + isa.shiftcls = (uintptr_t)cls >> 3; + } +} +``` + +上面的代码只是对 `isa_t` 结构体进行初始化而已: + +```objectivec +union isa_t { + isa_t() { } + isa_t(uintptr_t value) : bits(value) { } + + Class cls; + uintptr_t bits; + + struct { + uintptr_t indexed : 1; + uintptr_t has_assoc : 1; + uintptr_t has_cxx_dtor : 1; + uintptr_t shiftcls : 44; + uintptr_t magic : 6; + uintptr_t weakly_referenced : 1; + uintptr_t deallocating : 1; + uintptr_t has_sidetable_rc : 1; + uintptr_t extra_rc : 8; + }; +}; +``` + +> 在这里并不想过多介绍关于 `isa_t` 结构体的内容,你可以看[从 NSObject 的初始化了解 isa](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/从%20NSObject%20的初始化了解%20isa.md) 来了解你想知道的关于 `isa_t` 的全部内容。 + +## init 方法 + +`NSObject` 的 `- init` 方法只是调用了 `_objc_rootInit` 并返回了当前对象: + +```objectivec +- (id)init { + return _objc_rootInit(self); +} + +id _objc_rootInit(id obj) { + return obj; +} +``` + +## 总结 + +在 iOS 中一个对象的初始化过程很符合直觉,只是分配内存空间、然后初始化 `isa_t` 结构体,其实现也并不复杂,这篇文章也是这个系列文章中较为简单并且简短的一篇。 + +> Follow: [Draveness · Github](https://github.com/Draveness) + + diff --git "a/objc/\346\207\222\346\203\260\347\232\204 initialize \346\226\271\346\263\225.md" "b/contents/objc/\346\207\222\346\203\260\347\232\204 initialize \346\226\271\346\263\225.md" similarity index 97% rename from "objc/\346\207\222\346\203\260\347\232\204 initialize \346\226\271\346\263\225.md" rename to "contents/objc/\346\207\222\346\203\260\347\232\204 initialize \346\226\271\346\263\225.md" index baa20b8..4ed7ab6 100644 --- "a/objc/\346\207\222\346\203\260\347\232\204 initialize \346\226\271\346\263\225.md" +++ "b/contents/objc/\346\207\222\346\203\260\347\232\204 initialize \346\226\271\346\263\225.md" @@ -6,7 +6,7 @@ 这篇文章可能是对 Objective-C 源代码解析系列文章中最短的一篇了,在 Objective-C 中,我们总是会同时想到 `load`、`initialize` 这两个类方法。而这两个方法也经常在一起比较: -在上一篇介绍 `load` 方法的[文章](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/你真的了解%20load%20方法么?.md)中,已经对 `load` 方法的调用时机、调用顺序进行了详细地分析,所以对于 `load` 方法,这里就不在赘述了。 +在上一篇介绍 `load` 方法的[文章](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/你真的了解%20load%20方法么?.md)中,已经对 `load` 方法的调用时机、调用顺序进行了详细地分析,所以对于 `load` 方法,这里就不在赘述了。 这篇文章会~~假设你知道:~~假设你是 iOS 开发者。 @@ -80,7 +80,7 @@ int main(int argc, const char * argv[]) { 6 start ``` -直接来看调用栈中的 `lookUpImpOrForward` 方法,`lookUpImpOrForward` 方法**只会在向对象发送消息,并且在类的缓存中没有找到消息的选择子时**才会调用,具体可以看这篇文章,[从源代码看 ObjC 中消息的发送](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/从源代码看%20ObjC%20中消息的发送.md)。 +直接来看调用栈中的 `lookUpImpOrForward` 方法,`lookUpImpOrForward` 方法**只会在向对象发送消息,并且在类的缓存中没有找到消息的选择子时**才会调用,具体可以看这篇文章,[从源代码看 ObjC 中消息的发送](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/从源代码看%20ObjC%20中消息的发送.md)。 在这里,我们知道 `lookUpImpOrForward` 方法是 `objc_msgSend` 触发的就够了。 diff --git "a/objc/\346\267\261\345\205\245\350\247\243\346\236\220 ObjC \344\270\255\346\226\271\346\263\225\347\232\204\347\273\223\346\236\204.md" "b/contents/objc/\346\267\261\345\205\245\350\247\243\346\236\220 ObjC \344\270\255\346\226\271\346\263\225\347\232\204\347\273\223\346\236\204.md" similarity index 96% rename from "objc/\346\267\261\345\205\245\350\247\243\346\236\220 ObjC \344\270\255\346\226\271\346\263\225\347\232\204\347\273\223\346\236\204.md" rename to "contents/objc/\346\267\261\345\205\245\350\247\243\346\236\220 ObjC \344\270\255\346\226\271\346\263\225\347\232\204\347\273\223\346\236\204.md" index ecf91b6..17d666a 100644 --- "a/objc/\346\267\261\345\205\245\350\247\243\346\236\220 ObjC \344\270\255\346\226\271\346\263\225\347\232\204\347\273\223\346\236\204.md" +++ "b/contents/objc/\346\267\261\345\205\245\350\247\243\346\236\220 ObjC \344\270\255\346\226\271\346\263\225\347\232\204\347\273\223\346\236\204.md" @@ -2,7 +2,7 @@ > 因为 ObjC 的 runtime 只能在 Mac OS 下才能编译,所以文章中的代码都是在 Mac OS,也就是 `x86_64` 架构下运行的,对于在 arm64 中运行的代码会特别说明。 -在上一篇分析 `isa` 的文章[从 NSObject 的初始化了解 isa](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/从%20NSObject%20的初始化了解%20isa.md) 中曾经说到过实例方法被调用时,会通过其持有 `isa` 指针寻找对应的类,然后在其中的 `class_data_bits_t` 中查找对应的方法,在这一篇文章中会介绍方法在 ObjC 中是如何存储方法的。 +在上一篇分析 `isa` 的文章[从 NSObject 的初始化了解 isa](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/从%20NSObject%20的初始化了解%20isa.md) 中曾经说到过实例方法被调用时,会通过其持有 `isa` 指针寻找对应的类,然后在其中的 `class_data_bits_t` 中查找对应的方法,在这一篇文章中会介绍方法在 ObjC 中是如何存储方法的。 这篇文章的首先会根据 ObjC 源代码来分析方法在内存中的存储结构,然后在 lldb 调试器中一步一步验证分析的正确性。 @@ -10,7 +10,6 @@ 先来了解一下 ObjC 中类的结构图: -<p align="center"> ![objc-method-class](../images/objc-method-class.png) + `isa` 是指向元类的指针,不了解元类的可以看 [Classes and Metaclasses](http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html) @@ -24,7 +23,6 @@ 下面就是 ObjC 中 `class_data_bits_t` 的结构体,其中只含有一个 64 位的 `bits` 用于存储与类有关的信息: -<p align="center"> ![objc-method-class-data-bits-t](../images/objc-method-class-data-bits-t.png) 在 `objc_class` 结构体中的注释写到 `class_data_bits_t` 相当于 `class_rw_t` 指针加上 rr/alloc 的标志。 @@ -47,7 +45,6 @@ class_rw_t* data() { 因为 `class_rw_t *` 指针只存于第 `[3, 47]` 位,所以可以使用最后三位来存储关于当前类的其他信息: -<p align="center"> ![objc-method-class_data_bits_t](../images/objc-method-class_data_bits_t.png) @@ -126,7 +123,6 @@ struct class_ro_t { **在编译期间**类的结构中的 `class_data_bits_t *data` 指向的是一个 `class_ro_t *` 指针: -<p align='center'> ![objc-method-before-realize](../images/objc-method-before-realize.png) @@ -147,7 +143,6 @@ cls->setData(rw); 下图是 `realizeClass` 方法执行过后的类所占用内存的布局,你可以与上面调用方法前的内存布局对比以下,看有哪些更改: -<p align='center'> ![objc-method-after-realize-class](../images/objc-method-after-realize-class.png) 但是,在这段代码运行之后 `class_rw_t` 中的方法,属性以及协议列表均为空。这时需要 `realizeClass` 调用 `methodizeClass` 方法来**将类自己实现的方法(包括分类)、属性和遵循的协议加载到 `methods`、 `properties` 和 `protocols` 列表中**。 @@ -181,7 +176,6 @@ cls->setData(rw); > 这段代码是运行在 Mac OS X 10.11.3 (x86_64)版本中,而不是运行在 iPhone 模拟器或者真机上的,如果你在 iPhone 或者真机上运行,可能有一定差别。 -<p align='center'> ![objc-method-target](../images/objc-method-target.png) 这是主程序的代码: @@ -209,7 +203,6 @@ int main(int argc, const char * argv[]) { 接下来,在整个 ObjC 运行时初始化之前,也就是 `_objc_init` 方法中加入一个断点: -<p align="center"> ![objc-method-after-compile](../images/objc-method-after-compile.png) 然后在 lldb 中输入以下命令: @@ -240,7 +233,6 @@ warning: could not load any Objective-C class information. This will significant } ``` -<p align="center"> ![objc-method-lldb-print-before-realize](../images/objc-method-lldb-print-before-realize.png) 现在我们获取了类经过编译器处理后的只读属性 `class_ro_t`: @@ -281,7 +273,6 @@ The process has been returned to the state before expression evaluation. (lldb) ``` -<p align="center"> ![objc-method-lldb-print-method-list](../images/objc-method-lldb-print-method-list.png) 使用 `$5->get(0)` 时,成功获取到了 `-[XXObject hello]` 方法的结构体 `method_t`。而尝试获取下一个方法时,断言提示我们当前类只有一个方法。 @@ -299,14 +290,12 @@ static Class realizeClass(Class cls) 上面就是这个方法的签名,我们需要在这个方法中打一个条件断点,来判断当前类是否为 `XXObject`: -<p align="center"> ![objc-method-lldb-breakpoint](../images/objc-method-lldb-breakpoint.png) 这里直接判断两个指针是否相等,而不使用 `[NSStringFromClass(cls) isEqualToString:@"XXObject"]` 是因为在这个时间点,这些方法都不能调用,在 ObjC 中没有这些方法,所以只能通过判断类指针是否相等的方式来确认当前类是 `XXObject`。 > 直接与指针比较是因为类在内存中的位置是编译期确定的,只要代码不改变,类在内存中的位置就会不变(已经说过很多遍了)。 -<p align="center"> ![objc-method-breakpoint-before-set-r](../images/objc-method-breakpoint-before-set-rw.png) @@ -316,13 +305,11 @@ static Class realizeClass(Class cls) 在这时打印类结构体中的 `data` 的值,发现其中的布局依旧是这样的: -<p align="center"> ![objc-method-before-realize](../images/objc-method-before-realize.png) 在运行完这段代码之后: -<p align="center"> ![objc-method-after-realize-breakpoint](../images/objc-method-after-realize-breakpoint.png) 我们再来打印类的结构: @@ -400,7 +387,6 @@ Assertion failed: (i < count), function get, file /Users/apple/Desktop/objc-runt (lldb) ``` -<p align="center"> ![objc-method-print-class-struct-after-realize](../images/objc-method-print-class-struct-after-realize.png) > 最后一个操作实在是截取不到了 @@ -415,7 +401,6 @@ cls->setData(rw); 在上述的代码运行之后,类的只读指针 `class_ro_t` 以及可读写指针 `class_rw_t` 都被正确的设置了。但是到这里,其 `class_rw_t` 部分的方法等成员的指针 `methods`、 `protocols` 和 `properties` 均为空,这些会在 `methodizeClass` 中进行设置: -<p align="center"> ![objc-method-after-methodizeClass](../images/objc-method-after-methodizeClass.png) 在这里调用了 `method_array_t` 的 `attachLists` 方法,将 `baseMethods` 中的方法添加到 `methods` 数组之后。我们访问 `methods` 才会获取当前类的实例方法。 @@ -434,7 +419,6 @@ struct method_t { 其中包含方法名,类型还有方法的实现指针 `IMP`: -<p align="center"> ![obj-method-struct](../images/obj-method-struct.png) 上面的 `-[XXObject hello]` 方法的结构体是这样的: diff --git "a/objc/\350\207\252\345\212\250\351\207\212\346\224\276\346\261\240\347\232\204\345\211\215\344\270\226\344\273\212\347\224\237.md" "b/contents/objc/\350\207\252\345\212\250\351\207\212\346\224\276\346\261\240\347\232\204\345\211\215\344\270\226\344\273\212\347\224\237.md" similarity index 99% rename from "objc/\350\207\252\345\212\250\351\207\212\346\224\276\346\261\240\347\232\204\345\211\215\344\270\226\344\273\212\347\224\237.md" rename to "contents/objc/\350\207\252\345\212\250\351\207\212\346\224\276\346\261\240\347\232\204\345\211\215\344\270\226\344\273\212\347\224\237.md" index 1717739..9f222be 100644 --- "a/objc/\350\207\252\345\212\250\351\207\212\346\224\276\346\261\240\347\232\204\345\211\215\344\270\226\344\273\212\347\224\237.md" +++ "b/contents/objc/\350\207\252\345\212\250\351\207\212\346\224\276\346\261\240\347\232\204\345\211\215\344\270\226\344\273\212\347\224\237.md" @@ -2,8 +2,8 @@ > 由于 Objective-C 中的内存管理是一个比较大的话题,所以会分为两篇文章来对内存管理中的一些机制进行剖析,一部分分析自动释放池以及 `autorelease` 方法,另一部分分析 `retain`、`release` 方法的实现以及自动引用计数。 -+ [自动释放池的前世今生](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/自动释放池的前世今生.md) -+ [黑箱中的 retain 和 release](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/黑箱中的%20retain%20和%20release.md) ++ [自动释放池的前世今生](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/自动释放池的前世今生.md) ++ [黑箱中的 retain 和 release](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/黑箱中的%20retain%20和%20release.md) ## 写在前面 diff --git "a/objc/\351\273\221\347\256\261\344\270\255\347\232\204 retain \345\222\214 release.md" "b/contents/objc/\351\273\221\347\256\261\344\270\255\347\232\204 retain \345\222\214 release.md" similarity index 98% rename from "objc/\351\273\221\347\256\261\344\270\255\347\232\204 retain \345\222\214 release.md" rename to "contents/objc/\351\273\221\347\256\261\344\270\255\347\232\204 retain \345\222\214 release.md" index 6996cc3..f8471a8 100644 --- "a/objc/\351\273\221\347\256\261\344\270\255\347\232\204 retain \345\222\214 release.md" +++ "b/contents/objc/\351\273\221\347\256\261\344\270\255\347\232\204 retain \345\222\214 release.md" @@ -2,8 +2,8 @@ > 由于 Objective-C 中的内存管理是一个比较大的话题,所以会分为两篇文章来对内存管理中的一些机制进行剖析,一部分分析自动释放池以及 `autorelease` 方法,另一部分分析 `retain`、`release` 方法的实现以及自动引用计数。 -+ [自动释放池的前世今生](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/自动释放池的前世今生.md) -+ [黑箱中的 retain 和 release](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/黑箱中的%20retain%20和%20release.md) ++ [自动释放池的前世今生](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/自动释放池的前世今生.md) ++ [黑箱中的 retain 和 release](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/黑箱中的%20retain%20和%20release.md) ## 写在前面 @@ -359,7 +359,7 @@ inline uintptr_t objc_object::rootRetainCount() { + Objective-C 使用 `isa` 中的 `extra_rc` 和 `SideTable` 来存储对象的引用计数 + 在对象的引用计数归零时,会调用 `dealloc` 方法回收对象 -有关于自动释放池实现的介绍,可以看[自动释放池的前世今生](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/自动释放池的前世今生.md)。 +有关于自动释放池实现的介绍,可以看[自动释放池的前世今生](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/contents/objc/自动释放池的前世今生.md)。 > Follow: [Draveness · Github](https://github.com/Draveness) diff --git a/contents/rack/images/rack-thin/event-callback.png b/contents/rack/images/rack-thin/event-callback.png new file mode 100644 index 0000000..97e6423 Binary files /dev/null and b/contents/rack/images/rack-thin/event-callback.png differ diff --git a/contents/rack/images/rack-thin/eventmachine-select.png b/contents/rack/images/rack-thin/eventmachine-select.png new file mode 100644 index 0000000..8673de9 Binary files /dev/null and b/contents/rack/images/rack-thin/eventmachine-select.png differ diff --git a/contents/rack/images/rack-thin/reactor-eventloop.png b/contents/rack/images/rack-thin/reactor-eventloop.png new file mode 100644 index 0000000..eed3171 Binary files /dev/null and b/contents/rack/images/rack-thin/reactor-eventloop.png differ diff --git a/contents/rack/images/rack-thin/selectable-and-subclasses.png b/contents/rack/images/rack-thin/selectable-and-subclasses.png new file mode 100644 index 0000000..af1891c Binary files /dev/null and b/contents/rack/images/rack-thin/selectable-and-subclasses.png differ diff --git a/contents/rack/images/rack-thin/thin-handle-request.png b/contents/rack/images/rack-thin/thin-handle-request.png new file mode 100644 index 0000000..aaec961 Binary files /dev/null and b/contents/rack/images/rack-thin/thin-handle-request.png differ diff --git a/contents/rack/images/rack-thin/thin-initialize-server.png b/contents/rack/images/rack-thin/thin-initialize-server.png new file mode 100644 index 0000000..515c9d0 Binary files /dev/null and b/contents/rack/images/rack-thin/thin-initialize-server.png differ diff --git a/contents/rack/images/rack-thin/thin-io-model.png b/contents/rack/images/rack-thin/thin-io-model.png new file mode 100644 index 0000000..a5846b3 Binary files /dev/null and b/contents/rack/images/rack-thin/thin-io-model.png differ diff --git a/contents/rack/images/rack-thin/thin-send-response.png b/contents/rack/images/rack-thin/thin-send-response.png new file mode 100644 index 0000000..0685d5b Binary files /dev/null and b/contents/rack/images/rack-thin/thin-send-response.png differ diff --git a/contents/rack/images/rack-thin/thin-start-server.png b/contents/rack/images/rack-thin/thin-start-server.png new file mode 100644 index 0000000..ebdc972 Binary files /dev/null and b/contents/rack/images/rack-thin/thin-start-server.png differ diff --git a/contents/rack/images/rack-unicorn/unicorn-daemonize.png b/contents/rack/images/rack-unicorn/unicorn-daemonize.png new file mode 100644 index 0000000..2d4bb0b Binary files /dev/null and b/contents/rack/images/rack-unicorn/unicorn-daemonize.png differ diff --git a/contents/rack/images/rack-unicorn/unicorn-io-model.png b/contents/rack/images/rack-unicorn/unicorn-io-model.png new file mode 100644 index 0000000..b25d078 Binary files /dev/null and b/contents/rack/images/rack-unicorn/unicorn-io-model.png differ diff --git a/contents/rack/images/rack-unicorn/unicorn-multi-processes.png b/contents/rack/images/rack-unicorn/unicorn-multi-processes.png new file mode 100644 index 0000000..423398a Binary files /dev/null and b/contents/rack/images/rack-unicorn/unicorn-multi-processes.png differ diff --git a/contents/rack/images/rack-unicorn/unicorn.jpeg b/contents/rack/images/rack-unicorn/unicorn.jpeg new file mode 100644 index 0000000..6df4100 Binary files /dev/null and b/contents/rack/images/rack-unicorn/unicorn.jpeg differ diff --git a/contents/rack/images/rack-webrick/mounttable-and-applications.png b/contents/rack/images/rack-webrick/mounttable-and-applications.png new file mode 100644 index 0000000..0a3b6b3 Binary files /dev/null and b/contents/rack/images/rack-webrick/mounttable-and-applications.png differ diff --git a/contents/rack/images/rack-webrick/webrick-io-model.png b/contents/rack/images/rack-webrick/webrick-io-model.png new file mode 100644 index 0000000..4092d1b Binary files /dev/null and b/contents/rack/images/rack-webrick/webrick-io-model.png differ diff --git a/contents/rack/images/rack/rack-and-web-servers-frameworks.png b/contents/rack/images/rack/rack-and-web-servers-frameworks.png new file mode 100644 index 0000000..51163df Binary files /dev/null and b/contents/rack/images/rack/rack-and-web-servers-frameworks.png differ diff --git a/contents/rack/images/rack/rack-app.png b/contents/rack/images/rack/rack-app.png new file mode 100644 index 0000000..c2c7966 Binary files /dev/null and b/contents/rack/images/rack/rack-app.png differ diff --git a/contents/rack/images/rack/rack-logo.png b/contents/rack/images/rack/rack-logo.png new file mode 100644 index 0000000..f5bba1a Binary files /dev/null and b/contents/rack/images/rack/rack-logo.png differ diff --git a/contents/rack/images/rack/rack-protocol.png b/contents/rack/images/rack/rack-protocol.png new file mode 100644 index 0000000..b5ae951 Binary files /dev/null and b/contents/rack/images/rack/rack-protocol.png differ diff --git a/contents/rack/images/rack/rails-application.png b/contents/rack/images/rack/rails-application.png new file mode 100644 index 0000000..0fe07d9 Binary files /dev/null and b/contents/rack/images/rack/rails-application.png differ diff --git a/contents/rack/images/rack/server-app-call-stack.png b/contents/rack/images/rack/server-app-call-stack.png new file mode 100644 index 0000000..8dde02d Binary files /dev/null and b/contents/rack/images/rack/server-app-call-stack.png differ diff --git a/contents/rack/images/rack/wrapped-app.png b/contents/rack/images/rack/wrapped-app.png new file mode 100644 index 0000000..2b0e12a Binary files /dev/null and b/contents/rack/images/rack/wrapped-app.png differ diff --git a/contents/rack/rack-thin.md b/contents/rack/rack-thin.md new file mode 100644 index 0000000..99ceaf9 --- /dev/null +++ b/contents/rack/rack-thin.md @@ -0,0 +1,786 @@ +# 浅谈 Thin 的事件驱动模型 + ++ [谈谈 Rack 协议与实现](https://draveness.me/rack) ++ [浅谈 WEBrick 的实现](https://draveness.me/rack-webrick) ++ [浅谈 Thin 的事件驱动模型](https://draveness.me/rack-thin) ++ [浅谈 Unicorn 的多进程模型](https://draveness.me/rack-unicorn) ++ [浅谈 Puma 的实现](https://draveness.me/rack-puma) + +在上一篇文章中我们已经介绍了 WEBrick 的实现,它的 handler 是写在 Rack 工程中的,而在这篇文章介绍的 webserver [thin](https://github.com/macournoyer/thin) 的 Rack 处理器也是写在 Rack 中的;与 WEBrick 相同,Thin 的实现也非常简单,官方对它的介绍是: + +> A very fast & simple Ruby web server. + +它将 [Mongrel](https://zedshaw.com/archive/ragel-state-charts/)、[Event Machine](https://github.com/eventmachine/eventmachine) 和 [Rack](http://rack.github.io) 三者进行组合,在其中起到胶水的作用,所以在理解 Thin 的实现的过程中我们也需要分析 EventMachine 到底是如何工作的。 + +## Thin 的实现 + +在这一节中我们将从源代码来分析介绍 Thin 的实现原理,因为部分代码仍然是在 Rack 工程中实现的,所以我们要从 Rack 工程的代码开始理解 Thin 的实现。 + +### 从 Rack 开始 + +Thin 的处理器 `Rack::Handler::Thin` 与其他遵循 Rack 协议的 webserver 一样都实现了 `.run` 方法,接受 Rack 应用和 `options` 作为输入: + +```ruby +module Rack + module Handler + class Thin + def self.run(app, options={}) + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : '0.0.0.0' + + host = options.delete(:Host) || default_host + port = options.delete(:Port) || 8080 + args = [host, port, app, options] + args.pop if ::Thin::VERSION::MAJOR < 1 && ::Thin::VERSION::MINOR < 8 + server = ::Thin::Server.new(*args) + yield server if block_given? + server.start + end + end + end +end +``` + +上述方法仍然会从 `options` 中取出 ip 地址和端口号,然后初始化一个 `Thin::Server` 的实例后,执行 `#start` 方法在 8080 端口上监听来自用户的请求。 + +### 初始化服务 + +Thin 服务的初始化由以下的代码来处理,首先会处理在 `Rack::Handler::Thin.run` 中传入的几个参数 `host`、`port`、`app` 和 `options`,将 Rack 应用存储在临时变量中: + +```ruby +From: lib/thin/server.rb @ line 100: +Owner: Thin::Server + +def initialize(*args, &block) + host, port, options = DEFAULT_HOST, DEFAULT_PORT, {} + + args.each do |arg| + case arg + when 0.class, /^\d+$/ then port = arg.to_i + when String then host = arg + when Hash then options = arg + else + @app = arg if arg.respond_to?(:call) + end + end + + @backend = select_backend(host, port, options) + @backend.server = self + @backend.maximum_connections = DEFAULT_MAXIMUM_CONNECTIONS + @backend.maximum_persistent_connections = DEFAULT_MAXIMUM_PERSISTENT_CONNECTIONS + @backend.timeout = options[:timeout] || DEFAULT_TIMEOUT + + @app = Rack::Builder.new(&block).to_app if block +end +``` + +在初始化服务的过程中,总共只做了三件事情,处理参数、选择并配置 `backend`,创建新的应用: + +![thin-initialize-serve](images/rack-thin/thin-initialize-server.png) + +处理参数的过程自然不用多说,只是这里判断的方式并不是按照顺序处理的,而是按照参数的类型;在初始化器的最后,如果向初始化器传入了 block,那么就会使用 `Rack::Builder` 和 block 中的代码初始化一个新的 Rack 应用。 + +### 选择后端 + +在选择后端时 Thin 使用了 `#select_backend` 方法,这里使用 `case` 语句替代多个 `if`、`else`,也是一个我们可以使用的小技巧: + +```ruby +From: lib/thin/server.rb @ line 261: +Owner: Thin::Server + +def select_backend(host, port, options) + case + when options.has_key?(:backend) + raise ArgumentError, ":backend must be a class" unless options[:backend].is_a?(Class) + options[:backend].new(host, port, options) + when options.has_key?(:swiftiply) + Backends::SwiftiplyClient.new(host, port, options) + when host.include?('/') + Backends::UnixServer.new(host) + else + Backends::TcpServer.new(host, port) + end +end +``` + +在大多数时候,我们只会选择 `UnixServer` 和 `TcpServer` 两种后端中的一个,而后者又是两者中使用更为频繁的后端: + +```ruby +From: lib/thin/backends/tcp_server.rb @ line 8: +Owner: Thin::Backends::TcpServer + +def initialize(host, port) + @host = host + @port = port + super() +end + +From: lib/thin/backends/base.rb @ line 47: +Owner: Thin::Backends::Base + +def initialize + @connections = {} + @timeout = Server::DEFAULT_TIMEOUT + @persistent_connection_count = 0 + @maximum_connections = Server::DEFAULT_MAXIMUM_CONNECTIONS + @maximum_persistent_connections = Server::DEFAULT_MAXIMUM_PERSISTENT_CONNECTIONS + @no_epoll = false + @ssl = nil + @threaded = nil + @started_reactor = false +end +``` + +初始化的过程中只是对属性设置默认值,比如 `host`、`port` 以及超时时间等等,并没有太多值得注意的代码。 + +### 启动服务 + +在启动服务时会直接调用 `TcpServer#start` 方法并在其中传入一个用于处理信号的 block: + +```ruby +From: lib/thin/server.rb @ line 152: +Owner: Thin::Server + +def start + raise ArgumentError, 'app required' unless @app + + log_info "Thin web server (v#{VERSION::STRING} codename #{VERSION::CODENAME})" + log_debug "Debugging ON" + trace "Tracing ON" + + log_info "Maximum connections set to #{@backend.maximum_connections}" + log_info "Listening on #{@backend}, CTRL+C to stop" + + @backend.start { setup_signals if @setup_signals } +end +``` + +虽然这里的 `backend` 其实已经被选择成了 `TcpServer`,但是该子类并没有覆写 `#start` 方法,这里执行的方法其实是从父类继承的: + +```ruby +From: lib/thin/backends/base.rb @ line 60: +Owner: Thin::Backends::Base + +def start + @stopping = false + starter = proc do + connect + yield if block_given? + @running = true + end + + # Allow for early run up of eventmachine. + if EventMachine.reactor_running? + starter.call + else + @started_reactor = true + EventMachine.run(&starter) + end +end +``` + +上述方法在构建一个 `starter` block 之后,将该 block 传入 `EventMachine.run` 方法,随后执行的 `#connect` 会启动一个 `EventMachine` 的服务器用于处理用户的网络请求: + +```ruby +From: lib/thin/backends/tcp_server.rb @ line 15: +Owner: Thin::Backends::TcpServer + +def connect + @signature = EventMachine.start_server(@host, @port, Connection, &method(:initialize_connection)) + binary_name = EventMachine.get_sockname( @signature ) + port_name = Socket.unpack_sockaddr_in( binary_name ) + @port = port_name[0] + @host = port_name[1] + @signature +end +``` + +在 EventMachine 的文档中,`.start_server` 方法被描述成一个在指定的地址和端口上初始化 TCP 服务的方法,正如这里所展示的,它经常在 `.run` 方法的 block 中执行;该方法的参数 `Connection` 作为处理 TCP 请求的类,会实现不同的方法接受各种各样的回调,传入的 `initialize_connection` block 会在有请求需要处理时对 `Connection` 对象进行初始化: + +> `Connection` 对象继承自 `EventMachine::Connection`,是 EventMachine 与外界的接口,在 EventMachine 中的大部分事件都会调用 `Connection` 的一个实例方法来传递数据和参数。 + +```ruby +From: lib/thin/backends/base.rb @ line 145: +Owner: Thin::Backends::Base + +def initialize_connection(connection) + connection.backend = self + connection.app = @server.app + connection.comm_inactivity_timeout = @timeout + connection.threaded = @threaded + connection.start_tls(@ssl_options) if @ssl + + if @persistent_connection_count < @maximum_persistent_connections + connection.can_persist! + @persistent_connection_count += 1 + end + @connections[connection.__id__] = connection +end +``` + +### 处理请求的连接 + +`Connection` 类中有很多的方法 `#post_init`、`#receive_data` 方法等等都是由 EventMachine 在接收到请求时调用的,当 Thin 的服务接收到来自客户端的数据时就会调用 `#receive_data` 方法: + +```ruby +From: lib/thin/connection.rb @ line 36: +Owner: Thin::Connection + +def receive_data(data) + @idle = false + trace data + process if @request.parse(data) +rescue InvalidRequest => e + log_error("Invalid request", e) + post_process Response::BAD_REQUEST +end +``` + +在这里我们看到了与 WEBrick 在处理来自客户端的原始数据时使用的方法 `#parse`,它会解析客户端请求的原始数据并执行 `#process` 来处理 HTTP 请求: + +```ruby +From: lib/thin/connection.rb @ line 47: +Owner: Thin::Connection + +def process + if threaded? + @request.threaded = true + EventMachine.defer { post_process(pre_process) } + else + @request.threaded = false + post_process(pre_process) + end +end +``` + +如果当前的连接允许并行处理多个用户的请求,那么就会在 `EventMachine.defer` 的 block 中执行两个方法 `#pre_process` 和 `#post_process`: + +```ruby +From: lib/thin/connection.rb @ line 63: +Owner: Thin::Connection + +def pre_process + @request.remote_address = remote_address + @request.async_callback = method(:post_process) + + response = AsyncResponse + catch(:async) do + response = @app.call(@request.env) + end + response +rescue Exception => e + unexpected_error(e) + can_persist? && @request.persistent? ? Response::PERSISTENT_ERROR : Response::ERROR +end +``` + +在 `#pre_process` 中没有做太多的事情,只是调用了 Rack 应用的 `#call` 方法,得到一个三元组 `response`,在这之后将这个数组传入 `#post_process` 方法: + +```ruby +From: lib/thin/connection.rb @ line 95: +Owner: Thin::Connection + +def post_process(result) + return unless result + result = result.to_a + return if result.first == AsyncResponse.first + + @response.status, @response.headers, @response.body = *result + @response.each do |chunk| + send_data chunk + end +rescue Exception => e + unexpected_error(e) + close_connection +ensure + if @response.body.respond_to?(:callback) && @response.body.respond_to?(:errback) + @response.body.callback { terminate_request } + @response.body.errback { terminate_request } + else + terminate_request unless result && result.first == AsyncResponse.first + end +end +``` + +`#post_response` 方法将传入的数组赋值给 `response` 的 `status`、`headers` 和 `body` 这三部分,在这之后通过 `#send_data` 方法将 HTTP 响应以块的形式写回 Socket;写回结束后可能会调用对应的 `callback` 并关闭持有的 `request` 和 `response` 两个实例变量。 + +> 上述方法中调用的 `#send_data` 继承自 `EventMachine::Connection` 类。 + +### 小结 + +到此为止,我们对于 Thin 是如何处理来自用户的 HTTP 请求的就比较清楚了,我们可以看到 Thin 本身并没有做一些类似解析 HTTP 数据包以及发送数据的问题,它使用了来自 Rack 和 EventMachine 两个开源框架中很多已有的代码逻辑,确实只做了一些胶水的事情。 + +对于 Rack 是如何工作的我们在前面的文章 [谈谈 Rack 协议与实现](https://draveness.me/rack) 中已经介绍过了;虽然我们看到了很多与 EventMachine 相关的代码,但是到这里我们仍然对 EventMachine 不是太了解。 + +## EventMachine 和 Reactor 模式 + +为了更好地理解 Thin 的工作原理,在这里我们会介绍一个 EventMachine 和 Reactor 模式。 + +EventMachine 其实是一个使用 Ruby 实现的事件驱动的并行框架,它使用 Reactor 模式提供了事件驱动的 IO 模型,如果你对 Node.js 有所了解的话,那么你一定对事件驱动这个词并不陌生,EventMachine 的出现主要是为了解决两个核心问题: + ++ 为生产环境提供更高的可伸缩性、更好的性能和稳定性; ++ 为上层提供了一些能够减少高性能的网络编程复杂性的 API; + +其实 EventMachine 的主要作用就是将所有同步的 IO 都变成异步的,调度都通过事件来进行,这样用于监听用户请求的进程不会被其他代码阻塞,能够同时为更多的客户端提供服务;在这一节中,我们需要了解一下在 Thin 中使用的 EventMachine 中几个常用方法的实现。 + +### 启动事件循环 + +EventMachine 其实就是一个事件循环(Event Loop),当我们想使用 EventMachine 来处理某些任务时就一定需要调用 `.run` 方法启动这个事件循环来接受外界触发的各种事件: + +```ruby +From: lib/eventmachine.rb @ line 149: +Owner: #<Class:EventMachine> + +def self.run blk=nil, tail=nil, &block + # ... + begin + @reactor_pid = Process.pid + @reactor_running = true + initialize_event_machine + (b = blk || block) and add_timer(0, b) + if @next_tick_queue && !@next_tick_queue.empty? + add_timer(0) { signal_loopbreak } + end + @reactor_thread = Thread.current + + run_machine + ensure + until @tails.empty? + @tails.pop.call + end + + release_machine + cleanup_machine + @reactor_running = false + @reactor_thread = nil + end +end +``` + +在这里我们会使用 `.initialize_event_machine` 初始化当前的事件循环,其实也就是一个全局的 `Reactor` 的单例,最终会执行 `Reactor#initialize_for_run` 方法: + +```ruby +From: lib/em/pure_ruby.rb @ line 522: +Owner: EventMachine::Reactor + +def initialize_for_run + @running = false + @stop_scheduled = false + @selectables ||= {}; @selectables.clear + @timers = SortedSet.new # [] + set_timer_quantum(0.1) + @current_loop_time = Time.now + @next_heartbeat = @current_loop_time + HeartbeatInterval +end +``` + +在启动事件循环的过程中,它还会将传入的 block 与一个 `interval` 为 0 的键组成键值对存到 `@timers` 字典中,所有加入的键值对都会在大约 `interval` 的时间过后执行一次 block。 + +随后执行的 `#run_machine` 在最后也会执行 `Reactor` 的 `#run` 方法,该方法中包含一个 loop 语句,也就是我们一直说的事件循环: + +```ruby +From: lib/em/pure_ruby.rb @ line 540: +Owner: EventMachine::Reactor + +def run + raise Error.new( "already running" ) if @running + @running = true + + begin + open_loopbreaker + + loop { + @current_loop_time = Time.now + + break if @stop_scheduled + run_timers + break if @stop_scheduled + crank_selectables + break if @stop_scheduled + run_heartbeats + } + ensure + close_loopbreaker + @selectables.each {|k, io| io.close} + @selectables.clear + + @running = false + end +end +``` + +在启动事件循环之间会在 `#open_loopbreaker` 中创建一个 `LoopbreakReader` 的实例绑定在 `127.0.0.1` 和随机的端口号组成的地址上,然后开始运行事件循环。 + +![reactor-eventloop](images/rack-thin/reactor-eventloop.png) + +在事件循环中,Reactor 总共需要执行三部分的任务,分别是执行定时器、处理 Socket 上的事件以及运行心跳方法。 + +无论是运行定时器还是执行心跳方法其实都非常简单,只要与当前时间进行比较,如果到了触发的时间就调用正确的方法或者回调,最后的 `#crank_selectables` 方法就是用于处理 Socket 上读写事件的方法了: + +```ruby +From: lib/em/pure_ruby.rb @ line 540: +Owner: EventMachine::Reactor + +def crank_selectables + readers = @selectables.values.select { |io| io.select_for_reading? } + writers = @selectables.values.select { |io| io.select_for_writing? } + + s = select(readers, writers, nil, @timer_quantum) + + s and s[1] and s[1].each { |w| w.eventable_write } + s and s[0] and s[0].each { |r| r.eventable_read } + + @selectables.delete_if {|k,io| + if io.close_scheduled? + io.close + begin + EventMachine::event_callback io.uuid, ConnectionUnbound, nil + rescue ConnectionNotBound; end + true + end + } +end +``` + +上述方法会在 Socket 变成可读或者可写时执行 `#eventable_write` 或 `#eventable_read` 执行事件的回调,我们暂时放下这两个方法,先来了解一下 EventMachine 是如何启动服务的。 + +### 启动服务 + +在启动服务的过程中,最重要的目的就是创建一个 Socket 并绑定在指定的 ip 和端口上,在实现这个目的的过程中,我们使用了以下的几个方法,首先是 `EventMachine.start_server`: + +```ruby +From: lib/eventmachine.rb @ line 516: +Owner: #<Class:EventMachine> + +def self.start_server server, port=nil, handler=nil, *args, &block + port = Integer(port) + klass = klass_from_handler(Connection, handler, *args) + + s = if port + start_tcp_server server, port + else + start_unix_server server + end + @acceptors[s] = [klass, args, block] + s +end +``` + +该方法其实使我们在使用 EventMachine 时常见的接口,只要我们想要启动一个新的 TCP 或者 UNIX 服务器,就可以上述方法,在这里会根据端口号是否存在,选择执行 `.start_tcp_server` 或者 `.start_unix_server` 创建一个新的 Socket 并存储在 `@acceptors` 中: + +```ruby +From: lib/em/pure_ruby.rb @ line 184: +Owner: #<Class:EventMachine> + +def self.start_tcp_server host, port + (s = EvmaTCPServer.start_server host, port) or raise "no acceptor" + s.uuid +end +``` + +`EventMachine.start_tcp_server` 在这里也只做了个『转发』方法的作用的,直接调用 `EvmaTCPServer.start_server` 创建一个新的 Socket 对象并绑定到传入的 `<host, port>` 上: + +```ruby +From: lib/em/pure_ruby.rb @ line 1108: +Owner: #<Class:EventMachine::EvmaTCPServer> + +def self.start_server host, port + sd = Socket.new( Socket::AF_LOCAL, Socket::SOCK_STREAM, 0 ) + sd.setsockopt( Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true ) + sd.bind( Socket.pack_sockaddr_in( port, host )) + sd.listen( 50 ) # 5 is what you see in all the books. Ain't enough. + EvmaTCPServer.new sd +end +``` + +方法的最后会创建一个新的 `EvmaTCPServer` 实例的过程中,我们需要通过 `#fcntl` 将 Socket 变成非阻塞式的: + +```ruby +From: lib/em/pure_ruby.rb @ line 687: +Owner: EventMachine::Selectable + +def initialize io + @io = io + @uuid = UuidGenerator.generate + @is_server = false + @last_activity = Reactor.instance.current_loop_time + + m = @io.fcntl(Fcntl::F_GETFL, 0) + @io.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK | m) + + @close_scheduled = false + @close_requested = false + + se = self; @io.instance_eval { @my_selectable = se } + Reactor.instance.add_selectable @io +end +``` + +不只是 `EvmaTCPServer`,所有的 `Selectable` 子类在初始化的最后都会将新的 Socket 以 `uuid` 为键存储到 `Reactor` 单例对象的 `@selectables` 字典中: + +```ruby +From: lib/em/pure_ruby.rb @ line 532: +Owner: EventMachine::Reactor + +def add_selectable io + @selectables[io.uuid] = io +end +``` + +在整个事件循环的大循环中,这里存入的所有 Socket 都会被 `#select` 方法监听,在响应的事件发生时交给合适的回调处理,作者在 [Redis 中的事件循环](https://draveness.me/redis-eventloop) 一文中也介绍过非常相似的处理过程。 + +![eventmachine-select](images/rack-thin/eventmachine-select.png) + +所有的 Socket 都会存储在一个 `@selectables` 的哈希中并由 `#select` 方法监听所有的读写事件,一旦相应的事件触发就会通过 `eventable_read` 或者 `eventable_write` 方法来响应该事件。 + +### 处理读写事件 + +所有的读写事件都是通过 `Selectable` 和它的子类来处理的,在 EventMachine 中,总共有以下的几种子类: + +![selectable-and-subclasses](images/rack-thin/selectable-and-subclasses.png) + +所有处理服务端读写事件的都是 `Selectable` 的子类,也就是 `EvmaTCPServer` 和 `EvmaUNIXServer`,而所有处理客户端读写事件的都是 `StreamObject` 的子类 `EvmaTCPServer` 和 `EvmaUNIXClient`。 + +当我们初始化的绑定在 `<host, port>` 上的 Socket 对象监听到了来自用户的 TCP 请求时,当前的 Socket 就会变得可读,事件循环中的 `#select` 方法就会调用 `EvmaTCPClient#eventable_read` 通知由一个请求需要处理: + +```ruby +From: lib/em/pure_ruby.rb @ line 1130: +Owner: EventMachine::EvmaTCPServer + +def eventable_read + begin + 10.times { + descriptor, peername = io.accept_nonblock + sd = EvmaTCPClient.new descriptor + sd.is_server = true + EventMachine::event_callback uuid, ConnectionAccepted, sd.uuid + } + rescue Errno::EWOULDBLOCK, Errno::EAGAIN + end +end +``` + +在这里会尝试多次 `#accept_non_block` 当前的 Socket 并会创建一个 TCP 的客户端对象 `EvmaTCPClient`,同时通过 `.event_callback` 方法发送 `ConnectionAccepted` 消息。 + +`EventMachine::event_callback` 就像是一个用于处理所有事件的中心方法,所有的回调都要通过这个中继器进行调度,在实现上就是一个庞大的 `if`、`else` 语句,里面处理了 EventMachine 中可能出现的 10 种状态和操作: + +![event-callback](images/rack-thin/event-callback.png) + +大多数事件在触发时,都会从 `@conns` 中取出相应的 `Connection` 对象,最后执行合适的方法来处理,而这里触发的 `ConnectionAccepted` 事件是通过以下的代码来处理的: + +```ruby +From: lib/eventmachine.rb @ line 1462: +Owner: #<Class:EventMachine> + +def self.event_callback conn_binding, opcode, data + if opcode == # ... + # ... + elsif opcode == ConnectionAccepted + accep, args, blk = @acceptors[conn_binding] + raise NoHandlerForAcceptedConnection unless accep + c = accep.new data, *args + @conns[data] = c + blk and blk.call(c) + c + else + # ... + end +end +``` + +上述的 `accep` 变量就是我们在 Thin 调用 `.start_server` 时传入的 `Connection` 类,在这里我们初始化了一个新的实例,同时以 Socket 的 `uuid` 作为键存到 `@conns` 中。 + +在这之后 `#select` 方法就会监听更多 Socket 上的事件了,当这个 "accept" 后创建的 Socket 接收到数据时,就会触发下面的 `#eventable_read` 方法: + +```ruby +From: lib/em/pure_ruby.rb @ line 1130: +Owner: EventMachine::StreamObject + +def eventable_read + @last_activity = Reactor.instance.current_loop_time + begin + if io.respond_to?(:read_nonblock) + 10.times { + data = io.read_nonblock(4096) + EventMachine::event_callback uuid, ConnectionData, data + } + else + data = io.sysread(4096) + EventMachine::event_callback uuid, ConnectionData, data + end + rescue Errno::EAGAIN, Errno::EWOULDBLOCK, SSLConnectionWaitReadable + rescue Errno::ECONNRESET, Errno::ECONNREFUSED, EOFError, Errno::EPIPE, OpenSSL::SSL::SSLError + @close_scheduled = true + EventMachine::event_callback uuid, ConnectionUnbound, nil + end +end +``` + +方法会从 Socket 中读取数据并通过 `.event_callback` 发送 `ConnectionData` 事件: + +```ruby +From: lib/eventmachine.rb @ line 1462: +Owner: #<Class:EventMachine> + +def self.event_callback conn_binding, opcode, data + if opcode == # ... + # ... + elsif opcode == ConnectionData + c = @conns[conn_binding] or raise ConnectionNotBound, "received data #{data} for unknown signature: #{conn_binding}" + c.receive_data data + else + # ... + end +end +``` + +从上述方法对 `ConnectionData` 事件的处理就可以看到通过传入 Socket 的 `uuid` 和数据,就可以找到上面初始化的 `Connection` 对象,`#receive_data` 方法就能够将数据传递到上层,让用户在自定义的 `Connection` 中实现自己的处理逻辑,这也就是 Thin 需要覆写 `#receive_data` 方法来接受数据的原因了。 + +当 Thin 以及 Rack 应用已经接收到了来自用户的请求、完成处理并返回之后经过一系列复杂的调用栈就会执行 `Connection#send_data` 方法: + +```ruby +From: lib/em/connection.rb @ line 324: +Owner: EventMachine::Connection + +def send_data data + data = data.to_s + size = data.bytesize if data.respond_to?(:bytesize) + size ||= data.size + EventMachine::send_data @signature, data, size +end + +From: lib/em/pure_ruby.rb @ line 172: +Owner: #<Class:EventMachine> + +def self.send_data target, data, datalength + selectable = Reactor.instance.get_selectable( target ) or raise "unknown send_data target" + selectable.send_data data +end + +From: lib/em/pure_ruby.rb @ line 851: +Owner: EventMachine::StreamObject + +def send_data data + unless @close_scheduled or @close_requested or !data or data.length <= 0 + @outbound_q << data.to_s + end +end +``` + +经过一系列同名方法的调用,在调用栈末尾的 `StreamObject#send_data` 中,将所有需要写入的数据全部加入 `@outbound_q` 中,这其实就是一个待写入数据的队列。 + +当 Socket 变得可写之后,就会由 `#select` 方法触发 `#eventable_write` 将 `@outbound_q` 队列中的数据通过 `#write_nonblock` 或者 `syswrite` 写入 Socket,也就是将请求返回给客户端。 + +```ruby +From: lib/em/pure_ruby.rb @ line 823: +Owner: EventMachine::StreamObject + +def eventable_write + @last_activity = Reactor.instance.current_loop_time + while data = @outbound_q.shift do + begin + data = data.to_s + w = if io.respond_to?(:write_nonblock) + io.write_nonblock data + else + io.syswrite data + end + + if w < data.length + @outbound_q.unshift data[w..-1] + break + end + rescue Errno::EAGAIN, SSLConnectionWaitReadable, SSLConnectionWaitWritable + @outbound_q.unshift data + break + rescue EOFError, Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::EPIPE, OpenSSL::SSL::SSLError + @close_scheduled = true + @outbound_q.clear + end + end +end +``` + +### 关闭 Socket + +当数据写入时发生了 `EOFError` 或者其他错误时就会将 `close_scheduled` 标记为 `true`,在随后的事件循环中会关闭 Socket 并发送 `ConnectionUnbound` 事件: + +```ruby +From: lib/em/pure_ruby.rb @ line 540: +Owner: EventMachine::Reactor + +def crank_selectables + # ... + + @selectables.delete_if {|k,io| + if io.close_scheduled? + io.close + begin + EventMachine::event_callback io.uuid, ConnectionUnbound, nil + rescue ConnectionNotBound; end + true + end + } +end +``` + +`.event_callback` 在处理 `ConnectionUnbound` 事件时会在 `@conns` 中将结束的 `Connection` 剔除: + +```ruby +def self.event_callback conn_binding, opcode, data + if opcode == ConnectionUnbound + if c = @conns.delete( conn_binding ) + c.unbind + io = c.instance_variable_get(:@io) + begin + io.close + rescue Errno::EBADF, IOError + end + elsif c = @acceptors.delete( conn_binding ) + else + raise ConnectionNotBound, "received ConnectionUnbound for an unknown signature: #{conn_binding}" + end + elsif opcode = 1 + #... + end +end +``` + +在这之后会调用 `Connection` 的 `#unbind` 方法,再次执行 `#close` 确保 Socket 连接已经断掉了。 + +### 小结 + +EventMachine 在处理用户的请求时,会通过一个事件循环和一个中心化的事件处理中心 `.event_callback` 来响应所有的事件,你可以看到在使用 EventMachine 时所有的响应都是异步的,尤其是对 Socket 的读写,所有外部的输入在 EventMachine 看来都是一个事件,它们会被 EventMachine 选择合适的处理器进行转发。 + +## I/O 模型 + +Thin 本身其实没有实现任何的 I/O 模型,它通过对 EventMachine 进行封装,使用了其事件驱动的特点,为上层提供了处理并发 I/O 的 Reactor 模型,在不同的阶段有着不同的工作流程,在启动 Thin 的服务时,Thin 会直接通过 `.start_server` 创建一个 Socket 监听一个 `<host, port>` 组成的元组: + +![thin-start-server](images/rack-thin/thin-start-server.png) + +当服务启动之后,就可以接受来自客户端的 HTTP 请求了,处理 HTTP 请求总共需要三个模块的合作,分别是 EventMachine、Thin 以及 Rack 应用: + +![thin-handle-request](images/rack-thin/thin-handle-request.png) + +在上图中省略了 Rack 的处理部分,不过对于其他部分的展示还是比较详细的,EventMachine 负责对 TCP Socket 进行监听,在发生事件时通过 `.event_callback` 进行处理,将消息转发给位于 Thin 中的 `Connection`,该类以及模块负责处理 HTTP 协议相关的内容,将整个请求包装成一个 `env` 对象,调用 `#call` 方法。 + +在这时就开始了返回响应的逻辑了,`#call` 方法会返回一个三元组,经过 Thin 中的 `#send_data` 最终将数据写入 `outbound_q` 队列中等待处理: + +![thin-send-response](images/rack-thin/thin-send-response.png) + +EventMachine 会通过一个事件循环,使用 `#select` 监听当前 Socket 的可读写状态,并在合适的时候触发 `#eventable_write` 从 `outbound_q` 队列中读取数据写入 Socket,在写入结束后 Socket 就会被关闭,整个请求的响应也就结束了。 + +![thin-io-model](images/rack-thin/thin-io-model.png) + +Thin 使用了 EventMachine 作为底层处理 TCP 协议的框架,提供了事件驱动的 I/O 模型,也就是我们理解的 Reactor 模型,对于每一个 HTTP 请求都会创建一个对应的 `Connection` 对象,所有的事件都由 EventMachine 来派发,最大程度做到了 I/O 的读写都是异步的,不会阻塞当前的线程,这也是 Thin 以及 Node.js 能够并发处理大量请求的原因。 + +## 总结 + +Thin 作为一个 Ruby 社区中简单的 webserver,其实本身没有做太多的事情,只是使用了 EventMachine 提供的事件驱动的 I/O 模型,为上层提供了更加易用的 API,相比于其他同步处理请求的 webserver,Reactor 模式的优点就是 Thin 的优点,主程序只负责监听事件和分发事件,一旦涉及到 I/O 的工作都尽量使用回调的方式处理,当回调完成后再发送通知,这种方式能够减少进程的等待时间,时刻都在处理用户的请求和事件。 + +## Reference + ++ [Ragel State Charts](https://zedshaw.com/archive/ragel-state-charts/) ++ [Ragel State Machine Compiler](http://www.colm.net/open-source/ragel/) ++ [Ruby EventMachine - The Speed Demon](https://www.igvita.com/2008/05/27/ruby-eventmachine-the-speed-demon/) + diff --git a/contents/rack/rack-unicorn.md b/contents/rack/rack-unicorn.md new file mode 100644 index 0000000..576ab74 --- /dev/null +++ b/contents/rack/rack-unicorn.md @@ -0,0 +1,640 @@ +# 浅谈 Unicorn 的多进程模型 + ++ [谈谈 Rack 协议与实现](https://draveness.me/rack) ++ [浅谈 WEBrick 的实现](https://draveness.me/rack-webrick) ++ [浅谈 Thin 的事件驱动模型](https://draveness.me/rack-thin) ++ [浅谈 Unicorn 的多进程模型](https://draveness.me/rack-unicorn) ++ [浅谈 Puma 的实现](https://draveness.me/rack-puma) + +作为 Ruby 社区中老牌的 webserver,在今天也有很多开发者在生产环境使用 Unicorn 处理客户端的发出去的 HTTP 请求,与 WEBrick 和 Thin 不同,Unicorn 使用了完全不同的模型,提供了多进程模型批量处理来自客户端的请求。 + +![unicorn](images/rack-unicorn/unicorn.jpeg) + +Unicorn 为 Rails 应用提供并发的方式是使用 `fork` 创建多个 worker 线程,监听同一个 Socket 上的输入。 + +> 本文中使用的是 5.3.1 的 Unicorn,如果你使用了不同版本的 Unicorn,原理上的区别不会太大,只是在一些方法的实现上会有一些细微的不同。 + +## 实现原理 + +Unicorn 虽然也是一个遵循 Rack 协议的 Ruby webserver,但是因为它本身并没有提供 Rack 处理器,随意没有办法直接通过 `rackup -s Unicorn` 来启动 Unicorn 的进程。 + +```ruby +$ unicorn -c unicorn.rb +I, [2017-11-06T08:05:03.082116 #33222] INFO -- : listening on addr=0.0.0.0:8080 fd=10 +I, [2017-11-06T08:05:03.082290 #33222] INFO -- : worker=0 spawning... +I, [2017-11-06T08:05:03.083505 #33222] INFO -- : worker=1 spawning... +I, [2017-11-06T08:05:03.083989 #33222] INFO -- : master process ready +I, [2017-11-06T08:05:03.084610 #33223] INFO -- : worker=0 spawned pid=33223 +I, [2017-11-06T08:05:03.085100 #33223] INFO -- : Refreshing Gem list +I, [2017-11-06T08:05:03.084902 #33224] INFO -- : worker=1 spawned pid=33224 +I, [2017-11-06T08:05:03.085457 #33224] INFO -- : Refreshing Gem list +I, [2017-11-06T08:05:03.123611 #33224] INFO -- : worker=1 ready +I, [2017-11-06T08:05:03.123670 #33223] INFO -- : worker=0 ready +``` + +在使用 Unicorn 时,我们需要直接使用 `unicorn` 命令来启动一个 Unicorn 服务,在使用时可以通过 `-c` 传入一个配置文件,文件中的内容其实都是 Ruby 代码,每一个方法调用都是 Unicorn 的一条配置项: + +```ruby +$ cat unicorn.rb +worker_processes 2 +``` + +### 可执行文件 + +`unicorn` 这个命令位于 `bin/unicorn` 中,在这个可执行文件中,大部分的代码都是对命令行参数的配置和说明,整个文件可以简化为以下的几行代码: + +```ruby +rackup_opts = # ... +app = Unicorn.builder(ARGV[0] || 'config.ru', op) +Unicorn::Launcher.daemonize!(options) if rackup_opts[:daemonize] +Unicorn::HttpServer.new(app, options).start.join +``` + +`unicorn` 命令会从 Rack 应用的标配 config.ru 文件或者传入的文件中加载代码构建一个新的 Rack 应用;初始化 Rack 应用后会使用 `.daemonize!` 方法将 unicorn 进程启动在后台运行;最后会创建并启动一个新的 `HttpServer` 的实例。 + +### 构建应用 + +读取 config.ru 文件并解析的过程其实就是直接使用了 Rack 的 `Builder` 模块,通过 `eval` 运行一段代码得到一个 Rack 应用: + +```ruby +From: lib/unicorn.rb @ line 39: +Owner: #<Class:Unicorn> + +def self.builder(ru, op) + raw = File.read(ru) + inner_app = eval("Rack::Builder.new {(\n#{raw}\n)}.to_app", TOPLEVEL_BINDING, ru) + + middleware = { + ContentLength: nil, + Chunked: nil, + CommonLogger: [ $stderr ], + ShowExceptions: nil, + Lint: nil, + TempfileReaper: nil, + } + + Rack::Builder.new do + middleware.each do |m, args| + use(Rack.const_get(m), *args) if Rack.const_defined?(m) + end + run inner_app + end.to_app +end +``` + +在该方法中会执行两次 `Rack::Builder.new` 方法,第一次会运行 config.ru 中的代码,第二次会添加一些默认的中间件,最终会返回一个接受 `#call` 方法返回三元组的 Rack 应用。 + +### 守护进程 + +在默认情况下,Unicorn 的进程都是以前台进程的形式运行的,但是在生产环境我们往往需要在后台运行 Unicorn 进程,这也就是 `Unicorn::Launcher` 所做的工作。 + +```ruby +From: lib/unicorn.rb @ line 23: +Owner: #<Class:Unicorn::Launcher> + +def self.daemonize!(options) + cfg = Unicorn::Configurator + $stdin.reopen("/dev/null") + + unless ENV['UNICORN_FD'] + rd, wr = IO.pipe + grandparent = $$ + if fork + wr.close + else + rd.close + Process.setsid + exit if fork + end + + if grandparent == $$ + master_pid = (rd.readpartial(16) rescue nil).to_i + unless master_pid > 1 + warn "master failed to start, check stderr log for details" + exit!(1) + end + exit 0 + else + options[:ready_pipe] = wr + end + end + cfg::DEFAULTS[:stderr_path] ||= "/dev/null" + cfg::DEFAULTS[:stdout_path] ||= "/dev/null" + cfg::RACKUP[:daemonized] = true +end +``` + +想要真正理解上述代码的工作,我们需要理解广义上的 daemonize 过程,在 Unix-like 的系统中,一个 [daemon](https://en.wikipedia.org/wiki/Daemon_(computing))(守护进程)是运行在后台不直接被用户操作的进程;一个进程想要变成守护进程通常需要做以下的事情: + +1. 执行 `fork` 和 `exit` 来创建一个后台任务; +2. 从 tty 的控制中分离、创建一个新的 session 并成为新的 session 和进程组的管理者; +3. 将根目录 `/` 设置为当前进程的工作目录; +4. 将 umask 更新成 `0` 以提供自己的权限管理掩码; +5. 使用日志文件、控制台或者 `/dev/null` 设备作为标准输入、输出和错误; + +在 `.daemonize!` 方法中我们总共使用 fork 创建了两个进程,整个过程涉及三个进程的协作,其中 grandparent 是启动 Unicorn 的进程一般指终端,parent 是用来启动 Unicorn 服务的进程,master 就是 Unicorn 服务中的主进程,三个进程有以下的关系: + +![unicorn-daemonize](images/rack-unicorn/unicorn-daemonize.png) + +上述的三个进程中,grandparent 表示用于启动 Unicorn 进程的终端,parent 只是一个用于设置进程状态和掩码的中间进程,它在启动 Unicorn 的 master 进程后就会立刻退出。 + +在这里,我们会分三个部分分别介绍 grandparent、parent 和 master 究竟做了哪些事情;首先,对于 grandparent 进程来说,我们实际上运行了以下的代码: + +```ruby +def self.daemonize!(options) + $stdin.reopen("/dev/null") + rd, wr = IO.pipe + wr.close + + # fork + + master_pid = (rd.readpartial(16) rescue nil).to_i + unless master_pid > 1 + warn "master failed to start, check stderr log for details" + exit!(1) + end +end +``` + +通过 `IO.pipe` 方法创建了一对 Socket 节点,其中一个用于读,另一个用于写,在这里由于当前进程 grantparent 不需要写,所以直接将写的一端 `#close`,保留读的一端等待 Unicorn master 进程发送它的 `pid`,如果 master 没有成功启动就会报错,这也是 grandparent 进程的主要作用。 + +对于 parent 进程来说做的事情其实就更简单了,在 `fork` 之后会直接将读的一端执行 `#close`,这样无论是当前进程 parent 还是 parent fork 出来的进程都无法通过 `rd` 读取数据: + +```ruby +def self.daemonize!(options) + $stdin.reopen("/dev/null") + rd, wr = IO.pipe + + # fork + + rd.close + Process.setsid + exit if fork +end +``` + +在 parent 进程中,我们通过 `Process.setsid` 将当前的进程设置为新的 session 和进程组的管理者,从 tty 中分离;最后直接执行 `fork` 创建一个新的进程 master 并退出 parent 进程,parent 进程的作用其实就是为了启动新 Unicorn master 进程。 + +```ruby +def self.daemonize!(options) + cfg = Unicorn::Configurator + $stdin.reopen("/dev/null") + + rd, wr = IO.pipe + rd.close + + Process.setsid + + # fork + + options[:ready_pipe] = wr + cfg::DEFAULTS[:stderr_path] ||= "/dev/null" + cfg::DEFAULTS[:stdout_path] ||= "/dev/null" + cfg::RACKUP[:daemonized] = true +end +``` + +新的进程 Unicorn master 就是一个不关联在任何 tty 的一个后台进程,不过到这里为止也仅仅创建另一个进程,Unicorn 还无法对外提供服务,我们将可读的 Socket `wr` 写入 `options` 中,在 webserver 成功启动后将通过 `IO.pipe` 创建的一对 Socket 将信息回传给 grandparent 进程通知服务启动的结果。 + +### 初始化服务 + +HTTP 服务在初始化时其实也没有做太多的事情,只是对 Rack 应用进行存储并初始化了一些实例变量: + +```ruby +From: lib/unicorn/http_server.rb @ line 69: +Owner: Unicorn::HttpServer + +def initialize(app, options = {}) + @app = app + @request = Unicorn::HttpRequest.new + @reexec_pid = 0 + @ready_pipe = options.delete(:ready_pipe) + @init_listeners = options[:listeners] ? options[:listeners].dup : [] + self.config = Unicorn::Configurator.new(options) + self.listener_opts = {} + + @self_pipe = [] + @workers = {} + @sig_queue = [] + @pid = nil + + config.commit!(self, :skip => [:listeners, :pid]) + @orig_app = app + @queue_sigs = [:WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU] +end +``` + +在 `.daemonize!` 方法中存储的 `ready_pipe` 在这时被当前的 `HttpServer` 对象持有,之后会通过这个管道上传数据。 + +### 启动服务 + +`HttpServer` 服务的启动一看就是这个 `#start` 实例方法控制的,在这个方法中总过做了两件比较重要的事情: + +```ruby +From: lib/unicorn/http_server.rb @ line 120: +Owner: Unicorn::HttpServer + +def start + @queue_sigs.each { |sig| trap(sig) { @sig_queue << sig; awaken_master } } + trap(:CHLD) { awaken_master } + + self.pid = config[:pid] + + spawn_missing_workers + self +end +``` + +第一件事情是将构造器中初始化的 `queue_sigs` 实例变量中的全部信号,通过 `trap` 为信号提供用于响应事件的代码。 + +第二件事情就是通过 `#spawn_missing_workers` 方法 `fork` 当前 master 进程创建一系列的 worker 进程: + +```ruby +From: lib/unicorn/http_server.rb @ line 531: +Owner: Unicorn::HttpServer + +def spawn_missing_workers + worker_nr = -1 + until (worker_nr += 1) == @worker_processes + worker = Unicorn::Worker.new(worker_nr) + before_fork.call(self, worker) + + pid = fork + + unless pid + after_fork_internal + worker_loop(worker) + exit + end + + @workers[pid] = worker + worker.atfork_parent + end +rescue => e + @logger.error(e) rescue nil + exit! +end +``` + +在这种调用了 `fork` 的方法中,我们还是将其一分为二来看,在这里就是 master 和 worker 进程,对于 master 进程来说: + +```ruby +From: lib/unicorn/http_server.rb @ line 531: +Owner: Unicorn::HttpServer + +def spawn_missing_workers + worker_nr = -1 + until (worker_nr += 1) == @worker_processes + worker = Unicorn::Worker.new(worker_nr) + before_fork.call(self, worker) + + pid = fork + + # ... + + @workers[pid] = worker + end +rescue => e + @logger.error(e) rescue nil + exit! +end +``` + +通过一个 until 循环,master 进程能够创建 `worker_processes` 个 worker 进程,在每个循环中,上述方法都会创建一个 `Unicorn::Worker` 对象并在 `fork` 之后,将子进程的 `pid` 和 `worker` 以键值对的形式存到 `workers` 这个实例变量中。 + +`before_fork` 中存储的 block 是我们非常熟悉的,其实就是向服务器的日志中追加内容: + +```ruby +DEFAULTS = { + # ... + :after_fork => lambda { |server, worker| + server.logger.info("worker=#{worker.nr} spawned pid=#{$$}") + }, + :before_fork => lambda { |server, worker| + server.logger.info("worker=#{worker.nr} spawning...") + }, + :before_exec => lambda { |server| + server.logger.info("forked child re-executing...") + }, + :after_worker_exit => lambda { |server, worker, status| + m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}" + if status.success? + server.logger.info(m) + else + server.logger.error(m) + end + }, + :after_worker_ready => lambda { |server, worker| + server.logger.info("worker=#{worker.nr} ready") + }, + # ... +} +``` + +所有日志相关的输出大都在 `Unicorn::Configurator` 类中作为常量定义起来,并在初始化时作为缺省值赋值到 `HttpServer` 相应的实例变量上。而对于真正处理 HTTP 请求的 worker 进程来说,就会进入更加复杂的逻辑了: + +```ruby +def spawn_missing_workers + worker_nr = -1 + until (worker_nr += 1) == @worker_processes + worker = Unicorn::Worker.new(worker_nr) + before_fork.call(self, worker) + + # fork + + after_fork_internal + worker_loop(worker) + exit + end +rescue => e + @logger.error(e) rescue nil + exit! +end +``` + +在这里调用了两个实例方法,其中一个是 `#after_fork_internal`,另一个是 `#worker_loop` 方法,前者用于处理一些 `fork` 之后收尾的逻辑,比如关闭仅在 master 进程中使用的 `self_pipe`: + +```ruby +def after_fork_internal + @self_pipe.each(&:close).clear + @ready_pipe.close if @ready_pipe + Unicorn::Configurator::RACKUP.clear + @ready_pipe = @init_listeners = @before_exec = @before_fork = nil +end +``` + +而后者就是 worker 持续监听 Socket 输入并处理请求的循环了。 + +### 循环 + +当我们开始运行 worker 中的循环时,就开始监听 Socket 上的事件,整个过程还是比较直观的: + +```ruby +From: lib/unicorn/http_server.rb @ line 681: +Owner: Unicorn::HttpServer + +def worker_loop(worker) + ppid = @master_pid + readers = init_worker_process(worker) + ready = readers.dup + @after_worker_ready.call(self, worker) + + begin + tmp = ready.dup + while sock = tmp.shift + if client = sock.kgio_tryaccept + process_client(client) + end + end + + unless nr == 0 + tmp = ready.dup + redo + end + + ppid == Process.ppid or return + + ret = IO.select(readers, nil, nil, @timeout) and ready = ret[0] + rescue => e + # ... + end while readers[0] +end +``` + +如果当前 Socket 上有等待处理的 HTTP 请求,就会执行 `#process_client` 方法队请求进行处理,在这里调用了 Rack 应用的 `#call` 方法得到了三元组: + +```ruby +From: lib/unicorn/http_server.rb @ line 605: +Owner: Unicorn::HttpServer + +def process_client(client) + status, headers, body = @app.call(env = @request.read(client)) + + begin + return if @request.hijacked? + + @request.headers? or headers = nil + http_response_write(client, status, headers, body, + @request.response_start_sent) + ensure + body.respond_to?(:close) and body.close + end + + unless client.closed? + client.shutdown + client.close + end +rescue => e + handle_error(client, e) +end +``` + +请求的解析是通过 `Request#read` 处理的,而向 Socket 写 HTTP 响应是通过 `#http_response_write` 方法来完成的,在这里有关 HTTP 请求的解析和响应的处理都属于一些不重要的实现细节,在这里也就不展开介绍了;当我们已经响应了用户的请求就可以将当前 Socket 直接关掉,断掉这个 TCP 连接了。 + +## 调度 + +我们在上面已经通过多次 `fork` 启动了用于管理 Unicorn worker 进程的 master 以及多个 worker 进程,由于 Unicorn webserver 涉及了多个进程,所以需要进程之间进行调度。 + +在 Unix 中,进程的调度往往都是通过信号来进行的,`HttpServer#join` 就在 Unicorn 的 master 进程上监听外界发送的各种信号,不过在监听信号之前,要通过 `ready_pipe` 通知 grandparent 进程当前 master 进程已经启动完毕: + +```ruby +From: lib/unicorn/http_server.rb @ line 267: +Owner: Unicorn::HttpServer + +def join + respawn = true + last_check = time_now + + proc_name 'master' + logger.info "master process ready" # test_exec.rb relies on this message + if @ready_pipe + begin + @ready_pipe.syswrite($$.to_s) + rescue => e + logger.warn("grandparent died too soon?: #{e.message} (#{e.class})") + end + @ready_pipe = @ready_pipe.close rescue nil + end + + # ... +end +``` + +当 grandparent 进程,也就是执行 Unicorn 命令的进程接收到命令退出之后,就可以继续做其他的操作了,而 master 进程会进入一个 while 循环持续监听外界发送的信号: + +```ruby +def join + # ... + + begin + reap_all_workers + case @sig_queue.shift + # ... + when :WINCH + respawn = false + soft_kill_each_worker(:QUIT) + self.worker_processes = 0 + when :TTIN + respawn = true + self.worker_processes += 1 + when :TTOU + self.worker_processes -= 1 if self.worker_processes > 0 + when # ... + end + rescue => e + Unicorn.log_error(@logger, "master loop error", e) + end while true + + # ... +end +``` + +这一部分的几个信号都会改变当前 Unicorn worker 的进程数,无论是 `TTIN`、`TTOU` 还是 `WINCH` 信号最终都修改了 `worker_processes` 变量,其中 `#soft_kill_each_worker` 方法向所有的 Unicorn worker 进程发送了 `QUIT` 信号。 + +除了一些用于改变当前 worker 数量的信号,Unicorn 的 master 进程还监听了一些用于终止 master 进程或者更新配置文件的信号。 + +```ruby +def join + # ... + + begin + reap_all_workers + case @sig_queue.shift + # ... + when :QUIT + break + when :TERM, :INT + stop(false) + break + when :HUP + respawn = true + if config.config_file + load_config! + else # exec binary and exit if there's no config file + reexec + end + when # ... + end + rescue => e + Unicorn.log_error(@logger, "master loop error", e) + end while true + + # ... +end +``` + +无论是 `QUIT` 信号还是 `TERM`、`INT` 最终都执行了 `#stop` 方法,选择使用不同的信号干掉当前 master 管理的 worker 进程: + +```ruby +From: lib/unicorn/http_server.rb @ line 339: +Owner: Unicorn::HttpServer + +def stop(graceful = true) + self.listeners = [] + limit = time_now + timeout + until @workers.empty? || time_now > limit + if graceful + soft_kill_each_worker(:QUIT) + else + kill_each_worker(:TERM) + end + sleep(0.1) + reap_all_workers + end + kill_each_worker(:KILL) +end +``` + +上述方法其实非常容易理解,它会根据传入的参数选择强制终止或者正常停止所有的 worker 进程,这样整个 Unicorn 服务才真正停止并不再为外界提供服务了。 + +当我们向 master 发送 `TTIN` 或者 `TTOU` 信号时只是改变了实例变量 `worker_process` 的值,还并没有 `fork` 出新的进程,这些操作都是在 `nil` 条件中完成的: + +```ruby +def join + # ... + + begin + reap_all_workers + case @sig_queue.shift + when nil + if (last_check + @timeout) >= (last_check = time_now) + sleep_time = murder_lazy_workers + else + sleep_time = @timeout/2.0 + 1 + end + maintain_worker_count if respawn + master_sleep(sleep_time) + when # ... + end + rescue => e + Unicorn.log_error(@logger, "master loop error", e) + end while true + + # ... +end +``` + +当 `@sig_queue.shift` 返回 `nil` 时也就代表当前没有需要处理的信号,如果需要创建新的进程或者停掉进程就会通过 `#maintain_worker_count` 方法,之后 master 进程会陷入睡眠直到被再次唤醒。 + +```ruby +From: lib/unicorn/http_server.rb @ line 561: +Owner: Unicorn::HttpServer + +def maintain_worker_count + (off = @workers.size - worker_processes) == 0 and return + off < 0 and return spawn_missing_workers + @workers.each_value { |w| w.nr >= worker_processes and w.soft_kill(:QUIT) } +end +``` + +通过创建缺失的进程并关闭多余的进程,我们能够实时的保证整个 Unicorn 服务中的进程数与期望的配置完全相同。 + +在 Unicorn 的服务中,不仅 master 进程能够接收到来自用户或者其他进程的各种信号,worker 进程也能通过以下的方式将接受到的信号交给 master 处理:
 +```ruby +From: lib/unicorn/http_server.rb @ line 120: +Owner: Unicorn::HttpServer + +def start + # ... + @queue_sigs.each { |sig| trap(sig) { @sig_queue << sig; awaken_master } } + trap(:CHLD) { awaken_master } +end + +From: lib/unicorn/http_server.rb @ line 391: +Owner: Unicorn::HttpServer + +def awaken_master + return if $$ != @master_pid + @self_pipe[1].kgio_trywrite('.') +end +``` + +所以即使向 worker 进程发送 `TTIN` 或者 `TTOU` 等信号也能够改变整个 Unicorn 服务中 worker 进程的个数。 + +## 多进程模型 + +总的来说,Unicorn 作为 Web 服务使用了多进程的模型,通过一个 master 进程来管理多个 worker 进程,其中 master 进程不负责处理客户端的 HTTP 请求,多个 worker 进程监听同一组 Socket: + +![unicorn-io-mode](images/rack-unicorn/unicorn-io-model.png) + +一组 worker 进程在监听 Socket 时,如果发现当前的 Socket 有等待处理的请求时就会在当前的进程中直接通过 `#process_client` 方法处理,整个过程会阻塞当前的进程,而多进程阻塞 I/O 的方式没有办法接受慢客户端造成的性能损失,只能通过反向代理 nginx 才可以解决这个问题。 + +![unicorn-multi-processes](images/rack-unicorn/unicorn-multi-processes.png) + +在 Unicorn 中,worker 之间的负载均衡是由操作系统解决的,所有的 worker 是通过 `.select` 方法等待共享 Socket 上的请求,一旦出现可用的 worker,就可以立即进行处理,避开了其他负载均衡算法没有考虑到请求处理时间的问题。 + +## 总结 + +Unicorn 的源代码其实是作者读过的可读性最差的 Ruby 代码了,很多 Ruby 代码的风格写得跟 C 差不多,看起来也比较头疼,可能是需要处理很多边界条件以及信号,涉及较多底层的进程问题;虽然代码风格上看起来确实让人头疼,不过实现还是值得一看的,重要的代码大都包含在 unicorn.rb 和 http_server.rb 两个文件中,阅读时也不需要改变太多的上下文。 + +相比于 WEBrick 的单进程多线程的 I/O 模型,Unicorn 的多进程模型有很多优势,一是能够充分利用多核 CPU 的性能,其次能够通过 master 来管理并监控 Unicorn 中包含的一组 worker 并提供了零宕机部署的功能,除此之外,多进程的 I/O 模型还不在乎当前的应用是否是线程安全的,所以不会出现线程竞争等问题,不过 Unicorn 由于 `fork` 了大量的 worker 进程,如果长时间的在 Unicorn 上运行内存泄露的应用会非常耗费内存资源,可以考虑使用 [unicorn-worker-killer](https://github.com/kzk/unicorn-worker-killer) 来自动重启。 + +## Reference + ++ [How To Optimize Unicorn Workers in a Ruby on Rails App](https://www.digitalocean.com/community/tutorials/how-to-optimize-unicorn-workers-in-a-ruby-on-rails-app) ++ [Ruby Web 服务器:这十五年](https://read01.com/zh-hk/zm5B.html#.Wf0oLduB0sk) ++ [unicorn-worker-killer](https://github.com/kzk/unicorn-worker-killer) ++ [Daemon (computing)](https://en.wikipedia.org/wiki/Daemon_(computing)) ++ [Nginx 与 Unicorn](http://jiangpeng.info/blogs/2014/03/10/nginx-unicorn.html) ++ [Unicorn!](https://github.com/blog/517-unicorn) + diff --git a/contents/rack/rack-webrik.md b/contents/rack/rack-webrik.md new file mode 100644 index 0000000..4bf75e7 --- /dev/null +++ b/contents/rack/rack-webrik.md @@ -0,0 +1,459 @@ +# 浅谈 WEBrick 的实现 + ++ [谈谈 Rack 协议与实现](https://draveness.me/rack) ++ [浅谈 WEBrick 的实现](https://draveness.me/rack-webrick) ++ [浅谈 Thin 的事件驱动模型](https://draveness.me/rack-thin) ++ [浅谈 Unicorn 的多进程模型](https://draveness.me/rack-unicorn) ++ [浅谈 Puma 的实现](https://draveness.me/rack-puma) + +这篇文章会介绍在开发环境中最常用的应用容器 WEBrick 的实现原理,除了通过源代码分析之外,我们也会介绍它的 IO 模型以及一些特点。 + +在 GitHub 上,WEBrick 从 2003 年的六月份就开始开发了,有着十几年历史的 WEBrick 的实现非常简单,总共只有 4000 多行的代码: + +```ruby +$ loc_counter . +40 files processed +Total 6918 lines +Empty 990 lines +Comments 1927 lines +Code 4001 lines +``` + +## WEBrick 的实现 + +由于 WEBrick 是 Rack 中内置的处理器,所以与 Unicorn 和 Puma 这种第三方开发的 webserver 不同,WEBrick 的处理器是在 Rack 中实现的,而 WEBrick 的运行也都是从这个处理器的开始的。 + +```ruby +module Rack + module Handler + class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet + def self.run(app, options={}) + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : nil + + options[:BindAddress] = options.delete(:Host) || default_host + options[:Port] ||= 8080 + @server = ::WEBrick::HTTPServer.new(options) + @server.mount "/", Rack::Handler::WEBrick, app + yield @server if block_given? + @server.start + end + end + end +end +``` + +我们在上一篇文章 [谈谈 Rack 协议与实现](https://draveness.me/rack) 中介绍 Rack 的实现原理时,最终调用了上述方法,从这里开始大部分的实现都与 WEBrick 有关了。 + +在这里,你可以看到方法会先处理传入的参数比如:地址、端口号等等,在这之后会使用 WEBrick 提供的 `HTTPServer` 来处理 HTTP 请求,调用 `mount` 在根路由上挂载应用和处理器 `Rack::Handler::WEBrick` 接受请求,最后执行 `#start` 方法启动服务器。 + +### 初始化服务器 + +`HTTPServer` 的初始化分为两个阶段,一部分是 `HTTPServer` 的初始化,另一部分调用父类的 `initialize` 方法,在自己构造器中,会配置当前服务器能够处理的 HTTP 版本并初始化新的 `MountTable` 实例: + +```ruby +From: lib/webrick/httpserver.rb @ line 46: +Owner: #<Class:WEBrick::HTTPServer> + +def initialize(config={}, default=Config::HTTP) + super(config, default) + @http_version = HTTPVersion::convert(@config[:HTTPVersion]) + + @mount_tab = MountTable.new + if @config[:DocumentRoot] + mount("/", HTTPServlet::FileHandler, @config[:DocumentRoot], + @config[:DocumentRootOptions]) + end + + unless @config[:AccessLog] + @config[:AccessLog] = [ + [ $stderr, AccessLog::COMMON_LOG_FORMAT ], + [ $stderr, AccessLog::REFERER_LOG_FORMAT ] + ] + end + + @virtual_hosts = Array.new +end +``` + +在父类 `GenericServer` 中初始化了用于监听端口号的 Socket 连接: + +```ruby +From: lib/webrick/server.rb @ line 185: +Owner: #<Class:WEBrick::GenericServer> + +def initialize(config={}, default=Config::General) + @config = default.dup.update(config) + @status = :Stop + + @listeners = [] + listen(@config[:BindAddress], @config[:Port]) + if @config[:Port] == 0 + @config[:Port] = @listeners[0].addr[1] + end +end +``` + +每一个服务器都会在初始化的时候创建一系列的 `listener` 用于监听地址和端口号组成的元组,其内部调用了 `Utils` 模块中定义的方法: + +```ruby +From: lib/webrick/server.rb @ line 127: +Owner: #<Class:WEBrick::GenericServer> + +def listen(address, port) + @listeners += Utils::create_listeners(address, port) +end + +From: lib/webrick/utils.rb @ line 61: +Owner: #<Class:WEBrick::Utils> + +def create_listeners(address, port) + sockets = Socket.tcp_server_sockets(address, port) + sockets = sockets.map {|s| + s.autoclose = false + ts = TCPServer.for_fd(s.fileno) + s.close + ts + } + return sockets +end +module_function :create_listeners +``` + +在 `.create_listeners` 方法中调用了 `.tcp_server_sockets` 方法由于初始化一组 `Socket` 对象,最后得到一个数组的 `TCPServer` 实例。 + +### 挂载应用 + +在使用 `WEBrick` 启动服务的时候,第二步就是将处理器和 Rack 应用挂载到根路由下: + +```ruby +@server.mount "/", Rack::Handler::WEBrick, app +``` + +`#mount` 方法其实是一个比较简单的方法,因为我们在构造器中已经初始化了 `MountTable` 对象,所以这一步只是将传入的多个参数放到这个表中: + +```ruby +From: lib/webrick/httpserver.rb @ line 155: +Owner: WEBrick::HTTPServer + +def mount(dir, servlet, *options) + @mount_tab[dir] = [ servlet, options ] +end +``` + +`MountTable` 是一个包含从路由到 Rack 处理器一个 App 的映射表: + +![mounttable-and-applications](images/rack-webrick/mounttable-and-applications.png) + +当执行了 `MountTable` 的 `#compile` 方法时,上述的对象就会将表中的所有键按照加入的顺序逆序拼接成一个如下的正则表达式用来匹配传入的路由: + +```ruby +^(/|/admin|/user)(?=/|$) +``` + +上述正则表达式在使用时如果匹配到了指定的路由就会返回 `$&` 和 `$'` 两个部分,前者表示整个匹配的文本,后者表示匹配文本后面的字符串。 + +### 启动服务器 + +在 `Rack::Handler::WEBrick` 中的 `.run` 方法先初始化了服务器,将处理器和应用挂载到了根路由上,在最后执行 `#start` 方法启动服务器: + +```ruby +From: lib/webrick/server.rb @ line 152: +Owner: WEBrick::GenericServer + +def start(&block) + raise ServerError, "already started." if @status != :Stop + + @status = :Running + begin + while @status == :Running + begin + if svrs = IO.select([*@listeners], nil, nil, 2.0) + svrs[0].each{ |svr| + sock = accept_client(svr) + start_thread(sock, &block) + } + end + rescue Errno::EBADF, Errno::ENOTSOCK, IOError, StandardError => ex + rescue Exception => ex + raise + end + end + ensure + cleanup_listener + @status = :Stop + end +end +``` + +由于原方法的实现比较复杂不容易阅读,在这里对方法进行了简化,省略了向 logger 中输出内容、处理服务的关闭以及执行回调等功能。 + +我们可以理解为上述方法通过 `.select` 方法对一组 Socket 进行监听,当有消息需要处理时就依次执行 `#accept_client` 和 `#start_thread` 两个方法处理来自客户端的请求: + +```ruby +From: lib/webrick/server.rb @ line 254: +Owner: WEBrick::GenericServer + +def accept_client(svr) + sock = nil + begin + sock = svr.accept + sock.sync = true + Utils::set_non_blocking(sock) + rescue Errno::ECONNRESET, Errno::ECONNABORTED, + Errno::EPROTO, Errno::EINVAL + rescue StandardError => ex + msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}" + @logger.error msg + end + return sock +end +``` + +WEBrick 在 `#accept_client` 方法中执行了 `#accept` 方法来得到一个 TCP 客户端 Socket,同时会通过 `set_non_blocking` 将该 Socket 变成非阻塞的,最后在方法末尾返回创建的 Socket。 + +在 `#start_thread` 方法中会**开启一个新的线程**,并在新的线程中执行 `#run` 方法来处理请求: + +```ruby +From: lib/webrick/server.rb @ line 278: +Owner: WEBrick::GenericServer + +def start_thread(sock, &block) + Thread.start { + begin + Thread.current[:WEBrickSocket] = sock + run(sock) + rescue Errno::ENOTCONN, ServerError, Exception + ensure + Thread.current[:WEBrickSocket] = nil + sock.close + end + } +end +``` + +### 处理请求 + +所有的请求都不会由 `GenericServer` 这个通用的服务器来处理,它只处理通用的逻辑,对于 HTTP 请求的处理都是在 `HTTPServer#run` 中完成的: + +```ruby +From: lib/webrick/httpserver.rb @ line 69: +Owner: WEBrick::HTTPServer + +def run(sock) + while true + res = HTTPResponse.new(@config) + req = HTTPRequest.new(@config) + server = self + begin + timeout = @config[:RequestTimeout] + while timeout > 0 + break if sock.to_io.wait_readable(0.5) + break if @status != :Running + timeout -= 0.5 + end + raise HTTPStatus::EOFError if timeout <= 0 || @status != :Running + raise HTTPStatus::EOFError if sock.eof? + req.parse(sock) + res.request_method = req.request_method + res.request_uri = req.request_uri + res.request_http_version = req.http_version + self.service(req, res) + rescue HTTPStatus::EOFError, HTTPStatus::RequestTimeout, HTTPStatus::Error => ex + res.set_error(ex) + rescue HTTPStatus::Status => ex + res.status = ex.code + rescue StandardError => ex + res.set_error(ex, true) + ensure + res.send_response(sock) if req.request_line + end + break if @http_version < "1.1" + end +end +``` + +对 HTTP 协议了解的读者应该能从上面的代码中看到很多与 HTTP 协议相关的东西,比如 HTTP 的版本号、方法、URL 等等,上述方法总共做了三件事情,等待监听的 Socket 变得可读,执行 `#parse` 方法解析 Socket 上的数据,通过 `#service` 方法完成处理请求的响应,首先是对 Socket 上的数据进行解析: + +```ruby +From: lib/webrick/httprequest.rb @ line 192: +Owner: WEBrick::HTTPRequest + +def parse(socket=nil) + @socket = socket + begin + @peeraddr = socket.respond_to?(:peeraddr) ? socket.peeraddr : [] + @addr = socket.respond_to?(:addr) ? socket.addr : [] + rescue Errno::ENOTCONN + raise HTTPStatus::EOFError + end + + read_request_line(socket) + if @http_version.major > 0 + # ... + end + return if @request_method == "CONNECT" + return if @unparsed_uri == "*" + + begin + setup_forwarded_info + @request_uri = parse_uri(@unparsed_uri) + @path = HTTPUtils::unescape(@request_uri.path) + @path = HTTPUtils::normalize_path(@path) + @host = @request_uri.host + @port = @request_uri.port + @query_string = @request_uri.query + @script_name = "" + @path_info = @path.dup + rescue + raise HTTPStatus::BadRequest, "bad URI `#{@unparsed_uri}'." + end + + if /close/io =~ self["connection"] + # deal with keep alive + end +end +``` + +由于 HTTP 协议本身就比较复杂,请求中包含的信息也非常多,所以在这里用于**解析** HTTP 请求的代码也很多,想要了解 WEBrick 是如何解析 HTTP 请求的可以看 httprequest.rb 文件中的代码,在处理了 HTTP 请求之后,就开始执行 `#service` 响应该 HTTP 请求了: + +```ruby +From: lib/webrick/httpserver.rb @ line 125: +Owner: WEBrick::HTTPServer + +def service(req, res) + servlet, options, script_name, path_info = search_servlet(req.path) + raise HTTPStatus::NotFound, "`#{req.path}' not found." unless servlet + req.script_name = script_name + req.path_info = path_info + si = servlet.get_instance(self, *options) + si.service(req, res) +end +``` + +在这里我们会从上面提到的 `MountTable` 中找出在之前注册的处理器 handler 和 Rack 应用: + +```ruby +From: lib/webrick/httpserver.rb @ line 182: +Owner: WEBrick::HTTPServer + +def search_servlet(path) + script_name, path_info = @mount_tab.scan(path) + servlet, options = @mount_tab[script_name] + if servlet + [ servlet, options, script_name, path_info ] + end +end +``` + +得到了处理器 handler 之后,通过 `.get_instance` 方法创建一个新的实例,这个方法在大多数情况下等同于初始化方法 `.new`,随后调用了该处理器 `Rack::WEBrick::Handler` 的 `#service` 方法,该方法是在 rack 工程中定义的: + +```ruby +From: rack/lib/handler/webrick.rb @ line 57: +Owner: Rack::Handler::WEBrick + +def service(req, res) + res.rack = true + env = req.meta_vars + env.delete_if { |k, v| v.nil? } + + env.update( + # ... + RACK_URL_SCHEME => ["yes", "on", "1"].include?(env[HTTPS]) ? "https" : "http", + # ... + ) + + status, headers, body = @app.call(env) + begin + res.status = status.to_i + headers.each { |k, vs| + # ... + } + + body.each { |part| + res.body << part + } + ensure + body.close if body.respond_to? :close + end +end +``` + +由于上述方法也涉及了非常多 HTTP 协议的实现细节所以很多过程都被省略了,在上述方法中,我们先构建了应用的输入 `env` 哈希变量,然后通过执行 `#call` 方法将控制权交给 Rack 应用,最后获得一个由 `status`、`headers` 和 `body` 组成的三元组;在接下来的代码中,分别对这三者进行处理,为这次请求『填充』一个完成的 HTTP 请求。 + +到这里,最后由 `WEBrick::HTTPServer#run` 方法中的 `ensure` block 来结束整个 HTTP 请求的处理: + +```ruby +From: lib/webrick/httpserver.rb @ line 69: +Owner: WEBrick::HTTPServer + +def run(sock) + while true + res = HTTPResponse.new(@config) + req = HTTPRequest.new(@config) + server = self + begin + # ... + ensure + res.send_response(sock) if req.request_line + end + break if @http_version < "1.1" + end +end +``` + +在 `#send_reponse` 方法中,分别执行了 `#send_header` 和 `#send_body` 方法向当前的 Socket 中发送 HTTP 响应中的数据: + +```ruby +From: lib/webrick/httpresponse @ line 205: +Owner: WEBrick::HTTPResponse + +def send_response(socket) + begin + setup_header() + send_header(socket) + send_body(socket) + rescue Errno::EPIPE, Errno::ECONNRESET, Errno::ENOTCONN => ex + @logger.debug(ex) + @keep_alive = false + rescue Exception => ex + @logger.error(ex) + @keep_alive = false + end +end +``` + +所有向 Socket 中写入数据的工作最终都会由 `#_write_data` 这个方法来处理,将数据全部写入 Socket 中: + +```ruby +From: lib/webrick/httpresponse @ line 464: +Owner: WEBrick::HTTPResponse + +def _write_data(socket, data) + socket << data +end +``` + +从解析 HTTP 请求、调用 Rack 应用、创建 Response 到最后向 Socket 中写回数据,WEBrick 处理 HTTP 请求的部分就结束了。 + +## I/O 模型 + +通过对 WEBrick 源代码的阅读,我们其实已经能够了解整个 webserver 的工作原理,当我们启动一个 WEBrick 服务时只会启动一个进程,该进程会在指定的 ip 和端口上使用 `.select` 监听来自用户的所有 HTTP 请求: + +![webrick-io-mode](images/rack-webrick/webrick-io-model.png) + +当 `.select` 接收到来自用户的请求时,会为每一个请求创建一个新的 `Thread` 并在新的线程中对 HTTP 请求进行处理。 + +由于 WEBrick 在运行时只会启动一个进程,并没有其他的守护进程,所以它不够健壮,不能在发生问题时重启持续对外界提供服务,再加上 WEBrick 确实历史比较久远,代码的风格也不是特别的优雅,还有普遍知道的内存泄漏以及 HTTP 解析的问题,所以在生产环境中很少被使用。 + +虽然 WEBrick 有一些性能问题,但是作为 Ruby 自带的默认 webserver,在开发阶段使用 WEBrick 提供服务还是没有什么问题的。 + +## 总结 + +WEBrick 是 Ruby 社区中老牌的 webserver,虽然至今也仍然被广泛了解和使用,但是在生产环境中开发者往往会使用更加稳定的 Unicorn 和 Puma 代替它,我们选择在这个系列的文章中介绍它很大原因就是 WEBrick 的源代码与实现足够简单,我们很快就能了解一个 webserver 到底具备那些功能,在接下来的文章中我们就可以分析更加复杂的 webserver、了解更复杂的 IO 模型与实现了。 + +## Reference + ++ [Ruby on Rails Server options](https://stackoverflow.com/questions/4113299/ruby-on-rails-server-options) + + diff --git a/contents/rack/rack.md b/contents/rack/rack.md new file mode 100644 index 0000000..13fd418 --- /dev/null +++ b/contents/rack/rack.md @@ -0,0 +1,669 @@ +# 谈谈 Rack 的协议与实现 + ++ [谈谈 Rack 协议与实现](https://draveness.me/rack) ++ [浅谈 WEBrick 的实现](https://draveness.me/rack-webrick) ++ [浅谈 Thin 的事件驱动模型](https://draveness.me/rack-thin) ++ [浅谈 Unicorn 的多进程模型](https://draveness.me/rack-unicorn) ++ [浅谈 Puma 的实现](https://draveness.me/rack-puma) + +作为 Rails 开发者,基本上每天都与 Rails 的各种 API 以及数据库打交道,Rails 的世界虽然非常简洁,不过其内部的实现还是很复杂的,很多刚刚接触 Rails 的开发者可能都不知道 Rails 其实就是一个 [Rack](https://github.com/rack/rack) 应用,在这一系列的文章中,我们会分别介绍 Rack 以及一些常见的遵循 Rack 协议的 webserver 的实现原理。 + +![rack-logo](images/rack/rack-logo.png) + +不只是 Rails,几乎所有的 Ruby 的 Web 框架都是一个 Rack 的应用,除了 Web 框架之外,Rack 也支持相当多的 Web 服务器,可以说 Ruby 世界几乎一切与 Web 相关的服务都与 Rack 有关。 + +![rack-and-web-servers-frameworks](images/rack/rack-and-web-servers-frameworks.png) + +所以如果想要了解 Rails 或者其他 Web 服务底层的实现,那么一定需要了解 Rack 是如何成为应用容器(webserver)和应用框架之间的桥梁的,本文中介绍的是 2.0.3 版本的 rack。 + +## Rack 协议 + +在 Rack 的协议中,将 Rack 应用描述成一个可以响应 `call` 方法的 Ruby 对象,它仅接受来自外界的一个参数,也就是环境,然后返回一个只包含三个值的数组,按照顺序分别是状态码、HTTP Headers 以及响应请求的正文。 + +> A Rack application is a Ruby object (not a class) that responds to call. It takes exactly one argument, the environment and returns an Array of exactly three values: The status, the headers, and the body. + +![rack-protoco](images/rack/rack-protocol.png) + +Rack 在 webserver 和应用框架之间提供了一套最小的 API 接口,如果 webserver 都遵循 Rack 提供的这套规则,那么所有的框架都能通过协议任意地改变底层使用 webserver;所有的 webserver 只需要在 `Rack::Handler` 的模块中创建一个实现了 `.run` 方法的类就可以了: + +```ruby +module Rack + module Handler + class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet + def self.run(app, options={}) + # .. + end + end + end +end +``` + +这个类方法接受两个参数,分别是一个 Rack 应用对象和一个包含各种参数的 `options` 字典,其中可能包括自定义的 ip 地址和端口号以及各种配置,根据 Rack 协议,所有应用对象在接受到一个 `#call` 方法并且传入 `env` 时,都会返回一个三元组: + +![rack-app](images/rack/rack-app.png) + +最后的 `body` 响应体其实是一个由多个响应内容组成的数组,Rack 使用的 webserver 会将 `body` 中几个部分的连接到一起最后拼接成一个 HTTP 响应后返回。 + +## Rack 的使用 + +我们在大致了解 Rack 协议之后,其实可以从一段非常简单的代码入手来了解 Rack 是如何启动 webserver 来处理来自用户的请求的,我们可以在任意目录下创建如下所示的 config.ru 文件: + +```ruby +# config.ru + +run Proc.new { |env| ['200', {'Content-Type' => 'text/html'}, ['get rack\'d']] } +``` + +> 因为 `Proc` 对象也能够响应 `#call` 方法,所以上述的 Proc 对象也可以看做是一个 Rack 应用。 + +接下来,我们在同一目录使用 `rackup` 命令在命令行中启动一个 webserver 进程: + +```bash +$ rackup config.ru +[2017-10-26 22:59:26] INFO WEBrick 1.3.1 +[2017-10-26 22:59:26] INFO ruby 2.3.3 (2016-11-21) [x86_64-darwin16] +[2017-10-26 22:59:26] INFO WEBrick::HTTPServer#start: pid=83546 port=9292 +``` + +从命令的输出我们可以看到,使用 rackup 运行了一个 WEBrick 的进程,监听了 9292 端口,如果我们使用 curl 来访问对应的请求,就可以得到在 config.ru 文件中出现的 `'get rack\'d'` 文本: + +> 在这篇文章中,作者都会使用开源的工具 [httpie](https://github.com/jakubroztocil/httpie) 代替 curl 在命令行中发出 HTTP 请求,相比 curl 而言 httpie 能够提供与 HTTP 响应有关的更多信息。 + +```ruby +$ http http://localhost:9292 +HTTP/1.1 200 OK +Connection: Keep-Alive +Content-Type: text/html +Date: Thu, 26 Oct 2017 15:07:47 GMT +Server: WEBrick/1.3.1 (Ruby/2.3.3/2016-11-21) +Transfer-Encoding: chunked + +get rack'd +``` + +从上述请求返回的 HTTP 响应头中的信息,我们可以看到 WEBrick 确实按照 config.ru 文件中的代码对当前的 HTTP 请求进行了处理。 + +### 中间件 + +Rack 协议和中间件是 Rack 能达到今天地位不可或缺的两个功能或者说特性,Rack 协议规定了 webserver 和 Rack 应用之间应该如何通信,而 Rack 中间件能够在上层改变 HTTP 的响应或者请求,在不改变应用的基础上为 Rack 应用增加新的功能。 + +Rack 的中间件是一个实现了两个方法 `.initialize` 和 `#call` 的类,初始化方法会接受两个参数,分别是 `app` 和 `options` 字典,而 `#call` 方法接受一个参数也就是 HTTP 请求的环境参数 `env`,在这里我们创建了一个新的 Rack 中间件 `StatusLogger`: + +```ruby +class StatusLogger + def initialize(app, options={}) + @app = app + end + + def call(env) + status, headers, body = @app.call(env) + puts status + [status, headers, body] + end +end +``` + +在所有的 `#call` 方法中都**应该**调用 `app.call` 让应用对 HTTP 请求进行处理并在方法结束时将所有的参数按照顺序返回。 + +```ruby +use StatusLogger +run Proc.new { |env| ['200', {'Content-Type' => 'text/html'}, ['get rack\'d']] } +``` + +如果需要使用某一个 Rack 中间件只需要在当前文件中使用 `use` 方法,在每次接收到来自用户的 HTTP 请求时都会打印出当前响应的状态码。 + +```ruby +$ rackup +[2017-10-27 19:46:40] INFO WEBrick 1.3.1 +[2017-10-27 19:46:40] INFO ruby 2.3.3 (2016-11-21) [x86_64-darwin16] +[2017-10-27 19:46:40] INFO WEBrick::HTTPServer#start: pid=5274 port=9292 +200 +127.0.0.1 - - [27/Oct/2017:19:46:53 +0800] "GET / HTTP/1.1" 200 - 0.0004 +``` + +除了直接通过 `use` 方法直接传入 `StatusLogger` 中间件之外,我们也可以在 `use` 中传入配置参数,所有的配置都会通过 `options` 最终初始化一个中间件的实例,比如,我们有以下的中间件 `BodyTransformer`: + +```ruby +class BodyTransformer + def initialize(app, options={}) + @app = app + @count = options[:count] + end + + def call(env) + status, headers, body = @app.call(env) + body = body.map { |str| str[0...@count].upcase + str[@count..-1] } + [status, headers, body] + end +end +``` + +上述中间件会在每次调用时都将 Rack 应用返回的 `body` 中前 `count` 个字符变成大写的,我们可以在 config.ru 中添加一个新的中间件: + +```ruby +use StatusLogger +use BodyTransformer, count: 3 +run Proc.new { |env| ['200', {'Content-Type' => 'text/html'}, ['get rack\'d']] } +``` + +当我们再次使用 http 命令请求相同的 URL 时,就会获得不同的结果,同时由于我们保留了 `StatusLogger`,所以在 console 中也会打印出当前响应的状态码: + +```ruby +# session 1 +$ rackup +[2017-10-27 21:04:05] INFO WEBrick 1.3.1 +[2017-10-27 21:04:05] INFO ruby 2.3.3 (2016-11-21) [x86_64-darwin16] +[2017-10-27 21:04:05] INFO WEBrick::HTTPServer#start: pid=7524 port=9292 +200 +127.0.0.1 - - [27/Oct/2017:21:04:19 +0800] "GET / HTTP/1.1" 200 - 0.0005 + +# session 2 +$ http http://localhost:9292 +HTTP/1.1 200 OK +Connection: Keep-Alive +Content-Type: text/html +Date: Fri, 27 Oct 2017 13:04:19 GMT +Server: WEBrick/1.3.1 (Ruby/2.3.3/2016-11-21) +Transfer-Encoding: chunked + +GET rack'd +``` + +Rack 的中间件的使用其实非常简单,我们只需要定义符合要求的类,然后在合适的方法中返回合适的结果就可以了,在接下来的部分我们将介绍 Rack 以及中间件的实现原理。 + +## Rack 的实现原理 + +到这里,我们已经对 Rack 的使用有一些基本的了解了,包括如何使用 `rackup` 命令启动一个 webserver,也包括 Rack 的中间件如何使用,接下来我们就准备开始对 Rack 是如何实现上述功能进行分析了。 + +### rackup 命令 + +那么 `rackup` 到底是如何工作的呢,首先我们通过 `which` 命令来查找当前 `rackup` 的执行路径并打印出该文件的全部内容: + +```ruby +$ which rackup +/Users/draveness/.rvm/gems/ruby-2.3.3/bin/rackup + +$ cat /Users/draveness/.rvm/gems/ruby-2.3.3/bin/rackup +#!/usr/bin/env ruby_executable_hooks +# +# This file was generated by RubyGems. +# +# The application 'rack' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +version = ">= 0.a" + +if ARGV.first + str = ARGV.first + str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding + if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then + version = $1 + ARGV.shift + end +end + +load Gem.activate_bin_path('rack', 'rackup', version) +``` + +从上述文件中的注释中可以看到当前文件是由 RubyGems 自动生成的,在文件的最后由一个 `load` 方法加载了某一个文件中的代码,我们可以在 pry 中尝试运行一下这个命令。 + +首先,通过 `gem list` 命令得到当前机器中所有 rack 的版本,然后进入 pry 执行 `.activate_bin_path` 命令: + +```ruby +$ gem list "^rack$" + +*** LOCAL GEMS *** + +rack (2.0.3, 2.0.1, 1.6.8, 1.2.3) + +$ pry +[1] pry(main)> Gem.activate_bin_path('rack', 'rackup', '2.0.3') +=> "/Users/draveness/.rvm/gems/ruby-2.3.3/gems/rack-2.0.3/bin/rackup" + +$ cat /Users/draveness/.rvm/gems/ruby-2.3.3/gems/rack-2.0.3/bin/rackup +#!/usr/bin/env ruby + +require "rack" +Rack::Server.start +``` + +> `rackup` 命令定义在 rack 工程的 bin/rackup 文件中,在通过 rubygems 安装后会生成另一个加载该文件的可执行文建。 + +在最后打印了该文件的内容,到这里我们就应该知道 `.activate_bin_path` 方法会查找对应 gem 当前生效的版本,并返回文件的路径;在这个可执行文件中,上述代码只是简单的 `require` 了一下 rack 方法,之后运行 `.start` 启动了一个 `Rack::Server`。 + +### Server 的启动 + +从这里开始,我们就已经从 rackup 命令的执行进入了 rack 的源代码,可以直接使用 pry 找到 `.start` 方法所在的文件,从方法中可以看到当前类方法初始化了一个新的实例后,在新的对象上执行了 `#start` 方法: + +```ruby +$ pry +[1] pry(main)> require 'rack' +=> true +[2] pry(main)> $ Rack::Server.start + +From: lib/rack/server.rb @ line 147: +Owner: #<Class:Rack::Server> + +def self.start(options = nil) + new(options).start +end +``` + +### 初始化和配置 + +在 `Rack::Server` 启动的过程中初始化了一个新的对象,初始化的过程中其实也包含了整个服务器的配置过程: + +```ruby +From: lib/rack/server.rb @ line 185: +Owner: #<Class:Rack::Server> + +def initialize(options = nil) + @ignore_options = [] + + if options + @use_default_options = false + @options = options + @app = options[:app] if options[:app] + else + argv = defined?(SPEC_ARGV) ? SPEC_ARGV : ARGV + @use_default_options = true + @options = parse_options(argv) + end +end +``` + +在这个 `Server` 对象的初始化器中,虽然可以通过 `options` 从外界传入参数,但是当前类中仍然存在这个 `#options` 和 `#default_options` 两个实例方法: + +```ruby +From: lib/rack/server.rb @ line 199: +Owner: Rack::Server + +def options + merged_options = @use_default_options ? default_options.merge(@options) : @options + merged_options.reject { |k, v| @ignore_options.include?(k) } +end + +From: lib/rack/server.rb @ line 204: +Owner: Rack::Server + +def default_options + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : '0.0.0.0' + { + :environment => environment, + :pid => nil, + :Port => 9292, + :Host => default_host, + :AccessLog => [], + :config => "config.ru" + } +end +``` + +上述两个方法中处理了一些对象本身定义的一些参数,比如默认的端口号 9292 以及默认的 config 文件,config 文件也就是 `rackup` 命令接受的一个文件参数,文件中的内容就是用来配置一个 Rack 服务器的代码,在默认情况下为 config.ru,也就是如果文件名是 config.ru,我们不需要向 `rackup` 命令传任何参数,它会自动找当前目录的该文件: + +```ruby +$ rackup +[2017-10-27 09:00:34] INFO WEBrick 1.3.1 +[2017-10-27 09:00:34] INFO ruby 2.3.3 (2016-11-21) [x86_64-darwin16] +[2017-10-27 09:00:34] INFO WEBrick::HTTPServer#start: pid=96302 port=9292 +``` + +访问相同的 URL 能得到完全一致的结果,在这里就不再次展示了,有兴趣的读者可以亲自尝试一下。 + +### 『包装』应用 + +当我们执行了 `.initialize` 方法初始化了一个新的实例之后,接下来就会进入 `#start` 实例方法尝试启动一个 webserver 处理 config.ru 中定义的应用了: + +```ruby +From: lib/rack/server.rb @ line 258: +Owner: Rack::Server + +def start &blk + # ... + + wrapped_app + # .. + + server.run wrapped_app, options, &blk +end +``` + +我们已经从上述方法中删除了很多对于本文来说不重要的代码实现,所以上述方法中最重要的部分就是 `#wrapped_app` 方法,以及另一个 `#server` 方法,首先来看 `#wrapped_app` 方法的实现。 + + +```ruby +From: lib/rack/server.rb @ line 353: +Owner: Rack::Server + +def wrapped_app + @wrapped_app ||= build_app app +end +``` + +上述方法有两部分组成,分别是 `#app` 和 `#build_app` 两个实例方法,其中 `#app` 方法的调用栈比较复杂: + +![server-app-call-stack](images/rack/server-app-call-stack.png) + +整个方法在最终会执行 `Builder.new_from_string` 通过 Ruby 中元编程中经常使用的 `eval` 方法,将输入文件中的全部内容与两端字符串拼接起来,并直接执行这段代码: + +```ruby +From: lib/rack/builder.rb @ line 48: +Owner: Rack::Builder + +def self.new_from_string(builder_script, file="(rackup)") + eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app", + TOPLEVEL_BINDING, file, 0 +end +``` + +在 `eval` 方法中执行代码的作用其实就是如下所示的: + +```ruby +Rack::Builder.new { + use StatusLogger + use BodyTransformer, count: 3 + run Proc.new { |env| ['200', {'Content-Type' => 'text/html'}, ['get rack\'d']] } +}.to_app +``` + +我们先暂时不管这段代码是如何执行的,我们只需要知道上述代码存储了所有的中间件以及 Proc 对象,最后通过 `#to_app` 方法返回一个 Rack 应用。 + +在这之后会使用 `#build_app` 方法将所有的中间件都包括在 Rack 应用周围,因为所有的中间件也都是一个响应 `#call` 方法,返回三元组的对象,其实也就是一个遵循协议的 App,唯一的区别就是中间件中会调用初始化时传入的 Rack App: + +```ruby +From: lib/rack/server.rb @ line 343: +Owner: Rack::Server + +def build_app(app) + middleware[options[:environment]].reverse_each do |middleware| + middleware = middleware.call(self) if middleware.respond_to?(:call) + next unless middleware + klass, *args = middleware + app = klass.new(app, *args) + end + app +end +``` + +经过上述方法,我们在一个 Rack 应用周围一层一层包装上了所有的中间件,最后调用的中间件在整个调用栈中的最外层,当包装后的应用接受来自外界的请求时,会按照如下的方式进行调用: + +![wrapped-app](images/rack/wrapped-app.png) + +所有的请求都会先经过中间件,每一个中间件都会在 `#call` 方法内部调用另一个中间件或者应用,在接收到应用的返回之后会分别对响应进行处理最后由最先定义的中间件返回。 + +### 中间件的实现 + +在 Rack 中,中间件是由两部分的代码共同处理的,分别是 `Rack::Builder` 和 `Rack::Server` 两个类,前者包含所有的能够在 config.ru 文件中使用的 DSL 方法,当我们使用 `eval` 执行 config.ru 文件中的代码时,会先初始化一个 `Builder` 的实例,然后执行 `instance_eval` 运行代码块中的所有内容: + +```ruby +From: lib/rack/builder.rb @ line 53: +Owner: Rack::Builder + +def initialize(default_app = nil, &block) + @use, @map, @run, @warmup = [], nil, default_app, nil + instance_eval(&block) if block_given? +end +``` + +在这时,config.ru 文件中的代码就会在当前实例的环境下执行,文件中的 `#use` 和 `#run` 方法在调用时就会执行 `Builder` 的实例方法,我们可以先看一下 `#use` 方法是如何实现的: + +```ruby +From: lib/rack/builder.rb @ line 81: +Owner: Rack::Builder + +def use(middleware, *args, &block) + @use << proc { |app| middleware.new(app, *args, &block) } +end +``` + +上述方法会将传入的参数组合成一个接受 `app` 作为入参的 `Proc` 对象,然后加入到 `@use` 数组中存储起来,在这里并没有发生任何其他的事情,另一个 `#run` 方法的实现其实就更简单了: + +```ruby +From: lib/rack/builder.rb @ line 103: +Owner: Rack::Builder + +def run(app) + @run = app +end +``` + +它只是将传入的 `app` 对象存储到持有的 `@run` 实例变量中,如果我们想要获取当前的 `Builder` 生成的应用,只需要通过 `#to_app` 方法: + +```ruby +From: lib/rack/builder.rb @ line 144: +Owner: Rack::Builder + +def to_app + fail "missing run or map statement" unless @run + @use.reverse.inject(@run) { |a,e| e[a] } +end +``` + +上述方法将所有传入 `#use` 和 `#run` 命令的应用和中间件进行了组合,通过 `#inject` 方法达到了如下所示的效果: + +```ruby +# config.ru +use MiddleWare1 +use MiddleWare2 +run RackApp + +# equals to +MiddleWare1.new(MiddleWare2.new(RackApp))) +``` + +`Builder` 类其实简单来看就做了这件事情,将一种非常难以阅读的代码,变成比较清晰可读的 DSL,最终返回了一个中间件(也可以说是应用)对象,虽然在 `Builder` 中也包含其他的 DSL 语法元素,但是在这里都没有介绍。 + +上一小节提到的 `#build_app` 方法其实也只是根据当前的环境选择合适的中间件继续包裹到这个链式的调用中: + +```ruby +From: lib/rack/server.rb @ line 343: +Owner: Rack::Server + +def build_app(app) + middleware[options[:environment]].reverse_each do |middleware| + middleware = middleware.call(self) if middleware.respond_to?(:call) + next unless middleware + klass, *args = middleware + app = klass.new(app, *args) + end + app +end +``` + +在这里的 `#middleware` 方法可以被子类覆写,如果不覆写该方法会根据环境的不同选择不同的中间件数组包裹当前的应用: + +```ruby +From: lib/rack/server.rb @ line 229: +Owner: #<Class:Rack::Server> + +def default_middleware_by_environment + m = Hash.new {|h,k| h[k] = []} + m["deployment"] = [ + [Rack::ContentLength], + [Rack::Chunked], + logging_middleware, + [Rack::TempfileReaper] + ] + m["development"] = [ + [Rack::ContentLength], + [Rack::Chunked], + logging_middleware, + [Rack::ShowExceptions], + [Rack::Lint], + [Rack::TempfileReaper] + ] + m +end +``` + +`.default_middleware_by_environment` 中就包含了不同环境下应该使用的中间件,`#build_app` 会视情况选择中间件加载。 + +### webserver 的选择 + +在 `Server#start` 方法中,我们已经通过 `#wrapped_app` 方法将应用和中间件打包到了一起,然后分别执行 `#server` 和 `Server#run` 方法选择并运行 webserver,先来看 webserver 是如何选择的: + +```ruby +From: lib/rack/server.rb @ line 300: +Owner: Rack::Server + +def server + @_server ||= Rack::Handler.get(options[:server]) + unless @_server + @_server = Rack::Handler.default + end + @_server +end +``` + +如果我们在运行 `rackup` 命令时传入了 `server` 选项,例如 `rackup -s WEBrick`,就会直接使用传入的 webserver,否则就会使用默认的 Rack 处理器: + +```ruby +From: lib/rack/handler.rb @ line 46: +Owner: #<Class:Rack::Handler> + +def self.default + # Guess. + if ENV.include?("PHP_FCGI_CHILDREN") + Rack::Handler::FastCGI + elsif ENV.include?(REQUEST_METHOD) + Rack::Handler::CGI + elsif ENV.include?("RACK_HANDLER") + self.get(ENV["RACK_HANDLER"]) + else + pick ['puma', 'thin', 'webrick'] + end +end +``` + +在这个方法中,调用 `.pick` 其实最终也会落到 `.get` 方法上,在 `.pick` 中我们通过遍历传入的数组**尝试**对其进行加载: + +```ruby +From: lib/rack/handler.rb @ line 34: +Owner: #<Class:Rack::Handler> + +def self.pick(server_names) + server_names = Array(server_names) + server_names.each do |server_name| + begin + return get(server_name.to_s) + rescue LoadError, NameError + end + end + + raise LoadError, "Couldn't find handler for: #{server_names.join(', ')}." +end +``` + +`.get` 方法是用于加载 webserver 对应处理器的方法,方法中会通过一定的命名规范从对应的文件目录下加载相应的常量: + +```ruby +From: lib/rack/handler.rb @ line 11: +Owner: #<Class:Rack::Handler> + +def self.get(server) + return unless server + server = server.to_s + + unless @handlers.include? server + load_error = try_require('rack/handler', server) + end + + if klass = @handlers[server] + klass.split("::").inject(Object) { |o, x| o.const_get(x) } + else + const_get(server, false) + end + +rescue NameError => name_error + raise load_error || name_error +end +``` + +一部分常量是预先定义在 handler.rb 文件中的,另一部分是由各个 webserver 的开发者自己定义或者遵循一定的命名规范加载的: + +```ruby +register 'cgi', 'Rack::Handler::CGI' +register 'fastcgi', 'Rack::Handler::FastCGI' +register 'webrick', 'Rack::Handler::WEBrick' +register 'lsws', 'Rack::Handler::LSWS' +register 'scgi', 'Rack::Handler::SCGI' +register 'thin', 'Rack::Handler::Thin' +``` + +在默认的情况下,如果不在启动服务时指定服务器就会按照 puma、thin 和 webrick 的顺序依次尝试加载响应的处理器。 + +### webserver 的启动 + +当 Rack 已经使用中间件对应用进行包装并且选择了对应的 webserver 之后,我们就可以将处理好的应用作为参数传入 `WEBrick.run` 方法了: + +```ruby +module Rack + module Handler + class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet + def self.run(app, options={}) + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : nil + + options[:BindAddress] = options.delete(:Host) || default_host + options[:Port] ||= 8080 + @server = ::WEBrick::HTTPServer.new(options) + @server.mount "/", Rack::Handler::WEBrick, app + yield @server if block_given? + @server.start + end + end + end +end +``` + +所有遵循 Rack 协议的 webserver 都会实现上述 `.run` 方法接受 `app`、`options` 和一个 block 作为参数运行一个进程来处理所有的来自用户的 HTTP 请求,在这里就是每个 webserver 自己需要解决的了,它其实并不属于 Rack 负责的部门,但是 Rack 实现了一些常见 webserver 的 handler,比如 CGI、Thin 和 WEBrick 等等,这些 handler 的实现原理都不会包含在这篇文章中。 + +## Rails 和 Rack + +在了解了 Rack 的实现之后,其实我们可以发现 Rails 应用就是一堆 Rake 中间件和一个 Rack 应用的集合,在任意的工程中我们执行 `rake middleware` 的命令都可以得到以下的输出: + +```ruby +$ rake middleware +use Rack::Sendfile +use ActionDispatch::Static +use ActionDispatch::Executor +use ActiveSupport::Cache::Strategy::LocalCache::Middleware +use Rack::Runtime +use ActionDispatch::RequestId +use ActionDispatch::RemoteIp +use Rails::Rack::Logger +use ActionDispatch::ShowExceptions +use ActionDispatch::DebugExceptions +use ActionDispatch::Reloader +use ActionDispatch::Callbacks +use ActiveRecord::Migration::CheckPending +use Rack::Head +use Rack::ConditionalGet +use Rack::ETag +run ApplicationName::Application.routes +``` + +在这里包含了很多使用 `use` 加载的 Rack 中间件,当然在最后也包含一个 Rack 应用,也就是 `ApplicationName::Application.routes`,这个对象其实是一个 `RouteSet` 实例,也就是说在 Rails 中所有的请求在经过中间件之后都会先有一个路由表来处理,路由会根据一定的规则将请求交给其他控制器处理: + +![rails-application](images/rack/rails-application.png) + +除此之外,`rake middleware` 命令的输出也告诉我们 Rack 其实为我们提供了很多非常方便的中间件比如 `Rack::Sendfile` 等可以减少我们在开发一个 webserver 时需要处理的事情。 + +## 总结 + +Rack 协议可以说占领了整个 Ruby 服务端的市场,无论是常见的服务器还是框架都遵循 Rack 协议进行了设计,而正因为 Rack 以及 Rack 协议的存在我们在使用 Rails 或者 Sinatra 开发 Web 应用时才可以对底层使用的 webserver 进行无缝的替换,在接下来的文章中会逐一介绍不同的 webserver 是如何对 HTTP 请求进行处理以及它们拥有怎样的 I/O 模型。 + +## Reference + ++ [Rack · A modular Ruby webserver interface](https://github.com/rack/rack) ++ [Rack: a Ruby Webserver Interface](http://rack.github.io) ++ [Rack interface specification](http://rubydoc.info/github/rack/rack/master/file/SPEC) ++ [Rails on Rack](http://guides.rubyonrails.org/rails_on_rack.html) ++ [Rack Middleware](http://railscasts.com/episodes/151-rack-middleware) ++ [Introducing Rack](http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html) ++ [Ruby on Rails Server options](https://stackoverflow.com/questions/4113299/ruby-on-rails-server-options) + diff --git a/objc/README.md b/objc/README.md deleted file mode 100644 index f974393..0000000 --- a/objc/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# objc 源代码阅读 - -当前文件夹下的 objc-runtime 工程,是我在阅读 objc 源代码时所使用的版本,你可以 clone 整个仓库来进行调试,原工程地址为 [objc-runtime](https://github.com/RetVal/objc-runtime)。 - - -+ ObjC 源代码 - + [从 NSObject 的初始化了解 isa](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/从%20NSObject%20的初始化了解%20isa.md) - + [深入解析 ObjC 中方法的结构](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/深入解析%20ObjC%20中方法的结构.md) - + [从源代码看 ObjC 中消息的发送](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/从源代码看%20ObjC%20中消息的发送.md) - + [你真的了解 load 方法么?](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/你真的了解%20load%20方法么?.md) - + [懒惰的 initialize](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/懒惰的%20initialize%20方法.md) - + [自动释放池的前世今生](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/自动释放池的前世今生.md) - + [黑箱中的 retain 和 release](https://github.com/Draveness/iOS-Source-Code-Analyze/blob/master/objc/黑箱中的%20retain%20和%20release.md) - - diff --git a/objc/objc-runtime/$_3.JPG b/objc/objc-runtime/$_3.JPG deleted file mode 100644 index 7a3d1e9..0000000 Binary files a/objc/objc-runtime/$_3.JPG and /dev/null differ diff --git a/objc/objc-runtime/APPLE_LICENSE b/objc/objc-runtime/APPLE_LICENSE deleted file mode 100644 index fe81a60..0000000 --- a/objc/objc-runtime/APPLE_LICENSE +++ /dev/null @@ -1,367 +0,0 @@ -APPLE PUBLIC SOURCE LICENSE -Version 2.0 - August 6, 2003 - -Please read this License carefully before downloading this software. -By downloading or using this software, you are agreeing to be bound by -the terms of this License. If you do not or cannot agree to the terms -of this License, please do not download or use the software. - -1. General; Definitions. This License applies to any program or other -work which Apple Computer, Inc. ("Apple") makes publicly available and -which contains a notice placed by Apple identifying such program or -work as "Original Code" and stating that it is subject to the terms of -this Apple Public Source License version 2.0 ("License"). As used in -this License: - -1.1 "Applicable Patent Rights" mean: (a) in the case where Apple is -the grantor of rights, (i) claims of patents that are now or hereafter -acquired, owned by or assigned to Apple and (ii) that cover subject -matter contained in the Original Code, but only to the extent -necessary to use, reproduce and/or distribute the Original Code -without infringement; and (b) in the case where You are the grantor of -rights, (i) claims of patents that are now or hereafter acquired, -owned by or assigned to You and (ii) that cover subject matter in Your -Modifications, taken alone or in combination with Original Code. - -1.2 "Contributor" means any person or entity that creates or -contributes to the creation of Modifications. - -1.3 "Covered Code" means the Original Code, Modifications, the -combination of Original Code and any Modifications, and/or any -respective portions thereof. - -1.4 "Externally Deploy" means: (a) to sublicense, distribute or -otherwise make Covered Code available, directly or indirectly, to -anyone other than You; and/or (b) to use Covered Code, alone or as -part of a Larger Work, in any way to provide a service, including but -not limited to delivery of content, through electronic communication -with a client other than You. - -1.5 "Larger Work" means a work which combines Covered Code or portions -thereof with code not governed by the terms of this License. - -1.6 "Modifications" mean any addition to, deletion from, and/or change -to, the substance and/or structure of the Original Code, any previous -Modifications, the combination of Original Code and any previous -Modifications, and/or any respective portions thereof. When code is -released as a series of files, a Modification is: (a) any addition to -or deletion from the contents of a file containing Covered Code; -and/or (b) any new file or other representation of computer program -statements that contains any part of Covered Code. - -1.7 "Original Code" means (a) the Source Code of a program or other -work as originally made available by Apple under this License, -including the Source Code of any updates or upgrades to such programs -or works made available by Apple under this License, and that has been -expressly identified by Apple as such in the header file(s) of such -work; and (b) the object code compiled from such Source Code and -originally made available by Apple under this License. - -1.8 "Source Code" means the human readable form of a program or other -work that is suitable for making modifications to it, including all -modules it contains, plus any associated interface definition files, -scripts used to control compilation and installation of an executable -(object code). - -1.9 "You" or "Your" means an individual or a legal entity exercising -rights under this License. For legal entities, "You" or "Your" -includes any entity which controls, is controlled by, or is under -common control with, You, where "control" means (a) the power, direct -or indirect, to cause the direction or management of such entity, -whether by contract or otherwise, or (b) ownership of fifty percent -(50%) or more of the outstanding shares or beneficial ownership of -such entity. - -2. Permitted Uses; Conditions & Restrictions. Subject to the terms -and conditions of this License, Apple hereby grants You, effective on -the date You accept this License and download the Original Code, a -world-wide, royalty-free, non-exclusive license, to the extent of -Apple's Applicable Patent Rights and copyrights covering the Original -Code, to do the following: - -2.1 Unmodified Code. You may use, reproduce, display, perform, -internally distribute within Your organization, and Externally Deploy -verbatim, unmodified copies of the Original Code, for commercial or -non-commercial purposes, provided that in each instance: - -(a) You must retain and reproduce in all copies of Original Code the -copyright and other proprietary notices and disclaimers of Apple as -they appear in the Original Code, and keep intact all notices in the -Original Code that refer to this License; and - -(b) You must include a copy of this License with every copy of Source -Code of Covered Code and documentation You distribute or Externally -Deploy, and You may not offer or impose any terms on such Source Code -that alter or restrict this License or the recipients' rights -hereunder, except as permitted under Section 6. - -2.2 Modified Code. You may modify Covered Code and use, reproduce, -display, perform, internally distribute within Your organization, and -Externally Deploy Your Modifications and Covered Code, for commercial -or non-commercial purposes, provided that in each instance You also -meet all of these conditions: - -(a) You must satisfy all the conditions of Section 2.1 with respect to -the Source Code of the Covered Code; - -(b) You must duplicate, to the extent it does not already exist, the -notice in Exhibit A in each file of the Source Code of all Your -Modifications, and cause the modified files to carry prominent notices -stating that You changed the files and the date of any change; and - -(c) If You Externally Deploy Your Modifications, You must make -Source Code of all Your Externally Deployed Modifications either -available to those to whom You have Externally Deployed Your -Modifications, or publicly available. Source Code of Your Externally -Deployed Modifications must be released under the terms set forth in -this License, including the license grants set forth in Section 3 -below, for as long as you Externally Deploy the Covered Code or twelve -(12) months from the date of initial External Deployment, whichever is -longer. You should preferably distribute the Source Code of Your -Externally Deployed Modifications electronically (e.g. download from a -web site). - -2.3 Distribution of Executable Versions. In addition, if You -Externally Deploy Covered Code (Original Code and/or Modifications) in -object code, executable form only, You must include a prominent -notice, in the code itself as well as in related documentation, -stating that Source Code of the Covered Code is available under the -terms of this License with information on how and where to obtain such -Source Code. - -2.4 Third Party Rights. You expressly acknowledge and agree that -although Apple and each Contributor grants the licenses to their -respective portions of the Covered Code set forth herein, no -assurances are provided by Apple or any Contributor that the Covered -Code does not infringe the patent or other intellectual property -rights of any other entity. Apple and each Contributor disclaim any -liability to You for claims brought by any other entity based on -infringement of intellectual property rights or otherwise. As a -condition to exercising the rights and licenses granted hereunder, You -hereby assume sole responsibility to secure any other intellectual -property rights needed, if any. For example, if a third party patent -license is required to allow You to distribute the Covered Code, it is -Your responsibility to acquire that license before distributing the -Covered Code. - -3. Your Grants. In consideration of, and as a condition to, the -licenses granted to You under this License, You hereby grant to any -person or entity receiving or distributing Covered Code under this -License a non-exclusive, royalty-free, perpetual, irrevocable license, -under Your Applicable Patent Rights and other intellectual property -rights (other than patent) owned or controlled by You, to use, -reproduce, display, perform, modify, sublicense, distribute and -Externally Deploy Your Modifications of the same scope and extent as -Apple's licenses under Sections 2.1 and 2.2 above. - -4. Larger Works. You may create a Larger Work by combining Covered -Code with other code not governed by the terms of this License and -distribute the Larger Work as a single product. In each such instance, -You must make sure the requirements of this License are fulfilled for -the Covered Code or any portion thereof. - -5. Limitations on Patent License. Except as expressly stated in -Section 2, no other patent rights, express or implied, are granted by -Apple herein. Modifications and/or Larger Works may require additional -patent licenses from Apple which Apple may grant in its sole -discretion. - -6. Additional Terms. You may choose to offer, and to charge a fee for, -warranty, support, indemnity or liability obligations and/or other -rights consistent with the scope of the license granted herein -("Additional Terms") to one or more recipients of Covered Code. -However, You may do so only on Your own behalf and as Your sole -responsibility, and not on behalf of Apple or any Contributor. You -must obtain the recipient's agreement that any such Additional Terms -are offered by You alone, and You hereby agree to indemnify, defend -and hold Apple and every Contributor harmless for any liability -incurred by or claims asserted against Apple or such Contributor by -reason of any such Additional Terms. - -7. Versions of the License. Apple may publish revised and/or new -versions of this License from time to time. Each version will be given -a distinguishing version number. Once Original Code has been published -under a particular version of this License, You may continue to use it -under the terms of that version. You may also choose to use such -Original Code under the terms of any subsequent version of this -License published by Apple. No one other than Apple has the right to -modify the terms applicable to Covered Code created under this -License. - -8. NO WARRANTY OR SUPPORT. The Covered Code may contain in whole or in -part pre-release, untested, or not fully tested works. The Covered -Code may contain errors that could cause failures or loss of data, and -may be incomplete or contain inaccuracies. You expressly acknowledge -and agree that use of the Covered Code, or any portion thereof, is at -Your sole and entire risk. THE COVERED CODE IS PROVIDED "AS IS" AND -WITHOUT WARRANTY, UPGRADES OR SUPPORT OF ANY KIND AND APPLE AND -APPLE'S LICENSOR(S) (COLLECTIVELY REFERRED TO AS "APPLE" FOR THE -PURPOSES OF SECTIONS 8 AND 9) AND ALL CONTRIBUTORS EXPRESSLY DISCLAIM -ALL WARRANTIES AND/OR CONDITIONS, EXPRESS OR IMPLIED, INCLUDING, BUT -NOT LIMITED TO, THE IMPLIED WARRANTIES AND/OR CONDITIONS OF -MERCHANTABILITY, OF SATISFACTORY QUALITY, OF FITNESS FOR A PARTICULAR -PURPOSE, OF ACCURACY, OF QUIET ENJOYMENT, AND NONINFRINGEMENT OF THIRD -PARTY RIGHTS. APPLE AND EACH CONTRIBUTOR DOES NOT WARRANT AGAINST -INTERFERENCE WITH YOUR ENJOYMENT OF THE COVERED CODE, THAT THE -FUNCTIONS CONTAINED IN THE COVERED CODE WILL MEET YOUR REQUIREMENTS, -THAT THE OPERATION OF THE COVERED CODE WILL BE UNINTERRUPTED OR -ERROR-FREE, OR THAT DEFECTS IN THE COVERED CODE WILL BE CORRECTED. NO -ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE, AN APPLE -AUTHORIZED REPRESENTATIVE OR ANY CONTRIBUTOR SHALL CREATE A WARRANTY. -You acknowledge that the Covered Code is not intended for use in the -operation of nuclear facilities, aircraft navigation, communication -systems, or air traffic control machines in which case the failure of -the Covered Code could lead to death, personal injury, or severe -physical or environmental damage. - -9. LIMITATION OF LIABILITY. TO THE EXTENT NOT PROHIBITED BY LAW, IN NO -EVENT SHALL APPLE OR ANY CONTRIBUTOR BE LIABLE FOR ANY INCIDENTAL, -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATING -TO THIS LICENSE OR YOUR USE OR INABILITY TO USE THE COVERED CODE, OR -ANY PORTION THEREOF, WHETHER UNDER A THEORY OF CONTRACT, WARRANTY, -TORT (INCLUDING NEGLIGENCE), PRODUCTS LIABILITY OR OTHERWISE, EVEN IF -APPLE OR SUCH CONTRIBUTOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES AND NOTWITHSTANDING THE FAILURE OF ESSENTIAL PURPOSE OF ANY -REMEDY. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OF LIABILITY OF -INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION MAY NOT APPLY -TO YOU. In no event shall Apple's total liability to You for all -damages (other than as may be required by applicable law) under this -License exceed the amount of fifty dollars ($50.00). - -10. Trademarks. This License does not grant any rights to use the -trademarks or trade names "Apple", "Apple Computer", "Mac", "Mac OS", -"QuickTime", "QuickTime Streaming Server" or any other trademarks, -service marks, logos or trade names belonging to Apple (collectively -"Apple Marks") or to any trademark, service mark, logo or trade name -belonging to any Contributor. You agree not to use any Apple Marks in -or as part of the name of products derived from the Original Code or -to endorse or promote products derived from the Original Code other -than as expressly permitted by and in strict compliance at all times -with Apple's third party trademark usage guidelines which are posted -at http://www.apple.com/legal/guidelinesfor3rdparties.html. - -11. Ownership. Subject to the licenses granted under this License, -each Contributor retains all rights, title and interest in and to any -Modifications made by such Contributor. Apple retains all rights, -title and interest in and to the Original Code and any Modifications -made by or on behalf of Apple ("Apple Modifications"), and such Apple -Modifications will not be automatically subject to this License. Apple -may, at its sole discretion, choose to license such Apple -Modifications under this License, or on different terms from those -contained in this License or may choose not to license them at all. - -12. Termination. - -12.1 Termination. This License and the rights granted hereunder will -terminate: - -(a) automatically without notice from Apple if You fail to comply with -any term(s) of this License and fail to cure such breach within 30 -days of becoming aware of such breach; - -(b) immediately in the event of the circumstances described in Section -13.5(b); or - -(c) automatically without notice from Apple if You, at any time during -the term of this License, commence an action for patent infringement -against Apple; provided that Apple did not first commence -an action for patent infringement against You in that instance. - -12.2 Effect of Termination. Upon termination, You agree to immediately -stop any further use, reproduction, modification, sublicensing and -distribution of the Covered Code. All sublicenses to the Covered Code -which have been properly granted prior to termination shall survive -any termination of this License. Provisions which, by their nature, -should remain in effect beyond the termination of this License shall -survive, including but not limited to Sections 3, 5, 8, 9, 10, 11, -12.2 and 13. No party will be liable to any other for compensation, -indemnity or damages of any sort solely as a result of terminating -this License in accordance with its terms, and termination of this -License will be without prejudice to any other right or remedy of -any party. - -13. Miscellaneous. - -13.1 Government End Users. The Covered Code is a "commercial item" as -defined in FAR 2.101. Government software and technical data rights in -the Covered Code include only those rights customarily provided to the -public as defined in this License. This customary commercial license -in technical data and software is provided in accordance with FAR -12.211 (Technical Data) and 12.212 (Computer Software) and, for -Department of Defense purchases, DFAR 252.227-7015 (Technical Data -- -Commercial Items) and 227.7202-3 (Rights in Commercial Computer -Software or Computer Software Documentation). Accordingly, all U.S. -Government End Users acquire Covered Code with only those rights set -forth herein. - -13.2 Relationship of Parties. This License will not be construed as -creating an agency, partnership, joint venture or any other form of -legal association between or among You, Apple or any Contributor, and -You will not represent to the contrary, whether expressly, by -implication, appearance or otherwise. - -13.3 Independent Development. Nothing in this License will impair -Apple's right to acquire, license, develop, have others develop for -it, market and/or distribute technology or products that perform the -same or similar functions as, or otherwise compete with, -Modifications, Larger Works, technology or products that You may -develop, produce, market or distribute. - -13.4 Waiver; Construction. Failure by Apple or any Contributor to -enforce any provision of this License will not be deemed a waiver of -future enforcement of that or any other provision. Any law or -regulation which provides that the language of a contract shall be -construed against the drafter will not apply to this License. - -13.5 Severability. (a) If for any reason a court of competent -jurisdiction finds any provision of this License, or portion thereof, -to be unenforceable, that provision of the License will be enforced to -the maximum extent permissible so as to effect the economic benefits -and intent of the parties, and the remainder of this License will -continue in full force and effect. (b) Notwithstanding the foregoing, -if applicable law prohibits or restricts You from fully and/or -specifically complying with Sections 2 and/or 3 or prevents the -enforceability of either of those Sections, this License will -immediately terminate and You must immediately discontinue any use of -the Covered Code and destroy all copies of it that are in your -possession or control. - -13.6 Dispute Resolution. Any litigation or other dispute resolution -between You and Apple relating to this License shall take place in the -Northern District of California, and You and Apple hereby consent to -the personal jurisdiction of, and venue in, the state and federal -courts within that District with respect to this License. The -application of the United Nations Convention on Contracts for the -International Sale of Goods is expressly excluded. - -13.7 Entire Agreement; Governing Law. This License constitutes the -entire agreement between the parties with respect to the subject -matter hereof. This License shall be governed by the laws of the -United States and the State of California, except that body of -California law concerning conflicts of law. - -Where You are located in the province of Quebec, Canada, the following -clause applies: The parties hereby confirm that they have requested -that this License and all related documents be drafted in English. Les -parties ont exige que le present contrat et tous les documents -connexes soient rediges en anglais. - -EXHIBIT A. - -"Portions Copyright (c) 1999-2003 Apple Computer, Inc. All Rights -Reserved. - -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." diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.d deleted file mode 100644 index 3490795..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/debug-objc/XXObject.m \ - /Users/apple/Desktop/objc-runtime/debug-objc/XXObject.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.o deleted file mode 100644 index 42df0b7..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/debug-objc.LinkFileList b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/debug-objc.LinkFileList deleted file mode 100644 index 3e3d612..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/debug-objc.LinkFileList +++ /dev/null @@ -1,2 +0,0 @@ -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/XXObject.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.o diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/debug-objc_dependency_info.dat b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/debug-objc_dependency_info.dat deleted file mode 100644 index 8629b5b..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/debug-objc_dependency_info.dat and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.d deleted file mode 100644 index 86d4533..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/debug-objc/main.m \ - /Users/apple/Desktop/objc-runtime/debug-objc/XXObject.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.o deleted file mode 100644 index f7a5e15..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/Objects-normal/x86_64/main.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-all-non-framework-target-headers.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-all-non-framework-target-headers.hmap deleted file mode 100644 index 9844e74..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-all-non-framework-target-headers.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-all-target-headers.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-all-target-headers.hmap deleted file mode 100644 index 9844e74..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-all-target-headers.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-generated-files.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-generated-files.hmap deleted file mode 100644 index dd8b535..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-generated-files.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-own-target-headers.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-own-target-headers.hmap deleted file mode 100644 index dc511c4..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-own-target-headers.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-project-headers.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-project-headers.hmap deleted file mode 100644 index a6dd7b4..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc-project-headers.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc.hmap deleted file mode 100644 index 0330ad1..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/debug-objc.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/dgph b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/dgph deleted file mode 100644 index 45213b6..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/debug-objc.build/dgph and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h deleted file mode 100644 index e1290d9..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Generated by dtrace(1M). - */ - -#ifndef _OBJC_PROBES_H -#define _OBJC_PROBES_H - -#include <unistd.h> - -#ifdef __cplusplus -extern "C" { -#endif - -#define OBJC_RUNTIME_STABILITY "___dtrace_stability$objc_runtime$v1$1_1_0_1_1_0_1_1_0_1_1_0_1_1_0" - -#define OBJC_RUNTIME_TYPEDEFS "___dtrace_typedefs$objc_runtime$v2" - -#if !defined(DTRACE_PROBES_DISABLED) || !DTRACE_PROBES_DISABLED - -#define OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW() \ -do { \ - __asm__ volatile(".reference " OBJC_RUNTIME_TYPEDEFS); \ - __dtrace_probe$objc_runtime$objc_exception_rethrow$v1(); \ - __asm__ volatile(".reference " OBJC_RUNTIME_STABILITY); \ -} while (0) -#define OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW_ENABLED() \ - ({ int _r = __dtrace_isenabled$objc_runtime$objc_exception_rethrow$v1(); \ - __asm__ volatile(""); \ - _r; }) -#define OBJC_RUNTIME_OBJC_EXCEPTION_THROW(arg0) \ -do { \ - __asm__ volatile(".reference " OBJC_RUNTIME_TYPEDEFS); \ - __dtrace_probe$objc_runtime$objc_exception_throw$v1$766f6964202a(arg0); \ - __asm__ volatile(".reference " OBJC_RUNTIME_STABILITY); \ -} while (0) -#define OBJC_RUNTIME_OBJC_EXCEPTION_THROW_ENABLED() \ - ({ int _r = __dtrace_isenabled$objc_runtime$objc_exception_throw$v1(); \ - __asm__ volatile(""); \ - _r; }) - - -extern void __dtrace_probe$objc_runtime$objc_exception_rethrow$v1(void); -extern int __dtrace_isenabled$objc_runtime$objc_exception_rethrow$v1(void); -extern void __dtrace_probe$objc_runtime$objc_exception_throw$v1$766f6964202a(const void *); -extern int __dtrace_isenabled$objc_runtime$objc_exception_throw$v1(void); - -#else - -#define OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW() \ -do { \ - } while (0) -#define OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW_ENABLED() (0) -#define OBJC_RUNTIME_OBJC_EXCEPTION_THROW(arg0) \ -do { \ - } while (0) -#define OBJC_RUNTIME_OBJC_EXCEPTION_THROW_ENABLED() (0) - -#endif /* !defined(DTRACE_PROBES_DISABLED) || !DTRACE_PROBES_DISABLED */ - - -#ifdef __cplusplus -} -#endif - -#endif /* _OBJC_PROBES_H */ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.d deleted file mode 100644 index 79d3011..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/OldClasses.subproj/List.m diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.o deleted file mode 100644 index a58aa8c..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.d deleted file mode 100644 index bb31e4c..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.d +++ /dev/null @@ -1,47 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/NSObject.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/NSObject.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-weak.h \ - /Users/apple/Desktop/objc-runtime/runtime/llvm-DenseMap.h \ - /Users/apple/Desktop/objc-runtime/runtime/llvm-type_traits.h \ - /Users/apple/Desktop/objc-runtime/runtime/llvm-MathExtras.h \ - /Users/apple/Desktop/objc-runtime/runtime/llvm-AlignOf.h \ - /Users/apple/Desktop/objc-runtime/runtime/llvm-DenseMapInfo.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.dia deleted file mode 100644 index 32e1a6b..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.o deleted file mode 100644 index 7911d8f..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.d deleted file mode 100644 index f22fda4..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.d +++ /dev/null @@ -1,40 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/Object.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.dia deleted file mode 100644 index 851d157..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.o deleted file mode 100644 index 5d3dbe2..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.d deleted file mode 100644 index b7f7595..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/Protocol.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/Protocol.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.dia deleted file mode 100644 index 1bc69e8..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.o deleted file mode 100644 index a61582a..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.d deleted file mode 100644 index 6a96b8f..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/a1a2-blocktramps-arm.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.o deleted file mode 100644 index ae2bbfa..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.d deleted file mode 100644 index 5dee42b..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/a1a2-blocktramps-arm64.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.o deleted file mode 100644 index 505fcff..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.d deleted file mode 100644 index 417759f..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/a1a2-blocktramps-i386.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.o deleted file mode 100644 index 09d6eb8..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.d deleted file mode 100644 index 8916fbd..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/a1a2-blocktramps-x86_64.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.o deleted file mode 100644 index ee0f06b..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.d deleted file mode 100644 index 8048e62..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/a2a3-blocktramps-arm.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.o deleted file mode 100644 index 30827ed..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.d deleted file mode 100644 index 1213e3f..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/a2a3-blocktramps-i386.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.o deleted file mode 100644 index 67b9da6..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.d deleted file mode 100644 index 6c9cb3a..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/a2a3-blocktramps-x86_64.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.o deleted file mode 100644 index 4955ed6..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.d deleted file mode 100644 index 6279b16..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.d +++ /dev/null @@ -1,40 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/hashtable2.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.dia deleted file mode 100644 index ac8b885..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.o deleted file mode 100644 index 0cbab20..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.d deleted file mode 100644 index fea12d8..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.d +++ /dev/null @@ -1,40 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/maptable.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.dia deleted file mode 100644 index f94fd52..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.o deleted file mode 100644 index edebd0f..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.d deleted file mode 100644 index 47237b9..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-accessors.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-accessors.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.dia deleted file mode 100644 index b7e0d2b..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.o deleted file mode 100644 index 5712691..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.d deleted file mode 100644 index 09658d2..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-auto-dump.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto-dump.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.dia deleted file mode 100644 index 1269b92..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.o deleted file mode 100644 index 41a44d3..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.d deleted file mode 100644 index d0e2f6f..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.d +++ /dev/null @@ -1,47 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-auto.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/include/Block_private.h \ - /Users/apple/Desktop/objc-runtime/include/dispatch/private.h \ - /Users/apple/Desktop/objc-runtime/include/dispatch/benchmark.h \ - /Users/apple/Desktop/objc-runtime/include/dispatch/queue_private.h \ - /Users/apple/Desktop/objc-runtime/include/dispatch/source_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-accessors.h \ - /Users/apple/Desktop/objc-runtime/runtime/message.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.dia deleted file mode 100644 index aaca620..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.o deleted file mode 100644 index c4d3b33..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.d deleted file mode 100644 index 832c115..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.d +++ /dev/null @@ -1,42 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/objc-block-trampolines.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/include/Block_private.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.dia deleted file mode 100644 index e1de259..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.o deleted file mode 100644 index 9f0cbcd..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.d deleted file mode 100644 index 8029ba8..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.d +++ /dev/null @@ -1 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-cache-old.mm diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.o deleted file mode 100644 index 98c68f0..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.d deleted file mode 100644 index db68983..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-cache.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-cache.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.dia deleted file mode 100644 index 338d601..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.o deleted file mode 100644 index 5132499..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.d deleted file mode 100644 index 420bf07..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.d +++ /dev/null @@ -1 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-class-old.mm diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.o deleted file mode 100644 index 0405172..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.d deleted file mode 100644 index 189d187..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.d +++ /dev/null @@ -1,40 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-class.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.dia deleted file mode 100644 index e563f15..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.o deleted file mode 100644 index e3a2557..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.d deleted file mode 100644 index beebb8d..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-errors.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/include/vproc_priv.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.dia deleted file mode 100644 index d9be95c..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.o deleted file mode 100644 index 9e25a4f..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.d deleted file mode 100644 index 0f239dc..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-exception.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-exception.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.dia deleted file mode 100644 index 3bcf3b7..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.o deleted file mode 100644 index 8ccd20e..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.d deleted file mode 100644 index 60249f9..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.d +++ /dev/null @@ -1,42 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/objc-externalref.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/message.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.dia deleted file mode 100644 index cc9d05c..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.o deleted file mode 100644 index 7e17897..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.d deleted file mode 100644 index 6ee0efa..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.d +++ /dev/null @@ -1 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-file-old.mm diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.o deleted file mode 100644 index 40e3b73..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.d deleted file mode 100644 index 5c16b92..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-file.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-file.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.dia deleted file mode 100644 index 1c11c3e..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.o deleted file mode 100644 index 18b4e48..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.d deleted file mode 100644 index f1d3db5..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.d +++ /dev/null @@ -1,42 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/message.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.dia deleted file mode 100644 index 99ad5ae..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.o deleted file mode 100644 index c13807e..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.d deleted file mode 100644 index 2e3845d..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.d +++ /dev/null @@ -1,40 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-layout.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.dia deleted file mode 100644 index 7b6d1e6..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.o deleted file mode 100644 index 6111d5a..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.d deleted file mode 100644 index 43a0c24..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.d +++ /dev/null @@ -1,42 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-load.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-load.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-class.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.dia deleted file mode 100644 index e4366ef..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.o deleted file mode 100644 index 681e86e..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.d deleted file mode 100644 index 3ada9ed..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.dia deleted file mode 100644 index 0673073..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.o deleted file mode 100644 index 1ccff89..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.d deleted file mode 100644 index 38eb612..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.d +++ /dev/null @@ -1,40 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.dia deleted file mode 100644 index 9500c9f..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.o deleted file mode 100644 index bc2adc7..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.d deleted file mode 100644 index c52f1bd..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/Messengers.subproj/objc-msg-arm.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.o deleted file mode 100644 index 3d53bf2..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.d deleted file mode 100644 index 5eda45f..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/Messengers.subproj/objc-msg-i386.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.o deleted file mode 100644 index c22ee6a..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.d deleted file mode 100644 index c84af83..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/Messengers.subproj/objc-msg-simulator-i386.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.o deleted file mode 100644 index 53a3739..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.d deleted file mode 100644 index 269b0c3..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/Messengers.subproj/objc-msg-x86_64.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.o deleted file mode 100644 index 664a05d..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.d deleted file mode 100644 index c85943f..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.d +++ /dev/null @@ -1,40 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-opt.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.dia deleted file mode 100644 index c600caf..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.o deleted file mode 100644 index 7977ca3..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.d deleted file mode 100644 index 065f232..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.d +++ /dev/null @@ -1,42 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-os.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-file-old.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-file.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.dia deleted file mode 100644 index a78992f..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.o deleted file mode 100644 index 6448415..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.d deleted file mode 100644 index 7b786c3..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.dia deleted file mode 100644 index 13fee78..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.o deleted file mode 100644 index e508448..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.d deleted file mode 100644 index 2779d65..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.d +++ /dev/null @@ -1,43 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-file.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-cache.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.dia deleted file mode 100644 index 99b51dd..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.o deleted file mode 100644 index 2843e82..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.d deleted file mode 100644 index 876a98f..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.d +++ /dev/null @@ -1,2 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-old.mm diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.o deleted file mode 100644 index f9ac42b..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.d deleted file mode 100644 index 6983577..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-runtime.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/message.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.dia deleted file mode 100644 index 74c55d3..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.o deleted file mode 100644 index 887edea..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.d deleted file mode 100644 index d119cb8..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.d +++ /dev/null @@ -1 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-sel-old.mm diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.o deleted file mode 100644 index 6edc849..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.d deleted file mode 100644 index 85ce1ca..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-sel-set.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-sel-set.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.dia deleted file mode 100644 index a9f5eb6..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.o deleted file mode 100644 index 75f66d4..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.d deleted file mode 100644 index 8f02723..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.d +++ /dev/null @@ -1 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-sel-table.s diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.dia deleted file mode 100644 index 29ccd98..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.o deleted file mode 100644 index dcbbf02..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.d deleted file mode 100644 index cc0afea..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-sel.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-cache.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.dia deleted file mode 100644 index 299d660..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.o deleted file mode 100644 index 3deb191..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.d deleted file mode 100644 index 8162b75..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-sync.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-sync.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.dia deleted file mode 100644 index 929d153..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.o deleted file mode 100644 index 46bbe2d..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.d deleted file mode 100644 index db0ab15..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: \ - /Users/apple/Desktop/objc-runtime/runtime/objc-typeencoding.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.dia deleted file mode 100644 index e8ad8b3..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.o deleted file mode 100644 index e993f9d..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.d b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.d deleted file mode 100644 index 3a19c43..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.d +++ /dev/null @@ -1,41 +0,0 @@ -dependencies: /Users/apple/Desktop/objc-runtime/runtime/objc-weak.mm \ - /Users/apple/Desktop/objc-runtime/runtime/objc-private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-config.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-os.h \ - /Users/apple/Desktop/objc-runtime/include/mach-o/dyld_priv.h \ - /Users/apple/Desktop/objc-runtime/include/System/pthread_machdep.h \ - /Users/apple/Desktop/objc-runtime/include/System/machine/cpu_capabilities.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/tsd_private.h \ - /Users/apple/Desktop/objc-runtime/include/os/tsd.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/spinlock_private.h \ - /Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/DerivedSources/objc-probes.h \ - /Users/apple/Desktop/objc-runtime/include/CrashReporterClient.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/qos_private.h \ - /Users/apple/Desktop/objc-runtime/include/sys/qos_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-lockdebug.h \ - /Users/apple/Desktop/objc-runtime/include/pthread/workqueue_private.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-abi.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/message.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-api.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-internal.h \ - /Users/apple/Desktop/objc-runtime/runtime/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-auto.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-gdb.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h \ - /Users/apple/Desktop/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-runtime-new.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-references.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-initialize.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-loadmethod.h \ - /Users/apple/Desktop/objc-runtime/include/objc-shared-cache.h \ - /Users/apple/Desktop/objc-runtime/include/auto_zone.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-env.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-object.h \ - /Users/apple/Desktop/objc-runtime/runtime/objc-weak.h diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.dia b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.dia deleted file mode 100644 index 5c23f51..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.dia and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.o b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.o deleted file mode 100644 index 976370a..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.o and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc.A.LinkFileList b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc.A.LinkFileList deleted file mode 100644 index 36f8735..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc.A.LinkFileList +++ /dev/null @@ -1,48 +0,0 @@ -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Object.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/hashtable2.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class-old.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/maptable.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-class.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-errors.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-exception.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-initialize.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-layout.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-load.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-loadmethod.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-lockdebug.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-new.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto-dump.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-set.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-runtime-old.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sync.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-typeencoding.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-accessors.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-cache-old.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/Protocol.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/List.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-arm.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-i386.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-x86_64.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-references.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-os.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-i386.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-x86_64.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-i386.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-auto.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-x86_64.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-block-trampolines.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-msg-simulator-i386.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-old.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-sel-table.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a2a3-blocktramps-arm.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-externalref.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/a1a2-blocktramps-arm64.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-weak.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/NSObject.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-file-old.o -/Users/apple/Desktop/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc-opt.o diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc.A_dependency_info.dat b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc.A_dependency_info.dat deleted file mode 100644 index b79419a..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Objects-normal/x86_64/objc.A_dependency_info.dat and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Script-830F2AB60D739AB600392440.sh b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Script-830F2AB60D739AB600392440.sh deleted file mode 100755 index 47ff21a..0000000 --- a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/Script-830F2AB60D739AB600392440.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -set -x -/usr/bin/xcrun -toolchain XcodeDefault -sdk macosx clang++ -Wall -mmacosx-version-min=10.9 -arch x86_64 -std=c++11 "${SRCROOT}/markgc.cpp" -o "${BUILT_PRODUCTS_DIR}/markgc" -"${BUILT_PRODUCTS_DIR}/markgc" "${BUILT_PRODUCTS_DIR}/libobjc.A.dylib" diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/dgph b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/dgph deleted file mode 100644 index eb48531..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/dgph and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-all-non-framework-target-headers.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-all-non-framework-target-headers.hmap deleted file mode 100644 index 9844e74..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-all-non-framework-target-headers.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-all-target-headers.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-all-target-headers.hmap deleted file mode 100644 index 9844e74..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-all-target-headers.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-generated-files.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-generated-files.hmap deleted file mode 100644 index 62709ce..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-generated-files.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-own-target-headers.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-own-target-headers.hmap deleted file mode 100644 index 4489ba6..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-own-target-headers.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-project-headers.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-project-headers.hmap deleted file mode 100644 index a6dd7b4..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A-project-headers.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A.hmap b/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A.hmap deleted file mode 100644 index 38129e5..0000000 Binary files a/objc/objc-runtime/Build/Intermediates/objc.build/Debug/objc.build/objc.A.hmap and /dev/null differ diff --git a/objc/objc-runtime/Build/Products/Debug/debug-objc b/objc/objc-runtime/Build/Products/Debug/debug-objc deleted file mode 100755 index ee23d56..0000000 Binary files a/objc/objc-runtime/Build/Products/Debug/debug-objc and /dev/null differ diff --git a/objc/objc-runtime/Build/Products/Debug/libobjc.A.dylib b/objc/objc-runtime/Build/Products/Debug/libobjc.A.dylib deleted file mode 100755 index 55d3f18..0000000 Binary files a/objc/objc-runtime/Build/Products/Debug/libobjc.A.dylib and /dev/null differ diff --git a/objc/objc-runtime/Build/Products/Debug/markgc b/objc/objc-runtime/Build/Products/Debug/markgc deleted file mode 100755 index 0ac1e3a..0000000 Binary files a/objc/objc-runtime/Build/Products/Debug/markgc and /dev/null differ diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/List.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/List.h deleted file mode 100644 index 993cf2c..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/List.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 1999-2002, 2005-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@ - */ -/* - List.h - Copyright 1988-1996 NeXT Software, Inc. - - DEFINED AS: A common class - HEADER FILES: objc/List.h - -*/ - -#ifndef _OBJC_LIST_H_ -#define _OBJC_LIST_H_ - -#if __OBJC__ && !__OBJC2__ && !__cplusplus - -#include <objc/Object.h> -#include <Availability.h> - -DEPRECATED_ATTRIBUTE -@interface List : Object -{ -@public - id *dataPtr DEPRECATED_ATTRIBUTE; /* data of the List object */ - unsigned numElements DEPRECATED_ATTRIBUTE; /* Actual number of elements */ - unsigned maxElements DEPRECATED_ATTRIBUTE; /* Total allocated elements */ -} - -/* Creating, freeing */ - -- (id)free DEPRECATED_ATTRIBUTE; -- (id)freeObjects DEPRECATED_ATTRIBUTE; -- (id)copyFromZone:(void *)z DEPRECATED_ATTRIBUTE; - -/* Initializing */ - -- (id)init DEPRECATED_ATTRIBUTE; -- (id)initCount:(unsigned)numSlots DEPRECATED_ATTRIBUTE; - -/* Comparing two lists */ - -- (BOOL)isEqual: anObject DEPRECATED_ATTRIBUTE; - -/* Managing the storage capacity */ - -- (unsigned)capacity DEPRECATED_ATTRIBUTE; -- (id)setAvailableCapacity:(unsigned)numSlots DEPRECATED_ATTRIBUTE; - -/* Manipulating objects by index */ - -- (unsigned)count DEPRECATED_ATTRIBUTE; -- (id)objectAt:(unsigned)index DEPRECATED_ATTRIBUTE; -- (id)lastObject DEPRECATED_ATTRIBUTE; -- (id)addObject:anObject DEPRECATED_ATTRIBUTE; -- (id)insertObject:anObject at:(unsigned)index DEPRECATED_ATTRIBUTE; -- (id)removeObjectAt:(unsigned)index DEPRECATED_ATTRIBUTE; -- (id)removeLastObject DEPRECATED_ATTRIBUTE; -- (id)replaceObjectAt:(unsigned)index with:newObject DEPRECATED_ATTRIBUTE; -- (id)appendList: (List *)otherList DEPRECATED_ATTRIBUTE; - -/* Manipulating objects by id */ - -- (unsigned)indexOf:anObject DEPRECATED_ATTRIBUTE; -- (id)addObjectIfAbsent:anObject DEPRECATED_ATTRIBUTE; -- (id)removeObject:anObject DEPRECATED_ATTRIBUTE; -- (id)replaceObject:anObject with:newObject DEPRECATED_ATTRIBUTE; - -/* Emptying the list */ - -- (id)empty DEPRECATED_ATTRIBUTE; - -/* Sending messages to elements of the list */ - -- (id)makeObjectsPerform:(SEL)aSelector DEPRECATED_ATTRIBUTE; -- (id)makeObjectsPerform:(SEL)aSelector with:anObject DEPRECATED_ATTRIBUTE; - -/* - * The following new... methods are now obsolete. They remain in this - * interface file for backward compatibility only. Use Object's alloc method - * and the init... methods defined in this class instead. - */ - -+ (id)new DEPRECATED_ATTRIBUTE; -+ (id)newCount:(unsigned)numSlots DEPRECATED_ATTRIBUTE; - -@end - -typedef struct { - @defs(List); -} NXListId DEPRECATED_ATTRIBUTE; - -#define NX_ADDRESS(x) (((NXListId *)(x))->dataPtr) - -#define NX_NOT_IN_LIST 0xffffffff - -#endif - -#endif /* _OBJC_LIST_H_ */ diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/Object.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/Object.h deleted file mode 100644 index dd8838d..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/Object.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 1999-2003, 2005-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@ - */ -/* - Object.h - Copyright 1988-1996 NeXT Software, Inc. - - DEFINED AS: A common class - HEADER FILES: <objc/Object.h> - -*/ - -#ifndef _OBJC_OBJECT_H_ -#define _OBJC_OBJECT_H_ - -#include <stdarg.h> -#include <objc/objc-runtime.h> - -#if __OBJC__ && !__OBJC2__ - -__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_NA) -OBJC_ROOT_CLASS -@interface Object -{ - Class isa; /* A pointer to the instance's class structure */ -} - -/* Initializing classes and instances */ - -+ (id)initialize; -- (id)init; - -/* Creating, copying, and freeing instances */ - -+ (id)new; -+ (id)free; -- (id)free; -+ (id)alloc; -- (id)copy; -+ (id)allocFromZone:(void *)zone; -- (id)copyFromZone:(void *)zone; -- (void *)zone; - -/* Identifying classes */ - -+ (id)class; -+ (id)superclass; -+ (const char *) name; -- (id)class; -- (id)superclass; -- (const char *) name; - -/* Identifying and comparing instances */ - -- (id)self; -- (unsigned int) hash; -- (BOOL) isEqual:anObject; - -/* Testing inheritance relationships */ - -- (BOOL) isKindOf: aClassObject; -- (BOOL) isMemberOf: aClassObject; -- (BOOL) isKindOfClassNamed: (const char *)aClassName; -- (BOOL) isMemberOfClassNamed: (const char *)aClassName; - -/* Testing class functionality */ - -+ (BOOL) instancesRespondTo:(SEL)aSelector; -- (BOOL) respondsTo:(SEL)aSelector; - -/* Testing protocol conformance */ - -- (BOOL) conformsTo: (Protocol *)aProtocolObject; -+ (BOOL) conformsTo: (Protocol *)aProtocolObject; - -/* Obtaining method descriptors from protocols */ - -- (struct objc_method_description *) descriptionForMethod:(SEL)aSel; -+ (struct objc_method_description *) descriptionForInstanceMethod:(SEL)aSel; - -/* Obtaining method handles */ - -- (IMP) methodFor:(SEL)aSelector; -+ (IMP) instanceMethodFor:(SEL)aSelector; - -/* Sending messages determined at run time */ - -- (id)perform:(SEL)aSelector; -- (id)perform:(SEL)aSelector with:anObject; -- (id)perform:(SEL)aSelector with:object1 with:object2; - -/* Posing */ - -+ (id)poseAs: aClassObject; - -/* Enforcing intentions */ - -- (id)subclassResponsibility:(SEL)aSelector; -- (id)notImplemented:(SEL)aSelector; - -/* Error handling */ - -- (id)doesNotRecognize:(SEL)aSelector; -- (id)error:(const char *)aString, ...; - -/* Debugging */ - -- (void) printForDebugger:(void *)stream; - -/* Archiving */ - -- (id)awake; -- (id)write:(void *)stream; -- (id)read:(void *)stream; -+ (int) version; -+ (id)setVersion: (int) aVersion; - -/* Forwarding */ - -- (id)forward: (SEL)sel : (marg_list)args; -- (id)performv: (SEL)sel : (marg_list)args; - -@end - -/* Abstract Protocol for Archiving */ - -@interface Object (Archiving) - -- (id)startArchiving: (void *)stream; -- (id)finishUnarchiving; - -@end - -/* Abstract Protocol for Dynamic Loading */ - -@interface Object (DynamicLoading) - -//+ finishLoading:(headerType *)header; -struct mach_header; -+ (id)finishLoading:(struct mach_header *)header; -+ (id)startUnloading; - -@end - -#endif - -#endif /* _OBJC_OBJECT_H_ */ diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/Protocol.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/Protocol.h deleted file mode 100644 index 0e78850..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/Protocol.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 1999-2003, 2006-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@ - */ -/* - Protocol.h - Copyright 1991-1996 NeXT Software, Inc. -*/ - -#ifndef _OBJC_PROTOCOL_H_ -#define _OBJC_PROTOCOL_H_ - -#if !__OBJC__ - -// typedef Protocol is here: -#include <objc/runtime.h> - - -#elif __OBJC2__ - -#include <objc/NSObject.h> - -// All methods of class Protocol are unavailable. -// Use the functions in objc/runtime.h instead. - -__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) -@interface Protocol : NSObject -@end - - -#else - -#include <objc/Object.h> - -__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) -@interface Protocol : Object -{ -@private - char *protocol_name OBJC2_UNAVAILABLE; - struct objc_protocol_list *protocol_list OBJC2_UNAVAILABLE; - struct objc_method_description_list *instance_methods OBJC2_UNAVAILABLE; - struct objc_method_description_list *class_methods OBJC2_UNAVAILABLE; -} - -/* Obtaining attributes intrinsic to the protocol */ - -- (const char *)name OBJC2_UNAVAILABLE; - -/* Testing protocol conformance */ - -- (BOOL) conformsTo: (Protocol *)aProtocolObject OBJC2_UNAVAILABLE; - -/* Looking up information specific to a protocol */ - -- (struct objc_method_description *) descriptionForInstanceMethod:(SEL)aSel - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); -- (struct objc_method_description *) descriptionForClassMethod:(SEL)aSel - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); - -@end - -#endif - -#endif /* _OBJC_PROTOCOL_H_ */ diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h deleted file mode 100644 index 7f62780..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable.h +++ /dev/null @@ -1,2 +0,0 @@ -#include <objc/hashtable2.h> - diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h deleted file mode 100644 index c6612b8..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/hashtable2.h +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 1999-2006 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@ - */ -/* - hashtable2.h - Scalable hash table. - Copyright 1989-1996 NeXT Software, Inc. - */ - -#ifndef _OBJC_LITTLE_HASHTABLE_H_ -#define _OBJC_LITTLE_HASHTABLE_H_ - -#ifndef _OBJC_PRIVATE_H_ -# define OBJC_HASH_AVAILABILITY __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_1, __IPHONE_NA,__IPHONE_NA); -#else -# define OBJC_HASH_AVAILABILITY -#endif - -#include <objc/objc.h> -#include <stdint.h> -#include <TargetConditionals.h> - -__BEGIN_DECLS - -/************************************************************************* - * Hash tables of arbitrary data - *************************************************************************/ - -/* This module allows hashing of arbitrary data. Such data must be pointers or integers, and client is responsible for allocating/deallocating this data. A deallocation call-back is provided. - The objective C class HashTable is preferred when dealing with (key, values) associations because it is easier to use in that situation. - As well-behaved scalable data structures, hash tables double in size when they start becoming full, thus guaranteeing both average constant time access and linear size. */ - -typedef struct { - uintptr_t (*hash)(const void *info, const void *data); - int (*isEqual)(const void *info, const void *data1, const void *data2); - void (*free)(const void *info, void *data); - int style; /* reserved for future expansion; currently 0 */ -} NXHashTablePrototype; - -/* the info argument allows a certain generality, such as freeing according to some owner information */ -/* invariants assumed by the implementation: - 1 - data1 = data2 => hash(data1) = hash(data2) - when data varies over time, hash(data) must remain invariant - e.g. if data hashes over a string key, the string must not be changed - 2- isEqual (data1, data2) => data1= data2 - */ - -typedef struct { - const NXHashTablePrototype *prototype OBJC_HASH_AVAILABILITY; - unsigned count OBJC_HASH_AVAILABILITY; - unsigned nbBuckets OBJC_HASH_AVAILABILITY; - void *buckets OBJC_HASH_AVAILABILITY; - const void *info OBJC_HASH_AVAILABILITY; -} NXHashTable OBJC_HASH_AVAILABILITY; -/* private data structure; may change */ - -OBJC_EXPORT NXHashTable *NXCreateHashTableFromZone (NXHashTablePrototype prototype, unsigned capacity, const void *info, void *z) OBJC_HASH_AVAILABILITY; -OBJC_EXPORT NXHashTable *NXCreateHashTable (NXHashTablePrototype prototype, unsigned capacity, const void *info) OBJC_HASH_AVAILABILITY; -/* if hash is 0, pointer hash is assumed */ -/* if isEqual is 0, pointer equality is assumed */ -/* if free is 0, elements are not freed */ -/* capacity is only a hint; 0 creates a small table */ -/* info allows call backs to be very general */ - -OBJC_EXPORT void NXFreeHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* calls free for each data, and recovers table */ - -OBJC_EXPORT void NXEmptyHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* does not deallocate table nor data; keeps current capacity */ - -OBJC_EXPORT void NXResetHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* frees each entry; keeps current capacity */ - -OBJC_EXPORT BOOL NXCompareHashTables (NXHashTable *table1, NXHashTable *table2) OBJC_HASH_AVAILABILITY; -/* Returns YES if the two sets are equal (each member of table1 in table2, and table have same size) */ - -OBJC_EXPORT NXHashTable *NXCopyHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* makes a fresh table, copying data pointers, not data itself. */ - -OBJC_EXPORT unsigned NXCountHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* current number of data in table */ - -OBJC_EXPORT int NXHashMember (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* returns non-0 iff data is present in table. - Example of use when the hashed data is a struct containing the key, - and when the callee only has a key: - MyStruct pseudo; - pseudo.key = myKey; - return NXHashMember (myTable, &pseudo) - */ - -OBJC_EXPORT void *NXHashGet (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* return original table data or NULL. - Example of use when the hashed data is a struct containing the key, - and when the callee only has a key: - MyStruct pseudo; - MyStruct *original; - pseudo.key = myKey; - original = NXHashGet (myTable, &pseudo) - */ - -OBJC_EXPORT void *NXHashInsert (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* previous data or NULL is returned. */ - -OBJC_EXPORT void *NXHashInsertIfAbsent (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* If data already in table, returns the one in table - else adds argument to table and returns argument. */ - -OBJC_EXPORT void *NXHashRemove (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* previous data or NULL is returned */ - -/* Iteration over all elements of a table consists in setting up an iteration state and then to progress until all entries have been visited. An example of use for counting elements in a table is: - unsigned count = 0; - MyData *data; - NXHashState state = NXInitHashState(table); - while (NXNextHashState(table, &state, &data)) { - count++; - } - */ - -typedef struct {int i; int j;} NXHashState OBJC_HASH_AVAILABILITY; -/* callers should not rely on actual contents of the struct */ - -OBJC_EXPORT NXHashState NXInitHashState(NXHashTable *table) OBJC_HASH_AVAILABILITY; - -OBJC_EXPORT int NXNextHashState(NXHashTable *table, NXHashState *state, void **data) OBJC_HASH_AVAILABILITY; -/* returns 0 when all elements have been visited */ - -/************************************************************************* - * Conveniences for writing hash, isEqual and free functions - * and common prototypes - *************************************************************************/ - -OBJC_EXPORT uintptr_t NXPtrHash(const void *info, const void *data) OBJC_HASH_AVAILABILITY; -/* scrambles the address bits; info unused */ -OBJC_EXPORT uintptr_t NXStrHash(const void *info, const void *data) OBJC_HASH_AVAILABILITY; -/* string hashing; info unused */ -OBJC_EXPORT int NXPtrIsEqual(const void *info, const void *data1, const void *data2) OBJC_HASH_AVAILABILITY; -/* pointer comparison; info unused */ -OBJC_EXPORT int NXStrIsEqual(const void *info, const void *data1, const void *data2) OBJC_HASH_AVAILABILITY; -/* string comparison; NULL ok; info unused */ -OBJC_EXPORT void NXNoEffectFree(const void *info, void *data) OBJC_HASH_AVAILABILITY; -/* no effect; info unused */ -OBJC_EXPORT void NXReallyFree(const void *info, void *data) OBJC_HASH_AVAILABILITY; -/* frees it; info unused */ - -/* The two following prototypes are useful for manipulating set of pointers or set of strings; For them free is defined as NXNoEffectFree */ -OBJC_EXPORT const NXHashTablePrototype NXPtrPrototype OBJC_HASH_AVAILABILITY; -/* prototype when data is a pointer (void *) */ -OBJC_EXPORT const NXHashTablePrototype NXStrPrototype OBJC_HASH_AVAILABILITY; -/* prototype when data is a string (char *) */ - -/* following prototypes help describe mappings where the key is the first element of a struct and is either a pointer or a string. - For example NXStrStructKeyPrototype can be used to hash pointers to Example, where Example is: - typedef struct { - char *key; - int data1; - ... - } Example - - For the following prototypes, free is defined as NXReallyFree. - */ -OBJC_EXPORT const NXHashTablePrototype NXPtrStructKeyPrototype OBJC_HASH_AVAILABILITY; -OBJC_EXPORT const NXHashTablePrototype NXStrStructKeyPrototype OBJC_HASH_AVAILABILITY; - - -#if !__OBJC2__ && !TARGET_OS_WIN32 - -/************************************************************************* - * Unique strings and buffers - *************************************************************************/ - -/* Unique strings allows C users to enjoy the benefits of Lisp's atoms: - A unique string is a string that is allocated once for all (never de-allocated) and that has only one representant (thus allowing comparison with == instead of strcmp). A unique string should never be modified (and in fact some memory protection is done to ensure that). In order to more explicitly insist on the fact that the string has been uniqued, a synonym of (const char *) has been added, NXAtom. */ - -typedef const char *NXAtom OBJC_HASH_AVAILABILITY; - -OBJC_EXPORT NXAtom NXUniqueString(const char *buffer) OBJC_HASH_AVAILABILITY; -/* assumes that buffer is \0 terminated, and returns - a previously created string or a new string that is a copy of buffer. - If NULL is passed returns NULL. - Returned string should never be modified. To ensure this invariant, - allocations are made in a special read only zone. */ - -OBJC_EXPORT NXAtom NXUniqueStringWithLength(const char *buffer, int length) OBJC_HASH_AVAILABILITY; -/* assumes that buffer is a non NULL buffer of at least - length characters. Returns a previously created string or - a new string that is a copy of buffer. - If buffer contains \0, string will be truncated. - As for NXUniqueString, returned string should never be modified. */ - -OBJC_EXPORT NXAtom NXUniqueStringNoCopy(const char *string) OBJC_HASH_AVAILABILITY; -/* If there is already a unique string equal to string, returns the original. - Otherwise, string is entered in the table, without making a copy. Argument should then never be modified. */ - -OBJC_EXPORT char *NXCopyStringBuffer(const char *buffer) OBJC_HASH_AVAILABILITY; -/* given a buffer, allocates a new string copy of buffer. - Buffer should be \0 terminated; returned string is \0 terminated. */ - -OBJC_EXPORT char *NXCopyStringBufferFromZone(const char *buffer, void *z) OBJC_HASH_AVAILABILITY; -/* given a buffer, allocates a new string copy of buffer. - Buffer should be \0 terminated; returned string is \0 terminated. */ - -#endif - -__END_DECLS - -#endif /* _OBJC_LITTLE_HASHTABLE_H_ */ diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/message.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/message.h deleted file mode 100644 index 9f2a1c6..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/message.h +++ /dev/null @@ -1,333 +0,0 @@ -/* - * 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@ - */ - -#ifndef _OBJC_MESSAGE_H -#define _OBJC_MESSAGE_H - -#pragma GCC system_header - -#include <objc/objc.h> -#include <objc/runtime.h> - -#pragma GCC system_header - -#ifndef OBJC_SUPER -#define OBJC_SUPER - -/// Specifies the superclass of an instance. -struct objc_super { - /// Specifies an instance of a class. - __unsafe_unretained id receiver; - - /// Specifies the particular superclass of the instance to message. -#if !defined(__cplusplus) && !__OBJC2__ - /* For compatibility with old objc-runtime.h header */ - __unsafe_unretained Class class; -#else - __unsafe_unretained Class super_class; -#endif - /* super_class is the first class to search */ -}; -#endif - - -/* Basic Messaging Primitives - * - * On some architectures, use objc_msgSend_stret for some struct return types. - * On some architectures, use objc_msgSend_fpret for some float return types. - * On some architectures, use objc_msgSend_fp2ret for some float return types. - * - * These functions must be cast to an appropriate function pointer type - * before being called. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES -OBJC_EXPORT void objc_msgSend(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -OBJC_EXPORT void objc_msgSendSuper(void /* struct objc_super *super, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -#else -/** - * Sends a message with a simple return value to an instance of a class. - * - * @param self A pointer to the instance of the class that is to receive the message. - * @param op The selector of the method that handles the message. - * @param ... - * A variable argument list containing the arguments to the method. - * - * @return The return value of the method. - * - * @note When it encounters a method call, the compiler generates a call to one of the - * functions \c objc_msgSend, \c objc_msgSend_stret, \c objc_msgSendSuper, or \c objc_msgSendSuper_stret. - * Messages sent to an object’s superclass (using the \c super keyword) are sent using \c objc_msgSendSuper; - * other messages are sent using \c objc_msgSend. Methods that have data structures as return values - * are sent using \c objc_msgSendSuper_stret and \c objc_msgSend_stret. - */ -OBJC_EXPORT id objc_msgSend(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -/** - * Sends a message with a simple return value to the superclass of an instance of a class. - * - * @param super A pointer to an \c objc_super data structure. Pass values identifying the - * context the message was sent to, including the instance of the class that is to receive the - * message and the superclass at which to start searching for the method implementation. - * @param op A pointer of type SEL. Pass the selector of the method that will handle the message. - * @param ... - * A variable argument list containing the arguments to the method. - * - * @return The return value of the method identified by \e op. - * - * @see objc_msgSend - */ -OBJC_EXPORT id objc_msgSendSuper(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -#endif - - -/* Struct-returning Messaging Primitives - * - * Use these functions to call methods that return structs on the stack. - * On some architectures, some structures are returned in registers. - * Consult your local function call ABI documentation for details. - * - * These functions must be cast to an appropriate function pointer type - * before being called. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES -OBJC_EXPORT void objc_msgSend_stret(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -OBJC_EXPORT void objc_msgSendSuper_stret(void /* struct objc_super *super, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -#else -/** - * Sends a message with a data-structure return value to an instance of a class. - * - * @see objc_msgSend - */ -OBJC_EXPORT void objc_msgSend_stret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; - -/** - * Sends a message with a data-structure return value to the superclass of an instance of a class. - * - * @see objc_msgSendSuper - */ -OBJC_EXPORT void objc_msgSendSuper_stret(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -#endif - - -/* Floating-point-returning Messaging Primitives - * - * Use these functions to call methods that return floating-point values - * on the stack. - * Consult your local function call ABI documentation for details. - * - * arm: objc_msgSend_fpret not used - * i386: objc_msgSend_fpret used for `float`, `double`, `long double`. - * x86-64: objc_msgSend_fpret used for `long double`. - * - * arm: objc_msgSend_fp2ret not used - * i386: objc_msgSend_fp2ret not used - * x86-64: objc_msgSend_fp2ret used for `_Complex long double`. - * - * These functions must be cast to an appropriate function pointer type - * before being called. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES - -# if defined(__i386__) - -OBJC_EXPORT void objc_msgSend_fpret(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0); - -# elif defined(__x86_64__) - -OBJC_EXPORT void objc_msgSend_fpret(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_msgSend_fp2ret(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -# endif - -// !OBJC_OLD_DISPATCH_PROTOTYPES -#else -// OBJC_OLD_DISPATCH_PROTOTYPES -# if defined(__i386__) - -/** - * Sends a message with a floating-point return value to an instance of a class. - * - * @see objc_msgSend - * @note On the i386 platform, the ABI for functions returning a floating-point value is - * incompatible with that for functions returning an integral type. On the i386 platform, therefore, - * you must use \c objc_msgSend_fpret for functions returning non-integral type. For \c float or - * \c long \c double return types, cast the function to an appropriate function pointer type first. - */ -OBJC_EXPORT double objc_msgSend_fpret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0); - -/* Use objc_msgSendSuper() for fp-returning messages to super. */ -/* See also objc_msgSendv_fpret() below. */ - -# elif defined(__x86_64__) -/** - * Sends a message with a floating-point return value to an instance of a class. - * - * @see objc_msgSend - */ -OBJC_EXPORT long double objc_msgSend_fpret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -# if __STDC_VERSION__ >= 199901L -OBJC_EXPORT _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -# else -OBJC_EXPORT void objc_msgSend_fp2ret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -# endif - -/* Use objc_msgSendSuper() for fp-returning messages to super. */ -/* See also objc_msgSendv_fpret() below. */ - -# endif - -// OBJC_OLD_DISPATCH_PROTOTYPES -#endif - - -/* Direct Method Invocation Primitives - * Use these functions to call the implementation of a given Method. - * This is faster than calling method_getImplementation() and method_getName(). - * - * The receiver must not be nil. - * - * These functions must be cast to an appropriate function pointer type - * before being called. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES -OBJC_EXPORT void method_invoke(void /* id receiver, Method m, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void method_invoke_stret(void /* id receiver, Method m, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -#else -OBJC_EXPORT id method_invoke(id receiver, Method m, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void method_invoke_stret(id receiver, Method m, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -#endif - - -/* Message Forwarding Primitives - * Use these functions to forward a message as if the receiver did not - * respond to it. - * - * The receiver must not be nil. - * - * class_getMethodImplementation() may return (IMP)_objc_msgForward. - * class_getMethodImplementation_stret() may return (IMP)_objc_msgForward_stret - * - * These functions must be cast to an appropriate function pointer type - * before being called. - * - * Before Mac OS X 10.6, _objc_msgForward must not be called directly - * but may be compared to other IMP values. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES -OBJC_EXPORT void _objc_msgForward(void /* id receiver, SEL sel, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -OBJC_EXPORT void _objc_msgForward_stret(void /* id receiver, SEL sel, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) - OBJC_ARM64_UNAVAILABLE; -#else -OBJC_EXPORT id _objc_msgForward(id receiver, SEL sel, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -OBJC_EXPORT void _objc_msgForward_stret(id receiver, SEL sel, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) - OBJC_ARM64_UNAVAILABLE; -#endif - - -/* Variable-argument Messaging Primitives - * - * Use these functions to call methods with a list of arguments, such - * as the one passed to forward:: . - * - * The contents of the argument list are architecture-specific. - * Consult your local function call ABI documentation for details. - * - * These functions must be cast to an appropriate function pointer type - * before being called, except for objc_msgSendv_stret() which must not - * be cast to a struct-returning type. - */ - -typedef void* marg_list; - -OBJC_EXPORT id objc_msgSendv(id self, SEL op, size_t arg_size, marg_list arg_frame) OBJC2_UNAVAILABLE; -OBJC_EXPORT void objc_msgSendv_stret(void *stretAddr, id self, SEL op, size_t arg_size, marg_list arg_frame) OBJC2_UNAVAILABLE; -/* Note that objc_msgSendv_stret() does not return a structure type, - * and should not be cast to do so. This is unlike objc_msgSend_stret() - * and objc_msgSendSuper_stret(). - */ -#if defined(__i386__) -OBJC_EXPORT double objc_msgSendv_fpret(id self, SEL op, unsigned arg_size, marg_list arg_frame) OBJC2_UNAVAILABLE; -#endif - - -/* The following marg_list macros are of marginal utility. They - * are included for compatibility with the old objc-class.h header. */ - -#if !__OBJC2__ - -#define marg_prearg_size 0 - -#define marg_malloc(margs, method) \ - do { \ - margs = (marg_list *)malloc (marg_prearg_size + ((7 + method_getSizeOfArguments(method)) & ~7)); \ - } while (0) - -#define marg_free(margs) \ - do { \ - free(margs); \ - } while (0) - -#define marg_adjustedOffset(method, offset) \ - (marg_prearg_size + offset) - -#define marg_getRef(margs, offset, type) \ - ( (type *)((char *)margs + marg_adjustedOffset(method,offset) ) ) - -#define marg_getValue(margs, offset, type) \ - ( *marg_getRef(margs, offset, type) ) - -#define marg_setValue(margs, offset, type, value) \ - ( marg_getValue(margs, offset, type) = (value) ) - -#endif - -#endif diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h deleted file mode 100644 index dcc83f9..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-api.h +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (c) 1999-2006 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@ - */ -// Copyright 1988-1996 NeXT Software, Inc. - -#ifndef _OBJC_OBJC_API_H_ -#define _OBJC_OBJC_API_H_ - -#include <Availability.h> -#include <AvailabilityMacros.h> -#include <TargetConditionals.h> - -#ifndef __has_feature -# define __has_feature(x) 0 -#endif - -#ifndef __has_extension -# define __has_extension __has_feature -#endif - -#ifndef __has_attribute -# define __has_attribute(x) 0 -#endif - - -/* - * OBJC_API_VERSION 0 or undef: Tiger and earlier API only - * OBJC_API_VERSION 2: Leopard and later API available - */ -#if !defined(OBJC_API_VERSION) -# if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_5 -# define OBJC_API_VERSION 0 -# else -# define OBJC_API_VERSION 2 -# endif -#endif - - -/* - * OBJC_NO_GC 1: GC is not supported - * OBJC_NO_GC undef: GC is supported - * - * OBJC_NO_GC_API undef: Libraries must export any symbols that - * dual-mode code may links to. - * OBJC_NO_GC_API 1: Libraries need not export GC-related symbols. - */ -#if TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 - /* GC is unsupported. GC API symbols are not exported. */ -# define OBJC_NO_GC 1 -# define OBJC_NO_GC_API 1 -#elif TARGET_OS_MAC && __x86_64h__ - /* GC is unsupported. GC API symbols are exported. */ -# define OBJC_NO_GC 1 -# undef OBJC_NO_GC_API -#else - /* GC is supported. */ -# undef OBJC_NO_GC -# undef OBJC_GC_API -#endif - - -/* NS_ENFORCE_NSOBJECT_DESIGNATED_INITIALIZER == 1 - * marks -[NSObject init] as a designated initializer. */ -#if !defined(NS_ENFORCE_NSOBJECT_DESIGNATED_INITIALIZER) -# define NS_ENFORCE_NSOBJECT_DESIGNATED_INITIALIZER 1 -#endif - - -/* OBJC_OLD_DISPATCH_PROTOTYPES == 0 enforces the rule that the dispatch - * functions must be cast to an appropriate function pointer type. */ -#if !defined(OBJC_OLD_DISPATCH_PROTOTYPES) -# define OBJC_OLD_DISPATCH_PROTOTYPES 1 -#endif - - -/* OBJC_ISA_AVAILABILITY: `isa` will be deprecated or unavailable - * in the future */ -#if !defined(OBJC_ISA_AVAILABILITY) -# if __OBJC2__ -# define OBJC_ISA_AVAILABILITY __attribute__((deprecated)) -# else -# define OBJC_ISA_AVAILABILITY /* still available */ -# endif -#endif - - -/* OBJC2_UNAVAILABLE: unavailable in objc 2.0, deprecated in Leopard */ -#if !defined(OBJC2_UNAVAILABLE) -# if __OBJC2__ -# define OBJC2_UNAVAILABLE UNAVAILABLE_ATTRIBUTE -# else - /* plain C code also falls here, but this is close enough */ -# define OBJC2_UNAVAILABLE __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0) -# endif -#endif - -/* OBJC_ARC_UNAVAILABLE: unavailable with -fobjc-arc */ -#if !defined(OBJC_ARC_UNAVAILABLE) -# if __has_feature(objc_arc) -# if __has_extension(attribute_unavailable_with_message) -# define OBJC_ARC_UNAVAILABLE __attribute__((unavailable("not available in automatic reference counting mode"))) -# else -# define OBJC_ARC_UNAVAILABLE __attribute__((unavailable)) -# endif -# else -# define OBJC_ARC_UNAVAILABLE -# endif -#endif - -/* OBJC_SWIFT_UNAVAILABLE: unavailable in Swift */ -#if !defined(OBJC_SWIFT_UNAVAILABLE) -# if __has_feature(attribute_availability_swift) -# define OBJC_SWIFT_UNAVAILABLE(_msg) __attribute__((availability(swift, unavailable, message=_msg))) -# else -# define OBJC_SWIFT_UNAVAILABLE(_msg) -# endif -#endif - -/* OBJC_ARM64_UNAVAILABLE: unavailable on arm64 (i.e. stret dispatch) */ -#if !defined(OBJC_ARM64_UNAVAILABLE) -# if defined(__arm64__) -# define OBJC_ARM64_UNAVAILABLE __attribute__((unavailable("not available in arm64"))) -# else -# define OBJC_ARM64_UNAVAILABLE -# endif -#endif - -/* OBJC_GC_UNAVAILABLE: unavailable with -fobjc-gc or -fobjc-gc-only */ -#if !defined(OBJC_GC_UNAVAILABLE) -# if __OBJC_GC__ -# if __has_extension(attribute_unavailable_with_message) -# define OBJC_GC_UNAVAILABLE __attribute__((unavailable("not available in garbage collecting mode"))) -# else -# define OBJC_GC_UNAVAILABLE __attribute__((unavailable)) -# endif -# else -# define OBJC_GC_UNAVAILABLE -# endif -#endif - -#if !defined(OBJC_EXTERN) -# if defined(__cplusplus) -# define OBJC_EXTERN extern "C" -# else -# define OBJC_EXTERN extern -# endif -#endif - -#if !defined(OBJC_VISIBLE) -# if TARGET_OS_WIN32 -# if defined(BUILDING_OBJC) -# define OBJC_VISIBLE __declspec(dllexport) -# else -# define OBJC_VISIBLE __declspec(dllimport) -# endif -# else -# define OBJC_VISIBLE __attribute__((visibility("default"))) -# endif -#endif - -#if !defined(OBJC_EXPORT) -# define OBJC_EXPORT OBJC_EXTERN OBJC_VISIBLE -#endif - -#if !defined(OBJC_IMPORT) -# define OBJC_IMPORT extern -#endif - -#if !defined(OBJC_ROOT_CLASS) -# if __has_attribute(objc_root_class) -# define OBJC_ROOT_CLASS __attribute__((objc_root_class)) -# else -# define OBJC_ROOT_CLASS -# endif -#endif - -#ifndef __DARWIN_NULL -#define __DARWIN_NULL NULL -#endif - -#if !defined(OBJC_INLINE) -# define OBJC_INLINE __inline -#endif - -// Declares an enum type or option bits type as appropriate for each language. -#if (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || (!__cplusplus && __has_feature(objc_fixed_enum)) -#define OBJC_ENUM(_type, _name) enum _name : _type _name; enum _name : _type -#if (__cplusplus) -#define OBJC_OPTIONS(_type, _name) _type _name; enum : _type -#else -#define OBJC_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type -#endif -#else -#define OBJC_ENUM(_type, _name) _type _name; enum -#define OBJC_OPTIONS(_type, _name) _type _name; enum -#endif - -#endif diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-auto.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-auto.h deleted file mode 100644 index 8c755a4..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-auto.h +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Copyright (c) 2004-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@ - */ - -#ifndef _OBJC_AUTO_H_ -#define _OBJC_AUTO_H_ - -#pragma GCC system_header - -#include <objc/objc.h> -#include <malloc/malloc.h> -#include <stdint.h> -#include <stddef.h> -#include <string.h> -#include <Availability.h> -#include <TargetConditionals.h> - -#if !TARGET_OS_WIN32 -#include <sys/types.h> -#include <libkern/OSAtomic.h> -#else -# define WINVER 0x0501 // target Windows XP and later -# define _WIN32_WINNT 0x0501 // target Windows XP and later -# define WIN32_LEAN_AND_MEAN -// workaround: windef.h typedefs BOOL as int -# define BOOL WINBOOL -# include <windows.h> -# undef BOOL -#endif - - -/* objc_collect() options */ -enum { - // choose one - OBJC_RATIO_COLLECTION = (0 << 0), // run "ratio" generational collections, then a full - OBJC_GENERATIONAL_COLLECTION = (1 << 0), // run fast incremental collection - OBJC_FULL_COLLECTION = (2 << 0), // run full collection. - OBJC_EXHAUSTIVE_COLLECTION = (3 << 0), // run full collections until memory available stops improving - - OBJC_COLLECT_IF_NEEDED = (1 << 3), // run collection only if needed (allocation threshold exceeded) - OBJC_WAIT_UNTIL_DONE = (1 << 4), // wait (when possible) for collection to end before returning (when collector is running on dedicated thread) -}; - -/* objc_clear_stack() options */ -enum { - OBJC_CLEAR_RESIDENT_STACK = (1 << 0) -}; - -#ifndef OBJC_NO_GC - - -/* GC declarations */ - -/* Collection utilities */ - -OBJC_EXPORT void objc_collect(unsigned long options) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA); -OBJC_EXPORT BOOL objc_collectingEnabled(void) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT malloc_zone_t *objc_collectableZone(void) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/* GC configuration */ - -/* Tells collector to wait until specified bytes have been allocated before trying to collect again. */ -OBJC_EXPORT void objc_setCollectionThreshold(size_t threshold) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - -/* Tells collector to run a full collection for every ratio generational collections. */ -OBJC_EXPORT void objc_setCollectionRatio(size_t ratio) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - -// -// GC-safe compare-and-swap -// - -/* Atomic update, with write barrier. */ -OBJC_EXPORT BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; -/* "Barrier" version also includes memory barrier. */ -OBJC_EXPORT BOOL objc_atomicCompareAndSwapPtrBarrier(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; - -// atomic update of a global variable -OBJC_EXPORT BOOL objc_atomicCompareAndSwapGlobal(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; -OBJC_EXPORT BOOL objc_atomicCompareAndSwapGlobalBarrier(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; -// atomic update of an instance variable -OBJC_EXPORT BOOL objc_atomicCompareAndSwapInstanceVariable(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; -OBJC_EXPORT BOOL objc_atomicCompareAndSwapInstanceVariableBarrier(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; - - -// -// Read and write barriers -// - -OBJC_EXPORT id objc_assign_strongCast(id val, id *dest) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); -OBJC_EXPORT id objc_assign_global(id val, id *dest) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); -OBJC_EXPORT id objc_assign_threadlocal(id val, id *dest) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -OBJC_EXPORT id objc_assign_ivar(id value, id dest, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); -OBJC_EXPORT void *objc_memmove_collectable(void *dst, const void *src, size_t size) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); - -OBJC_EXPORT id objc_read_weak(id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT id objc_assign_weak(id value, id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - - -// -// Thread management -// - -/* Register the calling thread with the garbage collector. */ -OBJC_EXPORT void objc_registerThreadWithCollector(void) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA); - -/* Unregisters the calling thread with the garbage collector. - Unregistration also happens automatically at thread exit. */ -OBJC_EXPORT void objc_unregisterThreadWithCollector(void) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA); - -/* To be called from code which must only execute on a registered thread. */ -/* If the calling thread is unregistered then an error message is emitted and the thread is implicitly registered. */ -OBJC_EXPORT void objc_assertRegisteredThreadWithCollector(void) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA); - -/* Erases any stale references in unused parts of the stack. */ -OBJC_EXPORT void objc_clear_stack(unsigned long options) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - - -// -// Finalization -// - -/* Returns true if object has been scheduled for finalization. Can be used to avoid operations that may lead to resurrection, which are fatal. */ -OBJC_EXPORT BOOL objc_is_finalized(void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); - -// Deprcated. Tells runtime to issue finalize calls on the main thread only. -OBJC_EXPORT void objc_finalizeOnMainThread(Class cls) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); - - -// -// Deprecated names. -// - -/* Deprecated. Use objc_collectingEnabled() instead. */ -OBJC_EXPORT BOOL objc_collecting_enabled(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -/* Deprecated. Use objc_setCollectionThreshold() instead. */ -OBJC_EXPORT void objc_set_collection_threshold(size_t threshold) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -/* Deprecated. Use objc_setCollectionRatio() instead. */ -OBJC_EXPORT void objc_set_collection_ratio(size_t ratio) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -/* Deprecated. Use objc_startCollectorThread() instead. */ -OBJC_EXPORT void objc_start_collector_thread(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -/* Deprecated. No replacement. Formerly told the collector to run using a dedicated background thread. */ -OBJC_EXPORT void objc_startCollectorThread(void) -__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_7, __IPHONE_NA,__IPHONE_NA); - - -/* Deprecated. Use class_createInstance() instead. */ -OBJC_EXPORT id objc_allocate_object(Class cls, int extra) -__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_4, __IPHONE_NA,__IPHONE_NA); - - -/* !defined(OBJC_NO_GC) */ -#else -/* defined(OBJC_NO_GC) */ - - -/* Non-GC declarations */ - -static OBJC_INLINE void objc_collect(unsigned long options __unused) { } -static OBJC_INLINE BOOL objc_collectingEnabled(void) { return NO; } -#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && !TARGET_IPHONE_SIMULATOR -static OBJC_INLINE malloc_zone_t *objc_collectableZone(void) { return nil; } -#endif -static OBJC_INLINE void objc_setCollectionThreshold(size_t threshold __unused) { } -static OBJC_INLINE void objc_setCollectionRatio(size_t ratio __unused) { } -static OBJC_INLINE void objc_startCollectorThread(void) { } - -#if __has_feature(objc_arc) - -/* Covers for GC memory operations are unavailable in ARC */ - -#else - -#if TARGET_OS_WIN32 -static OBJC_INLINE BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) - { void *original = InterlockedCompareExchangePointer((void * volatile *)objectLocation, (void *)replacement, (void *)predicate); return (original == predicate); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapPtrBarrier(id predicate, id replacement, volatile id *objectLocation) - { void *original = InterlockedCompareExchangePointer((void * volatile *)objectLocation, (void *)replacement, (void *)predicate); return (original == predicate); } -#else -static OBJC_INLINE BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) - { return OSAtomicCompareAndSwapPtr((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapPtrBarrier(id predicate, id replacement, volatile id *objectLocation) - { return OSAtomicCompareAndSwapPtrBarrier((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); } -#endif - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapGlobal(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtr(predicate, replacement, objectLocation); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapGlobalBarrier(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtrBarrier(predicate, replacement, objectLocation); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapInstanceVariable(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtr(predicate, replacement, objectLocation); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapInstanceVariableBarrier(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtrBarrier(predicate, replacement, objectLocation); } - - -static OBJC_INLINE id objc_assign_strongCast(id val, id *dest) - { return (*dest = val); } - -static OBJC_INLINE id objc_assign_global(id val, id *dest) - { return (*dest = val); } - -static OBJC_INLINE id objc_assign_threadlocal(id val, id *dest) - { return (*dest = val); } - -static OBJC_INLINE id objc_assign_ivar(id val, id dest, ptrdiff_t offset) - { return (*(id*)((char *)dest+offset) = val); } - -static OBJC_INLINE id objc_read_weak(id *location) - { return *location; } - -static OBJC_INLINE id objc_assign_weak(id value, id *location) - { return (*location = value); } - -/* MRC */ -#endif - -static OBJC_INLINE void *objc_memmove_collectable(void *dst, const void *src, size_t size) - { return memmove(dst, src, size); } - -static OBJC_INLINE void objc_finalizeOnMainThread(Class cls __unused) { } -static OBJC_INLINE BOOL objc_is_finalized(void *ptr __unused) { return NO; } -static OBJC_INLINE void objc_clear_stack(unsigned long options __unused) { } - -static OBJC_INLINE BOOL objc_collecting_enabled(void) { return NO; } -static OBJC_INLINE void objc_set_collection_threshold(size_t threshold __unused) { } -static OBJC_INLINE void objc_set_collection_ratio(size_t ratio __unused) { } -static OBJC_INLINE void objc_start_collector_thread(void) { } - -#if __has_feature(objc_arc) -extern id objc_allocate_object(Class cls, int extra) UNAVAILABLE_ATTRIBUTE; -#else -OBJC_EXPORT id class_createInstance(Class cls, size_t extraBytes) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -static OBJC_INLINE id objc_allocate_object(Class cls, int extra) - { return class_createInstance(cls, extra); } -#endif - -static OBJC_INLINE void objc_registerThreadWithCollector() { } -static OBJC_INLINE void objc_unregisterThreadWithCollector() { } -static OBJC_INLINE void objc_assertRegisteredThreadWithCollector() { } - -/* defined(OBJC_NO_GC) */ -#endif - - -#if TARGET_OS_EMBEDDED -enum { - OBJC_GENERATIONAL = (1 << 0) -}; -static OBJC_INLINE void objc_collect_if_needed(unsigned long options) __attribute__((deprecated)); -static OBJC_INLINE void objc_collect_if_needed(unsigned long options __unused) { } -#endif - -#endif diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-class.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-class.h deleted file mode 100644 index 4599f08..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-class.h +++ /dev/null @@ -1,2 +0,0 @@ -#include <objc/runtime.h> -#include <objc/message.h> diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-exception.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-exception.h deleted file mode 100644 index 40668af..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-exception.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2002-2003, 2006-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@ - */ - -#ifndef __OBJC_EXCEPTION_H_ -#define __OBJC_EXCEPTION_H_ - -#include <objc/objc.h> -#include <stdint.h> - -#if !__OBJC2__ - -// compiler reserves a setjmp buffer + 4 words as localExceptionData - -OBJC_EXPORT void objc_exception_throw(id exception) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); -OBJC_EXPORT void objc_exception_try_enter(void *localExceptionData) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); -OBJC_EXPORT void objc_exception_try_exit(void *localExceptionData) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); -OBJC_EXPORT id objc_exception_extract(void *localExceptionData) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); -OBJC_EXPORT int objc_exception_match(Class exceptionClass, id exception) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - - -typedef struct { - int version; - void (*throw_exc)(id); // version 0 - void (*try_enter)(void *); // version 0 - void (*try_exit)(void *); // version 0 - id (*extract)(void *); // version 0 - int (*match)(Class, id); // version 0 -} objc_exception_functions_t; - -// get table; version tells how many -OBJC_EXPORT void objc_exception_get_functions(objc_exception_functions_t *table) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - -// set table -OBJC_EXPORT void objc_exception_set_functions(objc_exception_functions_t *table) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - - -// !__OBJC2__ -#else -// __OBJC2__ - -typedef id (*objc_exception_preprocessor)(id exception); -typedef int (*objc_exception_matcher)(Class catch_type, id exception); -typedef void (*objc_uncaught_exception_handler)(id exception); -typedef void (*objc_exception_handler)(id unused, void *context); - -/** - * Throw a runtime exception. This function is inserted by the compiler - * where \c @throw would otherwise be. - * - * @param exception The exception to be thrown. - */ -OBJC_EXPORT void objc_exception_throw(id exception) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_exception_rethrow(void) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT id objc_begin_catch(void *exc_buf) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_end_catch(void) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_terminate(void) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); - -OBJC_EXPORT objc_exception_preprocessor objc_setExceptionPreprocessor(objc_exception_preprocessor fn) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT objc_exception_matcher objc_setExceptionMatcher(objc_exception_matcher fn) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT objc_uncaught_exception_handler objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -// Not for iOS. -OBJC_EXPORT uintptr_t objc_addExceptionHandler(objc_exception_handler fn, void *context) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT void objc_removeExceptionHandler(uintptr_t token) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - -// __OBJC2__ -#endif - -#endif // __OBJC_EXCEPTION_H_ - diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-load.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-load.h deleted file mode 100644 index 8ec1fa2..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-load.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 1999-2001, 2005-2006 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@ - */ -/* - * objc-load.h - * Copyright 1988-1996, NeXT Software, Inc. - */ - -#ifndef _OBJC_LOAD_H_ -#define _OBJC_LOAD_H_ - -#include <objc/objc-class.h> - -#include <mach-o/loader.h> - -/* dynamically loading Mach-O object files that contain Objective-C code */ - -OBJC_EXPORT long objc_loadModules ( - char *modlist[], - void *errStream, - void (*class_callback) (Class, Category), - /*headerType*/ struct mach_header **hdr_addr, - char *debug_file -) OBJC2_UNAVAILABLE; -OBJC_EXPORT int objc_loadModule ( - char * moduleName, - void (*class_callback) (Class, Category), - int * errorCode -) OBJC2_UNAVAILABLE; -OBJC_EXPORT long objc_unloadModules( - void *errorStream, /* input (optional) */ - void (*unloadCallback)(Class, Category) /* input (optional) */ -) OBJC2_UNAVAILABLE; - -#endif /* _OBJC_LOAD_H_ */ diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-runtime.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-runtime.h deleted file mode 100644 index 4599f08..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-runtime.h +++ /dev/null @@ -1,2 +0,0 @@ -#include <objc/runtime.h> -#include <objc/message.h> diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-sync.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-sync.h deleted file mode 100644 index 77ecf01..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc-sync.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2002, 2006 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 __OBJC_SNYC_H_ -#define __OBJC_SNYC_H_ - -#include <objc/objc.h> - - -/** - * Begin synchronizing on 'obj'. - * Allocates recursive pthread_mutex associated with 'obj' if needed. - * - * @param obj The object to begin synchronizing on. - * - * @return OBJC_SYNC_SUCCESS once lock is acquired. - */ -OBJC_EXPORT int objc_sync_enter(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_2_0); - -/** - * End synchronizing on 'obj'. - * - * @param obj The objet to end synchronizing on. - * - * @return OBJC_SYNC_SUCCESS or OBJC_SYNC_NOT_OWNING_THREAD_ERROR - */ -OBJC_EXPORT int objc_sync_exit(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_2_0); - -// The wait/notify functions have never worked correctly and no longer exist. -OBJC_EXPORT int objc_sync_wait(id obj, long long milliSecondsMaxWait) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT int objc_sync_notify(id obj) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT int objc_sync_notifyAll(id obj) - UNAVAILABLE_ATTRIBUTE; - -enum { - OBJC_SYNC_SUCCESS = 0, - OBJC_SYNC_NOT_OWNING_THREAD_ERROR = -1, - OBJC_SYNC_TIMED_OUT = -2, - OBJC_SYNC_NOT_INITIALIZED = -3 -}; - - -#endif // __OBJC_SNYC_H_ diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h deleted file mode 100644 index b0554cc..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/objc.h +++ /dev/null @@ -1,229 +0,0 @@ -/* - * 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@ - */ -/* - * objc.h - * Copyright 1988-1996, NeXT Software, Inc. - */ - -#ifndef _OBJC_OBJC_H_ -#define _OBJC_OBJC_H_ - -#include <sys/types.h> // for __DARWIN_NULL -#include <Availability.h> -#include <objc/objc-api.h> -#include <stdbool.h> - -#if !OBJC_TYPES_DEFINED -/// An opaque type that represents an Objective-C class. -typedef struct objc_class *Class; - -/// Represents an instance of a class. -struct objc_object { - Class isa OBJC_ISA_AVAILABILITY; -}; - -/// A pointer to an instance of a class. -typedef struct objc_object *id; -#endif - -/// An opaque type that represents a method selector. -typedef struct objc_selector *SEL; - -/// A pointer to the function of a method implementation. -#if !OBJC_OLD_DISPATCH_PROTOTYPES -typedef void (*IMP)(void /* id, SEL, ... */ ); -#else -typedef id (*IMP)(id, SEL, ...); -#endif - -#define OBJC_BOOL_DEFINED - -/// Type to represent a boolean value. -#if (TARGET_OS_IPHONE && __LP64__) || TARGET_OS_WATCH -#define OBJC_BOOL_IS_BOOL 1 -typedef bool BOOL; -#else -#define OBJC_BOOL_IS_CHAR 1 -typedef signed char BOOL; -// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" -// even if -funsigned-char is used. -#endif - -#if __has_feature(objc_bool) -#define YES __objc_yes -#define NO __objc_no -#else -#define YES ((BOOL)1) -#define NO ((BOOL)0) -#endif - -#ifndef Nil -# if __has_feature(cxx_nullptr) -# define Nil nullptr -# else -# define Nil __DARWIN_NULL -# endif -#endif - -#ifndef nil -# if __has_feature(cxx_nullptr) -# define nil nullptr -# else -# define nil __DARWIN_NULL -# endif -#endif - -#if ! (defined(__OBJC_GC__) || __has_feature(objc_arc)) -#define __strong /* empty */ -#endif - -#if !__has_feature(objc_arc) -#define __unsafe_unretained /* empty */ -#define __autoreleasing /* empty */ -#endif - - -/** - * Returns the name of the method specified by a given selector. - * - * @param sel A pointer of type \c SEL. Pass the selector whose name you wish to determine. - * - * @return A C string indicating the name of the selector. - */ -OBJC_EXPORT const char *sel_getName(SEL sel) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Registers a method with the Objective-C runtime system, maps the method - * name to a selector, and returns the selector value. - * - * @param str A pointer to a C string. Pass the name of the method you wish to register. - * - * @return A pointer of type SEL specifying the selector for the named method. - * - * @note You must register a method name with the Objective-C runtime system to obtain the - * method’s selector before you can add the method to a class definition. If the method name - * has already been registered, this function simply returns the selector. - */ -OBJC_EXPORT SEL sel_registerName(const char *str) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the class name of a given object. - * - * @param obj An Objective-C object. - * - * @return The name of the class of which \e obj is an instance. - */ -OBJC_EXPORT const char *object_getClassName(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a pointer to any extra bytes allocated with an instance given object. - * - * @param obj An Objective-C object. - * - * @return A pointer to any extra bytes allocated with \e obj. If \e obj was - * not allocated with any extra bytes, then dereferencing the returned pointer is undefined. - * - * @note This function returns a pointer to any extra bytes allocated with the instance - * (as specified by \c class_createInstance with extraBytes>0). This memory follows the - * object's ordinary ivars, but may not be adjacent to the last ivar. - * @note The returned pointer is guaranteed to be pointer-size aligned, even if the area following - * the object's last ivar is less aligned than that. Alignment greater than pointer-size is never - * guaranteed, even if the area following the object's last ivar is more aligned than that. - * @note In a garbage-collected environment, the memory is scanned conservatively. - */ -OBJC_EXPORT void *object_getIndexedIvars(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Identifies a selector as being valid or invalid. - * - * @param sel The selector you want to identify. - * - * @return YES if selector is valid and has a function implementation, NO otherwise. - * - * @warning On some platforms, an invalid reference (to invalid memory addresses) can cause - * a crash. - */ -OBJC_EXPORT BOOL sel_isMapped(SEL sel) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Registers a method name with the Objective-C runtime system. - * - * @param str A pointer to a C string. Pass the name of the method you wish to register. - * - * @return A pointer of type SEL specifying the selector for the named method. - * - * @note The implementation of this method is identical to the implementation of \c sel_registerName. - * @note Prior to OS X version 10.0, this method tried to find the selector mapped to the given name - * and returned \c NULL if the selector was not found. This was changed for safety, because it was - * observed that many of the callers of this function did not check the return value for \c NULL. - */ -OBJC_EXPORT SEL sel_getUid(const char *str) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - - -// Obsolete ARC conversions. Deprecation forthcoming. -// Use CFBridgingRetain, CFBridgingRelease, and __bridge casts instead. - -typedef const void* objc_objectptr_t; - -#if __has_feature(objc_arc) -# define objc_retainedObject(o) ((__bridge_transfer id)(objc_objectptr_t)(o)) -# define objc_unretainedObject(o) ((__bridge id)(objc_objectptr_t)(o)) -# define objc_unretainedPointer(o) ((__bridge objc_objectptr_t)(id)(o)) -#else -# define objc_retainedObject(o) ((id)(objc_objectptr_t)(o)) -# define objc_unretainedObject(o) ((id)(objc_objectptr_t)(o)) -# define objc_unretainedPointer(o) ((objc_objectptr_t)(id)(o)) -#endif - - -#if !__OBJC2__ - -// The following declarations are provided here for source compatibility. - -#if defined(__LP64__) - typedef long arith_t; - typedef unsigned long uarith_t; -# define ARITH_SHIFT 32 -#else - typedef int arith_t; - typedef unsigned uarith_t; -# define ARITH_SHIFT 16 -#endif - -typedef char *STR; - -#define ISSELECTOR(sel) sel_isMapped(sel) -#define SELNAME(sel) sel_getName(sel) -#define SELUID(str) sel_getUid(str) -#define NAMEOF(obj) object_getClassName(obj) -#define IV(obj) object_getIndexedIvars(obj) - -#endif - -#endif /* _OBJC_OBJC_H_ */ diff --git a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h b/objc/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h deleted file mode 100644 index 7c7ce6e..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/include/objc/runtime.h +++ /dev/null @@ -1,1780 +0,0 @@ -/* - * 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@ - */ - -#ifndef _OBJC_RUNTIME_H -#define _OBJC_RUNTIME_H - -#include <objc/objc.h> -#include <stdarg.h> -#include <stdint.h> -#include <stddef.h> -#include <Availability.h> -#include <TargetConditionals.h> - -#if TARGET_OS_MAC -#include <sys/types.h> -#endif - - -/* Types */ - -#if !OBJC_TYPES_DEFINED - -/// An opaque type that represents a method in a class definition. -typedef struct objc_method *Method; - -/// An opaque type that represents an instance variable. -typedef struct objc_ivar *Ivar; - -/// An opaque type that represents a category. -typedef struct objc_category *Category; - -/// An opaque type that represents an Objective-C declared property. -typedef struct objc_property *objc_property_t; - -struct objc_class { - Class isa OBJC_ISA_AVAILABILITY; - -#if !__OBJC2__ - Class super_class OBJC2_UNAVAILABLE; - const char *name OBJC2_UNAVAILABLE; - long version OBJC2_UNAVAILABLE; - long info OBJC2_UNAVAILABLE; - long instance_size OBJC2_UNAVAILABLE; - struct objc_ivar_list *ivars OBJC2_UNAVAILABLE; - struct objc_method_list **methodLists OBJC2_UNAVAILABLE; - struct objc_cache *cache OBJC2_UNAVAILABLE; - struct objc_protocol_list *protocols OBJC2_UNAVAILABLE; -#endif - -} OBJC2_UNAVAILABLE; -/* Use `Class` instead of `struct objc_class *` */ - -#endif - -#ifdef __OBJC__ -@class Protocol; -#else -typedef struct objc_object Protocol; -#endif - -/// Defines a method -struct objc_method_description { - SEL name; /**< The name of the method */ - char *types; /**< The types of the method arguments */ -}; - -/// Defines a property attribute -typedef struct { - const char *name; /**< The name of the attribute */ - const char *value; /**< The value of the attribute (usually empty) */ -} objc_property_attribute_t; - - -/* Functions */ - -/* Working with Instances */ - -/** - * Returns a copy of a given object. - * - * @param obj An Objective-C object. - * @param size The size of the object \e obj. - * - * @return A copy of \e obj. - */ -OBJC_EXPORT id object_copy(id obj, size_t size) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Frees the memory occupied by a given object. - * - * @param obj An Objective-C object. - * - * @return nil - */ -OBJC_EXPORT id object_dispose(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Returns the class of an object. - * - * @param obj The object you want to inspect. - * - * @return The class object of which \e object is an instance, - * or \c Nil if \e object is \c nil. - */ -OBJC_EXPORT Class object_getClass(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the class of an object. - * - * @param obj The object to modify. - * @param cls A class object. - * - * @return The previous value of \e object's class, or \c Nil if \e object is \c nil. - */ -OBJC_EXPORT Class object_setClass(id obj, Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/** - * Returns whether an object is a class object. - * - * @param obj An Objective-C object. - * - * @return true if the object is a class or metaclass, false otherwise. - */ -OBJC_EXPORT BOOL object_isClass(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0); - - -/** - * Returns the class name of a given object. - * - * @param obj An Objective-C object. - * - * @return The name of the class of which \e obj is an instance. - */ -OBJC_EXPORT const char *object_getClassName(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a pointer to any extra bytes allocated with an instance given object. - * - * @param obj An Objective-C object. - * - * @return A pointer to any extra bytes allocated with \e obj. If \e obj was - * not allocated with any extra bytes, then dereferencing the returned pointer is undefined. - * - * @note This function returns a pointer to any extra bytes allocated with the instance - * (as specified by \c class_createInstance with extraBytes>0). This memory follows the - * object's ordinary ivars, but may not be adjacent to the last ivar. - * @note The returned pointer is guaranteed to be pointer-size aligned, even if the area following - * the object's last ivar is less aligned than that. Alignment greater than pointer-size is never - * guaranteed, even if the area following the object's last ivar is more aligned than that. - * @note In a garbage-collected environment, the memory is scanned conservatively. - */ -OBJC_EXPORT void *object_getIndexedIvars(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Reads the value of an instance variable in an object. - * - * @param obj The object containing the instance variable whose value you want to read. - * @param ivar The Ivar describing the instance variable whose value you want to read. - * - * @return The value of the instance variable specified by \e ivar, or \c nil if \e object is \c nil. - * - * @note \c object_getIvar is faster than \c object_getInstanceVariable if the Ivar - * for the instance variable is already known. - */ -OBJC_EXPORT id object_getIvar(id obj, Ivar ivar) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the value of an instance variable in an object. - * - * @param obj The object containing the instance variable whose value you want to set. - * @param ivar The Ivar describing the instance variable whose value you want to set. - * @param value The new value for the instance variable. - * - * @note \c object_setIvar is faster than \c object_setInstanceVariable if the Ivar - * for the instance variable is already known. - */ -OBJC_EXPORT void object_setIvar(id obj, Ivar ivar, id value) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Changes the value of an instance variable of a class instance. - * - * @param obj A pointer to an instance of a class. Pass the object containing - * the instance variable whose value you wish to modify. - * @param name A C string. Pass the name of the instance variable whose value you wish to modify. - * @param value The new value for the instance variable. - * - * @return A pointer to the \c Ivar data structure that defines the type and - * name of the instance variable specified by \e name. - */ -OBJC_EXPORT Ivar object_setInstanceVariable(id obj, const char *name, void *value) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Obtains the value of an instance variable of a class instance. - * - * @param obj A pointer to an instance of a class. Pass the object containing - * the instance variable whose value you wish to obtain. - * @param name A C string. Pass the name of the instance variable whose value you wish to obtain. - * @param outValue On return, contains a pointer to the value of the instance variable. - * - * @return A pointer to the \c Ivar data structure that defines the type and name of - * the instance variable specified by \e name. - */ -OBJC_EXPORT Ivar object_getInstanceVariable(id obj, const char *name, void **outValue) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - - -/* Obtaining Class Definitions */ - -/** - * Returns the class definition of a specified class. - * - * @param name The name of the class to look up. - * - * @return The Class object for the named class, or \c nil - * if the class is not registered with the Objective-C runtime. - * - * @note \c objc_getClass is different from \c objc_lookUpClass in that if the class - * is not registered, \c objc_getClass calls the class handler callback and then checks - * a second time to see whether the class is registered. \c objc_lookUpClass does - * not call the class handler callback. - * - * @warning Earlier implementations of this function (prior to OS X v10.0) - * terminate the program if the class does not exist. - */ -OBJC_EXPORT Class objc_getClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the metaclass definition of a specified class. - * - * @param name The name of the class to look up. - * - * @return The \c Class object for the metaclass of the named class, or \c nil if the class - * is not registered with the Objective-C runtime. - * - * @note If the definition for the named class is not registered, this function calls the class handler - * callback and then checks a second time to see if the class is registered. However, every class - * definition must have a valid metaclass definition, and so the metaclass definition is always returned, - * whether it’s valid or not. - */ -OBJC_EXPORT Class objc_getMetaClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the class definition of a specified class. - * - * @param name The name of the class to look up. - * - * @return The Class object for the named class, or \c nil if the class - * is not registered with the Objective-C runtime. - * - * @note \c objc_getClass is different from this function in that if the class is not - * registered, \c objc_getClass calls the class handler callback and then checks a second - * time to see whether the class is registered. This function does not call the class handler callback. - */ -OBJC_EXPORT Class objc_lookUpClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the class definition of a specified class. - * - * @param name The name of the class to look up. - * - * @return The Class object for the named class. - * - * @note This function is the same as \c objc_getClass, but kills the process if the class is not found. - * @note This function is used by ZeroLink, where failing to find a class would be a compile-time link error without ZeroLink. - */ -OBJC_EXPORT Class objc_getRequiredClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Obtains the list of registered class definitions. - * - * @param buffer An array of \c Class values. On output, each \c Class value points to - * one class definition, up to either \e bufferCount or the total number of registered classes, - * whichever is less. You can pass \c NULL to obtain the total number of registered class - * definitions without actually retrieving any class definitions. - * @param bufferCount An integer value. Pass the number of pointers for which you have allocated space - * in \e buffer. On return, this function fills in only this number of elements. If this number is less - * than the number of registered classes, this function returns an arbitrary subset of the registered classes. - * - * @return An integer value indicating the total number of registered classes. - * - * @note The Objective-C runtime library automatically registers all the classes defined in your source code. - * You can create class definitions at runtime and register them with the \c objc_addClass function. - * - * @warning You cannot assume that class objects you get from this function are classes that inherit from \c NSObject, - * so you cannot safely call any methods on such classes without detecting that the method is implemented first. - */ -OBJC_EXPORT int objc_getClassList(Class *buffer, int bufferCount) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Creates and returns a list of pointers to all registered class definitions. - * - * @param outCount An integer pointer used to store the number of classes returned by - * this function in the list. It can be \c nil. - * - * @return A nil terminated array of classes. It must be freed with \c free(). - * - * @see objc_getClassList - */ -OBJC_EXPORT Class *objc_copyClassList(unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_1); - - -/* Working with Classes */ - -/** - * Returns the name of a class. - * - * @param cls A class object. - * - * @return The name of the class, or the empty string if \e cls is \c Nil. - */ -OBJC_EXPORT const char *class_getName(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether a class object is a metaclass. - * - * @param cls A class object. - * - * @return \c YES if \e cls is a metaclass, \c NO if \e cls is a non-meta class, - * \c NO if \e cls is \c Nil. - */ -OBJC_EXPORT BOOL class_isMetaClass(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the superclass of a class. - * - * @param cls A class object. - * - * @return The superclass of the class, or \c Nil if - * \e cls is a root class, or \c Nil if \e cls is \c Nil. - * - * @note You should usually use \c NSObject's \c superclass method instead of this function. - */ -OBJC_EXPORT Class class_getSuperclass(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the superclass of a given class. - * - * @param cls The class whose superclass you want to set. - * @param newSuper The new superclass for cls. - * - * @return The old superclass for cls. - * - * @warning You should not use this function. - */ -OBJC_EXPORT Class class_setSuperclass(Class cls, Class newSuper) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); - -/** - * Returns the version number of a class definition. - * - * @param cls A pointer to a \c Class data structure. Pass - * the class definition for which you wish to obtain the version. - * - * @return An integer indicating the version number of the class definition. - * - * @see class_setVersion - */ -OBJC_EXPORT int class_getVersion(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Sets the version number of a class definition. - * - * @param cls A pointer to an Class data structure. - * Pass the class definition for which you wish to set the version. - * @param version An integer. Pass the new version number of the class definition. - * - * @note You can use the version number of the class definition to provide versioning of the - * interface that your class represents to other classes. This is especially useful for object - * serialization (that is, archiving of the object in a flattened form), where it is important to - * recognize changes to the layout of the instance variables in different class-definition versions. - * @note Classes derived from the Foundation framework \c NSObject class can set the class-definition - * version number using the \c setVersion: class method, which is implemented using the \c class_setVersion function. - */ -OBJC_EXPORT void class_setVersion(Class cls, int version) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the size of instances of a class. - * - * @param cls A class object. - * - * @return The size in bytes of instances of the class \e cls, or \c 0 if \e cls is \c Nil. - */ -OBJC_EXPORT size_t class_getInstanceSize(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the \c Ivar for a specified instance variable of a given class. - * - * @param cls The class whose instance variable you wish to obtain. - * @param name The name of the instance variable definition to obtain. - * - * @return A pointer to an \c Ivar data structure containing information about - * the instance variable specified by \e name. - */ -OBJC_EXPORT Ivar class_getInstanceVariable(Class cls, const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the Ivar for a specified class variable of a given class. - * - * @param cls The class definition whose class variable you wish to obtain. - * @param name The name of the class variable definition to obtain. - * - * @return A pointer to an \c Ivar data structure containing information about the class variable specified by \e name. - */ -OBJC_EXPORT Ivar class_getClassVariable(Class cls, const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Describes the instance variables declared by a class. - * - * @param cls The class to inspect. - * @param outCount On return, contains the length of the returned array. - * If outCount is NULL, the length is not returned. - * - * @return An array of pointers of type Ivar describing the instance variables declared by the class. - * Any instance variables declared by superclasses are not included. The array contains *outCount - * pointers followed by a NULL terminator. You must free the array with free(). - * - * If the class declares no instance variables, or cls is Nil, NULL is returned and *outCount is 0. - */ -OBJC_EXPORT Ivar *class_copyIvarList(Class cls, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a specified instance method for a given class. - * - * @param cls The class you want to inspect. - * @param name The selector of the method you want to retrieve. - * - * @return The method that corresponds to the implementation of the selector specified by - * \e name for the class specified by \e cls, or \c NULL if the specified class or its - * superclasses do not contain an instance method with the specified selector. - * - * @note This function searches superclasses for implementations, whereas \c class_copyMethodList does not. - */ -OBJC_EXPORT Method class_getInstanceMethod(Class cls, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a pointer to the data structure describing a given class method for a given class. - * - * @param cls A pointer to a class definition. Pass the class that contains the method you want to retrieve. - * @param name A pointer of type \c SEL. Pass the selector of the method you want to retrieve. - * - * @return A pointer to the \c Method data structure that corresponds to the implementation of the - * selector specified by aSelector for the class specified by aClass, or NULL if the specified - * class or its superclasses do not contain an instance method with the specified selector. - * - * @note Note that this function searches superclasses for implementations, - * whereas \c class_copyMethodList does not. - */ -OBJC_EXPORT Method class_getClassMethod(Class cls, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the function pointer that would be called if a - * particular message were sent to an instance of a class. - * - * @param cls The class you want to inspect. - * @param name A selector. - * - * @return The function pointer that would be called if \c [object name] were called - * with an instance of the class, or \c NULL if \e cls is \c Nil. - * - * @note \c class_getMethodImplementation may be faster than \c method_getImplementation(class_getInstanceMethod(cls, name)). - * @note The function pointer returned may be a function internal to the runtime instead of - * an actual method implementation. For example, if instances of the class do not respond to - * the selector, the function pointer returned will be part of the runtime's message forwarding machinery. - */ -OBJC_EXPORT IMP class_getMethodImplementation(Class cls, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the function pointer that would be called if a particular - * message were sent to an instance of a class. - * - * @param cls The class you want to inspect. - * @param name A selector. - * - * @return The function pointer that would be called if \c [object name] were called - * with an instance of the class, or \c NULL if \e cls is \c Nil. - */ -OBJC_EXPORT IMP class_getMethodImplementation_stret(Class cls, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; - -/** - * Returns a Boolean value that indicates whether instances of a class respond to a particular selector. - * - * @param cls The class you want to inspect. - * @param sel A selector. - * - * @return \c YES if instances of the class respond to the selector, otherwise \c NO. - * - * @note You should usually use \c NSObject's \c respondsToSelector: or \c instancesRespondToSelector: - * methods instead of this function. - */ -OBJC_EXPORT BOOL class_respondsToSelector(Class cls, SEL sel) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Describes the instance methods implemented by a class. - * - * @param cls The class you want to inspect. - * @param outCount On return, contains the length of the returned array. - * If outCount is NULL, the length is not returned. - * - * @return An array of pointers of type Method describing the instance methods - * implemented by the class—any instance methods implemented by superclasses are not included. - * The array contains *outCount pointers followed by a NULL terminator. You must free the array with free(). - * - * If cls implements no instance methods, or cls is Nil, returns NULL and *outCount is 0. - * - * @note To get the class methods of a class, use \c class_copyMethodList(object_getClass(cls), &count). - * @note To get the implementations of methods that may be implemented by superclasses, - * use \c class_getInstanceMethod or \c class_getClassMethod. - */ -OBJC_EXPORT Method *class_copyMethodList(Class cls, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether a class conforms to a given protocol. - * - * @param cls The class you want to inspect. - * @param protocol A protocol. - * - * @return YES if cls conforms to protocol, otherwise NO. - * - * @note You should usually use NSObject's conformsToProtocol: method instead of this function. - */ -OBJC_EXPORT BOOL class_conformsToProtocol(Class cls, Protocol *protocol) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Describes the protocols adopted by a class. - * - * @param cls The class you want to inspect. - * @param outCount On return, contains the length of the returned array. - * If outCount is NULL, the length is not returned. - * - * @return An array of pointers of type Protocol* describing the protocols adopted - * by the class. Any protocols adopted by superclasses or other protocols are not included. - * The array contains *outCount pointers followed by a NULL terminator. You must free the array with free(). - * - * If cls adopts no protocols, or cls is Nil, returns NULL and *outCount is 0. - */ -OBJC_EXPORT Protocol * __unsafe_unretained *class_copyProtocolList(Class cls, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a property with a given name of a given class. - * - * @param cls The class you want to inspect. - * @param name The name of the property you want to inspect. - * - * @return A pointer of type \c objc_property_t describing the property, or - * \c NULL if the class does not declare a property with that name, - * or \c NULL if \e cls is \c Nil. - */ -OBJC_EXPORT objc_property_t class_getProperty(Class cls, const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Describes the properties declared by a class. - * - * @param cls The class you want to inspect. - * @param outCount On return, contains the length of the returned array. - * If \e outCount is \c NULL, the length is not returned. - * - * @return An array of pointers of type \c objc_property_t describing the properties - * declared by the class. Any properties declared by superclasses are not included. - * The array contains \c *outCount pointers followed by a \c NULL terminator. You must free the array with \c free(). - * - * If \e cls declares no properties, or \e cls is \c Nil, returns \c NULL and \c *outCount is \c 0. - */ -OBJC_EXPORT objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a description of the \c Ivar layout for a given class. - * - * @param cls The class to inspect. - * - * @return A description of the \c Ivar layout for \e cls. - */ -OBJC_EXPORT const uint8_t *class_getIvarLayout(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a description of the layout of weak Ivars for a given class. - * - * @param cls The class to inspect. - * - * @return A description of the layout of the weak \c Ivars for \e cls. - */ -OBJC_EXPORT const uint8_t *class_getWeakIvarLayout(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Adds a new method to a class with a given name and implementation. - * - * @param cls The class to which to add a method. - * @param name A selector that specifies the name of the method being added. - * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd. - * @param types An array of characters that describe the types of the arguments to the method. - * - * @return YES if the method was added successfully, otherwise NO - * (for example, the class already contains a method implementation with that name). - * - * @note class_addMethod will add an override of a superclass's implementation, - * but will not replace an existing implementation in this class. - * To change an existing implementation, use method_setImplementation. - */ -OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, - const char *types) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Replaces the implementation of a method for a given class. - * - * @param cls The class you want to modify. - * @param name A selector that identifies the method whose implementation you want to replace. - * @param imp The new implementation for the method identified by name for the class identified by cls. - * @param types An array of characters that describe the types of the arguments to the method. - * Since the function must take at least two arguments—self and _cmd, the second and third characters - * must be “@:” (the first character is the return type). - * - * @return The previous implementation of the method identified by \e name for the class identified by \e cls. - * - * @note This function behaves in two different ways: - * - If the method identified by \e name does not yet exist, it is added as if \c class_addMethod were called. - * The type encoding specified by \e types is used as given. - * - If the method identified by \e name does exist, its \c IMP is replaced as if \c method_setImplementation were called. - * The type encoding specified by \e types is ignored. - */ -OBJC_EXPORT IMP class_replaceMethod(Class cls, SEL name, IMP imp, - const char *types) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Adds a new instance variable to a class. - * - * @return YES if the instance variable was added successfully, otherwise NO - * (for example, the class already contains an instance variable with that name). - * - * @note This function may only be called after objc_allocateClassPair and before objc_registerClassPair. - * Adding an instance variable to an existing class is not supported. - * @note The class must not be a metaclass. Adding an instance variable to a metaclass is not supported. - * @note The instance variable's minimum alignment in bytes is 1<<align. The minimum alignment of an instance - * variable depends on the ivar's type and the machine architecture. - * For variables of any pointer type, pass log2(sizeof(pointer_type)). - */ -OBJC_EXPORT BOOL class_addIvar(Class cls, const char *name, size_t size, - uint8_t alignment, const char *types) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Adds a protocol to a class. - * - * @param cls The class to modify. - * @param protocol The protocol to add to \e cls. - * - * @return \c YES if the method was added successfully, otherwise \c NO - * (for example, the class already conforms to that protocol). - */ -OBJC_EXPORT BOOL class_addProtocol(Class cls, Protocol *protocol) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Adds a property to a class. - * - * @param cls The class to modify. - * @param name The name of the property. - * @param attributes An array of property attributes. - * @param attributeCount The number of attributes in \e attributes. - * - * @return \c YES if the property was added successfully, otherwise \c NO - * (for example, the class already has that property). - */ -OBJC_EXPORT BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Replace a property of a class. - * - * @param cls The class to modify. - * @param name The name of the property. - * @param attributes An array of property attributes. - * @param attributeCount The number of attributes in \e attributes. - */ -OBJC_EXPORT void class_replaceProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Sets the Ivar layout for a given class. - * - * @param cls The class to modify. - * @param layout The layout of the \c Ivars for \e cls. - */ -OBJC_EXPORT void class_setIvarLayout(Class cls, const uint8_t *layout) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the layout for weak Ivars for a given class. - * - * @param cls The class to modify. - * @param layout The layout of the weak Ivars for \e cls. - */ -OBJC_EXPORT void class_setWeakIvarLayout(Class cls, const uint8_t *layout) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Used by CoreFoundation's toll-free bridging. - * Return the id of the named class. - * - * @return The id of the named class, or an uninitialized class - * structure that will be used for the class when and if it does - * get loaded. - * - * @warning Do not call this function yourself. - */ -OBJC_EXPORT Class objc_getFutureClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - - -/* Instantiating Classes */ - -/** - * Creates an instance of a class, allocating memory for the class in the - * default malloc memory zone. - * - * @param cls The class that you wish to allocate an instance of. - * @param extraBytes An integer indicating the number of extra bytes to allocate. - * The additional bytes can be used to store additional instance variables beyond - * those defined in the class definition. - * - * @return An instance of the class \e cls. - */ -OBJC_EXPORT id class_createInstance(Class cls, size_t extraBytes) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Creates an instance of a class at the specific location provided. - * - * @param cls The class that you wish to allocate an instance of. - * @param bytes The location at which to allocate an instance of \e cls. - * Must point to at least \c class_getInstanceSize(cls) bytes of well-aligned, - * zero-filled memory. - * - * @return \e bytes on success, \c nil otherwise. (For example, \e cls or \e bytes - * might be \c nil) - * - * @see class_createInstance - */ -OBJC_EXPORT id objc_constructInstance(Class cls, void *bytes) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Destroys an instance of a class without freeing memory and removes any - * associated references this instance might have had. - * - * @param obj The class instance to destroy. - * - * @return \e obj. Does nothing if \e obj is nil. - * - * @warning GC does not call this. If you edit this, also edit finalize. - * - * @note CF and other clients do call this under GC. - */ -OBJC_EXPORT void *objc_destructInstance(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) - OBJC_ARC_UNAVAILABLE; - - -/* Adding Classes */ - -/** - * Creates a new class and metaclass. - * - * @param superclass The class to use as the new class's superclass, or \c Nil to create a new root class. - * @param name The string to use as the new class's name. The string will be copied. - * @param extraBytes The number of bytes to allocate for indexed ivars at the end of - * the class and metaclass objects. This should usually be \c 0. - * - * @return The new class, or Nil if the class could not be created (for example, the desired name is already in use). - * - * @note You can get a pointer to the new metaclass by calling \c object_getClass(newClass). - * @note To create a new class, start by calling \c objc_allocateClassPair. - * Then set the class's attributes with functions like \c class_addMethod and \c class_addIvar. - * When you are done building the class, call \c objc_registerClassPair. The new class is now ready for use. - * @note Instance methods and instance variables should be added to the class itself. - * Class methods should be added to the metaclass. - */ -OBJC_EXPORT Class objc_allocateClassPair(Class superclass, const char *name, - size_t extraBytes) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Registers a class that was allocated using \c objc_allocateClassPair. - * - * @param cls The class you want to register. - */ -OBJC_EXPORT void objc_registerClassPair(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Used by Foundation's Key-Value Observing. - * - * @warning Do not call this function yourself. - */ -OBJC_EXPORT Class objc_duplicateClass(Class original, const char *name, size_t extraBytes) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Destroy a class and its associated metaclass. - * - * @param cls The class to be destroyed. It must have been allocated with - * \c objc_allocateClassPair - * - * @warning Do not call if instances of this class or a subclass exist. - */ -OBJC_EXPORT void objc_disposeClassPair(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Working with Methods */ - -/** - * Returns the name of a method. - * - * @param m The method to inspect. - * - * @return A pointer of type SEL. - * - * @note To get the method name as a C string, call \c sel_getName(method_getName(method)). - */ -OBJC_EXPORT SEL method_getName(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the implementation of a method. - * - * @param m The method to inspect. - * - * @return A function pointer of type IMP. - */ -OBJC_EXPORT IMP method_getImplementation(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a string describing a method's parameter and return types. - * - * @param m The method to inspect. - * - * @return A C string. The string may be \c NULL. - */ -OBJC_EXPORT const char *method_getTypeEncoding(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the number of arguments accepted by a method. - * - * @param m A pointer to a \c Method data structure. Pass the method in question. - * - * @return An integer containing the number of arguments accepted by the given method. - */ -OBJC_EXPORT unsigned int method_getNumberOfArguments(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a string describing a method's return type. - * - * @param m The method to inspect. - * - * @return A C string describing the return type. You must free the string with \c free(). - */ -OBJC_EXPORT char *method_copyReturnType(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a string describing a single parameter type of a method. - * - * @param m The method to inspect. - * @param index The index of the parameter to inspect. - * - * @return A C string describing the type of the parameter at index \e index, or \c NULL - * if method has no parameter index \e index. You must free the string with \c free(). - */ -OBJC_EXPORT char *method_copyArgumentType(Method m, unsigned int index) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns by reference a string describing a method's return type. - * - * @param m The method you want to inquire about. - * @param dst The reference string to store the description. - * @param dst_len The maximum number of characters that can be stored in \e dst. - * - * @note The method's return type string is copied to \e dst. - * \e dst is filled as if \c strncpy(dst, parameter_type, dst_len) were called. - */ -OBJC_EXPORT void method_getReturnType(Method m, char *dst, size_t dst_len) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns by reference a string describing a single parameter type of a method. - * - * @param m The method you want to inquire about. - * @param index The index of the parameter you want to inquire about. - * @param dst The reference string to store the description. - * @param dst_len The maximum number of characters that can be stored in \e dst. - * - * @note The parameter type string is copied to \e dst. \e dst is filled as if \c strncpy(dst, parameter_type, dst_len) - * were called. If the method contains no parameter with that index, \e dst is filled as - * if \c strncpy(dst, "", dst_len) were called. - */ -OBJC_EXPORT void method_getArgumentType(Method m, unsigned int index, - char *dst, size_t dst_len) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT struct objc_method_description *method_getDescription(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the implementation of a method. - * - * @param m The method for which to set an implementation. - * @param imp The implemention to set to this method. - * - * @return The previous implementation of the method. - */ -OBJC_EXPORT IMP method_setImplementation(Method m, IMP imp) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Exchanges the implementations of two methods. - * - * @param m1 Method to exchange with second method. - * @param m2 Method to exchange with first method. - * - * @note This is an atomic version of the following: - * \code - * IMP imp1 = method_getImplementation(m1); - * IMP imp2 = method_getImplementation(m2); - * method_setImplementation(m1, imp2); - * method_setImplementation(m2, imp1); - * \endcode - */ -OBJC_EXPORT void method_exchangeImplementations(Method m1, Method m2) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Working with Instance Variables */ - -/** - * Returns the name of an instance variable. - * - * @param v The instance variable you want to enquire about. - * - * @return A C string containing the instance variable's name. - */ -OBJC_EXPORT const char *ivar_getName(Ivar v) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the type string of an instance variable. - * - * @param v The instance variable you want to enquire about. - * - * @return A C string containing the instance variable's type encoding. - * - * @note For possible values, see Objective-C Runtime Programming Guide > Type Encodings. - */ -OBJC_EXPORT const char *ivar_getTypeEncoding(Ivar v) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the offset of an instance variable. - * - * @param v The instance variable you want to enquire about. - * - * @return The offset of \e v. - * - * @note For instance variables of type \c id or other object types, call \c object_getIvar - * and \c object_setIvar instead of using this offset to access the instance variable data directly. - */ -OBJC_EXPORT ptrdiff_t ivar_getOffset(Ivar v) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Working with Properties */ - -/** - * Returns the name of a property. - * - * @param property The property you want to inquire about. - * - * @return A C string containing the property's name. - */ -OBJC_EXPORT const char *property_getName(objc_property_t property) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the attribute string of a property. - * - * @param property A property. - * - * @return A C string containing the property's attributes. - * - * @note The format of the attribute string is described in Declared Properties in Objective-C Runtime Programming Guide. - */ -OBJC_EXPORT const char *property_getAttributes(objc_property_t property) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of property attributes for a property. - * - * @param property The property whose attributes you want copied. - * @param outCount The number of attributes returned in the array. - * - * @return An array of property attributes; must be free'd() by the caller. - */ -OBJC_EXPORT objc_property_attribute_t *property_copyAttributeList(objc_property_t property, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Returns the value of a property attribute given the attribute name. - * - * @param property The property whose attribute value you are interested in. - * @param attributeName C string representing the attribute name. - * - * @return The value string of the attribute \e attributeName if it exists in - * \e property, \c nil otherwise. - */ -OBJC_EXPORT char *property_copyAttributeValue(objc_property_t property, const char *attributeName) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - - -/* Working with Protocols */ - -/** - * Returns a specified protocol. - * - * @param name The name of a protocol. - * - * @return The protocol named \e name, or \c NULL if no protocol named \e name could be found. - * - * @note This function acquires the runtime lock. - */ -OBJC_EXPORT Protocol *objc_getProtocol(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of all the protocols known to the runtime. - * - * @param outCount Upon return, contains the number of protocols in the returned array. - * - * @return A C array of all the protocols known to the runtime. The array contains \c *outCount - * pointers followed by a \c NULL terminator. You must free the list with \c free(). - * - * @note This function acquires the runtime lock. - */ -OBJC_EXPORT Protocol * __unsafe_unretained *objc_copyProtocolList(unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether one protocol conforms to another protocol. - * - * @param proto A protocol. - * @param other A protocol. - * - * @return \c YES if \e proto conforms to \e other, otherwise \c NO. - * - * @note One protocol can incorporate other protocols using the same syntax - * that classes use to adopt a protocol: - * \code - * @protocol ProtocolName < protocol list > - * \endcode - * All the protocols listed between angle brackets are considered part of the ProtocolName protocol. - */ -OBJC_EXPORT BOOL protocol_conformsToProtocol(Protocol *proto, Protocol *other) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether two protocols are equal. - * - * @param proto A protocol. - * @param other A protocol. - * - * @return \c YES if \e proto is the same as \e other, otherwise \c NO. - */ -OBJC_EXPORT BOOL protocol_isEqual(Protocol *proto, Protocol *other) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the name of a protocol. - * - * @param p A protocol. - * - * @return The name of the protocol \e p as a C string. - */ -OBJC_EXPORT const char *protocol_getName(Protocol *p) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a method description structure for a specified method of a given protocol. - * - * @param p A protocol. - * @param aSel A selector. - * @param isRequiredMethod A Boolean value that indicates whether aSel is a required method. - * @param isInstanceMethod A Boolean value that indicates whether aSel is an instance method. - * - * @return An \c objc_method_description structure that describes the method specified by \e aSel, - * \e isRequiredMethod, and \e isInstanceMethod for the protocol \e p. - * If the protocol does not contain the specified method, returns an \c objc_method_description structure - * with the value \c {NULL, \c NULL}. - * - * @note This function recursively searches any protocols that this protocol conforms to. - */ -OBJC_EXPORT struct objc_method_description protocol_getMethodDescription(Protocol *p, SEL aSel, BOOL isRequiredMethod, BOOL isInstanceMethod) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of method descriptions of methods meeting a given specification for a given protocol. - * - * @param p A protocol. - * @param isRequiredMethod A Boolean value that indicates whether returned methods should - * be required methods (pass YES to specify required methods). - * @param isInstanceMethod A Boolean value that indicates whether returned methods should - * be instance methods (pass YES to specify instance methods). - * @param outCount Upon return, contains the number of method description structures in the returned array. - * - * @return A C array of \c objc_method_description structures containing the names and types of \e p's methods - * specified by \e isRequiredMethod and \e isInstanceMethod. The array contains \c *outCount pointers followed - * by a \c NULL terminator. You must free the list with \c free(). - * If the protocol declares no methods that meet the specification, \c NULL is returned and \c *outCount is 0. - * - * @note Methods in other protocols adopted by this protocol are not included. - */ -OBJC_EXPORT struct objc_method_description *protocol_copyMethodDescriptionList(Protocol *p, BOOL isRequiredMethod, BOOL isInstanceMethod, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the specified property of a given protocol. - * - * @param proto A protocol. - * @param name The name of a property. - * @param isRequiredProperty A Boolean value that indicates whether name is a required property. - * @param isInstanceProperty A Boolean value that indicates whether name is a required property. - * - * @return The property specified by \e name, \e isRequiredProperty, and \e isInstanceProperty for \e proto, - * or \c NULL if none of \e proto's properties meets the specification. - */ -OBJC_EXPORT objc_property_t protocol_getProperty(Protocol *proto, const char *name, BOOL isRequiredProperty, BOOL isInstanceProperty) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of the properties declared by a protocol. - * - * @param proto A protocol. - * @param outCount Upon return, contains the number of elements in the returned array. - * - * @return A C array of pointers of type \c objc_property_t describing the properties declared by \e proto. - * Any properties declared by other protocols adopted by this protocol are not included. The array contains - * \c *outCount pointers followed by a \c NULL terminator. You must free the array with \c free(). - * If the protocol declares no properties, \c NULL is returned and \c *outCount is \c 0. - */ -OBJC_EXPORT objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of the protocols adopted by a protocol. - * - * @param proto A protocol. - * @param outCount Upon return, contains the number of elements in the returned array. - * - * @return A C array of protocols adopted by \e proto. The array contains \e *outCount pointers - * followed by a \c NULL terminator. You must free the array with \c free(). - * If the protocol declares no properties, \c NULL is returned and \c *outCount is \c 0. - */ -OBJC_EXPORT Protocol * __unsafe_unretained *protocol_copyProtocolList(Protocol *proto, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Creates a new protocol instance that cannot be used until registered with - * \c objc_registerProtocol() - * - * @param name The name of the protocol to create. - * - * @return The Protocol instance on success, \c nil if a protocol - * with the same name already exists. - * @note There is no dispose method for this. - */ -OBJC_EXPORT Protocol *objc_allocateProtocol(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Registers a newly constructed protocol with the runtime. The protocol - * will be ready for use and is immutable after this. - * - * @param proto The protocol you want to register. - */ -OBJC_EXPORT void objc_registerProtocol(Protocol *proto) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Adds a method to a protocol. The protocol must be under construction. - * - * @param proto The protocol to add a method to. - * @param name The name of the method to add. - * @param types A C string that represents the method signature. - * @param isRequiredMethod YES if the method is not an optional method. - * @param isInstanceMethod YES if the method is an instance method. - */ -OBJC_EXPORT void protocol_addMethodDescription(Protocol *proto, SEL name, const char *types, BOOL isRequiredMethod, BOOL isInstanceMethod) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Adds an incorporated protocol to another protocol. The protocol being - * added to must still be under construction, while the additional protocol - * must be already constructed. - * - * @param proto The protocol you want to add to, it must be under construction. - * @param addition The protocol you want to incorporate into \e proto, it must be registered. - */ -OBJC_EXPORT void protocol_addProtocol(Protocol *proto, Protocol *addition) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Adds a property to a protocol. The protocol must be under construction. - * - * @param proto The protocol to add a property to. - * @param name The name of the property. - * @param attributes An array of property attributes. - * @param attributeCount The number of attributes in \e attributes. - * @param isRequiredProperty YES if the property (accessor methods) is not optional. - * @param isInstanceProperty YES if the property (accessor methods) are instance methods. - * This is the only case allowed fo a property, as a result, setting this to NO will - * not add the property to the protocol at all. - */ -OBJC_EXPORT void protocol_addProperty(Protocol *proto, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount, BOOL isRequiredProperty, BOOL isInstanceProperty) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - - -/* Working with Libraries */ - -/** - * Returns the names of all the loaded Objective-C frameworks and dynamic - * libraries. - * - * @param outCount The number of names returned. - * - * @return An array of C strings of names. Must be free()'d by caller. - */ -OBJC_EXPORT const char **objc_copyImageNames(unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the dynamic library name a class originated from. - * - * @param cls The class you are inquiring about. - * - * @return The name of the library containing this class. - */ -OBJC_EXPORT const char *class_getImageName(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the names of all the classes within a library. - * - * @param image The library or framework you are inquiring about. - * @param outCount The number of class names returned. - * - * @return An array of C strings representing the class names. - */ -OBJC_EXPORT const char **objc_copyClassNamesForImage(const char *image, - unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Working with Selectors */ - -/** - * Returns the name of the method specified by a given selector. - * - * @param sel A pointer of type \c SEL. Pass the selector whose name you wish to determine. - * - * @return A C string indicating the name of the selector. - */ -OBJC_EXPORT const char *sel_getName(SEL sel) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Registers a method name with the Objective-C runtime system. - * - * @param str A pointer to a C string. Pass the name of the method you wish to register. - * - * @return A pointer of type SEL specifying the selector for the named method. - * - * @note The implementation of this method is identical to the implementation of \c sel_registerName. - * @note Prior to OS X version 10.0, this method tried to find the selector mapped to the given name - * and returned \c NULL if the selector was not found. This was changed for safety, because it was - * observed that many of the callers of this function did not check the return value for \c NULL. - */ -OBJC_EXPORT SEL sel_getUid(const char *str) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Registers a method with the Objective-C runtime system, maps the method - * name to a selector, and returns the selector value. - * - * @param str A pointer to a C string. Pass the name of the method you wish to register. - * - * @return A pointer of type SEL specifying the selector for the named method. - * - * @note You must register a method name with the Objective-C runtime system to obtain the - * method’s selector before you can add the method to a class definition. If the method name - * has already been registered, this function simply returns the selector. - */ -OBJC_EXPORT SEL sel_registerName(const char *str) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether two selectors are equal. - * - * @param lhs The selector to compare with rhs. - * @param rhs The selector to compare with lhs. - * - * @return \c YES if \e rhs and \e rhs are equal, otherwise \c NO. - * - * @note sel_isEqual is equivalent to ==. - */ -OBJC_EXPORT BOOL sel_isEqual(SEL lhs, SEL rhs) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Objective-C Language Features */ - -/** - * This function is inserted by the compiler when a mutation - * is detected during a foreach iteration. It gets called - * when a mutation occurs, and the enumerationMutationHandler - * is enacted if it is set up. A fatal error occurs if a handler is not set up. - * - * @param obj The object being mutated. - * - */ -OBJC_EXPORT void objc_enumerationMutation(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the current mutation handler. - * - * @param handler Function pointer to the new mutation handler. - */ -OBJC_EXPORT void objc_setEnumerationMutationHandler(void (*handler)(id)) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Set the function to be called by objc_msgForward. - * - * @param fwd Function to be jumped to by objc_msgForward. - * @param fwd_stret Function to be jumped to by objc_msgForward_stret. - * - * @see message.h::_objc_msgForward - */ -OBJC_EXPORT void objc_setForwardHandler(void *fwd, void *fwd_stret) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Creates a pointer to a function that will call the block - * when the method is called. - * - * @param block The block that implements this method. Its signature should - * be: method_return_type ^(id self, method_args...). - * The selector is not available as a parameter to this block. - * The block is copied with \c Block_copy(). - * - * @return The IMP that calls this block. Must be disposed of with - * \c imp_removeBlock. - */ -OBJC_EXPORT IMP imp_implementationWithBlock(id block) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Return the block associated with an IMP that was created using - * \c imp_implementationWithBlock. - * - * @param anImp The IMP that calls this block. - * - * @return The block called by \e anImp. - */ -OBJC_EXPORT id imp_getBlock(IMP anImp) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Disassociates a block from an IMP that was created using - * \c imp_implementationWithBlock and releases the copy of the - * block that was created. - * - * @param anImp An IMP that was created using \c imp_implementationWithBlock. - * - * @return YES if the block was released successfully, NO otherwise. - * (For example, the block might not have been used to create an IMP previously). - */ -OBJC_EXPORT BOOL imp_removeBlock(IMP anImp) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * This loads the object referenced by a weak pointer and returns it, after - * retaining and autoreleasing the object to ensure that it stays alive - * long enough for the caller to use it. This function would be used - * anywhere a __weak variable is used in an expression. - * - * @param location The weak pointer address - * - * @return The object pointed to by \e location, or \c nil if \e location is \c nil. - */ -OBJC_EXPORT id objc_loadWeak(id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -/** - * This function stores a new value into a __weak variable. It would - * be used anywhere a __weak variable is the target of an assignment. - * - * @param location The address of the weak pointer itself - * @param obj The new object this weak ptr should now point to - * - * @return The value stored into \e location, i.e. \e obj - */ -OBJC_EXPORT id objc_storeWeak(id *location, id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -/* Associative References */ - -/** - * Policies related to associative references. - * These are options to objc_setAssociatedObject() - */ -typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) { - OBJC_ASSOCIATION_ASSIGN = 0, /**< Specifies a weak reference to the associated object. */ - OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. - * The association is not made atomically. */ - OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied. - * The association is not made atomically. */ - OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object. - * The association is made atomically. */ - OBJC_ASSOCIATION_COPY = 01403 /**< Specifies that the associated object is copied. - * The association is made atomically. */ -}; - -/** - * Sets an associated value for a given object using a given key and association policy. - * - * @param object The source object for the association. - * @param key The key for the association. - * @param value The value to associate with the key key for object. Pass nil to clear an existing association. - * @param policy The policy for the association. For possible values, see “Associative Object Behaviors.” - * - * @see objc_setAssociatedObject - * @see objc_removeAssociatedObjects - */ -OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); - -/** - * Returns the value associated with a given object for a given key. - * - * @param object The source object for the association. - * @param key The key for the association. - * - * @return The value associated with the key \e key for \e object. - * - * @see objc_setAssociatedObject - */ -OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); - -/** - * Removes all associations for a given object. - * - * @param object An object that maintains associated objects. - * - * @note The main purpose of this function is to make it easy to return an object - * to a "pristine state”. You should not use this function for general removal of - * associations from objects, since it also removes associations that other clients - * may have added to the object. Typically you should use \c objc_setAssociatedObject - * with a nil value to clear an association. - * - * @see objc_setAssociatedObject - * @see objc_getAssociatedObject - */ -OBJC_EXPORT void objc_removeAssociatedObjects(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); - - -#define _C_ID '@' -#define _C_CLASS '#' -#define _C_SEL ':' -#define _C_CHR 'c' -#define _C_UCHR 'C' -#define _C_SHT 's' -#define _C_USHT 'S' -#define _C_INT 'i' -#define _C_UINT 'I' -#define _C_LNG 'l' -#define _C_ULNG 'L' -#define _C_LNG_LNG 'q' -#define _C_ULNG_LNG 'Q' -#define _C_FLT 'f' -#define _C_DBL 'd' -#define _C_BFLD 'b' -#define _C_BOOL 'B' -#define _C_VOID 'v' -#define _C_UNDEF '?' -#define _C_PTR '^' -#define _C_CHARPTR '*' -#define _C_ATOM '%' -#define _C_ARY_B '[' -#define _C_ARY_E ']' -#define _C_UNION_B '(' -#define _C_UNION_E ')' -#define _C_STRUCT_B '{' -#define _C_STRUCT_E '}' -#define _C_VECTOR '!' -#define _C_CONST 'r' - - -/* Obsolete types */ - -#if !__OBJC2__ - -#define CLS_GETINFO(cls,infomask) ((cls)->info & (infomask)) -#define CLS_SETINFO(cls,infomask) ((cls)->info |= (infomask)) - -// class is not a metaclass -#define CLS_CLASS 0x1 -// class is a metaclass -#define CLS_META 0x2 -// class's +initialize method has completed -#define CLS_INITIALIZED 0x4 -// class is posing -#define CLS_POSING 0x8 -// unused -#define CLS_MAPPED 0x10 -// class and subclasses need cache flush during image loading -#define CLS_FLUSH_CACHE 0x20 -// method cache should grow when full -#define CLS_GROW_CACHE 0x40 -// unused -#define CLS_NEED_BIND 0x80 -// methodLists is array of method lists -#define CLS_METHOD_ARRAY 0x100 -// the JavaBridge constructs classes with these markers -#define CLS_JAVA_HYBRID 0x200 -#define CLS_JAVA_CLASS 0x400 -// thread-safe +initialize -#define CLS_INITIALIZING 0x800 -// bundle unloading -#define CLS_FROM_BUNDLE 0x1000 -// C++ ivar support -#define CLS_HAS_CXX_STRUCTORS 0x2000 -// Lazy method list arrays -#define CLS_NO_METHOD_ARRAY 0x4000 -// +load implementation -#define CLS_HAS_LOAD_METHOD 0x8000 -// objc_allocateClassPair API -#define CLS_CONSTRUCTING 0x10000 -// class compiled with bigger class structure -#define CLS_EXT 0x20000 - - -struct objc_method_description_list { - int count; - struct objc_method_description list[1]; -}; - - -struct objc_protocol_list { - struct objc_protocol_list *next; - long count; - Protocol *list[1]; -}; - - -struct objc_category { - char *category_name OBJC2_UNAVAILABLE; - char *class_name OBJC2_UNAVAILABLE; - struct objc_method_list *instance_methods OBJC2_UNAVAILABLE; - struct objc_method_list *class_methods OBJC2_UNAVAILABLE; - struct objc_protocol_list *protocols OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - - -struct objc_ivar { - char *ivar_name OBJC2_UNAVAILABLE; - char *ivar_type OBJC2_UNAVAILABLE; - int ivar_offset OBJC2_UNAVAILABLE; -#ifdef __LP64__ - int space OBJC2_UNAVAILABLE; -#endif -} OBJC2_UNAVAILABLE; - -struct objc_ivar_list { - int ivar_count OBJC2_UNAVAILABLE; -#ifdef __LP64__ - int space OBJC2_UNAVAILABLE; -#endif - /* variable length structure */ - struct objc_ivar ivar_list[1] OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - - -struct objc_method { - SEL method_name OBJC2_UNAVAILABLE; - char *method_types OBJC2_UNAVAILABLE; - IMP method_imp OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - -struct objc_method_list { - struct objc_method_list *obsolete OBJC2_UNAVAILABLE; - - int method_count OBJC2_UNAVAILABLE; -#ifdef __LP64__ - int space OBJC2_UNAVAILABLE; -#endif - /* variable length structure */ - struct objc_method method_list[1] OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - - -typedef struct objc_symtab *Symtab OBJC2_UNAVAILABLE; - -struct objc_symtab { - unsigned long sel_ref_cnt OBJC2_UNAVAILABLE; - SEL *refs OBJC2_UNAVAILABLE; - unsigned short cls_def_cnt OBJC2_UNAVAILABLE; - unsigned short cat_def_cnt OBJC2_UNAVAILABLE; - void *defs[1] /* variable size */ OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - - -typedef struct objc_cache *Cache OBJC2_UNAVAILABLE; - -#define CACHE_BUCKET_NAME(B) ((B)->method_name) -#define CACHE_BUCKET_IMP(B) ((B)->method_imp) -#define CACHE_BUCKET_VALID(B) (B) -#ifndef __LP64__ -#define CACHE_HASH(sel, mask) (((uintptr_t)(sel)>>2) & (mask)) -#else -#define CACHE_HASH(sel, mask) (((unsigned int)((uintptr_t)(sel)>>3)) & (mask)) -#endif -struct objc_cache { - unsigned int mask /* total = mask + 1 */ OBJC2_UNAVAILABLE; - unsigned int occupied OBJC2_UNAVAILABLE; - Method buckets[1] OBJC2_UNAVAILABLE; -}; - - -typedef struct objc_module *Module OBJC2_UNAVAILABLE; - -struct objc_module { - unsigned long version OBJC2_UNAVAILABLE; - unsigned long size OBJC2_UNAVAILABLE; - const char *name OBJC2_UNAVAILABLE; - Symtab symtab OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - -#else - -struct objc_method_list; - -#endif - - -/* Obsolete functions */ - -OBJC_EXPORT IMP class_lookupMethod(Class cls, SEL sel) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); -OBJC_EXPORT BOOL class_respondsToMethod(Class cls, SEL sel) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); -OBJC_EXPORT void _objc_flush_caches(Class cls) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); - -OBJC_EXPORT id object_copyFromZone(id anObject, size_t nBytes, void *z) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_NA,__IPHONE_NA) - OBJC_ARC_UNAVAILABLE; -OBJC_EXPORT id object_realloc(id anObject, size_t nBytes) OBJC2_UNAVAILABLE; -OBJC_EXPORT id object_reallocFromZone(id anObject, size_t nBytes, void *z) OBJC2_UNAVAILABLE; - -#define OBSOLETE_OBJC_GETCLASSES 1 -OBJC_EXPORT void *objc_getClasses(void) OBJC2_UNAVAILABLE; -OBJC_EXPORT void objc_addClass(Class myClass) OBJC2_UNAVAILABLE; -OBJC_EXPORT void objc_setClassHandler(int (*)(const char *)) OBJC2_UNAVAILABLE; -OBJC_EXPORT void objc_setMultithreaded (BOOL flag) OBJC2_UNAVAILABLE; - -OBJC_EXPORT id class_createInstanceFromZone(Class, size_t idxIvars, void *z) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_NA,__IPHONE_NA) - OBJC_ARC_UNAVAILABLE; - -OBJC_EXPORT void class_addMethods(Class, struct objc_method_list *) OBJC2_UNAVAILABLE; -OBJC_EXPORT void class_removeMethods(Class, struct objc_method_list *) OBJC2_UNAVAILABLE; -OBJC_EXPORT void _objc_resolve_categories_for_class(Class cls) OBJC2_UNAVAILABLE; - -OBJC_EXPORT Class class_poseAs(Class imposter, Class original) OBJC2_UNAVAILABLE; - -OBJC_EXPORT unsigned int method_getSizeOfArguments(Method m) OBJC2_UNAVAILABLE; -OBJC_EXPORT unsigned method_getArgumentInfo(struct objc_method *m, int arg, const char **type, int *offset) OBJC2_UNAVAILABLE; - -OBJC_EXPORT Class objc_getOrigClass(const char *name) OBJC2_UNAVAILABLE; -#define OBJC_NEXT_METHOD_LIST 1 -OBJC_EXPORT struct objc_method_list *class_nextMethodList(Class, void **) OBJC2_UNAVAILABLE; -// usage for nextMethodList -// -// void *iterator = 0; -// struct objc_method_list *mlist; -// while ( mlist = class_nextMethodList( cls, &iterator ) ) -// ; - -OBJC_EXPORT id (*_alloc)(Class, size_t) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_copy)(id, size_t) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_realloc)(id, size_t) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_dealloc)(id) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_zoneAlloc)(Class, size_t, void *) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_zoneRealloc)(id, size_t, void *) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_zoneCopy)(id, size_t, void *) OBJC2_UNAVAILABLE; -OBJC_EXPORT void (*_error)(id, const char *, va_list) OBJC2_UNAVAILABLE; - -#endif diff --git a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h b/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h deleted file mode 100644 index bc2a635..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/maptable.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 1999-2003, 2006-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@ - */ -/* maptable.h - Scalable hash table of mappings. - Bertrand, August 1990 - Copyright 1990-1996 NeXT Software, Inc. -*/ - -#ifndef _OBJC_MAPTABLE_H_ -#define _OBJC_MAPTABLE_H_ - -#ifndef _OBJC_PRIVATE_H_ -# define OBJC_MAP_AVAILABILITY __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_1, __IPHONE_NA,__IPHONE_NA); -#else -# define OBJC_MAP_AVAILABILITY -#endif - -#include <objc/objc.h> - -__BEGIN_DECLS - -/*************** Definitions ***************/ - - /* This module allows hashing of arbitrary associations [key -> value]. Keys and values must be pointers or integers, and client is responsible for allocating/deallocating this data. A deallocation call-back is provided. - NX_MAPNOTAKEY (-1) is used internally as a marker, and therefore keys must always be different from -1. - As well-behaved scalable data structures, hash tables double in size when they start becoming full, thus guaranteeing both average constant time access and linear size. */ - -typedef struct _NXMapTable { - /* private data structure; may change */ - const struct _NXMapTablePrototype *prototype; - unsigned count; - unsigned nbBucketsMinusOne; - void *buckets; -} NXMapTable OBJC_MAP_AVAILABILITY; - -typedef struct _NXMapTablePrototype { - unsigned (*hash)(NXMapTable *, const void *key); - int (*isEqual)(NXMapTable *, const void *key1, const void *key2); - void (*free)(NXMapTable *, void *key, void *value); - int style; /* reserved for future expansion; currently 0 */ -} NXMapTablePrototype OBJC_MAP_AVAILABILITY; - - /* invariants assumed by the implementation: - A - key != -1 - B - key1 == key2 => hash(key1) == hash(key2) - when key varies over time, hash(key) must remain invariant - e.g. if string key, the string must not be changed - C - isEqual(key1, key2) => key1 == key2 - */ - -#define NX_MAPNOTAKEY ((void *)(-1)) - -/*************** Functions ***************/ - -OBJC_EXPORT NXMapTable *NXCreateMapTableFromZone(NXMapTablePrototype prototype, unsigned capacity, void *z) OBJC_MAP_AVAILABILITY; -OBJC_EXPORT NXMapTable *NXCreateMapTable(NXMapTablePrototype prototype, unsigned capacity) OBJC_MAP_AVAILABILITY; - /* capacity is only a hint; 0 creates a small table */ - -OBJC_EXPORT void NXFreeMapTable(NXMapTable *table) OBJC_MAP_AVAILABILITY; - /* call free for each pair, and recovers table */ - -OBJC_EXPORT void NXResetMapTable(NXMapTable *table) OBJC_MAP_AVAILABILITY; - /* free each pair; keep current capacity */ - -OBJC_EXPORT BOOL NXCompareMapTables(NXMapTable *table1, NXMapTable *table2) OBJC_MAP_AVAILABILITY; - /* Returns YES if the two sets are equal (each member of table1 in table2, and table have same size) */ - -OBJC_EXPORT unsigned NXCountMapTable(NXMapTable *table) OBJC_MAP_AVAILABILITY; - /* current number of data in table */ - -OBJC_EXPORT void *NXMapMember(NXMapTable *table, const void *key, void **value) OBJC_MAP_AVAILABILITY; - /* return original table key or NX_MAPNOTAKEY. If key is found, value is set */ - -OBJC_EXPORT void *NXMapGet(NXMapTable *table, const void *key) OBJC_MAP_AVAILABILITY; - /* return original corresponding value or NULL. When NULL need be stored as value, NXMapMember can be used to test for presence */ - -OBJC_EXPORT void *NXMapInsert(NXMapTable *table, const void *key, const void *value) OBJC_MAP_AVAILABILITY; - /* override preexisting pair; Return previous value or NULL. */ - -OBJC_EXPORT void *NXMapRemove(NXMapTable *table, const void *key) OBJC_MAP_AVAILABILITY; - /* previous value or NULL is returned */ - -/* Iteration over all elements of a table consists in setting up an iteration state and then to progress until all entries have been visited. An example of use for counting elements in a table is: - unsigned count = 0; - const MyKey *key; - const MyValue *value; - NXMapState state = NXInitMapState(table); - while(NXNextMapState(table, &state, &key, &value)) { - count++; - } -*/ - -typedef struct {int index;} NXMapState OBJC_MAP_AVAILABILITY; - /* callers should not rely on actual contents of the struct */ - -OBJC_EXPORT NXMapState NXInitMapState(NXMapTable *table) OBJC_MAP_AVAILABILITY; - -OBJC_EXPORT int NXNextMapState(NXMapTable *table, NXMapState *state, const void **key, const void **value) OBJC_MAP_AVAILABILITY; - /* returns 0 when all elements have been visited */ - -/*************** Conveniences ***************/ - -OBJC_EXPORT const NXMapTablePrototype NXPtrValueMapPrototype OBJC_MAP_AVAILABILITY; - /* hashing is pointer/integer hashing; - isEqual is identity; - free is no-op. */ -OBJC_EXPORT const NXMapTablePrototype NXStrValueMapPrototype OBJC_MAP_AVAILABILITY; - /* hashing is string hashing; - isEqual is strcmp; - free is no-op. */ -OBJC_EXPORT const NXMapTablePrototype NXObjectMapPrototype OBJC2_UNAVAILABLE; - /* for objects; uses methods: hash, isEqual:, free, all for key. */ - -__END_DECLS - -#endif /* _OBJC_MAPTABLE_H_ */ diff --git a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-abi.h b/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-abi.h deleted file mode 100644 index fb325ef..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-abi.h +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (c) 2009 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 _OBJC_ABI_H -#define _OBJC_ABI_H - -/* - * WARNING DANGER HAZARD BEWARE EEK - * - * Everything in this file is for Apple Internal use only. - * These will change in arbitrary OS updates and in unpredictable ways. - * When your program breaks, you get to keep both pieces. - */ - -/* - * objc-abi.h: Declarations for functions used by compiler codegen. - */ - -#include <malloc/malloc.h> -#include <objc/objc.h> -#include <objc/runtime.h> -#include <objc/message.h> - -/* Runtime startup. */ - -// Old static initializer. Used by old crt1.o and old bug workarounds. -OBJC_EXPORT void _objcInit(void) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/* Images */ - -// Description of an Objective-C image. -// __DATA,__objc_imageinfo stores one of these. -typedef struct objc_image_info { - uint32_t version; // currently 0 - uint32_t flags; -} objc_image_info; - -// Values for objc_image_info.flags -#define OBJC_IMAGE_IS_REPLACEMENT (1<<0) -#define OBJC_IMAGE_SUPPORTS_GC (1<<1) -#define OBJC_IMAGE_REQUIRES_GC (1<<2) -#define OBJC_IMAGE_OPTIMIZED_BY_DYLD (1<<3) -#define OBJC_IMAGE_SUPPORTS_COMPACTION (1<<4) // might be re-assignable - - -/* Properties */ - -// Read or write an object property. Not all object properties use these. -OBJC_EXPORT id objc_getProperty(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -OBJC_EXPORT void objc_setProperty_atomic(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; -OBJC_EXPORT void objc_setProperty_nonatomic(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; -OBJC_EXPORT void objc_setProperty_atomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; -OBJC_EXPORT void objc_setProperty_nonatomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; - - -// Read or write a non-object property. Not all uses are C structs, -// and not all C struct properties use this. -OBJC_EXPORT void objc_copyStruct(void *dest, const void *src, ptrdiff_t size, BOOL atomic, BOOL hasStrong) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -// Perform a copy of a C++ object using striped locks. Used by non-POD C++ typed atomic properties. -OBJC_EXPORT void objc_copyCppObjectAtomic(void *dest, const void *src, void (*copyHelper) (void *dest, const void *source)) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); - -/* Classes. */ -#if __OBJC2__ -OBJC_EXPORT IMP _objc_empty_vtable - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -#endif -OBJC_EXPORT struct objc_cache _objc_empty_cache - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - - -/* Messages */ - -#if __OBJC2__ -// objc_msgSendSuper2() takes the current search class, not its superclass. -OBJC_EXPORT id objc_msgSendSuper2(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0); -OBJC_EXPORT void objc_msgSendSuper2_stret(struct objc_super *super, SEL op,...) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; - -// objc_msgSend_noarg() may be faster for methods with no additional arguments. -OBJC_EXPORT id objc_msgSend_noarg(id self, SEL _cmd) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#endif - -#if __OBJC2__ -// Debug messengers. Messengers used by the compiler have a debug flavor that -// may perform extra sanity checking. -// Old objc_msgSendSuper() does not have a debug version; this is OBJC2 only. -// *_fixup() do not have debug versions; use non-fixup only for debug mode. -OBJC_EXPORT id objc_msgSend_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT id objc_msgSendSuper2_debug(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT void objc_msgSend_stret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0) - OBJC_ARM64_UNAVAILABLE; -OBJC_EXPORT void objc_msgSendSuper2_stret_debug(struct objc_super *super, SEL op,...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0) - OBJC_ARM64_UNAVAILABLE; - -# if defined(__i386__) -OBJC_EXPORT double objc_msgSend_fpret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# elif defined(__x86_64__) -OBJC_EXPORT long double objc_msgSend_fpret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# if __STDC_VERSION__ >= 199901L -OBJC_EXPORT _Complex long double objc_msgSend_fp2ret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# else -OBJC_EXPORT void objc_msgSend_fp2ret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# endif -# endif - -#endif - -#if defined(__x86_64__) && TARGET_OS_MAC && !TARGET_IPHONE_SIMULATOR -// objc_msgSend_fixup() is used for vtable-dispatchable call sites. -OBJC_EXPORT void objc_msgSend_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSend_stret_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSendSuper2_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSendSuper2_stret_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSend_fpret_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSend_fp2ret_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -#endif - -/* C++-compatible exception handling. */ -#if __OBJC2__ - -// fixme these conflict with C++ compiler's internal definitions -#if !defined(__cplusplus) - -// Vtable for C++ exception typeinfo for Objective-C types. -OBJC_EXPORT const void *objc_ehtype_vtable[] - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -// C++ exception typeinfo for type `id`. -OBJC_EXPORT struct objc_typeinfo OBJC_EHTYPE_id - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -#endif - -// Exception personality function for Objective-C and Objective-C++ code. -struct _Unwind_Exception; -struct _Unwind_Context; -OBJC_EXPORT int -__objc_personality_v0(int version, - int actions, - uint64_t exceptionClass, - struct _Unwind_Exception *exceptionObject, - struct _Unwind_Context *context) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -#endif - -/* ARR */ - -OBJC_EXPORT id objc_retainBlock(id) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -#endif diff --git a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-auto-dump.h b/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-auto-dump.h deleted file mode 100644 index d58e0c0..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-auto-dump.h +++ /dev/null @@ -1,55 +0,0 @@ -// -// objc-auto-dump.h -// objc -// The raw dump file format -// See objc-gdb.h for the primitive. -// -// Created by Blaine Garst on 12/8/08. -// Copyright 2008 Apple, Inc. All rights reserved. -// -#ifndef _OBJC_AUTO_DUMP_H_ -#define _OBJC_AUTO_DUMP_H_ - -/* - * Raw file format definitions - */ - -// must be unique in first letter... -// RAW FORMAT -#define HEADER "dumpster" -#define THREAD 't' -#define LOCAL 'l' -#define NODE 'n' -#define REGISTER 'r' -#define ROOT 'g' -#define WEAK 'w' -#define CLASS 'c' -#define END 'e' - -#define SixtyFour 1 -#define Little 2 - -/* - -Raw format, not that anyone should really care. Most programs should use the cooked file reader. - -<rawfile := <header> <arch> <middle>* <end> -<header> := 'd' 'u' 'm' 'p' 's' 't' 'e' 'r' ; the HEADER string -<arch> := SixtyFour? + Little? ; architecture -<middle> := <thread> | <root> | <node> | <weak> | <class> -<thread> := <register> <stack> <local>* ; the triple -<register> := 'r' longLength [bytes] ; the register bank -<stack> := 't' longLength [bytes] ; the stack -<local> := 'l' [long] ; a thread local node -<root> := 'g' longAddress longValue -<node> := 'n' longAddress longSize intLayout longRefcount longIsa? -<weak> := 'w' longAddress longValue -<class> := 'c' longAddress <name> <strongLayout> <weakLayout> -<name> := intLength [bytes] ; no null byte -<strongLayout> := intLength [bytes] ; including 0 byte at end -<weakLayout> := intLength [bytes] ; including 0 byte at end -<end> := 'e' - - */ - -#endif diff --git a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-gdb.h b/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-gdb.h deleted file mode 100644 index 65b3862..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-gdb.h +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -#ifndef _OBJC_GDB_H -#define _OBJC_GDB_H - -/* - * WARNING DANGER HAZARD BEWARE EEK - * - * Everything in this file is for debugger and developer tool use only. - * These will change in arbitrary OS updates and in unpredictable ways. - * When your program breaks, you get to keep both pieces. - */ - -#ifdef __APPLE_API_PRIVATE - -#define _OBJC_PRIVATE_H_ -#include <stdint.h> -#include <objc/hashtable.h> -#include <objc/maptable.h> - -__BEGIN_DECLS - - -/*********************************************************************** -* Class pointer preflighting -**********************************************************************/ - -// Return cls if it's a valid class, or crash. -OBJC_EXPORT Class gdb_class_getClass(Class cls) -#if __OBJC2__ - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); -#else - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_1); -#endif - -// Same as gdb_class_getClass(object_getClass(cls)). -OBJC_EXPORT Class gdb_object_getClass(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - - -/*********************************************************************** -* Class lists for heap. -**********************************************************************/ - -#if __OBJC2__ - -// Maps class name to Class, for in-use classes only. NXStrValueMapPrototype. -OBJC_EXPORT NXMapTable *gdb_objc_realized_classes - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); - -#else - -// Hashes Classes, for all known classes. Custom prototype. -OBJC_EXPORT NXHashTable *_objc_debug_class_hash - __OSX_AVAILABLE_STARTING(__MAC_10_2, __IPHONE_NA); - -#endif - - -/*********************************************************************** -* Non-pointer isa -**********************************************************************/ - -#if __OBJC2__ - -// Extract isa pointer from an isa field. -// (Class)(isa & mask) == class pointer -OBJC_EXPORT const uintptr_t objc_debug_isa_class_mask - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_7_0); - -// Extract magic cookie from an isa field. -// (isa & magic_mask) == magic_value -OBJC_EXPORT const uintptr_t objc_debug_isa_magic_mask - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_7_0); -OBJC_EXPORT const uintptr_t objc_debug_isa_magic_value - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_7_0); - -#endif - - -/*********************************************************************** -* Tagged pointer decoding -**********************************************************************/ -#if __OBJC2__ - -// if (obj & mask) obj is a tagged pointer object -OBJC_EXPORT uintptr_t objc_debug_taggedpointer_mask - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -// tag_slot = (obj >> slot_shift) & slot_mask -OBJC_EXPORT unsigned int objc_debug_taggedpointer_slot_shift - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); -OBJC_EXPORT uintptr_t objc_debug_taggedpointer_slot_mask - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -// class = classes[tag_slot] -OBJC_EXPORT Class objc_debug_taggedpointer_classes[] - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -// payload = (obj << payload_lshift) >> payload_rshift -// Payload signedness is determined by the signedness of the right-shift. -OBJC_EXPORT unsigned int objc_debug_taggedpointer_payload_lshift - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); -OBJC_EXPORT unsigned int objc_debug_taggedpointer_payload_rshift - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -#endif - - -/*********************************************************************** -* Breakpoints in objc_msgSend for debugger stepping. -* The array is a {0,0} terminated list of addresses. -* Each address is one of the following: -* OBJC_MESSENGER_START: Address is the start of a messenger function. -* OBJC_MESSENGER_END_FAST: Address is a jump insn that calls an IMP. -* OBJC_MESSENGER_END_SLOW: Address is some insn in the slow lookup path. -* OBJC_MESSENGER_END_NIL: Address is a return insn for messages to nil. -* -* Every path from OBJC_MESSENGER_START should reach some OBJC_MESSENGER_END. -* At all ENDs, the stack and parameter register state is the same as START. -* -* In some cases, the END_FAST case jumps to something other than the -* method's implementation. In those cases the jump's destination will -* be another function that is marked OBJC_MESSENGER_START. -**********************************************************************/ -#if __OBJC2__ - -#define OBJC_MESSENGER_START 1 -#define OBJC_MESSENGER_END_FAST 2 -#define OBJC_MESSENGER_END_SLOW 3 -#define OBJC_MESSENGER_END_NIL 4 - -struct objc_messenger_breakpoint { - uintptr_t address; - uintptr_t kind; -}; - -OBJC_EXPORT struct objc_messenger_breakpoint -gdb_objc_messenger_breakpoints[] - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -#endif - - -#ifndef OBJC_NO_GC - -/*********************************************************************** - * Garbage Collector heap dump -**********************************************************************/ - -/* Dump GC heap; if supplied the name is returned in filenamebuffer. Returns YES on success. */ -OBJC_EXPORT BOOL objc_dumpHeap(char *filenamebuffer, unsigned long length) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -#define OBJC_HEAP_DUMP_FILENAME_FORMAT "/tmp/objc-gc-heap-dump-%d-%d" - -#endif - -__END_DECLS - -#endif - -#endif diff --git a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-internal.h b/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-internal.h deleted file mode 100644 index f77cb18..0000000 --- a/objc/objc-runtime/Build/Products/Debug/usr/local/include/objc/objc-internal.h +++ /dev/null @@ -1,673 +0,0 @@ -/* - * Copyright (c) 2009 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 _OBJC_INTERNAL_H -#define _OBJC_INTERNAL_H - -/* - * WARNING DANGER HAZARD BEWARE EEK - * - * Everything in this file is for Apple Internal use only. - * These will change in arbitrary OS updates and in unpredictable ways. - * When your program breaks, you get to keep both pieces. - */ - -/* - * objc-internal.h: Private SPI for use by other system frameworks. - */ - -#include <objc/objc.h> -#include <objc/runtime.h> -#include <Availability.h> -#include <malloc/malloc.h> -#include <dispatch/dispatch.h> - -__BEGIN_DECLS - -// This is the allocation size required for each of the class and the metaclass -// with objc_initializeClassPair() and objc_readClassPair(). -// The runtime's class structure will never grow beyond this. -#define OBJC_MAX_CLASS_SIZE (32*sizeof(void*)) - -// In-place construction of an Objective-C class. -// cls and metacls must each be OBJC_MAX_CLASS_SIZE bytes. -// Returns nil if a class with the same name already exists. -// Returns nil if the superclass is under construction. -// Call objc_registerClassPair() when you are done. -OBJC_EXPORT Class objc_initializeClassPair(Class superclass, const char *name, Class cls, Class metacls) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0); - -// Class and metaclass construction from a compiler-generated memory image. -// cls and cls->isa must each be OBJC_MAX_CLASS_SIZE bytes. -// Extra bytes not used the the metadata must be zero. -// info is the same objc_image_info that would be emitted by a static compiler. -// Returns nil if a class with the same name already exists. -// Returns nil if the superclass is nil and the class is not marked as a root. -// Returns nil if the superclass is under construction. -// Do not call objc_registerClassPair(). -#if __OBJC2__ -struct objc_image_info; -OBJC_EXPORT Class objc_readClassPair(Class cls, - const struct objc_image_info *info) - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0); -#endif - -// Batch object allocation using malloc_zone_batch_malloc(). -OBJC_EXPORT unsigned class_createInstances(Class cls, size_t extraBytes, - id *results, unsigned num_requested) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3) - OBJC_ARC_UNAVAILABLE; - -// Get the isa pointer written into objects just before being freed. -OBJC_EXPORT Class _objc_getFreedObjectClass(void) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -// Return YES if GC is on and `object` is a GC allocation. -OBJC_EXPORT BOOL objc_isAuto(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); - -// env NSObjCMessageLoggingEnabled -OBJC_EXPORT void instrumentObjcMessageSends(BOOL flag) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -// Initializer called by libSystem -#if __OBJC2__ -OBJC_EXPORT void _objc_init(void) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); -#endif - -#ifndef OBJC_NO_GC -// GC startup callback from Foundation -OBJC_EXPORT malloc_zone_t *objc_collect_init(int (*callback)(void)) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); -#endif - -// Plainly-implemented GC barriers. Rosetta used to use these. -OBJC_EXPORT id objc_assign_strongCast_generic(id value, id *dest) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT id objc_assign_global_generic(id value, id *dest) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT id objc_assign_threadlocal_generic(id value, id *dest) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT id objc_assign_ivar_generic(id value, id dest, ptrdiff_t offset) - UNAVAILABLE_ATTRIBUTE; - -// Install missing-class callback. Used by the late unlamented ZeroLink. -OBJC_EXPORT void _objc_setClassLoader(BOOL (*newClassLoader)(const char *)) OBJC2_UNAVAILABLE; - -// Install handler for allocation failures. -// Handler may abort, or throw, or provide an object to return. -OBJC_EXPORT void _objc_setBadAllocHandler(id (*newHandler)(Class isa)) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); - -// This can go away when AppKit stops calling it (rdar://7811851) -#if __OBJC2__ -OBJC_EXPORT void objc_setMultithreaded (BOOL flag) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -#endif - -// Used by ExceptionHandling.framework -#if !__OBJC2__ -OBJC_EXPORT void _objc_error(id rcv, const char *fmt, va_list args) - __attribute__((noreturn)) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); - -#endif - - -// Tagged pointer objects. - -#if __LP64__ -#define OBJC_HAVE_TAGGED_POINTERS 1 -#endif - -#if OBJC_HAVE_TAGGED_POINTERS - -// Tagged pointer layout and usage is subject to change -// on different OS versions. The current layout is: -// (MSB) -// 60 bits payload -// 3 bits tag index -// 1 bit 1 for tagged pointer objects, 0 for ordinary objects -// (LSB) - -#if __has_feature(objc_fixed_enum) || __cplusplus >= 201103L -enum objc_tag_index_t : uint8_t -#else -typedef uint8_t objc_tag_index_t; -enum -#endif -{ - OBJC_TAG_NSAtom = 0, - OBJC_TAG_1 = 1, - OBJC_TAG_NSString = 2, - OBJC_TAG_NSNumber = 3, - OBJC_TAG_NSIndexPath = 4, - OBJC_TAG_NSManagedObjectID = 5, - OBJC_TAG_NSDate = 6, - OBJC_TAG_7 = 7 -}; -#if __has_feature(objc_fixed_enum) && !defined(__cplusplus) -typedef enum objc_tag_index_t objc_tag_index_t; -#endif - -OBJC_EXPORT void _objc_registerTaggedPointerClass(objc_tag_index_t tag, Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -OBJC_EXPORT Class _objc_getClassForTag(objc_tag_index_t tag) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -static inline bool -_objc_taggedPointersEnabled(void) -{ - extern uintptr_t objc_debug_taggedpointer_mask; - return (objc_debug_taggedpointer_mask != 0); -} - -#if TARGET_OS_IPHONE -// tagged pointer marker is MSB - -static inline void * -_objc_makeTaggedPointer(objc_tag_index_t tag, uintptr_t value) -{ - // assert(_objc_taggedPointersEnabled()); - // assert((unsigned int)tag < 8); - // assert(((value << 4) >> 4) == value); - return (void*)((1UL << 63) | ((uintptr_t)tag << 60) | (value & ~(0xFUL << 60))); -} - -static inline bool -_objc_isTaggedPointer(const void *ptr) -{ - return (intptr_t)ptr < 0; // a.k.a. ptr & 0x8000000000000000 -} - -static inline objc_tag_index_t -_objc_getTaggedPointerTag(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (objc_tag_index_t)(((uintptr_t)ptr >> 60) & 0x7); -} - -static inline uintptr_t -_objc_getTaggedPointerValue(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (uintptr_t)ptr & 0x0fffffffffffffff; -} - -static inline intptr_t -_objc_getTaggedPointerSignedValue(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return ((intptr_t)ptr << 4) >> 4; -} - -// TARGET_OS_IPHONE -#else -// not TARGET_OS_IPHONE -// tagged pointer marker is LSB - -static inline void * -_objc_makeTaggedPointer(objc_tag_index_t tag, uintptr_t value) -{ - // assert(_objc_taggedPointersEnabled()); - // assert((unsigned int)tag < 8); - // assert(((value << 4) >> 4) == value); - return (void *)((value << 4) | ((uintptr_t)tag << 1) | 1); -} - -static inline bool -_objc_isTaggedPointer(const void *ptr) -{ - return (uintptr_t)ptr & 1; -} - -static inline objc_tag_index_t -_objc_getTaggedPointerTag(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (objc_tag_index_t)(((uintptr_t)ptr & 0xe) >> 1); -} - -static inline uintptr_t -_objc_getTaggedPointerValue(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (uintptr_t)ptr >> 4; -} - -static inline intptr_t -_objc_getTaggedPointerSignedValue(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (intptr_t)ptr >> 4; -} - -// not TARGET_OS_IPHONE -#endif - - -OBJC_EXPORT void _objc_insert_tagged_isa(unsigned char slotNumber, Class isa) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7,__MAC_10_9, __IPHONE_4_3,__IPHONE_7_0); - -#endif - - -// External Reference support. Used to support compaction. - -enum { - OBJC_XREF_STRONG = 1, - OBJC_XREF_WEAK = 2 -}; -typedef uintptr_t objc_xref_type_t; -typedef uintptr_t objc_xref_t; - -OBJC_EXPORT objc_xref_t _object_addExternalReference(id object, objc_xref_type_t type) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); -OBJC_EXPORT void _object_removeExternalReference(objc_xref_t xref) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); -OBJC_EXPORT id _object_readExternalReference(objc_xref_t xref) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -OBJC_EXPORT uintptr_t _object_getExternalHash(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -/** - * Returns the method implementation of an object. - * - * @param obj An Objective-C object. - * @param name An Objective-C selector. - * - * @return The IMP corresponding to the instance method implemented by - * the class of \e obj. - * - * @note Equivalent to: - * - * class_getMethodImplementation(object_getClass(obj), name); - */ -OBJC_EXPORT IMP object_getMethodImplementation(id obj, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -OBJC_EXPORT IMP object_getMethodImplementation_stret(id obj, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0) - OBJC_ARM64_UNAVAILABLE; - - -// Instance-specific instance variable layout. - -OBJC_EXPORT void _class_setIvarLayoutAccessor(Class cls_gen, const uint8_t* (*accessor) (id object)) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -OBJC_EXPORT const uint8_t *_object_getIvarLayout(Class cls_gen, id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -OBJC_EXPORT BOOL _class_usesAutomaticRetainRelease(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT BOOL _class_isFutureClass(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - - -// Obsolete ARC conversions. - -// hack - remove and reinstate objc.h's definitions -#undef objc_retainedObject -#undef objc_unretainedObject -#undef objc_unretainedPointer -OBJC_EXPORT id objc_retainedObject(objc_objectptr_t pointer) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT id objc_unretainedObject(objc_objectptr_t pointer) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT objc_objectptr_t objc_unretainedPointer(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#if __has_feature(objc_arc) -# define objc_retainedObject(o) ((__bridge_transfer id)(objc_objectptr_t)(o)) -# define objc_unretainedObject(o) ((__bridge id)(objc_objectptr_t)(o)) -# define objc_unretainedPointer(o) ((__bridge objc_objectptr_t)(id)(o)) -#else -# define objc_retainedObject(o) ((id)(objc_objectptr_t)(o)) -# define objc_unretainedObject(o) ((id)(objc_objectptr_t)(o)) -# define objc_unretainedPointer(o) ((objc_objectptr_t)(id)(o)) -#endif - -// API to only be called by root classes like NSObject or NSProxy - -OBJC_EXPORT -id -_objc_rootRetain(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -_objc_rootRelease(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -bool -_objc_rootReleaseWasZero(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -bool -_objc_rootTryRetain(id obj) -__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -bool -_objc_rootIsDeallocating(id obj) -__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -_objc_rootAutorelease(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -uintptr_t -_objc_rootRetainCount(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -_objc_rootInit(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -_objc_rootAlloc(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -_objc_rootDealloc(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -_objc_rootFinalize(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -malloc_zone_t * -_objc_rootZone(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -uintptr_t -_objc_rootHash(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void * -objc_autoreleasePoolPush(void) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -objc_autoreleasePoolPop(void *context) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -OBJC_EXPORT id objc_alloc(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -OBJC_EXPORT id objc_allocWithZone(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -OBJC_EXPORT id objc_retain(id obj) - __asm__("_objc_retain") - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT void objc_release(id obj) - __asm__("_objc_release") - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT id objc_autorelease(id obj) - __asm__("_objc_autorelease") - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Prepare a value at +1 for return through a +0 autoreleasing convention. -OBJC_EXPORT -id -objc_autoreleaseReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Prepare a value at +0 for return through a +0 autoreleasing convention. -OBJC_EXPORT -id -objc_retainAutoreleaseReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Accept a value returned through a +0 autoreleasing convention for use at +1. -OBJC_EXPORT -id -objc_retainAutoreleasedReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Accept a value returned through a +0 autoreleasing convention for use at +0. -OBJC_EXPORT -id -objc_unsafeClaimAutoreleasedReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_11, __IPHONE_9_0); - -OBJC_EXPORT -void -objc_storeStrong(id *location, id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -objc_retainAutorelease(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// obsolete. -OBJC_EXPORT id objc_retain_autorelease(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -objc_loadWeakRetained(id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -objc_initWeak(id *location, id val) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Like objc_storeWeak, but stores nil if the new object is deallocating -// or the new object's class does not support weak references. -// Returns the value stored (either the new object or nil). -OBJC_EXPORT -id -objc_storeWeakOrNil(id *location, id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_11, __IPHONE_9_0); - -// Like objc_initWeak, but stores nil if the new object is deallocating -// or the new object's class does not support weak references. -// Returns the value stored (either the new object or nil). -OBJC_EXPORT -id -objc_initWeakOrNil(id *location, id val) - __OSX_AVAILABLE_STARTING(__MAC_10_11, __IPHONE_9_0); - -OBJC_EXPORT -void -objc_destroyWeak(id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -objc_copyWeak(id *to, id *from) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -objc_moveWeak(id *to, id *from) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -OBJC_EXPORT -void -_objc_autoreleasePoolPrint(void) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT BOOL objc_should_deallocate(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT void objc_clear_deallocating(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -// to make CF link for now - -OBJC_EXPORT -void * -_objc_autoreleasePoolPush(void) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -_objc_autoreleasePoolPop(void *context) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -// Extra @encode data for XPC, or NULL -OBJC_EXPORT const char *_protocol_getMethodTypeEncoding(Protocol *p, SEL sel, BOOL isRequiredMethod, BOOL isInstanceMethod) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); - - -// API to only be called by classes that provide their own reference count storage - -OBJC_EXPORT -void -_objc_deallocOnMainThreadHelper(void *context) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// On async versus sync deallocation and the _dealloc2main flag -// -// Theory: -// -// If order matters, then code must always: [self dealloc]. -// If order doesn't matter, then always async should be safe. -// -// Practice: -// -// The _dealloc2main bit is set for GUI objects that may be retained by other -// threads. Once deallocation begins on the main thread, doing more async -// deallocation will at best cause extra UI latency and at worst cause -// use-after-free bugs in unretained delegate style patterns. Yes, this is -// extremely fragile. Yes, in the long run, developers should switch to weak -// references. -// -// Note is NOT safe to do any equality check against the result of -// dispatch_get_current_queue(). The main thread can and does drain more than -// one dispatch queue. That is why we call pthread_main_np(). -// - -typedef enum { - _OBJC_RESURRECT_OBJECT = -1, /* _logicBlock has called -retain, and scheduled a -release for later. */ - _OBJC_DEALLOC_OBJECT_NOW = 1, /* call [self dealloc] immediately. */ - _OBJC_DEALLOC_OBJECT_LATER = 2 /* call [self dealloc] on the main queue. */ -} _objc_object_disposition_t; - -#define _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC_BLOCK(_rc_ivar, _logicBlock) \ - -(id)retain { \ - /* this will fail to compile if _rc_ivar is an unsigned type */ \ - int _retain_count_ivar_must_not_be_unsigned[0L - (__typeof__(_rc_ivar))-1] __attribute__((unused)); \ - __typeof__(_rc_ivar) _prev = __sync_fetch_and_add(&_rc_ivar, 2); \ - if (_prev < -2) { /* specifically allow resurrection from logical 0. */ \ - __builtin_trap(); /* BUG: retain of over-released ref */ \ - } \ - return self; \ - } \ - -(oneway void)release { \ - __typeof__(_rc_ivar) _prev = __sync_fetch_and_sub(&_rc_ivar, 2); \ - if (_prev > 0) { \ - return; \ - } else if (_prev < 0) { \ - __builtin_trap(); /* BUG: over-release */ \ - } \ - _objc_object_disposition_t fate = _logicBlock(self); \ - if (fate == _OBJC_RESURRECT_OBJECT) { \ - return; \ - } \ - /* mark the object as deallocating. */ \ - if (!__sync_bool_compare_and_swap(&_rc_ivar, -2, 1)) { \ - __builtin_trap(); /* BUG: dangling ref did a retain */ \ - } \ - if (fate == _OBJC_DEALLOC_OBJECT_NOW) { \ - [self dealloc]; \ - } else if (fate == _OBJC_DEALLOC_OBJECT_LATER) { \ - dispatch_barrier_async_f(dispatch_get_main_queue(), self, \ - _objc_deallocOnMainThreadHelper); \ - } else { \ - __builtin_trap(); /* BUG: bogus fate value */ \ - } \ - } \ - -(NSUInteger)retainCount { \ - return (_rc_ivar + 2) >> 1; \ - } \ - -(BOOL)_tryRetain { \ - __typeof__(_rc_ivar) _prev; \ - do { \ - _prev = _rc_ivar; \ - if (_prev & 1) { \ - return 0; \ - } else if (_prev == -2) { \ - return 0; \ - } else if (_prev < -2) { \ - __builtin_trap(); /* BUG: over-release elsewhere */ \ - } \ - } while ( ! __sync_bool_compare_and_swap(&_rc_ivar, _prev, _prev + 2)); \ - return 1; \ - } \ - -(BOOL)_isDeallocating { \ - if (_rc_ivar == -2) { \ - return 1; \ - } else if (_rc_ivar < -2) { \ - __builtin_trap(); /* BUG: over-release elsewhere */ \ - } \ - return _rc_ivar & 1; \ - } - -#define _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC(_rc_ivar, _dealloc2main) \ - _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC_BLOCK(_rc_ivar, (^(id _self_ __attribute__((unused))) { \ - if (_dealloc2main && !pthread_main_np()) { \ - return _OBJC_DEALLOC_OBJECT_LATER; \ - } else { \ - return _OBJC_DEALLOC_OBJECT_NOW; \ - } \ - })) - -#define _OBJC_SUPPORTED_INLINE_REFCNT(_rc_ivar) _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC(_rc_ivar, 0) -#define _OBJC_SUPPORTED_INLINE_REFCNT_WITH_DEALLOC2MAIN(_rc_ivar) _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC(_rc_ivar, 1) - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/README.md b/objc/objc-runtime/README.md deleted file mode 100644 index ee0a9e3..0000000 --- a/objc/objc-runtime/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# objc-runtime -objc runtime 680 diff --git a/objc/objc-runtime/ReleaseNotes.rtf b/objc/objc-runtime/ReleaseNotes.rtf deleted file mode 100644 index eec82a9..0000000 --- a/objc/objc-runtime/ReleaseNotes.rtf +++ /dev/null @@ -1,358 +0,0 @@ -{\rtf1\mac\ansicpg10000\cocoartf824\cocoasubrtf420 -{\fonttbl\f0\fswiss\fcharset77 Helvetica-Bold;\f1\fswiss\fcharset77 Helvetica;\f2\fnil\fcharset77 Monaco; -} -{\colortbl;\red255\green255\blue255;\red70\green130\blue100;} -\vieww11200\viewh14360\viewkind0 -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b\fs30 \cf0 Objective-C Release Notes\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\b0\fs24 \cf0 \ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b\fs30 \cf0 Mac OS X 10.5 Leopard -\f1\b0\fs24 \ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b \cf0 Contents -\f1\b0 \ -\'a5 Garbage Collection\ -\'a5\'caProperties\ -\'a5\'caLoading and Unloading Bundles\ -\'a5 Method and Class Attributes\ -\'a5\'ca@package Instance Variables\ -\'a5\'caRuntime API changes\ -\'a5\'ca64-bit ABI\ -\'a5\'ca64-bit Class and Instance Variable Access Control\ -\'a5\'ca64-bit Non-Fragile Instance Variables\ -\'a5\'ca64-bit Zero-Cost C++-Compatible Exceptions\ -\ -\ - -\f0\b Garbage Collection\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\b0 \cf0 \ -The Objective-C runtime examines on startup the execution image to determine whether to run with garbage collection or not. Each object file has an info section and they must all agree for execution to proceed. Standard compilation results in an info section that indicates that no GC capability is present. Compiling with -fobjc-gc indicates that both GC and retain/release logic is present. Compiling with -fobjc-gc-only indicates that only GC logic is present. A non-GC executable that attempts to load a gc-only framework will fail, as will a GC capable executable that attemps to load a GC incapable framework (or bundle).\ -\ -The collector initially runs only on the main thread when requested via objc_collect_if_needed(1), which is called automatically from the autoreleasepool -drain method. The AppKit arranges to call objc_start_collector_thread() after launch and subsequently collections run on a dedicated thread and are responsive to pure allocation demand. The objc_set_collection_threshold and objc_set_collection_ratio calls are used to establish the "need" for a collection. Once every ratio times a full (complete) collection will occur; otherwise a generational collection will be done if allocations have exceeded the threshold.\ -\ -The garbage collector minimally pauses those threads which have been registered to it while collecting. Registration occurs during establishment of an NSThread, not simply a pthread.\ -\ -A critical assumption that the collector makes is that one thread never gains access to an object (or more generally any block of garbage collected memory) by way of a pointer to another thread's stack memory. In other words, the collector does not make provision for cross thread stack references. This enables the collector to avoid pausing all threads at the same time while it examines recursively all of their references.\ -\ -The compiler uses three "helper" functions for assignments of strong pointers to garbage collected memory into global memory ( -\f2\fs20 objc_assign_global -\f1\fs24 ), garbage collected heap memory ( -\f2\fs20 objc_assign_ivar -\f1\fs24 ), or into unknown memory ( -\f2\fs20 objc_assign_strongCast -\f1\fs24 ). For assignments of weak pointers it uses objc_assign_weak and for reads it uses objc_read_weak.\ -\ -When copying memory in bulk into a garbage collected block one must use the API -\f2\fs20 objc_memmove_collectable(void *dst, const void *src, size_t size) -\f1\fs24 .\ -\ -Garbage Collection Errors\ -\ -The collector itself is found in -\f2\fs20 /usr/lib/libauto.dylib -\f1\fs24 . Its error messages are printed using -\f2\fs20 malloc_printf -\f1\fs24 . The ObjC runtime is found in -\f2\fs20 /usr/lib/libobjc.dylib -\f1\fs24 . Its errors are printed using -\f2\fs20 _objc_inform -\f1\fs24 . Currently we note resurrection and reference count underflow errors by calling the following routines:\ -\ -\pard\tx960\pardeftab960\ql\qnatural\pardirnatural - -\f2\fs20 \cf2 \CocoaLigature0 objc_assign_global_error\ -\pard\tx960\pardeftab960\ql\qnatural\pardirnatural -\cf0 objc_assign_ivar_error\ -\pard\tx960\pardeftab960\ql\qnatural\pardirnatural -\cf2 objc_exception_during_finalize_error\ -auto_zone_resurrection_error\cf0 \ -\cf2 auto_refcount_underflow_error -\f1\fs24 \cf0 \CocoaLigature1 \ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural -\cf0 \ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b \cf0 Properties -\f1\b0 \ -\ -The syntax for Objective-C properties has been overhauled since WWDC 2006. See the property documentation for details.\ -\ -In summary, @property(attributes) type name introduces an implicit declaration of a "getter" and a "setter" method (unless a read-only property is requested) for the "variable" named. The setter= and getter= attributes allow one to specify the names of the methods, otherwise a "name" method and a "setName:" method are implicitly declared. They may also be explicitly named.\ -\ -By default, properties are assigned when set. For objects under non-GC this is often incorrect and a warning is issued unless the assignment semantic is explicitly named. There are three choices - assign, for non-retained object references, copy, for objects that are copied and implicitly retained, and simply retain, for objects that require being retained when set.\ -\ -Access to properties is atomic by default. This is trivial under GC for almost everything and also trivial under non-GC for everything but objects and structures. In particular atomic access to retained objects under non-GC conditions can be expensive. As such, a nonatomic property attribute is available.\ -\ -Pointers may be held strongly under GC by declaring them __strong, and they can be zeroing weak by declaring them __weak.\ -\ -The implementations for properties can be provided by the compiler and runtime through the use of the @synthesize statement in the @implementation section of the class (or class extension). The compiler expects an instance variable of the same name as the property. If one wishes a different name it can be supplied to the @synthesize statement.\ -\ -In particular the compiler and runtime will implement accessors to retained objects by using atomic compare and swap instructions. It is extremely dangerous to directly access an atomic object property through its instance variable since another thread might change its value unpredictably. As such the compiler will warn you about such unprotected accesses. The runtime, in fact, will temporarily use the least significant bit of the instance variable as a temporary lock while retaining the new value and releasing the old. Direct use of an atomic instance variable under non-GC is strongly discouraged.\ -\ -\ - -\f0\b Loading and Unloading Bundles\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\b0 \cf0 \ -Since Mac OS X Version 10.4 it has been possible to unload bundles containing Objective-C. No attempt is made to prevent this if objects are still present for classes that are unloaded. Subclasses of classes loaded in bundles are particularly vulnerable.\ -\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b \cf0 Method and Class Attributes\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\b0 \cf0 Objective-C now supports some gcc attributes for Objective-C methods. Syntactically, attributes for a method follow the method's declaration, and attributes for a method parameter sit between the parameter type and the parameter name. Supported attributes include:\ -\ -Deprecation and availability, including AvailabilityMacros.h\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f2\fs20 \cf0 - (void)method:(id)param __attribute__((deprecated));\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\fs24 \cf0 \ -Unused parameters\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f2\fs20 \cf0 - (void)method:(id) __attribute__((unused)) param;\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\fs24 \cf0 \ -Sentinel parameters, including -\f2\fs20 NS_REQUIRES_NIL_TERMINATION -\f1\fs24 \ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f2\fs20 \cf0 - (void)methodWithObjects:(id)obj, ... NS_REQUIRES_NIL_TERMINATION;\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\fs24 \cf0 \ -Objective-C also supports some gcc attributes for Objective-C classes. Syntactically, attributes for a class precede the class's -\f2\fs20 @interface -\f1\fs24 declaration. Supported attributes include:\ -\ -Deprecation and availability, including AvailabilityMacros.h\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f2\fs20 \cf0 __attribute__((deprecated))\ - @interface MyDeprecatedClass : SomeSuperclass\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\fs24 \cf0 \ -Visibility\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f2\fs20 \cf0 __attribute__((visibility("hidden")))\ - @interface MyPrivateClass : SomeSuperclass -\f1\fs24 \ -\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b \cf0 @package Instance Variables -\f1\b0 \ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f2\fs20 \cf0 @package -\f1\fs24 is a new ivar protection class, like -\f2\fs20 @public -\f1\fs24 and -\f2\fs20 @protected -\f1\fs24 . -\f2\fs20 @package -\f1\fs24 ivars behave as follows:\ -\'a5\'ca -\f2\fs20 @public -\f1\fs24 in 32-bit; \ -\'a5\'ca -\f2\fs20 @public -\f1\fs24 in 64-bit, inside the framework that defined the class; \ -\'a5\'ca -\f2\fs20 @private -\f1\fs24 in 64-bit, outside the framework that defined the class.\ -\ -In 64-bit, the ivar symbol for an -\f2\fs20 @package -\f1\fs24 ivar is not exported, so any attempt to use the ivar from outside the framework that defined the class will fail with a link error. See "64-bit Class and Instance Variable Access Control" for more about ivar symbols.\ -\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b \cf0 Runtime API changes\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\b0 \cf0 The C interface to the Objective-C runtime (in -\f2\fs20 <objc/*.h> -\f1\fs24 ) has changed significantly. Highlights include:\ -\'a5\'caAlmost all structures are deprecated, including -\f2\fs20 struct objc_class -\f1\fs24 . Functional replacements for most of these are provided.\ -\'a5\'ca -\f2\fs20 class_poseAs -\f1\fs24 is deprecated. Use method list manipulation functions instead.\ -\'a5\'ca -\f2\fs20 class_nextMethodList -\f1\fs24 is deprecated. Use -\f2\fs20 class_copyMethodList -\f1\fs24 instead.\ -\'a5\'ca -\f2\fs20 class_addMethods -\f1\fs24 is deprecated. Use -\f2\fs20 class_addMethod -\f1\fs24 instead.\ -\'a5\'ca -\f2\fs20 objc_addClass -\f1\fs24 is deprecated. Use -\f2\fs20 objc_allocateClassPair -\f1\fs24 and -\f2\fs20 objc_registerClassPair -\f1\fs24 instead.\ -\'a5\'caIn general, all deprecated declarations are absent in 64-bit.\ -\'a5\'caThe API in objc/objc-runtime.h and objc/objc-class.h is now in objc/runtime.h and objc/message.h. The old header files simply #include the new ones.\ -\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b \cf0 64-bit ABI\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\b0 \cf0 The 64-bit Objective-C ABI is generally unlike the 32-bit ABI. The new ABI provides new features, better performance, and improved future adaptability. All aspects of the 64-bit ABI are private and subject to future change. Forthcoming documentation will describe the ABI for the use of compilers and developer tools only.\ -\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b \cf0 64-bit Class and Instance Variable Access Control\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\b0 \cf0 In 64-bit Objective-C, access control for classes and each class and instance variable has a symbol associated with it. All uses of a class or instance variable reference this symbol. These symbols are subject to access control by the linker.\ -\ -The upshot is that access to private classes and ivars is more strictly enforced. Illegal use of a private ivar may fail with a link error. Frameworks that provide classes and ivars must correctly export their symbols. In particular, frameworks built with -\f2\fs20 -fvisibility=hidden -\f1\fs24 or a linker export list may need to be changed.\ -\ -Class symbols have names of the form -\f2\fs20 _OBJC_CLASS_$_ClassName -\f1\fs24 and -\f2\fs20 _OBJC_METACLASS_$_ClassName -\f1\fs24 . The class symbol is used by clients who send messages to the class (i.e. -\f2\fs20 [ClassName someMessage] -\f1\fs24 ). The metaclass symbol is used by clients who subclass the class.\ -\ -By default, class symbols are exported. They are affected by gcc's symbol visibility flags, so -\f2\fs20 -fvisibility=hidden -\f1\fs24 will make the class symbols non-exported. The linker recognizes the old symbol name -\f2\fs20 .objc_class_name_ClassName -\f1\fs24 in linker export lists and translates it to these symbols. \ -\ -Visibility of a single class can be changed using an attribute.\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f2\fs20 \cf0 __attribute__((visibility("hidden")))\ - @interface ClassName : SomeSuperclass\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\fs24 \cf0 For classes with -\f2\fs20 "default" -\f1\fs24 visibility, the class symbols are exported, and the ivar symbols are handled as described below. For classes with -\f2\fs20 "hidden" -\f1\fs24 visibility, the class symbols and ivar symbols are all not exported.\ -\ -Ivar symbols have the form -\f2\fs20 _OBJC_IVAR_$_ClassName.IvarName -\f1\fs24 . The ivar symbol is used by clients who read or write the ivar.\ -\ -By default, ivar symbols for -\f2\fs20 @private -\f1\fs24 and -\f2\fs20 @package -\f1\fs24 ivars are not exported, and ivar symbols for -\f2\fs20 @public -\f1\fs24 and -\f2\fs20 @protected -\f1\fs24 ivars are exported. This can be changed by export lists, -\f2\fs20 -fvisibility -\f1\fs24 , or a visibility attribute on the class. Visibility attributes on individual ivars are currently not supported.\ -\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b \cf0 64-bit Non-Fragile Instance Variables\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\b0 \cf0 All instance variables in 64-bit Objective-C are non-fragile. That is, existing compiled code that uses a class's ivars will not break when the class or a superclass changes its own ivar layout. In particular, framework classes may add new ivars without breaking subclasses compiled against a previous version of the framework.\ -\ -Ivars may be added or reordered freely; existing users of a reordered ivar will adapt transparently. Other ivar changes are safe except that they will break any existing users of the ivar: deleting an ivar, renaming an ivar, moving an ivar to a different class, and changing the type of an ivar. \ -\ -Do not use -\f2\fs20 @defs -\f1\fs24 . The ivar layout it presents cannot adapt to superclass changes.\ -\ -Do not use -\f2\fs20 sizeof(SomeClass) -\f1\fs24 . Use -\f2\fs20 class_getInstanceSize([SomeClass class]) -\f1\fs24 instead.\ -\ -Do not use -\f2\fs20 offsetof(SomeClass, SomeIvar) -\f1\fs24 . Use -\f2\fs20 ivar_getOffset(class_getInstanceVariable([SomeClass class], "SomeIvar")) -\f1\fs24 instead.\ -\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f0\b \cf0 64-bit Zero-Cost C++-Compatible Exceptions\ -\ -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural - -\f1\b0 \cf0 In 64-bit, the implementation of Objective-C exceptions has been rewritten. The new system provides "zero-cost" try blocks and interoperability with C++. \ -\ -"Zero-cost" try blocks incur no time penalty when entering an -\f2\fs20 @try -\f1\fs24 block, unlike 32-bit which must call -\f2\fs20 setjmp() -\f1\fs24 and other additional bookkeeping. On the other hand, actually throwing an exception is much more expensive. For best performance in 64-bit, exceptions should be thrown only in exceptional cases.\ -\ -The Cocoa frameworks require that all exceptions be instances of NSException or its subclasses. Do not throw objects of other types.\ -\ -The Cocoa frameworks are generally not exception-safe. Their general pattern is that exceptions are reserved for programmer error only, and the program should quit soon after catching such an exception. Be careful when throwing exceptions across the Cocoa frameworks.\ -\ -In 64-bit, C++ exceptions and Objective-C exceptions are interoperable. In particular, C++ destructors and Objective-C -\f2\fs20 @finally -\f1\fs24 blocks are honored when unwinding any exception, and default catch clauses - -\f2\fs20 catch (...) -\f1\fs24 and -\f2\fs20 @catch (...) -\f1\fs24 - are able to catch and re-throw any exception.\ -\ -Objective-C -\f2\fs20 @catch (id e) -\f1\fs24 catches any Objective-C exception, but no C++ exceptions. Use -\f2\fs20 @catch (...) -\f1\fs24 to catch everything, and -\f2\fs20 @throw; -\f1\fs24 to re-throw caught exceptions. -\f2\fs20 @catch (...) -\f1\fs24 is allowed in 32-bit, and has the same effect there as -\f2\fs20 @catch (id e) -\f1\fs24 . \ -} \ No newline at end of file diff --git a/objc/objc-runtime/debug-objc/XXObject.h b/objc/objc-runtime/debug-objc/XXObject.h deleted file mode 100644 index c98eae6..0000000 --- a/objc/objc-runtime/debug-objc/XXObject.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// XXObject.h -// objc -// -// Created by Draveness on 6/12/16. -// -// - -#import <Foundation/Foundation.h> - -@interface XXObject : NSObject - -@property (nonatomic, strong) id strongObject; -@property (nonatomic, weak) id weakObject; - -@end diff --git a/objc/objc-runtime/debug-objc/XXObject.m b/objc/objc-runtime/debug-objc/XXObject.m deleted file mode 100644 index a167aa3..0000000 --- a/objc/objc-runtime/debug-objc/XXObject.m +++ /dev/null @@ -1,13 +0,0 @@ -// -// XXObject.m -// objc -// -// Created by Draveness on 6/12/16. -// -// - -#import "XXObject.h" - -@implementation XXObject - -@end diff --git a/objc/objc-runtime/debug-objc/main.cpp b/objc/objc-runtime/debug-objc/main.cpp deleted file mode 100644 index b08693c..0000000 --- a/objc/objc-runtime/debug-objc/main.cpp +++ /dev/null @@ -1,104993 +0,0 @@ -#ifndef __OBJC2__ -#define __OBJC2__ -#endif -struct objc_selector; struct objc_class; -struct __rw_objc_super { - struct objc_object *object; - struct objc_object *superClass; - __rw_objc_super(struct objc_object *o, struct objc_object *s) : object(o), superClass(s) {} -}; -#ifndef _REWRITER_typedef_Protocol -typedef struct objc_object Protocol; -#define _REWRITER_typedef_Protocol -#endif -#define __OBJC_RW_DLLIMPORT extern -__OBJC_RW_DLLIMPORT void objc_msgSend(void); -__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void); -__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void); -__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void); -__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void); -__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass(const char *); -__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass(struct objc_class *); -__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass(const char *); -__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *); -__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *); -__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *); -__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *); -#ifdef _WIN64 -typedef unsigned long long _WIN_NSUInteger; -#else -typedef unsigned int _WIN_NSUInteger; -#endif -#ifndef __FASTENUMERATIONSTATE -struct __objcFastEnumerationState { - unsigned long state; - void **itemsPtr; - unsigned long *mutationsPtr; - unsigned long extra[5]; -}; -__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *); -#define __FASTENUMERATIONSTATE -#endif -#ifndef __NSCONSTANTSTRINGIMPL -struct __NSConstantStringImpl { - int *isa; - int flags; - char *str; -#if _WIN64 - long long length; -#else - long length; -#endif -}; -#ifdef CF_EXPORT_CONSTANT_STRING -extern "C" __declspec(dllexport) int __CFConstantStringClassReference[]; -#else -__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[]; -#endif -#define __NSCONSTANTSTRINGIMPL -#endif -#ifndef BLOCK_IMPL -#define BLOCK_IMPL -struct __block_impl { - void *isa; - int Flags; - int Reserved; - void *FuncPtr; -}; -// Runtime copy/destroy helper functions (from Block_private.h) -#ifdef __OBJC_EXPORT_BLOCKS -extern "C" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int); -extern "C" __declspec(dllexport) void _Block_object_dispose(const void *, const int); -extern "C" __declspec(dllexport) void *_NSConcreteGlobalBlock[32]; -extern "C" __declspec(dllexport) void *_NSConcreteStackBlock[32]; -#else -__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int); -__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int); -__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32]; -__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32]; -#endif -#endif -#define __block -#define __weak - -#include <stdarg.h> -struct __NSContainer_literal { - void * *arr; - __NSContainer_literal (unsigned int count, ...) { - va_list marker; - va_start(marker, count); - arr = new void *[count]; - for (unsigned i = 0; i < count; i++) - arr[i] = va_arg(marker, void *); - va_end( marker ); - }; - ~__NSContainer_literal() { - delete[] arr; - } -}; -extern "C" __declspec(dllimport) void * objc_autoreleasePoolPush(void); -extern "C" __declspec(dllimport) void objc_autoreleasePoolPop(void *); - -struct __AtAutoreleasePool { - __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();} - ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);} - void * atautoreleasepoolobj; -}; - -#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER) -static __NSConstantStringImpl __NSConstantStringImpl__var_folders_b__zmq01c3j3fqd0nc7n75pylm40000gn_T_main_7e03ca_mi_0 __attribute__ ((section ("__DATA, __cfstring"))) = {__CFConstantStringClassReference,0x000007c8,"Hell",4}; -static __NSConstantStringImpl __NSConstantStringImpl__var_folders_b__zmq01c3j3fqd0nc7n75pylm40000gn_T_main_7e03ca_mi_1 __attribute__ ((section ("__DATA, __cfstring"))) = {__CFConstantStringClassReference,0x000007c8,"ss",2}; -static __NSConstantStringImpl __NSConstantStringImpl__var_folders_b__zmq01c3j3fqd0nc7n75pylm40000gn_T_main_7e03ca_mi_2 __attribute__ ((section ("__DATA, __cfstring"))) = {__CFConstantStringClassReference,0x000007c8,"sssssss",7}; -static __NSConstantStringImpl __NSConstantStringImpl__var_folders_b__zmq01c3j3fqd0nc7n75pylm40000gn_T_main_7e03ca_mi_3 __attribute__ ((section ("__DATA, __cfstring"))) = {__CFConstantStringClassReference,0x000007c8,"ss",2}; -static __NSConstantStringImpl __NSConstantStringImpl__var_folders_b__zmq01c3j3fqd0nc7n75pylm40000gn_T_main_7e03ca_mi_4 __attribute__ ((section ("__DATA, __cfstring"))) = {__CFConstantStringClassReference,0x000007c8,"%@",2}; - - - - - - - - - - - - - - - - - -typedef signed char __int8_t; - - - -typedef unsigned char __uint8_t; -typedef short __int16_t; -typedef unsigned short __uint16_t; -typedef int __int32_t; -typedef unsigned int __uint32_t; -typedef long long __int64_t; -typedef unsigned long long __uint64_t; - -typedef long __darwin_intptr_t; -typedef unsigned int __darwin_natural_t; -typedef int __darwin_ct_rune_t; - - - - - -typedef union { - char __mbstate8[128]; - long long _mbstateL; -} __mbstate_t; - -typedef __mbstate_t __darwin_mbstate_t; - - -typedef long int __darwin_ptrdiff_t; - - - - - - - -typedef long unsigned int __darwin_size_t; - - - - - -typedef __builtin_va_list __darwin_va_list; - - - - - -typedef int __darwin_wchar_t; - - - - -typedef __darwin_wchar_t __darwin_rune_t; - - -typedef int __darwin_wint_t; - - - - -typedef unsigned long __darwin_clock_t; -typedef __uint32_t __darwin_socklen_t; -typedef long __darwin_ssize_t; -typedef long __darwin_time_t; - - - - - -typedef signed char int8_t; -typedef short int16_t; -typedef int int32_t; -typedef long long int64_t; - -typedef unsigned char u_int8_t; -typedef unsigned short u_int16_t; -typedef unsigned int u_int32_t; -typedef unsigned long long u_int64_t; - - -typedef int64_t register_t; - - - - - -typedef __darwin_intptr_t intptr_t; -typedef unsigned long uintptr_t; - - - -typedef u_int64_t user_addr_t; -typedef u_int64_t user_size_t; -typedef int64_t user_ssize_t; -typedef int64_t user_long_t; -typedef u_int64_t user_ulong_t; -typedef int64_t user_time_t; -typedef int64_t user_off_t; - - - - - - - -typedef u_int64_t syscall_arg_t; -typedef __int64_t __darwin_blkcnt_t; -typedef __int32_t __darwin_blksize_t; -typedef __int32_t __darwin_dev_t; -typedef unsigned int __darwin_fsblkcnt_t; -typedef unsigned int __darwin_fsfilcnt_t; -typedef __uint32_t __darwin_gid_t; -typedef __uint32_t __darwin_id_t; -typedef __uint64_t __darwin_ino64_t; - -typedef __darwin_ino64_t __darwin_ino_t; - - - -typedef __darwin_natural_t __darwin_mach_port_name_t; -typedef __darwin_mach_port_name_t __darwin_mach_port_t; -typedef __uint16_t __darwin_mode_t; -typedef __int64_t __darwin_off_t; -typedef __int32_t __darwin_pid_t; -typedef __uint32_t __darwin_sigset_t; -typedef __int32_t __darwin_suseconds_t; -typedef __uint32_t __darwin_uid_t; -typedef __uint32_t __darwin_useconds_t; -typedef unsigned char __darwin_uuid_t[16]; -typedef char __darwin_uuid_string_t[37]; - - -struct __darwin_pthread_handler_rec { - void (*__routine)(void *); - void *__arg; - struct __darwin_pthread_handler_rec *__next; -}; - -struct _opaque_pthread_attr_t { - long __sig; - char __opaque[56]; -}; - -struct _opaque_pthread_cond_t { - long __sig; - char __opaque[40]; -}; - -struct _opaque_pthread_condattr_t { - long __sig; - char __opaque[8]; -}; - -struct _opaque_pthread_mutex_t { - long __sig; - char __opaque[56]; -}; - -struct _opaque_pthread_mutexattr_t { - long __sig; - char __opaque[8]; -}; - -struct _opaque_pthread_once_t { - long __sig; - char __opaque[8]; -}; - -struct _opaque_pthread_rwlock_t { - long __sig; - char __opaque[192]; -}; - -struct _opaque_pthread_rwlockattr_t { - long __sig; - char __opaque[16]; -}; - -struct _opaque_pthread_t { - long __sig; - struct __darwin_pthread_handler_rec *__cleanup_stack; - char __opaque[8176]; -}; - -typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t; -typedef struct _opaque_pthread_cond_t __darwin_pthread_cond_t; -typedef struct _opaque_pthread_condattr_t __darwin_pthread_condattr_t; -typedef unsigned long __darwin_pthread_key_t; -typedef struct _opaque_pthread_mutex_t __darwin_pthread_mutex_t; -typedef struct _opaque_pthread_mutexattr_t __darwin_pthread_mutexattr_t; -typedef struct _opaque_pthread_once_t __darwin_pthread_once_t; -typedef struct _opaque_pthread_rwlock_t __darwin_pthread_rwlock_t; -typedef struct _opaque_pthread_rwlockattr_t __darwin_pthread_rwlockattr_t; -typedef struct _opaque_pthread_t *__darwin_pthread_t; - -static inline -__uint16_t -_OSSwapInt16( - __uint16_t _data -) -{ - return ((__uint16_t)((_data << 8) | (_data >> 8))); -} - -static inline -__uint32_t -_OSSwapInt32( - __uint32_t _data -) -{ - - return __builtin_bswap32(_data); - - - - -} - - -static inline -__uint64_t -_OSSwapInt64( - __uint64_t _data -) -{ - return __builtin_bswap64(_data); -} - - -typedef unsigned char u_char; -typedef unsigned short u_short; -typedef unsigned int u_int; - -typedef unsigned long u_long; - - -typedef unsigned short ushort; -typedef unsigned int uint; - - -typedef u_int64_t u_quad_t; -typedef int64_t quad_t; -typedef quad_t * qaddr_t; - -typedef char * caddr_t; -typedef int32_t daddr_t; - - -typedef __darwin_dev_t dev_t; - -typedef u_int32_t fixpt_t; - - -typedef __darwin_blkcnt_t blkcnt_t; -typedef __darwin_blksize_t blksize_t; -typedef __darwin_gid_t gid_t; -typedef __uint32_t in_addr_t; -typedef __uint16_t in_port_t; -typedef __darwin_ino_t ino_t; - - -typedef __darwin_ino64_t ino64_t; - - -typedef __int32_t key_t; -typedef __darwin_mode_t mode_t; -typedef __uint16_t nlink_t; -typedef __darwin_id_t id_t; -typedef __darwin_pid_t pid_t; -typedef __darwin_off_t off_t; - -typedef int32_t segsz_t; -typedef int32_t swblk_t; - - -typedef __darwin_uid_t uid_t; -static inline __int32_t major(__uint32_t _x) -{ - return (__int32_t)(((__uint32_t)_x >> 24) & 0xff); -} - -static inline __int32_t minor(__uint32_t _x) -{ - return (__int32_t)((_x) & 0xffffff); -} - -static inline dev_t makedev(__uint32_t _major, __uint32_t _minor) -{ - return (dev_t)(((_major) << 24) | (_minor)); -} -typedef __darwin_clock_t clock_t; -typedef __darwin_size_t size_t; -typedef __darwin_ssize_t ssize_t; -typedef __darwin_time_t time_t; - -typedef __darwin_useconds_t useconds_t; -typedef __darwin_suseconds_t suseconds_t; - - -typedef __darwin_size_t rsize_t; -typedef int errno_t; - - - - - - - - -extern "C" { -typedef struct fd_set { - __int32_t fds_bits[((((1024) % ((sizeof(__int32_t) * 8))) == 0) ? ((1024) / ((sizeof(__int32_t) * 8))) : (((1024) / ((sizeof(__int32_t) * 8))) + 1))]; -} fd_set; -} - - -static inline int -__darwin_fd_isset(int _n, const struct fd_set *_p) -{ - return (_p->fds_bits[(unsigned long)_n/(sizeof(__int32_t) * 8)] & ((__int32_t)(1<<((unsigned long)_n % (sizeof(__int32_t) * 8))))); -} - - - - -typedef __int32_t fd_mask; - - - - - - - - - - -typedef __darwin_pthread_attr_t pthread_attr_t; -typedef __darwin_pthread_cond_t pthread_cond_t; -typedef __darwin_pthread_condattr_t pthread_condattr_t; -typedef __darwin_pthread_mutex_t pthread_mutex_t; -typedef __darwin_pthread_mutexattr_t pthread_mutexattr_t; -typedef __darwin_pthread_once_t pthread_once_t; -typedef __darwin_pthread_rwlock_t pthread_rwlock_t; -typedef __darwin_pthread_rwlockattr_t pthread_rwlockattr_t; -typedef __darwin_pthread_t pthread_t; - - - -typedef __darwin_pthread_key_t pthread_key_t; - - - - -typedef __darwin_fsblkcnt_t fsblkcnt_t; -typedef __darwin_fsfilcnt_t fsfilcnt_t; -typedef __builtin_va_list va_list; -typedef __builtin_va_list __gnuc_va_list; - -typedef int __darwin_nl_item; -typedef int __darwin_wctrans_t; - -typedef __uint32_t __darwin_wctype_t; - -typedef enum { - P_ALL, - P_PID, - P_PGID -} idtype_t; -typedef int sig_atomic_t; -struct __darwin_i386_thread_state -{ - unsigned int __eax; - unsigned int __ebx; - unsigned int __ecx; - unsigned int __edx; - unsigned int __edi; - unsigned int __esi; - unsigned int __ebp; - unsigned int __esp; - unsigned int __ss; - unsigned int __eflags; - unsigned int __eip; - unsigned int __cs; - unsigned int __ds; - unsigned int __es; - unsigned int __fs; - unsigned int __gs; -}; -struct __darwin_fp_control -{ - unsigned short __invalid :1, - __denorm :1, - __zdiv :1, - __ovrfl :1, - __undfl :1, - __precis :1, - :2, - __pc :2, - - - - - - __rc :2, - - - - - - - :1, - :3; -}; -typedef struct __darwin_fp_control __darwin_fp_control_t; -struct __darwin_fp_status -{ - unsigned short __invalid :1, - __denorm :1, - __zdiv :1, - __ovrfl :1, - __undfl :1, - __precis :1, - __stkflt :1, - __errsumm :1, - __c0 :1, - __c1 :1, - __c2 :1, - __tos :3, - __c3 :1, - __busy :1; -}; -typedef struct __darwin_fp_status __darwin_fp_status_t; -struct __darwin_mmst_reg -{ - char __mmst_reg[10]; - char __mmst_rsrv[6]; -}; -struct __darwin_xmm_reg -{ - char __xmm_reg[16]; -}; -struct __darwin_i386_float_state -{ - int __fpu_reserved[2]; - struct __darwin_fp_control __fpu_fcw; - struct __darwin_fp_status __fpu_fsw; - __uint8_t __fpu_ftw; - __uint8_t __fpu_rsrv1; - __uint16_t __fpu_fop; - __uint32_t __fpu_ip; - __uint16_t __fpu_cs; - __uint16_t __fpu_rsrv2; - __uint32_t __fpu_dp; - __uint16_t __fpu_ds; - __uint16_t __fpu_rsrv3; - __uint32_t __fpu_mxcsr; - __uint32_t __fpu_mxcsrmask; - struct __darwin_mmst_reg __fpu_stmm0; - struct __darwin_mmst_reg __fpu_stmm1; - struct __darwin_mmst_reg __fpu_stmm2; - struct __darwin_mmst_reg __fpu_stmm3; - struct __darwin_mmst_reg __fpu_stmm4; - struct __darwin_mmst_reg __fpu_stmm5; - struct __darwin_mmst_reg __fpu_stmm6; - struct __darwin_mmst_reg __fpu_stmm7; - struct __darwin_xmm_reg __fpu_xmm0; - struct __darwin_xmm_reg __fpu_xmm1; - struct __darwin_xmm_reg __fpu_xmm2; - struct __darwin_xmm_reg __fpu_xmm3; - struct __darwin_xmm_reg __fpu_xmm4; - struct __darwin_xmm_reg __fpu_xmm5; - struct __darwin_xmm_reg __fpu_xmm6; - struct __darwin_xmm_reg __fpu_xmm7; - char __fpu_rsrv4[14*16]; - int __fpu_reserved1; -}; - - -struct __darwin_i386_avx_state -{ - int __fpu_reserved[2]; - struct __darwin_fp_control __fpu_fcw; - struct __darwin_fp_status __fpu_fsw; - __uint8_t __fpu_ftw; - __uint8_t __fpu_rsrv1; - __uint16_t __fpu_fop; - __uint32_t __fpu_ip; - __uint16_t __fpu_cs; - __uint16_t __fpu_rsrv2; - __uint32_t __fpu_dp; - __uint16_t __fpu_ds; - __uint16_t __fpu_rsrv3; - __uint32_t __fpu_mxcsr; - __uint32_t __fpu_mxcsrmask; - struct __darwin_mmst_reg __fpu_stmm0; - struct __darwin_mmst_reg __fpu_stmm1; - struct __darwin_mmst_reg __fpu_stmm2; - struct __darwin_mmst_reg __fpu_stmm3; - struct __darwin_mmst_reg __fpu_stmm4; - struct __darwin_mmst_reg __fpu_stmm5; - struct __darwin_mmst_reg __fpu_stmm6; - struct __darwin_mmst_reg __fpu_stmm7; - struct __darwin_xmm_reg __fpu_xmm0; - struct __darwin_xmm_reg __fpu_xmm1; - struct __darwin_xmm_reg __fpu_xmm2; - struct __darwin_xmm_reg __fpu_xmm3; - struct __darwin_xmm_reg __fpu_xmm4; - struct __darwin_xmm_reg __fpu_xmm5; - struct __darwin_xmm_reg __fpu_xmm6; - struct __darwin_xmm_reg __fpu_xmm7; - char __fpu_rsrv4[14*16]; - int __fpu_reserved1; - char __avx_reserved1[64]; - struct __darwin_xmm_reg __fpu_ymmh0; - struct __darwin_xmm_reg __fpu_ymmh1; - struct __darwin_xmm_reg __fpu_ymmh2; - struct __darwin_xmm_reg __fpu_ymmh3; - struct __darwin_xmm_reg __fpu_ymmh4; - struct __darwin_xmm_reg __fpu_ymmh5; - struct __darwin_xmm_reg __fpu_ymmh6; - struct __darwin_xmm_reg __fpu_ymmh7; -}; -struct __darwin_i386_exception_state -{ - __uint16_t __trapno; - __uint16_t __cpu; - __uint32_t __err; - __uint32_t __faultvaddr; -}; -struct __darwin_x86_debug_state32 -{ - unsigned int __dr0; - unsigned int __dr1; - unsigned int __dr2; - unsigned int __dr3; - unsigned int __dr4; - unsigned int __dr5; - unsigned int __dr6; - unsigned int __dr7; -}; -struct __darwin_x86_thread_state64 -{ - __uint64_t __rax; - __uint64_t __rbx; - __uint64_t __rcx; - __uint64_t __rdx; - __uint64_t __rdi; - __uint64_t __rsi; - __uint64_t __rbp; - __uint64_t __rsp; - __uint64_t __r8; - __uint64_t __r9; - __uint64_t __r10; - __uint64_t __r11; - __uint64_t __r12; - __uint64_t __r13; - __uint64_t __r14; - __uint64_t __r15; - __uint64_t __rip; - __uint64_t __rflags; - __uint64_t __cs; - __uint64_t __fs; - __uint64_t __gs; -}; -struct __darwin_x86_float_state64 -{ - int __fpu_reserved[2]; - struct __darwin_fp_control __fpu_fcw; - struct __darwin_fp_status __fpu_fsw; - __uint8_t __fpu_ftw; - __uint8_t __fpu_rsrv1; - __uint16_t __fpu_fop; - - - __uint32_t __fpu_ip; - __uint16_t __fpu_cs; - - __uint16_t __fpu_rsrv2; - - - __uint32_t __fpu_dp; - __uint16_t __fpu_ds; - - __uint16_t __fpu_rsrv3; - __uint32_t __fpu_mxcsr; - __uint32_t __fpu_mxcsrmask; - struct __darwin_mmst_reg __fpu_stmm0; - struct __darwin_mmst_reg __fpu_stmm1; - struct __darwin_mmst_reg __fpu_stmm2; - struct __darwin_mmst_reg __fpu_stmm3; - struct __darwin_mmst_reg __fpu_stmm4; - struct __darwin_mmst_reg __fpu_stmm5; - struct __darwin_mmst_reg __fpu_stmm6; - struct __darwin_mmst_reg __fpu_stmm7; - struct __darwin_xmm_reg __fpu_xmm0; - struct __darwin_xmm_reg __fpu_xmm1; - struct __darwin_xmm_reg __fpu_xmm2; - struct __darwin_xmm_reg __fpu_xmm3; - struct __darwin_xmm_reg __fpu_xmm4; - struct __darwin_xmm_reg __fpu_xmm5; - struct __darwin_xmm_reg __fpu_xmm6; - struct __darwin_xmm_reg __fpu_xmm7; - struct __darwin_xmm_reg __fpu_xmm8; - struct __darwin_xmm_reg __fpu_xmm9; - struct __darwin_xmm_reg __fpu_xmm10; - struct __darwin_xmm_reg __fpu_xmm11; - struct __darwin_xmm_reg __fpu_xmm12; - struct __darwin_xmm_reg __fpu_xmm13; - struct __darwin_xmm_reg __fpu_xmm14; - struct __darwin_xmm_reg __fpu_xmm15; - char __fpu_rsrv4[6*16]; - int __fpu_reserved1; -}; - - -struct __darwin_x86_avx_state64 -{ - int __fpu_reserved[2]; - struct __darwin_fp_control __fpu_fcw; - struct __darwin_fp_status __fpu_fsw; - __uint8_t __fpu_ftw; - __uint8_t __fpu_rsrv1; - __uint16_t __fpu_fop; - - - __uint32_t __fpu_ip; - __uint16_t __fpu_cs; - - __uint16_t __fpu_rsrv2; - - - __uint32_t __fpu_dp; - __uint16_t __fpu_ds; - - __uint16_t __fpu_rsrv3; - __uint32_t __fpu_mxcsr; - __uint32_t __fpu_mxcsrmask; - struct __darwin_mmst_reg __fpu_stmm0; - struct __darwin_mmst_reg __fpu_stmm1; - struct __darwin_mmst_reg __fpu_stmm2; - struct __darwin_mmst_reg __fpu_stmm3; - struct __darwin_mmst_reg __fpu_stmm4; - struct __darwin_mmst_reg __fpu_stmm5; - struct __darwin_mmst_reg __fpu_stmm6; - struct __darwin_mmst_reg __fpu_stmm7; - struct __darwin_xmm_reg __fpu_xmm0; - struct __darwin_xmm_reg __fpu_xmm1; - struct __darwin_xmm_reg __fpu_xmm2; - struct __darwin_xmm_reg __fpu_xmm3; - struct __darwin_xmm_reg __fpu_xmm4; - struct __darwin_xmm_reg __fpu_xmm5; - struct __darwin_xmm_reg __fpu_xmm6; - struct __darwin_xmm_reg __fpu_xmm7; - struct __darwin_xmm_reg __fpu_xmm8; - struct __darwin_xmm_reg __fpu_xmm9; - struct __darwin_xmm_reg __fpu_xmm10; - struct __darwin_xmm_reg __fpu_xmm11; - struct __darwin_xmm_reg __fpu_xmm12; - struct __darwin_xmm_reg __fpu_xmm13; - struct __darwin_xmm_reg __fpu_xmm14; - struct __darwin_xmm_reg __fpu_xmm15; - char __fpu_rsrv4[6*16]; - int __fpu_reserved1; - char __avx_reserved1[64]; - struct __darwin_xmm_reg __fpu_ymmh0; - struct __darwin_xmm_reg __fpu_ymmh1; - struct __darwin_xmm_reg __fpu_ymmh2; - struct __darwin_xmm_reg __fpu_ymmh3; - struct __darwin_xmm_reg __fpu_ymmh4; - struct __darwin_xmm_reg __fpu_ymmh5; - struct __darwin_xmm_reg __fpu_ymmh6; - struct __darwin_xmm_reg __fpu_ymmh7; - struct __darwin_xmm_reg __fpu_ymmh8; - struct __darwin_xmm_reg __fpu_ymmh9; - struct __darwin_xmm_reg __fpu_ymmh10; - struct __darwin_xmm_reg __fpu_ymmh11; - struct __darwin_xmm_reg __fpu_ymmh12; - struct __darwin_xmm_reg __fpu_ymmh13; - struct __darwin_xmm_reg __fpu_ymmh14; - struct __darwin_xmm_reg __fpu_ymmh15; -}; -struct __darwin_x86_exception_state64 -{ - __uint16_t __trapno; - __uint16_t __cpu; - __uint32_t __err; - __uint64_t __faultvaddr; -}; -struct __darwin_x86_debug_state64 -{ - __uint64_t __dr0; - __uint64_t __dr1; - __uint64_t __dr2; - __uint64_t __dr3; - __uint64_t __dr4; - __uint64_t __dr5; - __uint64_t __dr6; - __uint64_t __dr7; -}; - - - - -struct __darwin_mcontext32 -{ - struct __darwin_i386_exception_state __es; - struct __darwin_i386_thread_state __ss; - struct __darwin_i386_float_state __fs; -}; - - -struct __darwin_mcontext_avx32 -{ - struct __darwin_i386_exception_state __es; - struct __darwin_i386_thread_state __ss; - struct __darwin_i386_avx_state __fs; -}; -struct __darwin_mcontext64 -{ - struct __darwin_x86_exception_state64 __es; - struct __darwin_x86_thread_state64 __ss; - struct __darwin_x86_float_state64 __fs; -}; - - -struct __darwin_mcontext_avx64 -{ - struct __darwin_x86_exception_state64 __es; - struct __darwin_x86_thread_state64 __ss; - struct __darwin_x86_avx_state64 __fs; -}; -typedef struct __darwin_mcontext64 *mcontext_t; - - - -struct __darwin_sigaltstack -{ - void *ss_sp; - __darwin_size_t ss_size; - int ss_flags; -}; -typedef struct __darwin_sigaltstack stack_t; -struct __darwin_ucontext -{ - int uc_onstack; - __darwin_sigset_t uc_sigmask; - struct __darwin_sigaltstack uc_stack; - struct __darwin_ucontext *uc_link; - __darwin_size_t uc_mcsize; - struct __darwin_mcontext64 *uc_mcontext; - - - -}; - - -typedef struct __darwin_ucontext ucontext_t; - - -typedef __darwin_sigset_t sigset_t; - - - -union sigval { - - int sival_int; - void *sival_ptr; -}; - - - - - -struct sigevent { - int sigev_notify; - int sigev_signo; - union sigval sigev_value; - void (*sigev_notify_function)(union sigval); - pthread_attr_t *sigev_notify_attributes; -}; - - -typedef struct __siginfo { - int si_signo; - int si_errno; - int si_code; - pid_t si_pid; - uid_t si_uid; - int si_status; - void *si_addr; - union sigval si_value; - long si_band; - unsigned long __pad[7]; -} siginfo_t; -union __sigaction_u { - void (*__sa_handler)(int); - void (*__sa_sigaction)(int, struct __siginfo *, - void *); -}; - - -struct __sigaction { - union __sigaction_u __sigaction_u; - void (*sa_tramp)(void *, int, int, siginfo_t *, void *); - sigset_t sa_mask; - int sa_flags; -}; - - - - -struct sigaction { - union __sigaction_u __sigaction_u; - sigset_t sa_mask; - int sa_flags; -}; -typedef void (*sig_t)(int); -struct sigvec { - void (*sv_handler)(int); - int sv_mask; - int sv_flags; -}; -struct sigstack { - char *ss_sp; - int ss_onstack; -}; -extern "C" { -void (*signal(int, void (*)(int)))(int); -} -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; -typedef unsigned long long uint64_t; - - -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; - - - -typedef int8_t int_fast8_t; -typedef int16_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint16_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; -typedef long int intmax_t; -typedef long unsigned int uintmax_t; - - - - - - - -struct timeval -{ - __darwin_time_t tv_sec; - __darwin_suseconds_t tv_usec; -}; - - - - - - - - -typedef __uint64_t rlim_t; -struct rusage { - struct timeval ru_utime; - struct timeval ru_stime; - long ru_maxrss; - - long ru_ixrss; - long ru_idrss; - long ru_isrss; - long ru_minflt; - long ru_majflt; - long ru_nswap; - long ru_inblock; - long ru_oublock; - long ru_msgsnd; - long ru_msgrcv; - long ru_nsignals; - long ru_nvcsw; - long ru_nivcsw; - - -}; -typedef void *rusage_info_t; - -struct rusage_info_v0 { - uint8_t ri_uuid[16]; - uint64_t ri_user_time; - uint64_t ri_system_time; - uint64_t ri_pkg_idle_wkups; - uint64_t ri_interrupt_wkups; - uint64_t ri_pageins; - uint64_t ri_wired_size; - uint64_t ri_resident_size; - uint64_t ri_phys_footprint; - uint64_t ri_proc_start_abstime; - uint64_t ri_proc_exit_abstime; -}; - -struct rusage_info_v1 { - uint8_t ri_uuid[16]; - uint64_t ri_user_time; - uint64_t ri_system_time; - uint64_t ri_pkg_idle_wkups; - uint64_t ri_interrupt_wkups; - uint64_t ri_pageins; - uint64_t ri_wired_size; - uint64_t ri_resident_size; - uint64_t ri_phys_footprint; - uint64_t ri_proc_start_abstime; - uint64_t ri_proc_exit_abstime; - uint64_t ri_child_user_time; - uint64_t ri_child_system_time; - uint64_t ri_child_pkg_idle_wkups; - uint64_t ri_child_interrupt_wkups; - uint64_t ri_child_pageins; - uint64_t ri_child_elapsed_abstime; -}; - -struct rusage_info_v2 { - uint8_t ri_uuid[16]; - uint64_t ri_user_time; - uint64_t ri_system_time; - uint64_t ri_pkg_idle_wkups; - uint64_t ri_interrupt_wkups; - uint64_t ri_pageins; - uint64_t ri_wired_size; - uint64_t ri_resident_size; - uint64_t ri_phys_footprint; - uint64_t ri_proc_start_abstime; - uint64_t ri_proc_exit_abstime; - uint64_t ri_child_user_time; - uint64_t ri_child_system_time; - uint64_t ri_child_pkg_idle_wkups; - uint64_t ri_child_interrupt_wkups; - uint64_t ri_child_pageins; - uint64_t ri_child_elapsed_abstime; - uint64_t ri_diskio_bytesread; - uint64_t ri_diskio_byteswritten; -}; - -struct rusage_info_v3 { - uint8_t ri_uuid[16]; - uint64_t ri_user_time; - uint64_t ri_system_time; - uint64_t ri_pkg_idle_wkups; - uint64_t ri_interrupt_wkups; - uint64_t ri_pageins; - uint64_t ri_wired_size; - uint64_t ri_resident_size; - uint64_t ri_phys_footprint; - uint64_t ri_proc_start_abstime; - uint64_t ri_proc_exit_abstime; - uint64_t ri_child_user_time; - uint64_t ri_child_system_time; - uint64_t ri_child_pkg_idle_wkups; - uint64_t ri_child_interrupt_wkups; - uint64_t ri_child_pageins; - uint64_t ri_child_elapsed_abstime; - uint64_t ri_diskio_bytesread; - uint64_t ri_diskio_byteswritten; - uint64_t ri_cpu_time_qos_default; - uint64_t ri_cpu_time_qos_maintenance; - uint64_t ri_cpu_time_qos_background; - uint64_t ri_cpu_time_qos_utility; - uint64_t ri_cpu_time_qos_legacy; - uint64_t ri_cpu_time_qos_user_initiated; - uint64_t ri_cpu_time_qos_user_interactive; - uint64_t ri_billed_system_time; - uint64_t ri_serviced_system_time; -}; - -typedef struct rusage_info_v3 rusage_info_current; -struct rlimit { - rlim_t rlim_cur; - rlim_t rlim_max; -}; -struct proc_rlimit_control_wakeupmon { - uint32_t wm_flags; - int32_t wm_rate; -}; -extern "C" { -int getpriority(int, id_t); - -int getiopolicy_np(int, int) __attribute__((availability(macosx,introduced=10.5))); - -int getrlimit(int, struct rlimit *) __asm("_" "getrlimit" ); -int getrusage(int, struct rusage *); -int setpriority(int, id_t, int); - -int setiopolicy_np(int, int, int) __attribute__((availability(macosx,introduced=10.5))); - -int setrlimit(int, const struct rlimit *) __asm("_" "setrlimit" ); -} -union wait { - int w_status; - - - - struct { - - unsigned int w_Termsig:7, - w_Coredump:1, - w_Retcode:8, - w_Filler:16; - - - - - - - - } w_T; - - - - - - struct { - - unsigned int w_Stopval:8, - w_Stopsig:8, - w_Filler:16; - - - - - - - } w_S; -}; -extern "C" { -pid_t wait(int *) __asm("_" "wait" ); -pid_t waitpid(pid_t, int *, int) __asm("_" "waitpid" ); - -int waitid(idtype_t, id_t, siginfo_t *, int) __asm("_" "waitid" ); - - -pid_t wait3(int *, int, struct rusage *); -pid_t wait4(pid_t, int *, int, struct rusage *); - -} - -extern "C" { -void *alloca(size_t); -} - - - - - - - - -typedef __darwin_ct_rune_t ct_rune_t; -typedef __darwin_rune_t rune_t; - - - -typedef struct { - int quot; - int rem; -} div_t; - -typedef struct { - long quot; - long rem; -} ldiv_t; - - -typedef struct { - long long quot; - long long rem; -} lldiv_t; - - - -extern int __mb_cur_max; -extern "C" { -void abort(void) __attribute__((noreturn)); -int abs(int) __attribute__((const)); -int atexit(void (*)(void)); -double atof(const char *); -int atoi(const char *); -long atol(const char *); - -long long - atoll(const char *); - -void *bsearch(const void *, const void *, size_t, - size_t, int (*)(const void *, const void *)); -void *calloc(size_t, size_t); -div_t div(int, int) __attribute__((const)); -void exit(int) __attribute__((noreturn)); -void free(void *); -char *getenv(const char *); -long labs(long) __attribute__((const)); -ldiv_t ldiv(long, long) __attribute__((const)); - -long long - llabs(long long); -lldiv_t lldiv(long long, long long); - -void *malloc(size_t); -int mblen(const char *, size_t); -size_t mbstowcs(wchar_t * , const char * , size_t); -int mbtowc(wchar_t * , const char * , size_t); -int posix_memalign(void **, size_t, size_t) __attribute__((availability(macosx,introduced=10.6))); -void qsort(void *, size_t, size_t, - int (*)(const void *, const void *)); -int rand(void); -void *realloc(void *, size_t); -void srand(unsigned); -double strtod(const char *, char **) __asm("_" "strtod" ); -float strtof(const char *, char **) __asm("_" "strtof" ); -long strtol(const char *, char **, int); -long double - strtold(const char *, char **); - -long long - strtoll(const char *, char **, int); - -unsigned long - strtoul(const char *, char **, int); - -unsigned long long - strtoull(const char *, char **, int); - -int system(const char *) __asm("_" "system" ) __attribute__((availability(macosx,introduced=10.0))) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -size_t wcstombs(char * , const wchar_t * , size_t); -int wctomb(char *, wchar_t); - - -void _Exit(int) __attribute__((noreturn)); -long a64l(const char *); -double drand48(void); -char *ecvt(double, int, int *, int *); -double erand48(unsigned short[3]); -char *fcvt(double, int, int *, int *); -char *gcvt(double, int, char *); -int getsubopt(char **, char * const *, char **); -int grantpt(int); - -char *initstate(unsigned, char *, size_t); - - - -long jrand48(unsigned short[3]); -char *l64a(long); -void lcong48(unsigned short[7]); -long lrand48(void); -char *mktemp(char *); -int mkstemp(char *); -long mrand48(void); -long nrand48(unsigned short[3]); -int posix_openpt(int); -char *ptsname(int); -int putenv(char *) __asm("_" "putenv" ); -long random(void); -int rand_r(unsigned *); - -char *realpath(const char * , char * ) __asm("_" "realpath" "$DARWIN_EXTSN"); - - - -unsigned short - *seed48(unsigned short[3]); -int setenv(const char *, const char *, int) __asm("_" "setenv" ); - -void setkey(const char *) __asm("_" "setkey" ); - - - -char *setstate(const char *); -void srand48(long); - -void srandom(unsigned); - - - -int unlockpt(int); - -int unsetenv(const char *) __asm("_" "unsetenv" ); -u_int32_t arc4random(void); -void arc4random_addrandom(unsigned char * , int ); -void arc4random_buf(void * , size_t ) __attribute__((availability(macosx,introduced=10.7))); -void arc4random_stir(void); -u_int32_t - arc4random_uniform(u_int32_t ) __attribute__((availability(macosx,introduced=10.7))); - -int atexit_b(void (*)(void)) __attribute__((availability(macosx,introduced=10.6))); -void *bsearch_b(const void *, const void *, size_t, - size_t, int (*)(const void *, const void *)) __attribute__((availability(macosx,introduced=10.6))); - - - -char *cgetcap(char *, const char *, int); -int cgetclose(void); -int cgetent(char **, char **, const char *); -int cgetfirst(char **, char **); -int cgetmatch(const char *, const char *); -int cgetnext(char **, char **); -int cgetnum(char *, const char *, long *); -int cgetset(const char *); -int cgetstr(char *, const char *, char **); -int cgetustr(char *, const char *, char **); - -int daemon(int, int) __asm("_" "daemon" "$1050") __attribute__((availability(macosx,introduced=10.0,deprecated=10.5,message="Use posix_spawn APIs instead."))) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -char *devname(dev_t, mode_t); -char *devname_r(dev_t, mode_t, char *buf, int len); -char *getbsize(int *, long *); -int getloadavg(double [], int); -const char - *getprogname(void); - -int heapsort(void *, size_t, size_t, - int (*)(const void *, const void *)); - -int heapsort_b(void *, size_t, size_t, - int (*)(const void *, const void *)) __attribute__((availability(macosx,introduced=10.6))); - -int mergesort(void *, size_t, size_t, - int (*)(const void *, const void *)); - -int mergesort_b(void *, size_t, size_t, - int (*)(const void *, const void *)) __attribute__((availability(macosx,introduced=10.6))); - -void psort(void *, size_t, size_t, - int (*)(const void *, const void *)) __attribute__((availability(macosx,introduced=10.6))); - -void psort_b(void *, size_t, size_t, - int (*)(const void *, const void *)) __attribute__((availability(macosx,introduced=10.6))); - -void psort_r(void *, size_t, size_t, void *, - int (*)(void *, const void *, const void *)) __attribute__((availability(macosx,introduced=10.6))); - -void qsort_b(void *, size_t, size_t, - int (*)(const void *, const void *)) __attribute__((availability(macosx,introduced=10.6))); - -void qsort_r(void *, size_t, size_t, void *, - int (*)(void *, const void *, const void *)); -int radixsort(const unsigned char **, int, const unsigned char *, - unsigned); -void setprogname(const char *); -int sradixsort(const unsigned char **, int, const unsigned char *, - unsigned); -void sranddev(void); -void srandomdev(void); -void *reallocf(void *, size_t); - -long long - strtoq(const char *, char **, int); -unsigned long long - strtouq(const char *, char **, int); - -extern char *suboptarg; -void *valloc(size_t); - - - - - - -} -extern "C" { -void __assert_rtn(const char *, const char *, int, const char *) __attribute__((noreturn)); - - - -} -typedef __darwin_wint_t wint_t; -typedef struct { - __darwin_rune_t __min; - __darwin_rune_t __max; - __darwin_rune_t __map; - __uint32_t *__types; -} _RuneEntry; - -typedef struct { - int __nranges; - _RuneEntry *__ranges; -} _RuneRange; - -typedef struct { - char __name[14]; - __uint32_t __mask; -} _RuneCharClass; - -typedef struct { - char __magic[8]; - char __encoding[32]; - - __darwin_rune_t (*__sgetrune)(const char *, __darwin_size_t, char const **); - int (*__sputrune)(__darwin_rune_t, char *, __darwin_size_t, char **); - __darwin_rune_t __invalid_rune; - - __uint32_t __runetype[(1 <<8 )]; - __darwin_rune_t __maplower[(1 <<8 )]; - __darwin_rune_t __mapupper[(1 <<8 )]; - - - - - - - _RuneRange __runetype_ext; - _RuneRange __maplower_ext; - _RuneRange __mapupper_ext; - - void *__variable; - int __variable_len; - - - - - int __ncharclasses; - _RuneCharClass *__charclasses; -} _RuneLocale; - - - -extern "C" { -extern _RuneLocale _DefaultRuneLocale; -extern _RuneLocale *_CurrentRuneLocale; -} -extern "C" { -unsigned long ___runetype(__darwin_ct_rune_t); -__darwin_ct_rune_t ___tolower(__darwin_ct_rune_t); -__darwin_ct_rune_t ___toupper(__darwin_ct_rune_t); -} - -inline int -isascii(int _c) -{ - return ((_c & ~0x7F) == 0); -} -extern "C" { -int __maskrune(__darwin_ct_rune_t, unsigned long); -} - - -inline int -__istype(__darwin_ct_rune_t _c, unsigned long _f) -{ - - - - return (isascii(_c) ? !!(_DefaultRuneLocale.__runetype[_c] & _f) - : !!__maskrune(_c, _f)); - -} - -inline __darwin_ct_rune_t -__isctype(__darwin_ct_rune_t _c, unsigned long _f) -{ - - - - return (_c < 0 || _c >= (1 <<8 )) ? 0 : - !!(_DefaultRuneLocale.__runetype[_c] & _f); - -} -extern "C" { -__darwin_ct_rune_t __toupper(__darwin_ct_rune_t); -__darwin_ct_rune_t __tolower(__darwin_ct_rune_t); -} - - -inline int -__wcwidth(__darwin_ct_rune_t _c) -{ - unsigned int _x; - - if (_c == 0) - return (0); - _x = (unsigned int)__maskrune(_c, 0xe0000000L|0x00040000L); - if ((_x & 0xe0000000L) != 0) - return ((_x & 0xe0000000L) >> 30); - return ((_x & 0x00040000L) != 0 ? 1 : -1); -} - - - - - - -inline int -isalnum(int _c) -{ - return (__istype(_c, 0x00000100L|0x00000400L)); -} - -inline int -isalpha(int _c) -{ - return (__istype(_c, 0x00000100L)); -} - -inline int -isblank(int _c) -{ - return (__istype(_c, 0x00020000L)); -} - -inline int -iscntrl(int _c) -{ - return (__istype(_c, 0x00000200L)); -} - - -inline int -isdigit(int _c) -{ - return (__isctype(_c, 0x00000400L)); -} - -inline int -isgraph(int _c) -{ - return (__istype(_c, 0x00000800L)); -} - -inline int -islower(int _c) -{ - return (__istype(_c, 0x00001000L)); -} - -inline int -isprint(int _c) -{ - return (__istype(_c, 0x00040000L)); -} - -inline int -ispunct(int _c) -{ - return (__istype(_c, 0x00002000L)); -} - -inline int -isspace(int _c) -{ - return (__istype(_c, 0x00004000L)); -} - -inline int -isupper(int _c) -{ - return (__istype(_c, 0x00008000L)); -} - - -inline int -isxdigit(int _c) -{ - return (__isctype(_c, 0x00010000L)); -} - -inline int -toascii(int _c) -{ - return (_c & 0x7F); -} - -inline int -tolower(int _c) -{ - return (__tolower(_c)); -} - -inline int -toupper(int _c) -{ - return (__toupper(_c)); -} - - -inline int -digittoint(int _c) -{ - return (__maskrune(_c, 0x0F)); -} - -inline int -ishexnumber(int _c) -{ - return (__istype(_c, 0x00010000L)); -} - -inline int -isideogram(int _c) -{ - return (__istype(_c, 0x00080000L)); -} - -inline int -isnumber(int _c) -{ - return (__istype(_c, 0x00000400L)); -} - -inline int -isphonogram(int _c) -{ - return (__istype(_c, 0x00200000L)); -} - -inline int -isrune(int _c) -{ - return (__istype(_c, 0xFFFFFFF0L)); -} - -inline int -isspecial(int _c) -{ - return (__istype(_c, 0x00100000L)); -} -extern "C" { -extern int * __error(void); - -} - - - - - -struct lconv { - char *decimal_point; - char *thousands_sep; - char *grouping; - char *int_curr_symbol; - char *currency_symbol; - char *mon_decimal_point; - char *mon_thousands_sep; - char *mon_grouping; - char *positive_sign; - char *negative_sign; - char int_frac_digits; - char frac_digits; - char p_cs_precedes; - char p_sep_by_space; - char n_cs_precedes; - char n_sep_by_space; - char p_sign_posn; - char n_sign_posn; - char int_p_cs_precedes; - char int_n_cs_precedes; - char int_p_sep_by_space; - char int_n_sep_by_space; - char int_p_sign_posn; - char int_n_sign_posn; -}; - - - -extern "C" { -struct lconv *localeconv(void); -} -extern "C" { -char *setlocale(int, const char *); -} -extern "C" { - typedef float float_t; - typedef double double_t; -extern int __math_errhandling(void); -extern int __fpclassifyf(float); -extern int __fpclassifyd(double); -extern int __fpclassifyl(long double); -inline __attribute__ ((__always_inline__)) int __inline_isfinitef(float); -inline __attribute__ ((__always_inline__)) int __inline_isfinited(double); -inline __attribute__ ((__always_inline__)) int __inline_isfinitel(long double); -inline __attribute__ ((__always_inline__)) int __inline_isinff(float); -inline __attribute__ ((__always_inline__)) int __inline_isinfd(double); -inline __attribute__ ((__always_inline__)) int __inline_isinfl(long double); -inline __attribute__ ((__always_inline__)) int __inline_isnanf(float); -inline __attribute__ ((__always_inline__)) int __inline_isnand(double); -inline __attribute__ ((__always_inline__)) int __inline_isnanl(long double); -inline __attribute__ ((__always_inline__)) int __inline_isnormalf(float); -inline __attribute__ ((__always_inline__)) int __inline_isnormald(double); -inline __attribute__ ((__always_inline__)) int __inline_isnormall(long double); -inline __attribute__ ((__always_inline__)) int __inline_signbitf(float); -inline __attribute__ ((__always_inline__)) int __inline_signbitd(double); -inline __attribute__ ((__always_inline__)) int __inline_signbitl(long double); - -inline __attribute__ ((__always_inline__)) int __inline_isfinitef(float __x) { - return __x == __x && __builtin_fabsf(__x) != __builtin_inff(); -} -inline __attribute__ ((__always_inline__)) int __inline_isfinited(double __x) { - return __x == __x && __builtin_fabs(__x) != __builtin_inf(); -} -inline __attribute__ ((__always_inline__)) int __inline_isfinitel(long double __x) { - return __x == __x && __builtin_fabsl(__x) != __builtin_infl(); -} -inline __attribute__ ((__always_inline__)) int __inline_isinff(float __x) { - return __builtin_fabsf(__x) == __builtin_inff(); -} -inline __attribute__ ((__always_inline__)) int __inline_isinfd(double __x) { - return __builtin_fabs(__x) == __builtin_inf(); -} -inline __attribute__ ((__always_inline__)) int __inline_isinfl(long double __x) { - return __builtin_fabsl(__x) == __builtin_infl(); -} -inline __attribute__ ((__always_inline__)) int __inline_isnanf(float __x) { - return __x != __x; -} -inline __attribute__ ((__always_inline__)) int __inline_isnand(double __x) { - return __x != __x; -} -inline __attribute__ ((__always_inline__)) int __inline_isnanl(long double __x) { - return __x != __x; -} -inline __attribute__ ((__always_inline__)) int __inline_signbitf(float __x) { - union { float __f; unsigned int __u; } __u; - __u.__f = __x; - return (int)(__u.__u >> 31); -} -inline __attribute__ ((__always_inline__)) int __inline_signbitd(double __x) { - union { double __f; unsigned long long __u; } __u; - __u.__f = __x; - return (int)(__u.__u >> 63); -} - -inline __attribute__ ((__always_inline__)) int __inline_signbitl(long double __x) { - union { - long double __ld; - struct{ unsigned long long __m; unsigned short __sexp; } __p; - } __u; - __u.__ld = __x; - return (int)(__u.__p.__sexp >> 15); -} - - - - - - - -inline __attribute__ ((__always_inline__)) int __inline_isnormalf(float __x) { - return __inline_isfinitef(__x) && __builtin_fabsf(__x) >= 1.17549435e-38F; -} -inline __attribute__ ((__always_inline__)) int __inline_isnormald(double __x) { - return __inline_isfinited(__x) && __builtin_fabs(__x) >= 2.2250738585072014e-308; -} -inline __attribute__ ((__always_inline__)) int __inline_isnormall(long double __x) { - return __inline_isfinitel(__x) && __builtin_fabsl(__x) >= 3.36210314311209350626e-4932L; -} -extern float acosf(float); -extern double acos(double); -extern long double acosl(long double); - -extern float asinf(float); -extern double asin(double); -extern long double asinl(long double); - -extern float atanf(float); -extern double atan(double); -extern long double atanl(long double); - -extern float atan2f(float, float); -extern double atan2(double, double); -extern long double atan2l(long double, long double); - -extern float cosf(float); -extern double cos(double); -extern long double cosl(long double); - -extern float sinf(float); -extern double sin(double); -extern long double sinl(long double); - -extern float tanf(float); -extern double tan(double); -extern long double tanl(long double); - -extern float acoshf(float); -extern double acosh(double); -extern long double acoshl(long double); - -extern float asinhf(float); -extern double asinh(double); -extern long double asinhl(long double); - -extern float atanhf(float); -extern double atanh(double); -extern long double atanhl(long double); - -extern float coshf(float); -extern double cosh(double); -extern long double coshl(long double); - -extern float sinhf(float); -extern double sinh(double); -extern long double sinhl(long double); - -extern float tanhf(float); -extern double tanh(double); -extern long double tanhl(long double); - -extern float expf(float); -extern double exp(double); -extern long double expl(long double); - -extern float exp2f(float); -extern double exp2(double); -extern long double exp2l(long double); - -extern float expm1f(float); -extern double expm1(double); -extern long double expm1l(long double); - -extern float logf(float); -extern double log(double); -extern long double logl(long double); - -extern float log10f(float); -extern double log10(double); -extern long double log10l(long double); - -extern float log2f(float); -extern double log2(double); -extern long double log2l(long double); - -extern float log1pf(float); -extern double log1p(double); -extern long double log1pl(long double); - -extern float logbf(float); -extern double logb(double); -extern long double logbl(long double); - -extern float modff(float, float *); -extern double modf(double, double *); -extern long double modfl(long double, long double *); - -extern float ldexpf(float, int); -extern double ldexp(double, int); -extern long double ldexpl(long double, int); - -extern float frexpf(float, int *); -extern double frexp(double, int *); -extern long double frexpl(long double, int *); - -extern int ilogbf(float); -extern int ilogb(double); -extern int ilogbl(long double); - -extern float scalbnf(float, int); -extern double scalbn(double, int); -extern long double scalbnl(long double, int); - -extern float scalblnf(float, long int); -extern double scalbln(double, long int); -extern long double scalblnl(long double, long int); - -extern float fabsf(float); -extern double fabs(double); -extern long double fabsl(long double); - -extern float cbrtf(float); -extern double cbrt(double); -extern long double cbrtl(long double); - -extern float hypotf(float, float); -extern double hypot(double, double); -extern long double hypotl(long double, long double); - -extern float powf(float, float); -extern double pow(double, double); -extern long double powl(long double, long double); - -extern float sqrtf(float); -extern double sqrt(double); -extern long double sqrtl(long double); - -extern float erff(float); -extern double erf(double); -extern long double erfl(long double); - -extern float erfcf(float); -extern double erfc(double); -extern long double erfcl(long double); - - - - -extern float lgammaf(float); -extern double lgamma(double); -extern long double lgammal(long double); - -extern float tgammaf(float); -extern double tgamma(double); -extern long double tgammal(long double); - -extern float ceilf(float); -extern double ceil(double); -extern long double ceill(long double); - -extern float floorf(float); -extern double floor(double); -extern long double floorl(long double); - -extern float nearbyintf(float); -extern double nearbyint(double); -extern long double nearbyintl(long double); - -extern float rintf(float); -extern double rint(double); -extern long double rintl(long double); - -extern long int lrintf(float); -extern long int lrint(double); -extern long int lrintl(long double); - -extern float roundf(float); -extern double round(double); -extern long double roundl(long double); - -extern long int lroundf(float); -extern long int lround(double); -extern long int lroundl(long double); - - - - -extern long long int llrintf(float); -extern long long int llrint(double); -extern long long int llrintl(long double); - -extern long long int llroundf(float); -extern long long int llround(double); -extern long long int llroundl(long double); - - -extern float truncf(float); -extern double trunc(double); -extern long double truncl(long double); - -extern float fmodf(float, float); -extern double fmod(double, double); -extern long double fmodl(long double, long double); - -extern float remainderf(float, float); -extern double remainder(double, double); -extern long double remainderl(long double, long double); - -extern float remquof(float, float, int *); -extern double remquo(double, double, int *); -extern long double remquol(long double, long double, int *); - -extern float copysignf(float, float); -extern double copysign(double, double); -extern long double copysignl(long double, long double); - -extern float nanf(const char *); -extern double nan(const char *); -extern long double nanl(const char *); - -extern float nextafterf(float, float); -extern double nextafter(double, double); -extern long double nextafterl(long double, long double); - -extern double nexttoward(double, long double); -extern float nexttowardf(float, long double); -extern long double nexttowardl(long double, long double); - -extern float fdimf(float, float); -extern double fdim(double, double); -extern long double fdiml(long double, long double); - -extern float fmaxf(float, float); -extern double fmax(double, double); -extern long double fmaxl(long double, long double); - -extern float fminf(float, float); -extern double fmin(double, double); -extern long double fminl(long double, long double); - -extern float fmaf(float, float, float); -extern double fma(double, double, double); -extern long double fmal(long double, long double, long double); -extern float __inff(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern double __inf(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern long double __infl(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - -extern float __nan(void) __attribute__((availability(macosx,introduced=10.0))); -extern float __exp10f(float) __attribute__((availability(macosx,introduced=10.9))); -extern double __exp10(double) __attribute__((availability(macosx,introduced=10.9))); - - - - - -inline __attribute__ ((__always_inline__)) void __sincosf(float __x, float *__sinp, float *__cosp); -inline __attribute__ ((__always_inline__)) void __sincos(double __x, double *__sinp, double *__cosp); -extern float __cospif(float) __attribute__((availability(macosx,introduced=10.9))); -extern double __cospi(double) __attribute__((availability(macosx,introduced=10.9))); -extern float __sinpif(float) __attribute__((availability(macosx,introduced=10.9))); -extern double __sinpi(double) __attribute__((availability(macosx,introduced=10.9))); -extern float __tanpif(float) __attribute__((availability(macosx,introduced=10.9))); -extern double __tanpi(double) __attribute__((availability(macosx,introduced=10.9))); -inline __attribute__ ((__always_inline__)) void __sincospif(float __x, float *__sinp, float *__cosp); -inline __attribute__ ((__always_inline__)) void __sincospi(double __x, double *__sinp, double *__cosp); - - - - - - -struct __float2 { float __sinval; float __cosval; }; -struct __double2 { double __sinval; double __cosval; }; - -extern struct __float2 __sincosf_stret(float); -extern struct __double2 __sincos_stret(double); -extern struct __float2 __sincospif_stret(float); -extern struct __double2 __sincospi_stret(double); - -inline __attribute__ ((__always_inline__)) void __sincosf(float __x, float *__sinp, float *__cosp) { - const struct __float2 __stret = __sincosf_stret(__x); - *__sinp = __stret.__sinval; *__cosp = __stret.__cosval; -} - -inline __attribute__ ((__always_inline__)) void __sincos(double __x, double *__sinp, double *__cosp) { - const struct __double2 __stret = __sincos_stret(__x); - *__sinp = __stret.__sinval; *__cosp = __stret.__cosval; -} - -inline __attribute__ ((__always_inline__)) void __sincospif(float __x, float *__sinp, float *__cosp) { - const struct __float2 __stret = __sincospif_stret(__x); - *__sinp = __stret.__sinval; *__cosp = __stret.__cosval; -} - -inline __attribute__ ((__always_inline__)) void __sincospi(double __x, double *__sinp, double *__cosp) { - const struct __double2 __stret = __sincospi_stret(__x); - *__sinp = __stret.__sinval; *__cosp = __stret.__cosval; -} - - - - - - - -extern double j0(double) __attribute__((availability(macosx,introduced=10.0))); -extern double j1(double) __attribute__((availability(macosx,introduced=10.0))); -extern double jn(int, double) __attribute__((availability(macosx,introduced=10.0))); -extern double y0(double) __attribute__((availability(macosx,introduced=10.0))); -extern double y1(double) __attribute__((availability(macosx,introduced=10.0))); -extern double yn(int, double) __attribute__((availability(macosx,introduced=10.0))); -extern double scalb(double, double); -extern int signgam; -extern long int rinttol(double) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - -extern long int roundtol(double) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - -extern double drem(double, double) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - -extern int finite(double) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - -extern double gamma(double) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - -extern double significand(double) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -} -typedef int jmp_buf[((9 * 2) + 3 + 16)]; -typedef int sigjmp_buf[((9 * 2) + 3 + 16) + 1]; -extern "C" { -extern int setjmp(jmp_buf); -extern void longjmp(jmp_buf, int) __attribute__((noreturn)); - - -int _setjmp(jmp_buf); -void _longjmp(jmp_buf, int) __attribute__((noreturn)); -int sigsetjmp(sigjmp_buf, int); -void siglongjmp(sigjmp_buf, int) __attribute__((noreturn)); - - - -void longjmperror(void); - -} -extern const char *const sys_signame[32]; -extern const char *const sys_siglist[32]; - - -extern "C" { -int raise(int); -} - - -extern "C" { -void (*bsd_signal(int, void (*)(int)))(int); -int kill(pid_t, int) __asm("_" "kill" ); -int killpg(pid_t, int) __asm("_" "killpg" ); -int pthread_kill(pthread_t, int); -int pthread_sigmask(int, const sigset_t *, sigset_t *) __asm("_" "pthread_sigmask" ); -int sigaction(int, const struct sigaction * , - struct sigaction * ); -int sigaddset(sigset_t *, int); -int sigaltstack(const stack_t * , stack_t * ) __asm("_" "sigaltstack" ) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -int sigdelset(sigset_t *, int); -int sigemptyset(sigset_t *); -int sigfillset(sigset_t *); -int sighold(int); -int sigignore(int); -int siginterrupt(int, int); -int sigismember(const sigset_t *, int); -int sigpause(int) __asm("_" "sigpause" ); -int sigpending(sigset_t *); -int sigprocmask(int, const sigset_t * , sigset_t * ); -int sigrelse(int); -void (*sigset(int, void (*)(int)))(int); -int sigsuspend(const sigset_t *) __asm("_" "sigsuspend" ); -int sigwait(const sigset_t * , int * ) __asm("_" "sigwait" ); - -void psignal(unsigned int, const char *); -int sigblock(int); -int sigsetmask(int); -int sigvec(int, struct sigvec *, struct sigvec *); - -} - - - - -inline __attribute__ ((__always_inline__)) int -__sigbits(int __signo) -{ - return __signo > 32 ? 0 : (1 << (__signo - 1)); -} -typedef long int ptrdiff_t; -typedef __darwin_va_list va_list; - - - -extern "C" { - -int renameat(int, const char *, int, const char *) __attribute__((availability(macosx,introduced=10.10))); - -} - -typedef __darwin_off_t fpos_t; -struct __sbuf { - unsigned char *_base; - int _size; -}; - - -struct __sFILEX; -typedef struct __sFILE { - unsigned char *_p; - int _r; - int _w; - short _flags; - short _file; - struct __sbuf _bf; - int _lbfsize; - - - void *_cookie; - int (*_close)(void *); - int (*_read) (void *, char *, int); - fpos_t (*_seek) (void *, fpos_t, int); - int (*_write)(void *, const char *, int); - - - struct __sbuf _ub; - struct __sFILEX *_extra; - int _ur; - - - unsigned char _ubuf[3]; - unsigned char _nbuf[1]; - - - struct __sbuf _lb; - - - int _blksize; - fpos_t _offset; -} FILE; - -extern "C" { -extern FILE *__stdinp; -extern FILE *__stdoutp; -extern FILE *__stderrp; -} -extern "C" { -void clearerr(FILE *); -int fclose(FILE *); -int feof(FILE *); -int ferror(FILE *); -int fflush(FILE *); -int fgetc(FILE *); -int fgetpos(FILE * , fpos_t *); -char *fgets(char * , int, FILE *); - - - -FILE *fopen(const char * , const char * ) __asm("_" "fopen" ); - -int fprintf(FILE * , const char * , ...) __attribute__((__format__ (__printf__, 2, 3))); -int fputc(int, FILE *); -int fputs(const char * , FILE * ) __asm("_" "fputs" ); -size_t fread(void * , size_t, size_t, FILE * ); -FILE *freopen(const char * , const char * , - FILE * ) __asm("_" "freopen" ); -int fscanf(FILE * , const char * , ...) __attribute__((__format__ (__scanf__, 2, 3))); -int fseek(FILE *, long, int); -int fsetpos(FILE *, const fpos_t *); -long ftell(FILE *); -size_t fwrite(const void * , size_t, size_t, FILE * ) __asm("_" "fwrite" ); -int getc(FILE *); -int getchar(void); -char *gets(char *); -void perror(const char *); -int printf(const char * , ...) __attribute__((__format__ (__printf__, 1, 2))); -int putc(int, FILE *); -int putchar(int); -int puts(const char *); -int remove(const char *); -int rename (const char *, const char *); -void rewind(FILE *); -int scanf(const char * , ...) __attribute__((__format__ (__scanf__, 1, 2))); -void setbuf(FILE * , char * ); -int setvbuf(FILE * , char * , int, size_t); -int sprintf(char * , const char * , ...) __attribute__((__format__ (__printf__, 2, 3))); -int sscanf(const char * , const char * , ...) __attribute__((__format__ (__scanf__, 2, 3))); -FILE *tmpfile(void); - - -__attribute__((deprecated("This function is provided for compatibility reasons only. Due to security concerns inherent in the design of tmpnam(3), it is highly recommended that you use mkstemp(3) instead."))) - -char *tmpnam(char *); -int ungetc(int, FILE *); -int vfprintf(FILE * , const char * , va_list) __attribute__((__format__ (__printf__, 2, 0))); -int vprintf(const char * , va_list) __attribute__((__format__ (__printf__, 1, 0))); -int vsprintf(char * , const char * , va_list) __attribute__((__format__ (__printf__, 2, 0))); -} -extern "C" { - - - -char *ctermid(char *); - - - - - -FILE *fdopen(int, const char *) __asm("_" "fdopen" ); - -int fileno(FILE *); -} -extern "C" { -int pclose(FILE *); - - - -FILE *popen(const char *, const char *) __asm("_" "popen" ); - -} -extern "C" { -int __srget(FILE *); -int __svfscanf(FILE *, const char *, va_list) __attribute__((__format__ (__scanf__, 2, 0))); -int __swbuf(int, FILE *); -} - - - - - - - -inline __attribute__ ((__always_inline__)) int __sputc(int _c, FILE *_p) { - if (--_p->_w >= 0 || (_p->_w >= _p->_lbfsize && (char)_c != '\n')) - return (*_p->_p++ = _c); - else - return (__swbuf(_c, _p)); -} -extern "C" { -void flockfile(FILE *); -int ftrylockfile(FILE *); -void funlockfile(FILE *); -int getc_unlocked(FILE *); -int getchar_unlocked(void); -int putc_unlocked(int, FILE *); -int putchar_unlocked(int); - - - -int getw(FILE *); -int putw(int, FILE *); - - - -__attribute__((deprecated("This function is provided for compatibility reasons only. Due to security concerns inherent in the design of tempnam(3), it is highly recommended that you use mkstemp(3) instead."))) - -char *tempnam(const char *, const char *) __asm("_" "tempnam" ); -} -extern "C" { -int fseeko(FILE *, off_t, int); -off_t ftello(FILE *); -} - - - -extern "C" { -int snprintf(char * , size_t, const char * , ...) __attribute__((__format__ (__printf__, 3, 4))); -int vfscanf(FILE * , const char * , va_list) __attribute__((__format__ (__scanf__, 2, 0))); -int vscanf(const char * , va_list) __attribute__((__format__ (__scanf__, 1, 0))); -int vsnprintf(char * , size_t, const char * , va_list) __attribute__((__format__ (__printf__, 3, 0))); -int vsscanf(const char * , const char * , va_list) __attribute__((__format__ (__scanf__, 2, 0))); -} -extern "C" { -int dprintf(int, const char * , ...) __attribute__((__format__ (__printf__, 2, 3))) __attribute__((availability(macosx,introduced=10.7))); -int vdprintf(int, const char * , va_list) __attribute__((__format__ (__printf__, 2, 0))) __attribute__((availability(macosx,introduced=10.7))); -ssize_t getdelim(char ** , size_t * , int, FILE * ) __attribute__((availability(macosx,introduced=10.7))); -ssize_t getline(char ** , size_t * , FILE * ) __attribute__((availability(macosx,introduced=10.7))); -} - - - - - - - -extern "C" { -extern const int sys_nerr; -extern const char *const sys_errlist[]; - -int asprintf(char ** , const char * , ...) __attribute__((__format__ (__printf__, 2, 3))); -char *ctermid_r(char *); -char *fgetln(FILE *, size_t *); -const char *fmtcheck(const char *, const char *); -int fpurge(FILE *); -void setbuffer(FILE *, char *, int); -int setlinebuf(FILE *); -int vasprintf(char ** , const char * , va_list) __attribute__((__format__ (__printf__, 2, 0))); -FILE *zopen(const char *, const char *, int); - - - - - -FILE *funopen(const void *, - int (*)(void *, char *, int), - int (*)(void *, const char *, int), - fpos_t (*)(void *, fpos_t, int), - int (*)(void *)); -} - -extern "C" { -void *memchr(const void *, int, size_t); -int memcmp(const void *, const void *, size_t); -void *memcpy(void *, const void *, size_t); -void *memmove(void *, const void *, size_t); -void *memset(void *, int, size_t); -char *strcat(char *, const char *); -char *strchr(const char *, int); -int strcmp(const char *, const char *); -int strcoll(const char *, const char *); -char *strcpy(char *, const char *); -size_t strcspn(const char *, const char *); -char *strerror(int) __asm("_" "strerror" ); -size_t strlen(const char *); -char *strncat(char *, const char *, size_t); -int strncmp(const char *, const char *, size_t); -char *strncpy(char *, const char *, size_t); -char *strpbrk(const char *, const char *); -char *strrchr(const char *, int); -size_t strspn(const char *, const char *); -char *strstr(const char *, const char *); -char *strtok(char *, const char *); -size_t strxfrm(char *, const char *, size_t); -} -extern "C" { -char *strtok_r(char *, const char *, char **); -} -extern "C" { -int strerror_r(int, char *, size_t); -char *strdup(const char *); -void *memccpy(void *, const void *, int, size_t); -} -extern "C" { -char *stpcpy(char *, const char *); -char *stpncpy(char *, const char *, size_t) __attribute__((availability(macosx,introduced=10.7))); -char *strndup(const char *, size_t) __attribute__((availability(macosx,introduced=10.7))); -size_t strnlen(const char *, size_t) __attribute__((availability(macosx,introduced=10.7))); -char *strsignal(int sig); -} -extern "C" { -errno_t memset_s(void *, rsize_t, int, rsize_t) __attribute__((availability(macosx,introduced=10.9))); -} - - - - - - - -extern "C" { -void *memmem(const void *, size_t, const void *, size_t) __attribute__((availability(macosx,introduced=10.7))); -void memset_pattern4(void *, const void *, size_t) __attribute__((availability(macosx,introduced=10.5))); -void memset_pattern8(void *, const void *, size_t) __attribute__((availability(macosx,introduced=10.5))); -void memset_pattern16(void *, const void *, size_t) __attribute__((availability(macosx,introduced=10.5))); - -char *strcasestr(const char *, const char *); -char *strnstr(const char *, const char *, size_t); -size_t strlcat(char *, const char *, size_t); -size_t strlcpy(char *, const char *, size_t); -void strmode(int, char *); -char *strsep(char **, const char *); - - -void swab(const void * , void * , ssize_t); -} - - - - - - - -extern "C" { - - -int bcmp(const void *, const void *, size_t) ; -void bcopy(const void *, void *, size_t) ; -void bzero(void *, size_t) ; -char *index(const char *, int) ; -char *rindex(const char *, int) ; - - -int ffs(int); -int strcasecmp(const char *, const char *); -int strncasecmp(const char *, const char *, size_t); -} - - - -extern "C" { -int ffsl(long) __attribute__((availability(macosx,introduced=10.5))); -int ffsll(long long) __attribute__((availability(macosx,introduced=10.9))); -int fls(int) __attribute__((availability(macosx,introduced=10.5))); -int flsl(long) __attribute__((availability(macosx,introduced=10.5))); -int flsll(long long) __attribute__((availability(macosx,introduced=10.9))); -} - - -struct timespec -{ - __darwin_time_t tv_sec; - long tv_nsec; -}; - -struct tm { - int tm_sec; - int tm_min; - int tm_hour; - int tm_mday; - int tm_mon; - int tm_year; - int tm_wday; - int tm_yday; - int tm_isdst; - long tm_gmtoff; - char *tm_zone; -}; -extern char *tzname[]; - - -extern int getdate_err; - -extern long timezone __asm("_" "timezone" ); - -extern int daylight; - -extern "C" { -char *asctime(const struct tm *); -clock_t clock(void) __asm("_" "clock" ); -char *ctime(const time_t *); -double difftime(time_t, time_t); -struct tm *getdate(const char *); -struct tm *gmtime(const time_t *); -struct tm *localtime(const time_t *); -time_t mktime(struct tm *) __asm("_" "mktime" ); -size_t strftime(char * , size_t, const char * , const struct tm * ) __asm("_" "strftime" ); -char *strptime(const char * , const char * , struct tm * ) __asm("_" "strptime" ); -time_t time(time_t *); - - -void tzset(void); - - - -char *asctime_r(const struct tm * , char * ); -char *ctime_r(const time_t *, char *); -struct tm *gmtime_r(const time_t * , struct tm * ); -struct tm *localtime_r(const time_t * , struct tm * ); - - -time_t posix2time(time_t); - - - -void tzsetwall(void); -time_t time2posix(time_t); -time_t timelocal(struct tm * const); -time_t timegm(struct tm * const); - - - -int nanosleep(const struct timespec *, struct timespec *) __asm("_" "nanosleep" ); - -} - - - - - - - - - - -extern "C" { - - - - - -extern "C" void *_Block_copy(const void *aBlock) - __attribute__((availability(macosx,introduced=10.6))); - - -extern "C" void _Block_release(const void *aBlock) - __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" void _Block_object_assign(void *, const void *, const int) - __attribute__((availability(macosx,introduced=10.6))); - - -extern "C" void _Block_object_dispose(const void *, const int) - __attribute__((availability(macosx,introduced=10.6))); - - -extern "C" void * _NSConcreteGlobalBlock[32] - __attribute__((availability(macosx,introduced=10.6))); -extern "C" void * _NSConcreteStackBlock[32] - __attribute__((availability(macosx,introduced=10.6))); - - - -} - - - - -extern "C" { - - -#pragma pack(push, 2) -typedef unsigned char UInt8; -typedef signed char SInt8; -typedef unsigned short UInt16; -typedef signed short SInt16; - - -typedef unsigned int UInt32; -typedef signed int SInt32; -struct wide { - UInt32 lo; - SInt32 hi; -}; -typedef struct wide wide; -struct UnsignedWide { - UInt32 lo; - UInt32 hi; -}; -typedef struct UnsignedWide UnsignedWide; - typedef signed long long SInt64; - typedef unsigned long long UInt64; -typedef SInt32 Fixed; -typedef Fixed * FixedPtr; -typedef SInt32 Fract; -typedef Fract * FractPtr; -typedef UInt32 UnsignedFixed; -typedef UnsignedFixed * UnsignedFixedPtr; -typedef short ShortFixed; -typedef ShortFixed * ShortFixedPtr; -typedef float Float32; -typedef double Float64; -struct Float80 { - SInt16 exp; - UInt16 man[4]; -}; -typedef struct Float80 Float80; - -struct Float96 { - SInt16 exp[2]; - UInt16 man[4]; -}; -typedef struct Float96 Float96; -struct Float32Point { - Float32 x; - Float32 y; -}; -typedef struct Float32Point Float32Point; -typedef char * Ptr; -typedef Ptr * Handle; -typedef long Size; -typedef SInt16 OSErr; -typedef SInt32 OSStatus; -typedef void * LogicalAddress; -typedef const void * ConstLogicalAddress; -typedef void * PhysicalAddress; -typedef UInt8 * BytePtr; -typedef unsigned long ByteCount; -typedef unsigned long ByteOffset; -typedef SInt32 Duration; -typedef UnsignedWide AbsoluteTime; -typedef UInt32 OptionBits; -typedef unsigned long ItemCount; -typedef UInt32 PBVersion; -typedef SInt16 ScriptCode; -typedef SInt16 LangCode; -typedef SInt16 RegionCode; -typedef UInt32 FourCharCode; -typedef FourCharCode OSType; -typedef FourCharCode ResType; -typedef OSType * OSTypePtr; -typedef ResType * ResTypePtr; -typedef unsigned char Boolean; -typedef long ( * ProcPtr)(); -typedef void ( * Register68kProcPtr)(); - - - - -typedef ProcPtr UniversalProcPtr; - - -typedef ProcPtr * ProcHandle; -typedef UniversalProcPtr * UniversalProcHandle; -typedef void * PRefCon; - -typedef void * URefCon; -typedef void * SRefCon; -enum { - noErr = 0 -}; - -enum { - kNilOptions = 0 -}; - - -enum { - kVariableLengthArray - - - __attribute__((deprecated)) - - - = 1 -}; - -enum { - kUnknownType = 0x3F3F3F3F -}; -typedef UInt32 UnicodeScalarValue; -typedef UInt32 UTF32Char; -typedef UInt16 UniChar; -typedef UInt16 UTF16Char; -typedef UInt8 UTF8Char; -typedef UniChar * UniCharPtr; -typedef unsigned long UniCharCount; -typedef UniCharCount * UniCharCountPtr; -typedef unsigned char Str255[256]; -typedef unsigned char Str63[64]; -typedef unsigned char Str32[33]; -typedef unsigned char Str31[32]; -typedef unsigned char Str27[28]; -typedef unsigned char Str15[16]; -typedef unsigned char Str32Field[34]; -typedef Str63 StrFileName; -typedef unsigned char * StringPtr; -typedef StringPtr * StringHandle; -typedef const unsigned char * ConstStringPtr; -typedef const unsigned char * ConstStr255Param; -typedef const unsigned char * ConstStr63Param; -typedef const unsigned char * ConstStr32Param; -typedef const unsigned char * ConstStr31Param; -typedef const unsigned char * ConstStr27Param; -typedef const unsigned char * ConstStr15Param; -typedef ConstStr63Param ConstStrFileNameParam; - -inline unsigned char StrLength(ConstStr255Param string) { return (*string); } -struct ProcessSerialNumber { - UInt32 highLongOfPSN; - UInt32 lowLongOfPSN; -}; -typedef struct ProcessSerialNumber ProcessSerialNumber; -typedef ProcessSerialNumber * ProcessSerialNumberPtr; -struct Point { - short v; - short h; -}; -typedef struct Point Point; -typedef Point * PointPtr; -struct Rect { - short top; - short left; - short bottom; - short right; -}; -typedef struct Rect Rect; -typedef Rect * RectPtr; -struct FixedPoint { - Fixed x; - Fixed y; -}; -typedef struct FixedPoint FixedPoint; -struct FixedRect { - Fixed left; - Fixed top; - Fixed right; - Fixed bottom; -}; -typedef struct FixedRect FixedRect; - -typedef short CharParameter; -enum { - normal = 0, - bold = 1, - italic = 2, - underline = 4, - outline = 8, - shadow = 0x10, - condense = 0x20, - extend = 0x40 -}; - -typedef unsigned char Style; -typedef short StyleParameter; -typedef Style StyleField; -typedef SInt32 TimeValue; -typedef SInt32 TimeScale; -typedef wide CompTimeValue; -typedef SInt64 TimeValue64; -typedef struct TimeBaseRecord* TimeBase; -struct TimeRecord { - CompTimeValue value; - TimeScale scale; - TimeBase base; -}; -typedef struct TimeRecord TimeRecord; -struct NumVersion { - - UInt8 nonRelRev; - UInt8 stage; - UInt8 minorAndBugRev; - UInt8 majorRev; -}; -typedef struct NumVersion NumVersion; - - -enum { - - developStage = 0x20, - alphaStage = 0x40, - betaStage = 0x60, - finalStage = 0x80 -}; - -union NumVersionVariant { - - NumVersion parts; - UInt32 whole; -}; -typedef union NumVersionVariant NumVersionVariant; -typedef NumVersionVariant * NumVersionVariantPtr; -typedef NumVersionVariantPtr * NumVersionVariantHandle; -struct VersRec { - - NumVersion numericVersion; - short countryCode; - Str255 shortVersion; - Str255 reserved; -}; -typedef struct VersRec VersRec; -typedef VersRec * VersRecPtr; -typedef VersRecPtr * VersRecHndl; - - - - - -typedef UInt8 Byte; -typedef SInt8 SignedByte; -typedef wide * WidePtr; -typedef UnsignedWide * UnsignedWidePtr; -typedef Float80 extended80; -typedef Float96 extended96; -typedef SInt8 VHSelect; -extern void -Debugger(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DebugStr(ConstStr255Param debuggerMsg) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SysBreak(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SysBreakStr(ConstStr255Param debuggerMsg) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SysBreakFunc(ConstStr255Param debuggerMsg) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -#pragma pack(pop) - - -} -extern "C" { -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSAttributedString; -#ifndef _REWRITER_typedef_NSAttributedString -#define _REWRITER_typedef_NSAttributedString -typedef struct objc_object NSAttributedString; -typedef struct {} _objc_exc_NSAttributedString; -#endif - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSNull; -#ifndef _REWRITER_typedef_NSNull -#define _REWRITER_typedef_NSNull -typedef struct objc_object NSNull; -typedef struct {} _objc_exc_NSNull; -#endif - -// @class NSCharacterSet; -#ifndef _REWRITER_typedef_NSCharacterSet -#define _REWRITER_typedef_NSCharacterSet -typedef struct objc_object NSCharacterSet; -typedef struct {} _objc_exc_NSCharacterSet; -#endif - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -// @class NSDate; -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -// @class NSTimeZone; -#ifndef _REWRITER_typedef_NSTimeZone -#define _REWRITER_typedef_NSTimeZone -typedef struct objc_object NSTimeZone; -typedef struct {} _objc_exc_NSTimeZone; -#endif - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -// @class NSError; -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -// @class NSLocale; -#ifndef _REWRITER_typedef_NSLocale -#define _REWRITER_typedef_NSLocale -typedef struct objc_object NSLocale; -typedef struct {} _objc_exc_NSLocale; -#endif - -// @class NSNumber; -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - -// @class NSSet; -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - -// @class NSURL; -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -extern double kCFCoreFoundationVersionNumber; -typedef unsigned long CFTypeID; -typedef unsigned long CFOptionFlags; -typedef unsigned long CFHashCode; -typedef signed long CFIndex; - - - -typedef const __attribute__((objc_bridge(id))) void * CFTypeRef; - -typedef const struct __attribute__((objc_bridge(NSString))) __CFString * CFStringRef; -typedef struct __attribute__((objc_bridge_mutable(NSMutableString))) __CFString * CFMutableStringRef; - - - - - - -typedef __attribute__((objc_bridge(id))) CFTypeRef CFPropertyListRef; - - -typedef CFIndex CFComparisonResult; enum { - kCFCompareLessThan = -1L, - kCFCompareEqualTo = 0, - kCFCompareGreaterThan = 1 -}; - - -typedef CFComparisonResult (*CFComparatorFunction)(const void *val1, const void *val2, void *context); - - -static const CFIndex kCFNotFound = -1; - - - -typedef struct { - CFIndex location; - CFIndex length; -} CFRange; - - -static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) { - CFRange range; - range.location = loc; - range.length = len; - return range; -} - - - - - -extern -CFRange __CFRangeMake(CFIndex loc, CFIndex len); - - - - -typedef const struct __attribute__((objc_bridge(NSNull))) __CFNull * CFNullRef; - -extern -CFTypeID CFNullGetTypeID(void); - -extern -const CFNullRef kCFNull; -typedef const struct __attribute__((objc_bridge(id))) __CFAllocator * CFAllocatorRef; - - -extern -const CFAllocatorRef kCFAllocatorDefault; - - -extern -const CFAllocatorRef kCFAllocatorSystemDefault; - - - - - - - -extern -const CFAllocatorRef kCFAllocatorMalloc; - - - - - -extern -const CFAllocatorRef kCFAllocatorMallocZone; - - - - - -extern -const CFAllocatorRef kCFAllocatorNull; - - - - - -extern -const CFAllocatorRef kCFAllocatorUseContext; - -typedef const void * (*CFAllocatorRetainCallBack)(const void *info); -typedef void (*CFAllocatorReleaseCallBack)(const void *info); -typedef CFStringRef (*CFAllocatorCopyDescriptionCallBack)(const void *info); -typedef void * (*CFAllocatorAllocateCallBack)(CFIndex allocSize, CFOptionFlags hint, void *info); -typedef void * (*CFAllocatorReallocateCallBack)(void *ptr, CFIndex newsize, CFOptionFlags hint, void *info); -typedef void (*CFAllocatorDeallocateCallBack)(void *ptr, void *info); -typedef CFIndex (*CFAllocatorPreferredSizeCallBack)(CFIndex size, CFOptionFlags hint, void *info); -typedef struct { - CFIndex version; - void * info; - CFAllocatorRetainCallBack retain; - CFAllocatorReleaseCallBack release; - CFAllocatorCopyDescriptionCallBack copyDescription; - CFAllocatorAllocateCallBack allocate; - CFAllocatorReallocateCallBack reallocate; - CFAllocatorDeallocateCallBack deallocate; - CFAllocatorPreferredSizeCallBack preferredSize; -} CFAllocatorContext; - -extern -CFTypeID CFAllocatorGetTypeID(void); -extern -void CFAllocatorSetDefault(CFAllocatorRef allocator); - -extern -CFAllocatorRef CFAllocatorGetDefault(void); - -extern -CFAllocatorRef CFAllocatorCreate(CFAllocatorRef allocator, CFAllocatorContext *context); - -extern -void *CFAllocatorAllocate(CFAllocatorRef allocator, CFIndex size, CFOptionFlags hint); - -extern -void *CFAllocatorReallocate(CFAllocatorRef allocator, void *ptr, CFIndex newsize, CFOptionFlags hint); - -extern -void CFAllocatorDeallocate(CFAllocatorRef allocator, void *ptr); - -extern -CFIndex CFAllocatorGetPreferredSizeForSize(CFAllocatorRef allocator, CFIndex size, CFOptionFlags hint); - -extern -void CFAllocatorGetContext(CFAllocatorRef allocator, CFAllocatorContext *context); - - - - - - -extern -CFTypeID CFGetTypeID(CFTypeRef cf); - -extern -CFStringRef CFCopyTypeIDDescription(CFTypeID type_id); - -extern -CFTypeRef CFRetain(CFTypeRef cf); - -extern -void CFRelease(CFTypeRef cf); - -extern -CFTypeRef CFAutorelease(CFTypeRef __attribute__((cf_consumed)) arg) __attribute__((availability(macosx,introduced=10_9))); - -extern -CFIndex CFGetRetainCount(CFTypeRef cf); - -extern -Boolean CFEqual(CFTypeRef cf1, CFTypeRef cf2); - -extern -CFHashCode CFHash(CFTypeRef cf); - -extern -CFStringRef CFCopyDescription(CFTypeRef cf); - -extern -CFAllocatorRef CFGetAllocator(CFTypeRef cf); - - - - -extern -CFTypeRef CFMakeCollectable(CFTypeRef cf) ; - -} -extern "C" { -typedef const void * (*CFArrayRetainCallBack)(CFAllocatorRef allocator, const void *value); -typedef void (*CFArrayReleaseCallBack)(CFAllocatorRef allocator, const void *value); -typedef CFStringRef (*CFArrayCopyDescriptionCallBack)(const void *value); -typedef Boolean (*CFArrayEqualCallBack)(const void *value1, const void *value2); -typedef struct { - CFIndex version; - CFArrayRetainCallBack retain; - CFArrayReleaseCallBack release; - CFArrayCopyDescriptionCallBack copyDescription; - CFArrayEqualCallBack equal; -} CFArrayCallBacks; - - - - - - -extern -const CFArrayCallBacks kCFTypeArrayCallBacks; -typedef void (*CFArrayApplierFunction)(const void *value, void *context); - - - - - -typedef const struct __attribute__((objc_bridge(NSArray))) __CFArray * CFArrayRef; - - - - - -typedef struct __attribute__((objc_bridge_mutable(NSMutableArray))) __CFArray * CFMutableArrayRef; - - - - - -extern -CFTypeID CFArrayGetTypeID(void); -extern -CFArrayRef CFArrayCreate(CFAllocatorRef allocator, const void **values, CFIndex numValues, const CFArrayCallBacks *callBacks); -extern -CFArrayRef CFArrayCreateCopy(CFAllocatorRef allocator, CFArrayRef theArray); -extern -CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks); -extern -CFMutableArrayRef CFArrayCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFArrayRef theArray); -extern -CFIndex CFArrayGetCount(CFArrayRef theArray); -extern -CFIndex CFArrayGetCountOfValue(CFArrayRef theArray, CFRange range, const void *value); -extern -Boolean CFArrayContainsValue(CFArrayRef theArray, CFRange range, const void *value); -extern -const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx); -extern -void CFArrayGetValues(CFArrayRef theArray, CFRange range, const void **values); -extern -void CFArrayApplyFunction(CFArrayRef theArray, CFRange range, CFArrayApplierFunction applier, void *context); -extern -CFIndex CFArrayGetFirstIndexOfValue(CFArrayRef theArray, CFRange range, const void *value); -extern -CFIndex CFArrayGetLastIndexOfValue(CFArrayRef theArray, CFRange range, const void *value); -extern -CFIndex CFArrayBSearchValues(CFArrayRef theArray, CFRange range, const void *value, CFComparatorFunction comparator, void *context); -extern -void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value); -extern -void CFArrayInsertValueAtIndex(CFMutableArrayRef theArray, CFIndex idx, const void *value); -extern -void CFArraySetValueAtIndex(CFMutableArrayRef theArray, CFIndex idx, const void *value); -extern -void CFArrayRemoveValueAtIndex(CFMutableArrayRef theArray, CFIndex idx); -extern -void CFArrayRemoveAllValues(CFMutableArrayRef theArray); -extern -void CFArrayReplaceValues(CFMutableArrayRef theArray, CFRange range, const void **newValues, CFIndex newCount); -extern -void CFArrayExchangeValuesAtIndices(CFMutableArrayRef theArray, CFIndex idx1, CFIndex idx2); -extern -void CFArraySortValues(CFMutableArrayRef theArray, CFRange range, CFComparatorFunction comparator, void *context); -extern -void CFArrayAppendArray(CFMutableArrayRef theArray, CFArrayRef otherArray, CFRange otherRange); - -} -extern "C" { - -typedef const void * (*CFBagRetainCallBack)(CFAllocatorRef allocator, const void *value); -typedef void (*CFBagReleaseCallBack)(CFAllocatorRef allocator, const void *value); -typedef CFStringRef (*CFBagCopyDescriptionCallBack)(const void *value); -typedef Boolean (*CFBagEqualCallBack)(const void *value1, const void *value2); -typedef CFHashCode (*CFBagHashCallBack)(const void *value); -typedef struct { - CFIndex version; - CFBagRetainCallBack retain; - CFBagReleaseCallBack release; - CFBagCopyDescriptionCallBack copyDescription; - CFBagEqualCallBack equal; - CFBagHashCallBack hash; -} CFBagCallBacks; - -extern -const CFBagCallBacks kCFTypeBagCallBacks; -extern -const CFBagCallBacks kCFCopyStringBagCallBacks; - -typedef void (*CFBagApplierFunction)(const void *value, void *context); - -typedef const struct __attribute__((objc_bridge(id))) __CFBag * CFBagRef; -typedef struct __attribute__((objc_bridge_mutable(id))) __CFBag * CFMutableBagRef; - -extern -CFTypeID CFBagGetTypeID(void); - -extern -CFBagRef CFBagCreate(CFAllocatorRef allocator, const void **values, CFIndex numValues, const CFBagCallBacks *callBacks); - -extern -CFBagRef CFBagCreateCopy(CFAllocatorRef allocator, CFBagRef theBag); - -extern -CFMutableBagRef CFBagCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFBagCallBacks *callBacks); - -extern -CFMutableBagRef CFBagCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFBagRef theBag); - -extern -CFIndex CFBagGetCount(CFBagRef theBag); - -extern -CFIndex CFBagGetCountOfValue(CFBagRef theBag, const void *value); - -extern -Boolean CFBagContainsValue(CFBagRef theBag, const void *value); - -extern -const void *CFBagGetValue(CFBagRef theBag, const void *value); - -extern -Boolean CFBagGetValueIfPresent(CFBagRef theBag, const void *candidate, const void **value); - -extern -void CFBagGetValues(CFBagRef theBag, const void **values); - -extern -void CFBagApplyFunction(CFBagRef theBag, CFBagApplierFunction applier, void *context); - -extern -void CFBagAddValue(CFMutableBagRef theBag, const void *value); - -extern -void CFBagReplaceValue(CFMutableBagRef theBag, const void *value); - -extern -void CFBagSetValue(CFMutableBagRef theBag, const void *value); - -extern -void CFBagRemoveValue(CFMutableBagRef theBag, const void *value); - -extern -void CFBagRemoveAllValues(CFMutableBagRef theBag); - -} -extern "C" { - -typedef struct { - CFIndex version; - void * info; - const void *(*retain)(const void *info); - void (*release)(const void *info); - CFStringRef (*copyDescription)(const void *info); -} CFBinaryHeapCompareContext; -typedef struct { - CFIndex version; - const void *(*retain)(CFAllocatorRef allocator, const void *ptr); - void (*release)(CFAllocatorRef allocator, const void *ptr); - CFStringRef (*copyDescription)(const void *ptr); - CFComparisonResult (*compare)(const void *ptr1, const void *ptr2, void *context); -} CFBinaryHeapCallBacks; - - - - - - - -extern const CFBinaryHeapCallBacks kCFStringBinaryHeapCallBacks; -typedef void (*CFBinaryHeapApplierFunction)(const void *val, void *context); - - - - - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFBinaryHeap * CFBinaryHeapRef; - - - - - -extern CFTypeID CFBinaryHeapGetTypeID(void); -extern CFBinaryHeapRef CFBinaryHeapCreate(CFAllocatorRef allocator, CFIndex capacity, const CFBinaryHeapCallBacks *callBacks, const CFBinaryHeapCompareContext *compareContext); -extern CFBinaryHeapRef CFBinaryHeapCreateCopy(CFAllocatorRef allocator, CFIndex capacity, CFBinaryHeapRef heap); -extern CFIndex CFBinaryHeapGetCount(CFBinaryHeapRef heap); -extern CFIndex CFBinaryHeapGetCountOfValue(CFBinaryHeapRef heap, const void *value); -extern Boolean CFBinaryHeapContainsValue(CFBinaryHeapRef heap, const void *value); -extern const void * CFBinaryHeapGetMinimum(CFBinaryHeapRef heap); -extern Boolean CFBinaryHeapGetMinimumIfPresent(CFBinaryHeapRef heap, const void **value); -extern void CFBinaryHeapGetValues(CFBinaryHeapRef heap, const void **values); -extern void CFBinaryHeapApplyFunction(CFBinaryHeapRef heap, CFBinaryHeapApplierFunction applier, void *context); -extern void CFBinaryHeapAddValue(CFBinaryHeapRef heap, const void *value); - - - - - - - -extern void CFBinaryHeapRemoveMinimumValue(CFBinaryHeapRef heap); -extern void CFBinaryHeapRemoveAllValues(CFBinaryHeapRef heap); - -} -extern "C" { - -typedef UInt32 CFBit; - -typedef const struct __attribute__((objc_bridge(id))) __CFBitVector * CFBitVectorRef; -typedef struct __attribute__((objc_bridge_mutable(id))) __CFBitVector * CFMutableBitVectorRef; - -extern CFTypeID CFBitVectorGetTypeID(void); - -extern CFBitVectorRef CFBitVectorCreate(CFAllocatorRef allocator, const UInt8 *bytes, CFIndex numBits); -extern CFBitVectorRef CFBitVectorCreateCopy(CFAllocatorRef allocator, CFBitVectorRef bv); -extern CFMutableBitVectorRef CFBitVectorCreateMutable(CFAllocatorRef allocator, CFIndex capacity); -extern CFMutableBitVectorRef CFBitVectorCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFBitVectorRef bv); - -extern CFIndex CFBitVectorGetCount(CFBitVectorRef bv); -extern CFIndex CFBitVectorGetCountOfBit(CFBitVectorRef bv, CFRange range, CFBit value); -extern Boolean CFBitVectorContainsBit(CFBitVectorRef bv, CFRange range, CFBit value); -extern CFBit CFBitVectorGetBitAtIndex(CFBitVectorRef bv, CFIndex idx); -extern void CFBitVectorGetBits(CFBitVectorRef bv, CFRange range, UInt8 *bytes); -extern CFIndex CFBitVectorGetFirstIndexOfBit(CFBitVectorRef bv, CFRange range, CFBit value); -extern CFIndex CFBitVectorGetLastIndexOfBit(CFBitVectorRef bv, CFRange range, CFBit value); - -extern void CFBitVectorSetCount(CFMutableBitVectorRef bv, CFIndex count); -extern void CFBitVectorFlipBitAtIndex(CFMutableBitVectorRef bv, CFIndex idx); -extern void CFBitVectorFlipBits(CFMutableBitVectorRef bv, CFRange range); -extern void CFBitVectorSetBitAtIndex(CFMutableBitVectorRef bv, CFIndex idx, CFBit value); -extern void CFBitVectorSetBits(CFMutableBitVectorRef bv, CFRange range, CFBit value); -extern void CFBitVectorSetAllBits(CFMutableBitVectorRef bv, CFBit value); - -} - - - -static __inline__ -uint16_t -OSReadSwapInt16( - const volatile void * base, - uintptr_t byteOffset -) -{ - uint16_t result; - - result = *(volatile uint16_t *)((uintptr_t)base + byteOffset); - return _OSSwapInt16(result); -} - -static __inline__ -uint32_t -OSReadSwapInt32( - const volatile void * base, - uintptr_t byteOffset -) -{ - uint32_t result; - - result = *(volatile uint32_t *)((uintptr_t)base + byteOffset); - return _OSSwapInt32(result); -} - -static __inline__ -uint64_t -OSReadSwapInt64( - const volatile void * base, - uintptr_t byteOffset -) -{ - uint64_t result; - - result = *(volatile uint64_t *)((uintptr_t)base + byteOffset); - return _OSSwapInt64(result); -} - - - -static __inline__ -void -OSWriteSwapInt16( - volatile void * base, - uintptr_t byteOffset, - uint16_t data -) -{ - *(volatile uint16_t *)((uintptr_t)base + byteOffset) = _OSSwapInt16(data); -} - -static __inline__ -void -OSWriteSwapInt32( - volatile void * base, - uintptr_t byteOffset, - uint32_t data -) -{ - *(volatile uint32_t *)((uintptr_t)base + byteOffset) = _OSSwapInt32(data); -} - -static __inline__ -void -OSWriteSwapInt64( - volatile void * base, - uintptr_t byteOffset, - uint64_t data -) -{ - *(volatile uint64_t *)((uintptr_t)base + byteOffset) = _OSSwapInt64(data); -} -enum { - OSUnknownByteOrder, - OSLittleEndian, - OSBigEndian -}; - -static __inline__ -int32_t -OSHostByteOrder(void) { - - return OSLittleEndian; - - - - - -} -static __inline__ -uint16_t -_OSReadInt16( - const volatile void * base, - uintptr_t byteOffset -) -{ - return *(volatile uint16_t *)((uintptr_t)base + byteOffset); -} - -static __inline__ -uint32_t -_OSReadInt32( - const volatile void * base, - uintptr_t byteOffset -) -{ - return *(volatile uint32_t *)((uintptr_t)base + byteOffset); -} - -static __inline__ -uint64_t -_OSReadInt64( - const volatile void * base, - uintptr_t byteOffset -) -{ - return *(volatile uint64_t *)((uintptr_t)base + byteOffset); -} - - - -static __inline__ -void -_OSWriteInt16( - volatile void * base, - uintptr_t byteOffset, - uint16_t data -) -{ - *(volatile uint16_t *)((uintptr_t)base + byteOffset) = data; -} - -static __inline__ -void -_OSWriteInt32( - volatile void * base, - uintptr_t byteOffset, - uint32_t data -) -{ - *(volatile uint32_t *)((uintptr_t)base + byteOffset) = data; -} - -static __inline__ -void -_OSWriteInt64( - volatile void * base, - uintptr_t byteOffset, - uint64_t data -) -{ - *(volatile uint64_t *)((uintptr_t)base + byteOffset) = data; -} - - - -extern "C" { - -enum __CFByteOrder { - CFByteOrderUnknown, - CFByteOrderLittleEndian, - CFByteOrderBigEndian -}; -typedef CFIndex CFByteOrder; - -static __inline__ __attribute__((always_inline)) CFByteOrder CFByteOrderGetCurrent(void) { - - int32_t byteOrder = OSHostByteOrder(); - switch (byteOrder) { - case OSLittleEndian: return CFByteOrderLittleEndian; - case OSBigEndian: return CFByteOrderBigEndian; - default: break; - } - return CFByteOrderUnknown; -} - -static __inline__ __attribute__((always_inline)) uint16_t CFSwapInt16(uint16_t arg) { - - return ((__uint16_t)(__builtin_constant_p(arg) ? ((__uint16_t)((((__uint16_t)(arg) & 0xff00) >> 8) | (((__uint16_t)(arg) & 0x00ff) << 8))) : _OSSwapInt16(arg))); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint32_t CFSwapInt32(uint32_t arg) { - - return (__builtin_constant_p(arg) ? ((__uint32_t)((((__uint32_t)(arg) & 0xff000000) >> 24) | (((__uint32_t)(arg) & 0x00ff0000) >> 8) | (((__uint32_t)(arg) & 0x0000ff00) << 8) | (((__uint32_t)(arg) & 0x000000ff) << 24))) : _OSSwapInt32(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint64_t CFSwapInt64(uint64_t arg) { - - return (__builtin_constant_p(arg) ? ((__uint64_t)((((__uint64_t)(arg) & 0xff00000000000000ULL) >> 56) | (((__uint64_t)(arg) & 0x00ff000000000000ULL) >> 40) | (((__uint64_t)(arg) & 0x0000ff0000000000ULL) >> 24) | (((__uint64_t)(arg) & 0x000000ff00000000ULL) >> 8) | (((__uint64_t)(arg) & 0x00000000ff000000ULL) << 8) | (((__uint64_t)(arg) & 0x0000000000ff0000ULL) << 24) | (((__uint64_t)(arg) & 0x000000000000ff00ULL) << 40) | (((__uint64_t)(arg) & 0x00000000000000ffULL) << 56))) : _OSSwapInt64(arg)); -} - -static __inline__ __attribute__((always_inline)) uint16_t CFSwapInt16BigToHost(uint16_t arg) { - - return ((__uint16_t)(__builtin_constant_p(arg) ? ((__uint16_t)((((__uint16_t)(arg) & 0xff00) >> 8) | (((__uint16_t)(arg) & 0x00ff) << 8))) : _OSSwapInt16(arg))); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint32_t CFSwapInt32BigToHost(uint32_t arg) { - - return (__builtin_constant_p(arg) ? ((__uint32_t)((((__uint32_t)(arg) & 0xff000000) >> 24) | (((__uint32_t)(arg) & 0x00ff0000) >> 8) | (((__uint32_t)(arg) & 0x0000ff00) << 8) | (((__uint32_t)(arg) & 0x000000ff) << 24))) : _OSSwapInt32(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint64_t CFSwapInt64BigToHost(uint64_t arg) { - - return (__builtin_constant_p(arg) ? ((__uint64_t)((((__uint64_t)(arg) & 0xff00000000000000ULL) >> 56) | (((__uint64_t)(arg) & 0x00ff000000000000ULL) >> 40) | (((__uint64_t)(arg) & 0x0000ff0000000000ULL) >> 24) | (((__uint64_t)(arg) & 0x000000ff00000000ULL) >> 8) | (((__uint64_t)(arg) & 0x00000000ff000000ULL) << 8) | (((__uint64_t)(arg) & 0x0000000000ff0000ULL) << 24) | (((__uint64_t)(arg) & 0x000000000000ff00ULL) << 40) | (((__uint64_t)(arg) & 0x00000000000000ffULL) << 56))) : _OSSwapInt64(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint16_t CFSwapInt16HostToBig(uint16_t arg) { - - return ((__uint16_t)(__builtin_constant_p(arg) ? ((__uint16_t)((((__uint16_t)(arg) & 0xff00) >> 8) | (((__uint16_t)(arg) & 0x00ff) << 8))) : _OSSwapInt16(arg))); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint32_t CFSwapInt32HostToBig(uint32_t arg) { - - return (__builtin_constant_p(arg) ? ((__uint32_t)((((__uint32_t)(arg) & 0xff000000) >> 24) | (((__uint32_t)(arg) & 0x00ff0000) >> 8) | (((__uint32_t)(arg) & 0x0000ff00) << 8) | (((__uint32_t)(arg) & 0x000000ff) << 24))) : _OSSwapInt32(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint64_t CFSwapInt64HostToBig(uint64_t arg) { - - return (__builtin_constant_p(arg) ? ((__uint64_t)((((__uint64_t)(arg) & 0xff00000000000000ULL) >> 56) | (((__uint64_t)(arg) & 0x00ff000000000000ULL) >> 40) | (((__uint64_t)(arg) & 0x0000ff0000000000ULL) >> 24) | (((__uint64_t)(arg) & 0x000000ff00000000ULL) >> 8) | (((__uint64_t)(arg) & 0x00000000ff000000ULL) << 8) | (((__uint64_t)(arg) & 0x0000000000ff0000ULL) << 24) | (((__uint64_t)(arg) & 0x000000000000ff00ULL) << 40) | (((__uint64_t)(arg) & 0x00000000000000ffULL) << 56))) : _OSSwapInt64(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint16_t CFSwapInt16LittleToHost(uint16_t arg) { - - return ((uint16_t)(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint32_t CFSwapInt32LittleToHost(uint32_t arg) { - - return ((uint32_t)(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint64_t CFSwapInt64LittleToHost(uint64_t arg) { - - return ((uint64_t)(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint16_t CFSwapInt16HostToLittle(uint16_t arg) { - - return ((uint16_t)(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint32_t CFSwapInt32HostToLittle(uint32_t arg) { - - return ((uint32_t)(arg)); - - - - - -} - -static __inline__ __attribute__((always_inline)) uint64_t CFSwapInt64HostToLittle(uint64_t arg) { - - return ((uint64_t)(arg)); - - - - - -} - -typedef struct {uint32_t v;} CFSwappedFloat32; -typedef struct {uint64_t v;} CFSwappedFloat64; - -static __inline__ __attribute__((always_inline)) CFSwappedFloat32 CFConvertFloat32HostToSwapped(Float32 arg) { - union CFSwap { - Float32 v; - CFSwappedFloat32 sv; - } result; - result.v = arg; - - result.sv.v = CFSwapInt32(result.sv.v); - - return result.sv; -} - -static __inline__ __attribute__((always_inline)) Float32 CFConvertFloat32SwappedToHost(CFSwappedFloat32 arg) { - union CFSwap { - Float32 v; - CFSwappedFloat32 sv; - } result; - result.sv = arg; - - result.sv.v = CFSwapInt32(result.sv.v); - - return result.v; -} - -static __inline__ __attribute__((always_inline)) CFSwappedFloat64 CFConvertFloat64HostToSwapped(Float64 arg) { - union CFSwap { - Float64 v; - CFSwappedFloat64 sv; - } result; - result.v = arg; - - result.sv.v = CFSwapInt64(result.sv.v); - - return result.sv; -} - -static __inline__ __attribute__((always_inline)) Float64 CFConvertFloat64SwappedToHost(CFSwappedFloat64 arg) { - union CFSwap { - Float64 v; - CFSwappedFloat64 sv; - } result; - result.sv = arg; - - result.sv.v = CFSwapInt64(result.sv.v); - - return result.v; -} - -static __inline__ __attribute__((always_inline)) CFSwappedFloat32 CFConvertFloatHostToSwapped(float arg) { - union CFSwap { - float v; - CFSwappedFloat32 sv; - } result; - result.v = arg; - - result.sv.v = CFSwapInt32(result.sv.v); - - return result.sv; -} - -static __inline__ __attribute__((always_inline)) float CFConvertFloatSwappedToHost(CFSwappedFloat32 arg) { - union CFSwap { - float v; - CFSwappedFloat32 sv; - } result; - result.sv = arg; - - result.sv.v = CFSwapInt32(result.sv.v); - - return result.v; -} - -static __inline__ __attribute__((always_inline)) CFSwappedFloat64 CFConvertDoubleHostToSwapped(double arg) { - union CFSwap { - double v; - CFSwappedFloat64 sv; - } result; - result.v = arg; - - result.sv.v = CFSwapInt64(result.sv.v); - - return result.sv; -} - -static __inline__ __attribute__((always_inline)) double CFConvertDoubleSwappedToHost(CFSwappedFloat64 arg) { - union CFSwap { - double v; - CFSwappedFloat64 sv; - } result; - result.sv = arg; - - result.sv.v = CFSwapInt64(result.sv.v); - - return result.v; -} - -} - - - - - - - - -extern "C" { -typedef const void * (*CFDictionaryRetainCallBack)(CFAllocatorRef allocator, const void *value); -typedef void (*CFDictionaryReleaseCallBack)(CFAllocatorRef allocator, const void *value); -typedef CFStringRef (*CFDictionaryCopyDescriptionCallBack)(const void *value); -typedef Boolean (*CFDictionaryEqualCallBack)(const void *value1, const void *value2); -typedef CFHashCode (*CFDictionaryHashCallBack)(const void *value); -typedef struct { - CFIndex version; - CFDictionaryRetainCallBack retain; - CFDictionaryReleaseCallBack release; - CFDictionaryCopyDescriptionCallBack copyDescription; - CFDictionaryEqualCallBack equal; - CFDictionaryHashCallBack hash; -} CFDictionaryKeyCallBacks; - - - - - - - -extern -const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks; -extern -const CFDictionaryKeyCallBacks kCFCopyStringDictionaryKeyCallBacks; -typedef struct { - CFIndex version; - CFDictionaryRetainCallBack retain; - CFDictionaryReleaseCallBack release; - CFDictionaryCopyDescriptionCallBack copyDescription; - CFDictionaryEqualCallBack equal; -} CFDictionaryValueCallBacks; - - - - - - - -extern -const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks; -typedef void (*CFDictionaryApplierFunction)(const void *key, const void *value, void *context); - - - - - -typedef const struct __attribute__((objc_bridge(NSDictionary))) __CFDictionary * CFDictionaryRef; - - - - - -typedef struct __attribute__((objc_bridge_mutable(NSMutableDictionary))) __CFDictionary * CFMutableDictionaryRef; - - - - - -extern -CFTypeID CFDictionaryGetTypeID(void); -extern -CFDictionaryRef CFDictionaryCreate(CFAllocatorRef allocator, const void **keys, const void **values, CFIndex numValues, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks); -extern -CFDictionaryRef CFDictionaryCreateCopy(CFAllocatorRef allocator, CFDictionaryRef theDict); -extern -CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks); -extern -CFMutableDictionaryRef CFDictionaryCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFDictionaryRef theDict); -extern -CFIndex CFDictionaryGetCount(CFDictionaryRef theDict); -extern -CFIndex CFDictionaryGetCountOfKey(CFDictionaryRef theDict, const void *key); -extern -CFIndex CFDictionaryGetCountOfValue(CFDictionaryRef theDict, const void *value); -extern -Boolean CFDictionaryContainsKey(CFDictionaryRef theDict, const void *key); -extern -Boolean CFDictionaryContainsValue(CFDictionaryRef theDict, const void *value); -extern -const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key); -extern -Boolean CFDictionaryGetValueIfPresent(CFDictionaryRef theDict, const void *key, const void **value); -extern -void CFDictionaryGetKeysAndValues(CFDictionaryRef theDict, const void **keys, const void **values); -extern -void CFDictionaryApplyFunction(CFDictionaryRef theDict, CFDictionaryApplierFunction applier, void *context); -extern -void CFDictionaryAddValue(CFMutableDictionaryRef theDict, const void *key, const void *value); -extern -void CFDictionarySetValue(CFMutableDictionaryRef theDict, const void *key, const void *value); -extern -void CFDictionaryReplaceValue(CFMutableDictionaryRef theDict, const void *key, const void *value); -extern -void CFDictionaryRemoveValue(CFMutableDictionaryRef theDict, const void *key); -extern -void CFDictionaryRemoveAllValues(CFMutableDictionaryRef theDict); - -} - - -extern "C" { - -typedef const struct __attribute__((objc_bridge(NSLocale))) __CFLocale *CFLocaleRef; - -extern -CFTypeID CFLocaleGetTypeID(void); - -extern -CFLocaleRef CFLocaleGetSystem(void); - - -extern -CFLocaleRef CFLocaleCopyCurrent(void); -extern -CFArrayRef CFLocaleCopyAvailableLocaleIdentifiers(void); - - - -extern -CFArrayRef CFLocaleCopyISOLanguageCodes(void); - - - - -extern -CFArrayRef CFLocaleCopyISOCountryCodes(void); - - - - -extern -CFArrayRef CFLocaleCopyISOCurrencyCodes(void); - - - - -extern -CFArrayRef CFLocaleCopyCommonISOCurrencyCodes(void) __attribute__((availability(macosx,introduced=10_5))); - - - -extern -CFArrayRef CFLocaleCopyPreferredLanguages(void) __attribute__((availability(macosx,introduced=10_5))); - - -extern -CFStringRef CFLocaleCreateCanonicalLanguageIdentifierFromString(CFAllocatorRef allocator, CFStringRef localeIdentifier); - - - -extern -CFStringRef CFLocaleCreateCanonicalLocaleIdentifierFromString(CFAllocatorRef allocator, CFStringRef localeIdentifier); - - - -extern -CFStringRef CFLocaleCreateCanonicalLocaleIdentifierFromScriptManagerCodes(CFAllocatorRef allocator, LangCode lcode, RegionCode rcode); - - -extern -CFStringRef CFLocaleCreateLocaleIdentifierFromWindowsLocaleCode(CFAllocatorRef allocator, uint32_t lcid) __attribute__((availability(macosx,introduced=10_6))); - - -extern -uint32_t CFLocaleGetWindowsLocaleCodeFromLocaleIdentifier(CFStringRef localeIdentifier) __attribute__((availability(macosx,introduced=10_6))); - - -typedef CFIndex CFLocaleLanguageDirection; enum { - kCFLocaleLanguageDirectionUnknown = 0, - kCFLocaleLanguageDirectionLeftToRight = 1, - kCFLocaleLanguageDirectionRightToLeft = 2, - kCFLocaleLanguageDirectionTopToBottom = 3, - kCFLocaleLanguageDirectionBottomToTop = 4 -}; - -extern -CFLocaleLanguageDirection CFLocaleGetLanguageCharacterDirection(CFStringRef isoLangCode) __attribute__((availability(macosx,introduced=10_6))); - -extern -CFLocaleLanguageDirection CFLocaleGetLanguageLineDirection(CFStringRef isoLangCode) __attribute__((availability(macosx,introduced=10_6))); - -extern -CFDictionaryRef CFLocaleCreateComponentsFromLocaleIdentifier(CFAllocatorRef allocator, CFStringRef localeID); -extern -CFStringRef CFLocaleCreateLocaleIdentifierFromComponents(CFAllocatorRef allocator, CFDictionaryRef dictionary); - - - - - - -extern -CFLocaleRef CFLocaleCreate(CFAllocatorRef allocator, CFStringRef localeIdentifier); - - -extern -CFLocaleRef CFLocaleCreateCopy(CFAllocatorRef allocator, CFLocaleRef locale); - - - - -extern -CFStringRef CFLocaleGetIdentifier(CFLocaleRef locale); - - - -extern -CFTypeRef CFLocaleGetValue(CFLocaleRef locale, CFStringRef key); - - - -extern -CFStringRef CFLocaleCopyDisplayNameForPropertyValue(CFLocaleRef displayLocale, CFStringRef key, CFStringRef value); - - - - - -extern const CFStringRef kCFLocaleCurrentLocaleDidChangeNotification __attribute__((availability(macosx,introduced=10_5))); - - - -extern const CFStringRef kCFLocaleIdentifier; -extern const CFStringRef kCFLocaleLanguageCode; -extern const CFStringRef kCFLocaleCountryCode; -extern const CFStringRef kCFLocaleScriptCode; -extern const CFStringRef kCFLocaleVariantCode; - -extern const CFStringRef kCFLocaleExemplarCharacterSet; -extern const CFStringRef kCFLocaleCalendarIdentifier; -extern const CFStringRef kCFLocaleCalendar; -extern const CFStringRef kCFLocaleCollationIdentifier; -extern const CFStringRef kCFLocaleUsesMetricSystem; -extern const CFStringRef kCFLocaleMeasurementSystem; -extern const CFStringRef kCFLocaleDecimalSeparator; -extern const CFStringRef kCFLocaleGroupingSeparator; -extern const CFStringRef kCFLocaleCurrencySymbol; -extern const CFStringRef kCFLocaleCurrencyCode; -extern const CFStringRef kCFLocaleCollatorIdentifier __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFLocaleQuotationBeginDelimiterKey __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFLocaleQuotationEndDelimiterKey __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFLocaleAlternateQuotationBeginDelimiterKey __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFLocaleAlternateQuotationEndDelimiterKey __attribute__((availability(macosx,introduced=10_6))); - - -extern const CFStringRef kCFGregorianCalendar; -extern const CFStringRef kCFBuddhistCalendar; -extern const CFStringRef kCFChineseCalendar; -extern const CFStringRef kCFHebrewCalendar; -extern const CFStringRef kCFIslamicCalendar; -extern const CFStringRef kCFIslamicCivilCalendar; -extern const CFStringRef kCFJapaneseCalendar; -extern const CFStringRef kCFRepublicOfChinaCalendar __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFPersianCalendar __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFIndianCalendar __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFISO8601Calendar __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFIslamicTabularCalendar __attribute__((availability(macosx,introduced=10_10))); -extern const CFStringRef kCFIslamicUmmAlQuraCalendar __attribute__((availability(macosx,introduced=10_10))); - -} -extern "C" { - -typedef double CFTimeInterval; -typedef CFTimeInterval CFAbsoluteTime; - - - -extern -CFAbsoluteTime CFAbsoluteTimeGetCurrent(void); - -extern -const CFTimeInterval kCFAbsoluteTimeIntervalSince1970; -extern -const CFTimeInterval kCFAbsoluteTimeIntervalSince1904; - -typedef const struct __attribute__((objc_bridge(NSDate))) __CFDate * CFDateRef; - -extern -CFTypeID CFDateGetTypeID(void); - -extern -CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at); - -extern -CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate); - -extern -CFTimeInterval CFDateGetTimeIntervalSinceDate(CFDateRef theDate, CFDateRef otherDate); - -extern -CFComparisonResult CFDateCompare(CFDateRef theDate, CFDateRef otherDate, void *context); - - - -typedef const struct __attribute__((objc_bridge(NSTimeZone))) __CFTimeZone * CFTimeZoneRef; -typedef struct { - SInt32 year; - SInt8 month; - SInt8 day; - SInt8 hour; - SInt8 minute; - double second; -} CFGregorianDate __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -typedef struct { - SInt32 years; - SInt32 months; - SInt32 days; - SInt32 hours; - SInt32 minutes; - double seconds; -} CFGregorianUnits __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -typedef CFOptionFlags CFGregorianUnitFlags; enum { - kCFGregorianUnitsYears __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))) = (1UL << 0), - kCFGregorianUnitsMonths __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))) = (1UL << 1), - kCFGregorianUnitsDays __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))) = (1UL << 2), - kCFGregorianUnitsHours __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))) = (1UL << 3), - kCFGregorianUnitsMinutes __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))) = (1UL << 4), - kCFGregorianUnitsSeconds __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))) = (1UL << 5), - kCFGregorianAllUnits __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))) = 0x00FFFFFF -}; - -extern -Boolean CFGregorianDateIsValid(CFGregorianDate gdate, CFOptionFlags unitFlags) __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -extern -CFAbsoluteTime CFGregorianDateGetAbsoluteTime(CFGregorianDate gdate, CFTimeZoneRef tz) __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -extern -CFGregorianDate CFAbsoluteTimeGetGregorianDate(CFAbsoluteTime at, CFTimeZoneRef tz) __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -extern -CFAbsoluteTime CFAbsoluteTimeAddGregorianUnits(CFAbsoluteTime at, CFTimeZoneRef tz, CFGregorianUnits units) __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -extern -CFGregorianUnits CFAbsoluteTimeGetDifferenceAsGregorianUnits(CFAbsoluteTime at1, CFAbsoluteTime at2, CFTimeZoneRef tz, CFOptionFlags unitFlags) __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -extern -SInt32 CFAbsoluteTimeGetDayOfWeek(CFAbsoluteTime at, CFTimeZoneRef tz) __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -extern -SInt32 CFAbsoluteTimeGetDayOfYear(CFAbsoluteTime at, CFTimeZoneRef tz) __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -extern -SInt32 CFAbsoluteTimeGetWeekOfYear(CFAbsoluteTime at, CFTimeZoneRef tz) __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use CFCalendar or NSCalendar API instead"))); - -} -extern "C" { - -typedef const struct __attribute__((objc_bridge(NSData))) __CFData * CFDataRef; -typedef struct __attribute__((objc_bridge_mutable(NSMutableData))) __CFData * CFMutableDataRef; - -extern -CFTypeID CFDataGetTypeID(void); - -extern -CFDataRef CFDataCreate(CFAllocatorRef allocator, const UInt8 *bytes, CFIndex length); - -extern -CFDataRef CFDataCreateWithBytesNoCopy(CFAllocatorRef allocator, const UInt8 *bytes, CFIndex length, CFAllocatorRef bytesDeallocator); - - -extern -CFDataRef CFDataCreateCopy(CFAllocatorRef allocator, CFDataRef theData); - -extern -CFMutableDataRef CFDataCreateMutable(CFAllocatorRef allocator, CFIndex capacity); - -extern -CFMutableDataRef CFDataCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFDataRef theData); - -extern -CFIndex CFDataGetLength(CFDataRef theData); - -extern -const UInt8 *CFDataGetBytePtr(CFDataRef theData); - -extern -UInt8 *CFDataGetMutableBytePtr(CFMutableDataRef theData); - -extern -void CFDataGetBytes(CFDataRef theData, CFRange range, UInt8 *buffer); - -extern -void CFDataSetLength(CFMutableDataRef theData, CFIndex length); - -extern -void CFDataIncreaseLength(CFMutableDataRef theData, CFIndex extraLength); - -extern -void CFDataAppendBytes(CFMutableDataRef theData, const UInt8 *bytes, CFIndex length); - -extern -void CFDataReplaceBytes(CFMutableDataRef theData, CFRange range, const UInt8 *newBytes, CFIndex newLength); - -extern -void CFDataDeleteBytes(CFMutableDataRef theData, CFRange range); - -typedef CFOptionFlags CFDataSearchFlags; enum { - kCFDataSearchBackwards = 1UL << 0, - kCFDataSearchAnchored = 1UL << 1 -} __attribute__((availability(macosx,introduced=10_6))); - -extern -CFRange CFDataFind(CFDataRef theData, CFDataRef dataToFind, CFRange searchRange, CFDataSearchFlags compareOptions) __attribute__((availability(macosx,introduced=10_6))); - -} - - -extern "C" { - - - - - -typedef const struct __attribute__((objc_bridge(NSCharacterSet))) __CFCharacterSet * CFCharacterSetRef; - - - - - -typedef struct __attribute__((objc_bridge_mutable(NSMutableCharacterSet))) __CFCharacterSet * CFMutableCharacterSetRef; - - - - - - -typedef CFIndex CFCharacterSetPredefinedSet; enum { - kCFCharacterSetControl = 1, - kCFCharacterSetWhitespace, - kCFCharacterSetWhitespaceAndNewline, - kCFCharacterSetDecimalDigit, - kCFCharacterSetLetter, - kCFCharacterSetLowercaseLetter, - kCFCharacterSetUppercaseLetter, - kCFCharacterSetNonBase, - kCFCharacterSetDecomposable, - kCFCharacterSetAlphaNumeric, - kCFCharacterSetPunctuation, - kCFCharacterSetCapitalizedLetter = 13, - kCFCharacterSetSymbol = 14, - kCFCharacterSetNewline __attribute__((availability(macosx,introduced=10_5))) = 15, - kCFCharacterSetIllegal = 12 -}; - - - - - -extern -CFTypeID CFCharacterSetGetTypeID(void); -extern -CFCharacterSetRef CFCharacterSetGetPredefined(CFCharacterSetPredefinedSet theSetIdentifier); -extern -CFCharacterSetRef CFCharacterSetCreateWithCharactersInRange(CFAllocatorRef alloc, CFRange theRange); -extern -CFCharacterSetRef CFCharacterSetCreateWithCharactersInString(CFAllocatorRef alloc, CFStringRef theString); -extern -CFCharacterSetRef CFCharacterSetCreateWithBitmapRepresentation(CFAllocatorRef alloc, CFDataRef theData); -extern CFCharacterSetRef CFCharacterSetCreateInvertedSet(CFAllocatorRef alloc, CFCharacterSetRef theSet); -extern Boolean CFCharacterSetIsSupersetOfSet(CFCharacterSetRef theSet, CFCharacterSetRef theOtherset); -extern Boolean CFCharacterSetHasMemberInPlane(CFCharacterSetRef theSet, CFIndex thePlane); -extern -CFMutableCharacterSetRef CFCharacterSetCreateMutable(CFAllocatorRef alloc); -extern -CFCharacterSetRef CFCharacterSetCreateCopy(CFAllocatorRef alloc, CFCharacterSetRef theSet); -extern -CFMutableCharacterSetRef CFCharacterSetCreateMutableCopy(CFAllocatorRef alloc, CFCharacterSetRef theSet); -extern -Boolean CFCharacterSetIsCharacterMember(CFCharacterSetRef theSet, UniChar theChar); -extern Boolean CFCharacterSetIsLongCharacterMember(CFCharacterSetRef theSet, UTF32Char theChar); -extern -CFDataRef CFCharacterSetCreateBitmapRepresentation(CFAllocatorRef alloc, CFCharacterSetRef theSet); -extern -void CFCharacterSetAddCharactersInRange(CFMutableCharacterSetRef theSet, CFRange theRange); -extern -void CFCharacterSetRemoveCharactersInRange(CFMutableCharacterSetRef theSet, CFRange theRange); -extern -void CFCharacterSetAddCharactersInString(CFMutableCharacterSetRef theSet, CFStringRef theString); -extern -void CFCharacterSetRemoveCharactersInString(CFMutableCharacterSetRef theSet, CFStringRef theString); -extern -void CFCharacterSetUnion(CFMutableCharacterSetRef theSet, CFCharacterSetRef theOtherSet); -extern -void CFCharacterSetIntersect(CFMutableCharacterSetRef theSet, CFCharacterSetRef theOtherSet); -extern -void CFCharacterSetInvert(CFMutableCharacterSetRef theSet); - -} - - - - -extern "C" { -typedef UInt32 CFStringEncoding; - - - - - -typedef CFStringEncoding CFStringBuiltInEncodings; enum { - kCFStringEncodingMacRoman = 0, - kCFStringEncodingWindowsLatin1 = 0x0500, - kCFStringEncodingISOLatin1 = 0x0201, - kCFStringEncodingNextStepLatin = 0x0B01, - kCFStringEncodingASCII = 0x0600, - kCFStringEncodingUnicode = 0x0100, - kCFStringEncodingUTF8 = 0x08000100, - kCFStringEncodingNonLossyASCII = 0x0BFF, - - kCFStringEncodingUTF16 = 0x0100, - kCFStringEncodingUTF16BE = 0x10000100, - kCFStringEncodingUTF16LE = 0x14000100, - - kCFStringEncodingUTF32 = 0x0c000100, - kCFStringEncodingUTF32BE = 0x18000100, - kCFStringEncodingUTF32LE = 0x1c000100 -}; - - - -extern -CFTypeID CFStringGetTypeID(void); -extern -CFStringRef CFStringCreateWithPascalString(CFAllocatorRef alloc, ConstStr255Param pStr, CFStringEncoding encoding); - -extern -CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding); - - - -extern -CFStringRef CFStringCreateWithBytes(CFAllocatorRef alloc, const UInt8 *bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean isExternalRepresentation); - -extern -CFStringRef CFStringCreateWithCharacters(CFAllocatorRef alloc, const UniChar *chars, CFIndex numChars); -extern -CFStringRef CFStringCreateWithPascalStringNoCopy(CFAllocatorRef alloc, ConstStr255Param pStr, CFStringEncoding encoding, CFAllocatorRef contentsDeallocator); - -extern -CFStringRef CFStringCreateWithCStringNoCopy(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding, CFAllocatorRef contentsDeallocator); - - - -extern -CFStringRef CFStringCreateWithBytesNoCopy(CFAllocatorRef alloc, const UInt8 *bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean isExternalRepresentation, CFAllocatorRef contentsDeallocator); - -extern -CFStringRef CFStringCreateWithCharactersNoCopy(CFAllocatorRef alloc, const UniChar *chars, CFIndex numChars, CFAllocatorRef contentsDeallocator); - - - -extern -CFStringRef CFStringCreateWithSubstring(CFAllocatorRef alloc, CFStringRef str, CFRange range); - -extern -CFStringRef CFStringCreateCopy(CFAllocatorRef alloc, CFStringRef theString); - - - -extern -CFStringRef CFStringCreateWithFormat(CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef format, ...) __attribute__((format(CFString, 3, 4))); - -extern -CFStringRef CFStringCreateWithFormatAndArguments(CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef format, va_list arguments) __attribute__((format(CFString, 3, 0))); - - - -extern -CFMutableStringRef CFStringCreateMutable(CFAllocatorRef alloc, CFIndex maxLength); - -extern -CFMutableStringRef CFStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFStringRef theString); - - - - - - - -extern -CFMutableStringRef CFStringCreateMutableWithExternalCharactersNoCopy(CFAllocatorRef alloc, UniChar *chars, CFIndex numChars, CFIndex capacity, CFAllocatorRef externalCharactersAllocator); - - - - - -extern -CFIndex CFStringGetLength(CFStringRef theString); - - - - - - -extern -UniChar CFStringGetCharacterAtIndex(CFStringRef theString, CFIndex idx); - -extern -void CFStringGetCharacters(CFStringRef theString, CFRange range, UniChar *buffer); -extern -Boolean CFStringGetPascalString(CFStringRef theString, StringPtr buffer, CFIndex bufferSize, CFStringEncoding encoding); - -extern -Boolean CFStringGetCString(CFStringRef theString, char *buffer, CFIndex bufferSize, CFStringEncoding encoding); - - - - - - -extern -ConstStringPtr CFStringGetPascalStringPtr(CFStringRef theString, CFStringEncoding encoding); - -extern -const char *CFStringGetCStringPtr(CFStringRef theString, CFStringEncoding encoding); - -extern -const UniChar *CFStringGetCharactersPtr(CFStringRef theString); -extern -CFIndex CFStringGetBytes(CFStringRef theString, CFRange range, CFStringEncoding encoding, UInt8 lossByte, Boolean isExternalRepresentation, UInt8 *buffer, CFIndex maxBufLen, CFIndex *usedBufLen); - - - - - - - -extern -CFStringRef CFStringCreateFromExternalRepresentation(CFAllocatorRef alloc, CFDataRef data, CFStringEncoding encoding); - -extern -CFDataRef CFStringCreateExternalRepresentation(CFAllocatorRef alloc, CFStringRef theString, CFStringEncoding encoding, UInt8 lossByte); - - - -extern -CFStringEncoding CFStringGetSmallestEncoding(CFStringRef theString); - -extern -CFStringEncoding CFStringGetFastestEncoding(CFStringRef theString); - - - -extern -CFStringEncoding CFStringGetSystemEncoding(void); - -extern -CFIndex CFStringGetMaximumSizeForEncoding(CFIndex length, CFStringEncoding encoding); - - - - - - -extern -Boolean CFStringGetFileSystemRepresentation(CFStringRef string, char *buffer, CFIndex maxBufLen); - - - -extern -CFIndex CFStringGetMaximumSizeOfFileSystemRepresentation(CFStringRef string); - - - -extern -CFStringRef CFStringCreateWithFileSystemRepresentation(CFAllocatorRef alloc, const char *buffer); - - - - - - -typedef CFOptionFlags CFStringCompareFlags; enum { - kCFCompareCaseInsensitive = 1, - kCFCompareBackwards = 4, - kCFCompareAnchored = 8, - kCFCompareNonliteral = 16, - kCFCompareLocalized = 32, - kCFCompareNumerically = 64, - kCFCompareDiacriticInsensitive __attribute__((availability(macosx,introduced=10_5))) = 128, - kCFCompareWidthInsensitive __attribute__((availability(macosx,introduced=10_5))) = 256, - kCFCompareForcedOrdering __attribute__((availability(macosx,introduced=10_5))) = 512 -}; - - - - - - - -extern -CFComparisonResult CFStringCompareWithOptionsAndLocale(CFStringRef theString1, CFStringRef theString2, CFRange rangeToCompare, CFStringCompareFlags compareOptions, CFLocaleRef locale) __attribute__((availability(macosx,introduced=10_5))); - - - -extern -CFComparisonResult CFStringCompareWithOptions(CFStringRef theString1, CFStringRef theString2, CFRange rangeToCompare, CFStringCompareFlags compareOptions); - - - - - -extern -CFComparisonResult CFStringCompare(CFStringRef theString1, CFStringRef theString2, CFStringCompareFlags compareOptions); - - - - - - - -extern -Boolean CFStringFindWithOptionsAndLocale(CFStringRef theString, CFStringRef stringToFind, CFRange rangeToSearch, CFStringCompareFlags searchOptions, CFLocaleRef locale, CFRange *result) __attribute__((availability(macosx,introduced=10_5))); - - - -extern -Boolean CFStringFindWithOptions(CFStringRef theString, CFStringRef stringToFind, CFRange rangeToSearch, CFStringCompareFlags searchOptions, CFRange *result); -extern -CFArrayRef CFStringCreateArrayWithFindResults(CFAllocatorRef alloc, CFStringRef theString, CFStringRef stringToFind, CFRange rangeToSearch, CFStringCompareFlags compareOptions); - - - -extern -CFRange CFStringFind(CFStringRef theString, CFStringRef stringToFind, CFStringCompareFlags compareOptions); - -extern -Boolean CFStringHasPrefix(CFStringRef theString, CFStringRef prefix); - -extern -Boolean CFStringHasSuffix(CFStringRef theString, CFStringRef suffix); -extern CFRange CFStringGetRangeOfComposedCharactersAtIndex(CFStringRef theString, CFIndex theIndex); -extern Boolean CFStringFindCharacterFromSet(CFStringRef theString, CFCharacterSetRef theSet, CFRange rangeToSearch, CFStringCompareFlags searchOptions, CFRange *result); -extern -void CFStringGetLineBounds(CFStringRef theString, CFRange range, CFIndex *lineBeginIndex, CFIndex *lineEndIndex, CFIndex *contentsEndIndex); - - - -extern -void CFStringGetParagraphBounds(CFStringRef string, CFRange range, CFIndex *parBeginIndex, CFIndex *parEndIndex, CFIndex *contentsEndIndex) __attribute__((availability(macosx,introduced=10_5))); -extern -CFIndex CFStringGetHyphenationLocationBeforeIndex(CFStringRef string, CFIndex location, CFRange limitRange, CFOptionFlags options, CFLocaleRef locale, UTF32Char *character) __attribute__((availability(macosx,introduced=10_7))); - -extern -Boolean CFStringIsHyphenationAvailableForLocale(CFLocaleRef locale) __attribute__((availability(macosx,introduced=10_7))); - - - -extern -CFStringRef CFStringCreateByCombiningStrings(CFAllocatorRef alloc, CFArrayRef theArray, CFStringRef separatorString); - -extern -CFArrayRef CFStringCreateArrayBySeparatingStrings(CFAllocatorRef alloc, CFStringRef theString, CFStringRef separatorString); - - - - -extern -SInt32 CFStringGetIntValue(CFStringRef str); - -extern -double CFStringGetDoubleValue(CFStringRef str); -extern -void CFStringAppend(CFMutableStringRef theString, CFStringRef appendedString); - -extern -void CFStringAppendCharacters(CFMutableStringRef theString, const UniChar *chars, CFIndex numChars); - -extern -void CFStringAppendPascalString(CFMutableStringRef theString, ConstStr255Param pStr, CFStringEncoding encoding); - -extern -void CFStringAppendCString(CFMutableStringRef theString, const char *cStr, CFStringEncoding encoding); - -extern -void CFStringAppendFormat(CFMutableStringRef theString, CFDictionaryRef formatOptions, CFStringRef format, ...) __attribute__((format(CFString, 3, 4))); - -extern -void CFStringAppendFormatAndArguments(CFMutableStringRef theString, CFDictionaryRef formatOptions, CFStringRef format, va_list arguments) __attribute__((format(CFString, 3, 0))); - -extern -void CFStringInsert(CFMutableStringRef str, CFIndex idx, CFStringRef insertedStr); - -extern -void CFStringDelete(CFMutableStringRef theString, CFRange range); - -extern -void CFStringReplace(CFMutableStringRef theString, CFRange range, CFStringRef replacement); - -extern -void CFStringReplaceAll(CFMutableStringRef theString, CFStringRef replacement); -extern -CFIndex CFStringFindAndReplace(CFMutableStringRef theString, CFStringRef stringToFind, CFStringRef replacementString, CFRange rangeToSearch, CFStringCompareFlags compareOptions); -extern -void CFStringSetExternalCharactersNoCopy(CFMutableStringRef theString, UniChar *chars, CFIndex length, CFIndex capacity); -extern -void CFStringPad(CFMutableStringRef theString, CFStringRef padString, CFIndex length, CFIndex indexIntoPad); - -extern -void CFStringTrim(CFMutableStringRef theString, CFStringRef trimString); - -extern -void CFStringTrimWhitespace(CFMutableStringRef theString); - -extern -void CFStringLowercase(CFMutableStringRef theString, CFLocaleRef locale); - -extern -void CFStringUppercase(CFMutableStringRef theString, CFLocaleRef locale); - -extern -void CFStringCapitalize(CFMutableStringRef theString, CFLocaleRef locale); - - - - - - - -typedef CFIndex CFStringNormalizationForm; enum { - kCFStringNormalizationFormD = 0, - kCFStringNormalizationFormKD, - kCFStringNormalizationFormC, - kCFStringNormalizationFormKC -}; -extern void CFStringNormalize(CFMutableStringRef theString, CFStringNormalizationForm theForm); -extern -void CFStringFold(CFMutableStringRef theString, CFStringCompareFlags theFlags, CFLocaleRef theLocale) __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern -Boolean CFStringTransform(CFMutableStringRef string, CFRange *range, CFStringRef transform, Boolean reverse); - - - -extern const CFStringRef kCFStringTransformStripCombiningMarks; -extern const CFStringRef kCFStringTransformToLatin; -extern const CFStringRef kCFStringTransformFullwidthHalfwidth; -extern const CFStringRef kCFStringTransformLatinKatakana; -extern const CFStringRef kCFStringTransformLatinHiragana; -extern const CFStringRef kCFStringTransformHiraganaKatakana; -extern const CFStringRef kCFStringTransformMandarinLatin; -extern const CFStringRef kCFStringTransformLatinHangul; -extern const CFStringRef kCFStringTransformLatinArabic; -extern const CFStringRef kCFStringTransformLatinHebrew; -extern const CFStringRef kCFStringTransformLatinThai; -extern const CFStringRef kCFStringTransformLatinCyrillic; -extern const CFStringRef kCFStringTransformLatinGreek; -extern const CFStringRef kCFStringTransformToXMLHex; -extern const CFStringRef kCFStringTransformToUnicodeName; -extern const CFStringRef kCFStringTransformStripDiacritics __attribute__((availability(macosx,introduced=10_5))); - - - - - - -extern -Boolean CFStringIsEncodingAvailable(CFStringEncoding encoding); - - - -extern -const CFStringEncoding *CFStringGetListOfAvailableEncodings(void); - - - -extern -CFStringRef CFStringGetNameOfEncoding(CFStringEncoding encoding); - - - -extern -unsigned long CFStringConvertEncodingToNSStringEncoding(CFStringEncoding encoding); - -extern -CFStringEncoding CFStringConvertNSStringEncodingToEncoding(unsigned long encoding); - - - -extern -UInt32 CFStringConvertEncodingToWindowsCodepage(CFStringEncoding encoding); - -extern -CFStringEncoding CFStringConvertWindowsCodepageToEncoding(UInt32 codepage); - - - -extern -CFStringEncoding CFStringConvertIANACharSetNameToEncoding(CFStringRef theString); - -extern -CFStringRef CFStringConvertEncodingToIANACharSetName(CFStringEncoding encoding); - - - - - -extern -CFStringEncoding CFStringGetMostCompatibleMacStringEncoding(CFStringEncoding encoding); -typedef struct { - UniChar buffer[64]; - CFStringRef theString; - const UniChar *directUniCharBuffer; - const char *directCStringBuffer; - CFRange rangeToBuffer; - CFIndex bufferedRangeStart; - CFIndex bufferedRangeEnd; -} CFStringInlineBuffer; - - -static __inline__ __attribute__((always_inline)) void CFStringInitInlineBuffer(CFStringRef str, CFStringInlineBuffer *buf, CFRange range) { - buf->theString = str; - buf->rangeToBuffer = range; - buf->directCStringBuffer = (buf->directUniCharBuffer = CFStringGetCharactersPtr(str)) ? __null : CFStringGetCStringPtr(str, kCFStringEncodingASCII); - buf->bufferedRangeStart = buf->bufferedRangeEnd = 0; -} - -static __inline__ __attribute__((always_inline)) UniChar CFStringGetCharacterFromInlineBuffer(CFStringInlineBuffer *buf, CFIndex idx) { - if (idx < 0 || idx >= buf->rangeToBuffer.length) return 0; - if (buf->directUniCharBuffer) return buf->directUniCharBuffer[idx + buf->rangeToBuffer.location]; - if (buf->directCStringBuffer) return (UniChar)(buf->directCStringBuffer[idx + buf->rangeToBuffer.location]); - if (idx >= buf->bufferedRangeEnd || idx < buf->bufferedRangeStart) { - if ((buf->bufferedRangeStart = idx - 4) < 0) buf->bufferedRangeStart = 0; - buf->bufferedRangeEnd = buf->bufferedRangeStart + 64; - if (buf->bufferedRangeEnd > buf->rangeToBuffer.length) buf->bufferedRangeEnd = buf->rangeToBuffer.length; - CFStringGetCharacters(buf->theString, CFRangeMake(buf->rangeToBuffer.location + buf->bufferedRangeStart, buf->bufferedRangeEnd - buf->bufferedRangeStart), buf->buffer); - } - return buf->buffer[idx - buf->bufferedRangeStart]; -} -static __inline__ __attribute__((always_inline)) Boolean CFStringIsSurrogateHighCharacter(UniChar character) { - return ((character >= 0xD800UL) && (character <= 0xDBFFUL) ? true : false); -} - -static __inline__ __attribute__((always_inline)) Boolean CFStringIsSurrogateLowCharacter(UniChar character) { - return ((character >= 0xDC00UL) && (character <= 0xDFFFUL) ? true : false); -} - -static __inline__ __attribute__((always_inline)) UTF32Char CFStringGetLongCharacterForSurrogatePair(UniChar surrogateHigh, UniChar surrogateLow) { - return (UTF32Char)(((surrogateHigh - 0xD800UL) << 10) + (surrogateLow - 0xDC00UL) + 0x0010000UL); -} - - -static __inline__ __attribute__((always_inline)) Boolean CFStringGetSurrogatePairForLongCharacter(UTF32Char character, UniChar *surrogates) { - if ((character > 0xFFFFUL) && (character < 0x110000UL)) { - character -= 0x10000; - if (__null != surrogates) { - surrogates[0] = (UniChar)((character >> 10) + 0xD800UL); - surrogates[1] = (UniChar)((character & 0x3FF) + 0xDC00UL); - } - return true; - } else { - if (__null != surrogates) *surrogates = (UniChar)character; - return false; - } -} - - - - - - - -extern -void CFShow(CFTypeRef obj); - -extern -void CFShowStr(CFStringRef str); - - -extern -CFStringRef __CFStringMakeConstantString(const char *cStr) __attribute__((format_arg(1))); - -} - - -extern "C" { - -extern -CFTypeID CFTimeZoneGetTypeID(void); - -extern -CFTimeZoneRef CFTimeZoneCopySystem(void); - -extern -void CFTimeZoneResetSystem(void); - -extern -CFTimeZoneRef CFTimeZoneCopyDefault(void); - -extern -void CFTimeZoneSetDefault(CFTimeZoneRef tz); - -extern -CFArrayRef CFTimeZoneCopyKnownNames(void); - -extern -CFDictionaryRef CFTimeZoneCopyAbbreviationDictionary(void); - -extern -void CFTimeZoneSetAbbreviationDictionary(CFDictionaryRef dict); - -extern -CFTimeZoneRef CFTimeZoneCreate(CFAllocatorRef allocator, CFStringRef name, CFDataRef data); - -extern -CFTimeZoneRef CFTimeZoneCreateWithTimeIntervalFromGMT(CFAllocatorRef allocator, CFTimeInterval ti); - -extern -CFTimeZoneRef CFTimeZoneCreateWithName(CFAllocatorRef allocator, CFStringRef name, Boolean tryAbbrev); - -extern -CFStringRef CFTimeZoneGetName(CFTimeZoneRef tz); - -extern -CFDataRef CFTimeZoneGetData(CFTimeZoneRef tz); - -extern -CFTimeInterval CFTimeZoneGetSecondsFromGMT(CFTimeZoneRef tz, CFAbsoluteTime at); - -extern -CFStringRef CFTimeZoneCopyAbbreviation(CFTimeZoneRef tz, CFAbsoluteTime at); - -extern -Boolean CFTimeZoneIsDaylightSavingTime(CFTimeZoneRef tz, CFAbsoluteTime at); - -extern -CFTimeInterval CFTimeZoneGetDaylightSavingTimeOffset(CFTimeZoneRef tz, CFAbsoluteTime at) __attribute__((availability(macosx,introduced=10_5))); - -extern -CFAbsoluteTime CFTimeZoneGetNextDaylightSavingTimeTransition(CFTimeZoneRef tz, CFAbsoluteTime at) __attribute__((availability(macosx,introduced=10_5))); - -typedef CFIndex CFTimeZoneNameStyle; enum { - kCFTimeZoneNameStyleStandard, - kCFTimeZoneNameStyleShortStandard, - kCFTimeZoneNameStyleDaylightSaving, - kCFTimeZoneNameStyleShortDaylightSaving, - kCFTimeZoneNameStyleGeneric, - kCFTimeZoneNameStyleShortGeneric -} __attribute__((availability(macosx,introduced=10_5))); - -extern -CFStringRef CFTimeZoneCopyLocalizedName(CFTimeZoneRef tz, CFTimeZoneNameStyle style, CFLocaleRef locale) __attribute__((availability(macosx,introduced=10_5))); - -extern -const CFStringRef kCFTimeZoneSystemTimeZoneDidChangeNotification __attribute__((availability(macosx,introduced=10_5))); - -} - - -extern "C" { - -typedef struct __attribute__((objc_bridge_mutable(NSCalendar))) __CFCalendar * CFCalendarRef; - -extern -CFTypeID CFCalendarGetTypeID(void); - -extern -CFCalendarRef CFCalendarCopyCurrent(void); - -extern -CFCalendarRef CFCalendarCreateWithIdentifier(CFAllocatorRef allocator, CFStringRef identifier); - - - -extern -CFStringRef CFCalendarGetIdentifier(CFCalendarRef calendar); - - -extern -CFLocaleRef CFCalendarCopyLocale(CFCalendarRef calendar); - -extern -void CFCalendarSetLocale(CFCalendarRef calendar, CFLocaleRef locale); - -extern -CFTimeZoneRef CFCalendarCopyTimeZone(CFCalendarRef calendar); - -extern -void CFCalendarSetTimeZone(CFCalendarRef calendar, CFTimeZoneRef tz); - -extern -CFIndex CFCalendarGetFirstWeekday(CFCalendarRef calendar); - -extern -void CFCalendarSetFirstWeekday(CFCalendarRef calendar, CFIndex wkdy); - -extern -CFIndex CFCalendarGetMinimumDaysInFirstWeek(CFCalendarRef calendar); - -extern -void CFCalendarSetMinimumDaysInFirstWeek(CFCalendarRef calendar, CFIndex mwd); - - -typedef CFOptionFlags CFCalendarUnit; enum { - kCFCalendarUnitEra = (1UL << 1), - kCFCalendarUnitYear = (1UL << 2), - kCFCalendarUnitMonth = (1UL << 3), - kCFCalendarUnitDay = (1UL << 4), - kCFCalendarUnitHour = (1UL << 5), - kCFCalendarUnitMinute = (1UL << 6), - kCFCalendarUnitSecond = (1UL << 7), - kCFCalendarUnitWeek __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))) = (1UL << 8), - kCFCalendarUnitWeekday = (1UL << 9), - kCFCalendarUnitWeekdayOrdinal = (1UL << 10), - kCFCalendarUnitQuarter __attribute__((availability(macosx,introduced=10_6))) = (1UL << 11), - kCFCalendarUnitWeekOfMonth __attribute__((availability(macosx,introduced=10_7))) = (1UL << 12), - kCFCalendarUnitWeekOfYear __attribute__((availability(macosx,introduced=10_7))) = (1UL << 13), - kCFCalendarUnitYearForWeekOfYear __attribute__((availability(macosx,introduced=10_7))) = (1UL << 14), -}; - -extern -CFRange CFCalendarGetMinimumRangeOfUnit(CFCalendarRef calendar, CFCalendarUnit unit); - -extern -CFRange CFCalendarGetMaximumRangeOfUnit(CFCalendarRef calendar, CFCalendarUnit unit); - -extern -CFRange CFCalendarGetRangeOfUnit(CFCalendarRef calendar, CFCalendarUnit smallerUnit, CFCalendarUnit biggerUnit, CFAbsoluteTime at); - -extern -CFIndex CFCalendarGetOrdinalityOfUnit(CFCalendarRef calendar, CFCalendarUnit smallerUnit, CFCalendarUnit biggerUnit, CFAbsoluteTime at); - -extern -Boolean CFCalendarGetTimeRangeOfUnit(CFCalendarRef calendar, CFCalendarUnit unit, CFAbsoluteTime at, CFAbsoluteTime *startp, CFTimeInterval *tip) __attribute__((availability(macosx,introduced=10_5))); - -extern -Boolean CFCalendarComposeAbsoluteTime(CFCalendarRef calendar, CFAbsoluteTime *at, const char *componentDesc, ...); - -extern -Boolean CFCalendarDecomposeAbsoluteTime(CFCalendarRef calendar, CFAbsoluteTime at, const char *componentDesc, ...); - - -enum { - kCFCalendarComponentsWrap = (1UL << 0) -}; - -extern -Boolean CFCalendarAddComponents(CFCalendarRef calendar, CFAbsoluteTime *at, CFOptionFlags options, const char *componentDesc, ...); - -extern -Boolean CFCalendarGetComponentDifference(CFCalendarRef calendar, CFAbsoluteTime startingAT, CFAbsoluteTime resultAT, CFOptionFlags options, const char *componentDesc, ...); - - -} - - - -extern "C" { - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFDateFormatter *CFDateFormatterRef; - - - -extern -CFStringRef CFDateFormatterCreateDateFormatFromTemplate(CFAllocatorRef allocator, CFStringRef tmplate, CFOptionFlags options, CFLocaleRef locale) __attribute__((availability(macosx,introduced=10_6))); - - -extern -CFTypeID CFDateFormatterGetTypeID(void); - -typedef CFIndex CFDateFormatterStyle; enum { - kCFDateFormatterNoStyle = 0, - kCFDateFormatterShortStyle = 1, - kCFDateFormatterMediumStyle = 2, - kCFDateFormatterLongStyle = 3, - kCFDateFormatterFullStyle = 4 -}; -extern -CFDateFormatterRef CFDateFormatterCreate(CFAllocatorRef allocator, CFLocaleRef locale, CFDateFormatterStyle dateStyle, CFDateFormatterStyle timeStyle); - - - -extern -CFLocaleRef CFDateFormatterGetLocale(CFDateFormatterRef formatter); - -extern -CFDateFormatterStyle CFDateFormatterGetDateStyle(CFDateFormatterRef formatter); - -extern -CFDateFormatterStyle CFDateFormatterGetTimeStyle(CFDateFormatterRef formatter); - - -extern -CFStringRef CFDateFormatterGetFormat(CFDateFormatterRef formatter); - -extern -void CFDateFormatterSetFormat(CFDateFormatterRef formatter, CFStringRef formatString); - - - - - - - -extern -CFStringRef CFDateFormatterCreateStringWithDate(CFAllocatorRef allocator, CFDateFormatterRef formatter, CFDateRef date); - -extern -CFStringRef CFDateFormatterCreateStringWithAbsoluteTime(CFAllocatorRef allocator, CFDateFormatterRef formatter, CFAbsoluteTime at); - - - - -extern -CFDateRef CFDateFormatterCreateDateFromString(CFAllocatorRef allocator, CFDateFormatterRef formatter, CFStringRef string, CFRange *rangep); - -extern -Boolean CFDateFormatterGetAbsoluteTimeFromString(CFDateFormatterRef formatter, CFStringRef string, CFRange *rangep, CFAbsoluteTime *atp); -extern -void CFDateFormatterSetProperty(CFDateFormatterRef formatter, CFStringRef key, CFTypeRef value); - -extern -CFTypeRef CFDateFormatterCopyProperty(CFDateFormatterRef formatter, CFStringRef key); - - - -extern const CFStringRef kCFDateFormatterIsLenient; -extern const CFStringRef kCFDateFormatterTimeZone; -extern const CFStringRef kCFDateFormatterCalendarName; -extern const CFStringRef kCFDateFormatterDefaultFormat; -extern const CFStringRef kCFDateFormatterTwoDigitStartDate; -extern const CFStringRef kCFDateFormatterDefaultDate; -extern const CFStringRef kCFDateFormatterCalendar; -extern const CFStringRef kCFDateFormatterEraSymbols; -extern const CFStringRef kCFDateFormatterMonthSymbols; -extern const CFStringRef kCFDateFormatterShortMonthSymbols; -extern const CFStringRef kCFDateFormatterWeekdaySymbols; -extern const CFStringRef kCFDateFormatterShortWeekdaySymbols; -extern const CFStringRef kCFDateFormatterAMSymbol; -extern const CFStringRef kCFDateFormatterPMSymbol; -extern const CFStringRef kCFDateFormatterLongEraSymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterVeryShortMonthSymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterStandaloneMonthSymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterShortStandaloneMonthSymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterVeryShortStandaloneMonthSymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterVeryShortWeekdaySymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterStandaloneWeekdaySymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterShortStandaloneWeekdaySymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterVeryShortStandaloneWeekdaySymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterQuarterSymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterShortQuarterSymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterStandaloneQuarterSymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterShortStandaloneQuarterSymbols __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterGregorianStartDate __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDateFormatterDoesRelativeDateFormattingKey __attribute__((availability(macosx,introduced=10_6))); -} - -extern "C" { - - - - - -typedef struct __attribute__((objc_bridge(NSError))) __CFError * CFErrorRef; - - - - - -extern -CFTypeID CFErrorGetTypeID(void) __attribute__((availability(macosx,introduced=10_5))); - - - -extern const CFStringRef kCFErrorDomainPOSIX __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFErrorDomainOSStatus __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFErrorDomainMach __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFErrorDomainCocoa __attribute__((availability(macosx,introduced=10_5))); - - -extern const CFStringRef kCFErrorLocalizedDescriptionKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFErrorLocalizedFailureReasonKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFErrorLocalizedRecoverySuggestionKey __attribute__((availability(macosx,introduced=10_5))); - - -extern const CFStringRef kCFErrorDescriptionKey __attribute__((availability(macosx,introduced=10_5))); - - -extern const CFStringRef kCFErrorUnderlyingErrorKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFErrorURLKey __attribute__((availability(macosx,introduced=10_7))); -extern const CFStringRef kCFErrorFilePathKey __attribute__((availability(macosx,introduced=10_7))); -extern -CFErrorRef CFErrorCreate(CFAllocatorRef allocator, CFStringRef domain, CFIndex code, CFDictionaryRef userInfo) __attribute__((availability(macosx,introduced=10_5))); -extern -CFErrorRef CFErrorCreateWithUserInfoKeysAndValues(CFAllocatorRef allocator, CFStringRef domain, CFIndex code, const void *const *userInfoKeys, const void *const *userInfoValues, CFIndex numUserInfoValues) __attribute__((availability(macosx,introduced=10_5))); - - - - - - - -extern -CFStringRef CFErrorGetDomain(CFErrorRef err) __attribute__((availability(macosx,introduced=10_5))); - - - - - - - -extern -CFIndex CFErrorGetCode(CFErrorRef err) __attribute__((availability(macosx,introduced=10_5))); -extern -CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err) __attribute__((availability(macosx,introduced=10_5))); -extern -CFStringRef CFErrorCopyDescription(CFErrorRef err) __attribute__((availability(macosx,introduced=10_5))); -extern -CFStringRef CFErrorCopyFailureReason(CFErrorRef err) __attribute__((availability(macosx,introduced=10_5))); -extern -CFStringRef CFErrorCopyRecoverySuggestion(CFErrorRef err) __attribute__((availability(macosx,introduced=10_5))); - - - -} - -extern "C" { - -typedef const struct __attribute__((objc_bridge(NSNumber))) __CFBoolean * CFBooleanRef; - -extern -const CFBooleanRef kCFBooleanTrue; -extern -const CFBooleanRef kCFBooleanFalse; - -extern -CFTypeID CFBooleanGetTypeID(void); - -extern -Boolean CFBooleanGetValue(CFBooleanRef boolean); - -typedef CFIndex CFNumberType; enum { - - kCFNumberSInt8Type = 1, - kCFNumberSInt16Type = 2, - kCFNumberSInt32Type = 3, - kCFNumberSInt64Type = 4, - kCFNumberFloat32Type = 5, - kCFNumberFloat64Type = 6, - - kCFNumberCharType = 7, - kCFNumberShortType = 8, - kCFNumberIntType = 9, - kCFNumberLongType = 10, - kCFNumberLongLongType = 11, - kCFNumberFloatType = 12, - kCFNumberDoubleType = 13, - - kCFNumberCFIndexType = 14, - kCFNumberNSIntegerType __attribute__((availability(macosx,introduced=10_5))) = 15, - kCFNumberCGFloatType __attribute__((availability(macosx,introduced=10_5))) = 16, - kCFNumberMaxType = 16 -}; - -typedef const struct __attribute__((objc_bridge(NSNumber))) __CFNumber * CFNumberRef; - -extern -const CFNumberRef kCFNumberPositiveInfinity; -extern -const CFNumberRef kCFNumberNegativeInfinity; -extern -const CFNumberRef kCFNumberNaN; - -extern -CFTypeID CFNumberGetTypeID(void); -extern -CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr); - - - - - -extern -CFNumberType CFNumberGetType(CFNumberRef number); - - - - -extern -CFIndex CFNumberGetByteSize(CFNumberRef number); - - - - - -extern -Boolean CFNumberIsFloatType(CFNumberRef number); -extern -Boolean CFNumberGetValue(CFNumberRef number, CFNumberType theType, void *valuePtr); -extern -CFComparisonResult CFNumberCompare(CFNumberRef number, CFNumberRef otherNumber, void *context); - -} -extern "C" { - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFNumberFormatter *CFNumberFormatterRef; - - - -extern -CFTypeID CFNumberFormatterGetTypeID(void); - -typedef CFIndex CFNumberFormatterStyle; enum { - kCFNumberFormatterNoStyle = 0, - kCFNumberFormatterDecimalStyle = 1, - kCFNumberFormatterCurrencyStyle = 2, - kCFNumberFormatterPercentStyle = 3, - kCFNumberFormatterScientificStyle = 4, - kCFNumberFormatterSpellOutStyle = 5, - kCFNumberFormatterOrdinalStyle __attribute__((availability(macosx,introduced=10_11))) = 6, - kCFNumberFormatterCurrencyISOCodeStyle __attribute__((availability(macosx,introduced=10_11))) = 8, - kCFNumberFormatterCurrencyPluralStyle __attribute__((availability(macosx,introduced=10_11))) = 9, - kCFNumberFormatterCurrencyAccountingStyle __attribute__((availability(macosx,introduced=10_11))) = 10, -}; - - -extern -CFNumberFormatterRef CFNumberFormatterCreate(CFAllocatorRef allocator, CFLocaleRef locale, CFNumberFormatterStyle style); - - - -extern -CFLocaleRef CFNumberFormatterGetLocale(CFNumberFormatterRef formatter); - -extern -CFNumberFormatterStyle CFNumberFormatterGetStyle(CFNumberFormatterRef formatter); - - -extern -CFStringRef CFNumberFormatterGetFormat(CFNumberFormatterRef formatter); - -extern -void CFNumberFormatterSetFormat(CFNumberFormatterRef formatter, CFStringRef formatString); -extern -CFStringRef CFNumberFormatterCreateStringWithNumber(CFAllocatorRef allocator, CFNumberFormatterRef formatter, CFNumberRef number); - -extern -CFStringRef CFNumberFormatterCreateStringWithValue(CFAllocatorRef allocator, CFNumberFormatterRef formatter, CFNumberType numberType, const void *valuePtr); - - - - -typedef CFOptionFlags CFNumberFormatterOptionFlags; enum { - kCFNumberFormatterParseIntegersOnly = 1 -}; - -extern -CFNumberRef CFNumberFormatterCreateNumberFromString(CFAllocatorRef allocator, CFNumberFormatterRef formatter, CFStringRef string, CFRange *rangep, CFOptionFlags options); - -extern -Boolean CFNumberFormatterGetValueFromString(CFNumberFormatterRef formatter, CFStringRef string, CFRange *rangep, CFNumberType numberType, void *valuePtr); -extern -void CFNumberFormatterSetProperty(CFNumberFormatterRef formatter, CFStringRef key, CFTypeRef value); - -extern -CFTypeRef CFNumberFormatterCopyProperty(CFNumberFormatterRef formatter, CFStringRef key); - - - -extern const CFStringRef kCFNumberFormatterCurrencyCode; -extern const CFStringRef kCFNumberFormatterDecimalSeparator; -extern const CFStringRef kCFNumberFormatterCurrencyDecimalSeparator; -extern const CFStringRef kCFNumberFormatterAlwaysShowDecimalSeparator; -extern const CFStringRef kCFNumberFormatterGroupingSeparator; -extern const CFStringRef kCFNumberFormatterUseGroupingSeparator; -extern const CFStringRef kCFNumberFormatterPercentSymbol; -extern const CFStringRef kCFNumberFormatterZeroSymbol; -extern const CFStringRef kCFNumberFormatterNaNSymbol; -extern const CFStringRef kCFNumberFormatterInfinitySymbol; -extern const CFStringRef kCFNumberFormatterMinusSign; -extern const CFStringRef kCFNumberFormatterPlusSign; -extern const CFStringRef kCFNumberFormatterCurrencySymbol; -extern const CFStringRef kCFNumberFormatterExponentSymbol; -extern const CFStringRef kCFNumberFormatterMinIntegerDigits; -extern const CFStringRef kCFNumberFormatterMaxIntegerDigits; -extern const CFStringRef kCFNumberFormatterMinFractionDigits; -extern const CFStringRef kCFNumberFormatterMaxFractionDigits; -extern const CFStringRef kCFNumberFormatterGroupingSize; -extern const CFStringRef kCFNumberFormatterSecondaryGroupingSize; -extern const CFStringRef kCFNumberFormatterRoundingMode; -extern const CFStringRef kCFNumberFormatterRoundingIncrement; -extern const CFStringRef kCFNumberFormatterFormatWidth; -extern const CFStringRef kCFNumberFormatterPaddingPosition; -extern const CFStringRef kCFNumberFormatterPaddingCharacter; -extern const CFStringRef kCFNumberFormatterDefaultFormat; -extern const CFStringRef kCFNumberFormatterMultiplier; -extern const CFStringRef kCFNumberFormatterPositivePrefix; -extern const CFStringRef kCFNumberFormatterPositiveSuffix; -extern const CFStringRef kCFNumberFormatterNegativePrefix; -extern const CFStringRef kCFNumberFormatterNegativeSuffix; -extern const CFStringRef kCFNumberFormatterPerMillSymbol; -extern const CFStringRef kCFNumberFormatterInternationalCurrencySymbol; -extern const CFStringRef kCFNumberFormatterCurrencyGroupingSeparator __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFNumberFormatterIsLenient __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFNumberFormatterUseSignificantDigits __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFNumberFormatterMinSignificantDigits __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFNumberFormatterMaxSignificantDigits __attribute__((availability(macosx,introduced=10_5))); - -typedef CFIndex CFNumberFormatterRoundingMode; enum { - kCFNumberFormatterRoundCeiling = 0, - kCFNumberFormatterRoundFloor = 1, - kCFNumberFormatterRoundDown = 2, - kCFNumberFormatterRoundUp = 3, - kCFNumberFormatterRoundHalfEven = 4, - kCFNumberFormatterRoundHalfDown = 5, - kCFNumberFormatterRoundHalfUp = 6 -}; - -typedef CFIndex CFNumberFormatterPadPosition; enum { - kCFNumberFormatterPadBeforePrefix = 0, - kCFNumberFormatterPadAfterPrefix = 1, - kCFNumberFormatterPadBeforeSuffix = 2, - kCFNumberFormatterPadAfterSuffix = 3 -}; - - -extern -Boolean CFNumberFormatterGetDecimalInfoForCurrencyCode(CFStringRef currencyCode, int32_t *defaultFractionDigits, double *roundingIncrement); - - - - - - -} -extern "C" { - -extern -const CFStringRef kCFPreferencesAnyApplication; -extern -const CFStringRef kCFPreferencesCurrentApplication; -extern -const CFStringRef kCFPreferencesAnyHost; -extern -const CFStringRef kCFPreferencesCurrentHost; -extern -const CFStringRef kCFPreferencesAnyUser; -extern -const CFStringRef kCFPreferencesCurrentUser; -extern -CFPropertyListRef CFPreferencesCopyAppValue(CFStringRef key, CFStringRef applicationID); - - - - -extern -Boolean CFPreferencesGetAppBooleanValue(CFStringRef key, CFStringRef applicationID, Boolean *keyExistsAndHasValidFormat); - - - - -extern -CFIndex CFPreferencesGetAppIntegerValue(CFStringRef key, CFStringRef applicationID, Boolean *keyExistsAndHasValidFormat); - - - - -extern -void CFPreferencesSetAppValue(CFStringRef key, CFPropertyListRef value, CFStringRef applicationID); - - - - - -extern -void CFPreferencesAddSuitePreferencesToApp(CFStringRef applicationID, CFStringRef suiteID); - -extern -void CFPreferencesRemoveSuitePreferencesFromApp(CFStringRef applicationID, CFStringRef suiteID); - - - -extern -Boolean CFPreferencesAppSynchronize(CFStringRef applicationID); - - - - - -extern -CFPropertyListRef CFPreferencesCopyValue(CFStringRef key, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName); - - - - - -extern -CFDictionaryRef CFPreferencesCopyMultiple(CFArrayRef keysToFetch, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName); - - - -extern -void CFPreferencesSetValue(CFStringRef key, CFPropertyListRef value, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName); - - - -extern -void CFPreferencesSetMultiple(CFDictionaryRef keysToSet, CFArrayRef keysToRemove, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName); - -extern -Boolean CFPreferencesSynchronize(CFStringRef applicationID, CFStringRef userName, CFStringRef hostName); - - - - - -extern -CFArrayRef CFPreferencesCopyApplicationList(CFStringRef userName, CFStringRef hostName) __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))); - - - - -extern -CFArrayRef CFPreferencesCopyKeyList(CFStringRef applicationID, CFStringRef userName, CFStringRef hostName); - - - - - - - -extern -Boolean CFPreferencesAppValueIsForced(CFStringRef key, CFStringRef applicationID); - - - -} -extern "C" { - -typedef CFIndex CFURLPathStyle; enum { - kCFURLPOSIXPathStyle = 0, - kCFURLHFSPathStyle __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))), - kCFURLWindowsPathStyle -}; - -typedef const struct __attribute__((objc_bridge(NSURL))) __CFURL * CFURLRef; -extern -CFTypeID CFURLGetTypeID(void); -extern -CFURLRef CFURLCreateWithBytes(CFAllocatorRef allocator, const UInt8 *URLBytes, CFIndex length, CFStringEncoding encoding, CFURLRef baseURL); - - - - - -extern -CFDataRef CFURLCreateData(CFAllocatorRef allocator, CFURLRef url, CFStringEncoding encoding, Boolean escapeWhitespace); - - -extern -CFURLRef CFURLCreateWithString(CFAllocatorRef allocator, CFStringRef URLString, CFURLRef baseURL); -extern -CFURLRef CFURLCreateAbsoluteURLWithBytes(CFAllocatorRef alloc, const UInt8 *relativeURLBytes, CFIndex length, CFStringEncoding encoding, CFURLRef baseURL, Boolean useCompatibilityMode); - - - - - - - -extern -CFURLRef CFURLCreateWithFileSystemPath(CFAllocatorRef allocator, CFStringRef filePath, CFURLPathStyle pathStyle, Boolean isDirectory); - -extern -CFURLRef CFURLCreateFromFileSystemRepresentation(CFAllocatorRef allocator, const UInt8 *buffer, CFIndex bufLen, Boolean isDirectory); - - - - - - - -extern -CFURLRef CFURLCreateWithFileSystemPathRelativeToBase(CFAllocatorRef allocator, CFStringRef filePath, CFURLPathStyle pathStyle, Boolean isDirectory, CFURLRef baseURL); - -extern -CFURLRef CFURLCreateFromFileSystemRepresentationRelativeToBase(CFAllocatorRef allocator, const UInt8 *buffer, CFIndex bufLen, Boolean isDirectory, CFURLRef baseURL); -extern -Boolean CFURLGetFileSystemRepresentation(CFURLRef url, Boolean resolveAgainstBase, UInt8 *buffer, CFIndex maxBufLen); - - -extern -CFURLRef CFURLCopyAbsoluteURL(CFURLRef relativeURL); - - -extern -CFStringRef CFURLGetString(CFURLRef anURL); - - -extern -CFURLRef CFURLGetBaseURL(CFURLRef anURL); -extern -Boolean CFURLCanBeDecomposed(CFURLRef anURL); - - - -extern -CFStringRef CFURLCopyScheme(CFURLRef anURL); - - -extern -CFStringRef CFURLCopyNetLocation(CFURLRef anURL); -extern -CFStringRef CFURLCopyPath(CFURLRef anURL); - -extern -CFStringRef CFURLCopyStrictPath(CFURLRef anURL, Boolean *isAbsolute); - -extern -CFStringRef CFURLCopyFileSystemPath(CFURLRef anURL, CFURLPathStyle pathStyle); - - - -extern -Boolean CFURLHasDirectoryPath(CFURLRef anURL); - - - -extern -CFStringRef CFURLCopyResourceSpecifier(CFURLRef anURL); - -extern -CFStringRef CFURLCopyHostName(CFURLRef anURL); - -extern -SInt32 CFURLGetPortNumber(CFURLRef anURL); - -extern -CFStringRef CFURLCopyUserName(CFURLRef anURL); - -extern -CFStringRef CFURLCopyPassword(CFURLRef anURL); - - - - - - -extern -CFStringRef CFURLCopyParameterString(CFURLRef anURL, CFStringRef charactersToLeaveEscaped); - -extern -CFStringRef CFURLCopyQueryString(CFURLRef anURL, CFStringRef charactersToLeaveEscaped); - -extern -CFStringRef CFURLCopyFragment(CFURLRef anURL, CFStringRef charactersToLeaveEscaped); - -extern -CFStringRef CFURLCopyLastPathComponent(CFURLRef url); - -extern -CFStringRef CFURLCopyPathExtension(CFURLRef url); - - - - - -extern -CFURLRef CFURLCreateCopyAppendingPathComponent(CFAllocatorRef allocator, CFURLRef url, CFStringRef pathComponent, Boolean isDirectory); - -extern -CFURLRef CFURLCreateCopyDeletingLastPathComponent(CFAllocatorRef allocator, CFURLRef url); - -extern -CFURLRef CFURLCreateCopyAppendingPathExtension(CFAllocatorRef allocator, CFURLRef url, CFStringRef extension); - -extern -CFURLRef CFURLCreateCopyDeletingPathExtension(CFAllocatorRef allocator, CFURLRef url); - - - - - - - -extern -CFIndex CFURLGetBytes(CFURLRef url, UInt8 *buffer, CFIndex bufferLength); - -typedef CFIndex CFURLComponentType; enum { - kCFURLComponentScheme = 1, - kCFURLComponentNetLocation = 2, - kCFURLComponentPath = 3, - kCFURLComponentResourceSpecifier = 4, - - kCFURLComponentUser = 5, - kCFURLComponentPassword = 6, - kCFURLComponentUserInfo = 7, - kCFURLComponentHost = 8, - kCFURLComponentPort = 9, - kCFURLComponentParameterString = 10, - kCFURLComponentQuery = 11, - kCFURLComponentFragment = 12 -}; -extern -CFRange CFURLGetByteRangeForComponent(CFURLRef url, CFURLComponentType component, CFRange *rangeIncludingSeparators); -extern -CFStringRef CFURLCreateStringByReplacingPercentEscapes(CFAllocatorRef allocator, CFStringRef originalString, CFStringRef charactersToLeaveEscaped); - - -extern -CFStringRef CFURLCreateStringByReplacingPercentEscapesUsingEncoding(CFAllocatorRef allocator, CFStringRef origString, CFStringRef charsToLeaveEscaped, CFStringEncoding encoding) __attribute__((availability(macosx,introduced=10_0,deprecated=10_11,message="" "Use [NSString stringByRemovingPercentEncoding] or CFURLCreateStringByReplacingPercentEscapes() instead, which always uses the recommended UTF-8 encoding."))); -extern -CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator, CFStringRef originalString, CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped, CFStringEncoding encoding) __attribute__((availability(macosx,introduced=10_0,deprecated=10_11,message="" "Use [NSString stringByAddingPercentEncodingWithAllowedCharacters:] instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent (since each URL component or subcomponent has different rules for what characters are valid)."))); -extern -Boolean CFURLIsFileReferenceURL(CFURLRef url) __attribute__((availability(macosx,introduced=10_9))); -extern -CFURLRef CFURLCreateFileReferenceURL(CFAllocatorRef allocator, CFURLRef url, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); -extern -CFURLRef CFURLCreateFilePathURL(CFAllocatorRef allocator, CFURLRef url, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); - - - - - - - -struct FSRef; - - - -extern -CFURLRef CFURLCreateFromFSRef(CFAllocatorRef allocator, const struct FSRef *fsRef) __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))); - -extern -Boolean CFURLGetFSRef(CFURLRef url, struct FSRef *fsRef) __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))); -extern -Boolean CFURLCopyResourcePropertyForKey(CFURLRef url, CFStringRef key, void *propertyValueTypeRefPtr, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); -extern -CFDictionaryRef CFURLCopyResourcePropertiesForKeys(CFURLRef url, CFArrayRef keys, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); -extern -Boolean CFURLSetResourcePropertyForKey(CFURLRef url, CFStringRef key, CFTypeRef propertyValue, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); -extern -Boolean CFURLSetResourcePropertiesForKeys(CFURLRef url, CFDictionaryRef keyedPropertyValues, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLKeysOfUnsetValuesKey __attribute__((availability(macosx,introduced=10_7))); -extern -void CFURLClearResourcePropertyCacheForKey(CFURLRef url, CFStringRef key) __attribute__((availability(macosx,introduced=10_6))); -extern -void CFURLClearResourcePropertyCache(CFURLRef url) __attribute__((availability(macosx,introduced=10_6))); -extern -void CFURLSetTemporaryResourcePropertyForKey(CFURLRef url, CFStringRef key, CFTypeRef propertyValue) __attribute__((availability(macosx,introduced=10_6))); -extern -Boolean CFURLResourceIsReachable(CFURLRef url, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); - - - - - - -extern -const CFStringRef kCFURLNameKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLLocalizedNameKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLIsRegularFileKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLIsDirectoryKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLIsSymbolicLinkKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLIsVolumeKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLIsPackageKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLIsApplicationKey __attribute__((availability(macosx,introduced=10_11))); - - -extern -const CFStringRef kCFURLApplicationIsScriptableKey __attribute__((availability(macosx,introduced=10_11))); - - -extern -const CFStringRef kCFURLIsSystemImmutableKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLIsUserImmutableKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLIsHiddenKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLHasHiddenExtensionKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLCreationDateKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLContentAccessDateKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLContentModificationDateKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLAttributeModificationDateKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLLinkCountKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLParentDirectoryURLKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeURLKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLTypeIdentifierKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLLocalizedTypeDescriptionKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLLabelNumberKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLLabelColorKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLLocalizedLabelKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLEffectiveIconKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLCustomIconKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLFileResourceIdentifierKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeIdentifierKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLPreferredIOBlockSizeKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLIsReadableKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLIsWritableKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLIsExecutableKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLFileSecurityKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLIsExcludedFromBackupKey __attribute__((availability(macosx,introduced=10_8))); - - -extern -const CFStringRef kCFURLTagNamesKey __attribute__((availability(macosx,introduced=10_9))); - - -extern -const CFStringRef kCFURLPathKey __attribute__((availability(macosx,introduced=10_8))); - - -extern -const CFStringRef kCFURLIsMountTriggerKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLGenerationIdentifierKey __attribute__((availability(macosx,introduced=10_10))); - - -extern -const CFStringRef kCFURLDocumentIdentifierKey __attribute__((availability(macosx,introduced=10_10))); - - -extern -const CFStringRef kCFURLAddedToDirectoryDateKey __attribute__((availability(macosx,introduced=10_10))); - - -extern -const CFStringRef kCFURLQuarantinePropertiesKey __attribute__((availability(macosx,introduced=10_10))); - - -extern -const CFStringRef kCFURLFileResourceTypeKey __attribute__((availability(macosx,introduced=10_7))); - - - -extern -const CFStringRef kCFURLFileResourceTypeNamedPipe __attribute__((availability(macosx,introduced=10_7))); -extern -const CFStringRef kCFURLFileResourceTypeCharacterSpecial __attribute__((availability(macosx,introduced=10_7))); -extern -const CFStringRef kCFURLFileResourceTypeDirectory __attribute__((availability(macosx,introduced=10_7))); -extern -const CFStringRef kCFURLFileResourceTypeBlockSpecial __attribute__((availability(macosx,introduced=10_7))); -extern -const CFStringRef kCFURLFileResourceTypeRegular __attribute__((availability(macosx,introduced=10_7))); -extern -const CFStringRef kCFURLFileResourceTypeSymbolicLink __attribute__((availability(macosx,introduced=10_7))); -extern -const CFStringRef kCFURLFileResourceTypeSocket __attribute__((availability(macosx,introduced=10_7))); -extern -const CFStringRef kCFURLFileResourceTypeUnknown __attribute__((availability(macosx,introduced=10_7))); - - - -extern -const CFStringRef kCFURLFileSizeKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLFileAllocatedSizeKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLTotalFileSizeKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLTotalFileAllocatedSizeKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLIsAliasFileKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLFileProtectionKey __attribute__((availability(macosx,unavailable))); - - - -extern -const CFStringRef kCFURLFileProtectionNone __attribute__((availability(macosx,unavailable))); - -extern -const CFStringRef kCFURLFileProtectionComplete __attribute__((availability(macosx,unavailable))); - -extern -const CFStringRef kCFURLFileProtectionCompleteUnlessOpen __attribute__((availability(macosx,unavailable))); - -extern -const CFStringRef kCFURLFileProtectionCompleteUntilFirstUserAuthentication __attribute__((availability(macosx,unavailable))); - - - - - -extern -const CFStringRef kCFURLVolumeLocalizedFormatDescriptionKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeTotalCapacityKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeAvailableCapacityKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeResourceCountKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeSupportsPersistentIDsKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeSupportsSymbolicLinksKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeSupportsHardLinksKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeSupportsJournalingKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeIsJournalingKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeSupportsSparseFilesKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeSupportsZeroRunsKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeSupportsCaseSensitiveNamesKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeSupportsCasePreservedNamesKey __attribute__((availability(macosx,introduced=10_6))); - - -extern -const CFStringRef kCFURLVolumeSupportsRootDirectoryDatesKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeSupportsVolumeSizesKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeSupportsRenamingKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeSupportsAdvisoryFileLockingKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeSupportsExtendedSecurityKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeIsBrowsableKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeMaximumFileSizeKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeIsEjectableKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeIsRemovableKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeIsInternalKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeIsAutomountedKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeIsLocalKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeIsReadOnlyKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeCreationDateKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeURLForRemountingKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeUUIDStringKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeNameKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLVolumeLocalizedNameKey __attribute__((availability(macosx,introduced=10_7))); - - - - -extern -const CFStringRef kCFURLIsUbiquitousItemKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLUbiquitousItemHasUnresolvedConflictsKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLUbiquitousItemIsDownloadedKey __attribute__((availability(macosx,introduced=10_7,deprecated=10_9,message="" "Use kCFURLUbiquitousItemDownloadingStatusKey instead"))); - - -extern -const CFStringRef kCFURLUbiquitousItemIsDownloadingKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLUbiquitousItemIsUploadedKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLUbiquitousItemIsUploadingKey __attribute__((availability(macosx,introduced=10_7))); - - -extern -const CFStringRef kCFURLUbiquitousItemPercentDownloadedKey __attribute__((availability(macosx,introduced=10_7,deprecated=10_8,message="" "Use NSMetadataQuery and NSMetadataUbiquitousItemPercentDownloadedKey on NSMetadataItem instead"))); - - -extern -const CFStringRef kCFURLUbiquitousItemPercentUploadedKey __attribute__((availability(macosx,introduced=10_7,deprecated=10_8,message="" "Use NSMetadataQuery and NSMetadataUbiquitousItemPercentUploadedKey on NSMetadataItem instead"))); - - -extern -const CFStringRef kCFURLUbiquitousItemDownloadingStatusKey __attribute__((availability(macosx,introduced=10_9))); - - -extern -const CFStringRef kCFURLUbiquitousItemDownloadingErrorKey __attribute__((availability(macosx,introduced=10_9))); - - -extern -const CFStringRef kCFURLUbiquitousItemUploadingErrorKey __attribute__((availability(macosx,introduced=10_9))); - - - - -extern -const CFStringRef kCFURLUbiquitousItemDownloadingStatusNotDownloaded __attribute__((availability(macosx,introduced=10_9))); - - -extern -const CFStringRef kCFURLUbiquitousItemDownloadingStatusDownloaded __attribute__((availability(macosx,introduced=10_9))); - - -extern -const CFStringRef kCFURLUbiquitousItemDownloadingStatusCurrent __attribute__((availability(macosx,introduced=10_9))); - - - -typedef CFOptionFlags CFURLBookmarkCreationOptions; enum { - kCFURLBookmarkCreationMinimalBookmarkMask = ( 1UL << 9 ), - kCFURLBookmarkCreationSuitableForBookmarkFile = ( 1UL << 10 ), - kCFURLBookmarkCreationWithSecurityScope __attribute__((availability(macosx,introduced=10_7))) = ( 1UL << 11 ), - kCFURLBookmarkCreationSecurityScopeAllowOnlyReadAccess __attribute__((availability(macosx,introduced=10_7))) = ( 1UL << 12 ), - - - kCFURLBookmarkCreationPreferFileIDResolutionMask __attribute__((availability(macosx,introduced=10_6,deprecated=10_9,message="" "kCFURLBookmarkCreationPreferFileIDResolutionMask does nothing and has no effect on bookmark resolution"))) = ( 1UL << 8 ), -} __attribute__((availability(macosx,introduced=10_6))); - -typedef CFOptionFlags CFURLBookmarkResolutionOptions; enum { - kCFURLBookmarkResolutionWithoutUIMask = ( 1UL << 8 ), - kCFURLBookmarkResolutionWithoutMountingMask = ( 1UL << 9 ), - kCFURLBookmarkResolutionWithSecurityScope __attribute__((availability(macosx,introduced=10_7))) = ( 1UL << 10 ), - - kCFBookmarkResolutionWithoutUIMask = kCFURLBookmarkResolutionWithoutUIMask, - kCFBookmarkResolutionWithoutMountingMask = kCFURLBookmarkResolutionWithoutMountingMask, -} __attribute__((availability(macosx,introduced=10_6))); - -typedef CFOptionFlags CFURLBookmarkFileCreationOptions; - - - - - -extern -CFDataRef CFURLCreateBookmarkData ( CFAllocatorRef allocator, CFURLRef url, CFURLBookmarkCreationOptions options, CFArrayRef resourcePropertiesToInclude, CFURLRef relativeToURL, CFErrorRef* error ) __attribute__((availability(macosx,introduced=10_6))); - - - -extern -CFURLRef CFURLCreateByResolvingBookmarkData ( CFAllocatorRef allocator, CFDataRef bookmark, CFURLBookmarkResolutionOptions options, CFURLRef relativeToURL, CFArrayRef resourcePropertiesToInclude, Boolean* isStale, CFErrorRef* error ) __attribute__((availability(macosx,introduced=10_6))); - - - -extern -CFDictionaryRef CFURLCreateResourcePropertiesForKeysFromBookmarkData ( CFAllocatorRef allocator, CFArrayRef resourcePropertiesToReturn, CFDataRef bookmark ) __attribute__((availability(macosx,introduced=10_6))); - - - -extern -CFTypeRef CFURLCreateResourcePropertyForKeyFromBookmarkData( CFAllocatorRef allocator, CFStringRef resourcePropertyKey, CFDataRef bookmark ) __attribute__((availability(macosx,introduced=10_6))); - - - -extern -CFDataRef CFURLCreateBookmarkDataFromFile(CFAllocatorRef allocator, CFURLRef fileURL, CFErrorRef *errorRef ) __attribute__((availability(macosx,introduced=10_6))); - - - -extern -Boolean CFURLWriteBookmarkDataToFile( CFDataRef bookmarkRef, CFURLRef fileURL, CFURLBookmarkFileCreationOptions options, CFErrorRef *errorRef ) __attribute__((availability(macosx,introduced=10_6))); - - - -extern -CFDataRef CFURLCreateBookmarkDataFromAliasRecord ( CFAllocatorRef allocatorRef, CFDataRef aliasRecordDataRef ) __attribute__((availability(macosx,introduced=10_6))); - - - - - -extern -Boolean CFURLStartAccessingSecurityScopedResource(CFURLRef url) __attribute__((availability(macosx,introduced=10_7))); - - - -extern -void CFURLStopAccessingSecurityScopedResource(CFURLRef url) __attribute__((availability(macosx,introduced=10_7))); - - - -} -typedef unsigned int boolean_t; -typedef __darwin_natural_t natural_t; -typedef int integer_t; - - - - - - -typedef uintptr_t vm_offset_t; -typedef uintptr_t vm_size_t; -typedef uint64_t mach_vm_address_t; -typedef uint64_t mach_vm_offset_t; -typedef uint64_t mach_vm_size_t; - -typedef uint64_t vm_map_offset_t; -typedef uint64_t vm_map_address_t; -typedef uint64_t vm_map_size_t; - -typedef mach_vm_address_t mach_port_context_t; -typedef natural_t mach_port_name_t; -typedef mach_port_name_t *mach_port_name_array_t; -typedef __darwin_mach_port_t mach_port_t; - - -typedef mach_port_t *mach_port_array_t; -typedef natural_t mach_port_right_t; -typedef natural_t mach_port_type_t; -typedef mach_port_type_t *mach_port_type_array_t; -typedef natural_t mach_port_urefs_t; -typedef integer_t mach_port_delta_t; - - - -typedef natural_t mach_port_seqno_t; -typedef natural_t mach_port_mscount_t; -typedef natural_t mach_port_msgcount_t; -typedef natural_t mach_port_rights_t; - - - - - - -typedef unsigned int mach_port_srights_t; - -typedef struct mach_port_status { - mach_port_rights_t mps_pset; - mach_port_seqno_t mps_seqno; - mach_port_mscount_t mps_mscount; - mach_port_msgcount_t mps_qlimit; - mach_port_msgcount_t mps_msgcount; - mach_port_rights_t mps_sorights; - boolean_t mps_srights; - boolean_t mps_pdrequest; - boolean_t mps_nsrequest; - natural_t mps_flags; -} mach_port_status_t; -typedef struct mach_port_limits { - mach_port_msgcount_t mpl_qlimit; -} mach_port_limits_t; -typedef struct mach_port_info_ext { - mach_port_status_t mpie_status; - mach_port_msgcount_t mpie_boost_cnt; - uint32_t reserved[6]; -} mach_port_info_ext_t; - -typedef integer_t *mach_port_info_t; - - -typedef int mach_port_flavor_t; -typedef struct mach_port_qos { - unsigned int name:1; - unsigned int prealloc:1; - boolean_t pad1:30; - natural_t len; -} mach_port_qos_t; -typedef struct mach_port_options { - uint32_t flags; - mach_port_limits_t mpl; - uint64_t reserved[2]; -}mach_port_options_t; - -typedef mach_port_options_t *mach_port_options_ptr_t; -enum mach_port_guard_exception_codes { - kGUARD_EXC_DESTROY = 1u << 0, - kGUARD_EXC_MOD_REFS = 1u << 1, - kGUARD_EXC_SET_CONTEXT = 1u << 2, - kGUARD_EXC_UNGUARDED = 1u << 3, - kGUARD_EXC_INCORRECT_GUARD = 1u << 4 -}; - - - -extern "C" { - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFRunLoop * CFRunLoopRef; - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFRunLoopSource * CFRunLoopSourceRef; - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFRunLoopObserver * CFRunLoopObserverRef; - -typedef struct __attribute__((objc_bridge_mutable(NSTimer))) __CFRunLoopTimer * CFRunLoopTimerRef; - - -typedef SInt32 CFRunLoopRunResult; enum { - kCFRunLoopRunFinished = 1, - kCFRunLoopRunStopped = 2, - kCFRunLoopRunTimedOut = 3, - kCFRunLoopRunHandledSource = 4 -}; - - -typedef CFOptionFlags CFRunLoopActivity; enum { - kCFRunLoopEntry = (1UL << 0), - kCFRunLoopBeforeTimers = (1UL << 1), - kCFRunLoopBeforeSources = (1UL << 2), - kCFRunLoopBeforeWaiting = (1UL << 5), - kCFRunLoopAfterWaiting = (1UL << 6), - kCFRunLoopExit = (1UL << 7), - kCFRunLoopAllActivities = 0x0FFFFFFFU -}; - -extern const CFStringRef kCFRunLoopDefaultMode; -extern const CFStringRef kCFRunLoopCommonModes; - -extern CFTypeID CFRunLoopGetTypeID(void); - -extern CFRunLoopRef CFRunLoopGetCurrent(void); -extern CFRunLoopRef CFRunLoopGetMain(void); - -extern CFStringRef CFRunLoopCopyCurrentMode(CFRunLoopRef rl); - -extern CFArrayRef CFRunLoopCopyAllModes(CFRunLoopRef rl); - -extern void CFRunLoopAddCommonMode(CFRunLoopRef rl, CFStringRef mode); - -extern CFAbsoluteTime CFRunLoopGetNextTimerFireDate(CFRunLoopRef rl, CFStringRef mode); - -extern void CFRunLoopRun(void); -extern CFRunLoopRunResult CFRunLoopRunInMode(CFStringRef mode, CFTimeInterval seconds, Boolean returnAfterSourceHandled); -extern Boolean CFRunLoopIsWaiting(CFRunLoopRef rl); -extern void CFRunLoopWakeUp(CFRunLoopRef rl); -extern void CFRunLoopStop(CFRunLoopRef rl); - - -extern void CFRunLoopPerformBlock(CFRunLoopRef rl, CFTypeRef mode, void (*block)(void)) __attribute__((availability(macosx,introduced=10_6))); - - -extern Boolean CFRunLoopContainsSource(CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode); -extern void CFRunLoopAddSource(CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode); -extern void CFRunLoopRemoveSource(CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode); - -extern Boolean CFRunLoopContainsObserver(CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode); -extern void CFRunLoopAddObserver(CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode); -extern void CFRunLoopRemoveObserver(CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode); - -extern Boolean CFRunLoopContainsTimer(CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode); -extern void CFRunLoopAddTimer(CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode); -extern void CFRunLoopRemoveTimer(CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode); - -typedef struct { - CFIndex version; - void * info; - const void *(*retain)(const void *info); - void (*release)(const void *info); - CFStringRef (*copyDescription)(const void *info); - Boolean (*equal)(const void *info1, const void *info2); - CFHashCode (*hash)(const void *info); - void (*schedule)(void *info, CFRunLoopRef rl, CFStringRef mode); - void (*cancel)(void *info, CFRunLoopRef rl, CFStringRef mode); - void (*perform)(void *info); -} CFRunLoopSourceContext; - -typedef struct { - CFIndex version; - void * info; - const void *(*retain)(const void *info); - void (*release)(const void *info); - CFStringRef (*copyDescription)(const void *info); - Boolean (*equal)(const void *info1, const void *info2); - CFHashCode (*hash)(const void *info); - - mach_port_t (*getPort)(void *info); - void * (*perform)(void *msg, CFIndex size, CFAllocatorRef allocator, void *info); - - - - -} CFRunLoopSourceContext1; - -extern CFTypeID CFRunLoopSourceGetTypeID(void); - -extern CFRunLoopSourceRef CFRunLoopSourceCreate(CFAllocatorRef allocator, CFIndex order, CFRunLoopSourceContext *context); - -extern CFIndex CFRunLoopSourceGetOrder(CFRunLoopSourceRef source); -extern void CFRunLoopSourceInvalidate(CFRunLoopSourceRef source); -extern Boolean CFRunLoopSourceIsValid(CFRunLoopSourceRef source); -extern void CFRunLoopSourceGetContext(CFRunLoopSourceRef source, CFRunLoopSourceContext *context); -extern void CFRunLoopSourceSignal(CFRunLoopSourceRef source); - -typedef struct { - CFIndex version; - void * info; - const void *(*retain)(const void *info); - void (*release)(const void *info); - CFStringRef (*copyDescription)(const void *info); -} CFRunLoopObserverContext; - -typedef void (*CFRunLoopObserverCallBack)(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info); - -extern CFTypeID CFRunLoopObserverGetTypeID(void); - -extern CFRunLoopObserverRef CFRunLoopObserverCreate(CFAllocatorRef allocator, CFOptionFlags activities, Boolean repeats, CFIndex order, CFRunLoopObserverCallBack callout, CFRunLoopObserverContext *context); - -extern CFRunLoopObserverRef CFRunLoopObserverCreateWithHandler(CFAllocatorRef allocator, CFOptionFlags activities, Boolean repeats, CFIndex order, void (*block) (CFRunLoopObserverRef observer, CFRunLoopActivity activity)) __attribute__((availability(macosx,introduced=10_7))); - - -extern CFOptionFlags CFRunLoopObserverGetActivities(CFRunLoopObserverRef observer); -extern Boolean CFRunLoopObserverDoesRepeat(CFRunLoopObserverRef observer); -extern CFIndex CFRunLoopObserverGetOrder(CFRunLoopObserverRef observer); -extern void CFRunLoopObserverInvalidate(CFRunLoopObserverRef observer); -extern Boolean CFRunLoopObserverIsValid(CFRunLoopObserverRef observer); -extern void CFRunLoopObserverGetContext(CFRunLoopObserverRef observer, CFRunLoopObserverContext *context); - -typedef struct { - CFIndex version; - void * info; - const void *(*retain)(const void *info); - void (*release)(const void *info); - CFStringRef (*copyDescription)(const void *info); -} CFRunLoopTimerContext; - -typedef void (*CFRunLoopTimerCallBack)(CFRunLoopTimerRef timer, void *info); - -extern CFTypeID CFRunLoopTimerGetTypeID(void); - -extern CFRunLoopTimerRef CFRunLoopTimerCreate(CFAllocatorRef allocator, CFAbsoluteTime fireDate, CFTimeInterval interval, CFOptionFlags flags, CFIndex order, CFRunLoopTimerCallBack callout, CFRunLoopTimerContext *context); - -extern CFRunLoopTimerRef CFRunLoopTimerCreateWithHandler(CFAllocatorRef allocator, CFAbsoluteTime fireDate, CFTimeInterval interval, CFOptionFlags flags, CFIndex order, void (*block) (CFRunLoopTimerRef timer)) __attribute__((availability(macosx,introduced=10_7))); - - -extern CFAbsoluteTime CFRunLoopTimerGetNextFireDate(CFRunLoopTimerRef timer); -extern void CFRunLoopTimerSetNextFireDate(CFRunLoopTimerRef timer, CFAbsoluteTime fireDate); -extern CFTimeInterval CFRunLoopTimerGetInterval(CFRunLoopTimerRef timer); -extern Boolean CFRunLoopTimerDoesRepeat(CFRunLoopTimerRef timer); -extern CFIndex CFRunLoopTimerGetOrder(CFRunLoopTimerRef timer); -extern void CFRunLoopTimerInvalidate(CFRunLoopTimerRef timer); -extern Boolean CFRunLoopTimerIsValid(CFRunLoopTimerRef timer); -extern void CFRunLoopTimerGetContext(CFRunLoopTimerRef timer, CFRunLoopTimerContext *context); - - - -extern CFTimeInterval CFRunLoopTimerGetTolerance(CFRunLoopTimerRef timer) __attribute__((availability(macosx,introduced=10_9))); -extern void CFRunLoopTimerSetTolerance(CFRunLoopTimerRef timer, CFTimeInterval tolerance) __attribute__((availability(macosx,introduced=10_9))); - -} -extern "C" { - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFSocket * CFSocketRef; -typedef CFIndex CFSocketError; enum { - kCFSocketSuccess = 0, - kCFSocketError = -1L, - kCFSocketTimeout = -2L -}; - -typedef struct { - SInt32 protocolFamily; - SInt32 socketType; - SInt32 protocol; - CFDataRef address; -} CFSocketSignature; - - -typedef CFOptionFlags CFSocketCallBackType; enum { - kCFSocketNoCallBack = 0, - kCFSocketReadCallBack = 1, - kCFSocketAcceptCallBack = 2, - kCFSocketDataCallBack = 3, - kCFSocketConnectCallBack = 4, - kCFSocketWriteCallBack = 8 -}; - - -enum { - kCFSocketAutomaticallyReenableReadCallBack = 1, - kCFSocketAutomaticallyReenableAcceptCallBack = 2, - kCFSocketAutomaticallyReenableDataCallBack = 3, - kCFSocketAutomaticallyReenableWriteCallBack = 8, - kCFSocketLeaveErrors __attribute__((availability(macosx,introduced=10_5))) = 64, - kCFSocketCloseOnInvalidate = 128 -}; - -typedef void (*CFSocketCallBack)(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info); - - -typedef struct { - CFIndex version; - void * info; - const void *(*retain)(const void *info); - void (*release)(const void *info); - CFStringRef (*copyDescription)(const void *info); -} CFSocketContext; - - - - -typedef int CFSocketNativeHandle; - - -extern CFTypeID CFSocketGetTypeID(void); - -extern CFSocketRef CFSocketCreate(CFAllocatorRef allocator, SInt32 protocolFamily, SInt32 socketType, SInt32 protocol, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext *context); -extern CFSocketRef CFSocketCreateWithNative(CFAllocatorRef allocator, CFSocketNativeHandle sock, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext *context); -extern CFSocketRef CFSocketCreateWithSocketSignature(CFAllocatorRef allocator, const CFSocketSignature *signature, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext *context); - -extern CFSocketRef CFSocketCreateConnectedToSocketSignature(CFAllocatorRef allocator, const CFSocketSignature *signature, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext *context, CFTimeInterval timeout); - - -extern CFSocketError CFSocketSetAddress(CFSocketRef s, CFDataRef address); -extern CFSocketError CFSocketConnectToAddress(CFSocketRef s, CFDataRef address, CFTimeInterval timeout); -extern void CFSocketInvalidate(CFSocketRef s); - -extern Boolean CFSocketIsValid(CFSocketRef s); -extern CFDataRef CFSocketCopyAddress(CFSocketRef s); -extern CFDataRef CFSocketCopyPeerAddress(CFSocketRef s); -extern void CFSocketGetContext(CFSocketRef s, CFSocketContext *context); -extern CFSocketNativeHandle CFSocketGetNative(CFSocketRef s); - -extern CFRunLoopSourceRef CFSocketCreateRunLoopSource(CFAllocatorRef allocator, CFSocketRef s, CFIndex order); - -extern CFOptionFlags CFSocketGetSocketFlags(CFSocketRef s); -extern void CFSocketSetSocketFlags(CFSocketRef s, CFOptionFlags flags); -extern void CFSocketDisableCallBacks(CFSocketRef s, CFOptionFlags callBackTypes); -extern void CFSocketEnableCallBacks(CFSocketRef s, CFOptionFlags callBackTypes); - - - -extern CFSocketError CFSocketSendData(CFSocketRef s, CFDataRef address, CFDataRef data, CFTimeInterval timeout); -extern CFSocketError CFSocketRegisterValue(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFPropertyListRef value); -extern CFSocketError CFSocketCopyRegisteredValue(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFPropertyListRef *value, CFDataRef *nameServerAddress); - -extern CFSocketError CFSocketRegisterSocketSignature(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, const CFSocketSignature *signature); -extern CFSocketError CFSocketCopyRegisteredSocketSignature(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFSocketSignature *signature, CFDataRef *nameServerAddress); - -extern CFSocketError CFSocketUnregister(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name); - -extern void CFSocketSetDefaultNameRegistryPortNumber(UInt16 port); -extern UInt16 CFSocketGetDefaultNameRegistryPortNumber(void); - - -extern const CFStringRef kCFSocketCommandKey; -extern const CFStringRef kCFSocketNameKey; -extern const CFStringRef kCFSocketValueKey; -extern const CFStringRef kCFSocketResultKey; -extern const CFStringRef kCFSocketErrorKey; -extern const CFStringRef kCFSocketRegisterCommand; -extern const CFStringRef kCFSocketRetrieveCommand; - -} - - - - -struct accessx_descriptor { - unsigned int ad_name_offset; - int ad_flags; - int ad_pad[2]; -}; -extern "C" { - -int getattrlistbulk(int, void *, void *, size_t, uint64_t) __attribute__((availability(macosx,introduced=10.10))); - -} -extern "C" { - -int faccessat(int, const char *, int, int) __attribute__((availability(macosx,introduced=10.10))); -int fchownat(int, const char *, uid_t, gid_t, int) __attribute__((availability(macosx,introduced=10.10))); -int linkat(int, const char *, int, const char *, int) __attribute__((availability(macosx,introduced=10.10))); -ssize_t readlinkat(int, const char *, char *, size_t) __attribute__((availability(macosx,introduced=10.10))); -int symlinkat(const char *, int, const char *) __attribute__((availability(macosx,introduced=10.10))); -int unlinkat(int, const char *, int) __attribute__((availability(macosx,introduced=10.10))); -int getattrlistat(int, const char *, void *, void *, size_t, unsigned long) __attribute__((availability(macosx,introduced=10.10))); - -} -extern "C" { -void _exit(int) __attribute__((noreturn)); -int access(const char *, int); -unsigned int - alarm(unsigned int); -int chdir(const char *); -int chown(const char *, uid_t, gid_t); - -int close(int) __asm("_" "close" ); - -int dup(int); -int dup2(int, int); -int execl(const char *, const char *, ...) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -int execle(const char *, const char *, ...) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -int execlp(const char *, const char *, ...) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -int execv(const char *, char * const *) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -int execve(const char *, char * const *, char * const *) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -int execvp(const char *, char * const *) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -pid_t fork(void) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -long fpathconf(int, int); -char *getcwd(char *, size_t); -gid_t getegid(void); -uid_t geteuid(void); -gid_t getgid(void); - - - -int getgroups(int, gid_t []); - -char *getlogin(void); -pid_t getpgrp(void); -pid_t getpid(void); -pid_t getppid(void); -uid_t getuid(void); -int isatty(int); -int link(const char *, const char *); -off_t lseek(int, off_t, int); -long pathconf(const char *, int); - -int pause(void) __asm("_" "pause" ); - -int pipe(int [2]); - -ssize_t read(int, void *, size_t) __asm("_" "read" ); - -int rmdir(const char *); -int setgid(gid_t); -int setpgid(pid_t, pid_t); -pid_t setsid(void); -int setuid(uid_t); - -unsigned int - sleep(unsigned int) __asm("_" "sleep" ); - -long sysconf(int); -pid_t tcgetpgrp(int); -int tcsetpgrp(int, pid_t); -char *ttyname(int); - - -int ttyname_r(int, char *, size_t) __asm("_" "ttyname_r" ); - - - - -int unlink(const char *); - -ssize_t write(int, const void *, size_t) __asm("_" "write" ); -} -extern "C" { -size_t confstr(int, char *, size_t) __asm("_" "confstr" ); - -int getopt(int, char * const [], const char *) __asm("_" "getopt" ); - -extern char *optarg; -extern int optind, opterr, optopt; -} - extern "C" { - - - - - -__attribute__((deprecated)) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) - -void *brk(const void *); -int chroot(const char *) ; - - -char *crypt(const char *, const char *); - - - - - - -void encrypt(char *, int) __asm("_" "encrypt" ); - - - -int fchdir(int); -long gethostid(void); -pid_t getpgid(pid_t); -pid_t getsid(pid_t); - - - -int getdtablesize(void) ; -int getpagesize(void) __attribute__((const)) ; -char *getpass(const char *) ; - - - - -char *getwd(char *) ; - - -int lchown(const char *, uid_t, gid_t) __asm("_" "lchown" ); - -int lockf(int, int, off_t) __asm("_" "lockf" ); - -int nice(int) __asm("_" "nice" ); - -ssize_t pread(int, void *, size_t, off_t) __asm("_" "pread" ); - -ssize_t pwrite(int, const void *, size_t, off_t) __asm("_" "pwrite" ); - - - - - - -__attribute__((deprecated)) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) - -void *sbrk(int); - - - -pid_t setpgrp(void) __asm("_" "setpgrp" ); - - - - -int setregid(gid_t, gid_t) __asm("_" "setregid" ); - -int setreuid(uid_t, uid_t) __asm("_" "setreuid" ); - -void swab(const void * , void * , ssize_t); -void sync(void); -int truncate(const char *, off_t); -useconds_t ualarm(useconds_t, useconds_t); -int usleep(useconds_t) __asm("_" "usleep" ); -pid_t vfork(void) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); - - -int fsync(int) __asm("_" "fsync" ); - -int ftruncate(int, off_t); -int getlogin_r(char *, size_t); -} -extern "C" { -int fchown(int, uid_t, gid_t); -int gethostname(char *, size_t); -ssize_t readlink(const char * , char * , size_t); -int setegid(gid_t); -int seteuid(uid_t); -int symlink(const char *, const char *); -} - - - - - - - - -extern "C" { - - -int pselect(int, fd_set * , fd_set * , - fd_set * , const struct timespec * , - const sigset_t * ) - - - - - __asm("_" "pselect" "$1050") - - - - - ; - - - -int select(int, fd_set * , fd_set * , - fd_set * , struct timeval * ) - - - - - __asm("_" "select" "$1050") - - - - - ; - -} - - - -typedef __darwin_uuid_t uuid_t; - -extern "C" { -void _Exit(int) __attribute__((noreturn)); -int accessx_np(const struct accessx_descriptor *, size_t, int *, uid_t); -int acct(const char *); -int add_profil(char *, size_t, unsigned long, unsigned int) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -void endusershell(void); -int execvP(const char *, const char *, char * const *) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -char *fflagstostr(unsigned long); -int getdomainname(char *, int); -int getgrouplist(const char *, int, int *, int *); - - - - - -int gethostuuid(uuid_t, const struct timespec *) __attribute__((availability(macosx,introduced=10.5))); - - - - -mode_t getmode(const void *, mode_t); -int getpeereid(int, uid_t *, gid_t *); -int getsgroups_np(int *, uuid_t); -char *getusershell(void); -int getwgroups_np(int *, uuid_t); -int initgroups(const char *, int); -int iruserok(unsigned long, int, const char *, const char *); -int iruserok_sa(const void *, int, int, const char *, const char *); -int issetugid(void); -char *mkdtemp(char *); -int mknod(const char *, mode_t, dev_t); -int mkpath_np(const char *path, mode_t omode) __attribute__((availability(macosx,introduced=10.8))); -int mkstemp(char *); -int mkstemps(char *, int); -char *mktemp(char *); -int nfssvc(int, void *); -int profil(char *, size_t, unsigned long, unsigned int); -int pthread_setugid_np(uid_t, gid_t); -int pthread_getugid_np( uid_t *, gid_t *); -int rcmd(char **, int, const char *, const char *, const char *, int *); -int rcmd_af(char **, int, const char *, const char *, const char *, int *, - int); -int reboot(int); -int revoke(const char *); -int rresvport(int *); -int rresvport_af(int *, int); -int ruserok(const char *, int, const char *, const char *); -int setdomainname(const char *, int); -int setgroups(int, const gid_t *); -void sethostid(long); -int sethostname(const char *, int); - -void setkey(const char *) __asm("_" "setkey" ); - - - -int setlogin(const char *); -void *setmode(const char *) __asm("_" "setmode" ); -int setrgid(gid_t); -int setruid(uid_t); -int setsgroups_np(int, const uuid_t); -void setusershell(void); -int setwgroups_np(int, const uuid_t); -int strtofflags(char **, unsigned long *, unsigned long *); -int swapon(const char *); -int syscall(int, ...) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -int ttyslot(void); -int undelete(const char *); -int unwhiteout(const char *); -void *valloc(size_t); - -extern char *suboptarg; -int getsubopt(char **, char * const *, char **); - - - -int fgetattrlist(int,void*,void*,size_t,unsigned int) __attribute__((availability(macosx,introduced=10.6))); -int fsetattrlist(int,void*,void*,size_t,unsigned int) __attribute__((availability(macosx,introduced=10.6))); -int getattrlist(const char*,void*,void*,size_t,unsigned int) __asm("_" "getattrlist" ); -int setattrlist(const char*,void*,void*,size_t,unsigned int) __asm("_" "setattrlist" ); -int exchangedata(const char*,const char*,unsigned int) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -int getdirentriesattr(int,void*,void*,size_t,unsigned int*,unsigned int*,unsigned int*,unsigned int) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -struct fssearchblock; -struct searchstate; - -int searchfs(const char *, struct fssearchblock *, unsigned long *, unsigned int, unsigned int, struct searchstate *) __attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))); -int fsctl(const char *,unsigned long,void*,unsigned int); -int ffsctl(int,unsigned long,void*,unsigned int) __attribute__((availability(macosx,introduced=10.6))); - - - - -int fsync_volume_np(int, int) __attribute__((availability(macosx,introduced=10.8))); -int sync_volume_np(const char *, int) __attribute__((availability(macosx,introduced=10.8))); - -extern int optreset; - -} - - - - - -struct flock { - off_t l_start; - off_t l_len; - pid_t l_pid; - short l_type; - short l_whence; -}; -struct flocktimeout { - struct flock fl; - struct timespec timeout; -}; -struct radvisory { - off_t ra_offset; - int ra_count; -}; - - - -typedef struct fcodeblobs { - void *f_cd_hash; - size_t f_hash_size; - void *f_cd_buffer; - size_t f_cd_size; - unsigned int *f_out_size; - int f_arch; - int __padding; -} fcodeblobs_t; -typedef struct fsignatures { - off_t fs_file_start; - void *fs_blob_start; - size_t fs_blob_size; -} fsignatures_t; -typedef struct fstore { - unsigned int fst_flags; - int fst_posmode; - off_t fst_offset; - off_t fst_length; - off_t fst_bytesalloc; -} fstore_t; - - - -typedef struct fbootstraptransfer { - off_t fbt_offset; - size_t fbt_length; - void *fbt_buffer; -} fbootstraptransfer_t; -#pragma pack(4) - -struct log2phys { - unsigned int l2p_flags; - off_t l2p_contigbytes; - - - off_t l2p_devoffset; - - -}; - -#pragma pack() -struct _filesec; -typedef struct _filesec *filesec_t; - -typedef enum { - FILESEC_OWNER = 1, - FILESEC_GROUP = 2, - FILESEC_UUID = 3, - FILESEC_MODE = 4, - FILESEC_ACL = 5, - FILESEC_GRPUUID = 6, - - - FILESEC_ACL_RAW = 100, - FILESEC_ACL_ALLOCSIZE = 101 -} filesec_property_t; - - - - - -extern "C" { -int open(const char *, int, ...) __asm("_" "open" ); - -int openat(int, const char *, int, ...) __asm("_" "openat" ) __attribute__((availability(macosx,introduced=10.10))); - -int creat(const char *, mode_t) __asm("_" "creat" ); -int fcntl(int, int, ...) __asm("_" "fcntl" ); - - -int openx_np(const char *, int, filesec_t); - - - - -int open_dprotected_np ( const char *, int, int, int, ...); -int flock(int, int); -filesec_t filesec_init(void); -filesec_t filesec_dup(filesec_t); -void filesec_free(filesec_t); -int filesec_get_property(filesec_t, filesec_property_t, void *); -int filesec_query_property(filesec_t, filesec_property_t, int *); -int filesec_set_property(filesec_t, filesec_property_t, const void *); -int filesec_unset_property(filesec_t, filesec_property_t) __attribute__((availability(macosx,introduced=10.6))); - - - -} - - - - -typedef struct objc_class *Class; - - -struct objc_object { - Class isa __attribute__((deprecated)); -}; - - -typedef struct objc_object *id; - - - -typedef struct objc_selector *SEL; - - - - - -typedef id (*IMP)(id, SEL, ...); -typedef signed char BOOL; -extern "C" __attribute__((visibility("default"))) const char *sel_getName(SEL sel) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) SEL sel_registerName(const char *str) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) const char *object_getClassName(id obj) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) void *object_getIndexedIvars(id obj) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) BOOL sel_isMapped(SEL sel) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) SEL sel_getUid(const char *str) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -typedef const void* objc_objectptr_t; -typedef long NSInteger; -typedef unsigned long NSUInteger; - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSMethodSignature -#define _REWRITER_typedef_NSMethodSignature -typedef struct objc_object NSMethodSignature; -typedef struct {} _objc_exc_NSMethodSignature; -#endif - -#ifndef _REWRITER_typedef_NSInvocation -#define _REWRITER_typedef_NSInvocation -typedef struct objc_object NSInvocation; -typedef struct {} _objc_exc_NSInvocation; -#endif - - -// @protocol NSObject - -// - (BOOL)isEqual:(id)object; -// @property (readonly) NSUInteger hash; - -// @property (readonly) Class superclass; -// - (Class)class __attribute__((availability(swift, unavailable, message="use 'anObject.dynamicType' instead"))); -// - (instancetype)self; - -// - (id)performSelector:(SEL)aSelector; -// - (id)performSelector:(SEL)aSelector withObject:(id)object; -// - (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2; - -// - (BOOL)isProxy; - -// - (BOOL)isKindOfClass:(Class)aClass; -// - (BOOL)isMemberOfClass:(Class)aClass; -// - (BOOL)conformsToProtocol:(Protocol *)aProtocol; - -// - (BOOL)respondsToSelector:(SEL)aSelector; - -// - (instancetype)retain ; -// - (oneway void)release ; -// - (instancetype)autorelease ; -// - (NSUInteger)retainCount ; - -// - (struct _NSZone *)zone ; - -// @property (readonly, copy) NSString *description; -/* @optional */ -// @property (readonly, copy) NSString *debugDescription; - -/* @end */ - - - -__attribute__((availability(macosx,introduced=10.0))) -__attribute__((objc_root_class)) -extern "C" __attribute__((visibility("default"))) - -#ifndef _REWRITER_typedef_NSObject -#define _REWRITER_typedef_NSObject -typedef struct objc_object NSObject; -typedef struct {} _objc_exc_NSObject; -#endif - -struct NSObject_IMPL { - Class isa; -}; - - -// + (void)load; - -// + (void)initialize; -#if 0 -- (instancetype)init - - __attribute__((objc_designated_initializer)) - - ; -#endif - - -// + (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead"))); -// + (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((availability(swift, unavailable, message="use object initializers instead"))); -// + (instancetype)alloc __attribute__((availability(swift, unavailable, message="use object initializers instead"))); -// - (void)dealloc __attribute__((availability(swift, unavailable, message="use 'deinit' to define a de-initializer"))); - -// - (void)finalize; - -// - (id)copy; -// - (id)mutableCopy; - -// + (id)copyWithZone:(struct _NSZone *)zone ; -// + (id)mutableCopyWithZone:(struct _NSZone *)zone ; - -// + (BOOL)instancesRespondToSelector:(SEL)aSelector; -// + (BOOL)conformsToProtocol:(Protocol *)protocol; -// - (IMP)methodForSelector:(SEL)aSelector; -// + (IMP)instanceMethodForSelector:(SEL)aSelector; -// - (void)doesNotRecognizeSelector:(SEL)aSelector; - -// - (id)forwardingTargetForSelector:(SEL)aSelector __attribute__((availability(macosx,introduced=10.5))); -// - (void)forwardInvocation:(NSInvocation *)anInvocation __attribute__((availability(swift, unavailable, message=""))); -// - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector __attribute__((availability(swift, unavailable, message=""))); - -// + (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector __attribute__((availability(swift, unavailable, message=""))); - -// - (BOOL)allowsWeakReference __attribute__((unavailable)); -// - (BOOL)retainWeakReference __attribute__((unavailable)); - -// + (BOOL)isSubclassOfClass:(Class)aClass; - -// + (BOOL)resolveClassMethod:(SEL)sel __attribute__((availability(macosx,introduced=10.5))); -// + (BOOL)resolveInstanceMethod:(SEL)sel __attribute__((availability(macosx,introduced=10.5))); - -// + (NSUInteger)hash; -// + (Class)superclass; -// + (Class)class __attribute__((availability(swift, unavailable, message="use 'aClass.self' instead"))); -// + (NSString *)description; -// + (NSString *)debugDescription; - -/* @end */ - -extern "C" { -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((__visibility__("default"))) -void* -os_retain(void *object); -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((__visibility__("default"))) -void -os_release(void *object); - - - - - -} -typedef void (*dispatch_function_t)(void *); -struct time_value { - integer_t seconds; - integer_t microseconds; -}; - -typedef struct time_value time_value_t; - - - - -typedef int alarm_type_t; -typedef int sleep_type_t; -typedef int clock_id_t; -typedef int clock_flavor_t; -typedef int *clock_attr_t; -typedef int clock_res_t; - - - - -struct mach_timespec { - unsigned int tv_sec; - clock_res_t tv_nsec; -}; -typedef struct mach_timespec mach_timespec_t; -extern "C" { - -struct timespec; -typedef uint64_t dispatch_time_t; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_time_t -dispatch_time(dispatch_time_t when, int64_t delta); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_time_t -dispatch_walltime(const struct timespec *when, int64_t delta); - -} -// @protocol OS_dispatch_object <NSObject> /* @end */ - typedef NSObject/*<OS_dispatch_object>*/ *dispatch_object_t; - - - -static __inline__ __attribute__((__always_inline__)) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -_dispatch_object_validate(dispatch_object_t object) { - void *isa = *(void* volatile*)( void*)object; - (void)isa; -} -typedef void (*dispatch_block_t)(void); - - -extern "C" { -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_retain(dispatch_object_t object); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_release(dispatch_object_t object); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__pure__)) __attribute__((__warn_unused_result__)) -__attribute__((__nothrow__)) -void * -dispatch_get_context(dispatch_object_t object); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nothrow__)) -void -dispatch_set_context(dispatch_object_t object, void *context); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nothrow__)) -void -dispatch_set_finalizer_f(dispatch_object_t object, - dispatch_function_t finalizer); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_suspend(dispatch_object_t object); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_resume(dispatch_object_t object); -__attribute__((__unavailable__)) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -long -dispatch_wait(void *object, dispatch_time_t timeout); -__attribute__((__unavailable__)) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_notify(void *object, dispatch_object_t queue, - dispatch_block_t notification_block); -__attribute__((__unavailable__)) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_cancel(void *object); -__attribute__((__unavailable__)) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) __attribute__((__pure__)) -__attribute__((__nothrow__)) -long -dispatch_testcancel(void *object); -__attribute__((availability(macosx,introduced=10.6,deprecated=10.9))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(2))) __attribute__((__nothrow__)) -__attribute__((__format__(printf,2,3))) -void -dispatch_debug(dispatch_object_t object, const char *message, ...); - -__attribute__((availability(macosx,introduced=10.6,deprecated=10.9))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(2))) __attribute__((__nothrow__)) -__attribute__((__format__(printf,2,0))) -void -dispatch_debugv(dispatch_object_t object, const char *message, va_list ap); - -} -// @protocol OS_dispatch_queue <OS_dispatch_object> /* @end */ - typedef NSObject/*<OS_dispatch_queue>*/ *dispatch_queue_t; - -extern "C" { -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_async(dispatch_queue_t queue, dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) __attribute__((__nothrow__)) -void -dispatch_async_f(dispatch_queue_t queue, - void *context, - dispatch_function_t work); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_sync(dispatch_queue_t queue, dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) __attribute__((__nothrow__)) -void -dispatch_sync_f(dispatch_queue_t queue, - void *context, - dispatch_function_t work); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(3))) __attribute__((__nothrow__)) -void -dispatch_apply(size_t iterations, dispatch_queue_t queue, - void (*block)(size_t)); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(4))) __attribute__((__nothrow__)) -void -dispatch_apply_f(size_t iterations, dispatch_queue_t queue, - void *context, - void (*work)(void *, size_t)); -__attribute__((availability(macosx,introduced=10.6,deprecated=10.9))) -extern __attribute__((visibility("default"))) __attribute__((__pure__)) __attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_queue_t -dispatch_get_current_queue(void); - -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) struct dispatch_queue_s _dispatch_main_q; -static __inline__ __attribute__((__always_inline__)) __attribute__((__const__)) __attribute__((__nothrow__)) -dispatch_queue_t -dispatch_get_main_queue(void) -{ - return (( dispatch_queue_t)&(_dispatch_main_q)); -} -typedef long dispatch_queue_priority_t; - - - - - - - -typedef enum : unsigned int { QOS_CLASS_USER_INTERACTIVE __attribute__((availability(macosx,introduced=10.10))) = 0x21, QOS_CLASS_USER_INITIATED __attribute__((availability(macosx,introduced=10.10))) = 0x19, QOS_CLASS_DEFAULT __attribute__((availability(macosx,introduced=10.10))) = 0x15, QOS_CLASS_UTILITY __attribute__((availability(macosx,introduced=10.10))) = 0x11, QOS_CLASS_BACKGROUND __attribute__((availability(macosx,introduced=10.10))) = 0x09, QOS_CLASS_UNSPECIFIED __attribute__((availability(macosx,introduced=10.10))) = 0x00, } qos_class_t; -extern "C" { -__attribute__((availability(macosx,introduced=10.10))) -qos_class_t -qos_class_self(void); -__attribute__((availability(macosx,introduced=10.10))) -qos_class_t -qos_class_main(void); - -} -typedef qos_class_t dispatch_qos_class_t; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__const__)) __attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_queue_t -dispatch_get_global_queue(long identifier, unsigned long flags); - - - - - - - -// @protocol OS_dispatch_queue_attr <OS_dispatch_object> /* @end */ - typedef NSObject/*<OS_dispatch_queue_attr>*/ *dispatch_queue_attr_t; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -struct dispatch_queue_attr_s _dispatch_queue_attr_concurrent; -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__pure__)) __attribute__((__nothrow__)) -dispatch_queue_attr_t -dispatch_queue_attr_make_with_qos_class(dispatch_queue_attr_t attr, - dispatch_qos_class_t qos_class, int relative_priority); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -__attribute__((__nothrow__)) -dispatch_queue_t -dispatch_queue_create(const char *label, dispatch_queue_attr_t attr); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__pure__)) __attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -const char * -dispatch_queue_get_label(dispatch_queue_t queue); -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -dispatch_qos_class_t -dispatch_queue_get_qos_class(dispatch_queue_t queue, - int *relative_priority_ptr); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nothrow__)) -void -dispatch_set_target_queue(dispatch_object_t object, dispatch_queue_t queue); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nothrow__)) __attribute__((__noreturn__)) -void -dispatch_main(void); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(2))) __attribute__((__nonnull__(3))) __attribute__((__nothrow__)) -void -dispatch_after(dispatch_time_t when, - dispatch_queue_t queue, - dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(2))) __attribute__((__nonnull__(4))) __attribute__((__nothrow__)) -void -dispatch_after_f(dispatch_time_t when, - dispatch_queue_t queue, - void *context, - dispatch_function_t work); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) __attribute__((__nothrow__)) -void -dispatch_barrier_async_f(dispatch_queue_t queue, - void *context, - dispatch_function_t work); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_barrier_sync(dispatch_queue_t queue, dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) __attribute__((__nothrow__)) -void -dispatch_barrier_sync_f(dispatch_queue_t queue, - void *context, - dispatch_function_t work); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_queue_set_specific(dispatch_queue_t queue, const void *key, - void *context, dispatch_function_t destructor); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__pure__)) __attribute__((__warn_unused_result__)) -__attribute__((__nothrow__)) -void * -dispatch_queue_get_specific(dispatch_queue_t queue, const void *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__pure__)) __attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -void * -dispatch_get_specific(const void *key); - -} -extern "C" { -typedef enum : unsigned long { DISPATCH_BLOCK_BARRIER __attribute__((availability(macosx,introduced=10.10))) = 0x1, DISPATCH_BLOCK_DETACHED __attribute__((availability(macosx,introduced=10.10))) = 0x2, DISPATCH_BLOCK_ASSIGN_CURRENT __attribute__((availability(macosx,introduced=10.10))) = 0x4, DISPATCH_BLOCK_NO_QOS_CLASS __attribute__((availability(macosx,introduced=10.10))) = 0x8, DISPATCH_BLOCK_INHERIT_QOS_CLASS __attribute__((availability(macosx,introduced=10.10))) = 0x10, DISPATCH_BLOCK_ENFORCE_QOS_CLASS __attribute__((availability(macosx,introduced=10.10))) = 0x20, } dispatch_block_flags_t; -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(2))) __attribute__((__ns_returns_retained__)) -__attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_block_t -dispatch_block_create(dispatch_block_flags_t flags, dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(4))) __attribute__((__ns_returns_retained__)) -__attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_block_t -dispatch_block_create_with_qos_class(dispatch_block_flags_t flags, - dispatch_qos_class_t qos_class, int relative_priority, - dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(2))) __attribute__((__nothrow__)) -void -dispatch_block_perform(dispatch_block_flags_t flags, dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -long -dispatch_block_wait(dispatch_block_t block, dispatch_time_t timeout); -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_block_notify(dispatch_block_t block, dispatch_queue_t queue, - dispatch_block_t notification_block); -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_block_cancel(dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) __attribute__((__pure__)) -__attribute__((__nothrow__)) -long -dispatch_block_testcancel(dispatch_block_t block); - -} -typedef int kern_return_t; -typedef natural_t mach_msg_timeout_t; -typedef unsigned int mach_msg_bits_t; -typedef natural_t mach_msg_size_t; -typedef integer_t mach_msg_id_t; - - - - -typedef unsigned int mach_msg_type_name_t; -typedef unsigned int mach_msg_copy_options_t; -typedef unsigned int mach_msg_descriptor_type_t; - - - - - - -#pragma pack(4) - -typedef struct -{ - natural_t pad1; - mach_msg_size_t pad2; - unsigned int pad3 : 24; - mach_msg_descriptor_type_t type : 8; -} mach_msg_type_descriptor_t; - -typedef struct -{ - mach_port_t name; - - mach_msg_size_t pad1; - unsigned int pad2 : 16; - mach_msg_type_name_t disposition : 8; - mach_msg_descriptor_type_t type : 8; -} mach_msg_port_descriptor_t; - -typedef struct -{ - uint32_t address; - mach_msg_size_t size; - boolean_t deallocate: 8; - mach_msg_copy_options_t copy: 8; - unsigned int pad1: 8; - mach_msg_descriptor_type_t type: 8; -} mach_msg_ool_descriptor32_t; - -typedef struct -{ - uint64_t address; - boolean_t deallocate: 8; - mach_msg_copy_options_t copy: 8; - unsigned int pad1: 8; - mach_msg_descriptor_type_t type: 8; - mach_msg_size_t size; -} mach_msg_ool_descriptor64_t; - -typedef struct -{ - void* address; - - - - boolean_t deallocate: 8; - mach_msg_copy_options_t copy: 8; - unsigned int pad1: 8; - mach_msg_descriptor_type_t type: 8; - - mach_msg_size_t size; - -} mach_msg_ool_descriptor_t; - -typedef struct -{ - uint32_t address; - mach_msg_size_t count; - boolean_t deallocate: 8; - mach_msg_copy_options_t copy: 8; - mach_msg_type_name_t disposition : 8; - mach_msg_descriptor_type_t type : 8; -} mach_msg_ool_ports_descriptor32_t; - -typedef struct -{ - uint64_t address; - boolean_t deallocate: 8; - mach_msg_copy_options_t copy: 8; - mach_msg_type_name_t disposition : 8; - mach_msg_descriptor_type_t type : 8; - mach_msg_size_t count; -} mach_msg_ool_ports_descriptor64_t; - -typedef struct -{ - void* address; - - - - boolean_t deallocate: 8; - mach_msg_copy_options_t copy: 8; - mach_msg_type_name_t disposition : 8; - mach_msg_descriptor_type_t type : 8; - - mach_msg_size_t count; - -} mach_msg_ool_ports_descriptor_t; - - - - - - -typedef union -{ - mach_msg_port_descriptor_t port; - mach_msg_ool_descriptor_t out_of_line; - mach_msg_ool_ports_descriptor_t ool_ports; - mach_msg_type_descriptor_t type; -} mach_msg_descriptor_t; - -typedef struct -{ - mach_msg_size_t msgh_descriptor_count; -} mach_msg_body_t; - - - - -typedef struct -{ - mach_msg_bits_t msgh_bits; - mach_msg_size_t msgh_size; - mach_port_t msgh_remote_port; - mach_port_t msgh_local_port; - mach_port_name_t msgh_voucher_port; - mach_msg_id_t msgh_id; -} mach_msg_header_t; - - - - -typedef struct -{ - mach_msg_header_t header; - mach_msg_body_t body; -} mach_msg_base_t; - -typedef unsigned int mach_msg_trailer_type_t; - - - -typedef unsigned int mach_msg_trailer_size_t; -typedef char *mach_msg_trailer_info_t; - -typedef struct -{ - mach_msg_trailer_type_t msgh_trailer_type; - mach_msg_trailer_size_t msgh_trailer_size; -} mach_msg_trailer_t; -typedef struct -{ - mach_msg_trailer_type_t msgh_trailer_type; - mach_msg_trailer_size_t msgh_trailer_size; - mach_port_seqno_t msgh_seqno; -} mach_msg_seqno_trailer_t; - -typedef struct -{ - unsigned int val[2]; -} security_token_t; - -typedef struct -{ - mach_msg_trailer_type_t msgh_trailer_type; - mach_msg_trailer_size_t msgh_trailer_size; - mach_port_seqno_t msgh_seqno; - security_token_t msgh_sender; -} mach_msg_security_trailer_t; -typedef struct -{ - unsigned int val[8]; -} audit_token_t; - -typedef struct -{ - mach_msg_trailer_type_t msgh_trailer_type; - mach_msg_trailer_size_t msgh_trailer_size; - mach_port_seqno_t msgh_seqno; - security_token_t msgh_sender; - audit_token_t msgh_audit; -} mach_msg_audit_trailer_t; - -typedef struct -{ - mach_msg_trailer_type_t msgh_trailer_type; - mach_msg_trailer_size_t msgh_trailer_size; - mach_port_seqno_t msgh_seqno; - security_token_t msgh_sender; - audit_token_t msgh_audit; - mach_port_context_t msgh_context; -} mach_msg_context_trailer_t; - - - -typedef struct -{ - mach_port_name_t sender; -} msg_labels_t; - - - - - - -typedef struct -{ - mach_msg_trailer_type_t msgh_trailer_type; - mach_msg_trailer_size_t msgh_trailer_size; - mach_port_seqno_t msgh_seqno; - security_token_t msgh_sender; - audit_token_t msgh_audit; - mach_port_context_t msgh_context; - int msgh_ad; - msg_labels_t msgh_labels; -} mach_msg_mac_trailer_t; -typedef mach_msg_mac_trailer_t mach_msg_max_trailer_t; -typedef mach_msg_security_trailer_t mach_msg_format_0_trailer_t; - - - - - - - -extern security_token_t KERNEL_SECURITY_TOKEN; - - -extern audit_token_t KERNEL_AUDIT_TOKEN; - -typedef integer_t mach_msg_options_t; - -typedef struct -{ - mach_msg_header_t header; -} mach_msg_empty_send_t; - -typedef struct -{ - mach_msg_header_t header; - mach_msg_trailer_t trailer; -} mach_msg_empty_rcv_t; - -typedef union -{ - mach_msg_empty_send_t send; - mach_msg_empty_rcv_t rcv; -} mach_msg_empty_t; - -#pragma pack() -typedef natural_t mach_msg_type_size_t; -typedef natural_t mach_msg_type_number_t; -typedef integer_t mach_msg_option_t; -typedef kern_return_t mach_msg_return_t; -extern "C" { -__attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) -extern mach_msg_return_t mach_msg_overwrite( - mach_msg_header_t *msg, - mach_msg_option_t option, - mach_msg_size_t send_size, - mach_msg_size_t rcv_size, - mach_port_name_t rcv_name, - mach_msg_timeout_t timeout, - mach_port_name_t notify, - mach_msg_header_t *rcv_msg, - mach_msg_size_t rcv_limit); -__attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) -extern mach_msg_return_t mach_msg( - mach_msg_header_t *msg, - mach_msg_option_t option, - mach_msg_size_t send_size, - mach_msg_size_t rcv_size, - mach_port_name_t rcv_name, - mach_msg_timeout_t timeout, - mach_port_name_t notify); - - - - - - - -__attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) -extern kern_return_t mach_voucher_deallocate( - mach_port_name_t voucher); - - -} -// @protocol OS_dispatch_source <OS_dispatch_object> /* @end */ - typedef NSObject/*<OS_dispatch_source>*/ *dispatch_source_t; - -extern "C" { -typedef const struct dispatch_source_type_s *dispatch_source_type_t; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_data_add; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_data_or; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_mach_send; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_mach_recv; -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_memorypressure; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_proc; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_read; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_signal; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_timer; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_vnode; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) const struct dispatch_source_type_s _dispatch_source_type_write; -typedef unsigned long dispatch_source_mach_send_flags_t; -typedef unsigned long dispatch_source_memorypressure_flags_t; -typedef unsigned long dispatch_source_proc_flags_t; -typedef unsigned long dispatch_source_vnode_flags_t; -typedef unsigned long dispatch_source_timer_flags_t; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -__attribute__((__nothrow__)) -dispatch_source_t -dispatch_source_create(dispatch_source_type_t type, - uintptr_t handle, - unsigned long mask, - dispatch_queue_t queue); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_source_set_event_handler(dispatch_source_t source, - dispatch_block_t handler); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_source_set_event_handler_f(dispatch_source_t source, - dispatch_function_t handler); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_source_set_cancel_handler(dispatch_source_t source, - dispatch_block_t handler); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_source_set_cancel_handler_f(dispatch_source_t source, - dispatch_function_t handler); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_source_cancel(dispatch_source_t source); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) __attribute__((__pure__)) -__attribute__((__nothrow__)) -long -dispatch_source_testcancel(dispatch_source_t source); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) __attribute__((__pure__)) -__attribute__((__nothrow__)) -uintptr_t -dispatch_source_get_handle(dispatch_source_t source); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) __attribute__((__pure__)) -__attribute__((__nothrow__)) -unsigned long -dispatch_source_get_mask(dispatch_source_t source); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) __attribute__((__pure__)) -__attribute__((__nothrow__)) -unsigned long -dispatch_source_get_data(dispatch_source_t source); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_source_merge_data(dispatch_source_t source, unsigned long value); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_source_set_timer(dispatch_source_t source, - dispatch_time_t start, - uint64_t interval, - uint64_t leeway); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_source_set_registration_handler(dispatch_source_t source, - dispatch_block_t handler); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_source_set_registration_handler_f(dispatch_source_t source, - dispatch_function_t handler); - -} -// @protocol OS_dispatch_group <OS_dispatch_object> /* @end */ - typedef NSObject/*<OS_dispatch_group>*/ *dispatch_group_t; - -extern "C" { -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -__attribute__((__nothrow__)) -dispatch_group_t -dispatch_group_create(void); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_group_async(dispatch_group_t group, - dispatch_queue_t queue, - dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) __attribute__((__nonnull__(4))) -__attribute__((__nothrow__)) -void -dispatch_group_async_f(dispatch_group_t group, - dispatch_queue_t queue, - void *context, - dispatch_function_t work); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -long -dispatch_group_wait(dispatch_group_t group, dispatch_time_t timeout); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_group_notify(dispatch_group_t group, - dispatch_queue_t queue, - dispatch_block_t block); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) __attribute__((__nonnull__(4))) -__attribute__((__nothrow__)) -void -dispatch_group_notify_f(dispatch_group_t group, - dispatch_queue_t queue, - void *context, - dispatch_function_t work); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_group_enter(dispatch_group_t group); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_group_leave(dispatch_group_t group); - -} -// @protocol OS_dispatch_semaphore <OS_dispatch_object> /* @end */ - typedef NSObject/*<OS_dispatch_semaphore>*/ *dispatch_semaphore_t; - -extern "C" { -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -__attribute__((__nothrow__)) -dispatch_semaphore_t -dispatch_semaphore_create(long value); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -long -dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout); -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -long -dispatch_semaphore_signal(dispatch_semaphore_t dsema); - -} -extern "C" { -typedef long dispatch_once_t; -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_once(dispatch_once_t *predicate, dispatch_block_t block); - -static __inline__ __attribute__((__always_inline__)) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -_dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) -{ - if (__builtin_expect((*predicate), (~0l)) != ~0l) { - dispatch_once(predicate, block); - } -} - - - - -__attribute__((availability(macosx,introduced=10.6))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) __attribute__((__nothrow__)) -void -dispatch_once_f(dispatch_once_t *predicate, void *context, - dispatch_function_t function); - -static __inline__ __attribute__((__always_inline__)) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) -__attribute__((__nothrow__)) -void -_dispatch_once_f(dispatch_once_t *predicate, void *context, - dispatch_function_t function) -{ - if (__builtin_expect((*predicate), (~0l)) != ~0l) { - dispatch_once_f(predicate, context, function); - } -} - - - -} -extern "C" { -// @protocol OS_dispatch_data <OS_dispatch_object> /* @end */ - typedef NSObject/*<OS_dispatch_data>*/ *dispatch_data_t; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) struct dispatch_data_s _dispatch_data_empty; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) const dispatch_block_t _dispatch_data_destructor_free; - - - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) const dispatch_block_t _dispatch_data_destructor_munmap; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_data_t -dispatch_data_create(const void *buffer, - size_t size, - dispatch_queue_t queue, - dispatch_block_t destructor); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__pure__)) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -size_t -dispatch_data_get_size(dispatch_data_t data); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__ns_returns_retained__)) -__attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_data_t -dispatch_data_create_map(dispatch_data_t data, - const void **buffer_ptr, - size_t *size_ptr); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__ns_returns_retained__)) -__attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_data_t -dispatch_data_create_concat(dispatch_data_t data1, dispatch_data_t data2); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__ns_returns_retained__)) -__attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_data_t -dispatch_data_create_subrange(dispatch_data_t data, - size_t offset, - size_t length); -typedef bool (*dispatch_data_applier_t)(dispatch_data_t region, - size_t offset, - const void *buffer, - size_t size); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -bool -dispatch_data_apply(dispatch_data_t data, dispatch_data_applier_t applier); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) __attribute__((__ns_returns_retained__)) -__attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_data_t -dispatch_data_copy_region(dispatch_data_t data, - size_t location, - size_t *offset_ptr); - -} -extern "C" { -typedef int dispatch_fd_t; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(3))) __attribute__((__nonnull__(4))) __attribute__((__nothrow__)) -void -dispatch_read(dispatch_fd_t fd, - size_t length, - dispatch_queue_t queue, - void (*handler)(dispatch_data_t data, int error)); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(2))) __attribute__((__nonnull__(3))) __attribute__((__nonnull__(4))) -__attribute__((__nothrow__)) -void -dispatch_write(dispatch_fd_t fd, - dispatch_data_t data, - dispatch_queue_t queue, - void (*handler)(dispatch_data_t data, int error)); -// @protocol OS_dispatch_io <OS_dispatch_object> /* @end */ - typedef NSObject/*<OS_dispatch_io>*/ *dispatch_io_t; -typedef unsigned long dispatch_io_type_t; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -__attribute__((__nothrow__)) -dispatch_io_t -dispatch_io_create(dispatch_io_type_t type, - dispatch_fd_t fd, - dispatch_queue_t queue, - void (*cleanup_handler)(int error)); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(2))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) -__attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_io_t -dispatch_io_create_with_path(dispatch_io_type_t type, - const char *path, int oflag, mode_t mode, - dispatch_queue_t queue, - void (*cleanup_handler)(int error)); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(2))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) -__attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_io_t -dispatch_io_create_with_io(dispatch_io_type_t type, - dispatch_io_t io, - dispatch_queue_t queue, - void (*cleanup_handler)(int error)); -typedef void (*dispatch_io_handler_t)(bool done, dispatch_data_t data, - int error); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(4))) __attribute__((__nonnull__(5))) -__attribute__((__nothrow__)) -void -dispatch_io_read(dispatch_io_t channel, - off_t offset, - size_t length, - dispatch_queue_t queue, - dispatch_io_handler_t io_handler); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) __attribute__((__nonnull__(4))) -__attribute__((__nonnull__(5))) __attribute__((__nothrow__)) -void -dispatch_io_write(dispatch_io_t channel, - off_t offset, - dispatch_data_t data, - dispatch_queue_t queue, - dispatch_io_handler_t io_handler); -typedef unsigned long dispatch_io_close_flags_t; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_io_close(dispatch_io_t channel, dispatch_io_close_flags_t flags); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__)) -void -dispatch_io_barrier(dispatch_io_t channel, dispatch_block_t barrier); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) __attribute__((__nothrow__)) -dispatch_fd_t -dispatch_io_get_descriptor(dispatch_io_t channel); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_io_set_high_water(dispatch_io_t channel, size_t high_water); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_io_set_low_water(dispatch_io_t channel, size_t low_water); -typedef unsigned long dispatch_io_interval_flags_t; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nothrow__)) -void -dispatch_io_set_interval(dispatch_io_t channel, - uint64_t interval, - dispatch_io_interval_flags_t flags); - -} - - -extern "C" { - -typedef CFIndex CFStreamStatus; enum { - kCFStreamStatusNotOpen = 0, - kCFStreamStatusOpening, - kCFStreamStatusOpen, - kCFStreamStatusReading, - kCFStreamStatusWriting, - kCFStreamStatusAtEnd, - kCFStreamStatusClosed, - kCFStreamStatusError -}; - -typedef CFOptionFlags CFStreamEventType; enum { - kCFStreamEventNone = 0, - kCFStreamEventOpenCompleted = 1, - kCFStreamEventHasBytesAvailable = 2, - kCFStreamEventCanAcceptBytes = 4, - kCFStreamEventErrorOccurred = 8, - kCFStreamEventEndEncountered = 16 -}; - -typedef struct { - CFIndex version; - void *info; - void *(*retain)(void *info); - void (*release)(void *info); - CFStringRef (*copyDescription)(void *info); -} CFStreamClientContext; - -typedef struct __attribute__((objc_bridge_mutable(NSInputStream))) __CFReadStream * CFReadStreamRef; -typedef struct __attribute__((objc_bridge_mutable(NSOutputStream))) __CFWriteStream * CFWriteStreamRef; - -typedef void (*CFReadStreamClientCallBack)(CFReadStreamRef stream, CFStreamEventType type, void *clientCallBackInfo); -typedef void (*CFWriteStreamClientCallBack)(CFWriteStreamRef stream, CFStreamEventType type, void *clientCallBackInfo); - -extern -CFTypeID CFReadStreamGetTypeID(void); -extern -CFTypeID CFWriteStreamGetTypeID(void); - - - - -extern -const CFStringRef kCFStreamPropertyDataWritten; - - -extern -CFReadStreamRef CFReadStreamCreateWithBytesNoCopy(CFAllocatorRef alloc, const UInt8 *bytes, CFIndex length, CFAllocatorRef bytesDeallocator); - - -extern -CFWriteStreamRef CFWriteStreamCreateWithBuffer(CFAllocatorRef alloc, UInt8 *buffer, CFIndex bufferCapacity); - - -extern -CFWriteStreamRef CFWriteStreamCreateWithAllocatedBuffers(CFAllocatorRef alloc, CFAllocatorRef bufferAllocator); - - -extern -CFReadStreamRef CFReadStreamCreateWithFile(CFAllocatorRef alloc, CFURLRef fileURL); -extern -CFWriteStreamRef CFWriteStreamCreateWithFile(CFAllocatorRef alloc, CFURLRef fileURL); - -extern -void CFStreamCreateBoundPair(CFAllocatorRef alloc, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream, CFIndex transferBufferSize); - - - -extern -const CFStringRef kCFStreamPropertyAppendToFile; - -extern -const CFStringRef kCFStreamPropertyFileCurrentOffset; - - - - - -extern -const CFStringRef kCFStreamPropertySocketNativeHandle; - - -extern -const CFStringRef kCFStreamPropertySocketRemoteHostName; - - -extern -const CFStringRef kCFStreamPropertySocketRemotePortNumber; - - - -extern -void CFStreamCreatePairWithSocket(CFAllocatorRef alloc, CFSocketNativeHandle sock, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream); -extern -void CFStreamCreatePairWithSocketToHost(CFAllocatorRef alloc, CFStringRef host, UInt32 port, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream); -extern -void CFStreamCreatePairWithPeerSocketSignature(CFAllocatorRef alloc, const CFSocketSignature *signature, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream); - - - - -extern -CFStreamStatus CFReadStreamGetStatus(CFReadStreamRef stream); -extern -CFStreamStatus CFWriteStreamGetStatus(CFWriteStreamRef stream); - - -extern -CFErrorRef CFReadStreamCopyError(CFReadStreamRef stream) __attribute__((availability(macosx,introduced=10_5))); -extern -CFErrorRef CFWriteStreamCopyError(CFWriteStreamRef stream) __attribute__((availability(macosx,introduced=10_5))); - - - - - - -extern -Boolean CFReadStreamOpen(CFReadStreamRef stream); -extern -Boolean CFWriteStreamOpen(CFWriteStreamRef stream); - - - - -extern -void CFReadStreamClose(CFReadStreamRef stream); -extern -void CFWriteStreamClose(CFWriteStreamRef stream); - - - -extern -Boolean CFReadStreamHasBytesAvailable(CFReadStreamRef stream); -extern -CFIndex CFReadStreamRead(CFReadStreamRef stream, UInt8 *buffer, CFIndex bufferLength); -extern -const UInt8 *CFReadStreamGetBuffer(CFReadStreamRef stream, CFIndex maxBytesToRead, CFIndex *numBytesRead); - - - -extern -Boolean CFWriteStreamCanAcceptBytes(CFWriteStreamRef stream); - - - - - - -extern -CFIndex CFWriteStreamWrite(CFWriteStreamRef stream, const UInt8 *buffer, CFIndex bufferLength); -extern -CFTypeRef CFReadStreamCopyProperty(CFReadStreamRef stream, CFStringRef propertyName); -extern -CFTypeRef CFWriteStreamCopyProperty(CFWriteStreamRef stream, CFStringRef propertyName); - - - -extern -Boolean CFReadStreamSetProperty(CFReadStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue); -extern -Boolean CFWriteStreamSetProperty(CFWriteStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue); -extern -Boolean CFReadStreamSetClient(CFReadStreamRef stream, CFOptionFlags streamEvents, CFReadStreamClientCallBack clientCB, CFStreamClientContext *clientContext); -extern -Boolean CFWriteStreamSetClient(CFWriteStreamRef stream, CFOptionFlags streamEvents, CFWriteStreamClientCallBack clientCB, CFStreamClientContext *clientContext); - -extern -void CFReadStreamScheduleWithRunLoop(CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode); -extern -void CFWriteStreamScheduleWithRunLoop(CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode); - -extern -void CFReadStreamUnscheduleFromRunLoop(CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode); -extern -void CFWriteStreamUnscheduleFromRunLoop(CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode); -extern -void CFReadStreamSetDispatchQueue(CFReadStreamRef stream, dispatch_queue_t q) __attribute__((availability(macosx,introduced=10_9))); - -extern -void CFWriteStreamSetDispatchQueue(CFWriteStreamRef stream, dispatch_queue_t q) __attribute__((availability(macosx,introduced=10_9))); - - - - - - -extern -dispatch_queue_t CFReadStreamCopyDispatchQueue(CFReadStreamRef stream) __attribute__((availability(macosx,introduced=10_9))); - -extern -dispatch_queue_t CFWriteStreamCopyDispatchQueue(CFWriteStreamRef stream) __attribute__((availability(macosx,introduced=10_9))); - - -typedef CFIndex CFStreamErrorDomain; enum { - kCFStreamErrorDomainCustom = -1L, - kCFStreamErrorDomainPOSIX = 1, - kCFStreamErrorDomainMacOSStatus -}; - -typedef struct { - CFIndex domain; - SInt32 error; -} CFStreamError; -extern -CFStreamError CFReadStreamGetError(CFReadStreamRef stream); -extern -CFStreamError CFWriteStreamGetError(CFWriteStreamRef stream); - - -} - - - -extern "C" { - -typedef CFOptionFlags CFPropertyListMutabilityOptions; enum { - kCFPropertyListImmutable = 0, - kCFPropertyListMutableContainers, - kCFPropertyListMutableContainersAndLeaves -}; -extern -CFPropertyListRef CFPropertyListCreateFromXMLData(CFAllocatorRef allocator, CFDataRef xmlData, CFOptionFlags mutabilityOption, CFStringRef *errorString) __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use CFPropertyListCreateWithData instead."))); -extern -CFDataRef CFPropertyListCreateXMLData(CFAllocatorRef allocator, CFPropertyListRef propertyList) __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use CFPropertyListCreateData instead."))); -extern -CFPropertyListRef CFPropertyListCreateDeepCopy(CFAllocatorRef allocator, CFPropertyListRef propertyList, CFOptionFlags mutabilityOption); - -typedef CFIndex CFPropertyListFormat; enum { - kCFPropertyListOpenStepFormat = 1, - kCFPropertyListXMLFormat_v1_0 = 100, - kCFPropertyListBinaryFormat_v1_0 = 200 -}; - - - - - - -extern -Boolean CFPropertyListIsValid(CFPropertyListRef plist, CFPropertyListFormat format); -extern -CFIndex CFPropertyListWriteToStream(CFPropertyListRef propertyList, CFWriteStreamRef stream, CFPropertyListFormat format, CFStringRef *errorString) __attribute__((availability(macosx,introduced=10_2,deprecated=10_10,message="" "Use CFPropertyListWrite instead."))); -extern -CFPropertyListRef CFPropertyListCreateFromStream(CFAllocatorRef allocator, CFReadStreamRef stream, CFIndex streamLength, CFOptionFlags mutabilityOption, CFPropertyListFormat *format, CFStringRef *errorString) __attribute__((availability(macosx,introduced=10_2,deprecated=10_10,message="" "Use CFPropertyListCreateWithStream instead."))); - - - - - - -enum { - kCFPropertyListReadCorruptError = 3840, - kCFPropertyListReadUnknownVersionError = 3841, - kCFPropertyListReadStreamError = 3842, - kCFPropertyListWriteStreamError = 3851, -} __attribute__((availability(macosx,introduced=10_6))); - - - -extern -CFPropertyListRef CFPropertyListCreateWithData(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags options, CFPropertyListFormat *format, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); - - - - - -extern -CFPropertyListRef CFPropertyListCreateWithStream(CFAllocatorRef allocator, CFReadStreamRef stream, CFIndex streamLength, CFOptionFlags options, CFPropertyListFormat *format, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); - - - -extern -CFIndex CFPropertyListWrite(CFPropertyListRef propertyList, CFWriteStreamRef stream, CFPropertyListFormat format, CFOptionFlags options, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); - - - - - -extern -CFDataRef CFPropertyListCreateData(CFAllocatorRef allocator, CFPropertyListRef propertyList, CFPropertyListFormat format, CFOptionFlags options, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_6))); - - - -} -extern "C" { -typedef const void * (*CFSetRetainCallBack)(CFAllocatorRef allocator, const void *value); - - - - - - - -typedef void (*CFSetReleaseCallBack)(CFAllocatorRef allocator, const void *value); - - - - - - - -typedef CFStringRef (*CFSetCopyDescriptionCallBack)(const void *value); -typedef Boolean (*CFSetEqualCallBack)(const void *value1, const void *value2); - - - - - - - -typedef CFHashCode (*CFSetHashCallBack)(const void *value); -typedef struct { - CFIndex version; - CFSetRetainCallBack retain; - CFSetReleaseCallBack release; - CFSetCopyDescriptionCallBack copyDescription; - CFSetEqualCallBack equal; - CFSetHashCallBack hash; -} CFSetCallBacks; - - - - - - -extern -const CFSetCallBacks kCFTypeSetCallBacks; - - - - - - - -extern -const CFSetCallBacks kCFCopyStringSetCallBacks; -typedef void (*CFSetApplierFunction)(const void *value, void *context); - - - - - -typedef const struct __attribute__((objc_bridge(NSSet))) __CFSet * CFSetRef; - - - - - -typedef struct __attribute__((objc_bridge_mutable(NSMutableSet))) __CFSet * CFMutableSetRef; - - - - - -extern -CFTypeID CFSetGetTypeID(void); -extern -CFSetRef CFSetCreate(CFAllocatorRef allocator, const void **values, CFIndex numValues, const CFSetCallBacks *callBacks); -extern -CFSetRef CFSetCreateCopy(CFAllocatorRef allocator, CFSetRef theSet); -extern -CFMutableSetRef CFSetCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFSetCallBacks *callBacks); -extern -CFMutableSetRef CFSetCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFSetRef theSet); -extern -CFIndex CFSetGetCount(CFSetRef theSet); -extern -CFIndex CFSetGetCountOfValue(CFSetRef theSet, const void *value); -extern -Boolean CFSetContainsValue(CFSetRef theSet, const void *value); -extern -const void *CFSetGetValue(CFSetRef theSet, const void *value); -extern -Boolean CFSetGetValueIfPresent(CFSetRef theSet, const void *candidate, const void **value); -extern -void CFSetGetValues(CFSetRef theSet, const void **values); -extern -void CFSetApplyFunction(CFSetRef theSet, CFSetApplierFunction applier, void *context); -extern -void CFSetAddValue(CFMutableSetRef theSet, const void *value); -extern -void CFSetReplaceValue(CFMutableSetRef theSet, const void *value); -extern -void CFSetSetValue(CFMutableSetRef theSet, const void *value); -extern -void CFSetRemoveValue(CFMutableSetRef theSet, const void *value); -extern -void CFSetRemoveAllValues(CFMutableSetRef theSet); - -} - -extern "C" { - -typedef CFIndex CFStringEncodings; enum { - - kCFStringEncodingMacJapanese = 1, - kCFStringEncodingMacChineseTrad = 2, - kCFStringEncodingMacKorean = 3, - kCFStringEncodingMacArabic = 4, - kCFStringEncodingMacHebrew = 5, - kCFStringEncodingMacGreek = 6, - kCFStringEncodingMacCyrillic = 7, - kCFStringEncodingMacDevanagari = 9, - kCFStringEncodingMacGurmukhi = 10, - kCFStringEncodingMacGujarati = 11, - kCFStringEncodingMacOriya = 12, - kCFStringEncodingMacBengali = 13, - kCFStringEncodingMacTamil = 14, - kCFStringEncodingMacTelugu = 15, - kCFStringEncodingMacKannada = 16, - kCFStringEncodingMacMalayalam = 17, - kCFStringEncodingMacSinhalese = 18, - kCFStringEncodingMacBurmese = 19, - kCFStringEncodingMacKhmer = 20, - kCFStringEncodingMacThai = 21, - kCFStringEncodingMacLaotian = 22, - kCFStringEncodingMacGeorgian = 23, - kCFStringEncodingMacArmenian = 24, - kCFStringEncodingMacChineseSimp = 25, - kCFStringEncodingMacTibetan = 26, - kCFStringEncodingMacMongolian = 27, - kCFStringEncodingMacEthiopic = 28, - kCFStringEncodingMacCentralEurRoman = 29, - kCFStringEncodingMacVietnamese = 30, - kCFStringEncodingMacExtArabic = 31, - - kCFStringEncodingMacSymbol = 33, - kCFStringEncodingMacDingbats = 34, - kCFStringEncodingMacTurkish = 35, - kCFStringEncodingMacCroatian = 36, - kCFStringEncodingMacIcelandic = 37, - kCFStringEncodingMacRomanian = 38, - kCFStringEncodingMacCeltic = 39, - kCFStringEncodingMacGaelic = 40, - - kCFStringEncodingMacFarsi = 0x8C, - - kCFStringEncodingMacUkrainian = 0x98, - - kCFStringEncodingMacInuit = 0xEC, - kCFStringEncodingMacVT100 = 0xFC, - - kCFStringEncodingMacHFS = 0xFF, - - - - - - - kCFStringEncodingISOLatin2 = 0x0202, - kCFStringEncodingISOLatin3 = 0x0203, - kCFStringEncodingISOLatin4 = 0x0204, - kCFStringEncodingISOLatinCyrillic = 0x0205, - kCFStringEncodingISOLatinArabic = 0x0206, - kCFStringEncodingISOLatinGreek = 0x0207, - kCFStringEncodingISOLatinHebrew = 0x0208, - kCFStringEncodingISOLatin5 = 0x0209, - kCFStringEncodingISOLatin6 = 0x020A, - kCFStringEncodingISOLatinThai = 0x020B, - kCFStringEncodingISOLatin7 = 0x020D, - kCFStringEncodingISOLatin8 = 0x020E, - kCFStringEncodingISOLatin9 = 0x020F, - kCFStringEncodingISOLatin10 = 0x0210, - - - kCFStringEncodingDOSLatinUS = 0x0400, - kCFStringEncodingDOSGreek = 0x0405, - kCFStringEncodingDOSBalticRim = 0x0406, - kCFStringEncodingDOSLatin1 = 0x0410, - kCFStringEncodingDOSGreek1 = 0x0411, - kCFStringEncodingDOSLatin2 = 0x0412, - kCFStringEncodingDOSCyrillic = 0x0413, - kCFStringEncodingDOSTurkish = 0x0414, - kCFStringEncodingDOSPortuguese = 0x0415, - kCFStringEncodingDOSIcelandic = 0x0416, - kCFStringEncodingDOSHebrew = 0x0417, - kCFStringEncodingDOSCanadianFrench = 0x0418, - kCFStringEncodingDOSArabic = 0x0419, - kCFStringEncodingDOSNordic = 0x041A, - kCFStringEncodingDOSRussian = 0x041B, - kCFStringEncodingDOSGreek2 = 0x041C, - kCFStringEncodingDOSThai = 0x041D, - kCFStringEncodingDOSJapanese = 0x0420, - kCFStringEncodingDOSChineseSimplif = 0x0421, - kCFStringEncodingDOSKorean = 0x0422, - kCFStringEncodingDOSChineseTrad = 0x0423, - - kCFStringEncodingWindowsLatin2 = 0x0501, - kCFStringEncodingWindowsCyrillic = 0x0502, - kCFStringEncodingWindowsGreek = 0x0503, - kCFStringEncodingWindowsLatin5 = 0x0504, - kCFStringEncodingWindowsHebrew = 0x0505, - kCFStringEncodingWindowsArabic = 0x0506, - kCFStringEncodingWindowsBalticRim = 0x0507, - kCFStringEncodingWindowsVietnamese = 0x0508, - kCFStringEncodingWindowsKoreanJohab = 0x0510, - - - - kCFStringEncodingANSEL = 0x0601, - kCFStringEncodingJIS_X0201_76 = 0x0620, - kCFStringEncodingJIS_X0208_83 = 0x0621, - kCFStringEncodingJIS_X0208_90 = 0x0622, - kCFStringEncodingJIS_X0212_90 = 0x0623, - kCFStringEncodingJIS_C6226_78 = 0x0624, - kCFStringEncodingShiftJIS_X0213 __attribute__((availability(macosx,introduced=10_5))) = 0x0628, - kCFStringEncodingShiftJIS_X0213_MenKuTen = 0x0629, - kCFStringEncodingGB_2312_80 = 0x0630, - kCFStringEncodingGBK_95 = 0x0631, - kCFStringEncodingGB_18030_2000 = 0x0632, - kCFStringEncodingKSC_5601_87 = 0x0640, - kCFStringEncodingKSC_5601_92_Johab = 0x0641, - kCFStringEncodingCNS_11643_92_P1 = 0x0651, - kCFStringEncodingCNS_11643_92_P2 = 0x0652, - kCFStringEncodingCNS_11643_92_P3 = 0x0653, - - - kCFStringEncodingISO_2022_JP = 0x0820, - kCFStringEncodingISO_2022_JP_2 = 0x0821, - kCFStringEncodingISO_2022_JP_1 = 0x0822, - kCFStringEncodingISO_2022_JP_3 = 0x0823, - kCFStringEncodingISO_2022_CN = 0x0830, - kCFStringEncodingISO_2022_CN_EXT = 0x0831, - kCFStringEncodingISO_2022_KR = 0x0840, - - - kCFStringEncodingEUC_JP = 0x0920, - kCFStringEncodingEUC_CN = 0x0930, - kCFStringEncodingEUC_TW = 0x0931, - kCFStringEncodingEUC_KR = 0x0940, - - - kCFStringEncodingShiftJIS = 0x0A01, - kCFStringEncodingKOI8_R = 0x0A02, - kCFStringEncodingBig5 = 0x0A03, - kCFStringEncodingMacRomanLatin1 = 0x0A04, - kCFStringEncodingHZ_GB_2312 = 0x0A05, - kCFStringEncodingBig5_HKSCS_1999 = 0x0A06, - kCFStringEncodingVISCII = 0x0A07, - kCFStringEncodingKOI8_U = 0x0A08, - kCFStringEncodingBig5_E = 0x0A09, - - - - kCFStringEncodingNextStepJapanese = 0x0B02, - - - kCFStringEncodingEBCDIC_US = 0x0C01, - kCFStringEncodingEBCDIC_CP037 = 0x0C02, - - kCFStringEncodingUTF7 __attribute__((availability(macosx,introduced=10_6))) = 0x04000100, - kCFStringEncodingUTF7_IMAP __attribute__((availability(macosx,introduced=10_6))) = 0x0A10, - - - kCFStringEncodingShiftJIS_X0213_00 = 0x0628 -}; - -} - -extern "C" { -typedef const void * (*CFTreeRetainCallBack)(const void *info); - - - - - - - -typedef void (*CFTreeReleaseCallBack)(const void *info); -typedef CFStringRef (*CFTreeCopyDescriptionCallBack)(const void *info); -typedef struct { - CFIndex version; - void * info; - CFTreeRetainCallBack retain; - CFTreeReleaseCallBack release; - CFTreeCopyDescriptionCallBack copyDescription; -} CFTreeContext; -typedef void (*CFTreeApplierFunction)(const void *value, void *context); - - - - - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFTree * CFTreeRef; - - - - - -extern -CFTypeID CFTreeGetTypeID(void); -extern -CFTreeRef CFTreeCreate(CFAllocatorRef allocator, const CFTreeContext *context); -extern -CFTreeRef CFTreeGetParent(CFTreeRef tree); -extern -CFTreeRef CFTreeGetNextSibling(CFTreeRef tree); -extern -CFTreeRef CFTreeGetFirstChild(CFTreeRef tree); -extern -void CFTreeGetContext(CFTreeRef tree, CFTreeContext *context); -extern -CFIndex CFTreeGetChildCount(CFTreeRef tree); -extern -CFTreeRef CFTreeGetChildAtIndex(CFTreeRef tree, CFIndex idx); -extern -void CFTreeGetChildren(CFTreeRef tree, CFTreeRef *children); -extern -void CFTreeApplyFunctionToChildren(CFTreeRef tree, CFTreeApplierFunction applier, void *context); -extern -CFTreeRef CFTreeFindRoot(CFTreeRef tree); -extern -void CFTreeSetContext(CFTreeRef tree, const CFTreeContext *context); -extern -void CFTreePrependChild(CFTreeRef tree, CFTreeRef newChild); -extern -void CFTreeAppendChild(CFTreeRef tree, CFTreeRef newChild); -extern -void CFTreeInsertSibling(CFTreeRef tree, CFTreeRef newSibling); - - - - - - - -extern -void CFTreeRemove(CFTreeRef tree); - - - - - - - -extern -void CFTreeRemoveAllChildren(CFTreeRef tree); -extern -void CFTreeSortChildren(CFTreeRef tree, CFComparatorFunction comparator, void *context); - -} - -extern "C" { -extern -Boolean CFURLCreateDataAndPropertiesFromResource(CFAllocatorRef alloc, CFURLRef url, CFDataRef *resourceData, CFDictionaryRef *properties, CFArrayRef desiredProperties, SInt32 *errorCode) __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "For resource data, use the CFReadStream API. For file resource properties, use CFURLCopyResourcePropertiesForKeys."))); -extern -Boolean CFURLWriteDataAndPropertiesToResource(CFURLRef url, CFDataRef dataToWrite, CFDictionaryRef propertiesToWrite, SInt32 *errorCode) __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "For resource data, use the CFWriteStream API. For file resource properties, use CFURLSetResourcePropertiesForKeys."))); - - - - - -extern -Boolean CFURLDestroyResource(CFURLRef url, SInt32 *errorCode) __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "Use CFURLGetFileSystemRepresentation and removefile(3) instead."))); - - - - - -extern -CFTypeRef CFURLCreatePropertyFromResource(CFAllocatorRef alloc, CFURLRef url, CFStringRef property, SInt32 *errorCode) __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "For file resource properties, use CFURLCopyResourcePropertyForKey."))); - - - -typedef CFIndex CFURLError; enum { - kCFURLUnknownError = -10L, - kCFURLUnknownSchemeError = -11L, - kCFURLResourceNotFoundError = -12L, - kCFURLResourceAccessViolationError = -13L, - kCFURLRemoteHostUnavailableError = -14L, - kCFURLImproperArgumentsError = -15L, - kCFURLUnknownPropertyKeyError = -16L, - kCFURLPropertyKeyUnavailableError = -17L, - kCFURLTimeoutError = -18L -} __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))); - - - -extern -const CFStringRef kCFURLFileExists __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "Use CFURLResourceIsReachable instead."))); -extern -const CFStringRef kCFURLFileDirectoryContents __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "Use the CFURLEnumerator API instead."))); -extern -const CFStringRef kCFURLFileLength __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "Use CFURLCopyResourcePropertyForKey with kCFURLFileSizeKey instead."))); -extern -const CFStringRef kCFURLFileLastModificationTime __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "Use CFURLCopyResourcePropertyForKey with kCFURLContentModificationDateKey instead."))); -extern -const CFStringRef kCFURLFilePOSIXMode __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "Use CFURLCopyResourcePropertyForKey with kCFURLFileSecurityKey and then the CFFileSecurity API instead."))); -extern -const CFStringRef kCFURLFileOwnerID __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "Use CFURLCopyResourcePropertyForKey with kCFURLFileSecurityKey and then the CFFileSecurity API instead."))); -extern -const CFStringRef kCFURLHTTPStatusCode __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "Use NSHTTPURLResponse methods instead."))); -extern -const CFStringRef kCFURLHTTPStatusLine __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" "Use NSHTTPURLResponse methods instead."))); -} -extern "C" { - -typedef const struct __attribute__((objc_bridge(id))) __CFUUID * CFUUIDRef; - -typedef struct { - UInt8 byte0; - UInt8 byte1; - UInt8 byte2; - UInt8 byte3; - UInt8 byte4; - UInt8 byte5; - UInt8 byte6; - UInt8 byte7; - UInt8 byte8; - UInt8 byte9; - UInt8 byte10; - UInt8 byte11; - UInt8 byte12; - UInt8 byte13; - UInt8 byte14; - UInt8 byte15; -} CFUUIDBytes; - - - - - - -extern -CFTypeID CFUUIDGetTypeID(void); - -extern -CFUUIDRef CFUUIDCreate(CFAllocatorRef alloc); - - -extern -CFUUIDRef CFUUIDCreateWithBytes(CFAllocatorRef alloc, UInt8 byte0, UInt8 byte1, UInt8 byte2, UInt8 byte3, UInt8 byte4, UInt8 byte5, UInt8 byte6, UInt8 byte7, UInt8 byte8, UInt8 byte9, UInt8 byte10, UInt8 byte11, UInt8 byte12, UInt8 byte13, UInt8 byte14, UInt8 byte15); - - -extern -CFUUIDRef CFUUIDCreateFromString(CFAllocatorRef alloc, CFStringRef uuidStr); - - -extern -CFStringRef CFUUIDCreateString(CFAllocatorRef alloc, CFUUIDRef uuid); - - -extern -CFUUIDRef CFUUIDGetConstantUUIDWithBytes(CFAllocatorRef alloc, UInt8 byte0, UInt8 byte1, UInt8 byte2, UInt8 byte3, UInt8 byte4, UInt8 byte5, UInt8 byte6, UInt8 byte7, UInt8 byte8, UInt8 byte9, UInt8 byte10, UInt8 byte11, UInt8 byte12, UInt8 byte13, UInt8 byte14, UInt8 byte15); - - -extern -CFUUIDBytes CFUUIDGetUUIDBytes(CFUUIDRef uuid); - -extern -CFUUIDRef CFUUIDCreateFromUUIDBytes(CFAllocatorRef alloc, CFUUIDBytes bytes); - -} -extern "C" { - -extern -CFURLRef CFCopyHomeDirectoryURL(void) __attribute__((availability(macosx,unavailable))); - -} - - -extern "C" { - -typedef struct __attribute__((objc_bridge(id))) __CFBundle *CFBundleRef; -typedef struct __attribute__((objc_bridge(id))) __CFBundle *CFPlugInRef; - - -extern -const CFStringRef kCFBundleInfoDictionaryVersionKey; - -extern -const CFStringRef kCFBundleExecutableKey; - -extern -const CFStringRef kCFBundleIdentifierKey; - -extern -const CFStringRef kCFBundleVersionKey; - - - -extern -const CFStringRef kCFBundleDevelopmentRegionKey; - -extern -const CFStringRef kCFBundleNameKey; - -extern -const CFStringRef kCFBundleLocalizationsKey; - - - - -extern -CFBundleRef CFBundleGetMainBundle(void); - -extern -CFBundleRef CFBundleGetBundleWithIdentifier(CFStringRef bundleID); - - - - - - - -extern -CFArrayRef CFBundleGetAllBundles(void); - - - - - -extern -CFTypeID CFBundleGetTypeID(void); - -extern -CFBundleRef CFBundleCreate(CFAllocatorRef allocator, CFURLRef bundleURL); - - -extern -CFArrayRef CFBundleCreateBundlesFromDirectory(CFAllocatorRef allocator, CFURLRef directoryURL, CFStringRef bundleType); - - - - - -extern -CFURLRef CFBundleCopyBundleURL(CFBundleRef bundle); - -extern -CFTypeRef CFBundleGetValueForInfoDictionaryKey(CFBundleRef bundle, CFStringRef key); - - - -extern -CFDictionaryRef CFBundleGetInfoDictionary(CFBundleRef bundle); - - - -extern -CFDictionaryRef CFBundleGetLocalInfoDictionary(CFBundleRef bundle); - - -extern -void CFBundleGetPackageInfo(CFBundleRef bundle, UInt32 *packageType, UInt32 *packageCreator); - -extern -CFStringRef CFBundleGetIdentifier(CFBundleRef bundle); - -extern -UInt32 CFBundleGetVersionNumber(CFBundleRef bundle); - -extern -CFStringRef CFBundleGetDevelopmentRegion(CFBundleRef bundle); - -extern -CFURLRef CFBundleCopySupportFilesDirectoryURL(CFBundleRef bundle); - -extern -CFURLRef CFBundleCopyResourcesDirectoryURL(CFBundleRef bundle); - -extern -CFURLRef CFBundleCopyPrivateFrameworksURL(CFBundleRef bundle); - -extern -CFURLRef CFBundleCopySharedFrameworksURL(CFBundleRef bundle); - -extern -CFURLRef CFBundleCopySharedSupportURL(CFBundleRef bundle); - -extern -CFURLRef CFBundleCopyBuiltInPlugInsURL(CFBundleRef bundle); - - - - - - -extern -CFDictionaryRef CFBundleCopyInfoDictionaryInDirectory(CFURLRef bundleURL); - -extern -Boolean CFBundleGetPackageInfoInDirectory(CFURLRef url, UInt32 *packageType, UInt32 *packageCreator); - - - -extern -CFURLRef CFBundleCopyResourceURL(CFBundleRef bundle, CFStringRef resourceName, CFStringRef resourceType, CFStringRef subDirName); - -extern -CFArrayRef CFBundleCopyResourceURLsOfType(CFBundleRef bundle, CFStringRef resourceType, CFStringRef subDirName); - -extern -CFStringRef CFBundleCopyLocalizedString(CFBundleRef bundle, CFStringRef key, CFStringRef value, CFStringRef tableName) __attribute__((format_arg(2))); -extern -CFURLRef CFBundleCopyResourceURLInDirectory(CFURLRef bundleURL, CFStringRef resourceName, CFStringRef resourceType, CFStringRef subDirName); - -extern -CFArrayRef CFBundleCopyResourceURLsOfTypeInDirectory(CFURLRef bundleURL, CFStringRef resourceType, CFStringRef subDirName); - - - - - - -extern -CFArrayRef CFBundleCopyBundleLocalizations(CFBundleRef bundle); - - -extern -CFArrayRef CFBundleCopyPreferredLocalizationsFromArray(CFArrayRef locArray); - - - - - - -extern -CFArrayRef CFBundleCopyLocalizationsForPreferences(CFArrayRef locArray, CFArrayRef prefArray); -extern -CFURLRef CFBundleCopyResourceURLForLocalization(CFBundleRef bundle, CFStringRef resourceName, CFStringRef resourceType, CFStringRef subDirName, CFStringRef localizationName); - -extern -CFArrayRef CFBundleCopyResourceURLsOfTypeForLocalization(CFBundleRef bundle, CFStringRef resourceType, CFStringRef subDirName, CFStringRef localizationName); -extern -CFDictionaryRef CFBundleCopyInfoDictionaryForURL(CFURLRef url); - - - - - -extern -CFArrayRef CFBundleCopyLocalizationsForURL(CFURLRef url); - - - - - - -extern -CFArrayRef CFBundleCopyExecutableArchitecturesForURL(CFURLRef url) __attribute__((availability(macosx,introduced=10_5))); -extern -CFURLRef CFBundleCopyExecutableURL(CFBundleRef bundle); - -enum { - kCFBundleExecutableArchitectureI386 = 0x00000007, - kCFBundleExecutableArchitecturePPC = 0x00000012, - kCFBundleExecutableArchitectureX86_64 = 0x01000007, - kCFBundleExecutableArchitecturePPC64 = 0x01000012 -} __attribute__((availability(macosx,introduced=10_5))); - -extern -CFArrayRef CFBundleCopyExecutableArchitectures(CFBundleRef bundle) __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern -Boolean CFBundlePreflightExecutable(CFBundleRef bundle, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_5))); - - - - - - -extern -Boolean CFBundleLoadExecutableAndReturnError(CFBundleRef bundle, CFErrorRef *error) __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern -Boolean CFBundleLoadExecutable(CFBundleRef bundle); - -extern -Boolean CFBundleIsExecutableLoaded(CFBundleRef bundle); - -extern -void CFBundleUnloadExecutable(CFBundleRef bundle); - -extern -void *CFBundleGetFunctionPointerForName(CFBundleRef bundle, CFStringRef functionName); - -extern -void CFBundleGetFunctionPointersForNames(CFBundleRef bundle, CFArrayRef functionNames, void *ftbl[]); - -extern -void *CFBundleGetDataPointerForName(CFBundleRef bundle, CFStringRef symbolName); - -extern -void CFBundleGetDataPointersForNames(CFBundleRef bundle, CFArrayRef symbolNames, void *stbl[]); - -extern -CFURLRef CFBundleCopyAuxiliaryExecutableURL(CFBundleRef bundle, CFStringRef executableName); -extern -CFPlugInRef CFBundleGetPlugIn(CFBundleRef bundle); - - - - -typedef int CFBundleRefNum; - - - - -extern -CFBundleRefNum CFBundleOpenBundleResourceMap(CFBundleRef bundle); - - - - - - -extern -SInt32 CFBundleOpenBundleResourceFiles(CFBundleRef bundle, CFBundleRefNum *refNum, CFBundleRefNum *localizedRefNum); - - - -extern -void CFBundleCloseBundleResourceMap(CFBundleRef bundle, CFBundleRefNum refNum); - -} -extern "C" { - -typedef struct __attribute__((objc_bridge_mutable(NSMessagePort))) __CFMessagePort * CFMessagePortRef; - -enum { - kCFMessagePortSuccess = 0, - kCFMessagePortSendTimeout = -1, - kCFMessagePortReceiveTimeout = -2, - kCFMessagePortIsInvalid = -3, - kCFMessagePortTransportError = -4, - kCFMessagePortBecameInvalidError = -5 -}; - -typedef struct { - CFIndex version; - void * info; - const void *(*retain)(const void *info); - void (*release)(const void *info); - CFStringRef (*copyDescription)(const void *info); -} CFMessagePortContext; - -typedef CFDataRef (*CFMessagePortCallBack)(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info); - -typedef void (*CFMessagePortInvalidationCallBack)(CFMessagePortRef ms, void *info); - -extern CFTypeID CFMessagePortGetTypeID(void); - -extern CFMessagePortRef CFMessagePortCreateLocal(CFAllocatorRef allocator, CFStringRef name, CFMessagePortCallBack callout, CFMessagePortContext *context, Boolean *shouldFreeInfo); -extern CFMessagePortRef CFMessagePortCreateRemote(CFAllocatorRef allocator, CFStringRef name); - -extern Boolean CFMessagePortIsRemote(CFMessagePortRef ms); -extern CFStringRef CFMessagePortGetName(CFMessagePortRef ms); -extern Boolean CFMessagePortSetName(CFMessagePortRef ms, CFStringRef newName); -extern void CFMessagePortGetContext(CFMessagePortRef ms, CFMessagePortContext *context); -extern void CFMessagePortInvalidate(CFMessagePortRef ms); -extern Boolean CFMessagePortIsValid(CFMessagePortRef ms); -extern CFMessagePortInvalidationCallBack CFMessagePortGetInvalidationCallBack(CFMessagePortRef ms); -extern void CFMessagePortSetInvalidationCallBack(CFMessagePortRef ms, CFMessagePortInvalidationCallBack callout); - - -extern SInt32 CFMessagePortSendRequest(CFMessagePortRef remote, SInt32 msgid, CFDataRef data, CFTimeInterval sendTimeout, CFTimeInterval rcvTimeout, CFStringRef replyMode, CFDataRef *returnData); - -extern CFRunLoopSourceRef CFMessagePortCreateRunLoopSource(CFAllocatorRef allocator, CFMessagePortRef local, CFIndex order); - -extern void CFMessagePortSetDispatchQueue(CFMessagePortRef ms, dispatch_queue_t queue) __attribute__((availability(macosx,introduced=10_6))); - -} -extern "C" { - - - -extern const CFStringRef kCFPlugInDynamicRegistrationKey; -extern const CFStringRef kCFPlugInDynamicRegisterFunctionKey; -extern const CFStringRef kCFPlugInUnloadFunctionKey; -extern const CFStringRef kCFPlugInFactoriesKey; -extern const CFStringRef kCFPlugInTypesKey; - - - - -typedef void (*CFPlugInDynamicRegisterFunction)(CFPlugInRef plugIn); -typedef void (*CFPlugInUnloadFunction)(CFPlugInRef plugIn); -typedef void *(*CFPlugInFactoryFunction)(CFAllocatorRef allocator, CFUUIDRef typeUUID); - - - -extern CFTypeID CFPlugInGetTypeID(void); - -extern CFPlugInRef CFPlugInCreate(CFAllocatorRef allocator, CFURLRef plugInURL); - - -extern CFBundleRef CFPlugInGetBundle(CFPlugInRef plugIn); - - - - - - - -extern void CFPlugInSetLoadOnDemand(CFPlugInRef plugIn, Boolean flag); - -extern Boolean CFPlugInIsLoadOnDemand(CFPlugInRef plugIn); - - - - - - -extern CFArrayRef CFPlugInFindFactoriesForPlugInType(CFUUIDRef typeUUID) __attribute__((cf_returns_retained)); - - - -extern CFArrayRef CFPlugInFindFactoriesForPlugInTypeInPlugIn(CFUUIDRef typeUUID, CFPlugInRef plugIn) __attribute__((cf_returns_retained)); - - -extern void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryUUID, CFUUIDRef typeUUID); - - - - - -extern Boolean CFPlugInRegisterFactoryFunction(CFUUIDRef factoryUUID, CFPlugInFactoryFunction func); - -extern Boolean CFPlugInRegisterFactoryFunctionByName(CFUUIDRef factoryUUID, CFPlugInRef plugIn, CFStringRef functionName); - -extern Boolean CFPlugInUnregisterFactory(CFUUIDRef factoryUUID); - -extern Boolean CFPlugInRegisterPlugInType(CFUUIDRef factoryUUID, CFUUIDRef typeUUID); - -extern Boolean CFPlugInUnregisterPlugInType(CFUUIDRef factoryUUID, CFUUIDRef typeUUID); - - - - - -extern void CFPlugInAddInstanceForFactory(CFUUIDRef factoryID); - -extern void CFPlugInRemoveInstanceForFactory(CFUUIDRef factoryID); - - - - -typedef struct __attribute__((objc_bridge(id))) __CFPlugInInstance *CFPlugInInstanceRef; - -typedef Boolean (*CFPlugInInstanceGetInterfaceFunction)(CFPlugInInstanceRef instance, CFStringRef interfaceName, void **ftbl); -typedef void (*CFPlugInInstanceDeallocateInstanceDataFunction)(void *instanceData); - -extern Boolean CFPlugInInstanceGetInterfaceFunctionTable(CFPlugInInstanceRef instance, CFStringRef interfaceName, void **ftbl); - - -extern CFStringRef CFPlugInInstanceGetFactoryName(CFPlugInInstanceRef instance) __attribute__((cf_returns_retained)); - -extern void *CFPlugInInstanceGetInstanceData(CFPlugInInstanceRef instance); - -extern CFTypeID CFPlugInInstanceGetTypeID(void); - -extern CFPlugInInstanceRef CFPlugInInstanceCreateWithInstanceDataSize(CFAllocatorRef allocator, CFIndex instanceDataSize, CFPlugInInstanceDeallocateInstanceDataFunction deallocateInstanceFunction, CFStringRef factoryName, CFPlugInInstanceGetInterfaceFunction getInterfaceFunction); - -} - - - - - -extern "C" { - - - - -typedef const struct __attribute__((objc_bridge(NSAttributedString))) __CFAttributedString *CFAttributedStringRef; -typedef struct __attribute__((objc_bridge_mutable(NSMutableAttributedString))) __CFAttributedString *CFMutableAttributedStringRef; - - - - -extern CFTypeID CFAttributedStringGetTypeID(void); -extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes); - - - - -extern CFAttributedStringRef CFAttributedStringCreateWithSubstring(CFAllocatorRef alloc, CFAttributedStringRef aStr, CFRange range); - - - - -extern CFAttributedStringRef CFAttributedStringCreateCopy(CFAllocatorRef alloc, CFAttributedStringRef aStr); - - - - -extern CFStringRef CFAttributedStringGetString(CFAttributedStringRef aStr); - - - - -extern CFIndex CFAttributedStringGetLength(CFAttributedStringRef aStr); - - - - - - -extern CFDictionaryRef CFAttributedStringGetAttributes(CFAttributedStringRef aStr, CFIndex loc, CFRange *effectiveRange); - - - - -extern CFTypeRef CFAttributedStringGetAttribute(CFAttributedStringRef aStr, CFIndex loc, CFStringRef attrName, CFRange *effectiveRange); - - - - -extern CFDictionaryRef CFAttributedStringGetAttributesAndLongestEffectiveRange(CFAttributedStringRef aStr, CFIndex loc, CFRange inRange, CFRange *longestEffectiveRange); - - - - -extern CFTypeRef CFAttributedStringGetAttributeAndLongestEffectiveRange(CFAttributedStringRef aStr, CFIndex loc, CFStringRef attrName, CFRange inRange, CFRange *longestEffectiveRange); -extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr); - - - - -extern CFMutableAttributedStringRef CFAttributedStringCreateMutable(CFAllocatorRef alloc, CFIndex maxLength); - - - - - - -extern void CFAttributedStringReplaceString(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef replacement); - - - - - - -extern CFMutableStringRef CFAttributedStringGetMutableString(CFMutableAttributedStringRef aStr); - - - - -extern void CFAttributedStringSetAttributes(CFMutableAttributedStringRef aStr, CFRange range, CFDictionaryRef replacement, Boolean clearOtherAttributes); - - - - -extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value); - - - - -extern void CFAttributedStringRemoveAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName); - - - - -extern void CFAttributedStringReplaceAttributedString(CFMutableAttributedStringRef aStr, CFRange range, CFAttributedStringRef replacement); - - - - -extern void CFAttributedStringBeginEditing(CFMutableAttributedStringRef aStr); - - - - -extern void CFAttributedStringEndEditing(CFMutableAttributedStringRef aStr); - - -} -extern "C" { - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFNotificationCenter * CFNotificationCenterRef; - -typedef void (*CFNotificationCallback)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo); - -typedef CFIndex CFNotificationSuspensionBehavior; enum { - CFNotificationSuspensionBehaviorDrop = 1, - - CFNotificationSuspensionBehaviorCoalesce = 2, - - CFNotificationSuspensionBehaviorHold = 3, - - CFNotificationSuspensionBehaviorDeliverImmediately = 4 - -}; - -extern CFTypeID CFNotificationCenterGetTypeID(void); - -extern CFNotificationCenterRef CFNotificationCenterGetLocalCenter(void); - - -extern CFNotificationCenterRef CFNotificationCenterGetDistributedCenter(void); - - -extern CFNotificationCenterRef CFNotificationCenterGetDarwinNotifyCenter(void); -extern void CFNotificationCenterAddObserver(CFNotificationCenterRef center, const void *observer, CFNotificationCallback callBack, CFStringRef name, const void *object, CFNotificationSuspensionBehavior suspensionBehavior); - -extern void CFNotificationCenterRemoveObserver(CFNotificationCenterRef center, const void *observer, CFStringRef name, const void *object); -extern void CFNotificationCenterRemoveEveryObserver(CFNotificationCenterRef center, const void *observer); - -extern void CFNotificationCenterPostNotification(CFNotificationCenterRef center, CFStringRef name, const void *object, CFDictionaryRef userInfo, Boolean deliverImmediately); - -enum { - kCFNotificationDeliverImmediately = (1UL << 0), - kCFNotificationPostToAllSessions = (1UL << 1) -}; - -extern void CFNotificationCenterPostNotificationWithOptions(CFNotificationCenterRef center, CFStringRef name, const void *object, CFDictionaryRef userInfo, CFOptionFlags options); - - -} -extern "C" { - - -typedef const struct __attribute__((objc_bridge_mutable(id))) __CFURLEnumerator *CFURLEnumeratorRef; - - -extern -CFTypeID CFURLEnumeratorGetTypeID( void ) __attribute__((availability(macosx,introduced=10_6))); - - - -typedef CFOptionFlags CFURLEnumeratorOptions; enum { - kCFURLEnumeratorDefaultBehavior = 0, - kCFURLEnumeratorDescendRecursively = 1UL << 0, - kCFURLEnumeratorSkipInvisibles = 1UL << 1, - kCFURLEnumeratorGenerateFileReferenceURLs = 1UL << 2, - kCFURLEnumeratorSkipPackageContents = 1UL << 3, - kCFURLEnumeratorIncludeDirectoriesPreOrder = 1UL << 4, - kCFURLEnumeratorIncludeDirectoriesPostOrder = 1UL << 5, - -}; - - - - - - - -extern -CFURLEnumeratorRef CFURLEnumeratorCreateForDirectoryURL( CFAllocatorRef alloc, CFURLRef directoryURL, CFURLEnumeratorOptions option, CFArrayRef propertyKeys ) __attribute__((availability(macosx,introduced=10_6))); -extern -CFURLEnumeratorRef CFURLEnumeratorCreateForMountedVolumes( CFAllocatorRef alloc, CFURLEnumeratorOptions option, CFArrayRef propertyKeys ) __attribute__((availability(macosx,introduced=10_6))); - - - -typedef CFIndex CFURLEnumeratorResult; enum { - kCFURLEnumeratorSuccess = 1, - kCFURLEnumeratorEnd = 2, - kCFURLEnumeratorError = 3, - kCFURLEnumeratorDirectoryPostOrderSuccess = 4, -}; - - - - - -extern -CFURLEnumeratorResult CFURLEnumeratorGetNextURL( CFURLEnumeratorRef enumerator, CFURLRef *url, CFErrorRef *error ) __attribute__((availability(macosx,introduced=10_6))); -extern -void CFURLEnumeratorSkipDescendents( CFURLEnumeratorRef enumerator ) __attribute__((availability(macosx,introduced=10_6))); - - - - -extern -CFIndex CFURLEnumeratorGetDescendentLevel( CFURLEnumeratorRef enumerator ) __attribute__((availability(macosx,introduced=10_6))); - - - - - - -extern -Boolean CFURLEnumeratorGetSourceDidChange( CFURLEnumeratorRef enumerator ) __attribute__((availability(macosx,introduced=10_6,deprecated=10_7,message="" ))); - - -} - - - - - - -typedef struct { - - unsigned char g_guid[16]; -} guid_t; - - -#pragma pack(1) -typedef struct { - u_int8_t sid_kind; - u_int8_t sid_authcount; - u_int8_t sid_authority[6]; - - u_int32_t sid_authorities[16]; -} ntsid_t; -#pragma pack() -struct kauth_identity_extlookup { - u_int32_t el_seqno; - u_int32_t el_result; - - - - - - u_int32_t el_flags; - __darwin_pid_t el_info_pid; - u_int64_t el_extend; - u_int32_t el_info_reserved_1; - - uid_t el_uid; - guid_t el_uguid; - u_int32_t el_uguid_valid; - ntsid_t el_usid; - u_int32_t el_usid_valid; - gid_t el_gid; - guid_t el_gguid; - u_int32_t el_gguid_valid; - ntsid_t el_gsid; - u_int32_t el_gsid_valid; - u_int32_t el_member_valid; - u_int32_t el_sup_grp_cnt; - gid_t el_sup_groups[16]; -}; - -struct kauth_cache_sizes { - u_int32_t kcs_group_size; - u_int32_t kcs_id_size; -}; -typedef u_int32_t kauth_ace_rights_t; - - -struct kauth_ace { - guid_t ace_applicable; - u_int32_t ace_flags; - kauth_ace_rights_t ace_rights; - - - - - - -}; - - - -typedef struct kauth_ace *kauth_ace_t; - - - - -struct kauth_acl { - u_int32_t acl_entrycount; - u_int32_t acl_flags; - - struct kauth_ace acl_ace[1]; -}; -typedef struct kauth_acl *kauth_acl_t; -struct kauth_filesec { - u_int32_t fsec_magic; - - guid_t fsec_owner; - guid_t fsec_group; - - struct kauth_acl fsec_acl; -}; -typedef struct kauth_filesec *kauth_filesec_t; -typedef enum { - ACL_READ_DATA = (1<<1), - ACL_LIST_DIRECTORY = (1<<1), - ACL_WRITE_DATA = (1<<2), - ACL_ADD_FILE = (1<<2), - ACL_EXECUTE = (1<<3), - ACL_SEARCH = (1<<3), - ACL_DELETE = (1<<4), - ACL_APPEND_DATA = (1<<5), - ACL_ADD_SUBDIRECTORY = (1<<5), - ACL_DELETE_CHILD = (1<<6), - ACL_READ_ATTRIBUTES = (1<<7), - ACL_WRITE_ATTRIBUTES = (1<<8), - ACL_READ_EXTATTRIBUTES = (1<<9), - ACL_WRITE_EXTATTRIBUTES = (1<<10), - ACL_READ_SECURITY = (1<<11), - ACL_WRITE_SECURITY = (1<<12), - ACL_CHANGE_OWNER = (1<<13), - ACL_SYNCHRONIZE = (1<<20), -} acl_perm_t; - - -typedef enum { - ACL_UNDEFINED_TAG = 0, - ACL_EXTENDED_ALLOW = 1, - ACL_EXTENDED_DENY = 2 -} acl_tag_t; - - -typedef enum { - ACL_TYPE_EXTENDED = 0x00000100, - - ACL_TYPE_ACCESS = 0x00000000, - ACL_TYPE_DEFAULT = 0x00000001, - - ACL_TYPE_AFS = 0x00000002, - ACL_TYPE_CODA = 0x00000003, - ACL_TYPE_NTFS = 0x00000004, - ACL_TYPE_NWFS = 0x00000005 -} acl_type_t; - - - - - - -typedef enum { - ACL_FIRST_ENTRY = 0, - ACL_NEXT_ENTRY = -1, - ACL_LAST_ENTRY = -2 -} acl_entry_id_t; - - -typedef enum { - ACL_FLAG_DEFER_INHERIT = (1 << 0), - ACL_FLAG_NO_INHERIT = (1<<17), - ACL_ENTRY_INHERITED = (1<<4), - ACL_ENTRY_FILE_INHERIT = (1<<5), - ACL_ENTRY_DIRECTORY_INHERIT = (1<<6), - ACL_ENTRY_LIMIT_INHERIT = (1<<7), - ACL_ENTRY_ONLY_INHERIT = (1<<8) -} acl_flag_t; - - - -struct _acl; -struct _acl_entry; -struct _acl_permset; -struct _acl_flagset; - -typedef struct _acl *acl_t; -typedef struct _acl_entry *acl_entry_t; -typedef struct _acl_permset *acl_permset_t; -typedef struct _acl_flagset *acl_flagset_t; - -typedef u_int64_t acl_permset_mask_t; - -extern "C" { - -extern acl_t acl_dup(acl_t acl); -extern int acl_free(void *obj_p); -extern acl_t acl_init(int count); - - -extern int acl_copy_entry(acl_entry_t dest_d, acl_entry_t src_d); -extern int acl_create_entry(acl_t *acl_p, acl_entry_t *entry_p); -extern int acl_create_entry_np(acl_t *acl_p, acl_entry_t *entry_p, int entry_index); -extern int acl_delete_entry(acl_t acl, acl_entry_t entry_d); -extern int acl_get_entry(acl_t acl, int entry_id, acl_entry_t *entry_p); -extern int acl_valid(acl_t acl); -extern int acl_valid_fd_np(int fd, acl_type_t type, acl_t acl); -extern int acl_valid_file_np(const char *path, acl_type_t type, acl_t acl); -extern int acl_valid_link_np(const char *path, acl_type_t type, acl_t acl); - - -extern int acl_add_perm(acl_permset_t permset_d, acl_perm_t perm); -extern int acl_calc_mask(acl_t *acl_p); -extern int acl_clear_perms(acl_permset_t permset_d); -extern int acl_delete_perm(acl_permset_t permset_d, acl_perm_t perm); -extern int acl_get_perm_np(acl_permset_t permset_d, acl_perm_t perm); -extern int acl_get_permset(acl_entry_t entry_d, acl_permset_t *permset_p); -extern int acl_set_permset(acl_entry_t entry_d, acl_permset_t permset_d); - - -extern int acl_maximal_permset_mask_np(acl_permset_mask_t * mask_p) __attribute__((availability(macosx,introduced=10.7))); -extern int acl_get_permset_mask_np(acl_entry_t entry_d, acl_permset_mask_t * mask_p) __attribute__((availability(macosx,introduced=10.7))); -extern int acl_set_permset_mask_np(acl_entry_t entry_d, acl_permset_mask_t mask) __attribute__((availability(macosx,introduced=10.7))); - - -extern int acl_add_flag_np(acl_flagset_t flagset_d, acl_flag_t flag); -extern int acl_clear_flags_np(acl_flagset_t flagset_d); -extern int acl_delete_flag_np(acl_flagset_t flagset_d, acl_flag_t flag); -extern int acl_get_flag_np(acl_flagset_t flagset_d, acl_flag_t flag); -extern int acl_get_flagset_np(void *obj_p, acl_flagset_t *flagset_p); -extern int acl_set_flagset_np(void *obj_p, acl_flagset_t flagset_d); - - -extern void *acl_get_qualifier(acl_entry_t entry_d); -extern int acl_get_tag_type(acl_entry_t entry_d, acl_tag_t *tag_type_p); -extern int acl_set_qualifier(acl_entry_t entry_d, const void *tag_qualifier_p); -extern int acl_set_tag_type(acl_entry_t entry_d, acl_tag_t tag_type); - - -extern int acl_delete_def_file(const char *path_p); -extern acl_t acl_get_fd(int fd); -extern acl_t acl_get_fd_np(int fd, acl_type_t type); -extern acl_t acl_get_file(const char *path_p, acl_type_t type); -extern acl_t acl_get_link_np(const char *path_p, acl_type_t type); -extern int acl_set_fd(int fd, acl_t acl); -extern int acl_set_fd_np(int fd, acl_t acl, acl_type_t acl_type); -extern int acl_set_file(const char *path_p, acl_type_t type, acl_t acl); -extern int acl_set_link_np(const char *path_p, acl_type_t type, acl_t acl); - - -extern ssize_t acl_copy_ext(void *buf_p, acl_t acl, ssize_t size); -extern ssize_t acl_copy_ext_native(void *buf_p, acl_t acl, ssize_t size); -extern acl_t acl_copy_int(const void *buf_p); -extern acl_t acl_copy_int_native(const void *buf_p); -extern acl_t acl_from_text(const char *buf_p); -extern ssize_t acl_size(acl_t acl); -extern char *acl_to_text(acl_t acl, ssize_t *len_p); -} - - - - -extern "C" { - - - - - -typedef struct __attribute__((objc_bridge_mutable(NSFileSecurity))) __CFFileSecurity* CFFileSecurityRef; - - - - - - - -extern -CFTypeID CFFileSecurityGetTypeID(void) __attribute__((availability(macosx,introduced=10_7))); -extern -CFFileSecurityRef CFFileSecurityCreate(CFAllocatorRef allocator) __attribute__((availability(macosx,introduced=10_7))); -extern -CFFileSecurityRef CFFileSecurityCreateCopy(CFAllocatorRef allocator, CFFileSecurityRef fileSec) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecurityCopyOwnerUUID(CFFileSecurityRef fileSec, CFUUIDRef *ownerUUID) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecuritySetOwnerUUID(CFFileSecurityRef fileSec, CFUUIDRef ownerUUID) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecurityCopyGroupUUID(CFFileSecurityRef fileSec, CFUUIDRef *groupUUID) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecuritySetGroupUUID(CFFileSecurityRef fileSec, CFUUIDRef groupUUID) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecurityCopyAccessControlList(CFFileSecurityRef fileSec, acl_t *accessControlList) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecuritySetAccessControlList(CFFileSecurityRef fileSec, acl_t accessControlList) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecurityGetOwner(CFFileSecurityRef fileSec, uid_t *owner) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecuritySetOwner(CFFileSecurityRef fileSec, uid_t owner) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecurityGetGroup(CFFileSecurityRef fileSec, gid_t *group) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecuritySetGroup(CFFileSecurityRef fileSec, gid_t group) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecurityGetMode(CFFileSecurityRef fileSec, mode_t *mode) __attribute__((availability(macosx,introduced=10_7))); -extern -Boolean CFFileSecuritySetMode(CFFileSecurityRef fileSec, mode_t mode) __attribute__((availability(macosx,introduced=10_7))); - - - -typedef CFOptionFlags CFFileSecurityClearOptions; enum { - kCFFileSecurityClearOwner = 1UL << 0, - kCFFileSecurityClearGroup = 1UL << 1, - kCFFileSecurityClearMode = 1UL << 2, - kCFFileSecurityClearOwnerUUID = 1UL << 3, - kCFFileSecurityClearGroupUUID = 1UL << 4, - kCFFileSecurityClearAccessControlList = 1UL << 5 -} __attribute__((availability(macosx,introduced=10_8))); -extern -Boolean CFFileSecurityClearProperties(CFFileSecurityRef fileSec, CFFileSecurityClearOptions clearPropertyMask) __attribute__((availability(macosx,introduced=10_8))); - - -} -extern "C" { - -typedef struct __attribute__((objc_bridge_mutable(NSMachPort))) __CFMachPort * CFMachPortRef; - -typedef struct { - CFIndex version; - void * info; - const void *(*retain)(const void *info); - void (*release)(const void *info); - CFStringRef (*copyDescription)(const void *info); -} CFMachPortContext; - -typedef void (*CFMachPortCallBack)(CFMachPortRef port, void *msg, CFIndex size, void *info); -typedef void (*CFMachPortInvalidationCallBack)(CFMachPortRef port, void *info); - -extern CFTypeID CFMachPortGetTypeID(void); - -extern CFMachPortRef CFMachPortCreate(CFAllocatorRef allocator, CFMachPortCallBack callout, CFMachPortContext *context, Boolean *shouldFreeInfo); -extern CFMachPortRef CFMachPortCreateWithPort(CFAllocatorRef allocator, mach_port_t portNum, CFMachPortCallBack callout, CFMachPortContext *context, Boolean *shouldFreeInfo); - -extern mach_port_t CFMachPortGetPort(CFMachPortRef port); -extern void CFMachPortGetContext(CFMachPortRef port, CFMachPortContext *context); -extern void CFMachPortInvalidate(CFMachPortRef port); -extern Boolean CFMachPortIsValid(CFMachPortRef port); -extern CFMachPortInvalidationCallBack CFMachPortGetInvalidationCallBack(CFMachPortRef port); -extern void CFMachPortSetInvalidationCallBack(CFMachPortRef port, CFMachPortInvalidationCallBack callout); - -extern CFRunLoopSourceRef CFMachPortCreateRunLoopSource(CFAllocatorRef allocator, CFMachPortRef port, CFIndex order); - -} -extern "C" { -extern -CFStringRef CFStringTokenizerCopyBestStringLanguage(CFStringRef string, CFRange range) __attribute__((availability(macosx,introduced=10_5))); - - - - - - - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFStringTokenizer * CFStringTokenizerRef; - - - - -enum { - - - - - - - kCFStringTokenizerUnitWord = 0, - kCFStringTokenizerUnitSentence = 1, - kCFStringTokenizerUnitParagraph = 2, - kCFStringTokenizerUnitLineBreak = 3, - - - - - kCFStringTokenizerUnitWordBoundary = 4, - kCFStringTokenizerAttributeLatinTranscription = 1UL << 16, - - - kCFStringTokenizerAttributeLanguage = 1UL << 17, -}; - - - - - - -typedef CFOptionFlags CFStringTokenizerTokenType; enum { - - kCFStringTokenizerTokenNone = 0, - - - kCFStringTokenizerTokenNormal = 1UL << 0, - - - - - - kCFStringTokenizerTokenHasSubTokensMask = 1UL << 1, - - - - - - - kCFStringTokenizerTokenHasDerivedSubTokensMask = 1UL << 2, - - kCFStringTokenizerTokenHasHasNumbersMask = 1UL << 3, - kCFStringTokenizerTokenHasNonLettersMask = 1UL << 4, - kCFStringTokenizerTokenIsCJWordMask = 1UL << 5 -}; - - - - - - -extern -CFTypeID CFStringTokenizerGetTypeID(void) __attribute__((availability(macosx,introduced=10_5))); -extern -CFStringTokenizerRef CFStringTokenizerCreate(CFAllocatorRef alloc, CFStringRef string, CFRange range, CFOptionFlags options, CFLocaleRef locale) __attribute__((availability(macosx,introduced=10_5))); -extern -void CFStringTokenizerSetString(CFStringTokenizerRef tokenizer, CFStringRef string, CFRange range) __attribute__((availability(macosx,introduced=10_5))); -extern -CFStringTokenizerTokenType CFStringTokenizerGoToTokenAtIndex(CFStringTokenizerRef tokenizer, CFIndex index) __attribute__((availability(macosx,introduced=10_5))); -extern -CFStringTokenizerTokenType CFStringTokenizerAdvanceToNextToken(CFStringTokenizerRef tokenizer) __attribute__((availability(macosx,introduced=10_5))); -extern -CFRange CFStringTokenizerGetCurrentTokenRange(CFStringTokenizerRef tokenizer) __attribute__((availability(macosx,introduced=10_5))); -extern -CFTypeRef CFStringTokenizerCopyCurrentTokenAttribute(CFStringTokenizerRef tokenizer, CFOptionFlags attribute) __attribute__((availability(macosx,introduced=10_5))); -extern -CFIndex CFStringTokenizerGetCurrentSubTokens(CFStringTokenizerRef tokenizer, CFRange *ranges, CFIndex maxRangeLength, CFMutableArrayRef derivedSubTokens) __attribute__((availability(macosx,introduced=10_5))); - -} -extern "C" { - -typedef int CFFileDescriptorNativeDescriptor; - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFFileDescriptor * CFFileDescriptorRef; - - -enum { - kCFFileDescriptorReadCallBack = 1UL << 0, - kCFFileDescriptorWriteCallBack = 1UL << 1 -}; - -typedef void (*CFFileDescriptorCallBack)(CFFileDescriptorRef f, CFOptionFlags callBackTypes, void *info); - -typedef struct { - CFIndex version; - void * info; - void * (*retain)(void *info); - void (*release)(void *info); - CFStringRef (*copyDescription)(void *info); -} CFFileDescriptorContext; - -extern CFTypeID CFFileDescriptorGetTypeID(void) __attribute__((availability(macosx,introduced=10_5))); - -extern CFFileDescriptorRef CFFileDescriptorCreate(CFAllocatorRef allocator, CFFileDescriptorNativeDescriptor fd, Boolean closeOnInvalidate, CFFileDescriptorCallBack callout, const CFFileDescriptorContext *context) __attribute__((availability(macosx,introduced=10_5))); - -extern CFFileDescriptorNativeDescriptor CFFileDescriptorGetNativeDescriptor(CFFileDescriptorRef f) __attribute__((availability(macosx,introduced=10_5))); - -extern void CFFileDescriptorGetContext(CFFileDescriptorRef f, CFFileDescriptorContext *context) __attribute__((availability(macosx,introduced=10_5))); - -extern void CFFileDescriptorEnableCallBacks(CFFileDescriptorRef f, CFOptionFlags callBackTypes) __attribute__((availability(macosx,introduced=10_5))); -extern void CFFileDescriptorDisableCallBacks(CFFileDescriptorRef f, CFOptionFlags callBackTypes) __attribute__((availability(macosx,introduced=10_5))); - -extern void CFFileDescriptorInvalidate(CFFileDescriptorRef f) __attribute__((availability(macosx,introduced=10_5))); -extern Boolean CFFileDescriptorIsValid(CFFileDescriptorRef f) __attribute__((availability(macosx,introduced=10_5))); - -extern CFRunLoopSourceRef CFFileDescriptorCreateRunLoopSource(CFAllocatorRef allocator, CFFileDescriptorRef f, CFIndex order) __attribute__((availability(macosx,introduced=10_5))); - - -} - - - - -extern "C" { - -typedef struct __attribute__((objc_bridge_mutable(id))) __CFUserNotification * CFUserNotificationRef; -typedef void (*CFUserNotificationCallBack)(CFUserNotificationRef userNotification, CFOptionFlags responseFlags); - -extern -CFTypeID CFUserNotificationGetTypeID(void); - -extern -CFUserNotificationRef CFUserNotificationCreate(CFAllocatorRef allocator, CFTimeInterval timeout, CFOptionFlags flags, SInt32 *error, CFDictionaryRef dictionary); - -extern -SInt32 CFUserNotificationReceiveResponse(CFUserNotificationRef userNotification, CFTimeInterval timeout, CFOptionFlags *responseFlags); - -extern -CFStringRef CFUserNotificationGetResponseValue(CFUserNotificationRef userNotification, CFStringRef key, CFIndex idx); - -extern -CFDictionaryRef CFUserNotificationGetResponseDictionary(CFUserNotificationRef userNotification); - -extern -SInt32 CFUserNotificationUpdate(CFUserNotificationRef userNotification, CFTimeInterval timeout, CFOptionFlags flags, CFDictionaryRef dictionary); - -extern -SInt32 CFUserNotificationCancel(CFUserNotificationRef userNotification); - -extern -CFRunLoopSourceRef CFUserNotificationCreateRunLoopSource(CFAllocatorRef allocator, CFUserNotificationRef userNotification, CFUserNotificationCallBack callout, CFIndex order); - - - - -extern -SInt32 CFUserNotificationDisplayNotice(CFTimeInterval timeout, CFOptionFlags flags, CFURLRef iconURL, CFURLRef soundURL, CFURLRef localizationURL, CFStringRef alertHeader, CFStringRef alertMessage, CFStringRef defaultButtonTitle); - -extern -SInt32 CFUserNotificationDisplayAlert(CFTimeInterval timeout, CFOptionFlags flags, CFURLRef iconURL, CFURLRef soundURL, CFURLRef localizationURL, CFStringRef alertHeader, CFStringRef alertMessage, CFStringRef defaultButtonTitle, CFStringRef alternateButtonTitle, CFStringRef otherButtonTitle, CFOptionFlags *responseFlags); - - - - -enum { - kCFUserNotificationStopAlertLevel = 0, - kCFUserNotificationNoteAlertLevel = 1, - kCFUserNotificationCautionAlertLevel = 2, - kCFUserNotificationPlainAlertLevel = 3 -}; - -enum { - kCFUserNotificationDefaultResponse = 0, - kCFUserNotificationAlternateResponse = 1, - kCFUserNotificationOtherResponse = 2, - kCFUserNotificationCancelResponse = 3 -}; - -enum { - kCFUserNotificationNoDefaultButtonFlag = (1UL << 5), - kCFUserNotificationUseRadioButtonsFlag = (1UL << 6) -}; - -static __inline__ __attribute__((always_inline)) CFOptionFlags CFUserNotificationCheckBoxChecked(CFIndex i) {return ((CFOptionFlags)(1UL << (8 + i)));} -static __inline__ __attribute__((always_inline)) CFOptionFlags CFUserNotificationSecureTextField(CFIndex i) {return ((CFOptionFlags)(1UL << (16 + i)));} -static __inline__ __attribute__((always_inline)) CFOptionFlags CFUserNotificationPopUpSelection(CFIndex n) {return ((CFOptionFlags)(n << 24));} - - - - -extern -const CFStringRef kCFUserNotificationIconURLKey; - -extern -const CFStringRef kCFUserNotificationSoundURLKey; - -extern -const CFStringRef kCFUserNotificationLocalizationURLKey; - -extern -const CFStringRef kCFUserNotificationAlertHeaderKey; - -extern -const CFStringRef kCFUserNotificationAlertMessageKey; - -extern -const CFStringRef kCFUserNotificationDefaultButtonTitleKey; - -extern -const CFStringRef kCFUserNotificationAlternateButtonTitleKey; - -extern -const CFStringRef kCFUserNotificationOtherButtonTitleKey; - -extern -const CFStringRef kCFUserNotificationProgressIndicatorValueKey; - -extern -const CFStringRef kCFUserNotificationPopUpTitlesKey; - -extern -const CFStringRef kCFUserNotificationTextFieldTitlesKey; - -extern -const CFStringRef kCFUserNotificationCheckBoxTitlesKey; - -extern -const CFStringRef kCFUserNotificationTextFieldValuesKey; - -extern -const CFStringRef kCFUserNotificationPopUpSelectionKey __attribute__((availability(macosx,introduced=10_3))); -} -extern "C" { - -enum { - kCFXMLNodeCurrentVersion = 1 -}; - -typedef const struct __CFXMLNode * CFXMLNodeRef; -typedef CFTreeRef CFXMLTreeRef; -typedef CFIndex CFXMLNodeTypeCode; enum { - kCFXMLNodeTypeDocument = 1, - kCFXMLNodeTypeElement = 2, - kCFXMLNodeTypeAttribute = 3, - kCFXMLNodeTypeProcessingInstruction = 4, - kCFXMLNodeTypeComment = 5, - kCFXMLNodeTypeText = 6, - kCFXMLNodeTypeCDATASection = 7, - kCFXMLNodeTypeDocumentFragment = 8, - kCFXMLNodeTypeEntity = 9, - kCFXMLNodeTypeEntityReference = 10, - kCFXMLNodeTypeDocumentType = 11, - kCFXMLNodeTypeWhitespace = 12, - kCFXMLNodeTypeNotation = 13, - kCFXMLNodeTypeElementTypeDeclaration = 14, - kCFXMLNodeTypeAttributeListDeclaration = 15 -}; - -typedef struct { - CFDictionaryRef attributes; - CFArrayRef attributeOrder; - Boolean isEmpty; - char _reserved[3]; -} CFXMLElementInfo; - -typedef struct { - CFStringRef dataString; -} CFXMLProcessingInstructionInfo; - -typedef struct { - CFURLRef sourceURL; - CFStringEncoding encoding; -} CFXMLDocumentInfo; - -typedef struct { - CFURLRef systemID; - CFStringRef publicID; -} CFXMLExternalID; - -typedef struct { - CFXMLExternalID externalID; -} CFXMLDocumentTypeInfo; - -typedef struct { - CFXMLExternalID externalID; -} CFXMLNotationInfo; - -typedef struct { - - CFStringRef contentDescription; -} CFXMLElementTypeDeclarationInfo; - -typedef struct { - - CFStringRef attributeName; - CFStringRef typeString; - CFStringRef defaultString; -} CFXMLAttributeDeclarationInfo; - -typedef struct { - CFIndex numberOfAttributes; - CFXMLAttributeDeclarationInfo *attributes; -} CFXMLAttributeListDeclarationInfo; - -typedef CFIndex CFXMLEntityTypeCode; enum { - kCFXMLEntityTypeParameter, - kCFXMLEntityTypeParsedInternal, - kCFXMLEntityTypeParsedExternal, - kCFXMLEntityTypeUnparsed, - kCFXMLEntityTypeCharacter -}; - -typedef struct { - CFXMLEntityTypeCode entityType; - CFStringRef replacementText; - CFXMLExternalID entityID; - CFStringRef notationName; -} CFXMLEntityInfo; - -typedef struct { - CFXMLEntityTypeCode entityType; -} CFXMLEntityReferenceInfo; -extern -CFTypeID CFXMLNodeGetTypeID(void) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - -extern -CFXMLNodeRef CFXMLNodeCreate(CFAllocatorRef alloc, CFXMLNodeTypeCode xmlType, CFStringRef dataString, const void *additionalInfoPtr, CFIndex version) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - -extern -CFXMLNodeRef CFXMLNodeCreateCopy(CFAllocatorRef alloc, CFXMLNodeRef origNode) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -extern -CFXMLNodeTypeCode CFXMLNodeGetTypeCode(CFXMLNodeRef node) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -extern -CFStringRef CFXMLNodeGetString(CFXMLNodeRef node) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -extern -const void *CFXMLNodeGetInfoPtr(CFXMLNodeRef node) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -extern -CFIndex CFXMLNodeGetVersion(CFXMLNodeRef node) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - - - -extern -CFXMLTreeRef CFXMLTreeCreateWithNode(CFAllocatorRef allocator, CFXMLNodeRef node) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - -extern -CFXMLNodeRef CFXMLTreeGetNode(CFXMLTreeRef xmlTree) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -} -extern "C" { - -typedef struct __CFXMLParser * CFXMLParserRef; -typedef CFOptionFlags CFXMLParserOptions; enum { - kCFXMLParserValidateDocument = (1UL << 0), - kCFXMLParserSkipMetaData = (1UL << 1), - kCFXMLParserReplacePhysicalEntities = (1UL << 2), - kCFXMLParserSkipWhitespace = (1UL << 3), - kCFXMLParserResolveExternalEntities = (1UL << 4), - kCFXMLParserAddImpliedAttributes = (1UL << 5), - kCFXMLParserAllOptions = 0x00FFFFFF, - kCFXMLParserNoOptions = 0 -}; - - -typedef CFIndex CFXMLParserStatusCode; enum { - kCFXMLStatusParseNotBegun = -2, - kCFXMLStatusParseInProgress = -1, - kCFXMLStatusParseSuccessful = 0, - kCFXMLErrorUnexpectedEOF = 1, - kCFXMLErrorUnknownEncoding, - kCFXMLErrorEncodingConversionFailure, - kCFXMLErrorMalformedProcessingInstruction, - kCFXMLErrorMalformedDTD, - kCFXMLErrorMalformedName, - kCFXMLErrorMalformedCDSect, - kCFXMLErrorMalformedCloseTag, - kCFXMLErrorMalformedStartTag, - kCFXMLErrorMalformedDocument, - kCFXMLErrorElementlessDocument, - kCFXMLErrorMalformedComment, - kCFXMLErrorMalformedCharacterReference, - kCFXMLErrorMalformedParsedCharacterData, - kCFXMLErrorNoData -}; -typedef void * (*CFXMLParserCreateXMLStructureCallBack)(CFXMLParserRef parser, CFXMLNodeRef nodeDesc, void *info); -typedef void (*CFXMLParserAddChildCallBack)(CFXMLParserRef parser, void *parent, void *child, void *info); -typedef void (*CFXMLParserEndXMLStructureCallBack)(CFXMLParserRef parser, void *xmlType, void *info); -typedef CFDataRef (*CFXMLParserResolveExternalEntityCallBack)(CFXMLParserRef parser, CFXMLExternalID *extID, void *info); -typedef Boolean (*CFXMLParserHandleErrorCallBack)(CFXMLParserRef parser, CFXMLParserStatusCode error, void *info); -typedef struct { - CFIndex version; - CFXMLParserCreateXMLStructureCallBack createXMLStructure; - CFXMLParserAddChildCallBack addChild; - CFXMLParserEndXMLStructureCallBack endXMLStructure; - CFXMLParserResolveExternalEntityCallBack resolveExternalEntity; - CFXMLParserHandleErrorCallBack handleError; -} CFXMLParserCallBacks; - -typedef const void * (*CFXMLParserRetainCallBack)(const void *info); -typedef void (*CFXMLParserReleaseCallBack)(const void *info); -typedef CFStringRef (*CFXMLParserCopyDescriptionCallBack)(const void *info); -typedef struct { - CFIndex version; - void * info; - CFXMLParserRetainCallBack retain; - CFXMLParserReleaseCallBack release; - CFXMLParserCopyDescriptionCallBack copyDescription; -} CFXMLParserContext; - -extern -CFTypeID CFXMLParserGetTypeID(void) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); -extern -CFXMLParserRef CFXMLParserCreate(CFAllocatorRef allocator, CFDataRef xmlData, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes, CFXMLParserCallBacks *callBacks, CFXMLParserContext *context) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - - -extern -CFXMLParserRef CFXMLParserCreateWithDataFromURL(CFAllocatorRef allocator, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes, CFXMLParserCallBacks *callBacks, CFXMLParserContext *context) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -extern -void CFXMLParserGetContext(CFXMLParserRef parser, CFXMLParserContext *context) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -extern -void CFXMLParserGetCallBacks(CFXMLParserRef parser, CFXMLParserCallBacks *callBacks) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -extern -CFURLRef CFXMLParserGetSourceURL(CFXMLParserRef parser) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - -extern -CFIndex CFXMLParserGetLocation(CFXMLParserRef parser) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - -extern -CFIndex CFXMLParserGetLineNumber(CFXMLParserRef parser) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - -extern -void *CFXMLParserGetDocument(CFXMLParserRef parser) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - - - -extern -CFXMLParserStatusCode CFXMLParserGetStatusCode(CFXMLParserRef parser) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -extern -CFStringRef CFXMLParserCopyErrorDescription(CFXMLParserRef parser) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - - - -extern -void CFXMLParserAbort(CFXMLParserRef parser, CFXMLParserStatusCode errorCode, CFStringRef errorDescription) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - - - - - -extern -Boolean CFXMLParserParse(CFXMLParserRef parser) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - - - - - - -extern -CFXMLTreeRef CFXMLTreeCreateFromData(CFAllocatorRef allocator, CFDataRef xmlData, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - - - -extern -CFXMLTreeRef CFXMLTreeCreateFromDataWithError(CFAllocatorRef allocator, CFDataRef xmlData, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes, CFDictionaryRef *errorDict) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - -extern -CFXMLTreeRef CFXMLTreeCreateWithDataFromURL(CFAllocatorRef allocator, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - - - - - -extern -CFDataRef CFXMLTreeCreateXMLData(CFAllocatorRef allocator, CFXMLTreeRef xmlTree) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - - - - - - - -extern -CFStringRef CFXMLCreateStringByEscapingEntities(CFAllocatorRef allocator, CFStringRef string, CFDictionaryRef entitiesDictionary); - -extern -CFStringRef CFXMLCreateStringByUnescapingEntities(CFAllocatorRef allocator, CFStringRef string, CFDictionaryRef entitiesDictionary); - - -extern const CFStringRef kCFXMLTreeErrorDescription; - - -extern const CFStringRef kCFXMLTreeErrorLineNumber; - - -extern const CFStringRef kCFXMLTreeErrorLocation; - - -extern const CFStringRef kCFXMLTreeErrorStatusCode; - - -} - -extern "C" double NSFoundationVersionNumber; -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_Protocol -#define _REWRITER_typedef_Protocol -typedef struct objc_object Protocol; -typedef struct {} _objc_exc_Protocol; -#endif - - -extern "C" NSString *NSStringFromSelector(SEL aSelector); -extern "C" SEL NSSelectorFromString(NSString *aSelectorName); - -extern "C" NSString *NSStringFromClass(Class aClass); -extern "C" Class _Nullable NSClassFromString(NSString *aClassName); - -extern "C" NSString *NSStringFromProtocol(Protocol *proto) __attribute__((availability(macosx,introduced=10_5))); -extern "C" Protocol * _Nullable NSProtocolFromString(NSString *namestr) __attribute__((availability(macosx,introduced=10_5))); - -extern "C" const char *NSGetSizeAndAlignment(const char *typePtr, NSUInteger * _Nullable sizep, NSUInteger * _Nullable alignp); - -extern "C" void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2))); -extern "C" void NSLogv(NSString *format, va_list args) __attribute__((format(__NSString__, 1, 0))); - -typedef NSInteger NSComparisonResult; enum {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending}; - - -typedef NSComparisonResult (*NSComparator)(id obj1, id obj2); - - -typedef NSUInteger NSEnumerationOptions; enum { - NSEnumerationConcurrent = (1UL << 0), - NSEnumerationReverse = (1UL << 1), -}; - -typedef NSUInteger NSSortOptions; enum { - NSSortConcurrent = (1UL << 0), - NSSortStable = (1UL << 4), -}; - - -typedef NSInteger NSQualityOfService; enum { - - NSQualityOfServiceUserInteractive = 0x21, - - - NSQualityOfServiceUserInitiated = 0x19, - - - NSQualityOfServiceUtility = 0x11, - - - NSQualityOfServiceBackground = 0x09, - - - NSQualityOfServiceDefault = -1 -} __attribute__((availability(macosx,introduced=10_10))); - -static const NSInteger NSNotFound = 9223372036854775807L; - - - - - - - - - - - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -typedef struct _NSZone NSZone; - -extern "C" NSZone *NSDefaultMallocZone(void) __attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); -extern "C" NSZone *NSCreateZone(NSUInteger startSize, NSUInteger granularity, BOOL canFree) __attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); -extern "C" void NSRecycleZone(NSZone *zone)__attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); - -extern "C" void NSSetZoneName(NSZone * _Nullable zone, NSString *name)__attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); -extern "C" NSString *NSZoneName(NSZone * _Nullable zone) __attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); -extern "C" NSZone * _Nullable NSZoneFromPointer(void *ptr) __attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); - -extern "C" void *NSZoneMalloc(NSZone * _Nullable zone, NSUInteger size) __attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); -extern "C" void *NSZoneCalloc(NSZone * _Nullable zone, NSUInteger numElems, NSUInteger byteSize) __attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); -extern "C" void *NSZoneRealloc(NSZone * _Nullable zone, void * _Nullable ptr, NSUInteger size) __attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); -extern "C" void NSZoneFree(NSZone * _Nullable zone, void *ptr) __attribute__((availability(swift, unavailable, message="Zone-based memory management is unavailable"))); -enum { - NSScannedOption = (1UL << 0), - NSCollectorDisabledOption = (1UL << 1), -}; - -extern "C" void *__attribute__((objc_ownership(strong))) NSAllocateCollectable(NSUInteger size, NSUInteger options) __attribute__((availability(swift, unavailable, message="Garbage Collection is not supported"))); -extern "C" void *__attribute__((objc_ownership(strong))) NSReallocateCollectable(void * _Nullable ptr, NSUInteger size, NSUInteger options) __attribute__((availability(swift, unavailable, message="Garbage Collection is not supported"))); -static __inline__ __attribute__((always_inline)) __attribute__((ns_returns_retained)) id _Nullable NSMakeCollectable(CFTypeRef _Nullable __attribute__((cf_consumed)) cf) __attribute__((availability(swift, unavailable, message="Garbage Collection is not supported"))); -static __inline__ __attribute__((always_inline)) __attribute__((ns_returns_retained)) id _Nullable NSMakeCollectable(CFTypeRef _Nullable __attribute__((cf_consumed)) cf) { - - - - return (cf ? (id)CFMakeCollectable(cf) : __null); - -} - -extern "C" NSUInteger NSPageSize(void); -extern "C" NSUInteger NSLogPageSize(void); -extern "C" NSUInteger NSRoundUpToMultipleOfPageSize(NSUInteger bytes); -extern "C" NSUInteger NSRoundDownToMultipleOfPageSize(NSUInteger bytes); -extern "C" void *NSAllocateMemoryPages(NSUInteger bytes); -extern "C" void NSDeallocateMemoryPages(void *ptr, NSUInteger bytes); -extern "C" void NSCopyMemoryPages(const void *source, void *dest, NSUInteger bytes); -extern "C" NSUInteger NSRealMemoryAvailable(void) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -// @class NSInvocation; -#ifndef _REWRITER_typedef_NSInvocation -#define _REWRITER_typedef_NSInvocation -typedef struct objc_object NSInvocation; -typedef struct {} _objc_exc_NSInvocation; -#endif - -#ifndef _REWRITER_typedef_NSMethodSignature -#define _REWRITER_typedef_NSMethodSignature -typedef struct objc_object NSMethodSignature; -typedef struct {} _objc_exc_NSMethodSignature; -#endif - -#ifndef _REWRITER_typedef_NSCoder -#define _REWRITER_typedef_NSCoder -typedef struct objc_object NSCoder; -typedef struct {} _objc_exc_NSCoder; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSEnumerator -#define _REWRITER_typedef_NSEnumerator -typedef struct objc_object NSEnumerator; -typedef struct {} _objc_exc_NSEnumerator; -#endif - -// @class Protocol; -#ifndef _REWRITER_typedef_Protocol -#define _REWRITER_typedef_Protocol -typedef struct objc_object Protocol; -typedef struct {} _objc_exc_Protocol; -#endif - - - - - - -// @protocol NSCopying - -// - (id)copyWithZone:(nullable NSZone *)zone; - -/* @end */ - - -// @protocol NSMutableCopying - -// - (id)mutableCopyWithZone:(nullable NSZone *)zone; - -/* @end */ - - -// @protocol NSCoding - -// - (void)encodeWithCoder:(NSCoder *)aCoder; -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder; - -/* @end */ - - - - - -// @protocol NSSecureCoding <NSCoding> -/* @required */ - - -// + (BOOL)supportsSecureCoding; -/* @end */ - - - - -// @interface NSObject (NSCoderMethods) - -// + (NSInteger)version; -// + (void)setVersion:(NSInteger)aVersion; -// @property (readonly) Class classForCoder; -// - (nullable id)replacementObjectForCoder:(NSCoder *)aCoder; -// - (nullable id)awakeAfterUsingCoder:(NSCoder *)aDecoder __attribute__((ns_consumes_self)) __attribute__((ns_returns_retained)); - -/* @end */ - - - -// @interface NSObject (NSDeprecatedMethods) - -#if 0 -+ (void)poseAsClass:(Class)aClass __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))) - -__attribute__((unavailable)) - -; -#endif - - -/* @end */ - - - - - - -// @protocol NSDiscardableContent -/* @required */ -// - (BOOL)beginContentAccess; -// - (void)endContentAccess; -// - (void)discardContentIfPossible; -// - (BOOL)isContentDiscarded; -/* @end */ - - -// @interface NSObject (NSDiscardableContentProxy) -// @property (readonly, retain) id autoContentAccessingProxy __attribute__((availability(macosx,introduced=10_6))); -/* @end */ - - - - -extern "C" id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone * _Nullable zone) ; - -extern "C" void NSDeallocateObject(id object) ; - -extern "C" id NSCopyObject(id object, NSUInteger extraBytes, NSZone * _Nullable zone) __attribute__((availability(macosx,introduced=10_0,deprecated=10_8,message="" ))); - -extern "C" BOOL NSShouldRetainWithZone(id anObject, NSZone * _Nullable requestedZone) ; - -extern "C" void NSIncrementExtraRefCount(id object) ; - -extern "C" BOOL NSDecrementExtraRefCountWasZero(id object) ; - -extern "C" NSUInteger NSExtraRefCount(id object) ; -static __inline__ __attribute__((always_inline)) __attribute__((cf_returns_retained)) CFTypeRef _Nullable CFBridgingRetain(id _Nullable X) { - return X ? CFRetain((CFTypeRef)X) : __null; -} - - -static __inline__ __attribute__((always_inline)) id _Nullable CFBridgingRelease(CFTypeRef __attribute__((cf_consumed)) _Nullable X) { - return ((id (*)(id, SEL))(void *)objc_msgSend)((id)CFMakeCollectable(X), sel_registerName("autorelease")); -} - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -typedef struct { - unsigned long state; - id __attribute__((objc_ownership(none))) _Nullable * _Nullable itemsPtr; - unsigned long * _Nullable mutationsPtr; - unsigned long extra[5]; -} NSFastEnumerationState; - -// @protocol NSFastEnumeration - -// - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __attribute__((objc_ownership(none))) [])buffer count:(NSUInteger)len; - -/* @end */ - - - -#ifndef _REWRITER_typedef_NSEnumerator -#define _REWRITER_typedef_NSEnumerator -typedef struct objc_object NSEnumerator; -typedef struct {} _objc_exc_NSEnumerator; -#endif - -struct NSEnumerator_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (nullable ObjectType)nextObject; - -/* @end */ - - -// @interface NSEnumerator<ObjectType> (NSExtendedEnumerator) - -// @property (readonly, copy) NSArray<ObjectType> *allObjects; - -/* @end */ - - - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - - - - - -#ifndef _REWRITER_typedef_NSValue -#define _REWRITER_typedef_NSValue -typedef struct objc_object NSValue; -typedef struct {} _objc_exc_NSValue; -#endif - -struct NSValue_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (void)getValue:(void *)value; -// @property (readonly) const char *objCType __attribute__((objc_returns_inner_pointer)); - -// - (instancetype)initWithBytes:(const void *)value objCType:(const char *)type __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSValue (NSValueCreation) - -// + (NSValue *)valueWithBytes:(const void *)value objCType:(const char *)type; -// + (NSValue *)value:(const void *)value withObjCType:(const char *)type; - -/* @end */ - - -// @interface NSValue (NSValueExtensionMethods) - -// + (NSValue *)valueWithNonretainedObject:(nullable id)anObject; -// @property (nullable, readonly) id nonretainedObjectValue; - -// + (NSValue *)valueWithPointer:(nullable const void *)pointer; -// @property (nullable, readonly) void *pointerValue; - -// - (BOOL)isEqualToValue:(NSValue *)value; - -/* @end */ - - - -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - -struct NSNumber_IMPL { - struct NSValue_IMPL NSValue_IVARS; -}; - - -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithChar:(char)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithUnsignedChar:(unsigned char)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithShort:(short)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithUnsignedShort:(unsigned short)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithInt:(int)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithUnsignedInt:(unsigned int)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithLong:(long)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithUnsignedLong:(unsigned long)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithLongLong:(long long)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithUnsignedLongLong:(unsigned long long)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithFloat:(float)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithDouble:(double)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithBool:(BOOL)value __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithInteger:(NSInteger)value __attribute__((availability(macosx,introduced=10_5))) __attribute__((objc_designated_initializer)); -// - (NSNumber *)initWithUnsignedInteger:(NSUInteger)value __attribute__((availability(macosx,introduced=10_5))) __attribute__((objc_designated_initializer)); - -// @property (readonly) char charValue; -// @property (readonly) unsigned char unsignedCharValue; -// @property (readonly) short shortValue; -// @property (readonly) unsigned short unsignedShortValue; -// @property (readonly) int intValue; -// @property (readonly) unsigned int unsignedIntValue; -// @property (readonly) long longValue; -// @property (readonly) unsigned long unsignedLongValue; -// @property (readonly) long long longLongValue; -// @property (readonly) unsigned long long unsignedLongLongValue; -// @property (readonly) float floatValue; -// @property (readonly) double doubleValue; -// @property (readonly) BOOL boolValue; -// @property (readonly) NSInteger integerValue __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly) NSUInteger unsignedIntegerValue __attribute__((availability(macosx,introduced=10_5))); - -// @property (readonly, copy) NSString *stringValue; - -// - (NSComparisonResult)compare:(NSNumber *)otherNumber; - -// - (BOOL)isEqualToNumber:(NSNumber *)number; - -// - (NSString *)descriptionWithLocale:(nullable id)locale; - -/* @end */ - - -// @interface NSNumber (NSNumberCreation) - -// + (NSNumber *)numberWithChar:(char)value; -// + (NSNumber *)numberWithUnsignedChar:(unsigned char)value; -// + (NSNumber *)numberWithShort:(short)value; -// + (NSNumber *)numberWithUnsignedShort:(unsigned short)value; -// + (NSNumber *)numberWithInt:(int)value; -// + (NSNumber *)numberWithUnsignedInt:(unsigned int)value; -// + (NSNumber *)numberWithLong:(long)value; -// + (NSNumber *)numberWithUnsignedLong:(unsigned long)value; -// + (NSNumber *)numberWithLongLong:(long long)value; -// + (NSNumber *)numberWithUnsignedLongLong:(unsigned long long)value; -// + (NSNumber *)numberWithFloat:(float)value; -// + (NSNumber *)numberWithDouble:(double)value; -// + (NSNumber *)numberWithBool:(BOOL)value; -// + (NSNumber *)numberWithInteger:(NSInteger)value __attribute__((availability(macosx,introduced=10_5))); -// + (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -typedef struct _NSRange { - NSUInteger location; - NSUInteger length; -} NSRange; - -typedef NSRange *NSRangePointer; - -static __inline__ __attribute__((always_inline)) NSRange NSMakeRange(NSUInteger loc, NSUInteger len) { - NSRange r; - r.location = loc; - r.length = len; - return r; -} - -static __inline__ __attribute__((always_inline)) NSUInteger NSMaxRange(NSRange range) { - return (range.location + range.length); -} - -static __inline__ __attribute__((always_inline)) BOOL NSLocationInRange(NSUInteger loc, NSRange range) { - return (!(loc < range.location) && (loc - range.location) < range.length) ? ((bool)1) : ((bool)0); -} - -static __inline__ __attribute__((always_inline)) BOOL NSEqualRanges(NSRange range1, NSRange range2) { - return (range1.location == range2.location && range1.length == range2.length); -} - -extern "C" NSRange NSUnionRange(NSRange range1, NSRange range2); -extern "C" NSRange NSIntersectionRange(NSRange range1, NSRange range2); -extern "C" NSString *NSStringFromRange(NSRange range); -extern "C" NSRange NSRangeFromString(NSString *aString); - -// @interface NSValue (NSValueRangeExtensions) - -// + (NSValue *)valueWithRange:(NSRange)range; -// @property (readonly) NSRange rangeValue; - -/* @end */ - - - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSIndexSet -#define _REWRITER_typedef_NSIndexSet -typedef struct objc_object NSIndexSet; -typedef struct {} _objc_exc_NSIndexSet; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - - - - - - - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -struct NSArray_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly) NSUInteger count; -// - (ObjectType)objectAtIndex:(NSUInteger)index; -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (instancetype)initWithObjects:(const ObjectType [])objects count:(NSUInteger)cnt __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSArray<ObjectType> (NSExtendedArray) - -// - (NSArray<ObjectType> *)arrayByAddingObject:(ObjectType)anObject; -// - (NSArray<ObjectType> *)arrayByAddingObjectsFromArray:(NSArray<ObjectType> *)otherArray; -// - (NSString *)componentsJoinedByString:(NSString *)separator; -// - (BOOL)containsObject:(ObjectType)anObject; -// @property (readonly, copy) NSString *description; -// - (NSString *)descriptionWithLocale:(nullable id)locale; -// - (NSString *)descriptionWithLocale:(nullable id)locale indent:(NSUInteger)level; -// - (nullable ObjectType)firstObjectCommonWithArray:(NSArray<ObjectType> *)otherArray; -// - (void)getObjects:(ObjectType __attribute__((objc_ownership(none))) [])objects range:(NSRange)range; -// - (NSUInteger)indexOfObject:(ObjectType)anObject; -// - (NSUInteger)indexOfObject:(ObjectType)anObject inRange:(NSRange)range; -// - (NSUInteger)indexOfObjectIdenticalTo:(ObjectType)anObject; -// - (NSUInteger)indexOfObjectIdenticalTo:(ObjectType)anObject inRange:(NSRange)range; -// - (BOOL)isEqualToArray:(NSArray<ObjectType> *)otherArray; -// @property (nullable, nonatomic, readonly) ObjectType firstObject __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, nonatomic, readonly) ObjectType lastObject; -// - (NSEnumerator<ObjectType> *)objectEnumerator; -// - (NSEnumerator<ObjectType> *)reverseObjectEnumerator; -// @property (readonly, copy) NSData *sortedArrayHint; -// - (NSArray<ObjectType> *)sortedArrayUsingFunction:(NSInteger (*)(ObjectType, ObjectType, void * _Nullable))comparator context:(nullable void *)context; -// - (NSArray<ObjectType> *)sortedArrayUsingFunction:(NSInteger (*)(ObjectType, ObjectType, void * _Nullable))comparator context:(nullable void *)context hint:(nullable NSData *)hint; -// - (NSArray<ObjectType> *)sortedArrayUsingSelector:(SEL)comparator; -// - (NSArray<ObjectType> *)subarrayWithRange:(NSRange)range; -// - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile; -// - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically; - -// - (void)makeObjectsPerformSelector:(SEL)aSelector __attribute__((availability(swift, unavailable, message="Use enumerateObjectsUsingBlock: or a for loop instead"))); -// - (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(nullable id)argument __attribute__((availability(swift, unavailable, message="Use enumerateObjectsUsingBlock: or a for loop instead"))); - -// - (NSArray<ObjectType> *)objectsAtIndexes:(NSIndexSet *)indexes; - -// - (ObjectType)objectAtIndexedSubscript:(NSUInteger)idx __attribute__((availability(macosx,introduced=10_8))); - -// - (void)enumerateObjectsUsingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); -// - (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); -// - (void)enumerateObjectsAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts usingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); - -// - (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSUInteger)indexOfObjectWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSUInteger)indexOfObjectAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); - -// - (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSIndexSet *)indexesOfObjectsWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSIndexSet *)indexesOfObjectsAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); - -// - (NSArray<ObjectType> *)sortedArrayUsingComparator:(NSComparator)cmptr __attribute__((availability(macosx,introduced=10_6))); -// - (NSArray<ObjectType> *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr __attribute__((availability(macosx,introduced=10_6))); - -typedef NSUInteger NSBinarySearchingOptions; enum { - NSBinarySearchingFirstEqual = (1UL << 8), - NSBinarySearchingLastEqual = (1UL << 9), - NSBinarySearchingInsertionIndex = (1UL << 10), -}; - -// - (NSUInteger)indexOfObject:(ObjectType)obj inSortedRange:(NSRange)r options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator)cmp __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -// @interface NSArray<ObjectType> (NSArrayCreation) - -// + (instancetype)array; -// + (instancetype)arrayWithObject:(ObjectType)anObject; -// + (instancetype)arrayWithObjects:(const ObjectType [])objects count:(NSUInteger)cnt; -// + (instancetype)arrayWithObjects:(ObjectType)firstObj, ... __attribute__((sentinel(0,1))); -// + (instancetype)arrayWithArray:(NSArray<ObjectType> *)array; - -// - (instancetype)initWithObjects:(ObjectType)firstObj, ... __attribute__((sentinel(0,1))); -// - (instancetype)initWithArray:(NSArray<ObjectType> *)array; -// - (instancetype)initWithArray:(NSArray<ObjectType> *)array copyItems:(BOOL)flag; - -// + (nullable NSArray<ObjectType> *)arrayWithContentsOfFile:(NSString *)path; -// + (nullable NSArray<ObjectType> *)arrayWithContentsOfURL:(NSURL *)url; -// - (nullable NSArray<ObjectType> *)initWithContentsOfFile:(NSString *)path; -// - (nullable NSArray<ObjectType> *)initWithContentsOfURL:(NSURL *)url; - -/* @end */ - - -// @interface NSArray<ObjectType> (NSDeprecated) - - - -// - (void)getObjects:(ObjectType __attribute__((objc_ownership(none))) [])objects; - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSMutableArray -#define _REWRITER_typedef_NSMutableArray -typedef struct objc_object NSMutableArray; -typedef struct {} _objc_exc_NSMutableArray; -#endif - -struct NSMutableArray_IMPL { - struct NSArray_IMPL NSArray_IVARS; -}; - - -// - (void)addObject:(ObjectType)anObject; -// - (void)insertObject:(ObjectType)anObject atIndex:(NSUInteger)index; -// - (void)removeLastObject; -// - (void)removeObjectAtIndex:(NSUInteger)index; -// - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(ObjectType)anObject; -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (instancetype)initWithCapacity:(NSUInteger)numItems __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSMutableArray<ObjectType> (NSExtendedMutableArray) - -// - (void)addObjectsFromArray:(NSArray<ObjectType> *)otherArray; -// - (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2; -// - (void)removeAllObjects; -// - (void)removeObject:(ObjectType)anObject inRange:(NSRange)range; -// - (void)removeObject:(ObjectType)anObject; -// - (void)removeObjectIdenticalTo:(ObjectType)anObject inRange:(NSRange)range; -// - (void)removeObjectIdenticalTo:(ObjectType)anObject; -// - (void)removeObjectsFromIndices:(NSUInteger *)indices numIndices:(NSUInteger)cnt __attribute__((availability(macosx,introduced=10_0,deprecated=10_6,message="" ))); -// - (void)removeObjectsInArray:(NSArray<ObjectType> *)otherArray; -// - (void)removeObjectsInRange:(NSRange)range; -// - (void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray<ObjectType> *)otherArray range:(NSRange)otherRange; -// - (void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray<ObjectType> *)otherArray; -// - (void)setArray:(NSArray<ObjectType> *)otherArray; -// - (void)sortUsingFunction:(NSInteger (*)(ObjectType, ObjectType, void * _Nullable))compare context:(nullable void *)context; -// - (void)sortUsingSelector:(SEL)comparator; - -// - (void)insertObjects:(NSArray<ObjectType> *)objects atIndexes:(NSIndexSet *)indexes; -// - (void)removeObjectsAtIndexes:(NSIndexSet *)indexes; -// - (void)replaceObjectsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray<ObjectType> *)objects; - -// - (void)setObject:(ObjectType)obj atIndexedSubscript:(NSUInteger)idx __attribute__((availability(macosx,introduced=10_8))); - -// - (void)sortUsingComparator:(NSComparator)cmptr __attribute__((availability(macosx,introduced=10_6))); -// - (void)sortWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -// @interface NSMutableArray<ObjectType> (NSMutableArrayCreation) - -// + (instancetype)arrayWithCapacity:(NSUInteger)numItems; - -// + (nullable NSMutableArray<ObjectType> *)arrayWithContentsOfFile:(NSString *)path; -// + (nullable NSMutableArray<ObjectType> *)arrayWithContentsOfURL:(NSURL *)url; -// - (nullable NSMutableArray<ObjectType> *)initWithContentsOfFile:(NSString *)path; -// - (nullable NSMutableArray<ObjectType> *)initWithContentsOfURL:(NSURL *)url; - -/* @end */ - - -#ifndef _REWRITER_typedef_NSAutoreleasePool -#define _REWRITER_typedef_NSAutoreleasePool -typedef struct objc_object NSAutoreleasePool; -typedef struct {} _objc_exc_NSAutoreleasePool; -#endif - -struct NSAutoreleasePool_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_token; - void *_reserved3; - void *_reserved2; - void *_reserved; -}; - - -// + (void)addObject:(id)anObject; - -// - (void)addObject:(id)anObject; - -// - (void)drain; - -/* @end */ - - - - - - - - - - -typedef unsigned short unichar; - - - - - - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSCharacterSet -#define _REWRITER_typedef_NSCharacterSet -typedef struct objc_object NSCharacterSet; -typedef struct {} _objc_exc_NSCharacterSet; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSLocale -#define _REWRITER_typedef_NSLocale -typedef struct objc_object NSLocale; -typedef struct {} _objc_exc_NSLocale; -#endif - - - - - - -typedef NSUInteger NSStringCompareOptions; enum { - NSCaseInsensitiveSearch = 1, - NSLiteralSearch = 2, - NSBackwardsSearch = 4, - NSAnchoredSearch = 8, - NSNumericSearch = 64, - NSDiacriticInsensitiveSearch __attribute__((availability(macosx,introduced=10_5))) = 128, - NSWidthInsensitiveSearch __attribute__((availability(macosx,introduced=10_5))) = 256, - NSForcedOrderingSearch __attribute__((availability(macosx,introduced=10_5))) = 512, - NSRegularExpressionSearch __attribute__((availability(macosx,introduced=10_7))) = 1024 -}; - - - - - -typedef NSUInteger NSStringEncoding; -enum { - NSASCIIStringEncoding = 1, - NSNEXTSTEPStringEncoding = 2, - NSJapaneseEUCStringEncoding = 3, - NSUTF8StringEncoding = 4, - NSISOLatin1StringEncoding = 5, - NSSymbolStringEncoding = 6, - NSNonLossyASCIIStringEncoding = 7, - NSShiftJISStringEncoding = 8, - NSISOLatin2StringEncoding = 9, - NSUnicodeStringEncoding = 10, - NSWindowsCP1251StringEncoding = 11, - NSWindowsCP1252StringEncoding = 12, - NSWindowsCP1253StringEncoding = 13, - NSWindowsCP1254StringEncoding = 14, - NSWindowsCP1250StringEncoding = 15, - NSISO2022JPStringEncoding = 21, - NSMacOSRomanStringEncoding = 30, - - NSUTF16StringEncoding = NSUnicodeStringEncoding, - - NSUTF16BigEndianStringEncoding = 0x90000100, - NSUTF16LittleEndianStringEncoding = 0x94000100, - - NSUTF32StringEncoding = 0x8c000100, - NSUTF32BigEndianStringEncoding = 0x98000100, - NSUTF32LittleEndianStringEncoding = 0x9c000100 -}; - -typedef NSUInteger NSStringEncodingConversionOptions; enum { - NSStringEncodingConversionAllowLossy = 1, - NSStringEncodingConversionExternalRepresentation = 2 -}; - - - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -struct NSString_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - - - - -// @property (readonly) NSUInteger length; -// - (unichar)characterAtIndex:(NSUInteger)index; - - - -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSString (NSStringExtensionMethods) -// - (NSString *)substringFromIndex:(NSUInteger)from; -// - (NSString *)substringToIndex:(NSUInteger)to; -// - (NSString *)substringWithRange:(NSRange)range; - -// - (void)getCharacters:(unichar *)buffer range:(NSRange)range; - - - - - - -// - (NSComparisonResult)compare:(NSString *)string; -// - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask; -// - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange; -// - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange locale:(nullable id)locale; -// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)string; -// - (NSComparisonResult)localizedCompare:(NSString *)string; -// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string; - - - -// - (NSComparisonResult)localizedStandardCompare:(NSString *)string __attribute__((availability(macosx,introduced=10_6))); - -// - (BOOL)isEqualToString:(NSString *)aString; - - - - - - -// - (BOOL)hasPrefix:(NSString *)str; -// - (BOOL)hasSuffix:(NSString *)str; - -// - (NSString *)commonPrefixWithString:(NSString *)str options:(NSStringCompareOptions)mask; - - - -// - (BOOL)containsString:(NSString *)str __attribute__((availability(macosx,introduced=10_10))); -// - (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str __attribute__((availability(macosx,introduced=10_10))); - - - -// - (BOOL)localizedStandardContainsString:(NSString *)str __attribute__((availability(macosx,introduced=10_11))); -// - (NSRange)localizedStandardRangeOfString:(NSString *)str __attribute__((availability(macosx,introduced=10_11))); - - - - - -// - (NSRange)rangeOfString:(NSString *)searchString; -// - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask; -// - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)searchRange; -// - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(nullable NSLocale *)locale __attribute__((availability(macosx,introduced=10_5))); - - - -// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet; -// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask; -// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask range:(NSRange)searchRange; - -// - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index; -// - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range __attribute__((availability(macosx,introduced=10_5))); - -// - (NSString *)stringByAppendingString:(NSString *)aString; -// - (NSString *)stringByAppendingFormat:(NSString *)format, ... __attribute__((format(__NSString__, 1, 2))); - - - - - - -// @property (readonly) double doubleValue; -// @property (readonly) float floatValue; -// @property (readonly) int intValue; -// @property (readonly) NSInteger integerValue __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly) long long longLongValue __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly) BOOL boolValue __attribute__((availability(macosx,introduced=10_5))); - - - - - - -// @property (readonly, copy) NSString *uppercaseString; -// @property (readonly, copy) NSString *lowercaseString; -// @property (readonly, copy) NSString *capitalizedString; - - - -// @property (readonly, copy) NSString *localizedUppercaseString __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly, copy) NSString *localizedLowercaseString __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly, copy) NSString *localizedCapitalizedString __attribute__((availability(macosx,introduced=10_11))); - - - -// - (NSString *)uppercaseStringWithLocale:(nullable NSLocale *)locale __attribute__((availability(macosx,introduced=10_8))); -// - (NSString *)lowercaseStringWithLocale:(nullable NSLocale *)locale __attribute__((availability(macosx,introduced=10_8))); -// - (NSString *)capitalizedStringWithLocale:(nullable NSLocale *)locale __attribute__((availability(macosx,introduced=10_8))); - - - - -// - (void)getLineStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)lineEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range; -// - (NSRange)lineRangeForRange:(NSRange)range; - -// - (void)getParagraphStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)parEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range; -// - (NSRange)paragraphRangeForRange:(NSRange)range; - -typedef NSUInteger NSStringEnumerationOptions; enum { - - NSStringEnumerationByLines = 0, - NSStringEnumerationByParagraphs = 1, - NSStringEnumerationByComposedCharacterSequences = 2, - NSStringEnumerationByWords = 3, - NSStringEnumerationBySentences = 4, - - NSStringEnumerationReverse = 1UL << 8, - NSStringEnumerationSubstringNotRequired = 1UL << 9, - NSStringEnumerationLocalized = 1UL << 10 -}; - - - -// - (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); -// - (void)enumerateLinesUsingBlock:(void (^)(NSString *line, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); - - - - -// @property (nullable, readonly) __attribute__((objc_ownership(strong))) const char *UTF8String __attribute__((objc_returns_inner_pointer)); - -// @property (readonly) NSStringEncoding fastestEncoding; -// @property (readonly) NSStringEncoding smallestEncoding; - -// - (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)lossy; -// - (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding; - -// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding; - - - -// - (nullable __attribute__((objc_ownership(strong))) const char *)cStringUsingEncoding:(NSStringEncoding)encoding __attribute__((objc_returns_inner_pointer)); -// - (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding; -// - (BOOL)getBytes:(nullable void *)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(nullable NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(nullable NSRangePointer)leftover; - - - -// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc; -// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc; - -// + (const NSStringEncoding *)availableStringEncodings; -// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding; - - - -// + (NSStringEncoding)defaultCStringEncoding; - - - - -// @property (readonly, copy) NSString *decomposedStringWithCanonicalMapping; -// @property (readonly, copy) NSString *precomposedStringWithCanonicalMapping; -// @property (readonly, copy) NSString *decomposedStringWithCompatibilityMapping; -// @property (readonly, copy) NSString *precomposedStringWithCompatibilityMapping; - -// - (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator; -// - (NSArray<NSString *> *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator __attribute__((availability(macosx,introduced=10_5))); - -// - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set; -// - (NSString *)stringByPaddingToLength:(NSUInteger)newLength withString:(NSString *)padString startingAtIndex:(NSUInteger)padIndex; - - - -// - (NSString *)stringByFoldingWithOptions:(NSStringCompareOptions)options locale:(nullable NSLocale *)locale __attribute__((availability(macosx,introduced=10_5))); - - - -// - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange __attribute__((availability(macosx,introduced=10_5))); - - - -// - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement __attribute__((availability(macosx,introduced=10_5))); - - - -// - (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement __attribute__((availability(macosx,introduced=10_5))); - - - -// - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse __attribute__((availability(macosx,introduced=10_11))); - -extern "C" NSString * const NSStringTransformLatinToKatakana __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformLatinToHiragana __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformLatinToHangul __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformLatinToArabic __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformLatinToHebrew __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformLatinToThai __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformLatinToCyrillic __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformLatinToGreek __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformToLatin __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformMandarinToLatin __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformHiraganaToKatakana __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformFullwidthToHalfwidth __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformToXMLHex __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformToUnicodeName __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformStripCombiningMarks __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSStringTransformStripDiacritics __attribute__((availability(macosx,introduced=10_11))); - - - - -// - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error; -// - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error; - -// @property (readonly, copy) NSString *description; - -// @property (readonly) NSUInteger hash; - - - - - - -// - (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer; -// - (instancetype)initWithCharacters:(const unichar *)characters length:(NSUInteger)length; -// - (nullable instancetype)initWithUTF8String:(const char *)nullTerminatedCString; -// - (instancetype)initWithString:(NSString *)aString; -// - (instancetype)initWithFormat:(NSString *)format, ... __attribute__((format(__NSString__, 1, 2))); -// - (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argList __attribute__((format(__NSString__, 1, 0))); -// - (instancetype)initWithFormat:(NSString *)format locale:(nullable id)locale, ... __attribute__((format(__NSString__, 1, 3))); -// - (instancetype)initWithFormat:(NSString *)format locale:(nullable id)locale arguments:(va_list)argList __attribute__((format(__NSString__, 1, 0))); -// - (nullable instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding; -// - (nullable instancetype)initWithBytes:(const void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding; -// - (nullable instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)freeBuffer; - -// + (instancetype)string; -// + (instancetype)stringWithString:(NSString *)string; -// + (instancetype)stringWithCharacters:(const unichar *)characters length:(NSUInteger)length; -// + (nullable instancetype)stringWithUTF8String:(const char *)nullTerminatedCString; -// + (instancetype)stringWithFormat:(NSString *)format, ... __attribute__((format(__NSString__, 1, 2))); -// + (instancetype)localizedStringWithFormat:(NSString *)format, ... __attribute__((format(__NSString__, 1, 2))); - -// - (nullable instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding; -// + (nullable instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc; - - - -// - (nullable instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error; -// - (nullable instancetype)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error; -// + (nullable instancetype)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error; -// + (nullable instancetype)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error; - - - -// - (nullable instancetype)initWithContentsOfURL:(NSURL *)url usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; -// - (nullable instancetype)initWithContentsOfFile:(NSString *)path usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; -// + (nullable instancetype)stringWithContentsOfURL:(NSURL *)url usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; -// + (nullable instancetype)stringWithContentsOfFile:(NSString *)path usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; - -/* @end */ - - - -// @interface NSString (NSStringEncodingDetection) -#if 0 -+ (NSStringEncoding)stringEncodingForData:(NSData *)data - encodingOptions:(nullable NSDictionary<NSString *, id> *)opts - convertedString:(NSString * _Nullable * _Nullable)string - usedLossyConversion:(nullable BOOL *)usedLossyConversion __attribute__((availability(macosx,introduced=10_10))); -#endif - - - - -extern "C" NSString * const NSStringEncodingDetectionSuggestedEncodingsKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSStringEncodingDetectionDisallowedEncodingsKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSStringEncodingDetectionUseOnlySuggestedEncodingsKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSStringEncodingDetectionAllowLossyKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSStringEncodingDetectionFromWindowsKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSStringEncodingDetectionLossySubstitutionKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSStringEncodingDetectionLikelyLanguageKey __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSMutableString -#define _REWRITER_typedef_NSMutableString -typedef struct objc_object NSMutableString; -typedef struct {} _objc_exc_NSMutableString; -#endif - -struct NSMutableString_IMPL { - struct NSString_IMPL NSString_IVARS; -}; - - - - - - -// - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString; - -/* @end */ - - -// @interface NSMutableString (NSMutableStringExtensionMethods) - - - -// - (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc; -// - (void)deleteCharactersInRange:(NSRange)range; -// - (void)appendString:(NSString *)aString; -// - (void)appendFormat:(NSString *)format, ... __attribute__((format(__NSString__, 1, 2))); -// - (void)setString:(NSString *)aString; - - - -// - (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange; - - - -// - (BOOL)applyTransform:(NSString *)transform reverse:(BOOL)reverse range:(NSRange)range updatedRange:(nullable NSRangePointer)resultingRange __attribute__((availability(macosx,introduced=10_11))); - - - -// - (NSMutableString *)initWithCapacity:(NSUInteger)capacity; -// + (NSMutableString *)stringWithCapacity:(NSUInteger)capacity; - -/* @end */ - - - - -extern "C" NSString * const NSCharacterConversionException; -extern "C" NSString * const NSParseErrorException; - - - - -// @interface NSString (NSExtendedStringPropertyListParsing) - - - -// - (id)propertyList; -// - (nullable NSDictionary *)propertyListFromStringsFileFormat; - -/* @end */ - - -// @interface NSString (NSStringDeprecated) - - - -// - (nullable const char *)cString __attribute__((objc_returns_inner_pointer)) __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (nullable const char *)lossyCString __attribute__((objc_returns_inner_pointer)) __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (NSUInteger)cStringLength __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)getCString:(char *)bytes __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)getCString:(char *)bytes maxLength:(NSUInteger)maxLength __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)getCString:(char *)bytes maxLength:(NSUInteger)maxLength range:(NSRange)aRange remainingRange:(nullable NSRangePointer)leftoverRange __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (nullable id)initWithContentsOfFile:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (nullable id)initWithContentsOfURL:(NSURL *)url __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// + (nullable id)stringWithContentsOfFile:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// + (nullable id)stringWithContentsOfURL:(NSURL *)url __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (nullable id)initWithCStringNoCopy:(char *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (nullable id)initWithCString:(const char *)bytes length:(NSUInteger)length __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (nullable id)initWithCString:(const char *)bytes __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// + (nullable id)stringWithCString:(const char *)bytes length:(NSUInteger)length __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// + (nullable id)stringWithCString:(const char *)bytes __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - - - -// - (void)getCharacters:(unichar *)buffer; - -/* @end */ - - -enum { - NSProprietaryStringEncoding = 65536 -}; - -#ifndef _REWRITER_typedef_NSSimpleCString -#define _REWRITER_typedef_NSSimpleCString -typedef struct objc_object NSSimpleCString; -typedef struct {} _objc_exc_NSSimpleCString; -#endif - -struct NSSimpleCString_IMPL { - struct NSString_IMPL NSString_IVARS; - char *bytes; - int numBytes; - int _unused; -}; - -/* @end */ - - - -#ifndef _REWRITER_typedef_NSConstantString -#define _REWRITER_typedef_NSConstantString -typedef struct objc_object NSConstantString; -typedef struct {} _objc_exc_NSConstantString; -#endif - -struct NSConstantString_IMPL { - struct NSSimpleCString_IMPL NSSimpleCString_IVARS; -}; - -/* @end */ - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - - - - - - - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -struct NSDictionary_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly) NSUInteger count; -// - (nullable ObjectType)objectForKey:(KeyType)aKey; -// - (NSEnumerator<KeyType> *)keyEnumerator; -// - (instancetype)init __attribute__((objc_designated_initializer)); - - - -// - (instancetype)initWithObjects:(const ObjectType [])objects forKeys:(const KeyType <NSCopying> [])keys count:(NSUInteger)cnt __attribute__((objc_designated_initializer)); - -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSDictionary<KeyType, ObjectType> (NSExtendedDictionary) - -// @property (readonly, copy) NSArray<KeyType> *allKeys; -// - (NSArray<KeyType> *)allKeysForObject:(ObjectType)anObject; -// @property (readonly, copy) NSArray<ObjectType> *allValues; -// @property (readonly, copy) NSString *description; -// @property (readonly, copy) NSString *descriptionInStringsFileFormat; -// - (NSString *)descriptionWithLocale:(nullable id)locale; -// - (NSString *)descriptionWithLocale:(nullable id)locale indent:(NSUInteger)level; -// - (BOOL)isEqualToDictionary:(NSDictionary<KeyType, ObjectType> *)otherDictionary; -// - (NSEnumerator<ObjectType> *)objectEnumerator; -// - (NSArray<ObjectType> *)objectsForKeys:(NSArray<KeyType> *)keys notFoundMarker:(ObjectType)marker; -// - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile; -// - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically; - -// - (NSArray<KeyType> *)keysSortedByValueUsingSelector:(SEL)comparator; - -// - (void)getObjects:(ObjectType __attribute__((objc_ownership(none))) [])objects andKeys:(KeyType __attribute__((objc_ownership(none))) [])keys count:(NSUInteger)count __attribute__((availability(macosx,introduced=10_7))); - -// - (nullable ObjectType)objectForKeyedSubscript:(KeyType)key __attribute__((availability(macosx,introduced=10_8))); - -// - (void)enumerateKeysAndObjectsUsingBlock:(void (^)(KeyType key, ObjectType obj, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); -// - (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(KeyType key, ObjectType obj, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); - -// - (NSArray<KeyType> *)keysSortedByValueUsingComparator:(NSComparator)cmptr __attribute__((availability(macosx,introduced=10_6))); -// - (NSArray<KeyType> *)keysSortedByValueWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr __attribute__((availability(macosx,introduced=10_6))); - -// - (NSSet<KeyType> *)keysOfEntriesPassingTest:(BOOL (^)(KeyType key, ObjectType obj, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSSet<KeyType> *)keysOfEntriesWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(KeyType key, ObjectType obj, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -// @interface NSDictionary<KeyType, ObjectType> (NSDeprecated) - -// - (void)getObjects:(ObjectType __attribute__((objc_ownership(none))) [])objects andKeys:(KeyType __attribute__((objc_ownership(none))) [])keys; -/* @end */ - - -// @interface NSDictionary<KeyType, ObjectType> (NSDictionaryCreation) - -// + (instancetype)dictionary; -// + (instancetype)dictionaryWithObject:(ObjectType)object forKey:(KeyType <NSCopying>)key; - - - -// + (instancetype)dictionaryWithObjects:(const ObjectType [])objects forKeys:(const KeyType <NSCopying> [])keys count:(NSUInteger)cnt; - - -// + (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ... __attribute__((sentinel(0,1))) __attribute__((availability(swift, unavailable, message="Use dictionary literals instead"))); - -// + (instancetype)dictionaryWithDictionary:(NSDictionary<KeyType, ObjectType> *)dict; -// + (instancetype)dictionaryWithObjects:(NSArray<ObjectType> *)objects forKeys:(NSArray<KeyType <NSCopying>> *)keys; - -// - (instancetype)initWithObjectsAndKeys:(id)firstObject, ... __attribute__((sentinel(0,1))); -// - (instancetype)initWithDictionary:(NSDictionary<KeyType, ObjectType> *)otherDictionary; -// - (instancetype)initWithDictionary:(NSDictionary<KeyType, ObjectType> *)otherDictionary copyItems:(BOOL)flag; -// - (instancetype)initWithObjects:(NSArray<ObjectType> *)objects forKeys:(NSArray<KeyType <NSCopying>> *)keys; - -// + (nullable NSDictionary<KeyType, ObjectType> *)dictionaryWithContentsOfFile:(NSString *)path; -// + (nullable NSDictionary<KeyType, ObjectType> *)dictionaryWithContentsOfURL:(NSURL *)url; -// - (nullable NSDictionary<KeyType, ObjectType> *)initWithContentsOfFile:(NSString *)path; -// - (nullable NSDictionary<KeyType, ObjectType> *)initWithContentsOfURL:(NSURL *)url; - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -struct NSMutableDictionary_IMPL { - struct NSDictionary_IMPL NSDictionary_IVARS; -}; - - -// - (void)removeObjectForKey:(KeyType)aKey; -// - (void)setObject:(ObjectType)anObject forKey:(KeyType <NSCopying>)aKey; -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (instancetype)initWithCapacity:(NSUInteger)numItems __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSMutableDictionary<KeyType, ObjectType> (NSExtendedMutableDictionary) - -// - (void)addEntriesFromDictionary:(NSDictionary<KeyType, ObjectType> *)otherDictionary; -// - (void)removeAllObjects; -// - (void)removeObjectsForKeys:(NSArray<KeyType> *)keyArray; -// - (void)setDictionary:(NSDictionary<KeyType, ObjectType> *)otherDictionary; -// - (void)setObject:(nullable ObjectType)obj forKeyedSubscript:(KeyType <NSCopying>)key __attribute__((availability(macosx,introduced=10_8))); - -/* @end */ - - -// @interface NSMutableDictionary<KeyType, ObjectType> (NSMutableDictionaryCreation) - -// + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; - -// + (nullable NSMutableDictionary<KeyType, ObjectType> *)dictionaryWithContentsOfFile:(NSString *)path; -// + (nullable NSMutableDictionary<KeyType, ObjectType> *)dictionaryWithContentsOfURL:(NSURL *)url; -// - (nullable NSMutableDictionary<KeyType, ObjectType> *)initWithContentsOfFile:(NSString *)path; -// - (nullable NSMutableDictionary<KeyType, ObjectType> *)initWithContentsOfURL:(NSURL *)url; - -/* @end */ - - -// @interface NSDictionary<KeyType, ObjectType> (NSSharedKeySetDictionary) -// + (id)sharedKeySetForKeys:(NSArray<KeyType <NSCopying>> *)keys __attribute__((availability(macosx,introduced=10_8))); - -/* @end */ - - -// @interface NSMutableDictionary<KeyType, ObjectType> (NSSharedKeySetDictionary) - - - - - - - -// + (NSMutableDictionary<KeyType, ObjectType> *)dictionaryWithSharedKeySet:(id)keyset __attribute__((availability(macosx,introduced=10_8))); - -/* @end */ - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - - - -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - -struct NSSet_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly) NSUInteger count; -// - (nullable ObjectType)member:(ObjectType)object; -// - (NSEnumerator<ObjectType> *)objectEnumerator; -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (instancetype)initWithObjects:(const ObjectType [])objects count:(NSUInteger)cnt __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSSet<ObjectType> (NSExtendedSet) - -// @property (readonly, copy) NSArray<ObjectType> *allObjects; -// - (nullable ObjectType)anyObject; -// - (BOOL)containsObject:(ObjectType)anObject; -// @property (readonly, copy) NSString *description; -// - (NSString *)descriptionWithLocale:(nullable id)locale; -// - (BOOL)intersectsSet:(NSSet<ObjectType> *)otherSet; -// - (BOOL)isEqualToSet:(NSSet<ObjectType> *)otherSet; -// - (BOOL)isSubsetOfSet:(NSSet<ObjectType> *)otherSet; - -// - (void)makeObjectsPerformSelector:(SEL)aSelector __attribute__((availability(swift, unavailable, message="Use enumerateObjectsUsingBlock: or a for loop instead"))); -// - (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(nullable id)argument __attribute__((availability(swift, unavailable, message="Use enumerateObjectsUsingBlock: or a for loop instead"))); - -// - (NSSet<ObjectType> *)setByAddingObject:(ObjectType)anObject __attribute__((availability(macosx,introduced=10_5))); -// - (NSSet<ObjectType> *)setByAddingObjectsFromSet:(NSSet<ObjectType> *)other __attribute__((availability(macosx,introduced=10_5))); -// - (NSSet<ObjectType> *)setByAddingObjectsFromArray:(NSArray<ObjectType> *)other __attribute__((availability(macosx,introduced=10_5))); - -// - (void)enumerateObjectsUsingBlock:(void (^)(ObjectType obj, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); -// - (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(ObjectType obj, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); - -// - (NSSet<ObjectType> *)objectsPassingTest:(BOOL (^)(ObjectType obj, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSSet<ObjectType> *)objectsWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(ObjectType obj, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -// @interface NSSet<ObjectType> (NSSetCreation) - -// + (instancetype)set; -// + (instancetype)setWithObject:(ObjectType)object; -// + (instancetype)setWithObjects:(const ObjectType [])objects count:(NSUInteger)cnt; -// + (instancetype)setWithObjects:(ObjectType)firstObj, ... __attribute__((sentinel(0,1))); -// + (instancetype)setWithSet:(NSSet<ObjectType> *)set; -// + (instancetype)setWithArray:(NSArray<ObjectType> *)array; - -// - (instancetype)initWithObjects:(ObjectType)firstObj, ... __attribute__((sentinel(0,1))); -// - (instancetype)initWithSet:(NSSet<ObjectType> *)set; -// - (instancetype)initWithSet:(NSSet<ObjectType> *)set copyItems:(BOOL)flag; -// - (instancetype)initWithArray:(NSArray<ObjectType> *)array; - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSMutableSet -#define _REWRITER_typedef_NSMutableSet -typedef struct objc_object NSMutableSet; -typedef struct {} _objc_exc_NSMutableSet; -#endif - -struct NSMutableSet_IMPL { - struct NSSet_IMPL NSSet_IVARS; -}; - - -// - (void)addObject:(ObjectType)object; -// - (void)removeObject:(ObjectType)object; -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (instancetype)initWithCapacity:(NSUInteger)numItems __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSMutableSet<ObjectType> (NSExtendedMutableSet) - -// - (void)addObjectsFromArray:(NSArray<ObjectType> *)array; -// - (void)intersectSet:(NSSet<ObjectType> *)otherSet; -// - (void)minusSet:(NSSet<ObjectType> *)otherSet; -// - (void)removeAllObjects; -// - (void)unionSet:(NSSet<ObjectType> *)otherSet; - -// - (void)setSet:(NSSet<ObjectType> *)otherSet; - -/* @end */ - - -// @interface NSMutableSet<ObjectType> (NSMutableSetCreation) - -// + (instancetype)setWithCapacity:(NSUInteger)numItems; - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSCountedSet -#define _REWRITER_typedef_NSCountedSet -typedef struct objc_object NSCountedSet; -typedef struct {} _objc_exc_NSCountedSet; -#endif - -struct NSCountedSet_IMPL { - struct NSMutableSet_IMPL NSMutableSet_IVARS; - id _table; - void *_reserved; -}; - - -// - (instancetype)initWithCapacity:(NSUInteger)numItems __attribute__((objc_designated_initializer)); - -// - (instancetype)initWithArray:(NSArray<ObjectType> *)array; -// - (instancetype)initWithSet:(NSSet<ObjectType> *)set; - -// - (NSUInteger)countForObject:(ObjectType)object; - -// - (NSEnumerator<ObjectType> *)objectEnumerator; -// - (void)addObject:(ObjectType)object; -// - (void)removeObject:(ObjectType)object; - -/* @end */ - - - - - - - - - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSMutableSet -#define _REWRITER_typedef_NSMutableSet -typedef struct objc_object NSMutableSet; -typedef struct {} _objc_exc_NSMutableSet; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -#ifndef _REWRITER_typedef_NSUUID -#define _REWRITER_typedef_NSUUID -typedef struct objc_object NSUUID; -typedef struct {} _objc_exc_NSUUID; -#endif - -#ifndef _REWRITER_typedef_NSXPCConnection -#define _REWRITER_typedef_NSXPCConnection -typedef struct objc_object NSXPCConnection; -typedef struct {} _objc_exc_NSXPCConnection; -#endif - -#ifndef _REWRITER_typedef_NSLock -#define _REWRITER_typedef_NSLock -typedef struct objc_object NSLock; -typedef struct {} _objc_exc_NSLock; -#endif - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_9))) - -#ifndef _REWRITER_typedef_NSProgress -#define _REWRITER_typedef_NSProgress -typedef struct objc_object NSProgress; -typedef struct {} _objc_exc_NSProgress; -#endif - -struct NSProgress_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSProgress *__weak _parent; - int64_t _reserved4; - id _values; - void (*_resumingHandler)(); - void (*_cancellationHandler)(); - void (*_pausingHandler)(); - void (*_prioritizationHandler)(); - uint64_t _flags; - id _userInfoProxy; - NSString *_publisherID; - NSXPCConnection *_connection; - NSInteger _unpublishingBlockageCount; - NSInteger _disconnectingBlockageCount; - NSInteger _remoteObserverCount; - NSMutableDictionary *_acknowledgementHandlersByBundleID; - NSMutableDictionary *_lastNotificationTimesByKey; - NSMutableDictionary *_userInfoLastNotificationTimesByKey; - NSLock *_lock; - NSMutableSet *_children; -}; - - - - -// + (nullable NSProgress *)currentProgress; - - - - - -// + (NSProgress *)progressWithTotalUnitCount:(int64_t)unitCount; - - - -// + (NSProgress *)discreteProgressWithTotalUnitCount:(int64_t)unitCount __attribute__((availability(macosx,introduced=10_11))); - - - -// + (NSProgress *)progressWithTotalUnitCount:(int64_t)unitCount parent:(NSProgress *)parent pendingUnitCount:(int64_t)portionOfParentTotalUnitCount __attribute__((availability(macosx,introduced=10_11))); - - - -// - (instancetype)initWithParent:(nullable NSProgress *)parentProgressOrNil userInfo:(nullable NSDictionary *)userInfoOrNil __attribute__((objc_designated_initializer)); - - - - - -// - (void)becomeCurrentWithPendingUnitCount:(int64_t)unitCount; - - - -// - (void)resignCurrent; - - - -// - (void)addChild:(NSProgress *)child withPendingUnitCount:(int64_t)inUnitCount __attribute__((availability(macosx,introduced=10_11))); - - - - - - - -// @property int64_t totalUnitCount; -// @property int64_t completedUnitCount; -// @property (null_resettable, copy) NSString *localizedDescription; -// @property (null_resettable, copy) NSString *localizedAdditionalDescription; - - - -// @property (getter=isCancellable) BOOL cancellable; -// @property (getter=isPausable) BOOL pausable; - - - -// @property (readonly, getter=isCancelled) BOOL cancelled; -// @property (readonly, getter=isPaused) BOOL paused; - - - -// @property (nullable, copy) void (^cancellationHandler)(void); - - - -// @property (nullable, copy) void (^pausingHandler)(void); - - - -// @property (nullable, copy) void (^resumingHandler)(void) __attribute__((availability(macosx,introduced=10_11))); - - - -// - (void)setUserInfoObject:(nullable id)objectOrNil forKey:(NSString *)key; - - - - - -// @property (readonly, getter=isIndeterminate) BOOL indeterminate; - - - -// @property (readonly) double fractionCompleted; - - - -// - (void)cancel; - - - -// - (void)pause; - - - -// - (void)resume __attribute__((availability(macosx,introduced=10_11))); - - - -// @property (readonly, copy) NSDictionary *userInfo; - - - -// @property (nullable, copy) NSString *kind; -// - (void)publish __attribute__((availability(macosx,introduced=10_9))); - - - -// - (void)unpublish __attribute__((availability(macosx,introduced=10_9))); - - - -typedef void (*NSProgressUnpublishingHandler)(void); -typedef _Nullable NSProgressUnpublishingHandler (*NSProgressPublishingHandler)(NSProgress *progress); - - - -// + (id)addSubscriberForFileURL:(NSURL *)url withPublishingHandler:(NSProgressPublishingHandler)publishingHandler __attribute__((availability(macosx,introduced=10_9))); - - - -// + (void)removeSubscriber:(id)subscriber __attribute__((availability(macosx,introduced=10_9))); - - - - - -// @property (readonly, getter=isOld) BOOL old __attribute__((availability(macosx,introduced=10_9))); - -/* @end */ - - - - -// @protocol NSProgressReporting <NSObject> -// @property (readonly) NSProgress *progress; -/* @end */ - - - - - - -extern "C" NSString *const NSProgressEstimatedTimeRemainingKey __attribute__((availability(macosx,introduced=10_9))); - - - -extern "C" NSString *const NSProgressThroughputKey __attribute__((availability(macosx,introduced=10_9))); - - - - - -extern "C" NSString *const NSProgressKindFile __attribute__((availability(macosx,introduced=10_9))); - - - -extern "C" NSString *const NSProgressFileOperationKindKey __attribute__((availability(macosx,introduced=10_9))); - - - -extern "C" NSString *const NSProgressFileOperationKindDownloading __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString *const NSProgressFileOperationKindDecompressingAfterDownloading __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString *const NSProgressFileOperationKindReceiving __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString *const NSProgressFileOperationKindCopying __attribute__((availability(macosx,introduced=10_9))); - - - -extern "C" NSString *const NSProgressFileURLKey __attribute__((availability(macosx,introduced=10_9))); - - - -extern "C" NSString *const NSProgressFileTotalCountKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString *const NSProgressFileCompletedCountKey __attribute__((availability(macosx,introduced=10_9))); - - - -extern "C" NSString *const NSProgressFileAnimationImageKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString *const NSProgressFileAnimationImageOriginalRectKey __attribute__((availability(macosx,introduced=10_9))); - - - -extern "C" NSString *const NSProgressFileIconKey __attribute__((availability(macosx,introduced=10_9))); - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSUUID -#define _REWRITER_typedef_NSUUID -typedef struct objc_object NSUUID; -typedef struct {} _objc_exc_NSUUID; -#endif - -#ifndef _REWRITER_typedef_NSLock -#define _REWRITER_typedef_NSLock -typedef struct objc_object NSLock; -typedef struct {} _objc_exc_NSLock; -#endif - -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - - - - - - - -#ifndef _REWRITER_typedef_NSBundle -#define _REWRITER_typedef_NSBundle -typedef struct objc_object NSBundle; -typedef struct {} _objc_exc_NSBundle; -#endif - -struct NSBundle_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSUInteger _flags; - id _cfBundle; - NSUInteger _reserved2; - Class _principalClass; - id _initialPath; - id _resolvedPath; - id _reserved3; - id _lock; -}; - - - -// + (NSBundle *)mainBundle; -// + (nullable instancetype)bundleWithPath:(NSString *)path; -// - (nullable instancetype)initWithPath:(NSString *)path __attribute__((objc_designated_initializer)); - -// + (nullable instancetype)bundleWithURL:(NSURL *)url __attribute__((availability(macosx,introduced=10_6))); -// - (nullable instancetype)initWithURL:(NSURL *)url __attribute__((availability(macosx,introduced=10_6))); - -// + (NSBundle *)bundleForClass:(Class)aClass; -// + (nullable NSBundle *)bundleWithIdentifier:(NSString *)identifier; - -// + (NSArray<NSBundle *> *)allBundles; -// + (NSArray<NSBundle *> *)allFrameworks; - - -// - (BOOL)load; -// @property (readonly, getter=isLoaded) BOOL loaded; -// - (BOOL)unload; - -// - (BOOL)preflightAndReturnError:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)loadAndReturnError:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - -// @property (readonly, copy) NSURL *bundleURL __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSURL *resourceURL __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSURL *executableURL __attribute__((availability(macosx,introduced=10_6))); -// - (nullable NSURL *)URLForAuxiliaryExecutable:(NSString *)executableName __attribute__((availability(macosx,introduced=10_6))); - -// @property (nullable, readonly, copy) NSURL *privateFrameworksURL __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSURL *sharedFrameworksURL __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSURL *sharedSupportURL __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSURL *builtInPlugInsURL __attribute__((availability(macosx,introduced=10_6))); - -// @property (nullable, readonly, copy) NSURL *appStoreReceiptURL __attribute__((availability(macosx,introduced=10_7))); - -// @property (readonly, copy) NSString *bundlePath; -// @property (nullable, readonly, copy) NSString *resourcePath; -// @property (nullable, readonly, copy) NSString *executablePath; -// - (nullable NSString *)pathForAuxiliaryExecutable:(NSString *)executableName; - -// @property (nullable, readonly, copy) NSString *privateFrameworksPath; -// @property (nullable, readonly, copy) NSString *sharedFrameworksPath; -// @property (nullable, readonly, copy) NSString *sharedSupportPath; -// @property (nullable, readonly, copy) NSString *builtInPlugInsPath; - - - -// + (nullable NSURL *)URLForResource:(nullable NSString *)name withExtension:(nullable NSString *)ext subdirectory:(nullable NSString *)subpath inBundleWithURL:(NSURL *)bundleURL __attribute__((availability(macosx,introduced=10_6))); -// + (nullable NSArray<NSURL *> *)URLsForResourcesWithExtension:(nullable NSString *)ext subdirectory:(nullable NSString *)subpath inBundleWithURL:(NSURL *)bundleURL __attribute__((availability(macosx,introduced=10_6))); - -// - (nullable NSURL *)URLForResource:(nullable NSString *)name withExtension:(nullable NSString *)ext __attribute__((availability(macosx,introduced=10_6))); -// - (nullable NSURL *)URLForResource:(nullable NSString *)name withExtension:(nullable NSString *)ext subdirectory:(nullable NSString *)subpath __attribute__((availability(macosx,introduced=10_6))); -// - (nullable NSURL *)URLForResource:(nullable NSString *)name withExtension:(nullable NSString *)ext subdirectory:(nullable NSString *)subpath localization:(nullable NSString *)localizationName __attribute__((availability(macosx,introduced=10_6))); - -// - (nullable NSArray<NSURL *> *)URLsForResourcesWithExtension:(nullable NSString *)ext subdirectory:(nullable NSString *)subpath __attribute__((availability(macosx,introduced=10_6))); -// - (nullable NSArray<NSURL *> *)URLsForResourcesWithExtension:(nullable NSString *)ext subdirectory:(nullable NSString *)subpath localization:(nullable NSString *)localizationName __attribute__((availability(macosx,introduced=10_6))); - -// + (nullable NSString *)pathForResource:(nullable NSString *)name ofType:(nullable NSString *)ext inDirectory:(NSString *)bundlePath; -// + (NSArray<NSString *> *)pathsForResourcesOfType:(nullable NSString *)ext inDirectory:(NSString *)bundlePath; - -// - (nullable NSString *)pathForResource:(nullable NSString *)name ofType:(nullable NSString *)ext; -// - (nullable NSString *)pathForResource:(nullable NSString *)name ofType:(nullable NSString *)ext inDirectory:(nullable NSString *)subpath; -// - (nullable NSString *)pathForResource:(nullable NSString *)name ofType:(nullable NSString *)ext inDirectory:(nullable NSString *)subpath forLocalization:(nullable NSString *)localizationName; - -// - (NSArray<NSString *> *)pathsForResourcesOfType:(nullable NSString *)ext inDirectory:(nullable NSString *)subpath; -// - (NSArray<NSString *> *)pathsForResourcesOfType:(nullable NSString *)ext inDirectory:(nullable NSString *)subpath forLocalization:(nullable NSString *)localizationName; - - -// - (NSString *)localizedStringForKey:(NSString *)key value:(nullable NSString *)value table:(nullable NSString *)tableName __attribute__ ((format_arg(1))); - - -// @property (nullable, readonly, copy) NSString *bundleIdentifier; -// @property (nullable, readonly, copy) NSDictionary<NSString *, id> *infoDictionary; -// @property (nullable, readonly, copy) NSDictionary<NSString *, id> *localizedInfoDictionary; -// - (nullable id)objectForInfoDictionaryKey:(NSString *)key; -// - (nullable Class)classNamed:(NSString *)className; -// @property (nullable, readonly) Class principalClass; - - -// @property (readonly, copy) NSArray<NSString *> *preferredLocalizations; - -// @property (readonly, copy) NSArray<NSString *> *localizations; -// @property (nullable, readonly, copy) NSString *developmentLocalization; - -// + (NSArray<NSString *> *)preferredLocalizationsFromArray:(NSArray<NSString *> *)localizationsArray; -// + (NSArray<NSString *> *)preferredLocalizationsFromArray:(NSArray<NSString *> *)localizationsArray forPreferences:(nullable NSArray<NSString *> *)preferencesArray; - - -enum { - NSBundleExecutableArchitectureI386 = 0x00000007, - NSBundleExecutableArchitecturePPC = 0x00000012, - NSBundleExecutableArchitectureX86_64 = 0x01000007, - NSBundleExecutableArchitecturePPC64 = 0x01000012 -}; - -// @property (nullable, readonly, copy) NSArray<NSNumber *> *executableArchitectures __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - -// @interface NSString (NSBundleExtensionMethods) - - - -// - (NSString *)variantFittingPresentationWidth:(NSInteger)width __attribute__((availability(macosx,introduced=10_11))); - -/* @end */ - - -extern "C" NSString * const NSBundleDidLoadNotification; -extern "C" NSString * const NSLoadedClasses; -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=NA))) - -#ifndef _REWRITER_typedef_NSBundleResourceRequest -#define _REWRITER_typedef_NSBundleResourceRequest -typedef struct objc_object NSBundleResourceRequest; -typedef struct {} _objc_exc_NSBundleResourceRequest; -#endif - -struct NSBundleResourceRequest_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (instancetype)init __attribute__((unavailable)); - - - - -// - (instancetype)initWithTags:(NSSet<NSString *> *)tags; -// - (instancetype)initWithTags:(NSSet<NSString *> *)tags bundle:(NSBundle *)bundle __attribute__((objc_designated_initializer)); - - - - - - -// @property double loadingPriority; - - - - -// @property (readonly, copy) NSSet<NSString *> *tags; - - - - -// @property (readonly, strong) NSBundle *bundle; -// - (void)beginAccessingResourcesWithCompletionHandler:(void (^)(NSError * _Nullable error))completionHandler; - - - - - - -// - (void)conditionallyBeginAccessingResourcesWithCompletionHandler:(void (^)(BOOL resourcesAvailable))completionHandler; - - - - -// - (void)endAccessingResources; - - - - -// @property (readonly, strong) NSProgress *progress; - -/* @end */ - - -// @interface NSBundle (NSBundleResourceRequestAdditions) - - - - - - - -// - (void)setPreservationPriority:(double)priority forTags:(NSSet<NSString *> *)tags __attribute__((availability(macosx,introduced=NA))); -// - (double)preservationPriorityForTag:(NSString *)tag __attribute__((availability(macosx,introduced=NA))); - -/* @end */ - -extern "C" NSString * const NSBundleResourceRequestLowDiskSpaceNotification __attribute__((availability(macosx,introduced=NA))); - - - -extern "C" double const NSBundleResourceRequestLoadingPriorityUrgent __attribute__((availability(macosx,introduced=NA))); - - - - - - - -enum { - NS_UnknownByteOrder = CFByteOrderUnknown, - NS_LittleEndian = CFByteOrderLittleEndian, - NS_BigEndian = CFByteOrderBigEndian -}; - -static __inline__ __attribute__((always_inline)) long NSHostByteOrder(void) { - return CFByteOrderGetCurrent(); -} - -static __inline__ __attribute__((always_inline)) unsigned short NSSwapShort(unsigned short inv) { - return CFSwapInt16(inv); -} - -static __inline__ __attribute__((always_inline)) unsigned int NSSwapInt(unsigned int inv) { - return CFSwapInt32(inv); -} - -static __inline__ __attribute__((always_inline)) unsigned long NSSwapLong(unsigned long inv) { - - return CFSwapInt64(inv); - - - -} - -static __inline__ __attribute__((always_inline)) unsigned long long NSSwapLongLong(unsigned long long inv) { - return CFSwapInt64(inv); -} - -static __inline__ __attribute__((always_inline)) unsigned short NSSwapBigShortToHost(unsigned short x) { - return CFSwapInt16BigToHost(x); -} - -static __inline__ __attribute__((always_inline)) unsigned int NSSwapBigIntToHost(unsigned int x) { - return CFSwapInt32BigToHost(x); -} - -static __inline__ __attribute__((always_inline)) unsigned long NSSwapBigLongToHost(unsigned long x) { - - return CFSwapInt64BigToHost(x); - - - -} - -static __inline__ __attribute__((always_inline)) unsigned long long NSSwapBigLongLongToHost(unsigned long long x) { - return CFSwapInt64BigToHost(x); -} - -static __inline__ __attribute__((always_inline)) unsigned short NSSwapHostShortToBig(unsigned short x) { - return CFSwapInt16HostToBig(x); -} - -static __inline__ __attribute__((always_inline)) unsigned int NSSwapHostIntToBig(unsigned int x) { - return CFSwapInt32HostToBig(x); -} - -static __inline__ __attribute__((always_inline)) unsigned long NSSwapHostLongToBig(unsigned long x) { - - return CFSwapInt64HostToBig(x); - - - -} - -static __inline__ __attribute__((always_inline)) unsigned long long NSSwapHostLongLongToBig(unsigned long long x) { - return CFSwapInt64HostToBig(x); -} - -static __inline__ __attribute__((always_inline)) unsigned short NSSwapLittleShortToHost(unsigned short x) { - return CFSwapInt16LittleToHost(x); -} - -static __inline__ __attribute__((always_inline)) unsigned int NSSwapLittleIntToHost(unsigned int x) { - return CFSwapInt32LittleToHost(x); -} - -static __inline__ __attribute__((always_inline)) unsigned long NSSwapLittleLongToHost(unsigned long x) { - - return CFSwapInt64LittleToHost(x); - - - -} - -static __inline__ __attribute__((always_inline)) unsigned long long NSSwapLittleLongLongToHost(unsigned long long x) { - return CFSwapInt64LittleToHost(x); -} - -static __inline__ __attribute__((always_inline)) unsigned short NSSwapHostShortToLittle(unsigned short x) { - return CFSwapInt16HostToLittle(x); -} - -static __inline__ __attribute__((always_inline)) unsigned int NSSwapHostIntToLittle(unsigned int x) { - return CFSwapInt32HostToLittle(x); -} - -static __inline__ __attribute__((always_inline)) unsigned long NSSwapHostLongToLittle(unsigned long x) { - - return CFSwapInt64HostToLittle(x); - - - -} - -static __inline__ __attribute__((always_inline)) unsigned long long NSSwapHostLongLongToLittle(unsigned long long x) { - return CFSwapInt64HostToLittle(x); -} - - -typedef struct {unsigned int v;} NSSwappedFloat; -typedef struct {unsigned long long v;} NSSwappedDouble; - -static __inline__ __attribute__((always_inline)) NSSwappedFloat NSConvertHostFloatToSwapped(float x) { - union fconv { - float number; - NSSwappedFloat sf; - }; - return ((union fconv *)&x)->sf; -} - -static __inline__ __attribute__((always_inline)) float NSConvertSwappedFloatToHost(NSSwappedFloat x) { - union fconv { - float number; - NSSwappedFloat sf; - }; - return ((union fconv *)&x)->number; -} - -static __inline__ __attribute__((always_inline)) NSSwappedDouble NSConvertHostDoubleToSwapped(double x) { - union dconv { - double number; - NSSwappedDouble sd; - }; - return ((union dconv *)&x)->sd; -} - -static __inline__ __attribute__((always_inline)) double NSConvertSwappedDoubleToHost(NSSwappedDouble x) { - union dconv { - double number; - NSSwappedDouble sd; - }; - return ((union dconv *)&x)->number; -} - -static __inline__ __attribute__((always_inline)) NSSwappedFloat NSSwapFloat(NSSwappedFloat x) { - x.v = NSSwapInt(x.v); - return x; -} - -static __inline__ __attribute__((always_inline)) NSSwappedDouble NSSwapDouble(NSSwappedDouble x) { - x.v = NSSwapLongLong(x.v); - return x; -} -static __inline__ __attribute__((always_inline)) double NSSwapBigDoubleToHost(NSSwappedDouble x) { - return NSConvertSwappedDoubleToHost(NSSwapDouble(x)); -} - -static __inline__ __attribute__((always_inline)) float NSSwapBigFloatToHost(NSSwappedFloat x) { - return NSConvertSwappedFloatToHost(NSSwapFloat(x)); -} - -static __inline__ __attribute__((always_inline)) NSSwappedDouble NSSwapHostDoubleToBig(double x) { - return NSSwapDouble(NSConvertHostDoubleToSwapped(x)); -} - -static __inline__ __attribute__((always_inline)) NSSwappedFloat NSSwapHostFloatToBig(float x) { - return NSSwapFloat(NSConvertHostFloatToSwapped(x)); -} - -static __inline__ __attribute__((always_inline)) double NSSwapLittleDoubleToHost(NSSwappedDouble x) { - return NSConvertSwappedDoubleToHost(x); -} - -static __inline__ __attribute__((always_inline)) float NSSwapLittleFloatToHost(NSSwappedFloat x) { - return NSConvertSwappedFloatToHost(x); -} - -static __inline__ __attribute__((always_inline)) NSSwappedDouble NSSwapHostDoubleToLittle(double x) { - return NSConvertHostDoubleToSwapped(x); -} - -static __inline__ __attribute__((always_inline)) NSSwappedFloat NSSwapHostFloatToLittle(float x) { - return NSConvertHostFloatToSwapped(x); -} - - - - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -extern "C" NSString * const NSSystemClockDidChangeNotification __attribute__((availability(macosx,introduced=10_6))); - -typedef double NSTimeInterval; - - - - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -struct NSDate_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly) NSTimeInterval timeIntervalSinceReferenceDate; - -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (instancetype)initWithTimeIntervalSinceReferenceDate:(NSTimeInterval)ti __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSDate (NSExtendedDate) - -// - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate; -// @property (readonly) NSTimeInterval timeIntervalSinceNow; -// @property (readonly) NSTimeInterval timeIntervalSince1970; - -// - (id)addTimeInterval:(NSTimeInterval)seconds __attribute__((availability(macosx,introduced=10_0,deprecated=10_6,message="" ))); -// - (instancetype)dateByAddingTimeInterval:(NSTimeInterval)ti __attribute__((availability(macosx,introduced=10_6))); - -// - (NSDate *)earlierDate:(NSDate *)anotherDate; -// - (NSDate *)laterDate:(NSDate *)anotherDate; -// - (NSComparisonResult)compare:(NSDate *)other; -// - (BOOL)isEqualToDate:(NSDate *)otherDate; - -// @property (readonly, copy) NSString *description; -// - (NSString *)descriptionWithLocale:(nullable id)locale; - -// + (NSTimeInterval)timeIntervalSinceReferenceDate; - -/* @end */ - - -// @interface NSDate (NSDateCreation) - -// + (instancetype)date; -// + (instancetype)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs; -// + (instancetype)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)ti; -// + (instancetype)dateWithTimeIntervalSince1970:(NSTimeInterval)secs; -// + (instancetype)dateWithTimeInterval:(NSTimeInterval)secsToBeAdded sinceDate:(NSDate *)date; - -// + (NSDate *)distantFuture; -// + (NSDate *)distantPast; - -// - (instancetype)initWithTimeIntervalSinceNow:(NSTimeInterval)secs; -// - (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)secs; -// - (instancetype)initWithTimeInterval:(NSTimeInterval)secsToBeAdded sinceDate:(NSDate *)date; - -/* @end */ - - - -// @class NSDateComponents; -#ifndef _REWRITER_typedef_NSDateComponents -#define _REWRITER_typedef_NSDateComponents -typedef struct objc_object NSDateComponents; -typedef struct {} _objc_exc_NSDateComponents; -#endif - -#ifndef _REWRITER_typedef_NSLocale -#define _REWRITER_typedef_NSLocale -typedef struct objc_object NSLocale; -typedef struct {} _objc_exc_NSLocale; -#endif - -#ifndef _REWRITER_typedef_NSTimeZone -#define _REWRITER_typedef_NSTimeZone -typedef struct objc_object NSTimeZone; -typedef struct {} _objc_exc_NSTimeZone; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -extern "C" NSString * const NSCalendarIdentifierGregorian __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierBuddhist __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierChinese __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierCoptic __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierEthiopicAmeteMihret __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierEthiopicAmeteAlem __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierHebrew __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierISO8601 __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierIndian __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierIslamic __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierIslamicCivil __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierJapanese __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierPersian __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSCalendarIdentifierRepublicOfChina __attribute__((availability(macosx,introduced=10_6))); - -extern "C" NSString * const NSCalendarIdentifierIslamicTabular __attribute__((availability(macosx,introduced=10_10))); - -extern "C" NSString * const NSCalendarIdentifierIslamicUmmAlQura __attribute__((availability(macosx,introduced=10_10))); - - -typedef NSUInteger NSCalendarUnit; enum { - NSCalendarUnitEra = kCFCalendarUnitEra, - NSCalendarUnitYear = kCFCalendarUnitYear, - NSCalendarUnitMonth = kCFCalendarUnitMonth, - NSCalendarUnitDay = kCFCalendarUnitDay, - NSCalendarUnitHour = kCFCalendarUnitHour, - NSCalendarUnitMinute = kCFCalendarUnitMinute, - NSCalendarUnitSecond = kCFCalendarUnitSecond, - NSCalendarUnitWeekday = kCFCalendarUnitWeekday, - NSCalendarUnitWeekdayOrdinal = kCFCalendarUnitWeekdayOrdinal, - NSCalendarUnitQuarter __attribute__((availability(macosx,introduced=10_6))) = kCFCalendarUnitQuarter, - NSCalendarUnitWeekOfMonth __attribute__((availability(macosx,introduced=10_7))) = kCFCalendarUnitWeekOfMonth, - NSCalendarUnitWeekOfYear __attribute__((availability(macosx,introduced=10_7))) = kCFCalendarUnitWeekOfYear, - NSCalendarUnitYearForWeekOfYear __attribute__((availability(macosx,introduced=10_7))) = kCFCalendarUnitYearForWeekOfYear, - NSCalendarUnitNanosecond __attribute__((availability(macosx,introduced=10_7))) = (1 << 15), - NSCalendarUnitCalendar __attribute__((availability(macosx,introduced=10_7))) = (1 << 20), - NSCalendarUnitTimeZone __attribute__((availability(macosx,introduced=10_7))) = (1 << 21), - - NSEraCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitEra instead"))) = NSCalendarUnitEra, - NSYearCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitYear instead"))) = NSCalendarUnitYear, - NSMonthCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitMonth instead"))) = NSCalendarUnitMonth, - NSDayCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitDay instead"))) = NSCalendarUnitDay, - NSHourCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitHour instead"))) = NSCalendarUnitHour, - NSMinuteCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitMinute instead"))) = NSCalendarUnitMinute, - NSSecondCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitSecond instead"))) = NSCalendarUnitSecond, - NSWeekCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitWeekOfMonth or NSCalendarUnitWeekOfYear, depending on which you mean"))) = kCFCalendarUnitWeek, - NSWeekdayCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitWeekday instead"))) = NSCalendarUnitWeekday, - NSWeekdayOrdinalCalendarUnit __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarUnitWeekdayOrdinal instead"))) = NSCalendarUnitWeekdayOrdinal, - NSQuarterCalendarUnit __attribute__((availability(macosx,introduced=10_6,deprecated=10_10,message="" "Use NSCalendarUnitQuarter instead"))) = NSCalendarUnitQuarter, - NSWeekOfMonthCalendarUnit __attribute__((availability(macosx,introduced=10_7,deprecated=10_10,message="" "Use NSCalendarUnitWeekOfMonth instead"))) = NSCalendarUnitWeekOfMonth, - NSWeekOfYearCalendarUnit __attribute__((availability(macosx,introduced=10_7,deprecated=10_10,message="" "Use NSCalendarUnitWeekOfYear instead"))) = NSCalendarUnitWeekOfYear, - NSYearForWeekOfYearCalendarUnit __attribute__((availability(macosx,introduced=10_7,deprecated=10_10,message="" "Use NSCalendarUnitYearForWeekOfYear instead"))) = NSCalendarUnitYearForWeekOfYear, - NSCalendarCalendarUnit __attribute__((availability(macosx,introduced=10_7,deprecated=10_10,message="" "Use NSCalendarUnitCalendar instead"))) = NSCalendarUnitCalendar, - NSTimeZoneCalendarUnit __attribute__((availability(macosx,introduced=10_7,deprecated=10_10,message="" "Use NSCalendarUnitTimeZone instead"))) = NSCalendarUnitTimeZone, -}; - -typedef NSUInteger NSCalendarOptions; enum { - NSCalendarWrapComponents = (1UL << 0), - - NSCalendarMatchStrictly __attribute__((availability(macosx,introduced=10_9))) = (1ULL << 1), - NSCalendarSearchBackwards __attribute__((availability(macosx,introduced=10_9))) = (1ULL << 2), - - NSCalendarMatchPreviousTimePreservingSmallerUnits __attribute__((availability(macosx,introduced=10_9))) = (1ULL << 8), - NSCalendarMatchNextTimePreservingSmallerUnits __attribute__((availability(macosx,introduced=10_9))) = (1ULL << 9), - NSCalendarMatchNextTime __attribute__((availability(macosx,introduced=10_9))) = (1ULL << 10), - - NSCalendarMatchFirst __attribute__((availability(macosx,introduced=10_9))) = (1ULL << 12), - NSCalendarMatchLast __attribute__((availability(macosx,introduced=10_9))) = (1ULL << 13) -}; - -enum { - NSWrapCalendarComponents __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarWrapComponents instead"))) = NSCalendarWrapComponents, -}; - - - -#ifndef _REWRITER_typedef_NSCalendar -#define _REWRITER_typedef_NSCalendar -typedef struct objc_object NSCalendar; -typedef struct {} _objc_exc_NSCalendar; -#endif - -struct NSCalendar_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - -// + (NSCalendar *)currentCalendar; -// + (NSCalendar *)autoupdatingCurrentCalendar __attribute__((availability(macosx,introduced=10_5))); - - - - - -// + (nullable NSCalendar *)calendarWithIdentifier:(NSString *)calendarIdentifierConstant __attribute__((availability(macosx,introduced=10_9))); - -// - (instancetype)init __attribute__((unavailable)); - -// - (nullable id)initWithCalendarIdentifier:(NSString *)ident __attribute__((objc_designated_initializer)); - -// @property (readonly, copy) NSString *calendarIdentifier; -// @property (nullable, copy) NSLocale *locale; -// @property (copy) NSTimeZone *timeZone; -// @property NSUInteger firstWeekday; -// @property NSUInteger minimumDaysInFirstWeek; - - - -// @property (readonly, copy) NSArray<NSString *> *eraSymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *longEraSymbols __attribute__((availability(macosx,introduced=10_7))); - -// @property (readonly, copy) NSArray<NSString *> *monthSymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *shortMonthSymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *veryShortMonthSymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *standaloneMonthSymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *shortStandaloneMonthSymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *veryShortStandaloneMonthSymbols __attribute__((availability(macosx,introduced=10_7))); - -// @property (readonly, copy) NSArray<NSString *> *weekdaySymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *shortWeekdaySymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *veryShortWeekdaySymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *standaloneWeekdaySymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *shortStandaloneWeekdaySymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *veryShortStandaloneWeekdaySymbols __attribute__((availability(macosx,introduced=10_7))); - -// @property (readonly, copy) NSArray<NSString *> *quarterSymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *shortQuarterSymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *standaloneQuarterSymbols __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSArray<NSString *> *shortStandaloneQuarterSymbols __attribute__((availability(macosx,introduced=10_7))); - -// @property (readonly, copy) NSString *AMSymbol __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly, copy) NSString *PMSymbol __attribute__((availability(macosx,introduced=10_7))); - - - - -// - (NSRange)minimumRangeOfUnit:(NSCalendarUnit)unit; -// - (NSRange)maximumRangeOfUnit:(NSCalendarUnit)unit; - -// - (NSRange)rangeOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date; -// - (NSUInteger)ordinalityOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date; - -// - (BOOL)rangeOfUnit:(NSCalendarUnit)unit startDate:(NSDate * _Nullable * _Nullable)datep interval:(nullable NSTimeInterval *)tip forDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_5))); - -// - (nullable NSDate *)dateFromComponents:(NSDateComponents *)comps; -// - (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)date; - -// - (nullable NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSCalendarOptions)opts; - -// - (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSCalendarOptions)opts; - - - - - - -// - (void)getEra:(out nullable NSInteger *)eraValuePointer year:(out nullable NSInteger *)yearValuePointer month:(out nullable NSInteger *)monthValuePointer day:(out nullable NSInteger *)dayValuePointer fromDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - - -// - (void)getEra:(out nullable NSInteger *)eraValuePointer yearForWeekOfYear:(out nullable NSInteger *)yearValuePointer weekOfYear:(out nullable NSInteger *)weekValuePointer weekday:(out nullable NSInteger *)weekdayValuePointer fromDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - - -// - (void)getHour:(out nullable NSInteger *)hourValuePointer minute:(out nullable NSInteger *)minuteValuePointer second:(out nullable NSInteger *)secondValuePointer nanosecond:(out nullable NSInteger *)nanosecondValuePointer fromDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - -// - (NSInteger)component:(NSCalendarUnit)unit fromDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - - -// - (nullable NSDate *)dateWithEra:(NSInteger)eraValue year:(NSInteger)yearValue month:(NSInteger)monthValue day:(NSInteger)dayValue hour:(NSInteger)hourValue minute:(NSInteger)minuteValue second:(NSInteger)secondValue nanosecond:(NSInteger)nanosecondValue __attribute__((availability(macosx,introduced=10_9))); - - - - - - -// - (nullable NSDate *)dateWithEra:(NSInteger)eraValue yearForWeekOfYear:(NSInteger)yearValue weekOfYear:(NSInteger)weekValue weekday:(NSInteger)weekdayValue hour:(NSInteger)hourValue minute:(NSInteger)minuteValue second:(NSInteger)secondValue nanosecond:(NSInteger)nanosecondValue __attribute__((availability(macosx,introduced=10_9))); - - - - - - - -// - (NSDate *)startOfDayForDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - - - -// - (NSDateComponents *)componentsInTimeZone:(NSTimeZone *)timezone fromDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - -// - (NSComparisonResult)compareDate:(NSDate *)date1 toDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit __attribute__((availability(macosx,introduced=10_9))); - - - - - -// - (BOOL)isDate:(NSDate *)date1 equalToDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit __attribute__((availability(macosx,introduced=10_9))); - - - - - -// - (BOOL)isDate:(NSDate *)date1 inSameDayAsDate:(NSDate *)date2 __attribute__((availability(macosx,introduced=10_9))); - - - - - -// - (BOOL)isDateInToday:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - -// - (BOOL)isDateInYesterday:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - -// - (BOOL)isDateInTomorrow:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - -// - (BOOL)isDateInWeekend:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); - - - - - - - -// - (BOOL)rangeOfWeekendStartDate:(out NSDate * _Nullable * _Nullable)datep interval:(out nullable NSTimeInterval *)tip containingDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); -// - (BOOL)nextWeekendStartDate:(out NSDate * _Nullable * _Nullable)datep interval:(out nullable NSTimeInterval *)tip options:(NSCalendarOptions)options afterDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_9))); -// - (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDateComponents:(NSDateComponents *)startingDateComp toDateComponents:(NSDateComponents *)resultDateComp options:(NSCalendarOptions)options __attribute__((availability(macosx,introduced=10_9))); - - - - - - -// - (nullable NSDate *)dateByAddingUnit:(NSCalendarUnit)unit value:(NSInteger)value toDate:(NSDate *)date options:(NSCalendarOptions)options __attribute__((availability(macosx,introduced=10_9))); -// - (void)enumerateDatesStartingAfterDate:(NSDate *)start matchingComponents:(NSDateComponents *)comps options:(NSCalendarOptions)opts usingBlock:(void (^)(NSDate * _Nullable date, BOOL exactMatch, BOOL *stop))block __attribute__((availability(macosx,introduced=10_9))); - - - - - - -// - (nullable NSDate *)nextDateAfterDate:(NSDate *)date matchingComponents:(NSDateComponents *)comps options:(NSCalendarOptions)options __attribute__((availability(macosx,introduced=10_9))); - - - - - - - -// - (nullable NSDate *)nextDateAfterDate:(NSDate *)date matchingUnit:(NSCalendarUnit)unit value:(NSInteger)value options:(NSCalendarOptions)options __attribute__((availability(macosx,introduced=10_9))); - - - - - - - -// - (nullable NSDate *)nextDateAfterDate:(NSDate *)date matchingHour:(NSInteger)hourValue minute:(NSInteger)minuteValue second:(NSInteger)secondValue options:(NSCalendarOptions)options __attribute__((availability(macosx,introduced=10_9))); -// - (nullable NSDate *)dateBySettingUnit:(NSCalendarUnit)unit value:(NSInteger)v ofDate:(NSDate *)date options:(NSCalendarOptions)opts __attribute__((availability(macosx,introduced=10_9))); - - - - - - - -// - (nullable NSDate *)dateBySettingHour:(NSInteger)h minute:(NSInteger)m second:(NSInteger)s ofDate:(NSDate *)date options:(NSCalendarOptions)opts __attribute__((availability(macosx,introduced=10_9))); - - - - - - -// - (BOOL)date:(NSDate *)date matchesComponents:(NSDateComponents *)components __attribute__((availability(macosx,introduced=10_9))); - -/* @end */ - -extern "C" NSString * const NSCalendarDayChangedNotification __attribute__((availability(macosx,introduced=10_9))); -enum { - NSDateComponentUndefined = 9223372036854775807L, - - NSUndefinedDateComponent __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSDateComponentUndefined instead"))) = NSDateComponentUndefined -}; - - - -#ifndef _REWRITER_typedef_NSDateComponents -#define _REWRITER_typedef_NSDateComponents -typedef struct objc_object NSDateComponents; -typedef struct {} _objc_exc_NSDateComponents; -#endif - -struct NSDateComponents_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (nullable, copy) NSCalendar *calendar __attribute__((availability(macosx,introduced=10_7))); -// @property (nullable, copy) NSTimeZone *timeZone __attribute__((availability(macosx,introduced=10_7))); -// @property NSInteger era; -// @property NSInteger year; -// @property NSInteger month; -// @property NSInteger day; -// @property NSInteger hour; -// @property NSInteger minute; -// @property NSInteger second; -// @property NSInteger nanosecond __attribute__((availability(macosx,introduced=10_7))); -// @property NSInteger weekday; -// @property NSInteger weekdayOrdinal; -// @property NSInteger quarter __attribute__((availability(macosx,introduced=10_6))); -// @property NSInteger weekOfMonth __attribute__((availability(macosx,introduced=10_7))); -// @property NSInteger weekOfYear __attribute__((availability(macosx,introduced=10_7))); -// @property NSInteger yearForWeekOfYear __attribute__((availability(macosx,introduced=10_7))); -// @property (getter=isLeapMonth) BOOL leapMonth __attribute__((availability(macosx,introduced=10_8))); -// @property (nullable, readonly, copy) NSDate *date __attribute__((availability(macosx,introduced=10_7))); - -// - (NSInteger)week __attribute__((availability(macosx,introduced=10_4,deprecated=10_9,message="" "Use weekOfMonth or weekOfYear, depending on which you mean"))); -// - (void)setWeek:(NSInteger)v __attribute__((availability(macosx,introduced=10_4,deprecated=10_9,message="" "Use setWeekOfMonth: or setWeekOfYear:, depending on which you mean"))); - - - - - -// - (void)setValue:(NSInteger)value forComponent:(NSCalendarUnit)unit __attribute__((availability(macosx,introduced=10_9))); - - - - - - -// - (NSInteger)valueForComponent:(NSCalendarUnit)unit __attribute__((availability(macosx,introduced=10_9))); -// @property (getter=isValidDate, readonly) BOOL validDate __attribute__((availability(macosx,introduced=10_9))); -// - (BOOL)isValidDateInCalendar:(NSCalendar *)calendar __attribute__((availability(macosx,introduced=10_9))); - - -/* @end */ - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - - - - -enum { - NSOpenStepUnicodeReservedBase = 0xF400 -}; - - -#ifndef _REWRITER_typedef_NSCharacterSet -#define _REWRITER_typedef_NSCharacterSet -typedef struct objc_object NSCharacterSet; -typedef struct {} _objc_exc_NSCharacterSet; -#endif - -struct NSCharacterSet_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// + (NSCharacterSet *)controlCharacterSet; -// + (NSCharacterSet *)whitespaceCharacterSet; -// + (NSCharacterSet *)whitespaceAndNewlineCharacterSet; -// + (NSCharacterSet *)decimalDigitCharacterSet; -// + (NSCharacterSet *)letterCharacterSet; -// + (NSCharacterSet *)lowercaseLetterCharacterSet; -// + (NSCharacterSet *)uppercaseLetterCharacterSet; -// + (NSCharacterSet *)nonBaseCharacterSet; -// + (NSCharacterSet *)alphanumericCharacterSet; -// + (NSCharacterSet *)decomposableCharacterSet; -// + (NSCharacterSet *)illegalCharacterSet; -// + (NSCharacterSet *)punctuationCharacterSet; -// + (NSCharacterSet *)capitalizedLetterCharacterSet; -// + (NSCharacterSet *)symbolCharacterSet; -// + (NSCharacterSet *)newlineCharacterSet __attribute__((availability(macosx,introduced=10_5))); - -// + (NSCharacterSet *)characterSetWithRange:(NSRange)aRange; -// + (NSCharacterSet *)characterSetWithCharactersInString:(NSString *)aString; -// + (NSCharacterSet *)characterSetWithBitmapRepresentation:(NSData *)data; -// + (nullable NSCharacterSet *)characterSetWithContentsOfFile:(NSString *)fName; - -// - (instancetype) initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -// - (BOOL)characterIsMember:(unichar)aCharacter; -// @property (readonly, copy) NSData *bitmapRepresentation; -// @property (readonly, copy) NSCharacterSet *invertedSet; - - -// - (BOOL)longCharacterIsMember:(UTF32Char)theLongChar; - -// - (BOOL)isSupersetOfSet:(NSCharacterSet *)theOtherSet; -// - (BOOL)hasMemberInPlane:(uint8_t)thePlane; -/* @end */ - - - -#ifndef _REWRITER_typedef_NSMutableCharacterSet -#define _REWRITER_typedef_NSMutableCharacterSet -typedef struct objc_object NSMutableCharacterSet; -typedef struct {} _objc_exc_NSMutableCharacterSet; -#endif - -struct NSMutableCharacterSet_IMPL { - struct NSCharacterSet_IMPL NSCharacterSet_IVARS; -}; - - -// - (void)addCharactersInRange:(NSRange)aRange; -// - (void)removeCharactersInRange:(NSRange)aRange; -// - (void)addCharactersInString:(NSString *)aString; -// - (void)removeCharactersInString:(NSString *)aString; -// - (void)formUnionWithCharacterSet:(NSCharacterSet *)otherSet; -// - (void)formIntersectionWithCharacterSet:(NSCharacterSet *)otherSet; -// - (void)invert; - -// + (NSMutableCharacterSet *)controlCharacterSet; -// + (NSMutableCharacterSet *)whitespaceCharacterSet; -// + (NSMutableCharacterSet *)whitespaceAndNewlineCharacterSet; -// + (NSMutableCharacterSet *)decimalDigitCharacterSet; -// + (NSMutableCharacterSet *)letterCharacterSet; -// + (NSMutableCharacterSet *)lowercaseLetterCharacterSet; -// + (NSMutableCharacterSet *)uppercaseLetterCharacterSet; -// + (NSMutableCharacterSet *)nonBaseCharacterSet; -// + (NSMutableCharacterSet *)alphanumericCharacterSet; -// + (NSMutableCharacterSet *)decomposableCharacterSet; -// + (NSMutableCharacterSet *)illegalCharacterSet; -// + (NSMutableCharacterSet *)punctuationCharacterSet; -// + (NSMutableCharacterSet *)capitalizedLetterCharacterSet; -// + (NSMutableCharacterSet *)symbolCharacterSet; -// + (NSMutableCharacterSet *)newlineCharacterSet __attribute__((availability(macosx,introduced=10_5))); - -// + (NSMutableCharacterSet *)characterSetWithRange:(NSRange)aRange; -// + (NSMutableCharacterSet *)characterSetWithCharactersInString:(NSString *)aString; -// + (NSMutableCharacterSet *)characterSetWithBitmapRepresentation:(NSData *)data; -// + (nullable NSMutableCharacterSet *)characterSetWithContentsOfFile:(NSString *)fName; - -/* @end */ - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - - - - - -#ifndef _REWRITER_typedef_NSCoder -#define _REWRITER_typedef_NSCoder -typedef struct objc_object NSCoder; -typedef struct {} _objc_exc_NSCoder; -#endif - -struct NSCoder_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (void)encodeValueOfObjCType:(const char *)type at:(const void *)addr; -// - (void)encodeDataObject:(NSData *)data; -// - (void)decodeValueOfObjCType:(const char *)type at:(void *)data; -// - (nullable NSData *)decodeDataObject; -// - (NSInteger)versionForClassName:(NSString *)className; - -/* @end */ - - -// @interface NSCoder (NSExtendedCoder) - -// - (void)encodeObject:(nullable id)object; -// - (void)encodeRootObject:(id)rootObject; -// - (void)encodeBycopyObject:(nullable id)anObject; -// - (void)encodeByrefObject:(nullable id)anObject; -// - (void)encodeConditionalObject:(nullable id)object; -// - (void)encodeValuesOfObjCTypes:(const char *)types, ...; -// - (void)encodeArrayOfObjCType:(const char *)type count:(NSUInteger)count at:(const void *)array; -// - (void)encodeBytes:(nullable const void *)byteaddr length:(NSUInteger)length; - -// - (nullable id)decodeObject; -// - (nullable id)decodeTopLevelObjectAndReturnError:(NSError **)error __attribute__((availability(macosx,introduced=10_11))) __attribute__((availability(swift, unavailable, message="Use 'decodeTopLevelObject() throws' instead"))); -// - (void)decodeValuesOfObjCTypes:(const char *)types, ...; -// - (void)decodeArrayOfObjCType:(const char *)itemType count:(NSUInteger)count at:(void *)array; -// - (nullable void *)decodeBytesWithReturnedLength:(NSUInteger *)lengthp __attribute__((objc_returns_inner_pointer)); - - -// - (void)encodePropertyList:(id)aPropertyList; -// - (nullable id)decodePropertyList; - - -// - (void)setObjectZone:(nullable NSZone *)zone ; -// - (nullable NSZone *)objectZone ; - -// @property (readonly) unsigned int systemVersion; - -// @property (readonly) BOOL allowsKeyedCoding; - -// - (void)encodeObject:(nullable id)objv forKey:(NSString *)key; -// - (void)encodeConditionalObject:(nullable id)objv forKey:(NSString *)key; -// - (void)encodeBool:(BOOL)boolv forKey:(NSString *)key; -// - (void)encodeInt:(int)intv forKey:(NSString *)key; -// - (void)encodeInt32:(int32_t)intv forKey:(NSString *)key; -// - (void)encodeInt64:(int64_t)intv forKey:(NSString *)key; -// - (void)encodeFloat:(float)realv forKey:(NSString *)key; -// - (void)encodeDouble:(double)realv forKey:(NSString *)key; -// - (void)encodeBytes:(nullable const uint8_t *)bytesp length:(NSUInteger)lenv forKey:(NSString *)key; - -// - (BOOL)containsValueForKey:(NSString *)key; -// - (nullable id)decodeObjectForKey:(NSString *)key; -// - (nullable id)decodeTopLevelObjectForKey:(NSString *)key error:(NSError **)error __attribute__((availability(macosx,introduced=10_11))) __attribute__((availability(swift, unavailable, message="Use 'decodeObjectForKey(_:) throws' instead"))); -// - (BOOL)decodeBoolForKey:(NSString *)key; -// - (int)decodeIntForKey:(NSString *)key; -// - (int32_t)decodeInt32ForKey:(NSString *)key; -// - (int64_t)decodeInt64ForKey:(NSString *)key; -// - (float)decodeFloatForKey:(NSString *)key; -// - (double)decodeDoubleForKey:(NSString *)key; -// - (nullable const uint8_t *)decodeBytesForKey:(NSString *)key returnedLength:(nullable NSUInteger *)lengthp __attribute__((objc_returns_inner_pointer)); - -// - (void)encodeInteger:(NSInteger)intv forKey:(NSString *)key __attribute__((availability(macosx,introduced=10_5))); -// - (NSInteger)decodeIntegerForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_5))); - - -// @property (readonly) BOOL requiresSecureCoding __attribute__((availability(macosx,introduced=10_8))); - - -// - (nullable id)decodeObjectOfClass:(Class)aClass forKey:(NSString *)key __attribute__((availability(macosx,introduced=10_8))); -// - (nullable id)decodeTopLevelObjectOfClass:(Class)aClass forKey:(NSString *)key error:(NSError **)error __attribute__((availability(macosx,introduced=10_11))) __attribute__((availability(swift, unavailable, message="Use 'decodeTopLevelObjectOfClass(_:,forKey:) throws instead"))); - - -// - (nullable id)decodeObjectOfClasses:(nullable NSSet<Class> *)classes forKey:(NSString *)key __attribute__((availability(macosx,introduced=10_8))) __attribute__((swift_private)); -// - (nullable id)decodeTopLevelObjectOfClasses:(nullable NSSet<Class> *)classes forKey:(NSString *)key error:(NSError **)error __attribute__((availability(macosx,introduced=10_11))) __attribute__((availability(swift, unavailable, message="Use 'decodeObjectOfClasses(_:,forKey:) throws' instead"))); - - -// - (nullable id)decodePropertyListForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_8))); - - -// @property (nullable, readonly, copy) NSSet<Class> *allowedClasses __attribute__((availability(macosx,introduced=10_8))); - - -// - (void)failWithError:(NSError *)error __attribute__((availability(macosx,introduced=10_11))); - -/* @end */ - - - -extern "C" NSObject * _Nullable NXReadNSObjectFromCoder(NSCoder *decoder) __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - - - -// @interface NSCoder (NSTypedstreamCompatibility) - -// - (void)encodeNXObject:(id)object __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - - - - - - - -// - (nullable id)decodeNXObject __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -/* @end */ - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - - - - - - -typedef NSUInteger NSDataReadingOptions; enum { - NSDataReadingMappedIfSafe = 1UL << 0, - NSDataReadingUncached = 1UL << 1, - NSDataReadingMappedAlways __attribute__((availability(macosx,introduced=10_7))) = 1UL << 3, - - - NSDataReadingMapped = NSDataReadingMappedIfSafe, - NSMappedRead = NSDataReadingMapped, - NSUncachedRead = NSDataReadingUncached -}; - -typedef NSUInteger NSDataWritingOptions; enum { - NSDataWritingAtomic = 1UL << 0, - NSDataWritingWithoutOverwriting __attribute__((availability(macosx,introduced=10_8))) = 1UL << 1, - - NSDataWritingFileProtectionNone __attribute__((availability(macosx,unavailable))) = 0x10000000, - NSDataWritingFileProtectionComplete __attribute__((availability(macosx,unavailable))) = 0x20000000, - NSDataWritingFileProtectionCompleteUnlessOpen __attribute__((availability(macosx,unavailable))) = 0x30000000, - NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication __attribute__((availability(macosx,unavailable))) = 0x40000000, - NSDataWritingFileProtectionMask __attribute__((availability(macosx,unavailable))) = 0xf0000000, - - - NSAtomicWrite = NSDataWritingAtomic -}; - - - - -typedef NSUInteger NSDataSearchOptions; enum { - NSDataSearchBackwards = 1UL << 0, - NSDataSearchAnchored = 1UL << 1 -} __attribute__((availability(macosx,introduced=10_6))); - - - - -typedef NSUInteger NSDataBase64EncodingOptions; enum { - - NSDataBase64Encoding64CharacterLineLength = 1UL << 0, - NSDataBase64Encoding76CharacterLineLength = 1UL << 1, - - - NSDataBase64EncodingEndLineWithCarriageReturn = 1UL << 4, - NSDataBase64EncodingEndLineWithLineFeed = 1UL << 5, - -} __attribute__((availability(macosx,introduced=10_9))); - - -typedef NSUInteger NSDataBase64DecodingOptions; enum { - - NSDataBase64DecodingIgnoreUnknownCharacters = 1UL << 0 -} __attribute__((availability(macosx,introduced=10_9))); - - - - - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -struct NSData_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly) NSUInteger length; - - - - - -// @property (readonly) const void *bytes __attribute__((objc_returns_inner_pointer)); - -/* @end */ - - -// @interface NSData (NSExtendedData) - -// @property (readonly, copy) NSString *description; -// - (void)getBytes:(void *)buffer length:(NSUInteger)length; -// - (void)getBytes:(void *)buffer range:(NSRange)range; -// - (BOOL)isEqualToData:(NSData *)other; -// - (NSData *)subdataWithRange:(NSRange)range; -// - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile; -// - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically; -// - (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)writeOptionsMask error:(NSError **)errorPtr; -// - (BOOL)writeToURL:(NSURL *)url options:(NSDataWritingOptions)writeOptionsMask error:(NSError **)errorPtr; -// - (NSRange)rangeOfData:(NSData *)dataToFind options:(NSDataSearchOptions)mask range:(NSRange)searchRange __attribute__((availability(macosx,introduced=10_6))); - - - - -// - (void) enumerateByteRangesUsingBlock:(void (^)(const void *bytes, NSRange byteRange, BOOL *stop))block __attribute__((availability(macosx,introduced=10_9))); - -/* @end */ - - -// @interface NSData (NSDataCreation) - -// + (instancetype)data; -// + (instancetype)dataWithBytes:(nullable const void *)bytes length:(NSUInteger)length; -// + (instancetype)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length; -// + (instancetype)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b; -// + (nullable instancetype)dataWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr; -// + (nullable instancetype)dataWithContentsOfURL:(NSURL *)url options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr; -// + (nullable instancetype)dataWithContentsOfFile:(NSString *)path; -// + (nullable instancetype)dataWithContentsOfURL:(NSURL *)url; -// - (instancetype)initWithBytes:(nullable const void *)bytes length:(NSUInteger)length; -// - (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length; -// - (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b; -// - (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length deallocator:(nullable void (^)(void *bytes, NSUInteger length))deallocator __attribute__((availability(macosx,introduced=10_9))); -// - (nullable instancetype)initWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr; -// - (nullable instancetype)initWithContentsOfURL:(NSURL *)url options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr; -// - (nullable instancetype)initWithContentsOfFile:(NSString *)path; -// - (nullable instancetype)initWithContentsOfURL:(NSURL *)url; -// - (instancetype)initWithData:(NSData *)data; -// + (instancetype)dataWithData:(NSData *)data; - -/* @end */ - - -// @interface NSData (NSDataBase64Encoding) - - - -// - (nullable instancetype)initWithBase64EncodedString:(NSString *)base64String options:(NSDataBase64DecodingOptions)options __attribute__((availability(macosx,introduced=10_9))); - - - -// - (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options __attribute__((availability(macosx,introduced=10_9))); - - - -// - (nullable instancetype)initWithBase64EncodedData:(NSData *)base64Data options:(NSDataBase64DecodingOptions)options __attribute__((availability(macosx,introduced=10_9))); - - - -// - (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options __attribute__((availability(macosx,introduced=10_9))); - -/* @end */ - - - -// @interface NSData (NSDeprecated) - -// - (void)getBytes:(void *)buffer __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "This method is unsafe because it could potentially cause buffer overruns. Use -getBytes:length: instead."))); -// + (nullable id)dataWithContentsOfMappedFile:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use +dataWithContentsOfURL:options:error: and NSDataReadingMappedIfSafe or NSDataReadingMappedAlways instead."))); -// - (nullable id)initWithContentsOfMappedFile:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use -initWithContentsOfURL:options:error: and NSDataReadingMappedIfSafe or NSDataReadingMappedAlways instead."))); - - - -// - (nullable id)initWithBase64Encoding:(NSString *)base64String __attribute__((availability(macosx,introduced=10_6,deprecated=10_9,message="" ))); -// - (NSString *)base64Encoding __attribute__((availability(macosx,introduced=10_6,deprecated=10_9,message="" ))); - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSMutableData -#define _REWRITER_typedef_NSMutableData -typedef struct objc_object NSMutableData; -typedef struct {} _objc_exc_NSMutableData; -#endif - -struct NSMutableData_IMPL { - struct NSData_IMPL NSData_IVARS; -}; - - -// @property (readonly) void *mutableBytes __attribute__((objc_returns_inner_pointer)); -// @property NSUInteger length; - -/* @end */ - - -// @interface NSMutableData (NSExtendedMutableData) - -// - (void)appendBytes:(const void *)bytes length:(NSUInteger)length; -// - (void)appendData:(NSData *)other; -// - (void)increaseLengthBy:(NSUInteger)extraLength; -// - (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)bytes; -// - (void)resetBytesInRange:(NSRange)range; -// - (void)setData:(NSData *)data; -// - (void)replaceBytesInRange:(NSRange)range withBytes:(nullable const void *)replacementBytes length:(NSUInteger)replacementLength; - -/* @end */ - - -// @interface NSMutableData (NSMutableDataCreation) - -// + (nullable instancetype)dataWithCapacity:(NSUInteger)aNumItems; -// + (nullable instancetype)dataWithLength:(NSUInteger)length; -// - (nullable instancetype)initWithCapacity:(NSUInteger)capacity; -// - (nullable instancetype)initWithLength:(NSUInteger)length; - -/* @end */ - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_6))) - -#ifndef _REWRITER_typedef_NSPurgeableData -#define _REWRITER_typedef_NSPurgeableData -typedef struct objc_object NSPurgeableData; -typedef struct {} _objc_exc_NSPurgeableData; -#endif - -struct NSPurgeableData_IMPL { - struct NSMutableData_IMPL NSMutableData_IVARS; - NSUInteger _length; - int32_t _accessCount; - uint8_t _private[32]; - void *_reserved; -}; - - -/* @end */ - - - - - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSAttributedString; -#ifndef _REWRITER_typedef_NSAttributedString -#define _REWRITER_typedef_NSAttributedString -typedef struct objc_object NSAttributedString; -typedef struct {} _objc_exc_NSAttributedString; -#endif - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - - - - -typedef NSInteger NSFormattingContext; enum { - - - NSFormattingContextUnknown = 0, - - - NSFormattingContextDynamic = 1, - - - NSFormattingContextStandalone = 2, - - - NSFormattingContextListItem = 3, - - - NSFormattingContextBeginningOfSentence = 4, - - - NSFormattingContextMiddleOfSentence = 5, - -} __attribute__((availability(macosx,introduced=10_10))); - - - - - - -typedef NSInteger NSFormattingUnitStyle; enum { - NSFormattingUnitStyleShort = 1, - NSFormattingUnitStyleMedium, - NSFormattingUnitStyleLong, -} __attribute__((availability(macosx,introduced=10_10))); - - -#ifndef _REWRITER_typedef_NSFormatter -#define _REWRITER_typedef_NSFormatter -typedef struct objc_object NSFormatter; -typedef struct {} _objc_exc_NSFormatter; -#endif - -struct NSFormatter_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (nullable NSString *)stringForObjectValue:(id)obj; - -// - (nullable NSAttributedString *)attributedStringForObjectValue:(id)obj withDefaultAttributes:(nullable NSDictionary<NSString *, id> *)attrs; - -// - (nullable NSString *)editingStringForObjectValue:(id)obj; - -// - (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string errorDescription:(out NSString * _Nullable * _Nullable)error; - -// - (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString * _Nullable * _Nullable)newString errorDescription:(NSString * _Nullable * _Nullable)error; - - -// - (BOOL)isPartialStringValid:(NSString * _Nonnull * _Nonnull)partialStringPtr proposedSelectedRange:(nullable NSRangePointer)proposedSelRangePtr originalString:(NSString *)origString originalSelectedRange:(NSRange)origSelRange errorDescription:(NSString * _Nullable * _Nullable)error; - -/* @end */ - - - -// @class NSLocale; -#ifndef _REWRITER_typedef_NSLocale -#define _REWRITER_typedef_NSLocale -typedef struct objc_object NSLocale; -typedef struct {} _objc_exc_NSLocale; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -#ifndef _REWRITER_typedef_NSCalendar -#define _REWRITER_typedef_NSCalendar -typedef struct objc_object NSCalendar; -typedef struct {} _objc_exc_NSCalendar; -#endif - -#ifndef _REWRITER_typedef_NSTimeZone -#define _REWRITER_typedef_NSTimeZone -typedef struct objc_object NSTimeZone; -typedef struct {} _objc_exc_NSTimeZone; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - -#ifndef _REWRITER_typedef_NSDateFormatter -#define _REWRITER_typedef_NSDateFormatter -typedef struct objc_object NSDateFormatter; -typedef struct {} _objc_exc_NSDateFormatter; -#endif - -struct NSDateFormatter_IMPL { - struct NSFormatter_IMPL NSFormatter_IVARS; - NSMutableDictionary *_attributes; - CFDateFormatterRef _formatter; - NSUInteger _counter; -}; - - -// @property NSFormattingContext formattingContext __attribute__((availability(macosx,introduced=10_10))); - - - - - -// - (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string range:(inout nullable NSRange *)rangep error:(out NSError **)error; - - - - -// - (NSString *)stringFromDate:(NSDate *)date; -// - (nullable NSDate *)dateFromString:(NSString *)string; - -typedef NSUInteger NSDateFormatterStyle; enum { - NSDateFormatterNoStyle = kCFDateFormatterNoStyle, - NSDateFormatterShortStyle = kCFDateFormatterShortStyle, - NSDateFormatterMediumStyle = kCFDateFormatterMediumStyle, - NSDateFormatterLongStyle = kCFDateFormatterLongStyle, - NSDateFormatterFullStyle = kCFDateFormatterFullStyle -}; - -typedef NSUInteger NSDateFormatterBehavior; enum { - NSDateFormatterBehaviorDefault = 0, - - NSDateFormatterBehavior10_0 = 1000, - - NSDateFormatterBehavior10_4 = 1040, -}; - - -// + (NSString *)localizedStringFromDate:(NSDate *)date dateStyle:(NSDateFormatterStyle)dstyle timeStyle:(NSDateFormatterStyle)tstyle __attribute__((availability(macosx,introduced=10_6))); - -// + (nullable NSString *)dateFormatFromTemplate:(NSString *)tmplate options:(NSUInteger)opts locale:(nullable NSLocale *)locale __attribute__((availability(macosx,introduced=10_6))); - - - - -// + (NSDateFormatterBehavior)defaultFormatterBehavior; -// + (void)setDefaultFormatterBehavior:(NSDateFormatterBehavior)behavior; -// - (void) setLocalizedDateFormatFromTemplate:(NSString *)dateFormatTemplate __attribute__((availability(macosx,introduced=10_10))); - -// @property (null_resettable, copy) NSString *dateFormat; -// @property NSDateFormatterStyle dateStyle; -// @property NSDateFormatterStyle timeStyle; -// @property (null_resettable, copy) NSLocale *locale; -// @property BOOL generatesCalendarDates; -// @property NSDateFormatterBehavior formatterBehavior; -// @property (null_resettable, copy) NSTimeZone *timeZone; -// @property (null_resettable, copy) NSCalendar *calendar; -// @property (getter=isLenient) BOOL lenient; -// @property (nullable, copy) NSDate *twoDigitStartDate; -// @property (nullable, copy) NSDate *defaultDate; -// @property (null_resettable, copy) NSArray<NSString *> *eraSymbols; -// @property (null_resettable, copy) NSArray<NSString *> *monthSymbols; -// @property (null_resettable, copy) NSArray<NSString *> *shortMonthSymbols; -// @property (null_resettable, copy) NSArray<NSString *> *weekdaySymbols; -// @property (null_resettable, copy) NSArray<NSString *> *shortWeekdaySymbols; -// @property (null_resettable, copy) NSString *AMSymbol; -// @property (null_resettable, copy) NSString *PMSymbol; -// @property (null_resettable, copy) NSArray<NSString *> *longEraSymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *veryShortMonthSymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *standaloneMonthSymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *shortStandaloneMonthSymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *veryShortStandaloneMonthSymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *veryShortWeekdaySymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *standaloneWeekdaySymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *shortStandaloneWeekdaySymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *veryShortStandaloneWeekdaySymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *quarterSymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *shortQuarterSymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *standaloneQuarterSymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (null_resettable, copy) NSArray<NSString *> *shortStandaloneQuarterSymbols __attribute__((availability(macosx,introduced=10_5))); -// @property (nullable, copy) NSDate *gregorianStartDate __attribute__((availability(macosx,introduced=10_5))); -// @property BOOL doesRelativeDateFormatting __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - - -// @interface NSDateFormatter (NSDateFormatterCompatibility) - -// - (id)initWithDateFormat:(NSString *)format allowNaturalLanguage:(BOOL)flag __attribute__((availability(macosx,introduced=10_4,deprecated=10_9,message="" "Use -setDateFormat: as of OS X 10.9 to set the date format of a 10.0-style date formatter; but expect 10.0-style date formatting to be deprecated in the future as well"))); -// - (BOOL)allowsNaturalLanguage __attribute__((availability(macosx,introduced=10_4,deprecated=10_9,message="" "There is no replacement"))); - -/* @end */ - - - - - - - -// @class NSLocale; -#ifndef _REWRITER_typedef_NSLocale -#define _REWRITER_typedef_NSLocale -typedef struct objc_object NSLocale; -typedef struct {} _objc_exc_NSLocale; -#endif - -#ifndef _REWRITER_typedef_NSCalendar -#define _REWRITER_typedef_NSCalendar -typedef struct objc_object NSCalendar; -typedef struct {} _objc_exc_NSCalendar; -#endif - -#ifndef _REWRITER_typedef_NSTimeZone -#define _REWRITER_typedef_NSTimeZone -typedef struct objc_object NSTimeZone; -typedef struct {} _objc_exc_NSTimeZone; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - - - - -typedef NSUInteger NSDateIntervalFormatterStyle; enum { - NSDateIntervalFormatterNoStyle = 0, - NSDateIntervalFormatterShortStyle = 1, - NSDateIntervalFormatterMediumStyle = 2, - NSDateIntervalFormatterLongStyle = 3, - NSDateIntervalFormatterFullStyle = 4 -} __attribute__((availability(macosx,introduced=10_10))); - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSDateIntervalFormatter -#define _REWRITER_typedef_NSDateIntervalFormatter -typedef struct objc_object NSDateIntervalFormatter; -typedef struct {} _objc_exc_NSDateIntervalFormatter; -#endif - -struct NSDateIntervalFormatter_IMPL { - struct NSFormatter_IMPL NSFormatter_IVARS; - NSLocale *_locale; - NSCalendar *_calendar; - NSTimeZone *_timeZone; - NSString *_dateTemplate; - NSString *_dateTemplateFromStyles; - void *_formatter; - NSDateIntervalFormatterStyle _dateStyle; - NSDateIntervalFormatterStyle _timeStyle; - BOOL _modified; - BOOL _useTemplate; - dispatch_semaphore_t _lock; - void *_reserved[4]; -}; - - -// @property (null_resettable, copy) NSLocale *locale; -// @property (null_resettable, copy) NSCalendar *calendar; -// @property (null_resettable, copy) NSTimeZone *timeZone; -// @property (null_resettable, copy) NSString *dateTemplate; -// @property NSDateIntervalFormatterStyle dateStyle; -// @property NSDateIntervalFormatterStyle timeStyle; -// - (NSString *)stringFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate; - -/* @end */ - - - - - - - -// @class NSNumberFormatter; -#ifndef _REWRITER_typedef_NSNumberFormatter -#define _REWRITER_typedef_NSNumberFormatter -typedef struct objc_object NSNumberFormatter; -typedef struct {} _objc_exc_NSNumberFormatter; -#endif - - - - -typedef NSInteger NSMassFormatterUnit; enum { - NSMassFormatterUnitGram = 11, - NSMassFormatterUnitKilogram = 14, - NSMassFormatterUnitOunce = (6 << 8) + 1, - NSMassFormatterUnitPound = (6 << 8) + 2, - NSMassFormatterUnitStone = (6 << 8) + 3, -} __attribute__((availability(macosx,introduced=10_10))); - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSMassFormatter -#define _REWRITER_typedef_NSMassFormatter -typedef struct objc_object NSMassFormatter; -typedef struct {} _objc_exc_NSMassFormatter; -#endif - -struct NSMassFormatter_IMPL { - struct NSFormatter_IMPL NSFormatter_IVARS; - void *_formatter; - BOOL _isForPersonMassUse; - void *_reserved[2]; -}; - - -// @property (null_resettable, copy) NSNumberFormatter *numberFormatter; -// @property NSFormattingUnitStyle unitStyle; -// @property (getter = isForPersonMassUse) BOOL forPersonMassUse; - - -// - (NSString *)stringFromValue:(double)value unit:(NSMassFormatterUnit)unit; - - -// - (NSString *)stringFromKilograms:(double)numberInKilograms; - - -// - (NSString *)unitStringFromValue:(double)value unit:(NSMassFormatterUnit)unit; - - -// - (NSString *)unitStringFromKilograms:(double)numberInKilograms usedUnit:(nullable NSMassFormatterUnit *)unitp; - - -// - (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string errorDescription:(out NSString * _Nullable * _Nullable)error; -/* @end */ - - - - - - - - - -typedef NSInteger NSLengthFormatterUnit; enum { - NSLengthFormatterUnitMillimeter = 8, - NSLengthFormatterUnitCentimeter = 9, - NSLengthFormatterUnitMeter = 11, - NSLengthFormatterUnitKilometer = 14, - NSLengthFormatterUnitInch = (5 << 8) + 1, - NSLengthFormatterUnitFoot = (5 << 8) + 2, - NSLengthFormatterUnitYard = (5 << 8) + 3, - NSLengthFormatterUnitMile = (5 << 8) + 4, -} __attribute__((availability(macosx,introduced=10_10))); - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSLengthFormatter -#define _REWRITER_typedef_NSLengthFormatter -typedef struct objc_object NSLengthFormatter; -typedef struct {} _objc_exc_NSLengthFormatter; -#endif - -struct NSLengthFormatter_IMPL { - struct NSFormatter_IMPL NSFormatter_IVARS; - void *_formatter; - BOOL _isForPersonHeight; - void *_reserved[2]; -}; - -// @property (null_resettable, copy) NSNumberFormatter *numberFormatter; -// @property NSFormattingUnitStyle unitStyle; - -// @property (getter = isForPersonHeightUse) BOOL forPersonHeightUse; - - -// - (NSString *)stringFromValue:(double)value unit:(NSLengthFormatterUnit)unit; - - -// - (NSString *)stringFromMeters:(double)numberInMeters; - - -// - (NSString *)unitStringFromValue:(double)value unit:(NSLengthFormatterUnit)unit; - - -// - (NSString *)unitStringFromMeters:(double)numberInMeters usedUnit:(nullable NSLengthFormatterUnit *)unitp; - - -// - (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string errorDescription:(out NSString * _Nullable * _Nullable)error; -/* @end */ - - - - - - - - - -typedef NSInteger NSEnergyFormatterUnit; enum { - NSEnergyFormatterUnitJoule = 11, - NSEnergyFormatterUnitKilojoule = 14, - NSEnergyFormatterUnitCalorie = (7 << 8) + 1, - NSEnergyFormatterUnitKilocalorie = (7 << 8) + 2, -} __attribute__((availability(macosx,introduced=10_10))); - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSEnergyFormatter -#define _REWRITER_typedef_NSEnergyFormatter -typedef struct objc_object NSEnergyFormatter; -typedef struct {} _objc_exc_NSEnergyFormatter; -#endif - -struct NSEnergyFormatter_IMPL { - struct NSFormatter_IMPL NSFormatter_IVARS; - void *_formatter; - BOOL _isForFoodEnergyUse; - void *_reserved[2]; -}; - -// @property (null_resettable, copy) NSNumberFormatter *numberFormatter; -// @property NSFormattingUnitStyle unitStyle; -// @property (getter = isForFoodEnergyUse) BOOL forFoodEnergyUse; - - -// - (NSString *)stringFromValue:(double)value unit:(NSEnergyFormatterUnit)unit; - - -// - (NSString *)stringFromJoules:(double)numberInJoules; - - -// - (NSString *)unitStringFromValue:(double)value unit:(NSEnergyFormatterUnit)unit; - - -// - (NSString *)unitStringFromJoules:(double)numberInJoules usedUnit:(nullable NSEnergyFormatterUnit *)unitp; - - -// - (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string errorDescription:(out NSString * _Nullable * _Nullable)error; -/* @end */ - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_11))) - -#ifndef _REWRITER_typedef_NSPersonNameComponents -#define _REWRITER_typedef_NSPersonNameComponents -typedef struct objc_object NSPersonNameComponents; -typedef struct {} _objc_exc_NSPersonNameComponents; -#endif - -struct NSPersonNameComponents_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _private; -}; - - - - - -// @property (copy, nullable) NSString *namePrefix; - - -// @property (copy, nullable) NSString *givenName; - - -// @property (copy, nullable) NSString *middleName; - - -// @property (copy, nullable) NSString *familyName; - - -// @property (copy, nullable) NSString *nameSuffix; - - -// @property (copy, nullable) NSString *nickname; - - - - -// @property (copy, nullable) NSPersonNameComponents *phoneticRepresentation; - -/* @end */ - -typedef NSInteger NSPersonNameComponentsFormatterStyle; enum { - NSPersonNameComponentsFormatterStyleDefault = 0, - - - - NSPersonNameComponentsFormatterStyleShort, - - - NSPersonNameComponentsFormatterStyleMedium, - - - NSPersonNameComponentsFormatterStyleLong, - - - NSPersonNameComponentsFormatterStyleAbbreviated -} __attribute__((availability(macosx,introduced=10_11))); - -typedef NSUInteger NSPersonNameComponentsFormatterOptions; enum { - - - - - NSPersonNameComponentsFormatterPhonetic = (1UL << 1) -} __attribute__((availability(macosx,introduced=10_11))); - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_11))) - -#ifndef _REWRITER_typedef_NSPersonNameComponentsFormatter -#define _REWRITER_typedef_NSPersonNameComponentsFormatter -typedef struct objc_object NSPersonNameComponentsFormatter; -typedef struct {} _objc_exc_NSPersonNameComponentsFormatter; -#endif - -struct NSPersonNameComponentsFormatter_IMPL { - struct NSFormatter_IMPL NSFormatter_IVARS; - id _private; -}; - - - - -// @property NSPersonNameComponentsFormatterStyle style; - - - -// @property (getter=isPhonetic) BOOL phonetic; - - - - -#if 0 -+ (NSString *)localizedStringFromPersonNameComponents:(NSPersonNameComponents *)components - style:(NSPersonNameComponentsFormatterStyle)nameFormatStyle - options:(NSPersonNameComponentsFormatterOptions)nameOptions; -#endif - - - - -// - (NSString *)stringFromPersonNameComponents:(NSPersonNameComponents *)components; - - - - -// - (NSAttributedString *)annotatedStringFromPersonNameComponents:(NSPersonNameComponents *)components; - - - -// - (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string errorDescription:(out NSString * _Nullable * _Nullable)error; - -/* @end */ - - - -extern "C" NSString * const NSPersonNameComponentKey __attribute__((availability(macosx,introduced=10_11))); - - -extern "C" NSString * const NSPersonNameComponentGivenName __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSPersonNameComponentFamilyName __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSPersonNameComponentMiddleName __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSPersonNameComponentPrefix __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSPersonNameComponentSuffix __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSPersonNameComponentNickname __attribute__((availability(macosx,introduced=10_11))); - - - - -extern "C" NSString * const NSPersonNameComponentDelimiter __attribute__((availability(macosx,introduced=10_11))); - - - - - - - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -typedef NSUInteger NSRoundingMode; enum { - NSRoundPlain, - NSRoundDown, - NSRoundUp, - NSRoundBankers -}; - -typedef NSUInteger NSCalculationError; enum { - NSCalculationNoError = 0, - NSCalculationLossOfPrecision, - NSCalculationUnderflow, - NSCalculationOverflow, - NSCalculationDivideByZero -}; - - - - - - -typedef struct { - signed int _exponent:8; - unsigned int _length:4; - unsigned int _isNegative:1; - unsigned int _isCompact:1; - unsigned int _reserved:18; - unsigned short _mantissa[(8)]; -} NSDecimal; - -static __inline__ __attribute__((always_inline)) BOOL NSDecimalIsNotANumber(const NSDecimal *dcm) - { return ((dcm->_length == 0) && dcm->_isNegative); } - - - -extern "C" void NSDecimalCopy(NSDecimal *destination, const NSDecimal *source); - -extern "C" void NSDecimalCompact(NSDecimal *number); - -extern "C" NSComparisonResult NSDecimalCompare(const NSDecimal *leftOperand, const NSDecimal *rightOperand); - - -extern "C" void NSDecimalRound(NSDecimal *result, const NSDecimal *number, NSInteger scale, NSRoundingMode roundingMode); - - - - -extern "C" NSCalculationError NSDecimalNormalize(NSDecimal *number1, NSDecimal *number2, NSRoundingMode roundingMode); - -extern "C" NSCalculationError NSDecimalAdd(NSDecimal *result, const NSDecimal *leftOperand, const NSDecimal *rightOperand, NSRoundingMode roundingMode); - - -extern "C" NSCalculationError NSDecimalSubtract(NSDecimal *result, const NSDecimal *leftOperand, const NSDecimal *rightOperand, NSRoundingMode roundingMode); - - -extern "C" NSCalculationError NSDecimalMultiply(NSDecimal *result, const NSDecimal *leftOperand, const NSDecimal *rightOperand, NSRoundingMode roundingMode); - - -extern "C" NSCalculationError NSDecimalDivide(NSDecimal *result, const NSDecimal *leftOperand, const NSDecimal *rightOperand, NSRoundingMode roundingMode); - - - -extern "C" NSCalculationError NSDecimalPower(NSDecimal *result, const NSDecimal *number, NSUInteger power, NSRoundingMode roundingMode); - -extern "C" NSCalculationError NSDecimalMultiplyByPowerOf10(NSDecimal *result, const NSDecimal *number, short power, NSRoundingMode roundingMode); - -extern "C" NSString *NSDecimalString(const NSDecimal *dcm, id _Nullable locale); - - - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSCharacterSet -#define _REWRITER_typedef_NSCharacterSet -typedef struct objc_object NSCharacterSet; -typedef struct {} _objc_exc_NSCharacterSet; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - - - - - -#ifndef _REWRITER_typedef_NSScanner -#define _REWRITER_typedef_NSScanner -typedef struct objc_object NSScanner; -typedef struct {} _objc_exc_NSScanner; -#endif - -struct NSScanner_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly, copy) NSString *string; -// @property NSUInteger scanLocation; -// @property (nullable, copy) NSCharacterSet *charactersToBeSkipped; -// @property BOOL caseSensitive; -// @property (nullable, retain) id locale; - -// - (instancetype)initWithString:(NSString *)string __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSScanner (NSExtendedScanner) - - -// - (BOOL)scanInt:(nullable int *)result; -// - (BOOL)scanInteger:(nullable NSInteger *)result __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)scanLongLong:(nullable long long *)result; -// - (BOOL)scanUnsignedLongLong:(nullable unsigned long long *)result __attribute__((availability(macosx,introduced=10_9))); -// - (BOOL)scanFloat:(nullable float *)result; -// - (BOOL)scanDouble:(nullable double *)result; -// - (BOOL)scanHexInt:(nullable unsigned *)result; -// - (BOOL)scanHexLongLong:(nullable unsigned long long *)result __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)scanHexFloat:(nullable float *)result __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)scanHexDouble:(nullable double *)result __attribute__((availability(macosx,introduced=10_5))); - -// - (BOOL)scanString:(NSString *)string intoString:(NSString * _Nullable * _Nullable)result; -// - (BOOL)scanCharactersFromSet:(NSCharacterSet *)set intoString:(NSString * _Nullable * _Nullable)result; - -// - (BOOL)scanUpToString:(NSString *)string intoString:(NSString * _Nullable * _Nullable)result; -// - (BOOL)scanUpToCharactersFromSet:(NSCharacterSet *)set intoString:(NSString * _Nullable * _Nullable)result; - -// @property (getter=isAtEnd, readonly) BOOL atEnd; - -// + (instancetype)scannerWithString:(NSString *)string; -// + (id)localizedScannerWithString:(NSString *)string; - -/* @end */ - - - - - - - - -extern "C" NSString * const NSDecimalNumberExactnessException; -extern "C" NSString * const NSDecimalNumberOverflowException; -extern "C" NSString * const NSDecimalNumberUnderflowException; -extern "C" NSString * const NSDecimalNumberDivideByZeroException; - - - -// @class NSDecimalNumber; -#ifndef _REWRITER_typedef_NSDecimalNumber -#define _REWRITER_typedef_NSDecimalNumber -typedef struct objc_object NSDecimalNumber; -typedef struct {} _objc_exc_NSDecimalNumber; -#endif - - -// @protocol NSDecimalNumberBehaviors - -// - (NSRoundingMode)roundingMode; - -// - (short)scale; - - -// - (nullable NSDecimalNumber *)exceptionDuringOperation:(SEL)operation error:(NSCalculationError)error leftOperand:(NSDecimalNumber *)leftOperand rightOperand:(nullable NSDecimalNumber *)rightOperand; - - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSDecimalNumber -#define _REWRITER_typedef_NSDecimalNumber -typedef struct objc_object NSDecimalNumber; -typedef struct {} _objc_exc_NSDecimalNumber; -#endif - - struct NSDecimalNumber__T_1 { - int _exponent : 8; - unsigned int _length : 4; - unsigned int _isNegative : 1; - unsigned int _isCompact : 1; - unsigned int _reserved : 1; - unsigned int _hasExternalRefCount : 1; - unsigned int _refs : 16; - } ; -struct NSDecimalNumber_IMPL { - struct NSNumber_IMPL NSNumber_IVARS; - struct NSDecimalNumber__T_1 NSDecimalNumber__GRBF_1; - unsigned short _mantissa[0]; -}; - - -// - (instancetype)initWithMantissa:(unsigned long long)mantissa exponent:(short)exponent isNegative:(BOOL)flag; -// - (instancetype)initWithDecimal:(NSDecimal)dcm __attribute__((objc_designated_initializer)); -// - (instancetype)initWithString:(nullable NSString *)numberValue; -// - (instancetype)initWithString:(nullable NSString *)numberValue locale:(nullable id)locale; - -// - (NSString *)descriptionWithLocale:(nullable id)locale; - -// @property (readonly) NSDecimal decimalValue; - -// + (NSDecimalNumber *)decimalNumberWithMantissa:(unsigned long long)mantissa exponent:(short)exponent isNegative:(BOOL)flag; -// + (NSDecimalNumber *)decimalNumberWithDecimal:(NSDecimal)dcm; -// + (NSDecimalNumber *)decimalNumberWithString:(nullable NSString *)numberValue; -// + (NSDecimalNumber *)decimalNumberWithString:(nullable NSString *)numberValue locale:(nullable id)locale; - -// + (NSDecimalNumber *)zero; -// + (NSDecimalNumber *)one; -// + (NSDecimalNumber *)minimumDecimalNumber; -// + (NSDecimalNumber *)maximumDecimalNumber; -// + (NSDecimalNumber *)notANumber; - -// - (NSDecimalNumber *)decimalNumberByAdding:(NSDecimalNumber *)decimalNumber; -// - (NSDecimalNumber *)decimalNumberByAdding:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior; - -// - (NSDecimalNumber *)decimalNumberBySubtracting:(NSDecimalNumber *)decimalNumber; -// - (NSDecimalNumber *)decimalNumberBySubtracting:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior; - -// - (NSDecimalNumber *)decimalNumberByMultiplyingBy:(NSDecimalNumber *)decimalNumber; -// - (NSDecimalNumber *)decimalNumberByMultiplyingBy:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior; - -// - (NSDecimalNumber *)decimalNumberByDividingBy:(NSDecimalNumber *)decimalNumber; -// - (NSDecimalNumber *)decimalNumberByDividingBy:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior; - -// - (NSDecimalNumber *)decimalNumberByRaisingToPower:(NSUInteger)power; -// - (NSDecimalNumber *)decimalNumberByRaisingToPower:(NSUInteger)power withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior; - -// - (NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power; -// - (NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior; - - -// - (NSDecimalNumber *)decimalNumberByRoundingAccordingToBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior; - - -// - (NSComparisonResult)compare:(NSNumber *)decimalNumber; - - -// + (void)setDefaultBehavior:(id <NSDecimalNumberBehaviors>)behavior; - -// + (id <NSDecimalNumberBehaviors>)defaultBehavior; - - - - - - -// @property (readonly) const char *objCType __attribute__((objc_returns_inner_pointer)); - - -// @property (readonly) double doubleValue; - - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSDecimalNumberHandler -#define _REWRITER_typedef_NSDecimalNumberHandler -typedef struct objc_object NSDecimalNumberHandler; -typedef struct {} _objc_exc_NSDecimalNumberHandler; -#endif - - struct NSDecimalNumberHandler__T_1 { - int _scale : 16; - unsigned int _roundingMode : 3; - unsigned int _raiseOnExactness : 1; - unsigned int _raiseOnOverflow : 1; - unsigned int _raiseOnUnderflow : 1; - unsigned int _raiseOnDivideByZero : 1; - unsigned int _unused : 9; - } ; -struct NSDecimalNumberHandler_IMPL { - struct NSObject_IMPL NSObject_IVARS; - struct NSDecimalNumberHandler__T_1 NSDecimalNumberHandler__GRBF_1; - void *_reserved2; - void *_reserved; -}; - - -// + (NSDecimalNumberHandler *)defaultDecimalNumberHandler; - - - - - -// - (instancetype)initWithRoundingMode:(NSRoundingMode)roundingMode scale:(short)scale raiseOnExactness:(BOOL)exact raiseOnOverflow:(BOOL)overflow raiseOnUnderflow:(BOOL)underflow raiseOnDivideByZero:(BOOL)divideByZero __attribute__((objc_designated_initializer)); - -// + (instancetype)decimalNumberHandlerWithRoundingMode:(NSRoundingMode)roundingMode scale:(short)scale raiseOnExactness:(BOOL)exact raiseOnOverflow:(BOOL)overflow raiseOnUnderflow:(BOOL)underflow raiseOnDivideByZero:(BOOL)divideByZero; - -/* @end */ - - - - -// @interface NSNumber (NSDecimalNumberExtensions) - -// @property (readonly) NSDecimal decimalValue; - - -/* @end */ - - -// @interface NSScanner (NSDecimalNumberScanning) - -// - (BOOL)scanDecimal:(nullable NSDecimal *)dcm; - -/* @end */ - - - - - - - - - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - -extern "C" NSString *const NSCocoaErrorDomain; - - -extern "C" NSString *const NSPOSIXErrorDomain; -extern "C" NSString *const NSOSStatusErrorDomain; -extern "C" NSString *const NSMachErrorDomain; - - -extern "C" NSString *const NSUnderlyingErrorKey; - - -extern "C" NSString *const NSLocalizedDescriptionKey; -extern "C" NSString *const NSLocalizedFailureReasonErrorKey; -extern "C" NSString *const NSLocalizedRecoverySuggestionErrorKey; -extern "C" NSString *const NSLocalizedRecoveryOptionsErrorKey; -extern "C" NSString *const NSRecoveryAttempterErrorKey; -extern "C" NSString *const NSHelpAnchorErrorKey; - - -extern "C" NSString *const NSStringEncodingErrorKey ; -extern "C" NSString *const NSURLErrorKey; -extern "C" NSString *const NSFilePathErrorKey; - - - - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -struct NSError_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_reserved; - NSInteger _code; - NSString *_domain; - NSDictionary *_userInfo; -}; - - - - -// - (instancetype)initWithDomain:(NSString *)domain code:(NSInteger)code userInfo:(nullable NSDictionary *)dict __attribute__((objc_designated_initializer)); -// + (instancetype)errorWithDomain:(NSString *)domain code:(NSInteger)code userInfo:(nullable NSDictionary *)dict; - - - -// @property (readonly, copy) NSString *domain; -// @property (readonly) NSInteger code; - - - -// @property (readonly, copy) NSDictionary *userInfo; - - - -// @property (readonly, copy) NSString *localizedDescription; - - - -// @property (nullable, readonly, copy) NSString *localizedFailureReason; - - - -// @property (nullable, readonly, copy) NSString *localizedRecoverySuggestion; - - - -// @property (nullable, readonly, copy) NSArray<NSString *> *localizedRecoveryOptions; - - - -// @property (nullable, readonly, strong) id recoveryAttempter; - - - -// @property (nullable, readonly, copy) NSString *helpAnchor; -// + (void)setUserInfoValueProviderForDomain:(NSString *)errorDomain provider:(id _Nullable (^ _Nullable)(NSError *err, NSString *userInfoKey))provider __attribute__((availability(macosx,introduced=10_11))); -// + (id _Nullable (^ _Nullable)(NSError *err, NSString *userInfoKey))userInfoValueProviderForDomain:(NSString *)errorDomain __attribute__((availability(macosx,introduced=10_11))); - -/* @end */ - - - -// @interface NSObject(NSErrorRecoveryAttempting) - - - - - - - -// - (void)attemptRecoveryFromError:(NSError *)error optionIndex:(NSUInteger)recoveryOptionIndex delegate:(nullable id)delegate didRecoverSelector:(nullable SEL)didRecoverSelector contextInfo:(nullable void *)contextInfo; - - - -// - (BOOL)attemptRecoveryFromError:(NSError *)error optionIndex:(NSUInteger)recoveryOptionIndex; - -/* @end */ - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - - - - - - -extern "C" NSString * const NSGenericException; -extern "C" NSString * const NSRangeException; -extern "C" NSString * const NSInvalidArgumentException; -extern "C" NSString * const NSInternalInconsistencyException; - -extern "C" NSString * const NSMallocException; - -extern "C" NSString * const NSObjectInaccessibleException; -extern "C" NSString * const NSObjectNotAvailableException; -extern "C" NSString * const NSDestinationInvalidException; - -extern "C" NSString * const NSPortTimeoutException; -extern "C" NSString * const NSInvalidSendPortException; -extern "C" NSString * const NSInvalidReceivePortException; -extern "C" NSString * const NSPortSendException; -extern "C" NSString * const NSPortReceiveException; - -extern "C" NSString * const NSOldStyleException; - - - - -__attribute__((__objc_exception__)) - - -#ifndef _REWRITER_typedef_NSException -#define _REWRITER_typedef_NSException -typedef struct objc_object NSException; -typedef struct {} _objc_exc_NSException; -#endif - -struct NSException_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSString *name; - NSString *reason; - NSDictionary *userInfo; - id reserved; -}; - - -// + (NSException *)exceptionWithName:(NSString *)name reason:(nullable NSString *)reason userInfo:(nullable NSDictionary *)userInfo; -// - (instancetype)initWithName:(NSString *)aName reason:(nullable NSString *)aReason userInfo:(nullable NSDictionary *)aUserInfo __attribute__((objc_designated_initializer)); - -// @property (readonly, copy) NSString *name; -// @property (nullable, readonly, copy) NSString *reason; -// @property (nullable, readonly, copy) NSDictionary *userInfo; - -// @property (readonly, copy) NSArray<NSNumber *> *callStackReturnAddresses __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly, copy) NSArray<NSString *> *callStackSymbols __attribute__((availability(macosx,introduced=10_6))); - -// - (void)raise; - -/* @end */ - - -// @interface NSException (NSExceptionRaisingConveniences) - -// + (void)raise:(NSString *)name format:(NSString *)format, ... __attribute__((format(__NSString__, 2, 3))); -// + (void)raise:(NSString *)name format:(NSString *)format arguments:(va_list)argList __attribute__((format(__NSString__, 2, 0))); - -/* @end */ - -typedef void NSUncaughtExceptionHandler(NSException *exception); - -extern "C" NSUncaughtExceptionHandler * _Nullable NSGetUncaughtExceptionHandler(void); -extern "C" void NSSetUncaughtExceptionHandler(NSUncaughtExceptionHandler * _Nullable); -// @class NSAssertionHandler; -#ifndef _REWRITER_typedef_NSAssertionHandler -#define _REWRITER_typedef_NSAssertionHandler -typedef struct objc_object NSAssertionHandler; -typedef struct {} _objc_exc_NSAssertionHandler; -#endif - -extern "C" NSString * const NSAssertionHandlerKey __attribute__((availability(macosx,introduced=10_6))); - - -#ifndef _REWRITER_typedef_NSAssertionHandler -#define _REWRITER_typedef_NSAssertionHandler -typedef struct objc_object NSAssertionHandler; -typedef struct {} _objc_exc_NSAssertionHandler; -#endif - -struct NSAssertionHandler_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_reserved; -}; - - -// + (NSAssertionHandler *)currentHandler; - -// - (void)handleFailureInMethod:(SEL)selector object:(id)object file:(NSString *)fileName lineNumber:(NSInteger)line description:(nullable NSString *)format,... __attribute__((format(__NSString__, 5, 6))); - -// - (void)handleFailureInFunction:(NSString *)functionName file:(NSString *)fileName lineNumber:(NSInteger)line description:(nullable NSString *)format,... __attribute__((format(__NSString__, 4, 5))); - -/* @end */ - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - - - - - -#ifndef _REWRITER_typedef_NSFileHandle -#define _REWRITER_typedef_NSFileHandle -typedef struct objc_object NSFileHandle; -typedef struct {} _objc_exc_NSFileHandle; -#endif - -struct NSFileHandle_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly, copy) NSData *availableData; - -// - (NSData *)readDataToEndOfFile; -// - (NSData *)readDataOfLength:(NSUInteger)length; - -// - (void)writeData:(NSData *)data; - -// @property (readonly) unsigned long long offsetInFile; -// - (unsigned long long)seekToEndOfFile; -// - (void)seekToFileOffset:(unsigned long long)offset; - -// - (void)truncateFileAtOffset:(unsigned long long)offset; -// - (void)synchronizeFile; -// - (void)closeFile; - -// - (instancetype)initWithFileDescriptor:(int)fd closeOnDealloc:(BOOL)closeopt __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)coder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSFileHandle (NSFileHandleCreation) - -// + (NSFileHandle *)fileHandleWithStandardInput; -// + (NSFileHandle *)fileHandleWithStandardOutput; -// + (NSFileHandle *)fileHandleWithStandardError; -// + (NSFileHandle *)fileHandleWithNullDevice; - -// + (nullable instancetype)fileHandleForReadingAtPath:(NSString *)path; -// + (nullable instancetype)fileHandleForWritingAtPath:(NSString *)path; -// + (nullable instancetype)fileHandleForUpdatingAtPath:(NSString *)path; - -// + (nullable instancetype)fileHandleForReadingFromURL:(NSURL *)url error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); -// + (nullable instancetype)fileHandleForWritingToURL:(NSURL *)url error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); -// + (nullable instancetype)fileHandleForUpdatingURL:(NSURL *)url error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -extern "C" NSString * const NSFileHandleOperationException; - -extern "C" NSString * const NSFileHandleReadCompletionNotification; -extern "C" NSString * const NSFileHandleReadToEndOfFileCompletionNotification; -extern "C" NSString * const NSFileHandleConnectionAcceptedNotification; -extern "C" NSString * const NSFileHandleDataAvailableNotification; - -extern "C" NSString * const NSFileHandleNotificationDataItem; -extern "C" NSString * const NSFileHandleNotificationFileHandleItem; -extern "C" NSString * const NSFileHandleNotificationMonitorModes __attribute__((availability(macosx,introduced=10_0,deprecated=10_7,message="" ))); - -// @interface NSFileHandle (NSFileHandleAsynchronousAccess) - -// - (void)readInBackgroundAndNotifyForModes:(nullable NSArray<NSString *> *)modes; -// - (void)readInBackgroundAndNotify; - -// - (void)readToEndOfFileInBackgroundAndNotifyForModes:(nullable NSArray<NSString *> *)modes; -// - (void)readToEndOfFileInBackgroundAndNotify; - -// - (void)acceptConnectionInBackgroundAndNotifyForModes:(nullable NSArray<NSString *> *)modes; -// - (void)acceptConnectionInBackgroundAndNotify; - -// - (void)waitForDataInBackgroundAndNotifyForModes:(nullable NSArray<NSString *> *)modes; -// - (void)waitForDataInBackgroundAndNotify; - - -// @property (nullable, copy) void (^readabilityHandler)(NSFileHandle *) __attribute__((availability(macosx,introduced=10_7))); -// @property (nullable, copy) void (^writeabilityHandler)(NSFileHandle *) __attribute__((availability(macosx,introduced=10_7))); - - -/* @end */ - - -// @interface NSFileHandle (NSFileHandlePlatformSpecific) - -// - (instancetype)initWithFileDescriptor:(int)fd; - -// @property (readonly) int fileDescriptor; - -/* @end */ - - - -#ifndef _REWRITER_typedef_NSPipe -#define _REWRITER_typedef_NSPipe -typedef struct objc_object NSPipe; -typedef struct {} _objc_exc_NSPipe; -#endif - -struct NSPipe_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly, retain) NSFileHandle *fileHandleForReading; -// @property (readonly, retain) NSFileHandle *fileHandleForWriting; - -// + (NSPipe *)pipe; - -/* @end */ - - - - - - - - -// @interface NSString (NSStringPathExtensions) - -// + (NSString *)pathWithComponents:(NSArray<NSString *> *)components; -// @property (readonly, copy) NSArray<NSString *> *pathComponents; - -// @property (getter=isAbsolutePath, readonly) BOOL absolutePath; - -// @property (readonly, copy) NSString *lastPathComponent; -// @property (readonly, copy) NSString *stringByDeletingLastPathComponent; -// - (NSString *)stringByAppendingPathComponent:(NSString *)str; - -// @property (readonly, copy) NSString *pathExtension; -// @property (readonly, copy) NSString *stringByDeletingPathExtension; -// - (nullable NSString *)stringByAppendingPathExtension:(NSString *)str; - -// @property (readonly, copy) NSString *stringByAbbreviatingWithTildeInPath; -// @property (readonly, copy) NSString *stringByExpandingTildeInPath; - -// @property (readonly, copy) NSString *stringByStandardizingPath; - -// @property (readonly, copy) NSString *stringByResolvingSymlinksInPath; - -// - (NSArray<NSString *> *)stringsByAppendingPaths:(NSArray<NSString *> *)paths; - -// - (NSUInteger)completePathIntoString:(NSString * _Nonnull * _Nullable)outputName caseSensitive:(BOOL)flag matchesIntoArray:(NSArray<NSString *> * _Nonnull * _Nullable)outputArray filterTypes:(nullable NSArray<NSString *> *)filterTypes; - -// @property (readonly) __attribute__((objc_ownership(strong))) const char *fileSystemRepresentation __attribute__((objc_returns_inner_pointer)); -// - (BOOL)getFileSystemRepresentation:(char *)cname maxLength:(NSUInteger)max; - -/* @end */ - - -// @interface NSArray<ObjectType> (NSArrayPathExtensions) - -// - (NSArray<NSString *> *)pathsMatchingExtensions:(NSArray<NSString *> *)filterTypes; - -/* @end */ - - -extern "C" NSString *NSUserName(void); -extern "C" NSString *NSFullUserName(void); - -extern "C" NSString *NSHomeDirectory(void); -extern "C" NSString * _Nullable NSHomeDirectoryForUser(NSString * _Nullable userName); - -extern "C" NSString *NSTemporaryDirectory(void); - -extern "C" NSString *NSOpenStepRootDirectory(void); - -typedef NSUInteger NSSearchPathDirectory; enum { - NSApplicationDirectory = 1, - NSDemoApplicationDirectory, - NSDeveloperApplicationDirectory, - NSAdminApplicationDirectory, - NSLibraryDirectory, - NSDeveloperDirectory, - NSUserDirectory, - NSDocumentationDirectory, - NSDocumentDirectory, - NSCoreServiceDirectory, - NSAutosavedInformationDirectory __attribute__((availability(macosx,introduced=10_6))) = 11, - NSDesktopDirectory = 12, - NSCachesDirectory = 13, - NSApplicationSupportDirectory = 14, - NSDownloadsDirectory __attribute__((availability(macosx,introduced=10_5))) = 15, - NSInputMethodsDirectory __attribute__((availability(macosx,introduced=10_6))) = 16, - NSMoviesDirectory __attribute__((availability(macosx,introduced=10_6))) = 17, - NSMusicDirectory __attribute__((availability(macosx,introduced=10_6))) = 18, - NSPicturesDirectory __attribute__((availability(macosx,introduced=10_6))) = 19, - NSPrinterDescriptionDirectory __attribute__((availability(macosx,introduced=10_6))) = 20, - NSSharedPublicDirectory __attribute__((availability(macosx,introduced=10_6))) = 21, - NSPreferencePanesDirectory __attribute__((availability(macosx,introduced=10_6))) = 22, - NSApplicationScriptsDirectory __attribute__((availability(macosx,introduced=10_8))) = 23, - NSItemReplacementDirectory __attribute__((availability(macosx,introduced=10_6))) = 99, - NSAllApplicationsDirectory = 100, - NSAllLibrariesDirectory = 101, - NSTrashDirectory __attribute__((availability(macosx,introduced=10_8))) = 102 - -}; - -typedef NSUInteger NSSearchPathDomainMask; enum { - NSUserDomainMask = 1, - NSLocalDomainMask = 2, - NSNetworkDomainMask = 4, - NSSystemDomainMask = 8, - NSAllDomainsMask = 0x0ffff -}; - -extern "C" NSArray<NSString *> *NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory directory, NSSearchPathDomainMask domainMask, BOOL expandTilde); - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -#ifndef _REWRITER_typedef_NSDirectoryEnumerator -#define _REWRITER_typedef_NSDirectoryEnumerator -typedef struct objc_object NSDirectoryEnumerator; -typedef struct {} _objc_exc_NSDirectoryEnumerator; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - -// @protocol NSFileManagerDelegate; - - - - - - - -typedef NSUInteger NSVolumeEnumerationOptions; enum { - - - NSVolumeEnumerationSkipHiddenVolumes = 1UL << 1, - - - - NSVolumeEnumerationProduceFileReferenceURLs = 1UL << 2 -} __attribute__((availability(macosx,introduced=10_6))); - -typedef NSUInteger NSDirectoryEnumerationOptions; enum { - - - NSDirectoryEnumerationSkipsSubdirectoryDescendants = 1UL << 0, - - - - NSDirectoryEnumerationSkipsPackageDescendants = 1UL << 1, - - - - NSDirectoryEnumerationSkipsHiddenFiles = 1UL << 2 -} __attribute__((availability(macosx,introduced=10_6))); - -typedef NSUInteger NSFileManagerItemReplacementOptions; enum { - - - NSFileManagerItemReplacementUsingNewMetadataOnly = 1UL << 0, - - - - NSFileManagerItemReplacementWithoutDeletingBackupItem = 1UL << 1 -} __attribute__((availability(macosx,introduced=10_6))); - -typedef NSInteger NSURLRelationship; enum { - NSURLRelationshipContains, - NSURLRelationshipSame, - NSURLRelationshipOther -} __attribute__((availability(macosx,introduced=10_10))); - - -typedef NSUInteger NSFileManagerUnmountOptions; enum { - - - NSFileManagerUnmountAllPartitionsAndEjectDisk = 1UL << 0, - - - - NSFileManagerUnmountWithoutUI = 1UL << 1, -} __attribute__((availability(macosx,introduced=10_11))); - - -extern "C" NSString *const NSFileManagerUnmountDissentingProcessIdentifierErrorKey __attribute__((availability(macosx,introduced=10_11))); - - - -extern NSString * const NSUbiquityIdentityDidChangeNotification __attribute__((availability(macosx,introduced=10_8))); - - -#ifndef _REWRITER_typedef_NSFileManager -#define _REWRITER_typedef_NSFileManager -typedef struct objc_object NSFileManager; -typedef struct {} _objc_exc_NSFileManager; -#endif - -struct NSFileManager_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - - -// + (NSFileManager *)defaultManager; - - - -// - (nullable NSArray<NSURL *> *)mountedVolumeURLsIncludingResourceValuesForKeys:(nullable NSArray<NSString *> *)propertyKeys options:(NSVolumeEnumerationOptions)options __attribute__((availability(macosx,introduced=10_6))); - - - -// - (void)unmountVolumeAtURL:(NSURL *)url options:(NSFileManagerUnmountOptions)mask completionHandler:(void (^)(NSError * _Nullable errorOrNil))completionHandler __attribute__((availability(macosx,introduced=10_11))); - - - - - - - -// - (nullable NSArray<NSURL *> *)contentsOfDirectoryAtURL:(NSURL *)url includingPropertiesForKeys:(nullable NSArray<NSString *> *)keys options:(NSDirectoryEnumerationOptions)mask error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - - -// - (NSArray<NSURL *> *)URLsForDirectory:(NSSearchPathDirectory)directory inDomains:(NSSearchPathDomainMask)domainMask __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (nullable NSURL *)URLForDirectory:(NSSearchPathDirectory)directory inDomain:(NSSearchPathDomainMask)domain appropriateForURL:(nullable NSURL *)url create:(BOOL)shouldCreate error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// - (BOOL)getRelationship:(NSURLRelationship *)outRelationship ofDirectoryAtURL:(NSURL *)directoryURL toItemAtURL:(NSURL *)otherURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_10))); - - - -// - (BOOL)getRelationship:(NSURLRelationship *)outRelationship ofDirectory:(NSSearchPathDirectory)directory inDomain:(NSSearchPathDomainMask)domainMask toItemAtURL:(NSURL *)url error:(NSError **)error __attribute__((availability(macosx,introduced=10_10))); - - - -// - (BOOL)createDirectoryAtURL:(NSURL *)url withIntermediateDirectories:(BOOL)createIntermediates attributes:(nullable NSDictionary<NSString *, id> *)attributes error:(NSError **)error __attribute__((availability(macosx,introduced=10_7))); - - - -// - (BOOL)createSymbolicLinkAtURL:(NSURL *)url withDestinationURL:(NSURL *)destURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_7))); - - - -// @property (nullable, assign) id <NSFileManagerDelegate> delegate __attribute__((availability(macosx,introduced=10_5))); - - - - - -// - (BOOL)setAttributes:(NSDictionary<NSString *, id> *)attributes ofItemAtPath:(NSString *)path error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - - - - -// - (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(nullable NSDictionary<NSString *, id> *)attributes error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - - - - -// - (nullable NSArray<NSString *> *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - - - - -// - (nullable NSArray<NSString *> *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - - - - -// - (nullable NSDictionary<NSString *, id> *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - - - - -// - (nullable NSDictionary<NSString *, id> *)attributesOfFileSystemForPath:(NSString *)path error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - - - - -// - (BOOL)createSymbolicLinkAtPath:(NSString *)path withDestinationPath:(NSString *)destPath error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - - - - -// - (nullable NSString *)destinationOfSymbolicLinkAtPath:(NSString *)path error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - - -// - (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)linkItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error __attribute__((availability(macosx,introduced=10_5))); - - - -// - (BOOL)copyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); -// - (BOOL)moveItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); -// - (BOOL)linkItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); -// - (BOOL)removeItemAtURL:(NSURL *)URL error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (BOOL)trashItemAtURL:(NSURL *)url resultingItemURL:(NSURL * _Nullable * _Nullable)outResultingURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_8))); - - - -// - (nullable NSDictionary *)fileAttributesAtPath:(NSString *)path traverseLink:(BOOL)yorn __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (BOOL)changeFileAttributes:(NSDictionary *)attributes atPath:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (nullable NSArray *)directoryContentsAtPath:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (nullable NSDictionary *)fileSystemAttributesAtPath:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (nullable NSString *)pathContentOfSymbolicLinkAtPath:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (BOOL)createSymbolicLinkAtPath:(NSString *)path pathContent:(NSString *)otherpath __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (BOOL)createDirectoryAtPath:(NSString *)path attributes:(NSDictionary *)attributes __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - - -// - (BOOL)linkPath:(NSString *)src toPath:(NSString *)dest handler:(nullable id)handler __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (BOOL)copyPath:(NSString *)src toPath:(NSString *)dest handler:(nullable id)handler __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (BOOL)movePath:(NSString *)src toPath:(NSString *)dest handler:(nullable id)handler __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (BOOL)removeFileAtPath:(NSString *)path handler:(nullable id)handler __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - - - - -// @property (readonly, copy) NSString *currentDirectoryPath; -// - (BOOL)changeCurrentDirectoryPath:(NSString *)path; - - - -// - (BOOL)fileExistsAtPath:(NSString *)path; -// - (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(nullable BOOL *)isDirectory; -// - (BOOL)isReadableFileAtPath:(NSString *)path; -// - (BOOL)isWritableFileAtPath:(NSString *)path; -// - (BOOL)isExecutableFileAtPath:(NSString *)path; -// - (BOOL)isDeletableFileAtPath:(NSString *)path; - - - -// - (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2; - - - -// - (NSString *)displayNameAtPath:(NSString *)path; - - - -// - (nullable NSArray<NSString *> *)componentsToDisplayForPath:(NSString *)path; - - - -// - (nullable NSDirectoryEnumerator<NSString *> *)enumeratorAtPath:(NSString *)path; - - - - - -// - (nullable NSDirectoryEnumerator<NSURL *> *)enumeratorAtURL:(NSURL *)url includingPropertiesForKeys:(nullable NSArray<NSString *> *)keys options:(NSDirectoryEnumerationOptions)mask errorHandler:(nullable BOOL (^)(NSURL *url, NSError *error))handler __attribute__((availability(macosx,introduced=10_6))); - - - -// - (nullable NSArray<NSString *> *)subpathsAtPath:(NSString *)path; - - - -// - (nullable NSData *)contentsAtPath:(NSString *)path; -// - (BOOL)createFileAtPath:(NSString *)path contents:(nullable NSData *)data attributes:(nullable NSDictionary<NSString *, id> *)attr; - - - -// - (__attribute__((objc_ownership(strong))) const char *)fileSystemRepresentationWithPath:(NSString *)path __attribute__((objc_returns_inner_pointer)); - - - -// - (NSString *)stringWithFileSystemRepresentation:(const char *)str length:(NSUInteger)len; -// - (BOOL)replaceItemAtURL:(NSURL *)originalItemURL withItemAtURL:(NSURL *)newItemURL backupItemName:(nullable NSString *)backupItemName options:(NSFileManagerItemReplacementOptions)options resultingItemURL:(NSURL * _Nullable * _Nullable)resultingURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - - -// - (BOOL)setUbiquitous:(BOOL)flag itemAtURL:(NSURL *)url destinationURL:(NSURL *)destinationURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_7))); - - - -// - (BOOL)isUbiquitousItemAtURL:(NSURL *)url __attribute__((availability(macosx,introduced=10_7))); - - - -// - (BOOL)startDownloadingUbiquitousItemAtURL:(NSURL *)url error:(NSError **)error __attribute__((availability(macosx,introduced=10_7))); - - - -// - (BOOL)evictUbiquitousItemAtURL:(NSURL *)url error:(NSError **)error __attribute__((availability(macosx,introduced=10_7))); - - - -// - (nullable NSURL *)URLForUbiquityContainerIdentifier:(nullable NSString *)containerIdentifier __attribute__((availability(macosx,introduced=10_7))); - - - -// - (nullable NSURL *)URLForPublishingUbiquitousItemAtURL:(NSURL *)url expirationDate:(NSDate * _Nullable * _Nullable)outDate error:(NSError **)error __attribute__((availability(macosx,introduced=10_7))); - - - - - -// @property (nullable, readonly, copy) id<NSObject,NSCopying,NSCoding> ubiquityIdentityToken __attribute__((availability(macosx,introduced=10_8))); - - - -// - (nullable NSURL *)containerURLForSecurityApplicationGroupIdentifier:(NSString *)groupIdentifier __attribute__((availability(macosx,introduced=10_8))); - - -/* @end */ - - - - -// @interface NSObject (NSCopyLinkMoveHandler) -// - (BOOL)fileManager:(NSFileManager *)fm shouldProceedAfterError:(NSDictionary *)errorInfo __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// - (void)fileManager:(NSFileManager *)fm willProcessPath:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -/* @end */ - - - -// @protocol NSFileManagerDelegate <NSObject> -/* @optional */ - - - - - -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath; -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath; -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldMoveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath; -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldMoveItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error movingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath; -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error movingItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldLinkItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath; -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldLinkItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error linkingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath; -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error linkingItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldRemoveItemAtPath:(NSString *)path; -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldRemoveItemAtURL:(NSURL *)URL __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error removingItemAtPath:(NSString *)path; -// - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error removingItemAtURL:(NSURL *)URL __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSDirectoryEnumerator -#define _REWRITER_typedef_NSDirectoryEnumerator -typedef struct objc_object NSDirectoryEnumerator; -typedef struct {} _objc_exc_NSDirectoryEnumerator; -#endif - -struct NSDirectoryEnumerator_IMPL { - struct NSEnumerator_IMPL NSEnumerator_IVARS; -}; - - - - -// @property (nullable, readonly, copy) NSDictionary<NSString *, id> *fileAttributes; -// @property (nullable, readonly, copy) NSDictionary<NSString *, id> *directoryAttributes; - -// - (void)skipDescendents; - - - -// @property (readonly) NSUInteger level __attribute__((availability(macosx,introduced=10_6))); - - - -// - (void)skipDescendants __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -extern "C" NSString * const NSFileType; -extern "C" NSString * const NSFileTypeDirectory; -extern "C" NSString * const NSFileTypeRegular; -extern "C" NSString * const NSFileTypeSymbolicLink; -extern "C" NSString * const NSFileTypeSocket; -extern "C" NSString * const NSFileTypeCharacterSpecial; -extern "C" NSString * const NSFileTypeBlockSpecial; -extern "C" NSString * const NSFileTypeUnknown; -extern "C" NSString * const NSFileSize; -extern "C" NSString * const NSFileModificationDate; -extern "C" NSString * const NSFileReferenceCount; -extern "C" NSString * const NSFileDeviceIdentifier; -extern "C" NSString * const NSFileOwnerAccountName; -extern "C" NSString * const NSFileGroupOwnerAccountName; -extern "C" NSString * const NSFilePosixPermissions; -extern "C" NSString * const NSFileSystemNumber; -extern "C" NSString * const NSFileSystemFileNumber; -extern "C" NSString * const NSFileExtensionHidden; -extern "C" NSString * const NSFileHFSCreatorCode; -extern "C" NSString * const NSFileHFSTypeCode; -extern "C" NSString * const NSFileImmutable; -extern "C" NSString * const NSFileAppendOnly; -extern "C" NSString * const NSFileCreationDate; -extern "C" NSString * const NSFileOwnerAccountID; -extern "C" NSString * const NSFileGroupOwnerAccountID; -extern "C" NSString * const NSFileBusy; -extern "C" NSString * const NSFileProtectionKey __attribute__((availability(macosx,unavailable))); -extern "C" NSString * const NSFileProtectionNone __attribute__((availability(macosx,unavailable))); -extern "C" NSString * const NSFileProtectionComplete __attribute__((availability(macosx,unavailable))); -extern "C" NSString * const NSFileProtectionCompleteUnlessOpen __attribute__((availability(macosx,unavailable))); -extern "C" NSString * const NSFileProtectionCompleteUntilFirstUserAuthentication __attribute__((availability(macosx,unavailable))); - -extern "C" NSString * const NSFileSystemSize; -extern "C" NSString * const NSFileSystemFreeSize; -extern "C" NSString * const NSFileSystemNodes; -extern "C" NSString * const NSFileSystemFreeNodes; - -// @interface NSDictionary<KeyType, ObjectType> (NSFileAttributes) - -// - (unsigned long long)fileSize; -// - (nullable NSDate *)fileModificationDate; -// - (nullable NSString *)fileType; -// - (NSUInteger)filePosixPermissions; -// - (nullable NSString *)fileOwnerAccountName; -// - (nullable NSString *)fileGroupOwnerAccountName; -// - (NSInteger)fileSystemNumber; -// - (NSUInteger)fileSystemFileNumber; -// - (BOOL)fileExtensionHidden; -// - (OSType)fileHFSCreatorCode; -// - (OSType)fileHFSTypeCode; -// - (BOOL)fileIsImmutable; -// - (BOOL)fileIsAppendOnly; -// - (nullable NSDate *)fileCreationDate; -// - (nullable NSNumber *)fileOwnerAccountID; -// - (nullable NSNumber *)fileGroupOwnerAccountID; -/* @end */ - - - - - - -typedef NSUInteger NSPointerFunctionsOptions; enum { - - - - NSPointerFunctionsStrongMemory __attribute__((availability(macosx,introduced=10_5))) = (0UL << 0), - - NSPointerFunctionsZeroingWeakMemory __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))) = (1UL << 0), - - NSPointerFunctionsOpaqueMemory __attribute__((availability(macosx,introduced=10_5))) = (2UL << 0), - NSPointerFunctionsMallocMemory __attribute__((availability(macosx,introduced=10_5))) = (3UL << 0), - NSPointerFunctionsMachVirtualMemory __attribute__((availability(macosx,introduced=10_5))) = (4UL << 0), - NSPointerFunctionsWeakMemory __attribute__((availability(macosx,introduced=10_8))) = (5UL << 0), - - - - NSPointerFunctionsObjectPersonality __attribute__((availability(macosx,introduced=10_5))) = (0UL << 8), - NSPointerFunctionsOpaquePersonality __attribute__((availability(macosx,introduced=10_5))) = (1UL << 8), - NSPointerFunctionsObjectPointerPersonality __attribute__((availability(macosx,introduced=10_5))) = (2UL << 8), - NSPointerFunctionsCStringPersonality __attribute__((availability(macosx,introduced=10_5))) = (3UL << 8), - NSPointerFunctionsStructPersonality __attribute__((availability(macosx,introduced=10_5))) = (4UL << 8), - NSPointerFunctionsIntegerPersonality __attribute__((availability(macosx,introduced=10_5))) = (5UL << 8), - - NSPointerFunctionsCopyIn __attribute__((availability(macosx,introduced=10_5))) = (1UL << 16), -}; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_5))) - -#ifndef _REWRITER_typedef_NSPointerFunctions -#define _REWRITER_typedef_NSPointerFunctions -typedef struct objc_object NSPointerFunctions; -typedef struct {} _objc_exc_NSPointerFunctions; -#endif - -struct NSPointerFunctions_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (instancetype)initWithOptions:(NSPointerFunctionsOptions)options __attribute__((objc_designated_initializer)); -// + (NSPointerFunctions *)pointerFunctionsWithOptions:(NSPointerFunctionsOptions)options; - - -// @property (nullable) NSUInteger (*hashFunction)(const void *item, NSUInteger (* _Nullable size)(const void *item)); -// @property (nullable) BOOL (*isEqualFunction)(const void *item1, const void*item2, NSUInteger (* _Nullable size)(const void *item)); -// @property (nullable) NSUInteger (*sizeFunction)(const void *item); -// @property (nullable) NSString * _Nullable (*descriptionFunction)(const void *item); - - -// @property (nullable) void (*relinquishFunction)(const void *item, NSUInteger (* _Nullable size)(const void *item)); -// @property (nullable) void * _Nonnull (*acquireFunction)(const void *src, NSUInteger (* _Nullable size)(const void *item), BOOL shouldCopy); - - -// @property BOOL usesStrongWriteBarrier; -// @property BOOL usesWeakReadAndWriteBarriers; -/* @end */ - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - -#ifndef _REWRITER_typedef_NSHashTable -#define _REWRITER_typedef_NSHashTable -typedef struct objc_object NSHashTable; -typedef struct {} _objc_exc_NSHashTable; -#endif - - - - - - - - -static const NSPointerFunctionsOptions NSHashTableStrongMemory __attribute__((availability(macosx,introduced=10_5))) = NSPointerFunctionsStrongMemory; - -static const NSPointerFunctionsOptions NSHashTableZeroingWeakMemory __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))) = NSPointerFunctionsZeroingWeakMemory; - -static const NSPointerFunctionsOptions NSHashTableCopyIn __attribute__((availability(macosx,introduced=10_5))) = NSPointerFunctionsCopyIn; -static const NSPointerFunctionsOptions NSHashTableObjectPointerPersonality __attribute__((availability(macosx,introduced=10_5))) = NSPointerFunctionsObjectPointerPersonality; -static const NSPointerFunctionsOptions NSHashTableWeakMemory __attribute__((availability(macosx,introduced=10_8))) = NSPointerFunctionsWeakMemory; - -typedef NSUInteger NSHashTableOptions; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_5))) - -#ifndef _REWRITER_typedef_NSHashTable -#define _REWRITER_typedef_NSHashTable -typedef struct objc_object NSHashTable; -typedef struct {} _objc_exc_NSHashTable; -#endif - -struct NSHashTable_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (instancetype)initWithOptions:(NSPointerFunctionsOptions)options capacity:(NSUInteger)initialCapacity __attribute__((objc_designated_initializer)); -// - (instancetype)initWithPointerFunctions:(NSPointerFunctions *)functions capacity:(NSUInteger)initialCapacity __attribute__((objc_designated_initializer)); - - - -// + (NSHashTable<ObjectType> *)hashTableWithOptions:(NSPointerFunctionsOptions)options; - - -// + (id)hashTableWithWeakObjects __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))); - - -// + (NSHashTable<ObjectType> *)weakObjectsHashTable __attribute__((availability(macosx,introduced=10_8))); - - - -// @property (readonly, copy) NSPointerFunctions *pointerFunctions; - -// @property (readonly) NSUInteger count; -// - (nullable ObjectType)member:(nullable ObjectType)object; -// - (NSEnumerator<ObjectType> *)objectEnumerator; - -// - (void)addObject:(nullable ObjectType)object; -// - (void)removeObject:(nullable ObjectType)object; - -// - (void)removeAllObjects; - -// @property (readonly, copy) NSArray<ObjectType> *allObjects; - -// @property (nullable, nonatomic, readonly) ObjectType anyObject; -// - (BOOL)containsObject:(nullable ObjectType)anObject; - -// - (BOOL)intersectsHashTable:(NSHashTable<ObjectType> *)other; -// - (BOOL)isEqualToHashTable:(NSHashTable<ObjectType> *)other; -// - (BOOL)isSubsetOfHashTable:(NSHashTable<ObjectType> *)other; - -// - (void)intersectHashTable:(NSHashTable<ObjectType> *)other; -// - (void)unionHashTable:(NSHashTable<ObjectType> *)other; -// - (void)minusHashTable:(NSHashTable<ObjectType> *)other; - -// @property (readonly, copy) NSSet<ObjectType> *setRepresentation; - -/* @end */ - -typedef struct {NSUInteger _pi; NSUInteger _si; void * _Nullable _bs;} NSHashEnumerator; - -extern "C" void NSFreeHashTable(NSHashTable *table); -extern "C" void NSResetHashTable(NSHashTable *table); -extern "C" BOOL NSCompareHashTables(NSHashTable *table1, NSHashTable *table2); -extern "C" NSHashTable *NSCopyHashTableWithZone(NSHashTable *table, NSZone * _Nullable zone); -extern "C" void *NSHashGet(NSHashTable *table, const void * _Nullable pointer); -extern "C" void NSHashInsert(NSHashTable *table, const void * _Nullable pointer); -extern "C" void NSHashInsertKnownAbsent(NSHashTable *table, const void * _Nullable pointer); -extern "C" void * _Nullable NSHashInsertIfAbsent(NSHashTable *table, const void * _Nullable pointer); -extern "C" void NSHashRemove(NSHashTable *table, const void * _Nullable pointer); -extern "C" NSHashEnumerator NSEnumerateHashTable(NSHashTable *table); -extern "C" void * _Nullable NSNextHashEnumeratorItem(NSHashEnumerator *enumerator); -extern "C" void NSEndHashTableEnumeration(NSHashEnumerator *enumerator); -extern "C" NSUInteger NSCountHashTable(NSHashTable *table); -extern "C" NSString *NSStringFromHashTable(NSHashTable *table); -extern "C" NSArray *NSAllHashTableObjects(NSHashTable *table); - - - - -typedef struct { - NSUInteger (* _Nullable hash)(NSHashTable *table, const void *); - BOOL (* _Nullable isEqual)(NSHashTable *table, const void *, const void *); - void (* _Nullable retain)(NSHashTable *table, const void *); - void (* _Nullable release)(NSHashTable *table, void *); - NSString * _Nullable (* _Nullable describe)(NSHashTable *table, const void *); -} NSHashTableCallBacks; - -extern "C" NSHashTable *NSCreateHashTableWithZone(NSHashTableCallBacks callBacks, NSUInteger capacity, NSZone * _Nullable zone); -extern "C" NSHashTable *NSCreateHashTable(NSHashTableCallBacks callBacks, NSUInteger capacity); - - -extern "C" const NSHashTableCallBacks NSIntegerHashCallBacks __attribute__((availability(macosx,introduced=10_5))); -extern "C" const NSHashTableCallBacks NSNonOwnedPointerHashCallBacks; -extern "C" const NSHashTableCallBacks NSNonRetainedObjectHashCallBacks; -extern "C" const NSHashTableCallBacks NSObjectHashCallBacks; -extern "C" const NSHashTableCallBacks NSOwnedObjectIdentityHashCallBacks; -extern "C" const NSHashTableCallBacks NSOwnedPointerHashCallBacks; -extern "C" const NSHashTableCallBacks NSPointerToStructHashCallBacks; -extern "C" const NSHashTableCallBacks NSIntHashCallBacks __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSDate; -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -// @class NSNumber; -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSURL; -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - - - - - - - - -extern "C" NSString * const NSHTTPCookieName; - - - - - -extern "C" NSString * const NSHTTPCookieValue; - - - - - -extern "C" NSString * const NSHTTPCookieOriginURL; - - - - - -extern "C" NSString * const NSHTTPCookieVersion; - - - - - -extern "C" NSString * const NSHTTPCookieDomain; - - - - - -extern "C" NSString * const NSHTTPCookiePath; - - - - - -extern "C" NSString * const NSHTTPCookieSecure; - - - - - -extern "C" NSString * const NSHTTPCookieExpires; - - - - - -extern "C" NSString * const NSHTTPCookieComment; - - - - - -extern "C" NSString * const NSHTTPCookieCommentURL; - - - - - -extern "C" NSString * const NSHTTPCookieDiscard; - - - - - -extern "C" NSString * const NSHTTPCookieMaximumAge; - - - - - -extern "C" NSString * const NSHTTPCookiePort; - - -// @class NSHTTPCookieInternal; -#ifndef _REWRITER_typedef_NSHTTPCookieInternal -#define _REWRITER_typedef_NSHTTPCookieInternal -typedef struct objc_object NSHTTPCookieInternal; -typedef struct {} _objc_exc_NSHTTPCookieInternal; -#endif - - -#ifndef _REWRITER_typedef_NSHTTPCookie -#define _REWRITER_typedef_NSHTTPCookie -typedef struct objc_object NSHTTPCookie; -typedef struct {} _objc_exc_NSHTTPCookie; -#endif - -struct NSHTTPCookie_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSHTTPCookieInternal *_cookiePrivate; -}; - -// - (nullable instancetype)initWithProperties:(NSDictionary<NSString *, id> *)properties; -// + (nullable NSHTTPCookie *)cookieWithProperties:(NSDictionary<NSString *, id> *)properties; -// + (NSDictionary<NSString *, NSString *> *)requestHeaderFieldsWithCookies:(NSArray<NSHTTPCookie *> *)cookies; -// + (NSArray<NSHTTPCookie *> *)cookiesWithResponseHeaderFields:(NSDictionary<NSString *, NSString *> *)headerFields forURL:(NSURL *)URL; -// @property (nullable, readonly, copy) NSDictionary<NSString *, id> *properties; -// @property (readonly) NSUInteger version; - - - - - - -// @property (readonly, copy) NSString *name; - - - - - - -// @property (readonly, copy) NSString *value; -// @property (nullable, readonly, copy) NSDate *expiresDate; -// @property (readonly, getter=isSessionOnly) BOOL sessionOnly; -// @property (readonly, copy) NSString *domain; -// @property (readonly, copy) NSString *path; -// @property (readonly, getter=isSecure) BOOL secure; -// @property (readonly, getter=isHTTPOnly) BOOL HTTPOnly; -// @property (nullable, readonly, copy) NSString *comment; -// @property (nullable, readonly, copy) NSURL *commentURL; -// @property (nullable, readonly, copy) NSArray<NSNumber *> *portList; - -/* @end */ - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSHTTPCookie; -#ifndef _REWRITER_typedef_NSHTTPCookie -#define _REWRITER_typedef_NSHTTPCookie -typedef struct objc_object NSHTTPCookie; -typedef struct {} _objc_exc_NSHTTPCookie; -#endif - -// @class NSURL; -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -// @class NSDate; -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -// @class NSURLSessionTask; -#ifndef _REWRITER_typedef_NSURLSessionTask -#define _REWRITER_typedef_NSURLSessionTask -typedef struct objc_object NSURLSessionTask; -typedef struct {} _objc_exc_NSURLSessionTask; -#endif - -// @class NSSortDescriptor; -#ifndef _REWRITER_typedef_NSSortDescriptor -#define _REWRITER_typedef_NSSortDescriptor -typedef struct objc_object NSSortDescriptor; -typedef struct {} _objc_exc_NSSortDescriptor; -#endif - -typedef NSUInteger NSHTTPCookieAcceptPolicy; enum { - NSHTTPCookieAcceptPolicyAlways, - NSHTTPCookieAcceptPolicyNever, - NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain -}; - - -// @class NSHTTPCookieStorageInternal; -#ifndef _REWRITER_typedef_NSHTTPCookieStorageInternal -#define _REWRITER_typedef_NSHTTPCookieStorageInternal -typedef struct objc_object NSHTTPCookieStorageInternal; -typedef struct {} _objc_exc_NSHTTPCookieStorageInternal; -#endif - - -#ifndef _REWRITER_typedef_NSHTTPCookieStorage -#define _REWRITER_typedef_NSHTTPCookieStorage -typedef struct objc_object NSHTTPCookieStorage; -typedef struct {} _objc_exc_NSHTTPCookieStorage; -#endif - -struct NSHTTPCookieStorage_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSHTTPCookieStorageInternal *_internal; -}; - -// + (NSHTTPCookieStorage *)sharedHTTPCookieStorage; -// + (NSHTTPCookieStorage *)sharedCookieStorageForGroupContainerIdentifier:(NSString *)identifier __attribute__((availability(macosx,introduced=10_11))); - - - - - - -// @property (nullable , readonly, copy) NSArray<NSHTTPCookie *> *cookies; - - - - - - - -// - (void)setCookie:(NSHTTPCookie *)cookie; - - - - - -// - (void)deleteCookie:(NSHTTPCookie *)cookie; - - - - - -// - (void)removeCookiesSinceDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_10))); -// - (nullable NSArray<NSHTTPCookie *> *)cookiesForURL:(NSURL *)URL; -// - (void)setCookies:(NSArray<NSHTTPCookie *> *)cookies forURL:(nullable NSURL *)URL mainDocumentURL:(nullable NSURL *)mainDocumentURL; - - - - - - -// @property NSHTTPCookieAcceptPolicy cookieAcceptPolicy; - - - - - - - -// - (NSArray<NSHTTPCookie *> *)sortedCookiesUsingDescriptors:(NSArray<NSSortDescriptor *> *) sortOrder __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - -// @interface NSHTTPCookieStorage (NSURLSessionTaskAdditions) -// - (void)storeCookies:(NSArray<NSHTTPCookie *> *)cookies forTask:(NSURLSessionTask *)task __attribute__((availability(macosx,introduced=10_10))); -// - (void)getCookiesForTask:(NSURLSessionTask *)task completionHandler:(void (^) (NSArray<NSHTTPCookie *> * _Nullable cookies))completionHandler __attribute__((availability(macosx,introduced=10_10))); -/* @end */ - - - - - - - - -extern "C" NSString * const NSHTTPCookieManagerAcceptPolicyChangedNotification; - - - - - -extern "C" NSString * const NSHTTPCookieManagerCookiesChangedNotification; - -#ifndef _REWRITER_typedef_NSIndexPath -#define _REWRITER_typedef_NSIndexPath -typedef struct objc_object NSIndexPath; -typedef struct {} _objc_exc_NSIndexPath; -#endif - -struct NSIndexPath_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSUInteger *_indexes; - NSUInteger _length; - void *_reserved; -}; - - -// + (instancetype)indexPathWithIndex:(NSUInteger)index; -// + (instancetype)indexPathWithIndexes:(const NSUInteger [])indexes length:(NSUInteger)length; - -// - (instancetype)initWithIndexes:(const NSUInteger [])indexes length:(NSUInteger)length __attribute__((objc_designated_initializer)); - -// - (instancetype)initWithIndex:(NSUInteger)index; - - -// - (NSIndexPath *)indexPathByAddingIndex:(NSUInteger)index; -// - (NSIndexPath *)indexPathByRemovingLastIndex; - -// - (NSUInteger)indexAtPosition:(NSUInteger)position; -// @property (readonly) NSUInteger length; -// - (void)getIndexes:(NSUInteger *)indexes range:(NSRange)positionRange __attribute__((availability(macosx,introduced=10_9))); - - -// - (NSComparisonResult)compare:(NSIndexPath *)otherObject; - -/* @end */ - - -// @interface NSIndexPath (NSDeprecated) - -// - (void)getIndexes:(NSUInteger *)indexes; -/* @end */ - - -#ifndef _REWRITER_typedef_NSIndexSet -#define _REWRITER_typedef_NSIndexSet -typedef struct objc_object NSIndexSet; -typedef struct {} _objc_exc_NSIndexSet; -#endif - -struct NSIndexSet_IMPL { - struct NSObject_IMPL NSObject_IVARS; - - struct { - NSUInteger _isEmpty : 1; - NSUInteger _hasSingleRange : 1; - NSUInteger _cacheValid : 1; - NSUInteger _reservedArrayBinderController : 29; - } _indexSetFlags; - - union { - - struct { - NSRange _range; - } _singleRange; - - struct { - void *_data; - void *_reserved; - } _multipleRanges; - } _internal; -}; - - -// + (instancetype)indexSet; -// + (instancetype)indexSetWithIndex:(NSUInteger)value; -// + (instancetype)indexSetWithIndexesInRange:(NSRange)range; - -// - (instancetype)initWithIndexesInRange:(NSRange)range __attribute__((objc_designated_initializer)); -// - (instancetype)initWithIndexSet:(NSIndexSet *)indexSet __attribute__((objc_designated_initializer)); - -// - (instancetype)initWithIndex:(NSUInteger)value; - -// - (BOOL)isEqualToIndexSet:(NSIndexSet *)indexSet; - -// @property (readonly) NSUInteger count; - - - -// @property (readonly) NSUInteger firstIndex; -// @property (readonly) NSUInteger lastIndex; -// - (NSUInteger)indexGreaterThanIndex:(NSUInteger)value; -// - (NSUInteger)indexLessThanIndex:(NSUInteger)value; -// - (NSUInteger)indexGreaterThanOrEqualToIndex:(NSUInteger)value; -// - (NSUInteger)indexLessThanOrEqualToIndex:(NSUInteger)value; - - - -// - (NSUInteger)getIndexes:(NSUInteger *)indexBuffer maxCount:(NSUInteger)bufferSize inIndexRange:(nullable NSRangePointer)range; - -// - (NSUInteger)countOfIndexesInRange:(NSRange)range __attribute__((availability(macosx,introduced=10_5))); - -// - (BOOL)containsIndex:(NSUInteger)value; -// - (BOOL)containsIndexesInRange:(NSRange)range; -// - (BOOL)containsIndexes:(NSIndexSet *)indexSet; - -// - (BOOL)intersectsIndexesInRange:(NSRange)range; - -// - (void)enumerateIndexesUsingBlock:(void (^)(NSUInteger idx, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); -// - (void)enumerateIndexesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(NSUInteger idx, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); -// - (void)enumerateIndexesInRange:(NSRange)range options:(NSEnumerationOptions)opts usingBlock:(void (^)(NSUInteger idx, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); - -// - (NSUInteger)indexPassingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSUInteger)indexWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSUInteger)indexInRange:(NSRange)range options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); - -// - (NSIndexSet *)indexesPassingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSIndexSet *)indexesWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); -// - (NSIndexSet *)indexesInRange:(NSRange)range options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate __attribute__((availability(macosx,introduced=10_6))); - - - - - - -// - (void)enumerateRangesUsingBlock:(void (^)(NSRange range, BOOL *stop))block __attribute__((availability(macosx,introduced=10_7))); -// - (void)enumerateRangesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(NSRange range, BOOL *stop))block __attribute__((availability(macosx,introduced=10_7))); -// - (void)enumerateRangesInRange:(NSRange)range options:(NSEnumerationOptions)opts usingBlock:(void (^)(NSRange range, BOOL *stop))block __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - - -#ifndef _REWRITER_typedef_NSMutableIndexSet -#define _REWRITER_typedef_NSMutableIndexSet -typedef struct objc_object NSMutableIndexSet; -typedef struct {} _objc_exc_NSMutableIndexSet; -#endif - -struct NSMutableIndexSet_IMPL { - struct NSIndexSet_IMPL NSIndexSet_IVARS; - void *_reserved; -}; - - -// - (void)addIndexes:(NSIndexSet *)indexSet; -// - (void)removeIndexes:(NSIndexSet *)indexSet; -// - (void)removeAllIndexes; -// - (void)addIndex:(NSUInteger)value; -// - (void)removeIndex:(NSUInteger)value; -// - (void)addIndexesInRange:(NSRange)range; -// - (void)removeIndexesInRange:(NSRange)range; - - - -// - (void)shiftIndexesStartingAtIndex:(NSUInteger)index by:(NSInteger)delta; - -/* @end */ - - - - - - - - -// @class NSMethodSignature; -#ifndef _REWRITER_typedef_NSMethodSignature -#define _REWRITER_typedef_NSMethodSignature -typedef struct objc_object NSMethodSignature; -typedef struct {} _objc_exc_NSMethodSignature; -#endif - - - - -__attribute__((availability(swift, unavailable, message="NSInvocation and related APIs not available"))) - -#ifndef _REWRITER_typedef_NSInvocation -#define _REWRITER_typedef_NSInvocation -typedef struct objc_object NSInvocation; -typedef struct {} _objc_exc_NSInvocation; -#endif - -struct NSInvocation_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_frame; - void *_retdata; - id _signature; - id _container; - uint8_t _retainedArgs; - uint8_t _reserved[15]; -}; - - -// + (NSInvocation *)invocationWithMethodSignature:(NSMethodSignature *)sig; - -// @property (readonly, retain) NSMethodSignature *methodSignature; - -// - (void)retainArguments; -// @property (readonly) BOOL argumentsRetained; - -// @property (nullable, assign) id target; -// @property SEL selector; - -// - (void)getReturnValue:(void *)retLoc; -// - (void)setReturnValue:(void *)retLoc; - -// - (void)getArgument:(void *)argumentLocation atIndex:(NSInteger)idx; -// - (void)setArgument:(void *)argumentLocation atIndex:(NSInteger)idx; - -// - (void)invoke; -// - (void)invokeWithTarget:(id)target; - -/* @end */ - - - - - - - - -// @class NSError; -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSOutputStream -#define _REWRITER_typedef_NSOutputStream -typedef struct objc_object NSOutputStream; -typedef struct {} _objc_exc_NSOutputStream; -#endif - -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - - - - -typedef NSUInteger NSJSONReadingOptions; enum { - NSJSONReadingMutableContainers = (1UL << 0), - NSJSONReadingMutableLeaves = (1UL << 1), - NSJSONReadingAllowFragments = (1UL << 2) -} __attribute__((availability(macosx,introduced=10_7))); - -typedef NSUInteger NSJSONWritingOptions; enum { - NSJSONWritingPrettyPrinted = (1UL << 0) -} __attribute__((availability(macosx,introduced=10_7))); -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSJSONSerialization -#define _REWRITER_typedef_NSJSONSerialization -typedef struct objc_object NSJSONSerialization; -typedef struct {} _objc_exc_NSJSONSerialization; -#endif - -struct NSJSONSerialization_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *reserved[6]; -}; - -// + (BOOL)isValidJSONObject:(id)obj; - - - -// + (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error; - - - - -// + (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error; - - - -// + (NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream *)stream options:(NSJSONWritingOptions)opt error:(NSError **)error; - - - -// + (nullable id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error; - -/* @end */ - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSIndexSet -#define _REWRITER_typedef_NSIndexSet -typedef struct objc_object NSIndexSet; -typedef struct {} _objc_exc_NSIndexSet; -#endif - -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSOrderedSet -#define _REWRITER_typedef_NSOrderedSet -typedef struct objc_object NSOrderedSet; -typedef struct {} _objc_exc_NSOrderedSet; -#endif - -struct NSOrderedSet_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly) NSUInteger count; -// - (ObjectType)objectAtIndex:(NSUInteger)idx; -// - (NSUInteger)indexOfObject:(ObjectType)object; -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (instancetype)initWithObjects:(const ObjectType [])objects count:(NSUInteger)cnt __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSOrderedSet<ObjectType> (NSExtendedOrderedSet) - -// - (void)getObjects:(ObjectType __attribute__((objc_ownership(none))) [])objects range:(NSRange)range; -// - (NSArray<ObjectType> *)objectsAtIndexes:(NSIndexSet *)indexes; -// @property (nullable, nonatomic, readonly) ObjectType firstObject; -// @property (nullable, nonatomic, readonly) ObjectType lastObject; - -// - (BOOL)isEqualToOrderedSet:(NSOrderedSet<ObjectType> *)other; - -// - (BOOL)containsObject:(ObjectType)object; -// - (BOOL)intersectsOrderedSet:(NSOrderedSet<ObjectType> *)other; -// - (BOOL)intersectsSet:(NSSet<ObjectType> *)set; - -// - (BOOL)isSubsetOfOrderedSet:(NSOrderedSet<ObjectType> *)other; -// - (BOOL)isSubsetOfSet:(NSSet<ObjectType> *)set; - -// - (ObjectType)objectAtIndexedSubscript:(NSUInteger)idx __attribute__((availability(macosx,introduced=10_8))); - -// - (NSEnumerator<ObjectType> *)objectEnumerator; -// - (NSEnumerator<ObjectType> *)reverseObjectEnumerator; - -// @property (readonly, copy) NSOrderedSet<ObjectType> *reversedOrderedSet; - - - - - - - -// @property (readonly, strong) NSArray<ObjectType> *array; -// @property (readonly, strong) NSSet<ObjectType> *set; - -// - (void)enumerateObjectsUsingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block; -// - (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block; -// - (void)enumerateObjectsAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts usingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block; - -// - (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate; -// - (NSUInteger)indexOfObjectWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate; -// - (NSUInteger)indexOfObjectAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate; - -// - (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate; -// - (NSIndexSet *)indexesOfObjectsWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate; -// - (NSIndexSet *)indexesOfObjectsAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate; - -// - (NSUInteger)indexOfObject:(ObjectType)object inSortedRange:(NSRange)range options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator)cmp; - -// - (NSArray<ObjectType> *)sortedArrayUsingComparator:(NSComparator)cmptr; -// - (NSArray<ObjectType> *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr; - -// @property (readonly, copy) NSString *description; -// - (NSString *)descriptionWithLocale:(nullable id)locale; -// - (NSString *)descriptionWithLocale:(nullable id)locale indent:(NSUInteger)level; - -/* @end */ - - -// @interface NSOrderedSet<ObjectType> (NSOrderedSetCreation) - -// + (instancetype)orderedSet; -// + (instancetype)orderedSetWithObject:(ObjectType)object; -// + (instancetype)orderedSetWithObjects:(const ObjectType [])objects count:(NSUInteger)cnt; -// + (instancetype)orderedSetWithObjects:(ObjectType)firstObj, ... __attribute__((sentinel(0,1))); -// + (instancetype)orderedSetWithOrderedSet:(NSOrderedSet<ObjectType> *)set; -// + (instancetype)orderedSetWithOrderedSet:(NSOrderedSet<ObjectType> *)set range:(NSRange)range copyItems:(BOOL)flag; -// + (instancetype)orderedSetWithArray:(NSArray<ObjectType> *)array; -// + (instancetype)orderedSetWithArray:(NSArray<ObjectType> *)array range:(NSRange)range copyItems:(BOOL)flag; -// + (instancetype)orderedSetWithSet:(NSSet<ObjectType> *)set; -// + (instancetype)orderedSetWithSet:(NSSet<ObjectType> *)set copyItems:(BOOL)flag; - -// - (instancetype)initWithObject:(ObjectType)object; -// - (instancetype)initWithObjects:(ObjectType)firstObj, ... __attribute__((sentinel(0,1))); -// - (instancetype)initWithOrderedSet:(NSOrderedSet<ObjectType> *)set; -// - (instancetype)initWithOrderedSet:(NSOrderedSet<ObjectType> *)set copyItems:(BOOL)flag; -// - (instancetype)initWithOrderedSet:(NSOrderedSet<ObjectType> *)set range:(NSRange)range copyItems:(BOOL)flag; -// - (instancetype)initWithArray:(NSArray<ObjectType> *)array; -// - (instancetype)initWithArray:(NSArray<ObjectType> *)set copyItems:(BOOL)flag; -// - (instancetype)initWithArray:(NSArray<ObjectType> *)set range:(NSRange)range copyItems:(BOOL)flag; -// - (instancetype)initWithSet:(NSSet<ObjectType> *)set; -// - (instancetype)initWithSet:(NSSet<ObjectType> *)set copyItems:(BOOL)flag; - -/* @end */ - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSMutableOrderedSet -#define _REWRITER_typedef_NSMutableOrderedSet -typedef struct objc_object NSMutableOrderedSet; -typedef struct {} _objc_exc_NSMutableOrderedSet; -#endif - -struct NSMutableOrderedSet_IMPL { - struct NSOrderedSet_IMPL NSOrderedSet_IVARS; -}; - - -// - (void)insertObject:(ObjectType)object atIndex:(NSUInteger)idx; -// - (void)removeObjectAtIndex:(NSUInteger)idx; -// - (void)replaceObjectAtIndex:(NSUInteger)idx withObject:(ObjectType)object; -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (instancetype)initWithCapacity:(NSUInteger)numItems __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSMutableOrderedSet<ObjectType> (NSExtendedMutableOrderedSet) - -// - (void)addObject:(ObjectType)object; -// - (void)addObjects:(const ObjectType [])objects count:(NSUInteger)count; -// - (void)addObjectsFromArray:(NSArray<ObjectType> *)array; - -// - (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2; -// - (void)moveObjectsAtIndexes:(NSIndexSet *)indexes toIndex:(NSUInteger)idx; - -// - (void)insertObjects:(NSArray<ObjectType> *)objects atIndexes:(NSIndexSet *)indexes; - -// - (void)setObject:(ObjectType)obj atIndex:(NSUInteger)idx; -// - (void)setObject:(ObjectType)obj atIndexedSubscript:(NSUInteger)idx __attribute__((availability(macosx,introduced=10_8))); - -// - (void)replaceObjectsInRange:(NSRange)range withObjects:(const ObjectType [])objects count:(NSUInteger)count; -// - (void)replaceObjectsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray<ObjectType> *)objects; - -// - (void)removeObjectsInRange:(NSRange)range; -// - (void)removeObjectsAtIndexes:(NSIndexSet *)indexes; -// - (void)removeAllObjects; - -// - (void)removeObject:(ObjectType)object; -// - (void)removeObjectsInArray:(NSArray<ObjectType> *)array; - -// - (void)intersectOrderedSet:(NSOrderedSet<ObjectType> *)other; -// - (void)minusOrderedSet:(NSOrderedSet<ObjectType> *)other; -// - (void)unionOrderedSet:(NSOrderedSet<ObjectType> *)other; - -// - (void)intersectSet:(NSSet<ObjectType> *)other; -// - (void)minusSet:(NSSet<ObjectType> *)other; -// - (void)unionSet:(NSSet<ObjectType> *)other; - - -// - (void)sortUsingComparator:(NSComparator)cmptr; -// - (void)sortWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr; -// - (void)sortRange:(NSRange)range options:(NSSortOptions)opts usingComparator:(NSComparator)cmptr; - - -/* @end */ - - -// @interface NSMutableOrderedSet<ObjectType> (NSMutableOrderedSetCreation) - -// + (instancetype)orderedSetWithCapacity:(NSUInteger)numItems; - -/* @end */ - - - -// @class NSError; -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -extern "C" NSString *const NSUndefinedKeyException; - - - -extern "C" NSString *const NSAverageKeyValueOperator; -extern "C" NSString *const NSCountKeyValueOperator; -extern "C" NSString *const NSDistinctUnionOfArraysKeyValueOperator; -extern "C" NSString *const NSDistinctUnionOfObjectsKeyValueOperator; -extern "C" NSString *const NSDistinctUnionOfSetsKeyValueOperator; -extern "C" NSString *const NSMaximumKeyValueOperator; -extern "C" NSString *const NSMinimumKeyValueOperator; -extern "C" NSString *const NSSumKeyValueOperator; -extern "C" NSString *const NSUnionOfArraysKeyValueOperator; -extern "C" NSString *const NSUnionOfObjectsKeyValueOperator; -extern "C" NSString *const NSUnionOfSetsKeyValueOperator; - -// @interface NSObject(NSKeyValueCoding) - - - -// + (BOOL)accessInstanceVariablesDirectly; -// - (nullable id)valueForKey:(NSString *)key; -// - (void)setValue:(nullable id)value forKey:(NSString *)key; - - - - - -// - (BOOL)validateValue:(inout id _Nullable * _Nonnull)ioValue forKey:(NSString *)inKey error:(out NSError **)outError; -// - (NSMutableArray *)mutableArrayValueForKey:(NSString *)key; -// - (NSMutableOrderedSet *)mutableOrderedSetValueForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_7))); -// - (NSMutableSet *)mutableSetValueForKey:(NSString *)key; - - - -// - (nullable id)valueForKeyPath:(NSString *)keyPath; -// - (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath; -// - (BOOL)validateValue:(inout id _Nullable * _Nonnull)ioValue forKeyPath:(NSString *)inKeyPath error:(out NSError **)outError; -// - (NSMutableArray *)mutableArrayValueForKeyPath:(NSString *)keyPath; -// - (NSMutableOrderedSet *)mutableOrderedSetValueForKeyPath:(NSString *)keyPath __attribute__((availability(macosx,introduced=10_7))); -// - (NSMutableSet *)mutableSetValueForKeyPath:(NSString *)keyPath; - - - -// - (nullable id)valueForUndefinedKey:(NSString *)key; - - - -// - (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key; - - - -// - (void)setNilValueForKey:(NSString *)key; - - - -// - (NSDictionary<NSString *, id> *)dictionaryWithValuesForKeys:(NSArray<NSString *> *)keys; - - - -// - (void)setValuesForKeysWithDictionary:(NSDictionary<NSString *, id> *)keyedValues; - -/* @end */ - - -// @interface NSArray<ObjectType>(NSKeyValueCoding) - - - -// - (id)valueForKey:(NSString *)key; - - - -// - (void)setValue:(nullable id)value forKey:(NSString *)key; - -/* @end */ - - -// @interface NSDictionary<KeyType, ObjectType>(NSKeyValueCoding) - - - -// - (nullable ObjectType)valueForKey:(NSString *)key; - -/* @end */ - - -// @interface NSMutableDictionary<KeyType, ObjectType>(NSKeyValueCoding) - - - -// - (void)setValue:(nullable ObjectType)value forKey:(NSString *)key; - -/* @end */ - - -// @interface NSOrderedSet<ObjectType>(NSKeyValueCoding) - - - -// - (id)valueForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_7))); - - - -// - (void)setValue:(nullable id)value forKey:(NSString *)key __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - -// @interface NSSet<ObjectType>(NSKeyValueCoding) - - - -// - (id)valueForKey:(NSString *)key; - - - -// - (void)setValue:(nullable id)value forKey:(NSString *)key; - -/* @end */ - - - - -// @interface NSObject(NSDeprecatedKeyValueCoding) - - - -// + (BOOL)useStoredAccessor __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (nullable id)storedValueForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)takeStoredValue:(nullable id)value forKey:(NSString *)key __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - - - -// - (void)takeValue:(nullable id)value forKey:(NSString *)key __attribute__((availability(macosx,introduced=10_0,deprecated=10_3,message="" ))); -// - (void)takeValue:(nullable id)value forKeyPath:(NSString *)keyPath __attribute__((availability(macosx,introduced=10_0,deprecated=10_3,message="" ))); -// - (nullable id)handleQueryWithUnboundKey:(NSString *)key __attribute__((availability(macosx,introduced=10_0,deprecated=10_3,message="" ))); -// - (void)handleTakeValue:(nullable id)value forUnboundKey:(NSString *)key __attribute__((availability(macosx,introduced=10_0,deprecated=10_3,message="" ))); -// - (void)unableToSetNilForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_0,deprecated=10_3,message="" ))); -// - (NSDictionary *)valuesForKeys:(NSArray *)keys __attribute__((availability(macosx,introduced=10_0,deprecated=10_3,message="" ))); -// - (void)takeValuesFromDictionary:(NSDictionary *)properties __attribute__((availability(macosx,introduced=10_0,deprecated=10_3,message="" ))); - -/* @end */ - -// @class NSIndexSet; -#ifndef _REWRITER_typedef_NSIndexSet -#define _REWRITER_typedef_NSIndexSet -typedef struct objc_object NSIndexSet; -typedef struct {} _objc_exc_NSIndexSet; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - - -typedef NSUInteger NSKeyValueObservingOptions; enum { - - - - NSKeyValueObservingOptionNew = 0x01, - NSKeyValueObservingOptionOld = 0x02, - - - - NSKeyValueObservingOptionInitial __attribute__((availability(macosx,introduced=10_5))) = 0x04, - - - - - - NSKeyValueObservingOptionPrior __attribute__((availability(macosx,introduced=10_5))) = 0x08 - -}; - - - -typedef NSUInteger NSKeyValueChange; enum { - NSKeyValueChangeSetting = 1, - NSKeyValueChangeInsertion = 2, - NSKeyValueChangeRemoval = 3, - NSKeyValueChangeReplacement = 4, -}; - - - -typedef NSUInteger NSKeyValueSetMutationKind; enum { - NSKeyValueUnionSetMutation = 1, - NSKeyValueMinusSetMutation = 2, - NSKeyValueIntersectSetMutation = 3, - NSKeyValueSetSetMutation = 4 -}; - - - -extern "C" NSString *const NSKeyValueChangeKindKey; -extern "C" NSString *const NSKeyValueChangeNewKey; -extern "C" NSString *const NSKeyValueChangeOldKey; -extern "C" NSString *const NSKeyValueChangeIndexesKey; -extern "C" NSString *const NSKeyValueChangeNotificationIsPriorKey __attribute__((availability(macosx,introduced=10_5))); - -// @interface NSObject(NSKeyValueObserving) -// - (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSString*, id> *)change context:(nullable void *)context; - -/* @end */ - - -// @interface NSObject(NSKeyValueObserverRegistration) - - - -// - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context; -// - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable void *)context __attribute__((availability(macosx,introduced=10_7))); -// - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath; - -/* @end */ - - -// @interface NSArray<ObjectType>(NSKeyValueObserverRegistration) - - - -// - (void)addObserver:(NSObject *)observer toObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context; -// - (void)removeObserver:(NSObject *)observer fromObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath context:(nullable void *)context __attribute__((availability(macosx,introduced=10_7))); -// - (void)removeObserver:(NSObject *)observer fromObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath; - - - -// - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context; -// - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable void *)context __attribute__((availability(macosx,introduced=10_7))); -// - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath; - -/* @end */ - - -// @interface NSOrderedSet<ObjectType>(NSKeyValueObserverRegistration) - - - -// - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context; -// - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable void *)context __attribute__((availability(macosx,introduced=10_7))); -// - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath; - -/* @end */ - - -// @interface NSSet<ObjectType>(NSKeyValueObserverRegistration) - - - -// - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context; -// - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable void *)context __attribute__((availability(macosx,introduced=10_7))); -// - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath; - -/* @end */ - - -// @interface NSObject(NSKeyValueObserverNotification) - - - - - - - -// - (void)willChangeValueForKey:(NSString *)key; -// - (void)didChangeValueForKey:(NSString *)key; - - - - - - - -// - (void)willChange:(NSKeyValueChange)changeKind valuesAtIndexes:(NSIndexSet *)indexes forKey:(NSString *)key; -// - (void)didChange:(NSKeyValueChange)changeKind valuesAtIndexes:(NSIndexSet *)indexes forKey:(NSString *)key; -// - (void)willChangeValueForKey:(NSString *)key withSetMutation:(NSKeyValueSetMutationKind)mutationKind usingObjects:(NSSet *)objects; -// - (void)didChangeValueForKey:(NSString *)key withSetMutation:(NSKeyValueSetMutationKind)mutationKind usingObjects:(NSSet *)objects; - -/* @end */ - - -// @interface NSObject(NSKeyValueObservingCustomization) -// + (NSSet<NSString *> *)keyPathsForValuesAffectingValueForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_5))); - - - -// + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key; - - - -// @property (nullable) void *observationInfo __attribute__((objc_returns_inner_pointer)); - -/* @end */ - - - - -// @interface NSObject(NSDeprecatedKeyValueObservingCustomization) - - - -// + (void)setKeys:(NSArray *)keys triggerChangeNotificationsForDependentKey:(NSString *)dependentKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - -/* @end */ - - - - - - - - - - - - - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -#ifndef _REWRITER_typedef_NSOutputStream -#define _REWRITER_typedef_NSOutputStream -typedef struct objc_object NSOutputStream; -typedef struct {} _objc_exc_NSOutputStream; -#endif - - - - -typedef NSUInteger NSPropertyListMutabilityOptions; enum { - NSPropertyListImmutable = kCFPropertyListImmutable, - NSPropertyListMutableContainers = kCFPropertyListMutableContainers, - NSPropertyListMutableContainersAndLeaves = kCFPropertyListMutableContainersAndLeaves -}; - -typedef NSUInteger NSPropertyListFormat; enum { - NSPropertyListOpenStepFormat = kCFPropertyListOpenStepFormat, - NSPropertyListXMLFormat_v1_0 = kCFPropertyListXMLFormat_v1_0, - NSPropertyListBinaryFormat_v1_0 = kCFPropertyListBinaryFormat_v1_0 -}; - -typedef NSPropertyListMutabilityOptions NSPropertyListReadOptions; -typedef NSUInteger NSPropertyListWriteOptions; - - -#ifndef _REWRITER_typedef_NSPropertyListSerialization -#define _REWRITER_typedef_NSPropertyListSerialization -typedef struct objc_object NSPropertyListSerialization; -typedef struct {} _objc_exc_NSPropertyListSerialization; -#endif - -struct NSPropertyListSerialization_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *reserved[6]; -}; - - - - -// + (BOOL)propertyList:(id)plist isValidForFormat:(NSPropertyListFormat)format; - - - -// + (nullable NSData *)dataWithPropertyList:(id)plist format:(NSPropertyListFormat)format options:(NSPropertyListWriteOptions)opt error:(out NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// + (NSInteger)writePropertyList:(id)plist toStream:(NSOutputStream *)stream format:(NSPropertyListFormat)format options:(NSPropertyListWriteOptions)opt error:(out NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// + (nullable id)propertyListWithData:(NSData *)data options:(NSPropertyListReadOptions)opt format:(nullable NSPropertyListFormat *)format error:(out NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// + (nullable id)propertyListWithStream:(NSInputStream *)stream options:(NSPropertyListReadOptions)opt format:(nullable NSPropertyListFormat *)format error:(out NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - - -// + (nullable NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format errorDescription:(out __attribute__((objc_ownership(strong))) NSString * _Nullable * _Nullable)errorString __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use dataWithPropertyList:format:options:error: instead."))); - - - -// + (nullable id)propertyListFromData:(NSData *)data mutabilityOption:(NSPropertyListMutabilityOptions)opt format:(nullable NSPropertyListFormat *)format errorDescription:(out __attribute__((objc_ownership(strong))) NSString * _Nullable * _Nullable)errorString __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use propertyListWithData:options:format:error: instead."))); - -/* @end */ - - - - - - - - - - -typedef double CGFloat; -struct CGPoint { - CGFloat x; - CGFloat y; -}; -typedef struct CGPoint CGPoint; - - - -struct CGSize { - CGFloat width; - CGFloat height; -}; -typedef struct CGSize CGSize; - - - - - -struct CGVector { - CGFloat dx; - CGFloat dy; -}; -typedef struct CGVector CGVector; - - - -struct CGRect { - CGPoint origin; - CGSize size; -}; -typedef struct CGRect CGRect; - - - -typedef uint32_t CGRectEdge; enum { - CGRectMinXEdge, CGRectMinYEdge, CGRectMaxXEdge, CGRectMaxYEdge -}; - - - -extern "C" const CGPoint CGPointZero - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" const CGSize CGSizeZero - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" const CGRect CGRectZero - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" const CGRect CGRectNull - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" const CGRect CGRectInfinite - __attribute__((availability(macosx,introduced=10.4))); - - - -static inline CGPoint CGPointMake(CGFloat x, CGFloat y); - - - -static inline CGSize CGSizeMake(CGFloat width, CGFloat height); - - - -static inline CGVector CGVectorMake(CGFloat dx, CGFloat dy); - - - -static inline CGRect CGRectMake(CGFloat x, CGFloat y, CGFloat width, - CGFloat height); - - - -extern "C" CGFloat CGRectGetMinX(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGFloat CGRectGetMidX(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGFloat CGRectGetMaxX(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGFloat CGRectGetMinY(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGFloat CGRectGetMidY(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGFloat CGRectGetMaxY(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGFloat CGRectGetWidth(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGFloat CGRectGetHeight(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGPointEqualToPoint(CGPoint point1, CGPoint point2) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGSizeEqualToSize(CGSize size1, CGSize size2) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGRectEqualToRect(CGRect rect1, CGRect rect2) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGRect CGRectStandardize(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" bool CGRectIsEmpty(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGRectIsNull(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGRectIsInfinite(CGRect rect) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGRect CGRectInset(CGRect rect, CGFloat dx, CGFloat dy) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGRect CGRectIntegral(CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGRect CGRectUnion(CGRect r1, CGRect r2) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGRect CGRectIntersection(CGRect r1, CGRect r2) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGRect CGRectOffset(CGRect rect, CGFloat dx, CGFloat dy) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - - -extern "C" void CGRectDivide(CGRect rect, CGRect * slice, - CGRect * remainder, CGFloat amount, CGRectEdge edge) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGRectContainsPoint(CGRect rect, CGPoint point) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" bool CGRectContainsRect(CGRect rect1, CGRect rect2) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" bool CGRectIntersectsRect(CGRect rect1, CGRect rect2) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CFDictionaryRef CGPointCreateDictionaryRepresentation( - CGPoint point) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" bool CGPointMakeWithDictionaryRepresentation( - CFDictionaryRef _Nullable dict, CGPoint * _Nullable point) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" CFDictionaryRef CGSizeCreateDictionaryRepresentation(CGSize size) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" bool CGSizeMakeWithDictionaryRepresentation( - CFDictionaryRef _Nullable dict, CGSize * _Nullable size) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" CFDictionaryRef CGRectCreateDictionaryRepresentation(CGRect) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" bool CGRectMakeWithDictionaryRepresentation( - CFDictionaryRef _Nullable dict, CGRect * _Nullable rect) - __attribute__((availability(macosx,introduced=10.5))); - - - -static inline CGPoint -CGPointMake(CGFloat x, CGFloat y) -{ - CGPoint p; p.x = x; p.y = y; return p; -} - -static inline CGSize -CGSizeMake(CGFloat width, CGFloat height) -{ - CGSize size; size.width = width; size.height = height; return size; -} - -static inline CGVector -CGVectorMake(CGFloat dx, CGFloat dy) -{ - CGVector vector; vector.dx = dx; vector.dy = dy; return vector; -} - -static inline CGRect -CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height) -{ - CGRect rect; - rect.origin.x = x; rect.origin.y = y; - rect.size.width = width; rect.size.height = height; - return rect; -} - -static inline bool -__CGPointEqualToPoint(CGPoint point1, CGPoint point2) -{ - return point1.x == point2.x && point1.y == point2.y; -} - - -static inline bool -__CGSizeEqualToSize(CGSize size1, CGSize size2) -{ - return size1.width == size2.width && size1.height == size2.height; -} - - - - - - -typedef CGPoint NSPoint; - -typedef NSPoint *NSPointPointer; -typedef NSPoint *NSPointArray; - -typedef CGSize NSSize; - -typedef NSSize *NSSizePointer; -typedef NSSize *NSSizeArray; - -typedef CGRect NSRect; - -typedef NSRect *NSRectPointer; -typedef NSRect *NSRectArray; - -typedef NSUInteger NSRectEdge; enum { - NSRectEdgeMinX = CGRectMinXEdge, - NSRectEdgeMinY = CGRectMinYEdge, - NSRectEdgeMaxX = CGRectMaxXEdge, - NSRectEdgeMaxY = CGRectMaxYEdge, - - NSMinXEdge __attribute__((availability(swift, unavailable, message="Use NSRectEdge.MinX instead"))) = NSRectEdgeMinX, - NSMinYEdge __attribute__((availability(swift, unavailable, message="Use NSRectEdge.MinY instead"))) = NSRectEdgeMinY, - NSMaxXEdge __attribute__((availability(swift, unavailable, message="Use NSRectEdge.MaxX instead"))) = NSRectEdgeMaxX, - NSMaxYEdge __attribute__((availability(swift, unavailable, message="Use NSRectEdge.MaxX instead"))) = NSRectEdgeMaxY, -}; -typedef struct NSEdgeInsets { - CGFloat top; - CGFloat left; - CGFloat bottom; - CGFloat right; -} NSEdgeInsets; - -typedef unsigned long long NSAlignmentOptions; enum { - NSAlignMinXInward = 1ULL << 0, - NSAlignMinYInward = 1ULL << 1, - NSAlignMaxXInward = 1ULL << 2, - NSAlignMaxYInward = 1ULL << 3, - NSAlignWidthInward = 1ULL << 4, - NSAlignHeightInward = 1ULL << 5, - - NSAlignMinXOutward = 1ULL << 8, - NSAlignMinYOutward = 1ULL << 9, - NSAlignMaxXOutward = 1ULL << 10, - NSAlignMaxYOutward = 1ULL << 11, - NSAlignWidthOutward = 1ULL << 12, - NSAlignHeightOutward = 1ULL << 13, - - NSAlignMinXNearest = 1ULL << 16, - NSAlignMinYNearest = 1ULL << 17, - NSAlignMaxXNearest = 1ULL << 18, - NSAlignMaxYNearest = 1ULL << 19, - NSAlignWidthNearest = 1ULL << 20, - NSAlignHeightNearest = 1ULL << 21, - - NSAlignRectFlipped = 1ULL << 63, - - - NSAlignAllEdgesInward = NSAlignMinXInward|NSAlignMaxXInward|NSAlignMinYInward|NSAlignMaxYInward, - NSAlignAllEdgesOutward = NSAlignMinXOutward|NSAlignMaxXOutward|NSAlignMinYOutward|NSAlignMaxYOutward, - NSAlignAllEdgesNearest = NSAlignMinXNearest|NSAlignMaxXNearest|NSAlignMinYNearest|NSAlignMaxYNearest, -}; - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - -extern "C" const NSPoint NSZeroPoint; -extern "C" const NSSize NSZeroSize; -extern "C" const NSRect NSZeroRect; -extern "C" const NSEdgeInsets NSEdgeInsetsZero __attribute__((availability(macosx,introduced=10_10))); - -static __inline__ __attribute__((always_inline)) NSPoint NSMakePoint(CGFloat x, CGFloat y) { - NSPoint p; - p.x = x; - p.y = y; - return p; -} - -static __inline__ __attribute__((always_inline)) NSSize NSMakeSize(CGFloat w, CGFloat h) { - NSSize s; - s.width = w; - s.height = h; - return s; -} - -static __inline__ __attribute__((always_inline)) NSRect NSMakeRect(CGFloat x, CGFloat y, CGFloat w, CGFloat h) { - NSRect r; - r.origin.x = x; - r.origin.y = y; - r.size.width = w; - r.size.height = h; - return r; -} - -static __inline__ __attribute__((always_inline)) CGFloat NSMaxX(NSRect aRect) { - return (aRect.origin.x + aRect.size.width); -} - -static __inline__ __attribute__((always_inline)) CGFloat NSMaxY(NSRect aRect) { - return (aRect.origin.y + aRect.size.height); -} - -static __inline__ __attribute__((always_inline)) CGFloat NSMidX(NSRect aRect) { - return (aRect.origin.x + aRect.size.width * (CGFloat)0.5); -} - -static __inline__ __attribute__((always_inline)) CGFloat NSMidY(NSRect aRect) { - return (aRect.origin.y + aRect.size.height * (CGFloat)0.5); -} - -static __inline__ __attribute__((always_inline)) CGFloat NSMinX(NSRect aRect) { - return (aRect.origin.x); -} - -static __inline__ __attribute__((always_inline)) CGFloat NSMinY(NSRect aRect) { - return (aRect.origin.y); -} - -static __inline__ __attribute__((always_inline)) CGFloat NSWidth(NSRect aRect) { - return (aRect.size.width); -} - -static __inline__ __attribute__((always_inline)) CGFloat NSHeight(NSRect aRect) { - return (aRect.size.height); -} - -static __inline__ __attribute__((always_inline)) NSRect NSRectFromCGRect(CGRect cgrect) { - union _ {NSRect ns; CGRect cg;}; - return ((union _ *)&cgrect)->ns; -} - -static __inline__ __attribute__((always_inline)) CGRect NSRectToCGRect(NSRect nsrect) { - union _ {NSRect ns; CGRect cg;}; - return ((union _ *)&nsrect)->cg; -} - -static __inline__ __attribute__((always_inline)) NSPoint NSPointFromCGPoint(CGPoint cgpoint) { - union _ {NSPoint ns; CGPoint cg;}; - return ((union _ *)&cgpoint)->ns; -} - -static __inline__ __attribute__((always_inline)) CGPoint NSPointToCGPoint(NSPoint nspoint) { - union _ {NSPoint ns; CGPoint cg;}; - return ((union _ *)&nspoint)->cg; -} - -static __inline__ __attribute__((always_inline)) NSSize NSSizeFromCGSize(CGSize cgsize) { - union _ {NSSize ns; CGSize cg;}; - return ((union _ *)&cgsize)->ns; -} - -static __inline__ __attribute__((always_inline)) CGSize NSSizeToCGSize(NSSize nssize) { - union _ {NSSize ns; CGSize cg;}; - return ((union _ *)&nssize)->cg; -} - -static __inline__ __attribute__((always_inline)) NSEdgeInsets NSEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) { - NSEdgeInsets e; - e.top = top; - e.left = left; - e.bottom = bottom; - e.right = right; - return e; -} - -extern "C" BOOL NSEqualPoints(NSPoint aPoint, NSPoint bPoint); -extern "C" BOOL NSEqualSizes(NSSize aSize, NSSize bSize); -extern "C" BOOL NSEqualRects(NSRect aRect, NSRect bRect); -extern "C" BOOL NSIsEmptyRect(NSRect aRect); -extern "C" BOOL NSEdgeInsetsEqual(NSEdgeInsets aInsets, NSEdgeInsets bInsets) __attribute__((availability(macosx,introduced=10_10))); - -extern "C" NSRect NSInsetRect(NSRect aRect, CGFloat dX, CGFloat dY); -extern "C" NSRect NSIntegralRect(NSRect aRect); -extern "C" NSRect NSIntegralRectWithOptions(NSRect aRect, NSAlignmentOptions opts) __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSRect NSUnionRect(NSRect aRect, NSRect bRect); -extern "C" NSRect NSIntersectionRect(NSRect aRect, NSRect bRect); -extern "C" NSRect NSOffsetRect(NSRect aRect, CGFloat dX, CGFloat dY); -extern "C" void NSDivideRect(NSRect inRect, NSRect *slice, NSRect *rem, CGFloat amount, NSRectEdge edge); -extern "C" BOOL NSPointInRect(NSPoint aPoint, NSRect aRect); -extern "C" BOOL NSMouseInRect(NSPoint aPoint, NSRect aRect, BOOL flipped); -extern "C" BOOL NSContainsRect(NSRect aRect, NSRect bRect); -extern "C" BOOL NSIntersectsRect(NSRect aRect, NSRect bRect); - -extern "C" NSString *NSStringFromPoint(NSPoint aPoint); -extern "C" NSString *NSStringFromSize(NSSize aSize); -extern "C" NSString *NSStringFromRect(NSRect aRect); -extern "C" NSPoint NSPointFromString(NSString *aString); -extern "C" NSSize NSSizeFromString(NSString *aString); -extern "C" NSRect NSRectFromString(NSString *aString); - -// @interface NSValue (NSValueGeometryExtensions) - -// + (NSValue *)valueWithPoint:(NSPoint)point; -// + (NSValue *)valueWithSize:(NSSize)size; -// + (NSValue *)valueWithRect:(NSRect)rect; -// + (NSValue *)valueWithEdgeInsets:(NSEdgeInsets)insets __attribute__((availability(macosx,introduced=10_10))); - -// @property (readonly) NSPoint pointValue; -// @property (readonly) NSSize sizeValue; -// @property (readonly) NSRect rectValue; -// @property (readonly) NSEdgeInsets edgeInsetsValue __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - -// @interface NSCoder (NSGeometryCoding) - -// - (void)encodePoint:(NSPoint)point; -// - (NSPoint)decodePoint; - -// - (void)encodeSize:(NSSize)size; -// - (NSSize)decodeSize; - -// - (void)encodeRect:(NSRect)rect; -// - (NSRect)decodeRect; - -/* @end */ - - -// @interface NSCoder (NSGeometryKeyedCoding) - -// - (void)encodePoint:(NSPoint)point forKey:(NSString *)key; -// - (void)encodeSize:(NSSize)size forKey:(NSString *)key; -// - (void)encodeRect:(NSRect)rect forKey:(NSString *)key; - -// - (NSPoint)decodePointForKey:(NSString *)key; -// - (NSSize)decodeSizeForKey:(NSString *)key; -// - (NSRect)decodeRectForKey:(NSString *)key; - -/* @end */ - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSMutableData -#define _REWRITER_typedef_NSMutableData -typedef struct objc_object NSMutableData; -typedef struct {} _objc_exc_NSMutableData; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @protocol NSKeyedArchiverDelegate, NSKeyedUnarchiverDelegate; - - - -extern "C" NSString * const NSInvalidArchiveOperationException; -extern "C" NSString * const NSInvalidUnarchiveOperationException; - -extern "C" NSString * const NSKeyedArchiveRootObjectKey __attribute__((availability(macosx,introduced=10_9))); - - -#ifndef _REWRITER_typedef_NSKeyedArchiver -#define _REWRITER_typedef_NSKeyedArchiver -typedef struct objc_object NSKeyedArchiver; -typedef struct {} _objc_exc_NSKeyedArchiver; -#endif - -struct NSKeyedArchiver_IMPL { - struct NSCoder_IMPL NSCoder_IVARS; - void *_stream; - NSUInteger _flags; - id _delegate; - id _containers; - id _objects; - id _objRefMap; - id _replacementMap; - id _classNameMap; - id _conditionals; - id _classes; - NSUInteger _genericKey; - void *_cache; - NSUInteger _cacheSize; - NSUInteger _estimatedCount; - void *_reserved2; - id _visited; - void *_reserved0; -}; - - -// + (NSData *)archivedDataWithRootObject:(id)rootObject; -// + (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path; - -// - (instancetype)initForWritingWithMutableData:(NSMutableData *)data; - -// @property (nullable, assign) id <NSKeyedArchiverDelegate> delegate; - -// @property NSPropertyListFormat outputFormat; - -// - (void)finishEncoding; - -// + (void)setClassName:(nullable NSString *)codedName forClass:(Class)cls; -// - (void)setClassName:(nullable NSString *)codedName forClass:(Class)cls; - - - -// + (nullable NSString *)classNameForClass:(Class)cls; -// - (nullable NSString *)classNameForClass:(Class)cls; - -// - (void)encodeObject:(nullable id)objv forKey:(NSString *)key; -// - (void)encodeConditionalObject:(nullable id)objv forKey:(NSString *)key; -// - (void)encodeBool:(BOOL)boolv forKey:(NSString *)key; -// - (void)encodeInt:(int)intv forKey:(NSString *)key; -// - (void)encodeInt32:(int32_t)intv forKey:(NSString *)key; -// - (void)encodeInt64:(int64_t)intv forKey:(NSString *)key; -// - (void)encodeFloat:(float)realv forKey:(NSString *)key; -// - (void)encodeDouble:(double)realv forKey:(NSString *)key; -// - (void)encodeBytes:(nullable const uint8_t *)bytesp length:(NSUInteger)lenv forKey:(NSString *)key; - - -// @property (readwrite) BOOL requiresSecureCoding __attribute__((availability(macosx,introduced=10_8))); - -/* @end */ - - - -#ifndef _REWRITER_typedef_NSKeyedUnarchiver -#define _REWRITER_typedef_NSKeyedUnarchiver -typedef struct objc_object NSKeyedUnarchiver; -typedef struct {} _objc_exc_NSKeyedUnarchiver; -#endif - -struct NSKeyedUnarchiver_IMPL { - struct NSCoder_IMPL NSCoder_IVARS; - id _delegate; - uint32_t _flags; - id _objRefMap; - id _replacementMap; - id _nameClassMap; - id _tmpRefObjMap; - id _refObjMap; - int32_t _genericKey; - id _data; - void *_offsetData; - id _containers; - id _objects; - const uint8_t *_bytes; - uint64_t _len; - id _helper; - void *_reserved0; -}; - - -// + (nullable id)unarchiveObjectWithData:(NSData *)data; -// + (nullable id)unarchiveTopLevelObjectWithData:(NSData *)data error:(NSError **)error __attribute__((availability(macosx,introduced=10_11))) __attribute__((availability(swift, unavailable, message="Use 'unarchiveTopLevelObjectWithData(_:) throws' instead"))); -// + (nullable id)unarchiveObjectWithFile:(NSString *)path; - -// - (instancetype)initForReadingWithData:(NSData *)data; - -// @property (nullable, assign) id <NSKeyedUnarchiverDelegate> delegate; - -// - (void)finishDecoding; - -// + (void)setClass:(nullable Class)cls forClassName:(NSString *)codedName; -// - (void)setClass:(nullable Class)cls forClassName:(NSString *)codedName; - - - -// + (nullable Class)classForClassName:(NSString *)codedName; -// - (nullable Class)classForClassName:(NSString *)codedName; - -// - (BOOL)containsValueForKey:(NSString *)key; - -// - (nullable id)decodeObjectForKey:(NSString *)key; -// - (BOOL)decodeBoolForKey:(NSString *)key; -// - (int)decodeIntForKey:(NSString *)key; -// - (int32_t)decodeInt32ForKey:(NSString *)key; -// - (int64_t)decodeInt64ForKey:(NSString *)key; -// - (float)decodeFloatForKey:(NSString *)key; -// - (double)decodeDoubleForKey:(NSString *)key; -// - (nullable const uint8_t *)decodeBytesForKey:(NSString *)key returnedLength:(nullable NSUInteger *)lengthp __attribute__((objc_returns_inner_pointer)); - - -// @property (readwrite) BOOL requiresSecureCoding __attribute__((availability(macosx,introduced=10_8))); - -/* @end */ - - -// @protocol NSKeyedArchiverDelegate <NSObject> -/* @optional */ - - -// - (nullable id)archiver:(NSKeyedArchiver *)archiver willEncodeObject:(id)object; -// - (void)archiver:(NSKeyedArchiver *)archiver didEncodeObject:(nullable id)object; - - - - - - -// - (void)archiver:(NSKeyedArchiver *)archiver willReplaceObject:(nullable id)object withObject:(nullable id)newObject; - - - - - -// - (void)archiverWillFinish:(NSKeyedArchiver *)archiver; - - -// - (void)archiverDidFinish:(NSKeyedArchiver *)archiver; - - -/* @end */ - - -// @protocol NSKeyedUnarchiverDelegate <NSObject> -/* @optional */ - - -// - (nullable Class)unarchiver:(NSKeyedUnarchiver *)unarchiver cannotDecodeObjectOfClassName:(NSString *)name originalClasses:(NSArray<NSString *> *)classNames; -// - (nullable id)unarchiver:(NSKeyedUnarchiver *)unarchiver didDecodeObject:(nullable id) __attribute__((ns_consumed)) object __attribute__((ns_returns_retained)); - - - - - - - -// - (void)unarchiver:(NSKeyedUnarchiver *)unarchiver willReplaceObject:(id)object withObject:(id)newObject; - - - - - -// - (void)unarchiverWillFinish:(NSKeyedUnarchiver *)unarchiver; - - -// - (void)unarchiverDidFinish:(NSKeyedUnarchiver *)unarchiver; - - -/* @end */ - - -// @interface NSObject (NSKeyedArchiverObjectSubstitution) - -// @property (nullable, readonly) Class classForKeyedArchiver; -// - (nullable id)replacementObjectForKeyedArchiver:(NSKeyedArchiver *)archiver; -// + (NSArray<NSString *> *)classFallbacksForKeyedArchiver; - - -/* @end */ - - -// @interface NSObject (NSKeyedUnarchiverObjectSubstitution) - -// + (Class)classForKeyedUnarchiver; - - - - - -/* @end */ - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - - - -#ifndef _REWRITER_typedef_NSLocale -#define _REWRITER_typedef_NSLocale -typedef struct objc_object NSLocale; -typedef struct {} _objc_exc_NSLocale; -#endif - -struct NSLocale_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (nullable id)objectForKey:(id)key; - -// - (nullable NSString *)displayNameForKey:(id)key value:(id)value; - -// - (instancetype)initWithLocaleIdentifier:(NSString *)string __attribute__((objc_designated_initializer)); - -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSLocale (NSExtendedLocale) - -// @property (readonly, copy) NSString *localeIdentifier; - -/* @end */ - - -// @interface NSLocale (NSLocaleCreation) - -// + (NSLocale *)autoupdatingCurrentLocale __attribute__((availability(macosx,introduced=10_5))); - -// + (NSLocale *)currentLocale; -// + (NSLocale *)systemLocale; - -// + (instancetype)localeWithLocaleIdentifier:(NSString *)ident __attribute__((availability(macosx,introduced=10_6))); - -// - (instancetype)init __attribute__((unavailable)); - -/* @end */ - - -// @interface NSLocale (NSLocaleGeneralInfo) - -// + (NSArray<NSString *> *)availableLocaleIdentifiers; -// + (NSArray<NSString *> *)ISOLanguageCodes; -// + (NSArray<NSString *> *)ISOCountryCodes; -// + (NSArray<NSString *> *)ISOCurrencyCodes; -// + (NSArray<NSString *> *)commonISOCurrencyCodes __attribute__((availability(macosx,introduced=10_5))); - -// + (NSArray<NSString *> *)preferredLanguages __attribute__((availability(macosx,introduced=10_5))); - -// + (NSDictionary<NSString *, NSString *> *)componentsFromLocaleIdentifier:(NSString *)string; -// + (NSString *)localeIdentifierFromComponents:(NSDictionary<NSString *, NSString *> *)dict; - -// + (NSString *)canonicalLocaleIdentifierFromString:(NSString *)string; -// + (NSString *)canonicalLanguageIdentifierFromString:(NSString *)string; - -// + (nullable NSString *)localeIdentifierFromWindowsLocaleCode:(uint32_t)lcid __attribute__((availability(macosx,introduced=10_6))); -// + (uint32_t)windowsLocaleCodeFromLocaleIdentifier:(NSString *)localeIdentifier __attribute__((availability(macosx,introduced=10_6))); - -typedef NSUInteger NSLocaleLanguageDirection; enum { - NSLocaleLanguageDirectionUnknown = kCFLocaleLanguageDirectionUnknown, - NSLocaleLanguageDirectionLeftToRight = kCFLocaleLanguageDirectionLeftToRight, - NSLocaleLanguageDirectionRightToLeft = kCFLocaleLanguageDirectionRightToLeft, - NSLocaleLanguageDirectionTopToBottom = kCFLocaleLanguageDirectionTopToBottom, - NSLocaleLanguageDirectionBottomToTop = kCFLocaleLanguageDirectionBottomToTop -}; - -// + (NSLocaleLanguageDirection)characterDirectionForLanguage:(NSString *)isoLangCode __attribute__((availability(macosx,introduced=10_6))); -// + (NSLocaleLanguageDirection)lineDirectionForLanguage:(NSString *)isoLangCode __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - - -extern "C" NSString * const NSCurrentLocaleDidChangeNotification __attribute__((availability(macosx,introduced=10_5))); - - -extern "C" NSString * const NSLocaleIdentifier; -extern "C" NSString * const NSLocaleLanguageCode; -extern "C" NSString * const NSLocaleCountryCode; -extern "C" NSString * const NSLocaleScriptCode; -extern "C" NSString * const NSLocaleVariantCode; -extern "C" NSString * const NSLocaleExemplarCharacterSet; -extern "C" NSString * const NSLocaleCalendar; -extern "C" NSString * const NSLocaleCollationIdentifier; -extern "C" NSString * const NSLocaleUsesMetricSystem; -extern "C" NSString * const NSLocaleMeasurementSystem; -extern "C" NSString * const NSLocaleDecimalSeparator; -extern "C" NSString * const NSLocaleGroupingSeparator; -extern "C" NSString * const NSLocaleCurrencySymbol; -extern "C" NSString * const NSLocaleCurrencyCode; -extern "C" NSString * const NSLocaleCollatorIdentifier __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSLocaleQuotationBeginDelimiterKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSLocaleQuotationEndDelimiterKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSLocaleAlternateQuotationBeginDelimiterKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSLocaleAlternateQuotationEndDelimiterKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSGregorianCalendar __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarIdentifierGregorian instead"))); -extern "C" NSString * const NSBuddhistCalendar __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarIdentifierBuddhist instead"))); -extern "C" NSString * const NSChineseCalendar __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarIdentifierChinese instead"))); -extern "C" NSString * const NSHebrewCalendar __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarIdentifierHebrew instead"))); -extern "C" NSString * const NSIslamicCalendar __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarIdentifierIslamic instead"))); -extern "C" NSString * const NSIslamicCivilCalendar __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarIdentifierIslamicCivil instead"))); -extern "C" NSString * const NSJapaneseCalendar __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendarIdentifierJapanese instead"))); -extern "C" NSString * const NSRepublicOfChinaCalendar __attribute__((availability(macosx,introduced=10_6,deprecated=10_10,message="" "Use NSCalendarIdentifierRepublicOfChina instead"))); -extern "C" NSString * const NSPersianCalendar __attribute__((availability(macosx,introduced=10_6,deprecated=10_10,message="" "Use NSCalendarIdentifierPersian instead"))); -extern "C" NSString * const NSIndianCalendar __attribute__((availability(macosx,introduced=10_6,deprecated=10_10,message="" "Use NSCalendarIdentifierIndian instead"))); -extern "C" NSString * const NSISO8601Calendar __attribute__((availability(macosx,introduced=10_6,deprecated=10_10,message="" "Use NSCalendarIdentifierISO8601 instead"))); - - - - - - -// @class NSDate; -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - - - - -// @protocol NSLocking - -// - (void)lock; -// - (void)unlock; - -/* @end */ - - - -#ifndef _REWRITER_typedef_NSLock -#define _REWRITER_typedef_NSLock -typedef struct objc_object NSLock; -typedef struct {} _objc_exc_NSLock; -#endif - -struct NSLock_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_priv; -}; - - -// - (BOOL)tryLock; -// - (BOOL)lockBeforeDate:(NSDate *)limit; - -// @property (nullable, copy) NSString *name __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - - -#ifndef _REWRITER_typedef_NSConditionLock -#define _REWRITER_typedef_NSConditionLock -typedef struct objc_object NSConditionLock; -typedef struct {} _objc_exc_NSConditionLock; -#endif - -struct NSConditionLock_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_priv; -}; - - -// - (instancetype)initWithCondition:(NSInteger)condition __attribute__((objc_designated_initializer)); - -// @property (readonly) NSInteger condition; -// - (void)lockWhenCondition:(NSInteger)condition; -// - (BOOL)tryLock; -// - (BOOL)tryLockWhenCondition:(NSInteger)condition; -// - (void)unlockWithCondition:(NSInteger)condition; -// - (BOOL)lockBeforeDate:(NSDate *)limit; -// - (BOOL)lockWhenCondition:(NSInteger)condition beforeDate:(NSDate *)limit; - -// @property (nullable, copy) NSString *name __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - - -#ifndef _REWRITER_typedef_NSRecursiveLock -#define _REWRITER_typedef_NSRecursiveLock -typedef struct objc_object NSRecursiveLock; -typedef struct {} _objc_exc_NSRecursiveLock; -#endif - -struct NSRecursiveLock_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_priv; -}; - - -// - (BOOL)tryLock; -// - (BOOL)lockBeforeDate:(NSDate *)limit; - -// @property (nullable, copy) NSString *name __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_5))) - -#ifndef _REWRITER_typedef_NSCondition -#define _REWRITER_typedef_NSCondition -typedef struct objc_object NSCondition; -typedef struct {} _objc_exc_NSCondition; -#endif - -struct NSCondition_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_priv; -}; - - -// - (void)wait; -// - (BOOL)waitUntilDate:(NSDate *)limit; -// - (void)signal; -// - (void)broadcast; - -// @property (nullable, copy) NSString *name __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSMapTable -#define _REWRITER_typedef_NSMapTable -typedef struct objc_object NSMapTable; -typedef struct {} _objc_exc_NSMapTable; -#endif - -static const NSPointerFunctionsOptions NSMapTableStrongMemory __attribute__((availability(macosx,introduced=10_5))) = NSPointerFunctionsStrongMemory; - -static const NSPointerFunctionsOptions NSMapTableZeroingWeakMemory __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))) = NSPointerFunctionsZeroingWeakMemory; - -static const NSPointerFunctionsOptions NSMapTableCopyIn __attribute__((availability(macosx,introduced=10_5))) = NSPointerFunctionsCopyIn; -static const NSPointerFunctionsOptions NSMapTableObjectPointerPersonality __attribute__((availability(macosx,introduced=10_5))) = NSPointerFunctionsObjectPointerPersonality; -static const NSPointerFunctionsOptions NSMapTableWeakMemory __attribute__((availability(macosx,introduced=10_8))) = NSPointerFunctionsWeakMemory; - -typedef NSUInteger NSMapTableOptions; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_5))) - -#ifndef _REWRITER_typedef_NSMapTable -#define _REWRITER_typedef_NSMapTable -typedef struct objc_object NSMapTable; -typedef struct {} _objc_exc_NSMapTable; -#endif - -struct NSMapTable_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (instancetype)initWithKeyOptions:(NSPointerFunctionsOptions)keyOptions valueOptions:(NSPointerFunctionsOptions)valueOptions capacity:(NSUInteger)initialCapacity __attribute__((objc_designated_initializer)); -// - (instancetype)initWithKeyPointerFunctions:(NSPointerFunctions *)keyFunctions valuePointerFunctions:(NSPointerFunctions *)valueFunctions capacity:(NSUInteger)initialCapacity __attribute__((objc_designated_initializer)); - -// + (NSMapTable<KeyType, ObjectType> *)mapTableWithKeyOptions:(NSPointerFunctionsOptions)keyOptions valueOptions:(NSPointerFunctionsOptions)valueOptions; - - -// + (id)mapTableWithStrongToStrongObjects __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))); -// + (id)mapTableWithWeakToStrongObjects __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))); -// + (id)mapTableWithStrongToWeakObjects __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))); -// + (id)mapTableWithWeakToWeakObjects __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))); - - -// + (NSMapTable<KeyType, ObjectType> *)strongToStrongObjectsMapTable __attribute__((availability(macosx,introduced=10_8))); -// + (NSMapTable<KeyType, ObjectType> *)weakToStrongObjectsMapTable __attribute__((availability(macosx,introduced=10_8))); -// + (NSMapTable<KeyType, ObjectType> *)strongToWeakObjectsMapTable __attribute__((availability(macosx,introduced=10_8))); -// + (NSMapTable<KeyType, ObjectType> *)weakToWeakObjectsMapTable __attribute__((availability(macosx,introduced=10_8))); - - -// @property (readonly, copy) NSPointerFunctions *keyPointerFunctions; -// @property (readonly, copy) NSPointerFunctions *valuePointerFunctions; - -// - (nullable ObjectType)objectForKey:(nullable KeyType)aKey; - -// - (void)removeObjectForKey:(nullable KeyType)aKey; -// - (void)setObject:(nullable ObjectType)anObject forKey:(nullable KeyType)aKey; - -// @property (readonly) NSUInteger count; - -// - (NSEnumerator<KeyType> *)keyEnumerator; -// - (nullable NSEnumerator<ObjectType> *)objectEnumerator; - -// - (void)removeAllObjects; - -// - (NSDictionary<KeyType, ObjectType> *)dictionaryRepresentation; -/* @end */ - -typedef struct {NSUInteger _pi; NSUInteger _si; void * _Nullable _bs;} NSMapEnumerator; - - - -extern "C" void NSFreeMapTable(NSMapTable *table); -extern "C" void NSResetMapTable(NSMapTable *table); -extern "C" BOOL NSCompareMapTables(NSMapTable *table1, NSMapTable *table2); -extern "C" NSMapTable *NSCopyMapTableWithZone(NSMapTable *table, NSZone * _Nullable zone); -extern "C" BOOL NSMapMember(NSMapTable *table, const void *key, void * _Nullable * _Nullable originalKey, void * _Nullable * _Nullable value); -extern "C" void * _Nullable NSMapGet(NSMapTable *table, const void * _Nullable key); -extern "C" void NSMapInsert(NSMapTable *table, const void * _Nullable key, const void * _Nullable value); -extern "C" void NSMapInsertKnownAbsent(NSMapTable *table, const void * _Nullable key, const void * _Nullable value); -extern "C" void * _Nullable NSMapInsertIfAbsent(NSMapTable *table, const void * _Nullable key, const void * _Nullable value); -extern "C" void NSMapRemove(NSMapTable *table, const void * _Nullable key); -extern "C" NSMapEnumerator NSEnumerateMapTable(NSMapTable *table); -extern "C" BOOL NSNextMapEnumeratorPair(NSMapEnumerator *enumerator, void * _Nullable * _Nullable key, void * _Nullable * _Nullable value); -extern "C" void NSEndMapTableEnumeration(NSMapEnumerator *enumerator); -extern "C" NSUInteger NSCountMapTable(NSMapTable *table); -extern "C" NSString *NSStringFromMapTable(NSMapTable *table); -extern "C" NSArray *NSAllMapTableKeys(NSMapTable *table); -extern "C" NSArray *NSAllMapTableValues(NSMapTable *table); - - - - -typedef struct { - NSUInteger (* _Nullable hash)(NSMapTable *table, const void *); - BOOL (* _Nullable isEqual)(NSMapTable *table, const void *, const void *); - void (* _Nullable retain)(NSMapTable *table, const void *); - void (* _Nullable release)(NSMapTable *table, void *); - NSString * _Nullable (* _Nullable describe)(NSMapTable *table, const void *); - const void * _Nullable notAKeyMarker; -} NSMapTableKeyCallBacks; - - - - - -typedef struct { - void (* _Nullable retain)(NSMapTable *table, const void *); - void (* _Nullable release)(NSMapTable *table, void *); - NSString * _Nullable(* _Nullable describe)(NSMapTable *table, const void *); -} NSMapTableValueCallBacks; - -extern "C" NSMapTable *NSCreateMapTableWithZone(NSMapTableKeyCallBacks keyCallBacks, NSMapTableValueCallBacks valueCallBacks, NSUInteger capacity, NSZone * _Nullable zone); -extern "C" NSMapTable *NSCreateMapTable(NSMapTableKeyCallBacks keyCallBacks, NSMapTableValueCallBacks valueCallBacks, NSUInteger capacity); - - - - -extern "C" const NSMapTableKeyCallBacks NSIntegerMapKeyCallBacks __attribute__((availability(macosx,introduced=10_5))); -extern "C" const NSMapTableKeyCallBacks NSNonOwnedPointerMapKeyCallBacks; -extern "C" const NSMapTableKeyCallBacks NSNonOwnedPointerOrNullMapKeyCallBacks; -extern "C" const NSMapTableKeyCallBacks NSNonRetainedObjectMapKeyCallBacks; -extern "C" const NSMapTableKeyCallBacks NSObjectMapKeyCallBacks; -extern "C" const NSMapTableKeyCallBacks NSOwnedPointerMapKeyCallBacks; -extern "C" const NSMapTableKeyCallBacks NSIntMapKeyCallBacks __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - - - -extern "C" const NSMapTableValueCallBacks NSIntegerMapValueCallBacks __attribute__((availability(macosx,introduced=10_5))); -extern "C" const NSMapTableValueCallBacks NSNonOwnedPointerMapValueCallBacks; -extern "C" const NSMapTableValueCallBacks NSObjectMapValueCallBacks; -extern "C" const NSMapTableValueCallBacks NSNonRetainedObjectMapValueCallBacks; -extern "C" const NSMapTableValueCallBacks NSOwnedPointerMapValueCallBacks; -extern "C" const NSMapTableValueCallBacks NSIntMapValueCallBacks __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - - - - - - - - -__attribute__((availability(swift, unavailable, message="NSInvocation and related APIs not available"))) - -#ifndef _REWRITER_typedef_NSMethodSignature -#define _REWRITER_typedef_NSMethodSignature -typedef struct objc_object NSMethodSignature; -typedef struct {} _objc_exc_NSMethodSignature; -#endif - -struct NSMethodSignature_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_private; - void *_reserved[6]; -}; - - -// + (nullable NSMethodSignature *)signatureWithObjCTypes:(const char *)types; - -// @property (readonly) NSUInteger numberOfArguments; -// - (const char *)getArgumentTypeAtIndex:(NSUInteger)idx __attribute__((objc_returns_inner_pointer)); - -// @property (readonly) NSUInteger frameLength; - -// - (BOOL)isOneway; - -// @property (readonly) const char *methodReturnType __attribute__((objc_returns_inner_pointer)); -// @property (readonly) NSUInteger methodReturnLength; - -/* @end */ - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSOperationQueue -#define _REWRITER_typedef_NSOperationQueue -typedef struct objc_object NSOperationQueue; -typedef struct {} _objc_exc_NSOperationQueue; -#endif - - - - - - - -#ifndef _REWRITER_typedef_NSNotification -#define _REWRITER_typedef_NSNotification -typedef struct objc_object NSNotification; -typedef struct {} _objc_exc_NSNotification; -#endif - -struct NSNotification_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly, copy) NSString *name; -// @property (nullable, readonly, retain) id object; -// @property (nullable, readonly, copy) NSDictionary *userInfo; - -// - (instancetype)initWithName:(NSString *)name object:(nullable id)object userInfo:(nullable NSDictionary *)userInfo __attribute__((availability(macosx,introduced=10_6))) __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSNotification (NSNotificationCreation) - -// + (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject; -// + (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo; - -// - (instancetype)init ; - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSNotificationCenter -#define _REWRITER_typedef_NSNotificationCenter -typedef struct objc_object NSNotificationCenter; -typedef struct {} _objc_exc_NSNotificationCenter; -#endif - -struct NSNotificationCenter_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_impl; - void *_callback; - void *_pad[11]; -}; - - -// + (NSNotificationCenter *)defaultCenter; - -// - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject; - -// - (void)postNotification:(NSNotification *)notification; -// - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject; -// - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo; - -// - (void)removeObserver:(id)observer; -// - (void)removeObserver:(id)observer name:(nullable NSString *)aName object:(nullable id)anObject; - -// - (id <NSObject>)addObserverForName:(nullable NSString *)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block __attribute__((availability(macosx,introduced=10_6))); - - - -/* @end */ - - - - - - - -// @class NSNotification; -#ifndef _REWRITER_typedef_NSNotification -#define _REWRITER_typedef_NSNotification -typedef struct objc_object NSNotification; -typedef struct {} _objc_exc_NSNotification; -#endif - -#ifndef _REWRITER_typedef_NSNotificationCenter -#define _REWRITER_typedef_NSNotificationCenter -typedef struct objc_object NSNotificationCenter; -typedef struct {} _objc_exc_NSNotificationCenter; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -typedef NSUInteger NSPostingStyle; enum { - NSPostWhenIdle = 1, - NSPostASAP = 2, - NSPostNow = 3 -}; - -typedef NSUInteger NSNotificationCoalescing; enum { - NSNotificationNoCoalescing = 0, - NSNotificationCoalescingOnName = 1, - NSNotificationCoalescingOnSender = 2 -}; - - -#ifndef _REWRITER_typedef_NSNotificationQueue -#define _REWRITER_typedef_NSNotificationQueue -typedef struct objc_object NSNotificationQueue; -typedef struct {} _objc_exc_NSNotificationQueue; -#endif - -struct NSNotificationQueue_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _notificationCenter; - id _asapQueue; - id _asapObs; - id _idleQueue; - id _idleObs; -}; - - -// + (NSNotificationQueue *)defaultQueue; - -// - (instancetype)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter __attribute__((objc_designated_initializer)); - -// - (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle; -// - (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle coalesceMask:(NSNotificationCoalescing)coalesceMask forModes:(nullable NSArray<NSString *> *)modes; - -// - (void)dequeueNotificationsMatching:(NSNotification *)notification coalesceMask:(NSUInteger)coalesceMask; - -/* @end */ - - - - - - - - - - -#ifndef _REWRITER_typedef_NSNull -#define _REWRITER_typedef_NSNull -typedef struct objc_object NSNull; -typedef struct {} _objc_exc_NSNull; -#endif - -struct NSNull_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// + (NSNull *)null; - -/* @end */ - - - - - - - - -// @class NSLocale; -#ifndef _REWRITER_typedef_NSLocale -#define _REWRITER_typedef_NSLocale -typedef struct objc_object NSLocale; -typedef struct {} _objc_exc_NSLocale; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSRecursiveLock -#define _REWRITER_typedef_NSRecursiveLock -typedef struct objc_object NSRecursiveLock; -typedef struct {} _objc_exc_NSRecursiveLock; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSCache -#define _REWRITER_typedef_NSCache -typedef struct objc_object NSCache; -typedef struct {} _objc_exc_NSCache; -#endif - - - - -typedef NSUInteger NSNumberFormatterBehavior; enum { - NSNumberFormatterBehaviorDefault = 0, - - NSNumberFormatterBehavior10_0 = 1000, - - NSNumberFormatterBehavior10_4 = 1040, -}; - - -#ifndef _REWRITER_typedef_NSNumberFormatter -#define _REWRITER_typedef_NSNumberFormatter -typedef struct objc_object NSNumberFormatter; -typedef struct {} _objc_exc_NSNumberFormatter; -#endif - -struct NSNumberFormatter_IMPL { - struct NSFormatter_IMPL NSFormatter_IVARS; - NSMutableDictionary *_attributes; - CFNumberFormatterRef _formatter; - NSUInteger _counter; - NSNumberFormatterBehavior _behavior; - NSRecursiveLock *_lock; - unsigned long _stateBitMask; - NSInteger _cacheGeneration; - void *_reserved[8]; -}; - - -// @property NSFormattingContext formattingContext __attribute__((availability(macosx,introduced=10_10))); - - - - - -// - (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string range:(inout nullable NSRange *)rangep error:(out NSError **)error; - - - - -// - (nullable NSString *)stringFromNumber:(NSNumber *)number; -// - (nullable NSNumber *)numberFromString:(NSString *)string; - -typedef NSUInteger NSNumberFormatterStyle; enum { - NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle, - NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle, - NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle, - NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle, - NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle, - NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle, - NSNumberFormatterOrdinalStyle __attribute__((availability(macosx,introduced=10_11))) = kCFNumberFormatterOrdinalStyle, - NSNumberFormatterCurrencyISOCodeStyle __attribute__((availability(macosx,introduced=10_11))) = kCFNumberFormatterCurrencyISOCodeStyle, - NSNumberFormatterCurrencyPluralStyle __attribute__((availability(macosx,introduced=10_11))) = kCFNumberFormatterCurrencyPluralStyle, - NSNumberFormatterCurrencyAccountingStyle __attribute__((availability(macosx,introduced=10_11))) = kCFNumberFormatterCurrencyAccountingStyle, -}; - -// + (NSString *)localizedStringFromNumber:(NSNumber *)num numberStyle:(NSNumberFormatterStyle)nstyle __attribute__((availability(macosx,introduced=10_6))); - - - -// + (NSNumberFormatterBehavior)defaultFormatterBehavior; -// + (void)setDefaultFormatterBehavior:(NSNumberFormatterBehavior)behavior; - -// @property NSNumberFormatterStyle numberStyle; -// @property (null_resettable, copy) NSLocale *locale; -// @property BOOL generatesDecimalNumbers; -// @property NSNumberFormatterBehavior formatterBehavior; - -// @property (null_resettable, copy) NSString *negativeFormat; -// @property (nullable, copy) NSDictionary<NSString *, id> *textAttributesForNegativeValues; -// @property (null_resettable, copy) NSString *positiveFormat; -// @property (nullable, copy) NSDictionary<NSString *, id> *textAttributesForPositiveValues; -// @property BOOL allowsFloats; -// @property (null_resettable, copy) NSString *decimalSeparator; -// @property BOOL alwaysShowsDecimalSeparator; -// @property (null_resettable, copy) NSString *currencyDecimalSeparator; -// @property BOOL usesGroupingSeparator; -// @property (null_resettable, copy) NSString *groupingSeparator; - -// @property (nullable, copy) NSString *zeroSymbol; -// @property (nullable, copy) NSDictionary<NSString *, id> *textAttributesForZero; -// @property (copy) NSString *nilSymbol; -// @property (nullable, copy) NSDictionary<NSString *, id> *textAttributesForNil; -// @property (null_resettable, copy) NSString *notANumberSymbol; -// @property (nullable, copy) NSDictionary<NSString *, id> *textAttributesForNotANumber; -// @property (copy) NSString *positiveInfinitySymbol; -// @property (nullable, copy) NSDictionary<NSString *, id> *textAttributesForPositiveInfinity; -// @property (copy) NSString *negativeInfinitySymbol; -// @property (nullable, copy) NSDictionary<NSString *, id> *textAttributesForNegativeInfinity; - -// @property (null_resettable, copy) NSString *positivePrefix; -// @property (null_resettable, copy) NSString *positiveSuffix; -// @property (null_resettable, copy) NSString *negativePrefix; -// @property (null_resettable, copy) NSString *negativeSuffix; -// @property (null_resettable, copy) NSString *currencyCode; -// @property (null_resettable, copy) NSString *currencySymbol; -// @property (null_resettable, copy) NSString *internationalCurrencySymbol; -// @property (null_resettable, copy) NSString *percentSymbol; -// @property (null_resettable, copy) NSString *perMillSymbol; -// @property (null_resettable, copy) NSString *minusSign; -// @property (null_resettable, copy) NSString *plusSign; -// @property (null_resettable, copy) NSString *exponentSymbol; - -// @property NSUInteger groupingSize; -// @property NSUInteger secondaryGroupingSize; -// @property (nullable, copy) NSNumber *multiplier; -// @property NSUInteger formatWidth; -// @property (null_resettable, copy) NSString *paddingCharacter; - - -typedef NSUInteger NSNumberFormatterPadPosition; enum { - NSNumberFormatterPadBeforePrefix = kCFNumberFormatterPadBeforePrefix, - NSNumberFormatterPadAfterPrefix = kCFNumberFormatterPadAfterPrefix, - NSNumberFormatterPadBeforeSuffix = kCFNumberFormatterPadBeforeSuffix, - NSNumberFormatterPadAfterSuffix = kCFNumberFormatterPadAfterSuffix -}; - -typedef NSUInteger NSNumberFormatterRoundingMode; enum { - NSNumberFormatterRoundCeiling = kCFNumberFormatterRoundCeiling, - NSNumberFormatterRoundFloor = kCFNumberFormatterRoundFloor, - NSNumberFormatterRoundDown = kCFNumberFormatterRoundDown, - NSNumberFormatterRoundUp = kCFNumberFormatterRoundUp, - NSNumberFormatterRoundHalfEven = kCFNumberFormatterRoundHalfEven, - NSNumberFormatterRoundHalfDown = kCFNumberFormatterRoundHalfDown, - NSNumberFormatterRoundHalfUp = kCFNumberFormatterRoundHalfUp -}; - -// @property NSNumberFormatterPadPosition paddingPosition; -// @property NSNumberFormatterRoundingMode roundingMode; -// @property (null_resettable, copy) NSNumber *roundingIncrement; -// @property NSUInteger minimumIntegerDigits; -// @property NSUInteger maximumIntegerDigits; -// @property NSUInteger minimumFractionDigits; -// @property NSUInteger maximumFractionDigits; -// @property (nullable, copy) NSNumber *minimum; -// @property (nullable, copy) NSNumber *maximum; -// @property (null_resettable, copy) NSString *currencyGroupingSeparator __attribute__((availability(macosx,introduced=10_5))); -// @property (getter=isLenient) BOOL lenient __attribute__((availability(macosx,introduced=10_5))); -// @property BOOL usesSignificantDigits __attribute__((availability(macosx,introduced=10_5))); -// @property NSUInteger minimumSignificantDigits __attribute__((availability(macosx,introduced=10_5))); -// @property NSUInteger maximumSignificantDigits __attribute__((availability(macosx,introduced=10_5))); -// @property (getter=isPartialStringValidationEnabled) BOOL partialStringValidationEnabled __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - -// @class NSDecimalNumberHandler; -#ifndef _REWRITER_typedef_NSDecimalNumberHandler -#define _REWRITER_typedef_NSDecimalNumberHandler -typedef struct objc_object NSDecimalNumberHandler; -typedef struct {} _objc_exc_NSDecimalNumberHandler; -#endif - - - -// @interface NSNumberFormatter (NSNumberFormatterCompatibility) - -// @property BOOL hasThousandSeparators; -// @property (null_resettable, copy) NSString *thousandSeparator; - -// @property BOOL localizesFormat; - -// @property (copy) NSString *format; - -// @property (copy) NSAttributedString *attributedStringForZero; -// @property (copy) NSAttributedString *attributedStringForNil; -// @property (copy) NSAttributedString *attributedStringForNotANumber; - -// @property (copy) NSDecimalNumberHandler *roundingBehavior; - -/* @end */ - - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_5))) - -#ifndef _REWRITER_typedef_NSOperation -#define _REWRITER_typedef_NSOperation -typedef struct objc_object NSOperation; -typedef struct {} _objc_exc_NSOperation; -#endif - -struct NSOperation_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _private; - int32_t _private1; - int32_t _private1b; -}; - - -// - (void)start; -// - (void)main; - -// @property (readonly, getter=isCancelled) BOOL cancelled; -// - (void)cancel; - -// @property (readonly, getter=isExecuting) BOOL executing; -// @property (readonly, getter=isFinished) BOOL finished; -// @property (readonly, getter=isConcurrent) BOOL concurrent; -// @property (readonly, getter=isAsynchronous) BOOL asynchronous __attribute__((availability(macosx,introduced=10_8))); -// @property (readonly, getter=isReady) BOOL ready; - -// - (void)addDependency:(NSOperation *)op; -// - (void)removeDependency:(NSOperation *)op; - -// @property (readonly, copy) NSArray<NSOperation *> *dependencies; - -typedef NSInteger NSOperationQueuePriority; enum { - NSOperationQueuePriorityVeryLow = -8L, - NSOperationQueuePriorityLow = -4L, - NSOperationQueuePriorityNormal = 0, - NSOperationQueuePriorityHigh = 4, - NSOperationQueuePriorityVeryHigh = 8 -}; - -// @property NSOperationQueuePriority queuePriority; - -// @property (nullable, copy) void (^completionBlock)(void) __attribute__((availability(macosx,introduced=10_6))); - -// - (void)waitUntilFinished __attribute__((availability(macosx,introduced=10_6))); - -// @property double threadPriority __attribute__((availability(macosx,introduced=10_6,deprecated=10_10,message="" ))); - -// @property NSQualityOfService qualityOfService __attribute__((availability(macosx,introduced=10_10))); - -// @property (nullable, copy) NSString *name __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_6))) - -#ifndef _REWRITER_typedef_NSBlockOperation -#define _REWRITER_typedef_NSBlockOperation -typedef struct objc_object NSBlockOperation; -typedef struct {} _objc_exc_NSBlockOperation; -#endif - -struct NSBlockOperation_IMPL { - struct NSOperation_IMPL NSOperation_IVARS; - id _private2; - void *_reserved2; -}; - - -// + (instancetype)blockOperationWithBlock:(void (^)(void))block; - -// - (void)addExecutionBlock:(void (^)(void))block; -// @property (readonly, copy) NSArray<void (^)(void)> *executionBlocks; - -/* @end */ - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_5))) -__attribute__((availability(swift, unavailable, message="NSInvocation and related APIs not available"))) - -#ifndef _REWRITER_typedef_NSInvocationOperation -#define _REWRITER_typedef_NSInvocationOperation -typedef struct objc_object NSInvocationOperation; -typedef struct {} _objc_exc_NSInvocationOperation; -#endif - -struct NSInvocationOperation_IMPL { - struct NSOperation_IMPL NSOperation_IVARS; - id _inv; - id _exception; - void *_reserved2; -}; - - -// - (nullable instancetype)initWithTarget:(id)target selector:(SEL)sel object:(nullable id)arg; -// - (instancetype)initWithInvocation:(NSInvocation *)inv __attribute__((objc_designated_initializer)); - -// @property (readonly, retain) NSInvocation *invocation; - -// @property (nullable, readonly, retain) id result; - -/* @end */ - - -extern "C" NSString * const NSInvocationOperationVoidResultException __attribute__((availability(macosx,introduced=10_5))); -extern "C" NSString * const NSInvocationOperationCancelledException __attribute__((availability(macosx,introduced=10_5))); - -static const NSInteger NSOperationQueueDefaultMaxConcurrentOperationCount = -1; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_5))) - -#ifndef _REWRITER_typedef_NSOperationQueue -#define _REWRITER_typedef_NSOperationQueue -typedef struct objc_object NSOperationQueue; -typedef struct {} _objc_exc_NSOperationQueue; -#endif - -struct NSOperationQueue_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _private; - void *_reserved; -}; - - -// - (void)addOperation:(NSOperation *)op; -// - (void)addOperations:(NSArray<NSOperation *> *)ops waitUntilFinished:(BOOL)wait __attribute__((availability(macosx,introduced=10_6))); - -// - (void)addOperationWithBlock:(void (^)(void))block __attribute__((availability(macosx,introduced=10_6))); - -// @property (readonly, copy) NSArray<__kindof NSOperation *> *operations; -// @property (readonly) NSUInteger operationCount __attribute__((availability(macosx,introduced=10_6))); - -// @property NSInteger maxConcurrentOperationCount; - -// @property (getter=isSuspended) BOOL suspended; - -// @property (nullable, copy) NSString *name __attribute__((availability(macosx,introduced=10_6))); - -// @property NSQualityOfService qualityOfService __attribute__((availability(macosx,introduced=10_10))); - -// @property (nullable, assign ) dispatch_queue_t underlyingQueue __attribute__((availability(macosx,introduced=10_10))); - -// - (void)cancelAllOperations; - -// - (void)waitUntilAllOperationsAreFinished; - -// + (nullable NSOperationQueue *)currentQueue __attribute__((availability(macosx,introduced=10_6))); -// + (NSOperationQueue *)mainQueue __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_6))) - -#ifndef _REWRITER_typedef_NSOrthography -#define _REWRITER_typedef_NSOrthography -typedef struct objc_object NSOrthography; -typedef struct {} _objc_exc_NSOrthography; -#endif - -struct NSOrthography_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - -// @property (readonly, copy) NSString *dominantScript; -// @property (readonly, copy) NSDictionary<NSString *, NSArray<NSString *> *> *languageMap; -// - (instancetype)initWithDominantScript:(NSString *)script languageMap:(NSDictionary<NSString *, NSArray<NSString *> *> *)map __attribute__((availability(macosx,introduced=10_6))) __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); - -/* @end */ - - -// @interface NSOrthography (NSOrthographyExtended) - - -// - (nullable NSArray<NSString *> *)languagesForScript:(NSString *)script __attribute__((availability(macosx,introduced=10_6))); -// - (nullable NSString *)dominantLanguageForScript:(NSString *)script __attribute__((availability(macosx,introduced=10_6))); - - -// @property (readonly, copy) NSString *dominantLanguage __attribute__((availability(macosx,introduced=10_6))); -// @property (readonly, copy) NSArray<NSString *> *allScripts __attribute__((availability(macosx,introduced=10_6))); -// @property (readonly, copy) NSArray<NSString *> *allLanguages __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -// @interface NSOrthography (NSOrthographyCreation) - -// + (instancetype)orthographyWithDominantScript:(NSString *)script languageMap:(NSDictionary<NSString *, NSArray<NSString *> *> *)map __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_5))) - -#ifndef _REWRITER_typedef_NSPointerArray -#define _REWRITER_typedef_NSPointerArray -typedef struct objc_object NSPointerArray; -typedef struct {} _objc_exc_NSPointerArray; -#endif - -struct NSPointerArray_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (instancetype)initWithOptions:(NSPointerFunctionsOptions)options __attribute__((objc_designated_initializer)); -// - (instancetype)initWithPointerFunctions:(NSPointerFunctions *)functions __attribute__((objc_designated_initializer)); - -// + (NSPointerArray *)pointerArrayWithOptions:(NSPointerFunctionsOptions)options; -// + (NSPointerArray *)pointerArrayWithPointerFunctions:(NSPointerFunctions *)functions; - - -// @property (readonly, copy) NSPointerFunctions *pointerFunctions; - -// - (nullable void *)pointerAtIndex:(NSUInteger)index; - - -// - (void)addPointer:(nullable void *)pointer; -// - (void)removePointerAtIndex:(NSUInteger)index; -// - (void)insertPointer:(nullable void *)item atIndex:(NSUInteger)index; - -// - (void)replacePointerAtIndex:(NSUInteger)index withPointer:(nullable void *)item; - -// - (void)compact; - - - -// @property NSUInteger count; - -/* @end */ - - - -// @interface NSPointerArray (NSPointerArrayConveniences) - - - -// + (id) pointerArrayWithStrongObjects __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))); -// + (id) pointerArrayWithWeakObjects __attribute__((availability(macosx,introduced=10_5,deprecated=10_8,message="" ))); - - -// + (NSPointerArray *)strongObjectsPointerArray __attribute__((availability(macosx,introduced=10_8))); -// + (NSPointerArray *)weakObjectsPointerArray __attribute__((availability(macosx,introduced=10_8))); - -// @property (readonly, copy) NSArray *allObjects; - -/* @end */ - - - - - - - - -typedef int NSSocketNativeHandle; - -// @class NSRunLoop; -#ifndef _REWRITER_typedef_NSRunLoop -#define _REWRITER_typedef_NSRunLoop -typedef struct objc_object NSRunLoop; -typedef struct {} _objc_exc_NSRunLoop; -#endif - -#ifndef _REWRITER_typedef_NSMutableArray -#define _REWRITER_typedef_NSMutableArray -typedef struct objc_object NSMutableArray; -typedef struct {} _objc_exc_NSMutableArray; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -// @class NSConnection; -#ifndef _REWRITER_typedef_NSConnection -#define _REWRITER_typedef_NSConnection -typedef struct objc_object NSConnection; -typedef struct {} _objc_exc_NSConnection; -#endif - -#ifndef _REWRITER_typedef_NSPortMessage -#define _REWRITER_typedef_NSPortMessage -typedef struct objc_object NSPortMessage; -typedef struct {} _objc_exc_NSPortMessage; -#endif - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -// @protocol NSPortDelegate, NSMachPortDelegate; - - - -extern "C" NSString * const NSPortDidBecomeInvalidNotification; - - -#ifndef _REWRITER_typedef_NSPort -#define _REWRITER_typedef_NSPort -typedef struct objc_object NSPort; -typedef struct {} _objc_exc_NSPort; -#endif - -struct NSPort_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - - - - - - -// + (NSPort *)port; - -// - (void)invalidate; -// @property (readonly, getter=isValid) BOOL valid; - -// - (void)setDelegate:(nullable id <NSPortDelegate>)anObject; -// - (nullable id <NSPortDelegate>)delegate; - - - - - -// - (void)scheduleInRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode; -// - (void)removeFromRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode; - - - -// @property (readonly) NSUInteger reservedSpaceLength; -// - (BOOL)sendBeforeDate:(NSDate *)limitDate components:(nullable NSMutableArray *)components from:(nullable NSPort *) receivePort reserved:(NSUInteger)headerSpaceReserved; -// - (BOOL)sendBeforeDate:(NSDate *)limitDate msgid:(NSUInteger)msgID components:(nullable NSMutableArray *)components from:(nullable NSPort *)receivePort reserved:(NSUInteger)headerSpaceReserved; -// - (void)addConnection:(NSConnection *)conn toRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode __attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))); -// - (void)removeConnection:(NSConnection *)conn fromRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode __attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))); - - - - - - -/* @end */ - - -// @protocol NSPortDelegate <NSObject> -/* @optional */ - -// - (void)handlePortMessage:(NSPortMessage *)message; - - - -/* @end */ - - - - -__attribute__((objc_arc_weak_reference_unavailable)) - -#ifndef _REWRITER_typedef_NSMachPort -#define _REWRITER_typedef_NSMachPort -typedef struct objc_object NSMachPort; -typedef struct {} _objc_exc_NSMachPort; -#endif - -struct NSMachPort_IMPL { - struct NSPort_IMPL NSPort_IVARS; - id _delegate; - NSUInteger _flags; - uint32_t _machPort; - NSUInteger _reserved; -}; - - -// + (NSPort *)portWithMachPort:(uint32_t)machPort; -// - (instancetype)initWithMachPort:(uint32_t)machPort __attribute__((objc_designated_initializer)); - -// - (void)setDelegate:(nullable id <NSMachPortDelegate>)anObject; -// - (nullable id <NSMachPortDelegate>)delegate; - -typedef NSUInteger NSMachPortOptions; enum { - NSMachPortDeallocateNone = 0, - NSMachPortDeallocateSendRight = (1UL << 0), - NSMachPortDeallocateReceiveRight = (1UL << 1) -} __attribute__((availability(macosx,introduced=10_5))); - -// + (NSPort *)portWithMachPort:(uint32_t)machPort options:(NSMachPortOptions)f __attribute__((availability(macosx,introduced=10_5))); -// - (instancetype)initWithMachPort:(uint32_t)machPort options:(NSMachPortOptions)f __attribute__((availability(macosx,introduced=10_5))) __attribute__((objc_designated_initializer)); - -// @property (readonly) uint32_t machPort; - -// - (void)scheduleInRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode; -// - (void)removeFromRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode; - - - - -/* @end */ - - -// @protocol NSMachPortDelegate <NSPortDelegate> -/* @optional */ - - - -// - (void)handleMachMessage:(void *)msg; - -/* @end */ - - - - - - -__attribute__((objc_arc_weak_reference_unavailable)) - -#ifndef _REWRITER_typedef_NSMessagePort -#define _REWRITER_typedef_NSMessagePort -typedef struct objc_object NSMessagePort; -typedef struct {} _objc_exc_NSMessagePort; -#endif - -struct NSMessagePort_IMPL { - struct NSPort_IMPL NSPort_IVARS; - void *_port; - id _delegate; -}; - - -/* @end */ - - - - - - - - -#ifndef _REWRITER_typedef_NSSocketPort -#define _REWRITER_typedef_NSSocketPort -typedef struct objc_object NSSocketPort; -typedef struct {} _objc_exc_NSSocketPort; -#endif - -struct NSSocketPort_IMPL { - struct NSPort_IMPL NSPort_IVARS; - void *_receiver; - id _connectors; - void *_loops; - void *_data; - id _signature; - id _delegate; - id _lock; - NSUInteger _maxSize; - NSUInteger _useCount; - NSUInteger _reserved; -}; - - -// - (instancetype)init; -// - (nullable instancetype)initWithTCPPort:(unsigned short)port; -// - (nullable instancetype)initWithProtocolFamily:(int)family socketType:(int)type protocol:(int)protocol address:(NSData *)address __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithProtocolFamily:(int)family socketType:(int)type protocol:(int)protocol socket:(NSSocketNativeHandle)sock __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initRemoteWithTCPPort:(unsigned short)port host:(nullable NSString *)hostName; -// - (instancetype)initRemoteWithProtocolFamily:(int)family socketType:(int)type protocol:(int)protocol address:(NSData *)address __attribute__((objc_designated_initializer)); - - -// @property (readonly) int protocolFamily; -// @property (readonly) int socketType; -// @property (readonly) int protocol; -// @property (readonly, copy) NSData *address; -// @property (readonly) NSSocketNativeHandle socket; - -/* @end */ - -enum { - NSWindowsNTOperatingSystem = 1, - NSWindows95OperatingSystem, - NSSolarisOperatingSystem, - NSHPUXOperatingSystem, - NSMACHOperatingSystem, - NSSunOSOperatingSystem, - NSOSF1OperatingSystem -} __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" ))); - -typedef struct { - NSInteger majorVersion; - NSInteger minorVersion; - NSInteger patchVersion; -} NSOperatingSystemVersion; - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - - - -#ifndef _REWRITER_typedef_NSProcessInfo -#define _REWRITER_typedef_NSProcessInfo -typedef struct objc_object NSProcessInfo; -typedef struct {} _objc_exc_NSProcessInfo; -#endif - -struct NSProcessInfo_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSDictionary *environment; - NSArray *arguments; - NSString *hostName; - NSString *name; - NSInteger automaticTerminationOptOutCounter; -}; - - -// + (NSProcessInfo *)processInfo; - -// @property (readonly, copy) NSDictionary<NSString *, NSString *> *environment; -// @property (readonly, copy) NSArray<NSString *> *arguments; -// @property (readonly, copy) NSString *hostName; -// @property (copy) NSString *processName; -// @property (readonly) int processIdentifier; - -// @property (readonly, copy) NSString *globallyUniqueString; - -// - (NSUInteger)operatingSystem __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "-operatingSystem always returns NSMACHOperatingSystem, use -operatingSystemVersion or -isOperatingSystemAtLeastVersion: instead"))); -// - (NSString *)operatingSystemName __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "-operatingSystemName always returns NSMACHOperatingSystem, use -operatingSystemVersionString instead"))); - - -// @property (readonly, copy) NSString *operatingSystemVersionString; - -// @property (readonly) NSOperatingSystemVersion operatingSystemVersion __attribute__((availability(macosx,introduced=10_10))); - -// @property (readonly) NSUInteger processorCount __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly) NSUInteger activeProcessorCount __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly) unsigned long long physicalMemory __attribute__((availability(macosx,introduced=10_5))); - -// - (BOOL) isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version __attribute__((availability(macosx,introduced=10_10))); -// @property (readonly) NSTimeInterval systemUptime __attribute__((availability(macosx,introduced=10_6))); - - - - - - -// - (void)disableSuddenTermination __attribute__((availability(macosx,introduced=10_6))); -// - (void)enableSuddenTermination __attribute__((availability(macosx,introduced=10_6))); - - - - - - - -// - (void)disableAutomaticTermination:(NSString *)reason __attribute__((availability(macosx,introduced=10_7))); -// - (void)enableAutomaticTermination:(NSString *)reason __attribute__((availability(macosx,introduced=10_7))); - - - - - - -// @property BOOL automaticTerminationSupportEnabled __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - -typedef uint64_t NSActivityOptions; enum { - NSActivityIdleDisplaySleepDisabled = (1ULL << 40), - - - NSActivityIdleSystemSleepDisabled = (1ULL << 20), - - - NSActivitySuddenTerminationDisabled = (1ULL << 14), - - - NSActivityAutomaticTerminationDisabled = (1ULL << 15), - - - - - - NSActivityUserInitiated = (0x00FFFFFFULL | NSActivityIdleSystemSleepDisabled), - NSActivityUserInitiatedAllowingIdleSystemSleep = (NSActivityUserInitiated & ~NSActivityIdleSystemSleepDisabled), - - - NSActivityBackground = 0x000000FFULL, - - - NSActivityLatencyCritical = 0xFF00000000ULL, -} __attribute__((availability(macosx,introduced=10_9))); - -// @interface NSProcessInfo (NSProcessInfoActivity) - - - -// - (id <NSObject>)beginActivityWithOptions:(NSActivityOptions)options reason:(NSString *)reason __attribute__((availability(macosx,introduced=10_9))); - - - - -// - (void)endActivity:(id <NSObject>)activity __attribute__((availability(macosx,introduced=10_9))); - - - - -// - (void)performActivityWithOptions:(NSActivityOptions)options reason:(NSString *)reason usingBlock:(void (^)(void))block __attribute__((availability(macosx,introduced=10_9))); - - - - -// - (void)performExpiringActivityWithReason:(NSString *)reason usingBlock:(void(^)(BOOL expired))block __attribute__((availability(macosx,unavailable))); - -/* @end */ - - - -typedef NSInteger NSProcessInfoThermalState; enum { - - NSProcessInfoThermalStateNominal, - - - NSProcessInfoThermalStateFair, - - - NSProcessInfoThermalStateSerious, - - - NSProcessInfoThermalStateCritical -} __attribute__((availability(macosx,introduced=10_10_3))); - -// @interface NSProcessInfo (NSProcessInfoThermalState) - - -// @property (readonly) NSProcessInfoThermalState thermalState __attribute__((availability(macosx,introduced=10_10_3))); - -/* @end */ - - -// @interface NSProcessInfo (NSProcessInfoPowerState) - - -// @property (readonly, getter=isLowPowerModeEnabled) BOOL lowPowerModeEnabled __attribute__((availability(macosx,introduced=NA))); - -/* @end */ - -extern "C" NSString * const NSProcessInfoThermalStateDidChangeNotification __attribute__((availability(macosx,introduced=10_10_3))); -extern "C" NSString * const NSProcessInfoPowerStateDidChangeNotification __attribute__((availability(macosx,introduced=NA))); - - - - - - - -// @class NSMethodSignature; -#ifndef _REWRITER_typedef_NSMethodSignature -#define _REWRITER_typedef_NSMethodSignature -typedef struct objc_object NSMethodSignature; -typedef struct {} _objc_exc_NSMethodSignature; -#endif - -#ifndef _REWRITER_typedef_NSInvocation -#define _REWRITER_typedef_NSInvocation -typedef struct objc_object NSInvocation; -typedef struct {} _objc_exc_NSInvocation; -#endif - - - - -__attribute__((objc_root_class)) - -#ifndef _REWRITER_typedef_NSProxy -#define _REWRITER_typedef_NSProxy -typedef struct objc_object NSProxy; -typedef struct {} _objc_exc_NSProxy; -#endif - -struct NSProxy_IMPL { - Class isa; -}; - - -// + (id)alloc; -// + (id)allocWithZone:(nullable NSZone *)zone ; -// + (Class)class; - -// - (void)forwardInvocation:(NSInvocation *)invocation; -// - (nullable NSMethodSignature *)methodSignatureForSelector:(SEL)sel __attribute__((availability(swift, unavailable, message="NSInvocation and related APIs not available"))); -// - (void)dealloc; -// - (void)finalize; -// @property (readonly, copy) NSString *description; -// @property (readonly, copy) NSString *debugDescription; -// + (BOOL)respondsToSelector:(SEL)aSelector; - -// - (BOOL)allowsWeakReference __attribute__((unavailable)); -// - (BOOL)retainWeakReference __attribute__((unavailable)); - - - -/* @end */ - - - - - - - - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -#ifndef _REWRITER_typedef_NSTimeZone -#define _REWRITER_typedef_NSTimeZone -typedef struct objc_object NSTimeZone; -typedef struct {} _objc_exc_NSTimeZone; -#endif - -#ifndef _REWRITER_typedef_NSOrthography -#define _REWRITER_typedef_NSOrthography -typedef struct objc_object NSOrthography; -typedef struct {} _objc_exc_NSOrthography; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -#ifndef _REWRITER_typedef_NSRegularExpression -#define _REWRITER_typedef_NSRegularExpression -typedef struct objc_object NSRegularExpression; -typedef struct {} _objc_exc_NSRegularExpression; -#endif - - - - - - -typedef uint64_t NSTextCheckingType; enum { - NSTextCheckingTypeOrthography = 1ULL << 0, - NSTextCheckingTypeSpelling = 1ULL << 1, - NSTextCheckingTypeGrammar = 1ULL << 2, - NSTextCheckingTypeDate = 1ULL << 3, - NSTextCheckingTypeAddress = 1ULL << 4, - NSTextCheckingTypeLink = 1ULL << 5, - NSTextCheckingTypeQuote = 1ULL << 6, - NSTextCheckingTypeDash = 1ULL << 7, - NSTextCheckingTypeReplacement = 1ULL << 8, - NSTextCheckingTypeCorrection = 1ULL << 9, - NSTextCheckingTypeRegularExpression __attribute__((availability(macosx,introduced=10_7))) = 1ULL << 10, - NSTextCheckingTypePhoneNumber __attribute__((availability(macosx,introduced=10_7))) = 1ULL << 11, - NSTextCheckingTypeTransitInformation __attribute__((availability(macosx,introduced=10_7))) = 1ULL << 12 -}; - -typedef uint64_t NSTextCheckingTypes; -enum { - NSTextCheckingAllSystemTypes = 0xffffffffULL, - NSTextCheckingAllCustomTypes = 0xffffffffULL << 32, - NSTextCheckingAllTypes = (NSTextCheckingAllSystemTypes | NSTextCheckingAllCustomTypes) -}; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_6))) - -#ifndef _REWRITER_typedef_NSTextCheckingResult -#define _REWRITER_typedef_NSTextCheckingResult -typedef struct objc_object NSTextCheckingResult; -typedef struct {} _objc_exc_NSTextCheckingResult; -#endif - -struct NSTextCheckingResult_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - -// @property (readonly) NSTextCheckingType resultType; -// @property (readonly) NSRange range; - -/* @end */ - - -// @interface NSTextCheckingResult (NSTextCheckingResultOptional) - - -// @property (nullable, readonly, copy) NSOrthography *orthography; -// @property (nullable, readonly, copy) NSArray<NSString *> *grammarDetails; -// @property (nullable, readonly, copy) NSDate *date; -// @property (nullable, readonly, copy) NSTimeZone *timeZone; -// @property (readonly) NSTimeInterval duration; -// @property (nullable, readonly, copy) NSDictionary<NSString *, NSString *> *components __attribute__((availability(macosx,introduced=10_7))); -// @property (nullable, readonly, copy) NSURL *URL; -// @property (nullable, readonly, copy) NSString *replacementString; -// @property (nullable, readonly, copy) NSArray<NSString *> *alternativeStrings __attribute__((availability(macosx,introduced=10_9))); -// @property (nullable, readonly, copy) NSRegularExpression *regularExpression __attribute__((availability(macosx,introduced=10_7))); -// @property (nullable, readonly, copy) NSString *phoneNumber __attribute__((availability(macosx,introduced=10_7))); - -// @property (nullable, readonly, copy) NSDictionary<NSString *, NSString *> *addressComponents; - - -// @property (readonly) NSUInteger numberOfRanges __attribute__((availability(macosx,introduced=10_7))); -// - (NSRange)rangeAtIndex:(NSUInteger)idx __attribute__((availability(macosx,introduced=10_7))); -// - (NSTextCheckingResult *)resultByAdjustingRangesWithOffset:(NSInteger)offset __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - - - - -extern "C" NSString * const NSTextCheckingNameKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSTextCheckingJobTitleKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSTextCheckingOrganizationKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSTextCheckingStreetKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSTextCheckingCityKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSTextCheckingStateKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSTextCheckingZIPKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSTextCheckingCountryKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSTextCheckingPhoneKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSTextCheckingAirlineKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSTextCheckingFlightKey __attribute__((availability(macosx,introduced=10_7))); - - -// @interface NSTextCheckingResult (NSTextCheckingResultCreation) - - -// + (NSTextCheckingResult *)orthographyCheckingResultWithRange:(NSRange)range orthography:(NSOrthography *)orthography; -// + (NSTextCheckingResult *)spellCheckingResultWithRange:(NSRange)range; -// + (NSTextCheckingResult *)grammarCheckingResultWithRange:(NSRange)range details:(NSArray<NSString *> *)details; -// + (NSTextCheckingResult *)dateCheckingResultWithRange:(NSRange)range date:(NSDate *)date; -// + (NSTextCheckingResult *)dateCheckingResultWithRange:(NSRange)range date:(NSDate *)date timeZone:(NSTimeZone *)timeZone duration:(NSTimeInterval)duration; -// + (NSTextCheckingResult *)addressCheckingResultWithRange:(NSRange)range components:(NSDictionary<NSString *, NSString *> *)components; -// + (NSTextCheckingResult *)linkCheckingResultWithRange:(NSRange)range URL:(NSURL *)url; -// + (NSTextCheckingResult *)quoteCheckingResultWithRange:(NSRange)range replacementString:(NSString *)replacementString; -// + (NSTextCheckingResult *)dashCheckingResultWithRange:(NSRange)range replacementString:(NSString *)replacementString; -// + (NSTextCheckingResult *)replacementCheckingResultWithRange:(NSRange)range replacementString:(NSString *)replacementString; -// + (NSTextCheckingResult *)correctionCheckingResultWithRange:(NSRange)range replacementString:(NSString *)replacementString; -// + (NSTextCheckingResult *)correctionCheckingResultWithRange:(NSRange)range replacementString:(NSString *)replacementString alternativeStrings:(NSArray<NSString *> *)alternativeStrings __attribute__((availability(macosx,introduced=10_9))); -// + (NSTextCheckingResult *)regularExpressionCheckingResultWithRanges:(NSRangePointer)ranges count:(NSUInteger)count regularExpression:(NSRegularExpression *)regularExpression __attribute__((availability(macosx,introduced=10_7))); -// + (NSTextCheckingResult *)phoneNumberCheckingResultWithRange:(NSRange)range phoneNumber:(NSString *)phoneNumber __attribute__((availability(macosx,introduced=10_7))); -// + (NSTextCheckingResult *)transitInformationCheckingResultWithRange:(NSRange)range components:(NSDictionary<NSString *, NSString *> *)components __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - - - - - - - -typedef NSUInteger NSRegularExpressionOptions; enum { - NSRegularExpressionCaseInsensitive = 1 << 0, - NSRegularExpressionAllowCommentsAndWhitespace = 1 << 1, - NSRegularExpressionIgnoreMetacharacters = 1 << 2, - NSRegularExpressionDotMatchesLineSeparators = 1 << 3, - NSRegularExpressionAnchorsMatchLines = 1 << 4, - NSRegularExpressionUseUnixLineSeparators = 1 << 5, - NSRegularExpressionUseUnicodeWordBoundaries = 1 << 6 -}; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSRegularExpression -#define _REWRITER_typedef_NSRegularExpression -typedef struct objc_object NSRegularExpression; -typedef struct {} _objc_exc_NSRegularExpression; -#endif - -struct NSRegularExpression_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSString *_pattern; - NSUInteger _options; - void *_internal; - id _reserved1; - int32_t _checkout; - int32_t _reserved2; -}; - - - - -// + (nullable NSRegularExpression *)regularExpressionWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error; -// - (nullable instancetype)initWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error __attribute__((objc_designated_initializer)); - -// @property (readonly, copy) NSString *pattern; -// @property (readonly) NSRegularExpressionOptions options; -// @property (readonly) NSUInteger numberOfCaptureGroups; - - - -// + (NSString *)escapedPatternForString:(NSString *)string; - -/* @end */ - - - -typedef NSUInteger NSMatchingOptions; enum { - NSMatchingReportProgress = 1 << 0, - NSMatchingReportCompletion = 1 << 1, - NSMatchingAnchored = 1 << 2, - NSMatchingWithTransparentBounds = 1 << 3, - NSMatchingWithoutAnchoringBounds = 1 << 4 -}; - -typedef NSUInteger NSMatchingFlags; enum { - NSMatchingProgress = 1 << 0, - NSMatchingCompleted = 1 << 1, - NSMatchingHitEnd = 1 << 2, - NSMatchingRequiredEnd = 1 << 3, - NSMatchingInternalError = 1 << 4 -}; - -// @interface NSRegularExpression (NSMatching) - - - - -// - (void)enumerateMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range usingBlock:(void (^)(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL *stop))block; - -// - (NSArray<NSTextCheckingResult *> *)matchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range; -// - (NSUInteger)numberOfMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range; -// - (nullable NSTextCheckingResult *)firstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range; -// - (NSRange)rangeOfFirstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range; -/* @end */ - - - -// @interface NSRegularExpression (NSReplacement) - - - -// - (NSString *)stringByReplacingMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)templ; -// - (NSUInteger)replaceMatchesInString:(NSMutableString *)string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)templ; - - - -// - (NSString *)replacementStringForResult:(NSTextCheckingResult *)result inString:(NSString *)string offset:(NSInteger)offset template:(NSString *)templ; - - - -// + (NSString *)escapedTemplateForString:(NSString *)string; - -/* @end */ - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSDataDetector -#define _REWRITER_typedef_NSDataDetector -typedef struct objc_object NSDataDetector; -typedef struct {} _objc_exc_NSDataDetector; -#endif - -struct NSDataDetector_IMPL { - struct NSRegularExpression_IMPL NSRegularExpression_IVARS; - NSTextCheckingTypes _types; -}; - - - - -// + (nullable NSDataDetector *)dataDetectorWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error; -// - (nullable instancetype)initWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error __attribute__((objc_designated_initializer)); - -// @property (readonly) NSTextCheckingTypes checkingTypes; - -/* @end */ - - - - - - - - - -// @class NSTimer; -#ifndef _REWRITER_typedef_NSTimer -#define _REWRITER_typedef_NSTimer -typedef struct objc_object NSTimer; -typedef struct {} _objc_exc_NSTimer; -#endif - -#ifndef _REWRITER_typedef_NSPort -#define _REWRITER_typedef_NSPort -typedef struct objc_object NSPort; -typedef struct {} _objc_exc_NSPort; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -extern "C" NSString * const NSDefaultRunLoopMode; -extern "C" NSString * const NSRunLoopCommonModes __attribute__((availability(macosx,introduced=10_5))); - - -#ifndef _REWRITER_typedef_NSRunLoop -#define _REWRITER_typedef_NSRunLoop -typedef struct objc_object NSRunLoop; -typedef struct {} _objc_exc_NSRunLoop; -#endif - -struct NSRunLoop_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _rl; - id _dperf; - id _perft; - id _info; - id _ports; - void *_reserved[6]; -}; - - -// + (NSRunLoop *)currentRunLoop; -// + (NSRunLoop *)mainRunLoop __attribute__((availability(macosx,introduced=10_5))); - -// @property (nullable, readonly, copy) NSString *currentMode; - -// - (CFRunLoopRef)getCFRunLoop __attribute__((cf_returns_not_retained)); - -// - (void)addTimer:(NSTimer *)timer forMode:(NSString *)mode; - -// - (void)addPort:(NSPort *)aPort forMode:(NSString *)mode; -// - (void)removePort:(NSPort *)aPort forMode:(NSString *)mode; - -// - (nullable NSDate *)limitDateForMode:(NSString *)mode; -// - (void)acceptInputForMode:(NSString *)mode beforeDate:(NSDate *)limitDate; - -/* @end */ - - -// @interface NSRunLoop (NSRunLoopConveniences) - -// - (void)run; -// - (void)runUntilDate:(NSDate *)limitDate; -// - (BOOL)runMode:(NSString *)mode beforeDate:(NSDate *)limitDate; - - -// - (void)configureAsServer __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - - -/* @end */ - - - - -// @interface NSObject (NSDelayedPerforming) - -// - (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray<NSString *> *)modes; -// - (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay; -// + (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(nullable id)anArgument; -// + (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget; - -/* @end */ - - -// @interface NSRunLoop (NSOrderedPerform) - -// - (void)performSelector:(SEL)aSelector target:(id)target argument:(nullable id)arg order:(NSUInteger)order modes:(NSArray<NSString *> *)modes; -// - (void)cancelPerformSelector:(SEL)aSelector target:(id)target argument:(nullable id)arg; -// - (void)cancelPerformSelectorsWithTarget:(id)target; - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSSortDescriptor -#define _REWRITER_typedef_NSSortDescriptor -typedef struct objc_object NSSortDescriptor; -typedef struct {} _objc_exc_NSSortDescriptor; -#endif - -struct NSSortDescriptor_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSUInteger _sortDescriptorFlags; - NSString *_key; - SEL _selector; - id _selectorOrBlock; -}; - - -// + (instancetype)sortDescriptorWithKey:(nullable NSString *)key ascending:(BOOL)ascending __attribute__((availability(macosx,introduced=10_6))); -// + (instancetype)sortDescriptorWithKey:(nullable NSString *)key ascending:(BOOL)ascending selector:(nullable SEL)selector __attribute__((availability(macosx,introduced=10_6))); - - -// - (instancetype)initWithKey:(nullable NSString *)key ascending:(BOOL)ascending; -// - (instancetype)initWithKey:(nullable NSString *)key ascending:(BOOL)ascending selector:(nullable SEL)selector; -// - (nullable instancetype)initWithCoder:(NSCoder *)coder; - -// @property (nullable, readonly, copy) NSString *key; -// @property (readonly) BOOL ascending; -// @property (nullable, readonly) SEL selector; - -// - (void)allowEvaluation __attribute__((availability(macosx,introduced=10_9))); - -// + (instancetype)sortDescriptorWithKey:(nullable NSString *)key ascending:(BOOL)ascending comparator:(NSComparator)cmptr __attribute__((availability(macosx,introduced=10_6))); - -// - (instancetype)initWithKey:(nullable NSString *)key ascending:(BOOL)ascending comparator:(NSComparator)cmptr __attribute__((availability(macosx,introduced=10_6))); - -// @property (readonly) NSComparator comparator __attribute__((availability(macosx,introduced=10_6))); - -// - (NSComparisonResult)compareObject:(id)object1 toObject:(id)object2; -// @property (readonly, retain) id reversedSortDescriptor; - -/* @end */ - - -// @interface NSSet<ObjectType> (NSSortDescriptorSorting) - -// - (NSArray<ObjectType> *)sortedArrayUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -// @interface NSArray<ObjectType> (NSSortDescriptorSorting) - -// - (NSArray<ObjectType> *)sortedArrayUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors; - -/* @end */ - - -// @interface NSMutableArray<ObjectType> (NSSortDescriptorSorting) - -// - (void)sortUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors; - -/* @end */ - - -// @interface NSOrderedSet<ObjectType> (NSKeyValueSorting) - - -// - (NSArray<ObjectType> *)sortedArrayUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - -// @interface NSMutableOrderedSet<ObjectType> (NSKeyValueSorting) - - -// - (void)sortUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - - - - - - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSHost -#define _REWRITER_typedef_NSHost -typedef struct objc_object NSHost; -typedef struct {} _objc_exc_NSHost; -#endif - -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -#ifndef _REWRITER_typedef_NSOutputStream -#define _REWRITER_typedef_NSOutputStream -typedef struct objc_object NSOutputStream; -typedef struct {} _objc_exc_NSOutputStream; -#endif - -#ifndef _REWRITER_typedef_NSRunLoop -#define _REWRITER_typedef_NSRunLoop -typedef struct objc_object NSRunLoop; -typedef struct {} _objc_exc_NSRunLoop; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -// @protocol NSStreamDelegate; - - - -typedef NSUInteger NSStreamStatus; enum { - NSStreamStatusNotOpen = 0, - NSStreamStatusOpening = 1, - NSStreamStatusOpen = 2, - NSStreamStatusReading = 3, - NSStreamStatusWriting = 4, - NSStreamStatusAtEnd = 5, - NSStreamStatusClosed = 6, - NSStreamStatusError = 7 -}; - -typedef NSUInteger NSStreamEvent; enum { - NSStreamEventNone = 0, - NSStreamEventOpenCompleted = 1UL << 0, - NSStreamEventHasBytesAvailable = 1UL << 1, - NSStreamEventHasSpaceAvailable = 1UL << 2, - NSStreamEventErrorOccurred = 1UL << 3, - NSStreamEventEndEncountered = 1UL << 4 -}; - - - - -#ifndef _REWRITER_typedef_NSStream -#define _REWRITER_typedef_NSStream -typedef struct objc_object NSStream; -typedef struct {} _objc_exc_NSStream; -#endif - -struct NSStream_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - -// - (void)open; -// - (void)close; - -// @property (nullable, assign) id <NSStreamDelegate> delegate; - - -// - (nullable id)propertyForKey:(NSString *)key; -// - (BOOL)setProperty:(nullable id)property forKey:(NSString *)key; - -// - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; -// - (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; - -// @property (readonly) NSStreamStatus streamStatus; -// @property (nullable, readonly, copy) NSError *streamError; -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -struct NSInputStream_IMPL { - struct NSStream_IMPL NSStream_IVARS; -}; - -// - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len; - - -// - (BOOL)getBuffer:(uint8_t * _Nullable * _Nonnull)buffer length:(NSUInteger *)len; - - -// @property (readonly) BOOL hasBytesAvailable; - - -// - (instancetype)initWithData:(NSData *)data __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithURL:(NSURL *)url __attribute__((availability(macosx,introduced=10_6))) __attribute__((objc_designated_initializer)); - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSOutputStream -#define _REWRITER_typedef_NSOutputStream -typedef struct objc_object NSOutputStream; -typedef struct {} _objc_exc_NSOutputStream; -#endif - -struct NSOutputStream_IMPL { - struct NSStream_IMPL NSStream_IVARS; -}; - -// - (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)len; - - -// @property (readonly) BOOL hasSpaceAvailable; - - -// - (instancetype)initToMemory __attribute__((objc_designated_initializer)); -// - (instancetype)initToBuffer:(uint8_t *)buffer capacity:(NSUInteger)capacity __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithURL:(NSURL *)url append:(BOOL)shouldAppend __attribute__((availability(macosx,introduced=10_6))) __attribute__((objc_designated_initializer)); - -/* @end */ - - - -// @interface NSStream (NSSocketStreamCreationExtensions) - -// + (void)getStreamsToHostWithName:(NSString *)hostname port:(NSInteger)port inputStream:(NSInputStream * _Nullable * _Nullable)inputStream outputStream:(NSOutputStream * _Nullable * _Nullable)outputStream __attribute__((availability(macosx,introduced=10_10))); - - -// + (void)getStreamsToHost:(NSHost *)host port:(NSInteger)port inputStream:(NSInputStream * _Nullable * _Nullable)inputStream outputStream:(NSOutputStream * _Nullable * _Nullable)outputStream __attribute__((availability(macosx,introduced=10_3,deprecated=10_10,message="" "Please use getStreamsToHostWithName:port:inputStream:outputStream: instead"))); - - -/* @end */ - - -// @interface NSStream (NSStreamBoundPairCreationExtensions) -// + (void)getBoundStreamsWithBufferSize:(NSUInteger)bufferSize inputStream:(NSInputStream * _Nullable * _Nullable)inputStream outputStream:(NSOutputStream * _Nullable * _Nullable)outputStream __attribute__((availability(macosx,introduced=10_10))); -/* @end */ - - - -// @interface NSInputStream (NSInputStreamExtensions) -// - (nullable instancetype)initWithFileAtPath:(NSString *)path; - -// + (nullable instancetype)inputStreamWithData:(NSData *)data; -// + (nullable instancetype)inputStreamWithFileAtPath:(NSString *)path; -// + (nullable instancetype)inputStreamWithURL:(NSURL *)url __attribute__((availability(macosx,introduced=10_6))); -/* @end */ - - - -// @interface NSOutputStream (NSOutputStreamExtensions) -// - (nullable instancetype)initToFileAtPath:(NSString *)path append:(BOOL)shouldAppend; - -// + (instancetype)outputStreamToMemory; -// + (instancetype)outputStreamToBuffer:(uint8_t *)buffer capacity:(NSUInteger)capacity; -// + (instancetype)outputStreamToFileAtPath:(NSString *)path append:(BOOL)shouldAppend; -// + (nullable instancetype)outputStreamWithURL:(NSURL *)url append:(BOOL)shouldAppend __attribute__((availability(macosx,introduced=10_6))); -/* @end */ - - -// @protocol NSStreamDelegate <NSObject> -/* @optional */ -// - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode; -/* @end */ - - - - -extern "C" NSString * const NSStreamSocketSecurityLevelKey __attribute__((availability(macosx,introduced=10_3))); - -extern "C" NSString * const NSStreamSocketSecurityLevelNone __attribute__((availability(macosx,introduced=10_3))); -extern "C" NSString * const NSStreamSocketSecurityLevelSSLv2 __attribute__((availability(macosx,introduced=10_3))); -extern "C" NSString * const NSStreamSocketSecurityLevelSSLv3 __attribute__((availability(macosx,introduced=10_3))); -extern "C" NSString * const NSStreamSocketSecurityLevelTLSv1 __attribute__((availability(macosx,introduced=10_3))); -extern "C" NSString * const NSStreamSocketSecurityLevelNegotiatedSSL __attribute__((availability(macosx,introduced=10_3))); - -extern "C" NSString * const NSStreamSOCKSProxyConfigurationKey __attribute__((availability(macosx,introduced=10_3))); - -extern "C" NSString * const NSStreamSOCKSProxyHostKey __attribute__((availability(macosx,introduced=10_3))); - -extern "C" NSString * const NSStreamSOCKSProxyPortKey __attribute__((availability(macosx,introduced=10_3))); - -extern "C" NSString * const NSStreamSOCKSProxyVersionKey __attribute__((availability(macosx,introduced=10_3))); - -extern "C" NSString * const NSStreamSOCKSProxyUserKey __attribute__((availability(macosx,introduced=10_3))); - -extern "C" NSString * const NSStreamSOCKSProxyPasswordKey __attribute__((availability(macosx,introduced=10_3))); - - -extern "C" NSString * const NSStreamSOCKSProxyVersion4 __attribute__((availability(macosx,introduced=10_3))); - -extern "C" NSString * const NSStreamSOCKSProxyVersion5 __attribute__((availability(macosx,introduced=10_3))); - - -extern "C" NSString * const NSStreamDataWrittenToMemoryStreamKey __attribute__((availability(macosx,introduced=10_3))); - - -extern "C" NSString * const NSStreamFileCurrentOffsetKey __attribute__((availability(macosx,introduced=10_3))); - - - -extern "C" NSString * const NSStreamSocketSSLErrorDomain __attribute__((availability(macosx,introduced=10_3))); - -extern "C" NSString * const NSStreamSOCKSErrorDomain __attribute__((availability(macosx,introduced=10_3))); - - - - - - -extern "C" NSString * const NSStreamNetworkServiceType __attribute__((availability(macosx,introduced=10_7))); - -extern "C" NSString * const NSStreamNetworkServiceTypeVoIP __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSStreamNetworkServiceTypeVideo __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSStreamNetworkServiceTypeBackground __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSStreamNetworkServiceTypeVoice __attribute__((availability(macosx,introduced=10_7))); - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - -#ifndef _REWRITER_typedef_NSThread -#define _REWRITER_typedef_NSThread -typedef struct objc_object NSThread; -typedef struct {} _objc_exc_NSThread; -#endif - -struct NSThread_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _private; - uint8_t _bytes[44]; -}; - - -// + (NSThread *)currentThread; - -// + (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument; - -// + (BOOL)isMultiThreaded; - -// @property (readonly, retain) NSMutableDictionary *threadDictionary; - -// + (void)sleepUntilDate:(NSDate *)date; -// + (void)sleepForTimeInterval:(NSTimeInterval)ti; - -// + (void)exit; - -// + (double)threadPriority; -// + (BOOL)setThreadPriority:(double)p; - -// @property double threadPriority __attribute__((availability(macosx,introduced=10_6))); - -// @property NSQualityOfService qualityOfService __attribute__((availability(macosx,introduced=10_10))); - -// + (NSArray<NSNumber *> *)callStackReturnAddresses __attribute__((availability(macosx,introduced=10_5))); -// + (NSArray<NSString *> *)callStackSymbols __attribute__((availability(macosx,introduced=10_6))); - -// @property (nullable, copy) NSString *name __attribute__((availability(macosx,introduced=10_5))); - -// @property NSUInteger stackSize __attribute__((availability(macosx,introduced=10_5))); - -// @property (readonly) BOOL isMainThread __attribute__((availability(macosx,introduced=10_5))); -// + (BOOL)isMainThread __attribute__((availability(macosx,introduced=10_5))); -// + (NSThread *)mainThread __attribute__((availability(macosx,introduced=10_5))); - -// - (instancetype)init __attribute__((availability(macosx,introduced=10_5))) __attribute__((objc_designated_initializer)); -// - (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument __attribute__((availability(macosx,introduced=10_5))); - -// @property (readonly, getter=isExecuting) BOOL executing __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly, getter=isFinished) BOOL finished __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly, getter=isCancelled) BOOL cancelled __attribute__((availability(macosx,introduced=10_5))); - -// - (void)cancel __attribute__((availability(macosx,introduced=10_5))); - -// - (void)start __attribute__((availability(macosx,introduced=10_5))); - -// - (void)main __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - -extern "C" NSString * const NSWillBecomeMultiThreadedNotification; -extern "C" NSString * const NSDidBecomeSingleThreadedNotification; -extern "C" NSString * const NSThreadWillExitNotification; - -// @interface NSObject (NSThreadPerformAdditions) - -// - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array; -// - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait; - - -// - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array __attribute__((availability(macosx,introduced=10_5))); -// - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait __attribute__((availability(macosx,introduced=10_5))); - -// - (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSLocale -#define _REWRITER_typedef_NSLocale -typedef struct objc_object NSLocale; -typedef struct {} _objc_exc_NSLocale; -#endif - - - - - -#ifndef _REWRITER_typedef_NSTimeZone -#define _REWRITER_typedef_NSTimeZone -typedef struct objc_object NSTimeZone; -typedef struct {} _objc_exc_NSTimeZone; -#endif - -struct NSTimeZone_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly, copy) NSString *name; -// @property (readonly, copy) NSData *data; - -// - (NSInteger)secondsFromGMTForDate:(NSDate *)aDate; -// - (nullable NSString *)abbreviationForDate:(NSDate *)aDate; -// - (BOOL)isDaylightSavingTimeForDate:(NSDate *)aDate; -// - (NSTimeInterval)daylightSavingTimeOffsetForDate:(NSDate *)aDate __attribute__((availability(macosx,introduced=10_5))); -// - (nullable NSDate *)nextDaylightSavingTimeTransitionAfterDate:(NSDate *)aDate __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - -// @interface NSTimeZone (NSExtendedTimeZone) - -// + (NSTimeZone *)systemTimeZone; -// + (void)resetSystemTimeZone; - -// + (NSTimeZone *)defaultTimeZone; -// + (void)setDefaultTimeZone:(NSTimeZone *)aTimeZone; - -// + (NSTimeZone *)localTimeZone; - -// + (NSArray<NSString *> *)knownTimeZoneNames; - -// + (NSDictionary<NSString *, NSString *> *)abbreviationDictionary; -// + (void)setAbbreviationDictionary:(NSDictionary<NSString *, NSString *> *)dict __attribute__((availability(macosx,introduced=10_6))); - -// + (NSString *)timeZoneDataVersion __attribute__((availability(macosx,introduced=10_6))); - -// @property (readonly) NSInteger secondsFromGMT; -// @property (nullable, readonly, copy) NSString *abbreviation; -// @property (readonly, getter=isDaylightSavingTime) BOOL daylightSavingTime; -// @property (readonly) NSTimeInterval daylightSavingTimeOffset __attribute__((availability(macosx,introduced=10_5))); -// @property (nullable, readonly, copy) NSDate *nextDaylightSavingTimeTransition __attribute__((availability(macosx,introduced=10_5))); - -// @property (readonly, copy) NSString *description; - -// - (BOOL)isEqualToTimeZone:(NSTimeZone *)aTimeZone; - -typedef NSInteger NSTimeZoneNameStyle; enum { - NSTimeZoneNameStyleStandard, - NSTimeZoneNameStyleShortStandard, - NSTimeZoneNameStyleDaylightSaving, - NSTimeZoneNameStyleShortDaylightSaving, - NSTimeZoneNameStyleGeneric, - NSTimeZoneNameStyleShortGeneric -}; - -// - (nullable NSString *)localizedName:(NSTimeZoneNameStyle)style locale:(nullable NSLocale *)locale __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - -// @interface NSTimeZone (NSTimeZoneCreation) - - - - -// + (nullable instancetype)timeZoneWithName:(NSString *)tzName; -// + (nullable instancetype)timeZoneWithName:(NSString *)tzName data:(nullable NSData *)aData; - -// - (nullable instancetype)initWithName:(NSString *)tzName; -// - (nullable instancetype)initWithName:(NSString *)tzName data:(nullable NSData *)aData; - - - - -// + (instancetype)timeZoneForSecondsFromGMT:(NSInteger)seconds; - -// + (nullable instancetype)timeZoneWithAbbreviation:(NSString *)abbreviation; - -/* @end */ - - -extern "C" NSString * const NSSystemTimeZoneDidChangeNotification __attribute__((availability(macosx,introduced=10_5))); - -#ifndef _REWRITER_typedef_NSTimer -#define _REWRITER_typedef_NSTimer -typedef struct objc_object NSTimer; -typedef struct {} _objc_exc_NSTimer; -#endif - -struct NSTimer_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo; -// + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo; - -// + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo; -// + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo; - -// - (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(nullable id)ui repeats:(BOOL)rep __attribute__((objc_designated_initializer)); - -// - (void)fire; - -// @property (copy) NSDate *fireDate; -// @property (readonly) NSTimeInterval timeInterval; - - - -// @property NSTimeInterval tolerance __attribute__((availability(macosx,introduced=10_9))); - -// - (void)invalidate; -// @property (readonly, getter=isValid) BOOL valid; - -// @property (nullable, readonly, retain) id userInfo; - -/* @end */ - - - - - - - - - - - - - - - - - -// @class NSURLHandle; -#ifndef _REWRITER_typedef_NSURLHandle -#define _REWRITER_typedef_NSURLHandle -typedef struct objc_object NSURLHandle; -typedef struct {} _objc_exc_NSURLHandle; -#endif - -#ifndef _REWRITER_typedef_NSMutableArray -#define _REWRITER_typedef_NSMutableArray -typedef struct objc_object NSMutableArray; -typedef struct {} _objc_exc_NSMutableArray; -#endif - -#ifndef _REWRITER_typedef_NSMutableData -#define _REWRITER_typedef_NSMutableData -typedef struct objc_object NSMutableData; -typedef struct {} _objc_exc_NSMutableData; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - - - -extern "C" NSString *NSHTTPPropertyStatusCodeKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -extern "C" NSString *NSHTTPPropertyStatusReasonKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -extern "C" NSString *NSHTTPPropertyServerHTTPVersionKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -extern "C" NSString *NSHTTPPropertyRedirectionHeadersKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -extern "C" NSString *NSHTTPPropertyErrorPageDataKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -extern "C" NSString *NSHTTPPropertyHTTPProxy __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); - - - - - -extern "C" NSString *NSFTPPropertyUserLoginKey __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); -extern "C" NSString *NSFTPPropertyUserPasswordKey __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); -extern "C" NSString *NSFTPPropertyActiveTransferModeKey __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); -extern "C" NSString *NSFTPPropertyFileOffsetKey __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); - - - -extern "C" NSString *NSFTPPropertyFTPProxy __attribute__((availability(macosx,introduced=10_3,deprecated=10_4,message="" ))); - - - -typedef NSUInteger NSURLHandleStatus; enum { - NSURLHandleNotLoaded = 0, - NSURLHandleLoadSucceeded, - NSURLHandleLoadInProgress, - NSURLHandleLoadFailed -}; - -// @protocol NSURLHandleClient -// - (void)URLHandle:(NSURLHandle *)sender resourceDataDidBecomeAvailable:(NSData *)newBytes __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)URLHandleResourceDidBeginLoading:(NSURLHandle *)sender __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)URLHandleResourceDidFinishLoading:(NSURLHandle *)sender __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)URLHandleResourceDidCancelLoading:(NSURLHandle *)sender __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)URLHandle:(NSURLHandle *)sender resourceDidFailLoadingWithReason:(NSString *)reason __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -/* @end */ - - - -#ifndef _REWRITER_typedef_NSURLHandle -#define _REWRITER_typedef_NSURLHandle -typedef struct objc_object NSURLHandle; -typedef struct {} _objc_exc_NSURLHandle; -#endif - -struct NSURLHandle_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSMutableArray *_clients; - id _data; - NSURLHandleStatus _status; - NSInteger _reserved; -}; - - -// + (void)registerURLHandleClass:(Class)anURLHandleSubclass __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// + (Class)URLHandleClassForURL:(NSURL *)anURL __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (NSURLHandleStatus)status __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (NSString *)failureReason __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (void)addClient:(id <NSURLHandleClient>)client __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)removeClient:(id <NSURLHandleClient>)client __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (void)loadInBackground __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)cancelLoadInBackground __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (NSData *)resourceData __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (NSData *)availableResourceData __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (long long) expectedResourceDataSize __attribute__((availability(macosx,introduced=10_3,deprecated=10_4,message="" ))); - -// - (void)flushCachedData __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - - -// - (void)backgroundLoadDidFailWithReason:(NSString *)reason __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)didLoadBytes:(NSData *)newBytes loadComplete:(BOOL)yorn __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - - -// + (BOOL)canInitWithURL:(NSURL *)anURL __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// + (NSURLHandle *)cachedHandleForURL:(NSURL *)anURL __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - initWithURL:(NSURL *)anURL cached:(BOOL)willCache __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (id)propertyForKey:(NSString *)propertyKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (id)propertyForKeyIfAvailable:(NSString *)propertyKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (BOOL)writeProperty:(id)propertyValue forKey:(NSString *)propertyKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (BOOL)writeData:(NSData *)data __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (NSData *)loadInForeground __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)beginLoadInBackground __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)endLoadInBackground __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -/* @end */ - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - - - - - - - - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -struct NSURL_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSString *_urlString; - NSURL *_baseURL; - void *_clients; - void *_reserved; -}; - - - - - -extern "C" NSString *NSURLFileScheme; - - - - -// - (nullable instancetype)initWithScheme:(NSString *)scheme host:(nullable NSString *)host path:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_11,message="" "Use NSURLComponents instead, which lets you create a valid URL with any valid combination of URL components and subcomponents (not just scheme, host and path), and lets you set components and subcomponents with either percent-encoded or un-percent-encoded strings."))); - - - -// - (instancetype)initFileURLWithPath:(NSString *)path isDirectory:(BOOL)isDir relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_11))) __attribute__((objc_designated_initializer)); - - -// - (instancetype)initFileURLWithPath:(NSString *)path relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_11))) __attribute__((objc_designated_initializer)); - -// - (instancetype)initFileURLWithPath:(NSString *)path isDirectory:(BOOL)isDir __attribute__((availability(macosx,introduced=10_5))) __attribute__((objc_designated_initializer)); -// - (instancetype)initFileURLWithPath:(NSString *)path __attribute__((objc_designated_initializer)); - - - -// + (NSURL *)fileURLWithPath:(NSString *)path isDirectory:(BOOL) isDir relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_11))); - - -// + (NSURL *)fileURLWithPath:(NSString *)path relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_11))); - -// + (NSURL *)fileURLWithPath:(NSString *)path isDirectory:(BOOL)isDir __attribute__((availability(macosx,introduced=10_5))); -// + (NSURL *)fileURLWithPath:(NSString *)path; - - - -// - (instancetype)initFileURLWithFileSystemRepresentation:(const char *)path isDirectory:(BOOL)isDir relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_9))) __attribute__((objc_designated_initializer)); - - - -// + (NSURL *)fileURLWithFileSystemRepresentation:(const char *)path isDirectory:(BOOL) isDir relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_9))); - - - -// - (nullable instancetype)initWithString:(NSString *)URLString; -// - (nullable instancetype)initWithString:(NSString *)URLString relativeToURL:(nullable NSURL *)baseURL __attribute__((objc_designated_initializer)); -// + (nullable instancetype)URLWithString:(NSString *)URLString; -// + (nullable instancetype)URLWithString:(NSString *)URLString relativeToURL:(nullable NSURL *)baseURL; - - - - -// - (instancetype)initWithDataRepresentation:(NSData *)data relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_11))) __attribute__((objc_designated_initializer)); - - -// + (NSURL *)URLWithDataRepresentation:(NSData *)data relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_11))); - - - -// - (instancetype)initAbsoluteURLWithDataRepresentation:(NSData *)data relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_11))) __attribute__((objc_designated_initializer)); - - -// + (NSURL *)absoluteURLWithDataRepresentation:(NSData *)data relativeToURL:(nullable NSURL *)baseURL __attribute__((availability(macosx,introduced=10_11))); - - - -// @property (readonly, copy) NSData *dataRepresentation __attribute__((availability(macosx,introduced=10_11))); - -// @property (readonly, copy) NSString *absoluteString; -// @property (nullable, readonly, copy) NSString *relativeString; -// @property (nullable, readonly, copy) NSURL *baseURL; -// @property (readonly, copy) NSURL *absoluteURL; - - - -// @property (readonly, copy) NSString *scheme; -// @property (readonly, copy) NSString *resourceSpecifier; - - - -// @property (nullable, readonly, copy) NSString *host; -// @property (nullable, readonly, copy) NSNumber *port; -// @property (nullable, readonly, copy) NSString *user; -// @property (nullable, readonly, copy) NSString *password; -// @property (nullable, readonly, copy) NSString *path; -// @property (nullable, readonly, copy) NSString *fragment; -// @property (nullable, readonly, copy) NSString *parameterString; -// @property (nullable, readonly, copy) NSString *query; -// @property (nullable, readonly, copy) NSString *relativePath; - - - -// @property (readonly) BOOL hasDirectoryPath __attribute__((availability(macosx,introduced=10_11))); - - - -// - (BOOL)getFileSystemRepresentation:(char *)buffer maxLength:(NSUInteger)maxBufferLength __attribute__((availability(macosx,introduced=10_9))); - - - -// @property (readonly) __attribute__((objc_ownership(strong))) const char *fileSystemRepresentation __attribute__((objc_returns_inner_pointer)) __attribute__((availability(macosx,introduced=10_9))); - -// @property (readonly, getter=isFileURL) BOOL fileURL; - -// @property (nullable, readonly, copy) NSURL *standardizedURL; - - - - -// - (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error __attribute__((swift_error(none))) __attribute__((availability(macosx,introduced=10_6))); - - - - - - - -// - (BOOL)isFileReferenceURL __attribute__((availability(macosx,introduced=10_6))); - - - -// - (nullable NSURL *)fileReferenceURL __attribute__((availability(macosx,introduced=10_6))); - - - -// @property (nullable, readonly, copy) NSURL *filePathURL __attribute__((availability(macosx,introduced=10_6))); -// - (BOOL)getResourceValue:(out id _Nullable * _Nonnull)value forKey:(NSString *)key error:(out NSError ** _Nullable)error __attribute__((availability(macosx,introduced=10_6))); - - - -// - (nullable NSDictionary<NSString *, id> *)resourceValuesForKeys:(NSArray<NSString *> *)keys error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// - (BOOL)setResourceValue:(nullable id)value forKey:(NSString *)key error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// - (BOOL)setResourceValues:(NSDictionary<NSString *, id> *)keyedValues error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - -extern "C" NSString * const NSURLKeysOfUnsetValuesKey __attribute__((availability(macosx,introduced=10_7))); - - - -// - (void)removeCachedResourceValueForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_9))); - - - -// - (void)removeAllCachedResourceValues __attribute__((availability(macosx,introduced=10_9))); - - - -// - (void)setTemporaryResourceValue:(nullable id)value forKey:(NSString *)key __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSURLNameKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLLocalizedNameKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLIsRegularFileKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLIsDirectoryKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLIsSymbolicLinkKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLIsVolumeKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLIsPackageKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLIsApplicationKey __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSURLApplicationIsScriptableKey __attribute__((availability(macosx,introduced=10_11))); -extern "C" NSString * const NSURLIsSystemImmutableKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLIsUserImmutableKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLIsHiddenKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLHasHiddenExtensionKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLCreationDateKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLContentAccessDateKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLContentModificationDateKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLAttributeModificationDateKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLLinkCountKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLParentDirectoryURLKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeURLKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLTypeIdentifierKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLLocalizedTypeDescriptionKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLLabelNumberKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLLabelColorKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLLocalizedLabelKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLEffectiveIconKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLCustomIconKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLFileResourceIdentifierKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeIdentifierKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLPreferredIOBlockSizeKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLIsReadableKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLIsWritableKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLIsExecutableKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLFileSecurityKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLIsExcludedFromBackupKey __attribute__((availability(macosx,introduced=10_8))); -extern "C" NSString * const NSURLTagNamesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSURLPathKey __attribute__((availability(macosx,introduced=10_8))); -extern "C" NSString * const NSURLIsMountTriggerKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLGenerationIdentifierKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSURLDocumentIdentifierKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSURLAddedToDirectoryDateKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSURLQuarantinePropertiesKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSURLFileResourceTypeKey __attribute__((availability(macosx,introduced=10_7))); - - - -extern "C" NSString * const NSURLFileResourceTypeNamedPipe __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLFileResourceTypeCharacterSpecial __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLFileResourceTypeDirectory __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLFileResourceTypeBlockSpecial __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLFileResourceTypeRegular __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLFileResourceTypeSymbolicLink __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLFileResourceTypeSocket __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLFileResourceTypeUnknown __attribute__((availability(macosx,introduced=10_7))); - -extern "C" NSString * const NSURLThumbnailDictionaryKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSURLThumbnailKey __attribute__((availability(macosx,introduced=10_10))); - - - -extern "C" NSString * const NSThumbnail1024x1024SizeKey __attribute__((availability(macosx,introduced=10_10))); - - - -extern "C" NSString * const NSURLFileSizeKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLFileAllocatedSizeKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLTotalFileSizeKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLTotalFileAllocatedSizeKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLIsAliasFileKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLFileProtectionKey __attribute__((availability(macosx,unavailable))); - - - -extern "C" NSString * const NSURLFileProtectionNone __attribute__((availability(macosx,unavailable))); -extern "C" NSString * const NSURLFileProtectionComplete __attribute__((availability(macosx,unavailable))); -extern "C" NSString * const NSURLFileProtectionCompleteUnlessOpen __attribute__((availability(macosx,unavailable))); -extern "C" NSString * const NSURLFileProtectionCompleteUntilFirstUserAuthentication __attribute__((availability(macosx,unavailable))); - - - - - -extern "C" NSString * const NSURLVolumeLocalizedFormatDescriptionKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeTotalCapacityKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeAvailableCapacityKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeResourceCountKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeSupportsPersistentIDsKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeSupportsSymbolicLinksKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeSupportsHardLinksKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeSupportsJournalingKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeIsJournalingKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeSupportsSparseFilesKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeSupportsZeroRunsKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeSupportsCaseSensitiveNamesKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeSupportsCasePreservedNamesKey __attribute__((availability(macosx,introduced=10_6))); -extern "C" NSString * const NSURLVolumeSupportsRootDirectoryDatesKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeSupportsVolumeSizesKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeSupportsRenamingKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeSupportsAdvisoryFileLockingKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeSupportsExtendedSecurityKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeIsBrowsableKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeMaximumFileSizeKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeIsEjectableKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeIsRemovableKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeIsInternalKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeIsAutomountedKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeIsLocalKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeIsReadOnlyKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeCreationDateKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeURLForRemountingKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeUUIDStringKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeNameKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLVolumeLocalizedNameKey __attribute__((availability(macosx,introduced=10_7))); - - - -extern "C" NSString * const NSURLIsUbiquitousItemKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLUbiquitousItemHasUnresolvedConflictsKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLUbiquitousItemIsDownloadedKey __attribute__((availability(macosx,introduced=10_7,deprecated=10_9,message="" "Use NSURLUbiquitousItemDownloadingStatusKey instead"))); -extern "C" NSString * const NSURLUbiquitousItemIsDownloadingKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLUbiquitousItemIsUploadedKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLUbiquitousItemIsUploadingKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSURLUbiquitousItemPercentDownloadedKey __attribute__((availability(macosx,introduced=10_7,deprecated=10_8,message="" ))); -extern "C" NSString * const NSURLUbiquitousItemPercentUploadedKey __attribute__((availability(macosx,introduced=10_7,deprecated=10_8,message="" ))); -extern "C" NSString * const NSURLUbiquitousItemDownloadingStatusKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSURLUbiquitousItemDownloadingErrorKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSURLUbiquitousItemUploadingErrorKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSURLUbiquitousItemDownloadRequestedKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSURLUbiquitousItemContainerDisplayNameKey __attribute__((availability(macosx,introduced=10_10))); - - - - -extern "C" NSString * const NSURLUbiquitousItemDownloadingStatusNotDownloaded __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSURLUbiquitousItemDownloadingStatusDownloaded __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSURLUbiquitousItemDownloadingStatusCurrent __attribute__((availability(macosx,introduced=10_9))); - - - - -typedef NSUInteger NSURLBookmarkCreationOptions; enum { - NSURLBookmarkCreationPreferFileIDResolution __attribute__((availability(macosx,introduced=10_6,deprecated=10_9,message="" ))) = ( 1UL << 8 ), - NSURLBookmarkCreationMinimalBookmark = ( 1UL << 9 ), - NSURLBookmarkCreationSuitableForBookmarkFile = ( 1UL << 10 ), - NSURLBookmarkCreationWithSecurityScope __attribute__((availability(macosx,introduced=10_7))) = ( 1 << 11 ), - NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess __attribute__((availability(macosx,introduced=10_7))) = ( 1 << 12 ), -} __attribute__((availability(macosx,introduced=10_6))); - -typedef NSUInteger NSURLBookmarkResolutionOptions; enum { - NSURLBookmarkResolutionWithoutUI = ( 1UL << 8 ), - NSURLBookmarkResolutionWithoutMounting = ( 1UL << 9 ), - NSURLBookmarkResolutionWithSecurityScope __attribute__((availability(macosx,introduced=10_7))) = ( 1 << 10 ) -} __attribute__((availability(macosx,introduced=10_6))); - -typedef NSUInteger NSURLBookmarkFileCreationOptions; - - - -// - (nullable NSData *)bookmarkDataWithOptions:(NSURLBookmarkCreationOptions)options includingResourceValuesForKeys:(nullable NSArray<NSString *> *)keys relativeToURL:(nullable NSURL *)relativeURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// - (nullable instancetype)initByResolvingBookmarkData:(NSData *)bookmarkData options:(NSURLBookmarkResolutionOptions)options relativeToURL:(nullable NSURL *)relativeURL bookmarkDataIsStale:(BOOL * _Nullable)isStale error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - -// + (nullable instancetype)URLByResolvingBookmarkData:(NSData *)bookmarkData options:(NSURLBookmarkResolutionOptions)options relativeToURL:(nullable NSURL *)relativeURL bookmarkDataIsStale:(BOOL * _Nullable)isStale error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// + (nullable NSDictionary<NSString *, id> *)resourceValuesForKeys:(NSArray<NSString *> *)keys fromBookmarkData:(NSData *)bookmarkData __attribute__((availability(macosx,introduced=10_6))); - - - -// + (BOOL)writeBookmarkData:(NSData *)bookmarkData toURL:(NSURL *)bookmarkFileURL options:(NSURLBookmarkFileCreationOptions)options error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// + (nullable NSData *)bookmarkDataWithContentsOfURL:(NSURL *)bookmarkFileURL error:(NSError **)error __attribute__((availability(macosx,introduced=10_6))); - - - -// + (nullable instancetype)URLByResolvingAliasFileAtURL:(NSURL *)url options:(NSURLBookmarkResolutionOptions)options error:(NSError **)error __attribute__((availability(macosx,introduced=10_10))); - - - -// - (BOOL)startAccessingSecurityScopedResource __attribute__((availability(macosx,introduced=10_7))); - - - -// - (void)stopAccessingSecurityScopedResource __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - - -// @interface NSURL (NSPromisedItems) -// - (BOOL)getPromisedItemResourceValue:(id _Nullable * _Nonnull)value forKey:(NSString *)key error:(NSError **)error __attribute__((availability(macosx,introduced=10_10))); -// - (nullable NSDictionary<NSString *, id> *)promisedItemResourceValuesForKeys:(NSArray<NSString *> *)keys error:(NSError **)error __attribute__((availability(macosx,introduced=10_10))); -// - (BOOL)checkPromisedItemIsReachableAndReturnError:(NSError **)error __attribute__((swift_error(none))) __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - - -#ifndef _REWRITER_typedef_NSURLQueryItem -#define _REWRITER_typedef_NSURLQueryItem -typedef struct objc_object NSURLQueryItem; -typedef struct {} _objc_exc_NSURLQueryItem; -#endif - -struct NSURLQueryItem_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSString *_name; - NSString *_value; -}; - -// - (instancetype)initWithName:(NSString *)name value:(nullable NSString *)value __attribute__((objc_designated_initializer)); -// + (instancetype)queryItemWithName:(NSString *)name value:(nullable NSString *)value; -// @property (readonly) NSString *name; -// @property (nullable, readonly) NSString *value; -/* @end */ - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_9))) - -#ifndef _REWRITER_typedef_NSURLComponents -#define _REWRITER_typedef_NSURLComponents -typedef struct objc_object NSURLComponents; -typedef struct {} _objc_exc_NSURLComponents; -#endif - -struct NSURLComponents_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - -// - (instancetype)init; - - -// - (nullable instancetype)initWithURL:(NSURL *)url resolvingAgainstBaseURL:(BOOL)resolve; - - -// + (nullable instancetype)componentsWithURL:(NSURL *)url resolvingAgainstBaseURL:(BOOL)resolve; - - -// - (nullable instancetype)initWithString:(NSString *)URLString; - - -// + (nullable instancetype)componentsWithString:(NSString *)URLString; - - -// @property (nullable, readonly, copy) NSURL *URL; - - -// - (nullable NSURL *)URLRelativeToURL:(nullable NSURL *)baseURL; - - -// @property (nullable, readonly, copy) NSString *string __attribute__((availability(macosx,introduced=10_10))); - - - - -// @property (nullable, copy) NSString *scheme; -// @property (nullable, copy) NSString *user; -// @property (nullable, copy) NSString *password; -// @property (nullable, copy) NSString *host; -// @property (nullable, copy) NSNumber *port; -// @property (nullable, copy) NSString *path; -// @property (nullable, copy) NSString *query; -// @property (nullable, copy) NSString *fragment; - - -// @property (nullable, copy) NSString *percentEncodedUser; -// @property (nullable, copy) NSString *percentEncodedPassword; -// @property (nullable, copy) NSString *percentEncodedHost; -// @property (nullable, copy) NSString *percentEncodedPath; -// @property (nullable, copy) NSString *percentEncodedQuery; -// @property (nullable, copy) NSString *percentEncodedFragment; - - - -// @property (readonly) NSRange rangeOfScheme __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly) NSRange rangeOfUser __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly) NSRange rangeOfPassword __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly) NSRange rangeOfHost __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly) NSRange rangeOfPort __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly) NSRange rangeOfPath __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly) NSRange rangeOfQuery __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly) NSRange rangeOfFragment __attribute__((availability(macosx,introduced=10_11))); - - - - -// @property (nullable, copy) NSArray<NSURLQueryItem *> *queryItems __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - - -// @interface NSCharacterSet (NSURLUtilities) - - - - -// + (NSCharacterSet *)URLUserAllowedCharacterSet __attribute__((availability(macosx,introduced=10_9))); - - -// + (NSCharacterSet *)URLPasswordAllowedCharacterSet __attribute__((availability(macosx,introduced=10_9))); - - -// + (NSCharacterSet *)URLHostAllowedCharacterSet __attribute__((availability(macosx,introduced=10_9))); - - -// + (NSCharacterSet *)URLPathAllowedCharacterSet __attribute__((availability(macosx,introduced=10_9))); - - -// + (NSCharacterSet *)URLQueryAllowedCharacterSet __attribute__((availability(macosx,introduced=10_9))); - - -// + (NSCharacterSet *)URLFragmentAllowedCharacterSet __attribute__((availability(macosx,introduced=10_9))); - -/* @end */ - - - -// @interface NSString (NSURLUtilities) - - -// - (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters __attribute__((availability(macosx,introduced=10_9))); - - -// @property (nullable, readonly, copy) NSString *stringByRemovingPercentEncoding __attribute__((availability(macosx,introduced=10_9))); - - -// - (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc __attribute__((availability(macosx,introduced=10_0,deprecated=10_11,message="" "Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid."))); -// - (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc __attribute__((availability(macosx,introduced=10_0,deprecated=10_11,message="" "Use -stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding."))); - -/* @end */ - - - -// @interface NSURL (NSURLPathUtilities) - - - -// + (nullable NSURL *)fileURLWithPathComponents:(NSArray<NSString *> *)components __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSArray<NSString *> *pathComponents __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSString *lastPathComponent __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSString *pathExtension __attribute__((availability(macosx,introduced=10_6))); -// - (NSURL *)URLByAppendingPathComponent:(NSString *)pathComponent __attribute__((availability(macosx,introduced=10_6))); -// - (NSURL *)URLByAppendingPathComponent:(NSString *)pathComponent isDirectory:(BOOL)isDirectory __attribute__((availability(macosx,introduced=10_7))); -// @property (nullable, readonly, copy) NSURL *URLByDeletingLastPathComponent __attribute__((availability(macosx,introduced=10_6))); -// - (NSURL *)URLByAppendingPathExtension:(NSString *)pathExtension __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSURL *URLByDeletingPathExtension __attribute__((availability(macosx,introduced=10_6))); - - - -// @property (nullable, readonly, copy) NSURL *URLByStandardizingPath __attribute__((availability(macosx,introduced=10_6))); -// @property (nullable, readonly, copy) NSURL *URLByResolvingSymlinksInPath __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSFileSecurity -#define _REWRITER_typedef_NSFileSecurity -typedef struct objc_object NSFileSecurity; -typedef struct {} _objc_exc_NSFileSecurity; -#endif - -struct NSFileSecurity_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - -// - (nullable instancetype) initWithCoder:(NSCoder *)aDecoder __attribute__((objc_designated_initializer)); -/* @end */ - -// @interface NSObject (NSURLClient) -// - (void)URL:(NSURL *)sender resourceDataDidBecomeAvailable:(NSData *)newBytes __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)URLResourceDidFinishLoading:(NSURL *)sender __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)URLResourceDidCancelLoading:(NSURL *)sender __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)URL:(NSURL *)sender resourceDidFailLoadingWithReason:(NSString *)reason __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -/* @end */ - - -// @interface NSURL (NSURLLoading) -// - (nullable NSData *)resourceDataUsingCache:(BOOL)shouldUseCache __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (void)loadResourceDataNotifyingClient:(id)client usingCache:(BOOL)shouldUseCache __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (nullable id)propertyForKey:(NSString *)propertyKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - - - -// - (BOOL)setResourceData:(NSData *)data __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -// - (BOOL)setProperty:(id)property forKey:(NSString *)propertyKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); - -// - (nullable NSURLHandle *)URLHandleUsingCache:(BOOL)shouldUseCache __attribute__((availability(macosx,introduced=10_0,deprecated=10_4,message="" ))); -/* @end */ - -// @class NSURLAuthenticationChallenge; -#ifndef _REWRITER_typedef_NSURLAuthenticationChallenge -#define _REWRITER_typedef_NSURLAuthenticationChallenge -typedef struct objc_object NSURLAuthenticationChallenge; -typedef struct {} _objc_exc_NSURLAuthenticationChallenge; -#endif - -// @class NSURLCredential; -#ifndef _REWRITER_typedef_NSURLCredential -#define _REWRITER_typedef_NSURLCredential -typedef struct objc_object NSURLCredential; -typedef struct {} _objc_exc_NSURLCredential; -#endif - -// @class NSURLProtectionSpace; -#ifndef _REWRITER_typedef_NSURLProtectionSpace -#define _REWRITER_typedef_NSURLProtectionSpace -typedef struct objc_object NSURLProtectionSpace; -typedef struct {} _objc_exc_NSURLProtectionSpace; -#endif - -// @class NSURLResponse; -#ifndef _REWRITER_typedef_NSURLResponse -#define _REWRITER_typedef_NSURLResponse -typedef struct objc_object NSURLResponse; -typedef struct {} _objc_exc_NSURLResponse; -#endif - -// @class NSError; -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -// @protocol NSURLAuthenticationChallengeSender <NSObject> - - - - -// - (void)useCredential:(NSURLCredential *)credential forAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; - - - - -// - (void)continueWithoutCredentialForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; - - - - -// - (void)cancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; - -/* @optional */ - - - -// - (void)performDefaultHandlingForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; - - - - -// - (void)rejectProtectionSpaceAndContinueWithChallenge:(NSURLAuthenticationChallenge *)challenge; - -/* @end */ - - -// @class NSURLAuthenticationChallengeInternal; -#ifndef _REWRITER_typedef_NSURLAuthenticationChallengeInternal -#define _REWRITER_typedef_NSURLAuthenticationChallengeInternal -typedef struct objc_object NSURLAuthenticationChallengeInternal; -typedef struct {} _objc_exc_NSURLAuthenticationChallengeInternal; -#endif - - -#ifndef _REWRITER_typedef_NSURLAuthenticationChallenge -#define _REWRITER_typedef_NSURLAuthenticationChallenge -typedef struct objc_object NSURLAuthenticationChallenge; -typedef struct {} _objc_exc_NSURLAuthenticationChallenge; -#endif - -struct NSURLAuthenticationChallenge_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLAuthenticationChallengeInternal *_internal; -}; - -// - (instancetype)initWithProtectionSpace:(NSURLProtectionSpace *)space proposedCredential:(nullable NSURLCredential *)credential previousFailureCount:(NSInteger)previousFailureCount failureResponse:(nullable NSURLResponse *)response error:(nullable NSError *)error sender:(id<NSURLAuthenticationChallengeSender>)sender; -// - (instancetype)initWithAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge sender:(id<NSURLAuthenticationChallengeSender>)sender; - - - - - - -// @property (readonly, copy) NSURLProtectionSpace *protectionSpace; -// @property (nullable, readonly, copy) NSURLCredential *proposedCredential; - - - - - - -// @property (readonly) NSInteger previousFailureCount; -// @property (nullable, readonly, copy) NSURLResponse *failureResponse; -// @property (nullable, readonly, copy) NSError *error; - - - - - - - -// @property (nullable, readonly, retain) id<NSURLAuthenticationChallengeSender> sender; - -/* @end */ - -typedef NSUInteger NSURLCacheStoragePolicy; enum -{ - NSURLCacheStorageAllowed, - NSURLCacheStorageAllowedInMemoryOnly, - NSURLCacheStorageNotAllowed, -}; - - -// @class NSCachedURLResponseInternal; -#ifndef _REWRITER_typedef_NSCachedURLResponseInternal -#define _REWRITER_typedef_NSCachedURLResponseInternal -typedef struct objc_object NSCachedURLResponseInternal; -typedef struct {} _objc_exc_NSCachedURLResponseInternal; -#endif - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -// @class NSURLRequest; -#ifndef _REWRITER_typedef_NSURLRequest -#define _REWRITER_typedef_NSURLRequest -typedef struct objc_object NSURLRequest; -typedef struct {} _objc_exc_NSURLRequest; -#endif - -// @class NSURLResponse; -#ifndef _REWRITER_typedef_NSURLResponse -#define _REWRITER_typedef_NSURLResponse -typedef struct objc_object NSURLResponse; -typedef struct {} _objc_exc_NSURLResponse; -#endif - -// @class NSDate; -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -// @class NSURLSessionDataTask; -#ifndef _REWRITER_typedef_NSURLSessionDataTask -#define _REWRITER_typedef_NSURLSessionDataTask -typedef struct objc_object NSURLSessionDataTask; -typedef struct {} _objc_exc_NSURLSessionDataTask; -#endif - - -#ifndef _REWRITER_typedef_NSCachedURLResponse -#define _REWRITER_typedef_NSCachedURLResponse -typedef struct objc_object NSCachedURLResponse; -typedef struct {} _objc_exc_NSCachedURLResponse; -#endif - -struct NSCachedURLResponse_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSCachedURLResponseInternal *_internal; -}; - -// - (instancetype)initWithResponse:(NSURLResponse *)response data:(NSData *)data; -// - (instancetype)initWithResponse:(NSURLResponse *)response data:(NSData *)data userInfo:(nullable NSDictionary *)userInfo storagePolicy:(NSURLCacheStoragePolicy)storagePolicy; - - - - - - -// @property (readonly, copy) NSURLResponse *response; - - - - - - -// @property (readonly, copy) NSData *data; - - - - - - -// @property (nullable, readonly, copy) NSDictionary *userInfo; - - - - - - -// @property (readonly) NSURLCacheStoragePolicy storagePolicy; - -/* @end */ - - - -// @class NSURLRequest; -#ifndef _REWRITER_typedef_NSURLRequest -#define _REWRITER_typedef_NSURLRequest -typedef struct objc_object NSURLRequest; -typedef struct {} _objc_exc_NSURLRequest; -#endif - -// @class NSURLCacheInternal; -#ifndef _REWRITER_typedef_NSURLCacheInternal -#define _REWRITER_typedef_NSURLCacheInternal -typedef struct objc_object NSURLCacheInternal; -typedef struct {} _objc_exc_NSURLCacheInternal; -#endif - - - -#ifndef _REWRITER_typedef_NSURLCache -#define _REWRITER_typedef_NSURLCache -typedef struct objc_object NSURLCache; -typedef struct {} _objc_exc_NSURLCache; -#endif - -struct NSURLCache_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLCacheInternal *_internal; -}; - -// + (NSURLCache *)sharedURLCache; -// + (void)setSharedURLCache:(NSURLCache *)cache; -// - (instancetype)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(nullable NSString *)path; -// - (nullable NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request; -// - (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request; -// - (void)removeCachedResponseForRequest:(NSURLRequest *)request; - - - - - - -// - (void)removeAllCachedResponses; - - - - - -// - (void)removeCachedResponsesSinceDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_10))); - - - - - - - -// @property NSUInteger memoryCapacity; - - - - - - - -// @property NSUInteger diskCapacity; -// @property (readonly) NSUInteger currentMemoryUsage; -// @property (readonly) NSUInteger currentDiskUsage; - -/* @end */ - - -// @interface NSURLCache (NSURLSessionTaskAdditions) -// - (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forDataTask:(NSURLSessionDataTask *)dataTask __attribute__((availability(macosx,introduced=10_10))); -// - (void)getCachedResponseForDataTask:(NSURLSessionDataTask *)dataTask completionHandler:(void (^) (NSCachedURLResponse * _Nullable cachedResponse))completionHandler __attribute__((availability(macosx,introduced=10_10))); -// - (void)removeCachedResponseForDataTask:(NSURLSessionDataTask *)dataTask __attribute__((availability(macosx,introduced=10_10))); -/* @end */ - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSURL; -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -// @class NSCachedURLResponse; -#ifndef _REWRITER_typedef_NSCachedURLResponse -#define _REWRITER_typedef_NSCachedURLResponse -typedef struct objc_object NSCachedURLResponse; -typedef struct {} _objc_exc_NSCachedURLResponse; -#endif - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -// @class NSError; -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -// @class NSURLAuthenticationChallenge; -#ifndef _REWRITER_typedef_NSURLAuthenticationChallenge -#define _REWRITER_typedef_NSURLAuthenticationChallenge -typedef struct objc_object NSURLAuthenticationChallenge; -typedef struct {} _objc_exc_NSURLAuthenticationChallenge; -#endif - -// @class NSURLConnectionInternal; -#ifndef _REWRITER_typedef_NSURLConnectionInternal -#define _REWRITER_typedef_NSURLConnectionInternal -typedef struct objc_object NSURLConnectionInternal; -typedef struct {} _objc_exc_NSURLConnectionInternal; -#endif - -// @class NSURLRequest; -#ifndef _REWRITER_typedef_NSURLRequest -#define _REWRITER_typedef_NSURLRequest -typedef struct objc_object NSURLRequest; -typedef struct {} _objc_exc_NSURLRequest; -#endif - -// @class NSURLResponse; -#ifndef _REWRITER_typedef_NSURLResponse -#define _REWRITER_typedef_NSURLResponse -typedef struct objc_object NSURLResponse; -typedef struct {} _objc_exc_NSURLResponse; -#endif - -// @class NSRunLoop; -#ifndef _REWRITER_typedef_NSRunLoop -#define _REWRITER_typedef_NSRunLoop -typedef struct objc_object NSRunLoop; -typedef struct {} _objc_exc_NSRunLoop; -#endif - -// @class NSInputStream; -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -// @class NSURLProtectionSpace; -#ifndef _REWRITER_typedef_NSURLProtectionSpace -#define _REWRITER_typedef_NSURLProtectionSpace -typedef struct objc_object NSURLProtectionSpace; -typedef struct {} _objc_exc_NSURLProtectionSpace; -#endif - -// @class NSOperationQueue; -#ifndef _REWRITER_typedef_NSOperationQueue -#define _REWRITER_typedef_NSOperationQueue -typedef struct objc_object NSOperationQueue; -typedef struct {} _objc_exc_NSOperationQueue; -#endif - - -// @protocol NSURLConnectionDelegate; - -#ifndef _REWRITER_typedef_NSURLConnection -#define _REWRITER_typedef_NSURLConnection -typedef struct objc_object NSURLConnection; -typedef struct {} _objc_exc_NSURLConnection; -#endif - -struct NSURLConnection_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLConnectionInternal *_internal; -}; - - - -// - (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate startImmediately:(BOOL)startImmediately __attribute__((availability(macosx,introduced=10_5,deprecated=10_11,message="" "Use NSURLSession (see NSURLSession.h)"))); - -// - (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSession (see NSURLSession.h)"))); -// + (nullable NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSession (see NSURLSession.h)"))); - -// @property (readonly, copy) NSURLRequest *originalRequest __attribute__((availability(macosx,introduced=10_8))); -// @property (readonly, copy) NSURLRequest *currentRequest __attribute__((availability(macosx,introduced=10_8))); - -// - (void)start __attribute__((availability(macosx,introduced=10_5))); -// - (void)cancel; - -// - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode __attribute__((availability(macosx,introduced=10_5))); -// - (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode __attribute__((availability(macosx,introduced=10_5))); -// - (void)setDelegateQueue:(nullable NSOperationQueue*) queue __attribute__((availability(macosx,introduced=10_7))); -// + (BOOL)canHandleRequest:(NSURLRequest *)request; - -/* @end */ - -// @protocol NSURLConnectionDelegate <NSObject> -/* @optional */ -// - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; -// - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection; -// - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; -// - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace __attribute__((availability(macosx,introduced=10_6,deprecated=10_10,message="" "Use -connection:willSendRequestForAuthenticationChallenge: instead."))); -// - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge __attribute__((availability(macosx,introduced=10_2,deprecated=10_10,message="" "Use -connection:willSendRequestForAuthenticationChallenge: instead."))); -// - (void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge __attribute__((availability(macosx,introduced=10_2,deprecated=10_10,message="" "Use -connection:willSendRequestForAuthenticationChallenge: instead."))); -/* @end */ - -// @protocol NSURLConnectionDataDelegate <NSURLConnectionDelegate> -/* @optional */ -// - (nullable NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)response; -// - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; - -// - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; - -// - (nullable NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request; -#if 0 -- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten - totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite; -#endif - - -// - (nullable NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse; - -// - (void)connectionDidFinishLoading:(NSURLConnection *)connection; -/* @end */ - -// @protocol NSURLConnectionDownloadDelegate <NSURLConnectionDelegate> -/* @optional */ -// - (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes; -// - (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes; - -/* @required */ -// - (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *) destinationURL; -/* @end */ - -// @interface NSURLConnection (NSURLConnectionSynchronousLoading) -// + (nullable NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse * _Nullable * _Nullable)response error:(NSError **)error __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession.h"))); - -/* @end */ - -// @interface NSURLConnection (NSURLConnectionQueuedLoading) -#if 0 -+ (void)sendAsynchronousRequest:(NSURLRequest*) request - queue:(NSOperationQueue*) queue - completionHandler:(void (^)(NSURLResponse* _Nullable response, NSData* _Nullable data, NSError* _Nullable connectionError)) handler __attribute__((availability(macosx,introduced=10_7,deprecated=10_11,message="" "Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession.h"))); -#endif - - -/* @end */ - - - - - - - - - -extern "C" { - - - -typedef int64_t sint64; - - - -typedef uint64_t uint64; - - - -typedef int32_t sint32; - - - -typedef int16_t sint16; - - - -typedef int8_t sint8; - - - -typedef uint32_t uint32; - - - -typedef uint16_t uint16; - - - -typedef uint8_t uint8; - - - -typedef intptr_t CSSM_INTPTR; -typedef size_t CSSM_SIZE; -} -extern "C" { -enum { - CSSM_BASE_ERROR = -0x7FFF0000 -}; - -enum { - CSSM_ERRORCODE_MODULE_EXTENT = 0x00000800, - CSSM_ERRORCODE_CUSTOM_OFFSET = 0x00000400, - CSSM_ERRORCODE_COMMON_EXTENT = 0x100 -}; -enum { - CSSM_CSSM_BASE_ERROR = CSSM_BASE_ERROR, - CSSM_CSSM_PRIVATE_ERROR = CSSM_BASE_ERROR + CSSM_ERRORCODE_CUSTOM_OFFSET, - CSSM_CSP_BASE_ERROR = CSSM_CSSM_BASE_ERROR + CSSM_ERRORCODE_MODULE_EXTENT, - CSSM_CSP_PRIVATE_ERROR = CSSM_CSP_BASE_ERROR + CSSM_ERRORCODE_CUSTOM_OFFSET, - CSSM_DL_BASE_ERROR = CSSM_CSP_BASE_ERROR + CSSM_ERRORCODE_MODULE_EXTENT, - CSSM_DL_PRIVATE_ERROR = CSSM_DL_BASE_ERROR + CSSM_ERRORCODE_CUSTOM_OFFSET, - CSSM_CL_BASE_ERROR = CSSM_DL_BASE_ERROR + CSSM_ERRORCODE_MODULE_EXTENT, - CSSM_CL_PRIVATE_ERROR = CSSM_CL_BASE_ERROR + CSSM_ERRORCODE_CUSTOM_OFFSET, - CSSM_TP_BASE_ERROR = CSSM_CL_BASE_ERROR + CSSM_ERRORCODE_MODULE_EXTENT, - CSSM_TP_PRIVATE_ERROR = CSSM_TP_BASE_ERROR + CSSM_ERRORCODE_CUSTOM_OFFSET , - CSSM_KR_BASE_ERROR = CSSM_TP_BASE_ERROR + CSSM_ERRORCODE_MODULE_EXTENT, - CSSM_KR_PRIVATE_ERROR = CSSM_KR_BASE_ERROR + CSSM_ERRORCODE_CUSTOM_OFFSET, - CSSM_AC_BASE_ERROR = CSSM_KR_BASE_ERROR + CSSM_ERRORCODE_MODULE_EXTENT, - CSSM_AC_PRIVATE_ERROR = CSSM_AC_BASE_ERROR + CSSM_ERRORCODE_CUSTOM_OFFSET -}; - - -enum { - CSSM_MDS_BASE_ERROR = CSSM_CSP_BASE_ERROR + CSSM_ERRORCODE_MODULE_EXTENT, - CSSM_MDS_PRIVATE_ERROR = CSSM_MDS_BASE_ERROR + CSSM_ERRORCODE_CUSTOM_OFFSET -}; - - -enum { - CSSMERR_CSSM_INVALID_ADDIN_HANDLE = - CSSM_CSSM_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT + 1, - CSSMERR_CSSM_NOT_INITIALIZED = - CSSM_CSSM_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT + 2, - CSSMERR_CSSM_INVALID_HANDLE_USAGE = - CSSM_CSSM_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT + 3, - CSSMERR_CSSM_PVC_REFERENT_NOT_FOUND = - CSSM_CSSM_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT + 4, - CSSMERR_CSSM_FUNCTION_INTEGRITY_FAIL = - CSSM_CSSM_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT + 5 -}; - - -enum { - CSSM_ERRCODE_INTERNAL_ERROR = 0x0001, - CSSM_ERRCODE_MEMORY_ERROR = 0x0002, - CSSM_ERRCODE_MDS_ERROR = 0x0003, - CSSM_ERRCODE_INVALID_POINTER = 0x0004, - CSSM_ERRCODE_INVALID_INPUT_POINTER = 0x0005, - CSSM_ERRCODE_INVALID_OUTPUT_POINTER = 0x0006, - CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED = 0x0007, - CSSM_ERRCODE_SELF_CHECK_FAILED = 0x0008, - CSSM_ERRCODE_OS_ACCESS_DENIED = 0x0009, - CSSM_ERRCODE_FUNCTION_FAILED = 0x000A, - CSSM_ERRCODE_MODULE_MANIFEST_VERIFY_FAILED = 0x000B, - CSSM_ERRCODE_INVALID_GUID = 0x000C -}; - - -enum { - CSSM_ERRCODE_OPERATION_AUTH_DENIED = 0x0020, - CSSM_ERRCODE_OBJECT_USE_AUTH_DENIED = 0x0021, - CSSM_ERRCODE_OBJECT_MANIP_AUTH_DENIED = 0x0022, - CSSM_ERRCODE_OBJECT_ACL_NOT_SUPPORTED = 0x0023, - CSSM_ERRCODE_OBJECT_ACL_REQUIRED = 0x0024, - CSSM_ERRCODE_INVALID_ACCESS_CREDENTIALS = 0x0025, - CSSM_ERRCODE_INVALID_ACL_BASE_CERTS = 0x0026, - CSSM_ERRCODE_ACL_BASE_CERTS_NOT_SUPPORTED = 0x0027, - CSSM_ERRCODE_INVALID_SAMPLE_VALUE = 0x0028, - CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED = 0x0029, - CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE = 0x002A, - CSSM_ERRCODE_ACL_SUBJECT_TYPE_NOT_SUPPORTED = 0x002B, - CSSM_ERRCODE_INVALID_ACL_CHALLENGE_CALLBACK = 0x002C, - CSSM_ERRCODE_ACL_CHALLENGE_CALLBACK_FAILED = 0x002D, - CSSM_ERRCODE_INVALID_ACL_ENTRY_TAG = 0x002E, - CSSM_ERRCODE_ACL_ENTRY_TAG_NOT_FOUND = 0x002F, - CSSM_ERRCODE_INVALID_ACL_EDIT_MODE = 0x0030, - CSSM_ERRCODE_ACL_CHANGE_FAILED = 0x0031, - CSSM_ERRCODE_INVALID_NEW_ACL_ENTRY = 0x0032, - CSSM_ERRCODE_INVALID_NEW_ACL_OWNER = 0x0033, - CSSM_ERRCODE_ACL_DELETE_FAILED = 0x0034, - CSSM_ERRCODE_ACL_REPLACE_FAILED = 0x0035, - CSSM_ERRCODE_ACL_ADD_FAILED = 0x0036 -}; - - -enum { - CSSM_ERRCODE_INVALID_CONTEXT_HANDLE = 0x0040, - CSSM_ERRCODE_INCOMPATIBLE_VERSION = 0x0041, - CSSM_ERRCODE_INVALID_CERTGROUP_POINTER = 0x0042, - CSSM_ERRCODE_INVALID_CERT_POINTER = 0x0043, - CSSM_ERRCODE_INVALID_CRL_POINTER = 0x0044, - CSSM_ERRCODE_INVALID_FIELD_POINTER = 0x0045, - CSSM_ERRCODE_INVALID_DATA = 0x0046, - CSSM_ERRCODE_CRL_ALREADY_SIGNED = 0x0047, - CSSM_ERRCODE_INVALID_NUMBER_OF_FIELDS = 0x0048, - CSSM_ERRCODE_VERIFICATION_FAILURE = 0x0049, - CSSM_ERRCODE_INVALID_DB_HANDLE = 0x004A, - CSSM_ERRCODE_PRIVILEGE_NOT_GRANTED = 0x004B, - CSSM_ERRCODE_INVALID_DB_LIST = 0x004C, - CSSM_ERRCODE_INVALID_DB_LIST_POINTER = 0x004D, - CSSM_ERRCODE_UNKNOWN_FORMAT = 0x004E, - CSSM_ERRCODE_UNKNOWN_TAG = 0x004F, - CSSM_ERRCODE_INVALID_CSP_HANDLE = 0x0050, - CSSM_ERRCODE_INVALID_DL_HANDLE = 0x0051, - CSSM_ERRCODE_INVALID_CL_HANDLE = 0x0052, - CSSM_ERRCODE_INVALID_TP_HANDLE = 0x0053, - CSSM_ERRCODE_INVALID_KR_HANDLE = 0x0054, - CSSM_ERRCODE_INVALID_AC_HANDLE = 0x0055, - CSSM_ERRCODE_INVALID_PASSTHROUGH_ID = 0x0056, - CSSM_ERRCODE_INVALID_NETWORK_ADDR = 0x0057, - CSSM_ERRCODE_INVALID_CRYPTO_DATA = 0x0058 -}; - - -enum { - CSSMERR_CSSM_INTERNAL_ERROR = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_INTERNAL_ERROR, - CSSMERR_CSSM_MEMORY_ERROR = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_MEMORY_ERROR, - CSSMERR_CSSM_MDS_ERROR = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_MDS_ERROR, - CSSMERR_CSSM_INVALID_POINTER = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_INVALID_POINTER, - CSSMERR_CSSM_INVALID_INPUT_POINTER = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_INVALID_INPUT_POINTER, - CSSMERR_CSSM_INVALID_OUTPUT_POINTER = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_INVALID_OUTPUT_POINTER, - CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED, - CSSMERR_CSSM_SELF_CHECK_FAILED = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_SELF_CHECK_FAILED, - CSSMERR_CSSM_OS_ACCESS_DENIED = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_OS_ACCESS_DENIED, - CSSMERR_CSSM_FUNCTION_FAILED = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_FUNCTION_FAILED, - CSSMERR_CSSM_MODULE_MANIFEST_VERIFY_FAILED = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_MODULE_MANIFEST_VERIFY_FAILED, - CSSMERR_CSSM_INVALID_GUID = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_INVALID_GUID -}; - - -enum { - CSSMERR_CSSM_INVALID_CONTEXT_HANDLE = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_INVALID_CONTEXT_HANDLE, - CSSMERR_CSSM_INCOMPATIBLE_VERSION = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_INCOMPATIBLE_VERSION, - CSSMERR_CSSM_PRIVILEGE_NOT_GRANTED = - CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_PRIVILEGE_NOT_GRANTED -}; - - -enum { - CSSM_CSSM_BASE_CSSM_ERROR = - CSSM_CSSM_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT + 0x10, - CSSMERR_CSSM_SCOPE_NOT_SUPPORTED = CSSM_CSSM_BASE_CSSM_ERROR + 1, - CSSMERR_CSSM_PVC_ALREADY_CONFIGURED = CSSM_CSSM_BASE_CSSM_ERROR + 2, - CSSMERR_CSSM_INVALID_PVC = CSSM_CSSM_BASE_CSSM_ERROR + 3, - CSSMERR_CSSM_EMM_LOAD_FAILED = CSSM_CSSM_BASE_CSSM_ERROR + 4, - CSSMERR_CSSM_EMM_UNLOAD_FAILED = CSSM_CSSM_BASE_CSSM_ERROR + 5, - CSSMERR_CSSM_ADDIN_LOAD_FAILED = CSSM_CSSM_BASE_CSSM_ERROR + 6, - CSSMERR_CSSM_INVALID_KEY_HIERARCHY = CSSM_CSSM_BASE_CSSM_ERROR + 7, - CSSMERR_CSSM_ADDIN_UNLOAD_FAILED = CSSM_CSSM_BASE_CSSM_ERROR + 8, - CSSMERR_CSSM_LIB_REF_NOT_FOUND = CSSM_CSSM_BASE_CSSM_ERROR + 9, - CSSMERR_CSSM_INVALID_ADDIN_FUNCTION_TABLE = CSSM_CSSM_BASE_CSSM_ERROR + 10, - CSSMERR_CSSM_EMM_AUTHENTICATE_FAILED = CSSM_CSSM_BASE_CSSM_ERROR + 11, - CSSMERR_CSSM_ADDIN_AUTHENTICATE_FAILED = CSSM_CSSM_BASE_CSSM_ERROR + 12, - CSSMERR_CSSM_INVALID_SERVICE_MASK = CSSM_CSSM_BASE_CSSM_ERROR + 13, - CSSMERR_CSSM_MODULE_NOT_LOADED = CSSM_CSSM_BASE_CSSM_ERROR + 14, - CSSMERR_CSSM_INVALID_SUBSERVICEID = CSSM_CSSM_BASE_CSSM_ERROR + 15, - CSSMERR_CSSM_BUFFER_TOO_SMALL = CSSM_CSSM_BASE_CSSM_ERROR + 16, - CSSMERR_CSSM_INVALID_ATTRIBUTE = CSSM_CSSM_BASE_CSSM_ERROR + 17, - CSSMERR_CSSM_ATTRIBUTE_NOT_IN_CONTEXT = CSSM_CSSM_BASE_CSSM_ERROR + 18, - CSSMERR_CSSM_MODULE_MANAGER_INITIALIZE_FAIL = CSSM_CSSM_BASE_CSSM_ERROR + 19, - CSSMERR_CSSM_MODULE_MANAGER_NOT_FOUND = CSSM_CSSM_BASE_CSSM_ERROR + 20, - CSSMERR_CSSM_EVENT_NOTIFICATION_CALLBACK_NOT_FOUND = CSSM_CSSM_BASE_CSSM_ERROR + 21 -}; - - -enum { - CSSMERR_CSP_INTERNAL_ERROR = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INTERNAL_ERROR, - CSSMERR_CSP_MEMORY_ERROR = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_MEMORY_ERROR, - CSSMERR_CSP_MDS_ERROR = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_MDS_ERROR, - CSSMERR_CSP_INVALID_POINTER = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_POINTER, - CSSMERR_CSP_INVALID_INPUT_POINTER = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_INPUT_POINTER, - CSSMERR_CSP_INVALID_OUTPUT_POINTER = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_OUTPUT_POINTER, - CSSMERR_CSP_FUNCTION_NOT_IMPLEMENTED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED, - CSSMERR_CSP_SELF_CHECK_FAILED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_SELF_CHECK_FAILED, - CSSMERR_CSP_OS_ACCESS_DENIED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_OS_ACCESS_DENIED, - CSSMERR_CSP_FUNCTION_FAILED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_FUNCTION_FAILED -}; - - -enum { - CSSMERR_CSP_OPERATION_AUTH_DENIED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_OPERATION_AUTH_DENIED, - CSSMERR_CSP_OBJECT_USE_AUTH_DENIED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_OBJECT_USE_AUTH_DENIED, - CSSMERR_CSP_OBJECT_MANIP_AUTH_DENIED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_OBJECT_MANIP_AUTH_DENIED, - CSSMERR_CSP_OBJECT_ACL_NOT_SUPPORTED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_OBJECT_ACL_NOT_SUPPORTED, - CSSMERR_CSP_OBJECT_ACL_REQUIRED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_OBJECT_ACL_REQUIRED, - CSSMERR_CSP_INVALID_ACCESS_CREDENTIALS = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_ACCESS_CREDENTIALS, - CSSMERR_CSP_INVALID_ACL_BASE_CERTS = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_BASE_CERTS, - CSSMERR_CSP_ACL_BASE_CERTS_NOT_SUPPORTED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_ACL_BASE_CERTS_NOT_SUPPORTED, - CSSMERR_CSP_INVALID_SAMPLE_VALUE = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_SAMPLE_VALUE, - CSSMERR_CSP_SAMPLE_VALUE_NOT_SUPPORTED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED, - CSSMERR_CSP_INVALID_ACL_SUBJECT_VALUE = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE, - CSSMERR_CSP_ACL_SUBJECT_TYPE_NOT_SUPPORTED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_ACL_SUBJECT_TYPE_NOT_SUPPORTED, - CSSMERR_CSP_INVALID_ACL_CHALLENGE_CALLBACK = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_CHALLENGE_CALLBACK, - CSSMERR_CSP_ACL_CHALLENGE_CALLBACK_FAILED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_ACL_CHALLENGE_CALLBACK_FAILED, - CSSMERR_CSP_INVALID_ACL_ENTRY_TAG = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_ENTRY_TAG, - CSSMERR_CSP_ACL_ENTRY_TAG_NOT_FOUND = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_ACL_ENTRY_TAG_NOT_FOUND, - CSSMERR_CSP_INVALID_ACL_EDIT_MODE = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_EDIT_MODE, - CSSMERR_CSP_ACL_CHANGE_FAILED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_ACL_CHANGE_FAILED, - CSSMERR_CSP_INVALID_NEW_ACL_ENTRY = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_NEW_ACL_ENTRY, - CSSMERR_CSP_INVALID_NEW_ACL_OWNER = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_NEW_ACL_OWNER, - CSSMERR_CSP_ACL_DELETE_FAILED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_ACL_DELETE_FAILED, - CSSMERR_CSP_ACL_REPLACE_FAILED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_ACL_REPLACE_FAILED, - CSSMERR_CSP_ACL_ADD_FAILED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_ACL_ADD_FAILED -}; - - -enum { - CSSMERR_CSP_INVALID_CONTEXT_HANDLE = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_CONTEXT_HANDLE, - CSSMERR_CSP_PRIVILEGE_NOT_GRANTED = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_PRIVILEGE_NOT_GRANTED, - CSSMERR_CSP_INVALID_DATA = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_DATA, - CSSMERR_CSP_INVALID_PASSTHROUGH_ID = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_PASSTHROUGH_ID, - CSSMERR_CSP_INVALID_CRYPTO_DATA = - CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INVALID_CRYPTO_DATA -}; - - -enum { - - CSSM_CSP_BASE_CSP_ERROR = - CSSM_CSP_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT, - CSSMERR_CSP_INPUT_LENGTH_ERROR = CSSM_CSP_BASE_CSP_ERROR + 1, - CSSMERR_CSP_OUTPUT_LENGTH_ERROR = CSSM_CSP_BASE_CSP_ERROR + 2, - CSSMERR_CSP_PRIVILEGE_NOT_SUPPORTED = CSSM_CSP_BASE_CSP_ERROR + 3, - CSSMERR_CSP_DEVICE_ERROR = CSSM_CSP_BASE_CSP_ERROR + 4, - CSSMERR_CSP_DEVICE_MEMORY_ERROR = CSSM_CSP_BASE_CSP_ERROR + 5, - CSSMERR_CSP_ATTACH_HANDLE_BUSY = CSSM_CSP_BASE_CSP_ERROR + 6, - CSSMERR_CSP_NOT_LOGGED_IN = CSSM_CSP_BASE_CSP_ERROR + 7, - CSSMERR_CSP_INVALID_KEY = CSSM_CSP_BASE_CSP_ERROR + 16, - CSSMERR_CSP_INVALID_KEY_REFERENCE = CSSM_CSP_BASE_CSP_ERROR + 17, - CSSMERR_CSP_INVALID_KEY_CLASS = CSSM_CSP_BASE_CSP_ERROR + 18, - CSSMERR_CSP_ALGID_MISMATCH = CSSM_CSP_BASE_CSP_ERROR + 19, - CSSMERR_CSP_KEY_USAGE_INCORRECT = CSSM_CSP_BASE_CSP_ERROR + 20, - CSSMERR_CSP_KEY_BLOB_TYPE_INCORRECT = CSSM_CSP_BASE_CSP_ERROR + 21, - CSSMERR_CSP_KEY_HEADER_INCONSISTENT = CSSM_CSP_BASE_CSP_ERROR + 22, - CSSMERR_CSP_UNSUPPORTED_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 23, - CSSMERR_CSP_UNSUPPORTED_KEY_SIZE = CSSM_CSP_BASE_CSP_ERROR + 24, - CSSMERR_CSP_INVALID_KEY_POINTER = CSSM_CSP_BASE_CSP_ERROR + 25, - CSSMERR_CSP_INVALID_KEYUSAGE_MASK = CSSM_CSP_BASE_CSP_ERROR + 26, - CSSMERR_CSP_UNSUPPORTED_KEYUSAGE_MASK = CSSM_CSP_BASE_CSP_ERROR + 27, - CSSMERR_CSP_INVALID_KEYATTR_MASK = CSSM_CSP_BASE_CSP_ERROR + 28, - CSSMERR_CSP_UNSUPPORTED_KEYATTR_MASK = CSSM_CSP_BASE_CSP_ERROR + 29, - CSSMERR_CSP_INVALID_KEY_LABEL = CSSM_CSP_BASE_CSP_ERROR + 30, - CSSMERR_CSP_UNSUPPORTED_KEY_LABEL = CSSM_CSP_BASE_CSP_ERROR + 31, - CSSMERR_CSP_INVALID_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 32, - - - CSSMERR_CSP_INVALID_DATA_COUNT = CSSM_CSP_BASE_CSP_ERROR + 40, - CSSMERR_CSP_VECTOR_OF_BUFS_UNSUPPORTED = CSSM_CSP_BASE_CSP_ERROR + 41, - CSSMERR_CSP_INVALID_INPUT_VECTOR = CSSM_CSP_BASE_CSP_ERROR + 42, - CSSMERR_CSP_INVALID_OUTPUT_VECTOR = CSSM_CSP_BASE_CSP_ERROR + 43, - - - CSSMERR_CSP_INVALID_CONTEXT = CSSM_CSP_BASE_CSP_ERROR + 48, - CSSMERR_CSP_INVALID_ALGORITHM = CSSM_CSP_BASE_CSP_ERROR + 49, - CSSMERR_CSP_INVALID_ATTR_KEY = CSSM_CSP_BASE_CSP_ERROR + 54, - CSSMERR_CSP_MISSING_ATTR_KEY = CSSM_CSP_BASE_CSP_ERROR + 55, - CSSMERR_CSP_INVALID_ATTR_INIT_VECTOR = CSSM_CSP_BASE_CSP_ERROR + 56, - CSSMERR_CSP_MISSING_ATTR_INIT_VECTOR = CSSM_CSP_BASE_CSP_ERROR + 57, - CSSMERR_CSP_INVALID_ATTR_SALT = CSSM_CSP_BASE_CSP_ERROR + 58, - CSSMERR_CSP_MISSING_ATTR_SALT = CSSM_CSP_BASE_CSP_ERROR + 59, - CSSMERR_CSP_INVALID_ATTR_PADDING = CSSM_CSP_BASE_CSP_ERROR + 60, - CSSMERR_CSP_MISSING_ATTR_PADDING = CSSM_CSP_BASE_CSP_ERROR + 61, - CSSMERR_CSP_INVALID_ATTR_RANDOM = CSSM_CSP_BASE_CSP_ERROR + 62, - CSSMERR_CSP_MISSING_ATTR_RANDOM = CSSM_CSP_BASE_CSP_ERROR + 63, - CSSMERR_CSP_INVALID_ATTR_SEED = CSSM_CSP_BASE_CSP_ERROR + 64, - CSSMERR_CSP_MISSING_ATTR_SEED = CSSM_CSP_BASE_CSP_ERROR + 65, - CSSMERR_CSP_INVALID_ATTR_PASSPHRASE = CSSM_CSP_BASE_CSP_ERROR + 66, - CSSMERR_CSP_MISSING_ATTR_PASSPHRASE = CSSM_CSP_BASE_CSP_ERROR + 67, - CSSMERR_CSP_INVALID_ATTR_KEY_LENGTH = CSSM_CSP_BASE_CSP_ERROR + 68, - CSSMERR_CSP_MISSING_ATTR_KEY_LENGTH = CSSM_CSP_BASE_CSP_ERROR + 69, - CSSMERR_CSP_INVALID_ATTR_BLOCK_SIZE = CSSM_CSP_BASE_CSP_ERROR + 70, - CSSMERR_CSP_MISSING_ATTR_BLOCK_SIZE = CSSM_CSP_BASE_CSP_ERROR + 71, - CSSMERR_CSP_INVALID_ATTR_OUTPUT_SIZE = CSSM_CSP_BASE_CSP_ERROR + 100, - CSSMERR_CSP_MISSING_ATTR_OUTPUT_SIZE = CSSM_CSP_BASE_CSP_ERROR + 101, - CSSMERR_CSP_INVALID_ATTR_ROUNDS = CSSM_CSP_BASE_CSP_ERROR + 102, - CSSMERR_CSP_MISSING_ATTR_ROUNDS = CSSM_CSP_BASE_CSP_ERROR + 103, - CSSMERR_CSP_INVALID_ATTR_ALG_PARAMS = CSSM_CSP_BASE_CSP_ERROR + 104, - CSSMERR_CSP_MISSING_ATTR_ALG_PARAMS = CSSM_CSP_BASE_CSP_ERROR + 105, - CSSMERR_CSP_INVALID_ATTR_LABEL = CSSM_CSP_BASE_CSP_ERROR + 106, - CSSMERR_CSP_MISSING_ATTR_LABEL = CSSM_CSP_BASE_CSP_ERROR + 107, - CSSMERR_CSP_INVALID_ATTR_KEY_TYPE = CSSM_CSP_BASE_CSP_ERROR + 108, - CSSMERR_CSP_MISSING_ATTR_KEY_TYPE = CSSM_CSP_BASE_CSP_ERROR + 109, - CSSMERR_CSP_INVALID_ATTR_MODE = CSSM_CSP_BASE_CSP_ERROR + 110, - CSSMERR_CSP_MISSING_ATTR_MODE = CSSM_CSP_BASE_CSP_ERROR + 111, - CSSMERR_CSP_INVALID_ATTR_EFFECTIVE_BITS = CSSM_CSP_BASE_CSP_ERROR + 112, - CSSMERR_CSP_MISSING_ATTR_EFFECTIVE_BITS = CSSM_CSP_BASE_CSP_ERROR + 113, - CSSMERR_CSP_INVALID_ATTR_START_DATE = CSSM_CSP_BASE_CSP_ERROR + 114, - CSSMERR_CSP_MISSING_ATTR_START_DATE = CSSM_CSP_BASE_CSP_ERROR + 115, - CSSMERR_CSP_INVALID_ATTR_END_DATE = CSSM_CSP_BASE_CSP_ERROR + 116, - CSSMERR_CSP_MISSING_ATTR_END_DATE = CSSM_CSP_BASE_CSP_ERROR + 117, - CSSMERR_CSP_INVALID_ATTR_VERSION = CSSM_CSP_BASE_CSP_ERROR + 118, - CSSMERR_CSP_MISSING_ATTR_VERSION = CSSM_CSP_BASE_CSP_ERROR + 119, - CSSMERR_CSP_INVALID_ATTR_PRIME = CSSM_CSP_BASE_CSP_ERROR + 120, - CSSMERR_CSP_MISSING_ATTR_PRIME = CSSM_CSP_BASE_CSP_ERROR + 121, - CSSMERR_CSP_INVALID_ATTR_BASE = CSSM_CSP_BASE_CSP_ERROR + 122, - CSSMERR_CSP_MISSING_ATTR_BASE = CSSM_CSP_BASE_CSP_ERROR + 123, - CSSMERR_CSP_INVALID_ATTR_SUBPRIME = CSSM_CSP_BASE_CSP_ERROR + 124, - CSSMERR_CSP_MISSING_ATTR_SUBPRIME = CSSM_CSP_BASE_CSP_ERROR + 125, - CSSMERR_CSP_INVALID_ATTR_ITERATION_COUNT = CSSM_CSP_BASE_CSP_ERROR + 126, - CSSMERR_CSP_MISSING_ATTR_ITERATION_COUNT = CSSM_CSP_BASE_CSP_ERROR + 127, - CSSMERR_CSP_INVALID_ATTR_DL_DB_HANDLE = CSSM_CSP_BASE_CSP_ERROR + 128, - CSSMERR_CSP_MISSING_ATTR_DL_DB_HANDLE = CSSM_CSP_BASE_CSP_ERROR + 129, - CSSMERR_CSP_INVALID_ATTR_ACCESS_CREDENTIALS = CSSM_CSP_BASE_CSP_ERROR + 130, - CSSMERR_CSP_MISSING_ATTR_ACCESS_CREDENTIALS = CSSM_CSP_BASE_CSP_ERROR + 131, - CSSMERR_CSP_INVALID_ATTR_PUBLIC_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 132, - CSSMERR_CSP_MISSING_ATTR_PUBLIC_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 133, - CSSMERR_CSP_INVALID_ATTR_PRIVATE_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 134, - CSSMERR_CSP_MISSING_ATTR_PRIVATE_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 135, - CSSMERR_CSP_INVALID_ATTR_SYMMETRIC_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 136, - CSSMERR_CSP_MISSING_ATTR_SYMMETRIC_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 137, - CSSMERR_CSP_INVALID_ATTR_WRAPPED_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 138, - CSSMERR_CSP_MISSING_ATTR_WRAPPED_KEY_FORMAT = CSSM_CSP_BASE_CSP_ERROR + 139, - - - CSSMERR_CSP_STAGED_OPERATION_IN_PROGRESS = CSSM_CSP_BASE_CSP_ERROR + 72, - CSSMERR_CSP_STAGED_OPERATION_NOT_STARTED = CSSM_CSP_BASE_CSP_ERROR + 73, - CSSMERR_CSP_VERIFY_FAILED = CSSM_CSP_BASE_CSP_ERROR + 74, - CSSMERR_CSP_INVALID_SIGNATURE = CSSM_CSP_BASE_CSP_ERROR + 75, - CSSMERR_CSP_QUERY_SIZE_UNKNOWN = CSSM_CSP_BASE_CSP_ERROR + 76, - CSSMERR_CSP_BLOCK_SIZE_MISMATCH = CSSM_CSP_BASE_CSP_ERROR + 77, - CSSMERR_CSP_PRIVATE_KEY_NOT_FOUND = CSSM_CSP_BASE_CSP_ERROR + 78, - CSSMERR_CSP_PUBLIC_KEY_INCONSISTENT = CSSM_CSP_BASE_CSP_ERROR + 79, - CSSMERR_CSP_DEVICE_VERIFY_FAILED = CSSM_CSP_BASE_CSP_ERROR + 80, - CSSMERR_CSP_INVALID_LOGIN_NAME = CSSM_CSP_BASE_CSP_ERROR + 81, - CSSMERR_CSP_ALREADY_LOGGED_IN = CSSM_CSP_BASE_CSP_ERROR + 82, - CSSMERR_CSP_PRIVATE_KEY_ALREADY_EXISTS = CSSM_CSP_BASE_CSP_ERROR + 83, - CSSMERR_CSP_KEY_LABEL_ALREADY_EXISTS = CSSM_CSP_BASE_CSP_ERROR + 84, - CSSMERR_CSP_INVALID_DIGEST_ALGORITHM = CSSM_CSP_BASE_CSP_ERROR + 85, - CSSMERR_CSP_CRYPTO_DATA_CALLBACK_FAILED = CSSM_CSP_BASE_CSP_ERROR + 86 -}; - - - -enum { - CSSMERR_TP_INTERNAL_ERROR = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INTERNAL_ERROR, - CSSMERR_TP_MEMORY_ERROR = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_MEMORY_ERROR, - CSSMERR_TP_MDS_ERROR = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_MDS_ERROR, - CSSMERR_TP_INVALID_POINTER = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_POINTER, - CSSMERR_TP_INVALID_INPUT_POINTER = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_INPUT_POINTER, - CSSMERR_TP_INVALID_OUTPUT_POINTER = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_OUTPUT_POINTER, - CSSMERR_TP_FUNCTION_NOT_IMPLEMENTED = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED, - CSSMERR_TP_SELF_CHECK_FAILED = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_SELF_CHECK_FAILED, - CSSMERR_TP_OS_ACCESS_DENIED = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_OS_ACCESS_DENIED, - CSSMERR_TP_FUNCTION_FAILED = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_FUNCTION_FAILED, - CSSMERR_TP_INVALID_CONTEXT_HANDLE = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_CONTEXT_HANDLE, - CSSMERR_TP_INVALID_DATA = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_DATA, - CSSMERR_TP_INVALID_DB_LIST = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_DB_LIST, - CSSMERR_TP_INVALID_CERTGROUP_POINTER = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_CERTGROUP_POINTER, - CSSMERR_TP_INVALID_CERT_POINTER = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_CERT_POINTER, - CSSMERR_TP_INVALID_CRL_POINTER = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_CRL_POINTER, - CSSMERR_TP_INVALID_FIELD_POINTER = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_FIELD_POINTER, - CSSMERR_TP_INVALID_NETWORK_ADDR = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_NETWORK_ADDR, - CSSMERR_TP_CRL_ALREADY_SIGNED = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_CRL_ALREADY_SIGNED, - CSSMERR_TP_INVALID_NUMBER_OF_FIELDS = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_NUMBER_OF_FIELDS, - CSSMERR_TP_VERIFICATION_FAILURE = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_VERIFICATION_FAILURE, - CSSMERR_TP_INVALID_DB_HANDLE = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_DB_HANDLE, - CSSMERR_TP_UNKNOWN_FORMAT = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_UNKNOWN_FORMAT, - CSSMERR_TP_UNKNOWN_TAG = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_UNKNOWN_TAG, - CSSMERR_TP_INVALID_PASSTHROUGH_ID = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_PASSTHROUGH_ID, - CSSMERR_TP_INVALID_CSP_HANDLE = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_CSP_HANDLE, - CSSMERR_TP_INVALID_DL_HANDLE = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_DL_HANDLE, - CSSMERR_TP_INVALID_CL_HANDLE = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_CL_HANDLE, - CSSMERR_TP_INVALID_DB_LIST_POINTER = - CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INVALID_DB_LIST_POINTER -}; - - -enum { - CSSM_TP_BASE_TP_ERROR = - CSSM_TP_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT, - CSSMERR_TP_INVALID_CALLERAUTH_CONTEXT_POINTER = CSSM_TP_BASE_TP_ERROR + 1, - CSSMERR_TP_INVALID_IDENTIFIER_POINTER = CSSM_TP_BASE_TP_ERROR + 2, - CSSMERR_TP_INVALID_KEYCACHE_HANDLE = CSSM_TP_BASE_TP_ERROR + 3, - CSSMERR_TP_INVALID_CERTGROUP = CSSM_TP_BASE_TP_ERROR + 4, - CSSMERR_TP_INVALID_CRLGROUP = CSSM_TP_BASE_TP_ERROR + 5, - CSSMERR_TP_INVALID_CRLGROUP_POINTER = CSSM_TP_BASE_TP_ERROR + 6, - CSSMERR_TP_AUTHENTICATION_FAILED = CSSM_TP_BASE_TP_ERROR + 7, - CSSMERR_TP_CERTGROUP_INCOMPLETE = CSSM_TP_BASE_TP_ERROR + 8, - CSSMERR_TP_CERTIFICATE_CANT_OPERATE = CSSM_TP_BASE_TP_ERROR + 9, - CSSMERR_TP_CERT_EXPIRED = CSSM_TP_BASE_TP_ERROR + 10, - CSSMERR_TP_CERT_NOT_VALID_YET = CSSM_TP_BASE_TP_ERROR + 11, - CSSMERR_TP_CERT_REVOKED = CSSM_TP_BASE_TP_ERROR + 12, - CSSMERR_TP_CERT_SUSPENDED = CSSM_TP_BASE_TP_ERROR + 13, - CSSMERR_TP_INSUFFICIENT_CREDENTIALS = CSSM_TP_BASE_TP_ERROR + 14, - CSSMERR_TP_INVALID_ACTION = CSSM_TP_BASE_TP_ERROR + 15, - CSSMERR_TP_INVALID_ACTION_DATA = CSSM_TP_BASE_TP_ERROR + 16, - CSSMERR_TP_INVALID_ANCHOR_CERT = CSSM_TP_BASE_TP_ERROR + 18, - CSSMERR_TP_INVALID_AUTHORITY = CSSM_TP_BASE_TP_ERROR + 19, - CSSMERR_TP_VERIFY_ACTION_FAILED = CSSM_TP_BASE_TP_ERROR + 20, - CSSMERR_TP_INVALID_CERTIFICATE = CSSM_TP_BASE_TP_ERROR + 21, - CSSMERR_TP_INVALID_CERT_AUTHORITY = CSSM_TP_BASE_TP_ERROR + 22, - CSSMERR_TP_INVALID_CRL_AUTHORITY = CSSM_TP_BASE_TP_ERROR + 23, - CSSMERR_TP_INVALID_CRL_ENCODING = CSSM_TP_BASE_TP_ERROR + 24, - CSSMERR_TP_INVALID_CRL_TYPE = CSSM_TP_BASE_TP_ERROR + 25, - CSSMERR_TP_INVALID_CRL = CSSM_TP_BASE_TP_ERROR + 26, - CSSMERR_TP_INVALID_FORM_TYPE = CSSM_TP_BASE_TP_ERROR + 27, - CSSMERR_TP_INVALID_ID = CSSM_TP_BASE_TP_ERROR + 28, - CSSMERR_TP_INVALID_IDENTIFIER = CSSM_TP_BASE_TP_ERROR + 29, - CSSMERR_TP_INVALID_INDEX = CSSM_TP_BASE_TP_ERROR + 30, - CSSMERR_TP_INVALID_NAME = CSSM_TP_BASE_TP_ERROR + 31, - CSSMERR_TP_INVALID_POLICY_IDENTIFIERS = CSSM_TP_BASE_TP_ERROR + 32, - CSSMERR_TP_INVALID_TIMESTRING = CSSM_TP_BASE_TP_ERROR + 33, - CSSMERR_TP_INVALID_REASON = CSSM_TP_BASE_TP_ERROR + 34, - CSSMERR_TP_INVALID_REQUEST_INPUTS = CSSM_TP_BASE_TP_ERROR + 35, - CSSMERR_TP_INVALID_RESPONSE_VECTOR = CSSM_TP_BASE_TP_ERROR + 36, - CSSMERR_TP_INVALID_SIGNATURE = CSSM_TP_BASE_TP_ERROR + 37, - CSSMERR_TP_INVALID_STOP_ON_POLICY = CSSM_TP_BASE_TP_ERROR + 38, - CSSMERR_TP_INVALID_CALLBACK = CSSM_TP_BASE_TP_ERROR + 39, - CSSMERR_TP_INVALID_TUPLE = CSSM_TP_BASE_TP_ERROR + 40, - CSSMERR_TP_NOT_SIGNER = CSSM_TP_BASE_TP_ERROR + 41, - CSSMERR_TP_NOT_TRUSTED = CSSM_TP_BASE_TP_ERROR + 42, - CSSMERR_TP_NO_DEFAULT_AUTHORITY = CSSM_TP_BASE_TP_ERROR + 43, - CSSMERR_TP_REJECTED_FORM = CSSM_TP_BASE_TP_ERROR + 44, - CSSMERR_TP_REQUEST_LOST = CSSM_TP_BASE_TP_ERROR + 45, - CSSMERR_TP_REQUEST_REJECTED = CSSM_TP_BASE_TP_ERROR + 46, - CSSMERR_TP_UNSUPPORTED_ADDR_TYPE = CSSM_TP_BASE_TP_ERROR + 47, - CSSMERR_TP_UNSUPPORTED_SERVICE = CSSM_TP_BASE_TP_ERROR + 48, - CSSMERR_TP_INVALID_TUPLEGROUP_POINTER = CSSM_TP_BASE_TP_ERROR + 49, - CSSMERR_TP_INVALID_TUPLEGROUP = CSSM_TP_BASE_TP_ERROR + 50 -}; - - -enum { - CSSMERR_AC_INTERNAL_ERROR = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INTERNAL_ERROR, - CSSMERR_AC_MEMORY_ERROR = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_MEMORY_ERROR, - CSSMERR_AC_MDS_ERROR = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_MDS_ERROR, - CSSMERR_AC_INVALID_POINTER = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_POINTER, - CSSMERR_AC_INVALID_INPUT_POINTER = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_INPUT_POINTER, - CSSMERR_AC_INVALID_OUTPUT_POINTER = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_OUTPUT_POINTER, - CSSMERR_AC_FUNCTION_NOT_IMPLEMENTED = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED, - CSSMERR_AC_SELF_CHECK_FAILED = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_SELF_CHECK_FAILED, - CSSMERR_AC_OS_ACCESS_DENIED = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_OS_ACCESS_DENIED, - CSSMERR_AC_FUNCTION_FAILED = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_FUNCTION_FAILED, - CSSMERR_AC_INVALID_CONTEXT_HANDLE = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_CONTEXT_HANDLE, - CSSMERR_AC_INVALID_DATA = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_DATA, - CSSMERR_AC_INVALID_DB_LIST = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_DB_LIST, - CSSMERR_AC_INVALID_PASSTHROUGH_ID = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_PASSTHROUGH_ID, - CSSMERR_AC_INVALID_DL_HANDLE = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_DL_HANDLE, - CSSMERR_AC_INVALID_CL_HANDLE = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_CL_HANDLE, - CSSMERR_AC_INVALID_TP_HANDLE = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_TP_HANDLE, - CSSMERR_AC_INVALID_DB_HANDLE = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_DB_HANDLE, - CSSMERR_AC_INVALID_DB_LIST_POINTER = - CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INVALID_DB_LIST_POINTER -}; - - -enum { - CSSM_AC_BASE_AC_ERROR = - CSSM_AC_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT, - CSSMERR_AC_INVALID_BASE_ACLS = CSSM_AC_BASE_AC_ERROR + 1, - CSSMERR_AC_INVALID_TUPLE_CREDENTIALS = CSSM_AC_BASE_AC_ERROR + 2, - CSSMERR_AC_INVALID_ENCODING = CSSM_AC_BASE_AC_ERROR + 3, - CSSMERR_AC_INVALID_VALIDITY_PERIOD = CSSM_AC_BASE_AC_ERROR + 4, - CSSMERR_AC_INVALID_REQUESTOR = CSSM_AC_BASE_AC_ERROR + 5, - CSSMERR_AC_INVALID_REQUEST_DESCRIPTOR = CSSM_AC_BASE_AC_ERROR + 6 -}; - - -enum { - CSSMERR_CL_INTERNAL_ERROR = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INTERNAL_ERROR, - CSSMERR_CL_MEMORY_ERROR = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_MEMORY_ERROR, - CSSMERR_CL_MDS_ERROR = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_MDS_ERROR, - CSSMERR_CL_INVALID_POINTER = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_POINTER, - CSSMERR_CL_INVALID_INPUT_POINTER = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_INPUT_POINTER, - CSSMERR_CL_INVALID_OUTPUT_POINTER = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_OUTPUT_POINTER, - CSSMERR_CL_FUNCTION_NOT_IMPLEMENTED = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED, - CSSMERR_CL_SELF_CHECK_FAILED = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_SELF_CHECK_FAILED, - CSSMERR_CL_OS_ACCESS_DENIED = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_OS_ACCESS_DENIED, - CSSMERR_CL_FUNCTION_FAILED = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_FUNCTION_FAILED, - CSSMERR_CL_INVALID_CONTEXT_HANDLE = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_CONTEXT_HANDLE, - CSSMERR_CL_INVALID_CERTGROUP_POINTER = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_CERTGROUP_POINTER, - CSSMERR_CL_INVALID_CERT_POINTER = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_CERT_POINTER, - CSSMERR_CL_INVALID_CRL_POINTER = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_CRL_POINTER, - CSSMERR_CL_INVALID_FIELD_POINTER = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_FIELD_POINTER, - CSSMERR_CL_INVALID_DATA = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_DATA, - CSSMERR_CL_CRL_ALREADY_SIGNED = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_CRL_ALREADY_SIGNED, - CSSMERR_CL_INVALID_NUMBER_OF_FIELDS = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_NUMBER_OF_FIELDS, - CSSMERR_CL_VERIFICATION_FAILURE = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_VERIFICATION_FAILURE, - CSSMERR_CL_UNKNOWN_FORMAT = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_UNKNOWN_FORMAT, - CSSMERR_CL_UNKNOWN_TAG = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_UNKNOWN_TAG, - CSSMERR_CL_INVALID_PASSTHROUGH_ID = - CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INVALID_PASSTHROUGH_ID -}; - - -enum { - CSSM_CL_BASE_CL_ERROR = - CSSM_CL_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT, - CSSMERR_CL_INVALID_BUNDLE_POINTER = CSSM_CL_BASE_CL_ERROR + 1, - CSSMERR_CL_INVALID_CACHE_HANDLE = CSSM_CL_BASE_CL_ERROR + 2, - CSSMERR_CL_INVALID_RESULTS_HANDLE = CSSM_CL_BASE_CL_ERROR + 3, - CSSMERR_CL_INVALID_BUNDLE_INFO = CSSM_CL_BASE_CL_ERROR + 4, - CSSMERR_CL_INVALID_CRL_INDEX = CSSM_CL_BASE_CL_ERROR + 5, - CSSMERR_CL_INVALID_SCOPE = CSSM_CL_BASE_CL_ERROR + 6, - CSSMERR_CL_NO_FIELD_VALUES = CSSM_CL_BASE_CL_ERROR + 7, - CSSMERR_CL_SCOPE_NOT_SUPPORTED = CSSM_CL_BASE_CL_ERROR + 8 -}; - - -enum { - CSSMERR_DL_INTERNAL_ERROR = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INTERNAL_ERROR, - CSSMERR_DL_MEMORY_ERROR = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_MEMORY_ERROR, - CSSMERR_DL_MDS_ERROR = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_MDS_ERROR, - CSSMERR_DL_INVALID_POINTER = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_POINTER, - CSSMERR_DL_INVALID_INPUT_POINTER = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_INPUT_POINTER, - CSSMERR_DL_INVALID_OUTPUT_POINTER = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_OUTPUT_POINTER, - CSSMERR_DL_FUNCTION_NOT_IMPLEMENTED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED, - CSSMERR_DL_SELF_CHECK_FAILED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_SELF_CHECK_FAILED, - CSSMERR_DL_OS_ACCESS_DENIED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_OS_ACCESS_DENIED, - CSSMERR_DL_FUNCTION_FAILED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_FUNCTION_FAILED, - CSSMERR_DL_INVALID_CSP_HANDLE = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_CSP_HANDLE, - CSSMERR_DL_INVALID_DL_HANDLE = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_DL_HANDLE, - CSSMERR_DL_INVALID_CL_HANDLE = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_CL_HANDLE, - CSSMERR_DL_INVALID_DB_LIST_POINTER = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_DB_LIST_POINTER -}; - - -enum { - CSSMERR_DL_OPERATION_AUTH_DENIED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_OPERATION_AUTH_DENIED, - CSSMERR_DL_OBJECT_USE_AUTH_DENIED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_OBJECT_USE_AUTH_DENIED, - CSSMERR_DL_OBJECT_MANIP_AUTH_DENIED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_OBJECT_MANIP_AUTH_DENIED, - CSSMERR_DL_OBJECT_ACL_NOT_SUPPORTED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_OBJECT_ACL_NOT_SUPPORTED, - CSSMERR_DL_OBJECT_ACL_REQUIRED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_OBJECT_ACL_REQUIRED, - CSSMERR_DL_INVALID_ACCESS_CREDENTIALS = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_ACCESS_CREDENTIALS, - CSSMERR_DL_INVALID_ACL_BASE_CERTS = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_BASE_CERTS, - CSSMERR_DL_ACL_BASE_CERTS_NOT_SUPPORTED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_ACL_BASE_CERTS_NOT_SUPPORTED, - CSSMERR_DL_INVALID_SAMPLE_VALUE = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_SAMPLE_VALUE, - CSSMERR_DL_SAMPLE_VALUE_NOT_SUPPORTED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED, - CSSMERR_DL_INVALID_ACL_SUBJECT_VALUE = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE, - CSSMERR_DL_ACL_SUBJECT_TYPE_NOT_SUPPORTED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_ACL_SUBJECT_TYPE_NOT_SUPPORTED, - CSSMERR_DL_INVALID_ACL_CHALLENGE_CALLBACK = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_CHALLENGE_CALLBACK, - CSSMERR_DL_ACL_CHALLENGE_CALLBACK_FAILED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_ACL_CHALLENGE_CALLBACK_FAILED, - CSSMERR_DL_INVALID_ACL_ENTRY_TAG = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_ENTRY_TAG, - CSSMERR_DL_ACL_ENTRY_TAG_NOT_FOUND = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_ACL_ENTRY_TAG_NOT_FOUND, - CSSMERR_DL_INVALID_ACL_EDIT_MODE = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_ACL_EDIT_MODE, - CSSMERR_DL_ACL_CHANGE_FAILED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_ACL_CHANGE_FAILED, - CSSMERR_DL_INVALID_NEW_ACL_ENTRY = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_NEW_ACL_ENTRY, - CSSMERR_DL_INVALID_NEW_ACL_OWNER = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_NEW_ACL_OWNER, - CSSMERR_DL_ACL_DELETE_FAILED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_ACL_DELETE_FAILED, - CSSMERR_DL_ACL_REPLACE_FAILED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_ACL_REPLACE_FAILED, - CSSMERR_DL_ACL_ADD_FAILED = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_ACL_ADD_FAILED -}; - - -enum { - CSSMERR_DL_INVALID_DB_HANDLE = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_DB_HANDLE, - CSSMERR_DL_INVALID_PASSTHROUGH_ID = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_PASSTHROUGH_ID, - CSSMERR_DL_INVALID_NETWORK_ADDR = - CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INVALID_NETWORK_ADDR -}; - - -enum { - CSSM_DL_BASE_DL_ERROR = - CSSM_DL_BASE_ERROR + CSSM_ERRORCODE_COMMON_EXTENT, - CSSMERR_DL_DATABASE_CORRUPT = CSSM_DL_BASE_DL_ERROR + 1, - CSSMERR_DL_INVALID_RECORD_INDEX = CSSM_DL_BASE_DL_ERROR + 8, - CSSMERR_DL_INVALID_RECORDTYPE = CSSM_DL_BASE_DL_ERROR + 9, - CSSMERR_DL_INVALID_FIELD_NAME = CSSM_DL_BASE_DL_ERROR + 10, - CSSMERR_DL_UNSUPPORTED_FIELD_FORMAT = CSSM_DL_BASE_DL_ERROR + 11, - CSSMERR_DL_UNSUPPORTED_INDEX_INFO = CSSM_DL_BASE_DL_ERROR + 12, - CSSMERR_DL_UNSUPPORTED_LOCALITY = CSSM_DL_BASE_DL_ERROR + 13, - CSSMERR_DL_UNSUPPORTED_NUM_ATTRIBUTES = CSSM_DL_BASE_DL_ERROR + 14, - CSSMERR_DL_UNSUPPORTED_NUM_INDEXES = CSSM_DL_BASE_DL_ERROR + 15, - CSSMERR_DL_UNSUPPORTED_NUM_RECORDTYPES = CSSM_DL_BASE_DL_ERROR + 16, - CSSMERR_DL_UNSUPPORTED_RECORDTYPE = CSSM_DL_BASE_DL_ERROR + 17, - CSSMERR_DL_FIELD_SPECIFIED_MULTIPLE = CSSM_DL_BASE_DL_ERROR + 18, - CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT = CSSM_DL_BASE_DL_ERROR + 19, - CSSMERR_DL_INVALID_PARSING_MODULE = CSSM_DL_BASE_DL_ERROR + 20, - CSSMERR_DL_INVALID_DB_NAME = CSSM_DL_BASE_DL_ERROR + 22, - CSSMERR_DL_DATASTORE_DOESNOT_EXIST = CSSM_DL_BASE_DL_ERROR + 23, - CSSMERR_DL_DATASTORE_ALREADY_EXISTS = CSSM_DL_BASE_DL_ERROR + 24, - CSSMERR_DL_DB_LOCKED = CSSM_DL_BASE_DL_ERROR + 25, - CSSMERR_DL_DATASTORE_IS_OPEN = CSSM_DL_BASE_DL_ERROR + 26, - CSSMERR_DL_RECORD_NOT_FOUND = CSSM_DL_BASE_DL_ERROR + 27, - CSSMERR_DL_MISSING_VALUE = CSSM_DL_BASE_DL_ERROR + 28, - CSSMERR_DL_UNSUPPORTED_QUERY = CSSM_DL_BASE_DL_ERROR + 29, - CSSMERR_DL_UNSUPPORTED_QUERY_LIMITS = CSSM_DL_BASE_DL_ERROR + 30, - CSSMERR_DL_UNSUPPORTED_NUM_SELECTION_PREDS = CSSM_DL_BASE_DL_ERROR + 31, - CSSMERR_DL_UNSUPPORTED_OPERATOR = CSSM_DL_BASE_DL_ERROR + 33, - CSSMERR_DL_INVALID_RESULTS_HANDLE = CSSM_DL_BASE_DL_ERROR + 34, - CSSMERR_DL_INVALID_DB_LOCATION = CSSM_DL_BASE_DL_ERROR + 35, - CSSMERR_DL_INVALID_ACCESS_REQUEST = CSSM_DL_BASE_DL_ERROR + 36, - CSSMERR_DL_INVALID_INDEX_INFO = CSSM_DL_BASE_DL_ERROR + 37, - CSSMERR_DL_INVALID_SELECTION_TAG = CSSM_DL_BASE_DL_ERROR + 38, - CSSMERR_DL_INVALID_NEW_OWNER = CSSM_DL_BASE_DL_ERROR + 39, - CSSMERR_DL_INVALID_RECORD_UID = CSSM_DL_BASE_DL_ERROR + 40, - CSSMERR_DL_INVALID_UNIQUE_INDEX_DATA = CSSM_DL_BASE_DL_ERROR + 41, - CSSMERR_DL_INVALID_MODIFY_MODE = CSSM_DL_BASE_DL_ERROR + 42, - CSSMERR_DL_INVALID_OPEN_PARAMETERS = CSSM_DL_BASE_DL_ERROR + 43, - CSSMERR_DL_RECORD_MODIFIED = CSSM_DL_BASE_DL_ERROR + 44, - CSSMERR_DL_ENDOFDATA = CSSM_DL_BASE_DL_ERROR + 45, - CSSMERR_DL_INVALID_QUERY = CSSM_DL_BASE_DL_ERROR + 46, - CSSMERR_DL_INVALID_VALUE = CSSM_DL_BASE_DL_ERROR + 47, - CSSMERR_DL_MULTIPLE_VALUES_UNSUPPORTED = CSSM_DL_BASE_DL_ERROR + 48, - CSSMERR_DL_STALE_UNIQUE_RECORD = CSSM_DL_BASE_DL_ERROR + 49 -}; - - - -} -extern "C" { - - - - -typedef CSSM_INTPTR CSSM_HANDLE, *CSSM_HANDLE_PTR; - -typedef uint64 CSSM_LONG_HANDLE, *CSSM_LONG_HANDLE_PTR; - -typedef CSSM_HANDLE CSSM_MODULE_HANDLE, *CSSM_MODULE_HANDLE_PTR; - -typedef CSSM_LONG_HANDLE CSSM_CC_HANDLE; - -typedef CSSM_MODULE_HANDLE CSSM_CSP_HANDLE; - -typedef CSSM_MODULE_HANDLE CSSM_TP_HANDLE; - -typedef CSSM_MODULE_HANDLE CSSM_AC_HANDLE; - -typedef CSSM_MODULE_HANDLE CSSM_CL_HANDLE; - -typedef CSSM_MODULE_HANDLE CSSM_DL_HANDLE; - -typedef CSSM_MODULE_HANDLE CSSM_DB_HANDLE; - - - -enum { - CSSM_INVALID_HANDLE = 0 -}; - - - - -typedef sint32 CSSM_BOOL; -enum { - CSSM_FALSE = 0, - CSSM_TRUE = !CSSM_FALSE -}; - - -typedef sint32 CSSM_RETURN; -enum { - CSSM_OK = 0 -}; - -enum { - CSSM_MODULE_STRING_SIZE = 64 -}; -typedef char CSSM_STRING [CSSM_MODULE_STRING_SIZE + 4]; - -typedef struct cssm_data { - CSSM_SIZE Length; - uint8 *Data; -} CSSM_DATA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DATA_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_guid { - uint32 Data1; - uint16 Data2; - uint16 Data3; - uint8 Data4[8]; -} CSSM_GUID __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_GUID_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_BITMASK; -typedef CSSM_BITMASK CSSM_KEY_HIERARCHY; -enum { - CSSM_KEY_HIERARCHY_NONE = 0, - CSSM_KEY_HIERARCHY_INTEG = 1, - CSSM_KEY_HIERARCHY_EXPORT = 2 -}; - -typedef CSSM_BITMASK CSSM_PVC_MODE; -enum { - CSSM_PVC_NONE = 0, - CSSM_PVC_APP = 1, - CSSM_PVC_SP = 2 -}; - -typedef uint32 CSSM_PRIVILEGE_SCOPE; -enum { - CSSM_PRIVILEGE_SCOPE_NONE = 0, - CSSM_PRIVILEGE_SCOPE_PROCESS = 1, - CSSM_PRIVILEGE_SCOPE_THREAD = 2 -}; - -typedef struct cssm_version { - uint32 Major; - uint32 Minor; -} CSSM_VERSION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_VERSION_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_SERVICE_MASK; -enum { - CSSM_SERVICE_CSSM = 0x1, - CSSM_SERVICE_CSP = 0x2, - CSSM_SERVICE_DL = 0x4, - CSSM_SERVICE_CL = 0x8, - CSSM_SERVICE_TP = 0x10, - CSSM_SERVICE_AC = 0x20, - CSSM_SERVICE_KR = 0x40 -}; - -typedef CSSM_SERVICE_MASK CSSM_SERVICE_TYPE; - -typedef struct cssm_subservice_uid { - CSSM_GUID Guid; - CSSM_VERSION Version; - uint32 SubserviceId; - CSSM_SERVICE_TYPE SubserviceType; -} CSSM_SUBSERVICE_UID __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SUBSERVICE_UID_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_MODULE_EVENT, *CSSM_MODULE_EVENT_PTR; -enum { - CSSM_NOTIFY_INSERT = 1, - CSSM_NOTIFY_REMOVE = 2, - CSSM_NOTIFY_FAULT = 3 -}; - -typedef CSSM_RETURN ( *CSSM_API_ModuleEventHandler) - (const CSSM_GUID *ModuleGuid, - void* AppNotifyCallbackCtx, - uint32 SubserviceId, - CSSM_SERVICE_TYPE ServiceType, - CSSM_MODULE_EVENT EventType); - -typedef uint32 CSSM_ATTACH_FLAGS; -enum { - CSSM_ATTACH_READ_ONLY = 0x00000001 -}; - - - -typedef uint64 CSSM_PRIVILEGE; -typedef CSSM_PRIVILEGE CSSM_USEE_TAG; -enum { - CSSM_USEE_LAST = 0xFF, - CSSM_USEE_NONE = 0, - CSSM_USEE_DOMESTIC = 1, - CSSM_USEE_FINANCIAL = 2, - CSSM_USEE_KRLE = 3, - CSSM_USEE_KRENT = 4, - CSSM_USEE_SSL = 5, - CSSM_USEE_AUTHENTICATION = 6, - CSSM_USEE_KEYEXCH = 7, - CSSM_USEE_MEDICAL = 8, - CSSM_USEE_INSURANCE = 9, - CSSM_USEE_WEAK = 10 -}; - -typedef uint32 CSSM_NET_ADDRESS_TYPE; -enum { - CSSM_ADDR_NONE = 0, - CSSM_ADDR_CUSTOM = 1, - CSSM_ADDR_URL = 2, - CSSM_ADDR_SOCKADDR = 3, - CSSM_ADDR_NAME = 4 -}; - -typedef struct cssm_net_address { - CSSM_NET_ADDRESS_TYPE AddressType; - CSSM_DATA Address; -} CSSM_NET_ADDRESS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_NET_ADDRESS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_NET_PROTOCOL; -enum { - CSSM_NET_PROTO_NONE = 0, - CSSM_NET_PROTO_CUSTOM = 1, - CSSM_NET_PROTO_UNSPECIFIED = 2, - CSSM_NET_PROTO_LDAP = 3, - CSSM_NET_PROTO_LDAPS = 4, - CSSM_NET_PROTO_LDAPNS = 5, - CSSM_NET_PROTO_X500DAP = 6, - CSSM_NET_PROTO_FTP = 7, - CSSM_NET_PROTO_FTPS = 8, - CSSM_NET_PROTO_OCSP = 9, - CSSM_NET_PROTO_CMP = 10, - CSSM_NET_PROTO_CMPS = 11 -}; - -typedef CSSM_RETURN ( *CSSM_CALLBACK) - (CSSM_DATA_PTR OutData, void *CallerCtx); - -typedef struct cssm_crypto_data { - CSSM_DATA Param; - CSSM_CALLBACK Callback; - void *CallerCtx; -} CSSM_CRYPTO_DATA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_CRYPTO_DATA_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef sint32 CSSM_WORDID_TYPE; -enum { - CSSM_WORDID__UNK_ = -1, - CSSM_WORDID__NLU_ = 0, - CSSM_WORDID__STAR_ = 1, - CSSM_WORDID_A = 2, - CSSM_WORDID_ACL = 3, - CSSM_WORDID_ALPHA = 4, - CSSM_WORDID_B = 5, - CSSM_WORDID_BER = 6, - CSSM_WORDID_BINARY = 7, - CSSM_WORDID_BIOMETRIC = 8, - CSSM_WORDID_C = 9, - CSSM_WORDID_CANCELED = 10, - CSSM_WORDID_CERT = 11, - CSSM_WORDID_COMMENT = 12, - CSSM_WORDID_CRL = 13, - CSSM_WORDID_CUSTOM = 14, - CSSM_WORDID_D = 15, - CSSM_WORDID_DATE = 16, - CSSM_WORDID_DB_DELETE = 17, - CSSM_WORDID_DB_EXEC_STORED_QUERY = 18, - CSSM_WORDID_DB_INSERT = 19, - CSSM_WORDID_DB_MODIFY = 20, - CSSM_WORDID_DB_READ = 21, - CSSM_WORDID_DBS_CREATE = 22, - CSSM_WORDID_DBS_DELETE = 23, - CSSM_WORDID_DECRYPT = 24, - CSSM_WORDID_DELETE = 25, - CSSM_WORDID_DELTA_CRL = 26, - CSSM_WORDID_DER = 27, - CSSM_WORDID_DERIVE = 28, - CSSM_WORDID_DISPLAY = 29, - CSSM_WORDID_DO = 30, - CSSM_WORDID_DSA = 31, - CSSM_WORDID_DSA_SHA1 = 32, - CSSM_WORDID_E = 33, - CSSM_WORDID_ELGAMAL = 34, - CSSM_WORDID_ENCRYPT = 35, - CSSM_WORDID_ENTRY = 36, - CSSM_WORDID_EXPORT_CLEAR = 37, - CSSM_WORDID_EXPORT_WRAPPED = 38, - CSSM_WORDID_G = 39, - CSSM_WORDID_GE = 40, - CSSM_WORDID_GENKEY = 41, - CSSM_WORDID_HASH = 42, - CSSM_WORDID_HASHED_PASSWORD = 43, - CSSM_WORDID_HASHED_SUBJECT = 44, - CSSM_WORDID_HAVAL = 45, - CSSM_WORDID_IBCHASH = 46, - CSSM_WORDID_IMPORT_CLEAR = 47, - CSSM_WORDID_IMPORT_WRAPPED = 48, - CSSM_WORDID_INTEL = 49, - CSSM_WORDID_ISSUER = 50, - CSSM_WORDID_ISSUER_INFO = 51, - CSSM_WORDID_K_OF_N = 52, - CSSM_WORDID_KEA = 53, - CSSM_WORDID_KEYHOLDER = 54, - CSSM_WORDID_L = 55, - CSSM_WORDID_LE = 56, - CSSM_WORDID_LOGIN = 57, - CSSM_WORDID_LOGIN_NAME = 58, - CSSM_WORDID_MAC = 59, - CSSM_WORDID_MD2 = 60, - CSSM_WORDID_MD2WITHRSA = 61, - CSSM_WORDID_MD4 = 62, - CSSM_WORDID_MD5 = 63, - CSSM_WORDID_MD5WITHRSA = 64, - CSSM_WORDID_N = 65, - CSSM_WORDID_NAME = 66, - CSSM_WORDID_NDR = 67, - CSSM_WORDID_NHASH = 68, - CSSM_WORDID_NOT_AFTER = 69, - CSSM_WORDID_NOT_BEFORE = 70, - CSSM_WORDID_NULL = 71, - CSSM_WORDID_NUMERIC = 72, - CSSM_WORDID_OBJECT_HASH = 73, - CSSM_WORDID_ONE_TIME = 74, - CSSM_WORDID_ONLINE = 75, - CSSM_WORDID_OWNER = 76, - CSSM_WORDID_P = 77, - CSSM_WORDID_PAM_NAME = 78, - CSSM_WORDID_PASSWORD = 79, - CSSM_WORDID_PGP = 80, - CSSM_WORDID_PREFIX = 81, - CSSM_WORDID_PRIVATE_KEY = 82, - CSSM_WORDID_PROMPTED_BIOMETRIC = 83, - CSSM_WORDID_PROMPTED_PASSWORD = 84, - CSSM_WORDID_PROPAGATE = 85, - CSSM_WORDID_PROTECTED_BIOMETRIC = 86, - CSSM_WORDID_PROTECTED_PASSWORD = 87, - CSSM_WORDID_PROTECTED_PIN = 88, - CSSM_WORDID_PUBLIC_KEY = 89, - CSSM_WORDID_PUBLIC_KEY_FROM_CERT = 90, - CSSM_WORDID_Q = 91, - CSSM_WORDID_RANGE = 92, - CSSM_WORDID_REVAL = 93, - CSSM_WORDID_RIPEMAC = 94, - CSSM_WORDID_RIPEMD = 95, - CSSM_WORDID_RIPEMD160 = 96, - CSSM_WORDID_RSA = 97, - CSSM_WORDID_RSA_ISO9796 = 98, - CSSM_WORDID_RSA_PKCS = 99, - CSSM_WORDID_RSA_PKCS_MD5 = 100, - CSSM_WORDID_RSA_PKCS_SHA1 = 101, - CSSM_WORDID_RSA_PKCS1 = 102, - CSSM_WORDID_RSA_PKCS1_MD5 = 103, - CSSM_WORDID_RSA_PKCS1_SHA1 = 104, - CSSM_WORDID_RSA_PKCS1_SIG = 105, - CSSM_WORDID_RSA_RAW = 106, - CSSM_WORDID_SDSIV1 = 107, - CSSM_WORDID_SEQUENCE = 108, - CSSM_WORDID_SET = 109, - CSSM_WORDID_SEXPR = 110, - CSSM_WORDID_SHA1 = 111, - CSSM_WORDID_SHA1WITHDSA = 112, - CSSM_WORDID_SHA1WITHECDSA = 113, - CSSM_WORDID_SHA1WITHRSA = 114, - CSSM_WORDID_SIGN = 115, - CSSM_WORDID_SIGNATURE = 116, - CSSM_WORDID_SIGNED_NONCE = 117, - CSSM_WORDID_SIGNED_SECRET = 118, - CSSM_WORDID_SPKI = 119, - CSSM_WORDID_SUBJECT = 120, - CSSM_WORDID_SUBJECT_INFO = 121, - CSSM_WORDID_TAG = 122, - CSSM_WORDID_THRESHOLD = 123, - CSSM_WORDID_TIME = 124, - CSSM_WORDID_URI = 125, - CSSM_WORDID_VERSION = 126, - CSSM_WORDID_X509_ATTRIBUTE = 127, - CSSM_WORDID_X509V1 = 128, - CSSM_WORDID_X509V2 = 129, - CSSM_WORDID_X509V3 = 130, - CSSM_WORDID_X9_ATTRIBUTE = 131, - CSSM_WORDID_VENDOR_START = 0x00010000, - CSSM_WORDID_VENDOR_END = 0x7FFF0000 -}; - -typedef uint32 CSSM_LIST_ELEMENT_TYPE, *CSSM_LIST_ELEMENT_TYPE_PTR; -enum { - CSSM_LIST_ELEMENT_DATUM = 0x00, - CSSM_LIST_ELEMENT_SUBLIST = 0x01, - CSSM_LIST_ELEMENT_WORDID = 0x02 -}; - -typedef uint32 CSSM_LIST_TYPE, *CSSM_LIST_TYPE_PTR; -enum { - CSSM_LIST_TYPE_UNKNOWN = 0, - CSSM_LIST_TYPE_CUSTOM = 1, - CSSM_LIST_TYPE_SEXPR = 2 -}; - -typedef struct cssm_list_element *CSSM_LIST_ELEMENT_PTR; - -typedef struct cssm_list { - CSSM_LIST_TYPE ListType; - CSSM_LIST_ELEMENT_PTR Head; - CSSM_LIST_ELEMENT_PTR Tail; -} CSSM_LIST __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_LIST_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_list_element { - struct cssm_list_element *NextElement; - CSSM_WORDID_TYPE WordID; - - CSSM_LIST_ELEMENT_TYPE ElementType; - union { - CSSM_LIST Sublist; - CSSM_DATA Word; - } Element; -} CSSM_LIST_ELEMENT; - -typedef struct { - CSSM_LIST Issuer; - CSSM_LIST Subject; - CSSM_BOOL Delegate; - CSSM_LIST AuthorizationTag; - CSSM_LIST ValidityPeriod; -} CSSM_TUPLE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TUPLE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_tuplegroup { - uint32 NumberOfTuples; - CSSM_TUPLE_PTR Tuples; -} CSSM_TUPLEGROUP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TUPLEGROUP_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef CSSM_WORDID_TYPE CSSM_SAMPLE_TYPE; -enum { - CSSM_SAMPLE_TYPE_PASSWORD = CSSM_WORDID_PASSWORD, - CSSM_SAMPLE_TYPE_HASHED_PASSWORD = CSSM_WORDID_HASHED_PASSWORD, - CSSM_SAMPLE_TYPE_PROTECTED_PASSWORD = CSSM_WORDID_PROTECTED_PASSWORD, - CSSM_SAMPLE_TYPE_PROMPTED_PASSWORD = CSSM_WORDID_PROMPTED_PASSWORD, - CSSM_SAMPLE_TYPE_SIGNED_NONCE = CSSM_WORDID_SIGNED_NONCE, - CSSM_SAMPLE_TYPE_SIGNED_SECRET = CSSM_WORDID_SIGNED_SECRET, - CSSM_SAMPLE_TYPE_BIOMETRIC = CSSM_WORDID_BIOMETRIC, - CSSM_SAMPLE_TYPE_PROTECTED_BIOMETRIC = CSSM_WORDID_PROTECTED_BIOMETRIC, - CSSM_SAMPLE_TYPE_PROMPTED_BIOMETRIC = CSSM_WORDID_PROMPTED_BIOMETRIC, - CSSM_SAMPLE_TYPE_THRESHOLD = CSSM_WORDID_THRESHOLD -}; - -typedef struct cssm_sample { - CSSM_LIST TypedSample; - const CSSM_SUBSERVICE_UID *Verifier; -} CSSM_SAMPLE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SAMPLE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_samplegroup { - uint32 NumberOfSamples; - const CSSM_SAMPLE *Samples; -} CSSM_SAMPLEGROUP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SAMPLEGROUP_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef void *( *CSSM_MALLOC) - (CSSM_SIZE size, - void *allocref); - -typedef void ( *CSSM_FREE) - (void *memblock, - void *allocref); - -typedef void *( *CSSM_REALLOC) - (void *memblock, - CSSM_SIZE size, - void *allocref); - -typedef void *( *CSSM_CALLOC) - (uint32 num, - CSSM_SIZE size, - void *allocref); - -typedef struct cssm_memory_funcs { - CSSM_MALLOC malloc_func; - CSSM_FREE free_func; - CSSM_REALLOC realloc_func; - CSSM_CALLOC calloc_func; - void *AllocRef; -} CSSM_MEMORY_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_MEMORY_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef CSSM_MEMORY_FUNCS CSSM_API_MEMORY_FUNCS; -typedef CSSM_API_MEMORY_FUNCS *CSSM_API_MEMORY_FUNCS_PTR; - -typedef CSSM_RETURN ( * CSSM_CHALLENGE_CALLBACK) - (const CSSM_LIST *Challenge, - CSSM_SAMPLEGROUP_PTR Response, - void *CallerCtx, - const CSSM_MEMORY_FUNCS *MemFuncs); - -typedef uint32 CSSM_CERT_TYPE, *CSSM_CERT_TYPE_PTR; -enum { - CSSM_CERT_UNKNOWN = 0x00, - CSSM_CERT_X_509v1 = 0x01, - CSSM_CERT_X_509v2 = 0x02, - CSSM_CERT_X_509v3 = 0x03, - CSSM_CERT_PGP = 0x04, - CSSM_CERT_SPKI = 0x05, - CSSM_CERT_SDSIv1 = 0x06, - CSSM_CERT_Intel = 0x08, - CSSM_CERT_X_509_ATTRIBUTE = 0x09, - CSSM_CERT_X9_ATTRIBUTE = 0x0A, - CSSM_CERT_TUPLE = 0x0B, - CSSM_CERT_ACL_ENTRY = 0x0C, - CSSM_CERT_MULTIPLE = 0x7FFE, - CSSM_CERT_LAST = 0x7FFF, - - - - CSSM_CL_CUSTOM_CERT_TYPE = 0x08000 -}; - -typedef uint32 CSSM_CERT_ENCODING, *CSSM_CERT_ENCODING_PTR; -enum { - CSSM_CERT_ENCODING_UNKNOWN = 0x00, - CSSM_CERT_ENCODING_CUSTOM = 0x01, - CSSM_CERT_ENCODING_BER = 0x02, - CSSM_CERT_ENCODING_DER = 0x03, - CSSM_CERT_ENCODING_NDR = 0x04, - CSSM_CERT_ENCODING_SEXPR = 0x05, - CSSM_CERT_ENCODING_PGP = 0x06, - CSSM_CERT_ENCODING_MULTIPLE = 0x7FFE, - CSSM_CERT_ENCODING_LAST = 0x7FFF, - - - - CSSM_CL_CUSTOM_CERT_ENCODING = 0x8000 -}; - -typedef struct cssm_encoded_cert { - CSSM_CERT_TYPE CertType; - CSSM_CERT_ENCODING CertEncoding; - CSSM_DATA CertBlob; -} CSSM_ENCODED_CERT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_ENCODED_CERT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_CERT_PARSE_FORMAT, *CSSM_CERT_PARSE_FORMAT_PTR; -enum { - CSSM_CERT_PARSE_FORMAT_NONE = 0x00, - CSSM_CERT_PARSE_FORMAT_CUSTOM = 0x01, - CSSM_CERT_PARSE_FORMAT_SEXPR = 0x02, - CSSM_CERT_PARSE_FORMAT_COMPLEX = 0x03, - CSSM_CERT_PARSE_FORMAT_OID_NAMED = 0x04, - CSSM_CERT_PARSE_FORMAT_TUPLE = 0x05, - CSSM_CERT_PARSE_FORMAT_MULTIPLE = 0x7FFE, - - - CSSM_CERT_PARSE_FORMAT_LAST = 0x7FFF, - - - - - CSSM_CL_CUSTOM_CERT_PARSE_FORMAT = 0x8000 -}; - -typedef struct cssm_parsed_cert { - CSSM_CERT_TYPE CertType; - CSSM_CERT_PARSE_FORMAT ParsedCertFormat; - - void *ParsedCert; -} CSSM_PARSED_CERT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_PARSED_CERT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_cert_pair { - CSSM_ENCODED_CERT EncodedCert; - CSSM_PARSED_CERT ParsedCert; -} CSSM_CERT_PAIR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_CERT_PAIR_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_CERTGROUP_TYPE, *CSSM_CERTGROUP_TYPE_PTR; -enum { - CSSM_CERTGROUP_DATA = 0x00, - CSSM_CERTGROUP_ENCODED_CERT = 0x01, - CSSM_CERTGROUP_PARSED_CERT = 0x02, - CSSM_CERTGROUP_CERT_PAIR = 0x03 -}; - -typedef struct cssm_certgroup { - CSSM_CERT_TYPE CertType; - CSSM_CERT_ENCODING CertEncoding; - uint32 NumCerts; - union { - CSSM_DATA_PTR CertList; - CSSM_ENCODED_CERT_PTR EncodedCertList; - - CSSM_PARSED_CERT_PTR ParsedCertList; - - CSSM_CERT_PAIR_PTR PairCertList; - - } GroupList; - CSSM_CERTGROUP_TYPE CertGroupType; - - void *Reserved; -} CSSM_CERTGROUP, *CSSM_CERTGROUP_PTR; - -typedef struct cssm_base_certs { - CSSM_TP_HANDLE TPHandle; - CSSM_CL_HANDLE CLHandle; - CSSM_CERTGROUP Certs; -} CSSM_BASE_CERTS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_BASE_CERTS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_access_credentials { - CSSM_STRING EntryTag; - CSSM_BASE_CERTS BaseCerts; - CSSM_SAMPLEGROUP Samples; - CSSM_CHALLENGE_CALLBACK Callback; - void *CallerCtx; -} CSSM_ACCESS_CREDENTIALS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_ACCESS_CREDENTIALS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef sint32 CSSM_ACL_SUBJECT_TYPE; -enum { - CSSM_ACL_SUBJECT_TYPE_ANY = CSSM_WORDID__STAR_, - CSSM_ACL_SUBJECT_TYPE_THRESHOLD = CSSM_WORDID_THRESHOLD, - CSSM_ACL_SUBJECT_TYPE_PASSWORD = CSSM_WORDID_PASSWORD, - CSSM_ACL_SUBJECT_TYPE_PROTECTED_PASSWORD = CSSM_WORDID_PROTECTED_PASSWORD, - CSSM_ACL_SUBJECT_TYPE_PROMPTED_PASSWORD = CSSM_WORDID_PROMPTED_PASSWORD, - CSSM_ACL_SUBJECT_TYPE_PUBLIC_KEY = CSSM_WORDID_PUBLIC_KEY, - CSSM_ACL_SUBJECT_TYPE_HASHED_SUBJECT = CSSM_WORDID_HASHED_SUBJECT, - CSSM_ACL_SUBJECT_TYPE_BIOMETRIC = CSSM_WORDID_BIOMETRIC, - CSSM_ACL_SUBJECT_TYPE_PROTECTED_BIOMETRIC = CSSM_WORDID_PROTECTED_BIOMETRIC, - CSSM_ACL_SUBJECT_TYPE_PROMPTED_BIOMETRIC = CSSM_WORDID_PROMPTED_BIOMETRIC, - CSSM_ACL_SUBJECT_TYPE_LOGIN_NAME = CSSM_WORDID_LOGIN_NAME, - CSSM_ACL_SUBJECT_TYPE_EXT_PAM_NAME = CSSM_WORDID_PAM_NAME -}; - - -typedef sint32 CSSM_ACL_AUTHORIZATION_TAG; -enum { - - - CSSM_ACL_AUTHORIZATION_TAG_VENDOR_DEFINED_START = 0x00010000, - - - CSSM_ACL_AUTHORIZATION_ANY = CSSM_WORDID__STAR_, - - CSSM_ACL_AUTHORIZATION_LOGIN = CSSM_WORDID_LOGIN, - CSSM_ACL_AUTHORIZATION_GENKEY = CSSM_WORDID_GENKEY, - CSSM_ACL_AUTHORIZATION_DELETE = CSSM_WORDID_DELETE, - CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED = CSSM_WORDID_EXPORT_WRAPPED, - CSSM_ACL_AUTHORIZATION_EXPORT_CLEAR = CSSM_WORDID_EXPORT_CLEAR, - CSSM_ACL_AUTHORIZATION_IMPORT_WRAPPED = CSSM_WORDID_IMPORT_WRAPPED, - CSSM_ACL_AUTHORIZATION_IMPORT_CLEAR = CSSM_WORDID_IMPORT_CLEAR, - CSSM_ACL_AUTHORIZATION_SIGN = CSSM_WORDID_SIGN, - CSSM_ACL_AUTHORIZATION_ENCRYPT = CSSM_WORDID_ENCRYPT, - CSSM_ACL_AUTHORIZATION_DECRYPT = CSSM_WORDID_DECRYPT, - CSSM_ACL_AUTHORIZATION_MAC = CSSM_WORDID_MAC, - CSSM_ACL_AUTHORIZATION_DERIVE = CSSM_WORDID_DERIVE, - - CSSM_ACL_AUTHORIZATION_DBS_CREATE = CSSM_WORDID_DBS_CREATE, - CSSM_ACL_AUTHORIZATION_DBS_DELETE = CSSM_WORDID_DBS_DELETE, - CSSM_ACL_AUTHORIZATION_DB_READ = CSSM_WORDID_DB_READ, - CSSM_ACL_AUTHORIZATION_DB_INSERT = CSSM_WORDID_DB_INSERT, - CSSM_ACL_AUTHORIZATION_DB_MODIFY = CSSM_WORDID_DB_MODIFY, - CSSM_ACL_AUTHORIZATION_DB_DELETE = CSSM_WORDID_DB_DELETE -}; - -typedef struct cssm_authorizationgroup { - uint32 NumberOfAuthTags; - CSSM_ACL_AUTHORIZATION_TAG *AuthTags; -} CSSM_AUTHORIZATIONGROUP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_AUTHORIZATIONGROUP_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_acl_validity_period { - CSSM_DATA StartDate; - CSSM_DATA EndDate; -} CSSM_ACL_VALIDITY_PERIOD __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_ACL_VALIDITY_PERIOD_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_acl_entry_prototype { - CSSM_LIST TypedSubject; - CSSM_BOOL Delegate; - CSSM_AUTHORIZATIONGROUP Authorization; - CSSM_ACL_VALIDITY_PERIOD TimeRange; - CSSM_STRING EntryTag; -} CSSM_ACL_ENTRY_PROTOTYPE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_ACL_ENTRY_PROTOTYPE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_acl_owner_prototype { - CSSM_LIST TypedSubject; - CSSM_BOOL Delegate; -} CSSM_ACL_OWNER_PROTOTYPE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_ACL_OWNER_PROTOTYPE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef CSSM_RETURN ( * CSSM_ACL_SUBJECT_CALLBACK) - (const CSSM_LIST *SubjectRequest, - CSSM_LIST_PTR SubjectResponse, - void *CallerContext, - const CSSM_MEMORY_FUNCS *MemFuncs); - -typedef struct cssm_acl_entry_input { - CSSM_ACL_ENTRY_PROTOTYPE Prototype; - CSSM_ACL_SUBJECT_CALLBACK Callback; - void *CallerContext; -} CSSM_ACL_ENTRY_INPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_ACL_ENTRY_INPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_resource_control_context { - CSSM_ACCESS_CREDENTIALS_PTR AccessCred; - CSSM_ACL_ENTRY_INPUT InitialAclEntry; -} CSSM_RESOURCE_CONTROL_CONTEXT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_RESOURCE_CONTROL_CONTEXT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef CSSM_HANDLE CSSM_ACL_HANDLE; - -typedef struct cssm_acl_entry_info { - CSSM_ACL_ENTRY_PROTOTYPE EntryPublicInfo; - CSSM_ACL_HANDLE EntryHandle; -} CSSM_ACL_ENTRY_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_ACL_ENTRY_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_ACL_EDIT_MODE; -enum { - CSSM_ACL_EDIT_MODE_ADD = 1, - CSSM_ACL_EDIT_MODE_DELETE = 2, - CSSM_ACL_EDIT_MODE_REPLACE = 3 -}; - -typedef struct cssm_acl_edit { - CSSM_ACL_EDIT_MODE EditMode; - CSSM_ACL_HANDLE OldEntryHandle; - const CSSM_ACL_ENTRY_INPUT *NewEntry; -} CSSM_ACL_EDIT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_ACL_EDIT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -typedef void ( *CSSM_PROC_ADDR) (); - -typedef CSSM_PROC_ADDR *CSSM_PROC_ADDR_PTR; - -typedef struct cssm_func_name_addr { - CSSM_STRING Name; - CSSM_PROC_ADDR Address; -} CSSM_FUNC_NAME_ADDR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_FUNC_NAME_ADDR_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -typedef struct cssm_date { - uint8 Year[4]; - uint8 Month[2]; - uint8 Day[2]; -} CSSM_DATE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DATE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_range { - uint32 Min; - uint32 Max; -} CSSM_RANGE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_RANGE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_query_size_data { - uint32 SizeInputBlock; - uint32 SizeOutputBlock; -} CSSM_QUERY_SIZE_DATA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_QUERY_SIZE_DATA_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_HEADERVERSION; -enum { - CSSM_KEYHEADER_VERSION = 2 -}; - -typedef struct cssm_key_size { - uint32 LogicalKeySizeInBits; - uint32 EffectiveKeySizeInBits; -} CSSM_KEY_SIZE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_KEY_SIZE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_KEYBLOB_TYPE; -enum { - CSSM_KEYBLOB_RAW = 0, - CSSM_KEYBLOB_REFERENCE = 2, - CSSM_KEYBLOB_WRAPPED = 3, - CSSM_KEYBLOB_OTHER = 0xFFFFFFFF -}; - -typedef uint32 CSSM_KEYBLOB_FORMAT; -enum { - - CSSM_KEYBLOB_RAW_FORMAT_NONE = 0, - - CSSM_KEYBLOB_RAW_FORMAT_PKCS1 = 1, - CSSM_KEYBLOB_RAW_FORMAT_PKCS3 = 2, - CSSM_KEYBLOB_RAW_FORMAT_MSCAPI = 3, - CSSM_KEYBLOB_RAW_FORMAT_PGP = 4, - CSSM_KEYBLOB_RAW_FORMAT_FIPS186 = 5, - CSSM_KEYBLOB_RAW_FORMAT_BSAFE = 6, - CSSM_KEYBLOB_RAW_FORMAT_CCA = 9, - CSSM_KEYBLOB_RAW_FORMAT_PKCS8 = 10, - CSSM_KEYBLOB_RAW_FORMAT_SPKI = 11, - CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING = 12, - CSSM_KEYBLOB_RAW_FORMAT_OTHER = 0xFFFFFFFF -}; -enum { - - CSSM_KEYBLOB_WRAPPED_FORMAT_NONE = 0, - - CSSM_KEYBLOB_WRAPPED_FORMAT_PKCS8 = 1, - CSSM_KEYBLOB_WRAPPED_FORMAT_PKCS7 = 2, - CSSM_KEYBLOB_WRAPPED_FORMAT_MSCAPI = 3, - CSSM_KEYBLOB_WRAPPED_FORMAT_OTHER = 0xFFFFFFFF -}; -enum { - - CSSM_KEYBLOB_REF_FORMAT_INTEGER = 0, - CSSM_KEYBLOB_REF_FORMAT_STRING = 1, - CSSM_KEYBLOB_REF_FORMAT_SPKI = 2, - - CSSM_KEYBLOB_REF_FORMAT_OTHER = 0xFFFFFFFF -}; - -typedef uint32 CSSM_KEYCLASS; -enum { - CSSM_KEYCLASS_PUBLIC_KEY = 0, - CSSM_KEYCLASS_PRIVATE_KEY = 1, - CSSM_KEYCLASS_SESSION_KEY = 2, - CSSM_KEYCLASS_SECRET_PART = 3, - CSSM_KEYCLASS_OTHER = 0xFFFFFFFF -}; - -typedef uint32 CSSM_KEYATTR_FLAGS; -enum { - - CSSM_KEYATTR_RETURN_DEFAULT = 0x00000000, - CSSM_KEYATTR_RETURN_DATA = 0x10000000, - CSSM_KEYATTR_RETURN_REF = 0x20000000, - CSSM_KEYATTR_RETURN_NONE = 0x40000000, - - CSSM_KEYATTR_PERMANENT = 0x00000001, - CSSM_KEYATTR_PRIVATE = 0x00000002, - CSSM_KEYATTR_MODIFIABLE = 0x00000004, - CSSM_KEYATTR_SENSITIVE = 0x00000008, - CSSM_KEYATTR_EXTRACTABLE = 0x00000020, - - CSSM_KEYATTR_ALWAYS_SENSITIVE = 0x00000010, - CSSM_KEYATTR_NEVER_EXTRACTABLE = 0x00000040 -}; - -typedef uint32 CSSM_KEYUSE; -enum { - CSSM_KEYUSE_ANY = 0x80000000, - CSSM_KEYUSE_ENCRYPT = 0x00000001, - CSSM_KEYUSE_DECRYPT = 0x00000002, - CSSM_KEYUSE_SIGN = 0x00000004, - CSSM_KEYUSE_VERIFY = 0x00000008, - CSSM_KEYUSE_SIGN_RECOVER = 0x00000010, - CSSM_KEYUSE_VERIFY_RECOVER = 0x00000020, - CSSM_KEYUSE_WRAP = 0x00000040, - CSSM_KEYUSE_UNWRAP = 0x00000080, - CSSM_KEYUSE_DERIVE = 0x00000100 -}; - -typedef uint32 CSSM_ALGORITHMS; -enum { - CSSM_ALGID_NONE = 0, - CSSM_ALGID_CUSTOM = CSSM_ALGID_NONE + 1, - CSSM_ALGID_DH = CSSM_ALGID_NONE + 2, - CSSM_ALGID_PH = CSSM_ALGID_NONE + 3, - CSSM_ALGID_KEA = CSSM_ALGID_NONE + 4, - CSSM_ALGID_MD2 = CSSM_ALGID_NONE + 5, - CSSM_ALGID_MD4 = CSSM_ALGID_NONE + 6, - CSSM_ALGID_MD5 = CSSM_ALGID_NONE + 7, - CSSM_ALGID_SHA1 = CSSM_ALGID_NONE + 8, - CSSM_ALGID_NHASH = CSSM_ALGID_NONE + 9, - CSSM_ALGID_HAVAL = CSSM_ALGID_NONE + 10, - CSSM_ALGID_RIPEMD = CSSM_ALGID_NONE + 11, - CSSM_ALGID_IBCHASH = CSSM_ALGID_NONE + 12, - CSSM_ALGID_RIPEMAC = CSSM_ALGID_NONE + 13, - CSSM_ALGID_DES = CSSM_ALGID_NONE + 14, - CSSM_ALGID_DESX = CSSM_ALGID_NONE + 15, - CSSM_ALGID_RDES = CSSM_ALGID_NONE + 16, - CSSM_ALGID_3DES_3KEY_EDE = CSSM_ALGID_NONE + 17, - CSSM_ALGID_3DES_2KEY_EDE = CSSM_ALGID_NONE + 18, - CSSM_ALGID_3DES_1KEY_EEE = CSSM_ALGID_NONE + 19, - CSSM_ALGID_3DES_3KEY = CSSM_ALGID_3DES_3KEY_EDE, - CSSM_ALGID_3DES_3KEY_EEE = CSSM_ALGID_NONE + 20, - CSSM_ALGID_3DES_2KEY = CSSM_ALGID_3DES_2KEY_EDE, - CSSM_ALGID_3DES_2KEY_EEE = CSSM_ALGID_NONE + 21, - CSSM_ALGID_3DES_1KEY = CSSM_ALGID_3DES_3KEY_EEE, - CSSM_ALGID_IDEA = CSSM_ALGID_NONE + 22, - CSSM_ALGID_RC2 = CSSM_ALGID_NONE + 23, - CSSM_ALGID_RC5 = CSSM_ALGID_NONE + 24, - CSSM_ALGID_RC4 = CSSM_ALGID_NONE + 25, - CSSM_ALGID_SEAL = CSSM_ALGID_NONE + 26, - CSSM_ALGID_CAST = CSSM_ALGID_NONE + 27, - CSSM_ALGID_BLOWFISH = CSSM_ALGID_NONE + 28, - CSSM_ALGID_SKIPJACK = CSSM_ALGID_NONE + 29, - CSSM_ALGID_LUCIFER = CSSM_ALGID_NONE + 30, - CSSM_ALGID_MADRYGA = CSSM_ALGID_NONE + 31, - CSSM_ALGID_FEAL = CSSM_ALGID_NONE + 32, - CSSM_ALGID_REDOC = CSSM_ALGID_NONE + 33, - CSSM_ALGID_REDOC3 = CSSM_ALGID_NONE + 34, - CSSM_ALGID_LOKI = CSSM_ALGID_NONE + 35, - CSSM_ALGID_KHUFU = CSSM_ALGID_NONE + 36, - CSSM_ALGID_KHAFRE = CSSM_ALGID_NONE + 37, - CSSM_ALGID_MMB = CSSM_ALGID_NONE + 38, - CSSM_ALGID_GOST = CSSM_ALGID_NONE + 39, - CSSM_ALGID_SAFER = CSSM_ALGID_NONE + 40, - CSSM_ALGID_CRAB = CSSM_ALGID_NONE + 41, - CSSM_ALGID_RSA = CSSM_ALGID_NONE + 42, - CSSM_ALGID_DSA = CSSM_ALGID_NONE + 43, - CSSM_ALGID_MD5WithRSA = CSSM_ALGID_NONE + 44, - CSSM_ALGID_MD2WithRSA = CSSM_ALGID_NONE + 45, - CSSM_ALGID_ElGamal = CSSM_ALGID_NONE + 46, - CSSM_ALGID_MD2Random = CSSM_ALGID_NONE + 47, - CSSM_ALGID_MD5Random = CSSM_ALGID_NONE + 48, - CSSM_ALGID_SHARandom = CSSM_ALGID_NONE + 49, - CSSM_ALGID_DESRandom = CSSM_ALGID_NONE + 50, - CSSM_ALGID_SHA1WithRSA = CSSM_ALGID_NONE + 51, - CSSM_ALGID_CDMF = CSSM_ALGID_NONE + 52, - CSSM_ALGID_CAST3 = CSSM_ALGID_NONE + 53, - CSSM_ALGID_CAST5 = CSSM_ALGID_NONE + 54, - CSSM_ALGID_GenericSecret = CSSM_ALGID_NONE + 55, - CSSM_ALGID_ConcatBaseAndKey = CSSM_ALGID_NONE + 56, - CSSM_ALGID_ConcatKeyAndBase = CSSM_ALGID_NONE + 57, - CSSM_ALGID_ConcatBaseAndData = CSSM_ALGID_NONE + 58, - CSSM_ALGID_ConcatDataAndBase = CSSM_ALGID_NONE + 59, - CSSM_ALGID_XORBaseAndData = CSSM_ALGID_NONE + 60, - CSSM_ALGID_ExtractFromKey = CSSM_ALGID_NONE + 61, - CSSM_ALGID_SSL3PreMasterGen = CSSM_ALGID_NONE + 62, - CSSM_ALGID_SSL3MasterDerive = CSSM_ALGID_NONE + 63, - CSSM_ALGID_SSL3KeyAndMacDerive = CSSM_ALGID_NONE + 64, - CSSM_ALGID_SSL3MD5_MAC = CSSM_ALGID_NONE + 65, - CSSM_ALGID_SSL3SHA1_MAC = CSSM_ALGID_NONE + 66, - CSSM_ALGID_PKCS5_PBKDF1_MD5 = CSSM_ALGID_NONE + 67, - CSSM_ALGID_PKCS5_PBKDF1_MD2 = CSSM_ALGID_NONE + 68, - CSSM_ALGID_PKCS5_PBKDF1_SHA1 = CSSM_ALGID_NONE + 69, - CSSM_ALGID_WrapLynks = CSSM_ALGID_NONE + 70, - CSSM_ALGID_WrapSET_OAEP = CSSM_ALGID_NONE + 71, - CSSM_ALGID_BATON = CSSM_ALGID_NONE + 72, - CSSM_ALGID_ECDSA = CSSM_ALGID_NONE + 73, - CSSM_ALGID_MAYFLY = CSSM_ALGID_NONE + 74, - CSSM_ALGID_JUNIPER = CSSM_ALGID_NONE + 75, - CSSM_ALGID_FASTHASH = CSSM_ALGID_NONE + 76, - CSSM_ALGID_3DES = CSSM_ALGID_NONE + 77, - CSSM_ALGID_SSL3MD5 = CSSM_ALGID_NONE + 78, - CSSM_ALGID_SSL3SHA1 = CSSM_ALGID_NONE + 79, - CSSM_ALGID_FortezzaTimestamp = CSSM_ALGID_NONE + 80, - CSSM_ALGID_SHA1WithDSA = CSSM_ALGID_NONE + 81, - CSSM_ALGID_SHA1WithECDSA = CSSM_ALGID_NONE + 82, - CSSM_ALGID_DSA_BSAFE = CSSM_ALGID_NONE + 83, - CSSM_ALGID_ECDH = CSSM_ALGID_NONE + 84, - CSSM_ALGID_ECMQV = CSSM_ALGID_NONE + 85, - CSSM_ALGID_PKCS12_SHA1_PBE = CSSM_ALGID_NONE + 86, - CSSM_ALGID_ECNRA = CSSM_ALGID_NONE + 87, - CSSM_ALGID_SHA1WithECNRA = CSSM_ALGID_NONE + 88, - CSSM_ALGID_ECES = CSSM_ALGID_NONE + 89, - CSSM_ALGID_ECAES = CSSM_ALGID_NONE + 90, - CSSM_ALGID_SHA1HMAC = CSSM_ALGID_NONE + 91, - CSSM_ALGID_FIPS186Random = CSSM_ALGID_NONE + 92, - CSSM_ALGID_ECC = CSSM_ALGID_NONE + 93, - CSSM_ALGID_MQV = CSSM_ALGID_NONE + 94, - CSSM_ALGID_NRA = CSSM_ALGID_NONE + 95, - CSSM_ALGID_IntelPlatformRandom = CSSM_ALGID_NONE + 96, - CSSM_ALGID_UTC = CSSM_ALGID_NONE + 97, - CSSM_ALGID_HAVAL3 = CSSM_ALGID_NONE + 98, - CSSM_ALGID_HAVAL4 = CSSM_ALGID_NONE + 99, - CSSM_ALGID_HAVAL5 = CSSM_ALGID_NONE + 100, - CSSM_ALGID_TIGER = CSSM_ALGID_NONE + 101, - CSSM_ALGID_MD5HMAC = CSSM_ALGID_NONE + 102, - CSSM_ALGID_PKCS5_PBKDF2 = CSSM_ALGID_NONE + 103, - CSSM_ALGID_RUNNING_COUNTER = CSSM_ALGID_NONE + 104, - CSSM_ALGID_LAST = CSSM_ALGID_NONE + 0x7FFFFFFF, - - - - CSSM_ALGID_VENDOR_DEFINED = CSSM_ALGID_NONE + 0x80000000 -}; - -typedef uint32 CSSM_ENCRYPT_MODE; -enum { - CSSM_ALGMODE_NONE = 0, - CSSM_ALGMODE_CUSTOM = CSSM_ALGMODE_NONE + 1, - CSSM_ALGMODE_ECB = CSSM_ALGMODE_NONE + 2, - CSSM_ALGMODE_ECBPad = CSSM_ALGMODE_NONE + 3, - CSSM_ALGMODE_CBC = CSSM_ALGMODE_NONE + 4, - CSSM_ALGMODE_CBC_IV8 = CSSM_ALGMODE_NONE + 5, - CSSM_ALGMODE_CBCPadIV8 = CSSM_ALGMODE_NONE + 6, - CSSM_ALGMODE_CFB = CSSM_ALGMODE_NONE + 7, - CSSM_ALGMODE_CFB_IV8 = CSSM_ALGMODE_NONE + 8, - CSSM_ALGMODE_CFBPadIV8 = CSSM_ALGMODE_NONE + 9, - CSSM_ALGMODE_OFB = CSSM_ALGMODE_NONE + 10, - CSSM_ALGMODE_OFB_IV8 = CSSM_ALGMODE_NONE + 11, - CSSM_ALGMODE_OFBPadIV8 = CSSM_ALGMODE_NONE + 12, - CSSM_ALGMODE_COUNTER = CSSM_ALGMODE_NONE + 13, - CSSM_ALGMODE_BC = CSSM_ALGMODE_NONE + 14, - CSSM_ALGMODE_PCBC = CSSM_ALGMODE_NONE + 15, - CSSM_ALGMODE_CBCC = CSSM_ALGMODE_NONE + 16, - CSSM_ALGMODE_OFBNLF = CSSM_ALGMODE_NONE + 17, - CSSM_ALGMODE_PBC = CSSM_ALGMODE_NONE + 18, - CSSM_ALGMODE_PFB = CSSM_ALGMODE_NONE + 19, - CSSM_ALGMODE_CBCPD = CSSM_ALGMODE_NONE + 20, - CSSM_ALGMODE_PUBLIC_KEY = CSSM_ALGMODE_NONE + 21, - CSSM_ALGMODE_PRIVATE_KEY = CSSM_ALGMODE_NONE + 22, - CSSM_ALGMODE_SHUFFLE = CSSM_ALGMODE_NONE + 23, - CSSM_ALGMODE_ECB64 = CSSM_ALGMODE_NONE + 24, - CSSM_ALGMODE_CBC64 = CSSM_ALGMODE_NONE + 25, - CSSM_ALGMODE_OFB64 = CSSM_ALGMODE_NONE + 26, - CSSM_ALGMODE_CFB32 = CSSM_ALGMODE_NONE + 28, - CSSM_ALGMODE_CFB16 = CSSM_ALGMODE_NONE + 29, - CSSM_ALGMODE_CFB8 = CSSM_ALGMODE_NONE + 30, - CSSM_ALGMODE_WRAP = CSSM_ALGMODE_NONE + 31, - CSSM_ALGMODE_PRIVATE_WRAP = CSSM_ALGMODE_NONE + 32, - CSSM_ALGMODE_RELAYX = CSSM_ALGMODE_NONE + 33, - CSSM_ALGMODE_ECB128 = CSSM_ALGMODE_NONE + 34, - CSSM_ALGMODE_ECB96 = CSSM_ALGMODE_NONE + 35, - CSSM_ALGMODE_CBC128 = CSSM_ALGMODE_NONE + 36, - CSSM_ALGMODE_OAEP_HASH = CSSM_ALGMODE_NONE + 37, - CSSM_ALGMODE_PKCS1_EME_V15 = CSSM_ALGMODE_NONE + 38, - CSSM_ALGMODE_PKCS1_EME_OAEP = CSSM_ALGMODE_NONE + 39, - CSSM_ALGMODE_PKCS1_EMSA_V15 = CSSM_ALGMODE_NONE + 40, - CSSM_ALGMODE_ISO_9796 = CSSM_ALGMODE_NONE + 41, - CSSM_ALGMODE_X9_31 = CSSM_ALGMODE_NONE + 42, - CSSM_ALGMODE_LAST = CSSM_ALGMODE_NONE + 0x7FFFFFFF, - - - - CSSM_ALGMODE_VENDOR_DEFINED = CSSM_ALGMODE_NONE + 0x80000000 -}; - -typedef struct cssm_keyheader { - CSSM_HEADERVERSION HeaderVersion; - CSSM_GUID CspId; - CSSM_KEYBLOB_TYPE BlobType; - CSSM_KEYBLOB_FORMAT Format; - CSSM_ALGORITHMS AlgorithmId; - CSSM_KEYCLASS KeyClass; - uint32 LogicalKeySizeInBits; - CSSM_KEYATTR_FLAGS KeyAttr; - CSSM_KEYUSE KeyUsage; - CSSM_DATE StartDate; - CSSM_DATE EndDate; - CSSM_ALGORITHMS WrapAlgorithmId; - CSSM_ENCRYPT_MODE WrapMode; - uint32 Reserved; -} CSSM_KEYHEADER __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_KEYHEADER_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_key { - CSSM_KEYHEADER KeyHeader; - CSSM_DATA KeyData; -} CSSM_KEY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_KEY_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef CSSM_KEY CSSM_WRAP_KEY, *CSSM_WRAP_KEY_PTR; - -typedef uint32 CSSM_CSPTYPE; -enum { - CSSM_CSP_SOFTWARE = 1, - CSSM_CSP_HARDWARE = CSSM_CSP_SOFTWARE + 1, - CSSM_CSP_HYBRID = CSSM_CSP_SOFTWARE + 2 -}; - - -typedef struct cssm_dl_db_handle { - CSSM_DL_HANDLE DLHandle; - CSSM_DB_HANDLE DBHandle; -} CSSM_DL_DB_HANDLE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DL_DB_HANDLE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_CONTEXT_TYPE; -enum { - CSSM_ALGCLASS_NONE = 0, - CSSM_ALGCLASS_CUSTOM = CSSM_ALGCLASS_NONE + 1, - CSSM_ALGCLASS_SIGNATURE = CSSM_ALGCLASS_NONE + 2, - CSSM_ALGCLASS_SYMMETRIC = CSSM_ALGCLASS_NONE + 3, - CSSM_ALGCLASS_DIGEST = CSSM_ALGCLASS_NONE + 4, - CSSM_ALGCLASS_RANDOMGEN = CSSM_ALGCLASS_NONE + 5, - CSSM_ALGCLASS_UNIQUEGEN = CSSM_ALGCLASS_NONE + 6, - CSSM_ALGCLASS_MAC = CSSM_ALGCLASS_NONE + 7, - CSSM_ALGCLASS_ASYMMETRIC = CSSM_ALGCLASS_NONE + 8, - CSSM_ALGCLASS_KEYGEN = CSSM_ALGCLASS_NONE + 9, - CSSM_ALGCLASS_DERIVEKEY = CSSM_ALGCLASS_NONE + 10 -}; - - -enum { - CSSM_ATTRIBUTE_DATA_NONE = 0x00000000, - CSSM_ATTRIBUTE_DATA_UINT32 = 0x10000000, - CSSM_ATTRIBUTE_DATA_CSSM_DATA = 0x20000000, - CSSM_ATTRIBUTE_DATA_CRYPTO_DATA = 0x30000000, - CSSM_ATTRIBUTE_DATA_KEY = 0x40000000, - CSSM_ATTRIBUTE_DATA_STRING = 0x50000000, - CSSM_ATTRIBUTE_DATA_DATE = 0x60000000, - CSSM_ATTRIBUTE_DATA_RANGE = 0x70000000, - CSSM_ATTRIBUTE_DATA_ACCESS_CREDENTIALS = 0x80000000, - CSSM_ATTRIBUTE_DATA_VERSION = 0x01000000, - CSSM_ATTRIBUTE_DATA_DL_DB_HANDLE = 0x02000000, - CSSM_ATTRIBUTE_DATA_KR_PROFILE = 0x03000000, - CSSM_ATTRIBUTE_TYPE_MASK = 0xFF000000 -}; - -typedef uint32 CSSM_ATTRIBUTE_TYPE; -enum { - CSSM_ATTRIBUTE_NONE = 0, - CSSM_ATTRIBUTE_CUSTOM = CSSM_ATTRIBUTE_DATA_CSSM_DATA | 1, - CSSM_ATTRIBUTE_DESCRIPTION = CSSM_ATTRIBUTE_DATA_STRING | 2, - CSSM_ATTRIBUTE_KEY = CSSM_ATTRIBUTE_DATA_KEY | 3, - CSSM_ATTRIBUTE_INIT_VECTOR = CSSM_ATTRIBUTE_DATA_CSSM_DATA | 4, - CSSM_ATTRIBUTE_SALT = CSSM_ATTRIBUTE_DATA_CSSM_DATA | 5, - CSSM_ATTRIBUTE_PADDING = CSSM_ATTRIBUTE_DATA_UINT32 | 6, - CSSM_ATTRIBUTE_RANDOM = CSSM_ATTRIBUTE_DATA_CSSM_DATA | 7, - CSSM_ATTRIBUTE_SEED = CSSM_ATTRIBUTE_DATA_CRYPTO_DATA | 8, - CSSM_ATTRIBUTE_PASSPHRASE = CSSM_ATTRIBUTE_DATA_CRYPTO_DATA | 9, - CSSM_ATTRIBUTE_KEY_LENGTH = CSSM_ATTRIBUTE_DATA_UINT32 | 10, - CSSM_ATTRIBUTE_KEY_LENGTH_RANGE = CSSM_ATTRIBUTE_DATA_RANGE | 11, - CSSM_ATTRIBUTE_BLOCK_SIZE = CSSM_ATTRIBUTE_DATA_UINT32 | 12, - CSSM_ATTRIBUTE_OUTPUT_SIZE = CSSM_ATTRIBUTE_DATA_UINT32 | 13, - CSSM_ATTRIBUTE_ROUNDS = CSSM_ATTRIBUTE_DATA_UINT32 | 14, - CSSM_ATTRIBUTE_IV_SIZE = CSSM_ATTRIBUTE_DATA_UINT32 | 15, - CSSM_ATTRIBUTE_ALG_PARAMS = CSSM_ATTRIBUTE_DATA_CSSM_DATA | 16, - CSSM_ATTRIBUTE_LABEL = CSSM_ATTRIBUTE_DATA_CSSM_DATA | 17, - CSSM_ATTRIBUTE_KEY_TYPE = CSSM_ATTRIBUTE_DATA_UINT32 | 18, - CSSM_ATTRIBUTE_MODE = CSSM_ATTRIBUTE_DATA_UINT32 | 19, - CSSM_ATTRIBUTE_EFFECTIVE_BITS = CSSM_ATTRIBUTE_DATA_UINT32 | 20, - CSSM_ATTRIBUTE_START_DATE = CSSM_ATTRIBUTE_DATA_DATE | 21, - CSSM_ATTRIBUTE_END_DATE = CSSM_ATTRIBUTE_DATA_DATE | 22, - CSSM_ATTRIBUTE_KEYUSAGE = CSSM_ATTRIBUTE_DATA_UINT32 | 23, - CSSM_ATTRIBUTE_KEYATTR = CSSM_ATTRIBUTE_DATA_UINT32 | 24, - CSSM_ATTRIBUTE_VERSION = CSSM_ATTRIBUTE_DATA_VERSION | 25, - CSSM_ATTRIBUTE_PRIME = CSSM_ATTRIBUTE_DATA_CSSM_DATA | 26, - CSSM_ATTRIBUTE_BASE = CSSM_ATTRIBUTE_DATA_CSSM_DATA | 27, - CSSM_ATTRIBUTE_SUBPRIME = CSSM_ATTRIBUTE_DATA_CSSM_DATA | 28, - CSSM_ATTRIBUTE_ALG_ID = CSSM_ATTRIBUTE_DATA_UINT32 | 29, - CSSM_ATTRIBUTE_ITERATION_COUNT = CSSM_ATTRIBUTE_DATA_UINT32 | 30, - CSSM_ATTRIBUTE_ROUNDS_RANGE = CSSM_ATTRIBUTE_DATA_RANGE | 31, - CSSM_ATTRIBUTE_KRPROFILE_LOCAL = CSSM_ATTRIBUTE_DATA_KR_PROFILE | 32, - CSSM_ATTRIBUTE_KRPROFILE_REMOTE = CSSM_ATTRIBUTE_DATA_KR_PROFILE | 33, - CSSM_ATTRIBUTE_CSP_HANDLE = CSSM_ATTRIBUTE_DATA_UINT32 | 34, - CSSM_ATTRIBUTE_DL_DB_HANDLE = CSSM_ATTRIBUTE_DATA_DL_DB_HANDLE | 35, - CSSM_ATTRIBUTE_ACCESS_CREDENTIALS = CSSM_ATTRIBUTE_DATA_ACCESS_CREDENTIALS | 36, - CSSM_ATTRIBUTE_PUBLIC_KEY_FORMAT = CSSM_ATTRIBUTE_DATA_UINT32 | 37, - CSSM_ATTRIBUTE_PRIVATE_KEY_FORMAT = CSSM_ATTRIBUTE_DATA_UINT32 | 38, - CSSM_ATTRIBUTE_SYMMETRIC_KEY_FORMAT=CSSM_ATTRIBUTE_DATA_UINT32 | 39, - CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT = CSSM_ATTRIBUTE_DATA_UINT32 | 40 -}; - -typedef uint32 CSSM_PADDING; -enum { - CSSM_PADDING_NONE = 0, - CSSM_PADDING_CUSTOM = CSSM_PADDING_NONE + 1, - CSSM_PADDING_ZERO = CSSM_PADDING_NONE + 2, - CSSM_PADDING_ONE = CSSM_PADDING_NONE + 3, - CSSM_PADDING_ALTERNATE = CSSM_PADDING_NONE + 4, - CSSM_PADDING_FF = CSSM_PADDING_NONE + 5, - CSSM_PADDING_PKCS5 = CSSM_PADDING_NONE + 6, - CSSM_PADDING_PKCS7 = CSSM_PADDING_NONE + 7, - CSSM_PADDING_CIPHERSTEALING = CSSM_PADDING_NONE + 8, - CSSM_PADDING_RANDOM = CSSM_PADDING_NONE + 9, - CSSM_PADDING_PKCS1 = CSSM_PADDING_NONE + 10, - CSSM_PADDING_SIGRAW = CSSM_PADDING_NONE + 11, - - - - CSSM_PADDING_VENDOR_DEFINED = CSSM_PADDING_NONE + 0x80000000 -}; - -typedef CSSM_ALGORITHMS CSSM_KEY_TYPE; - -typedef struct cssm_context_attribute { - CSSM_ATTRIBUTE_TYPE AttributeType; - uint32 AttributeLength; - union cssm_context_attribute_value { - char *String; - uint32 Uint32; - CSSM_ACCESS_CREDENTIALS_PTR AccessCredentials; - CSSM_KEY_PTR Key; - CSSM_DATA_PTR Data; - CSSM_PADDING Padding; - CSSM_DATE_PTR Date; - CSSM_RANGE_PTR Range; - CSSM_CRYPTO_DATA_PTR CryptoData; - CSSM_VERSION_PTR Version; - CSSM_DL_DB_HANDLE_PTR DLDBHandle; - struct cssm_kr_profile *KRProfile; - } Attribute; -} CSSM_CONTEXT_ATTRIBUTE, *CSSM_CONTEXT_ATTRIBUTE_PTR; - -typedef struct cssm_context { - CSSM_CONTEXT_TYPE ContextType; - CSSM_ALGORITHMS AlgorithmType; - uint32 NumberOfAttributes; - CSSM_CONTEXT_ATTRIBUTE_PTR ContextAttributes; - CSSM_CSP_HANDLE CSPHandle; - CSSM_BOOL Privileged; - uint32 EncryptionProhibited; - uint32 WorkFactor; - uint32 Reserved; -} CSSM_CONTEXT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_CONTEXT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_SC_FLAGS; -enum { - CSSM_CSP_TOK_RNG = 0x00000001, - CSSM_CSP_TOK_CLOCK_EXISTS = 0x00000040 -}; - -typedef uint32 CSSM_CSP_READER_FLAGS; -enum { - CSSM_CSP_RDR_TOKENPRESENT = 0x00000001, - - CSSM_CSP_RDR_EXISTS = 0x00000002, - - - CSSM_CSP_RDR_HW = 0x00000004 - -}; - -typedef uint32 CSSM_CSP_FLAGS; -enum { - CSSM_CSP_TOK_WRITE_PROTECTED = 0x00000002, - CSSM_CSP_TOK_LOGIN_REQUIRED = 0x00000004, - CSSM_CSP_TOK_USER_PIN_INITIALIZED = 0x00000008, - CSSM_CSP_TOK_PROT_AUTHENTICATION = 0x00000100, - CSSM_CSP_TOK_USER_PIN_EXPIRED = 0x00100000, - CSSM_CSP_TOK_SESSION_KEY_PASSWORD = 0x00200000, - CSSM_CSP_TOK_PRIVATE_KEY_PASSWORD = 0x00400000, - CSSM_CSP_STORES_PRIVATE_KEYS = 0x01000000, - CSSM_CSP_STORES_PUBLIC_KEYS = 0x02000000, - CSSM_CSP_STORES_SESSION_KEYS = 0x04000000, - CSSM_CSP_STORES_CERTIFICATES = 0x08000000, - CSSM_CSP_STORES_GENERIC = 0x10000000 -}; - -typedef uint32 CSSM_PKCS_OAEP_MGF; -enum { - CSSM_PKCS_OAEP_MGF_NONE = 0, - CSSM_PKCS_OAEP_MGF1_SHA1 = CSSM_PKCS_OAEP_MGF_NONE + 1, - CSSM_PKCS_OAEP_MGF1_MD5 = CSSM_PKCS_OAEP_MGF_NONE + 2 -}; - -typedef uint32 CSSM_PKCS_OAEP_PSOURCE; -enum { - CSSM_PKCS_OAEP_PSOURCE_NONE = 0, - CSSM_PKCS_OAEP_PSOURCE_Pspecified = CSSM_PKCS_OAEP_PSOURCE_NONE + 1 -}; - -typedef struct cssm_pkcs1_oaep_params { - uint32 HashAlgorithm; - CSSM_DATA HashParams; - CSSM_PKCS_OAEP_MGF MGF; - CSSM_DATA MGFParams; - CSSM_PKCS_OAEP_PSOURCE PSource; - CSSM_DATA PSourceParams; -} CSSM_PKCS1_OAEP_PARAMS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_PKCS1_OAEP_PARAMS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_csp_operational_statistics { - CSSM_BOOL UserAuthenticated; - - CSSM_CSP_FLAGS DeviceFlags; - uint32 TokenMaxSessionCount; - uint32 TokenOpenedSessionCount; - uint32 TokenMaxRWSessionCount; - uint32 TokenOpenedRWSessionCount; - uint32 TokenTotalPublicMem; - uint32 TokenFreePublicMem; - uint32 TokenTotalPrivateMem; - uint32 TokenFreePrivateMem; -} CSSM_CSP_OPERATIONAL_STATISTICS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_CSP_OPERATIONAL_STATISTICS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - -enum { - CSSM_VALUE_NOT_AVAILABLE = -1 -}; - -typedef struct cssm_pkcs5_pbkdf1_params { - CSSM_DATA Passphrase; - CSSM_DATA InitVector; -} CSSM_PKCS5_PBKDF1_PARAMS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_PKCS5_PBKDF1_PARAMS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_PKCS5_PBKDF2_PRF; -enum { - CSSM_PKCS5_PBKDF2_PRF_HMAC_SHA1 = 0 -}; - -typedef struct cssm_pkcs5_pbkdf2_params { - CSSM_DATA Passphrase; - CSSM_PKCS5_PBKDF2_PRF PseudoRandomFunction; -} CSSM_PKCS5_PBKDF2_PARAMS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_PKCS5_PBKDF2_PARAMS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_kea_derive_params { - CSSM_DATA Rb; - CSSM_DATA Yb; -} CSSM_KEA_DERIVE_PARAMS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_KEA_DERIVE_PARAMS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -typedef struct cssm_tp_authority_id { - CSSM_DATA *AuthorityCert; - CSSM_NET_ADDRESS_PTR AuthorityLocation; -} CSSM_TP_AUTHORITY_ID __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_AUTHORITY_ID_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_AUTHORITY_REQUEST_TYPE, *CSSM_TP_AUTHORITY_REQUEST_TYPE_PTR; -enum { - CSSM_TP_AUTHORITY_REQUEST_CERTISSUE = 0x01, - CSSM_TP_AUTHORITY_REQUEST_CERTREVOKE = 0x02, - CSSM_TP_AUTHORITY_REQUEST_CERTSUSPEND = 0x03, - CSSM_TP_AUTHORITY_REQUEST_CERTRESUME = 0x04, - CSSM_TP_AUTHORITY_REQUEST_CERTVERIFY = 0x05, - CSSM_TP_AUTHORITY_REQUEST_CERTNOTARIZE = 0x06, - CSSM_TP_AUTHORITY_REQUEST_CERTUSERECOVER = 0x07, - CSSM_TP_AUTHORITY_REQUEST_CRLISSUE = 0x100 -}; - -typedef CSSM_RETURN ( * CSSM_TP_VERIFICATION_RESULTS_CALLBACK) - (CSSM_MODULE_HANDLE ModuleHandle, - void *CallerCtx, - CSSM_DATA_PTR VerifiedCert); - - -typedef CSSM_DATA CSSM_OID, *CSSM_OID_PTR; - -typedef struct cssm_field { - CSSM_OID FieldOid; - CSSM_DATA FieldValue; -} CSSM_FIELD __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_FIELD_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_tp_policyinfo { - uint32 NumberOfPolicyIds; - CSSM_FIELD_PTR PolicyIds; - void *PolicyControl; -} CSSM_TP_POLICYINFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_POLICYINFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_SERVICES; -enum { - - CSSM_TP_KEY_ARCHIVE = 0x0001, - CSSM_TP_CERT_PUBLISH = 0x0002, - CSSM_TP_CERT_NOTIFY_RENEW = 0x0004, - CSSM_TP_CERT_DIR_UPDATE = 0x0008, - CSSM_TP_CRL_DISTRIBUTE = 0x0010 -}; - -typedef uint32 CSSM_TP_ACTION; -enum { - CSSM_TP_ACTION_DEFAULT = 0 -}; - -typedef uint32 CSSM_TP_STOP_ON; -enum { - CSSM_TP_STOP_ON_POLICY = 0, - CSSM_TP_STOP_ON_NONE = 1, - CSSM_TP_STOP_ON_FIRST_PASS = 2, - CSSM_TP_STOP_ON_FIRST_FAIL = 3 -}; - -typedef char *CSSM_TIMESTRING; - - -typedef struct cssm_dl_db_list { - uint32 NumHandles; - CSSM_DL_DB_HANDLE_PTR DLDBHandle; -} CSSM_DL_DB_LIST __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DL_DB_LIST_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_tp_callerauth_context { - CSSM_TP_POLICYINFO Policy; - CSSM_TIMESTRING VerifyTime; - CSSM_TP_STOP_ON VerificationAbortOn; - CSSM_TP_VERIFICATION_RESULTS_CALLBACK CallbackWithVerifiedCert; - uint32 NumberOfAnchorCerts; - CSSM_DATA_PTR AnchorCerts; - CSSM_DL_DB_LIST_PTR DBList; - CSSM_ACCESS_CREDENTIALS_PTR CallerCredentials; -} CSSM_TP_CALLERAUTH_CONTEXT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CALLERAUTH_CONTEXT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_CRL_PARSE_FORMAT, * CSSM_CRL_PARSE_FORMAT_PTR; -enum { - CSSM_CRL_PARSE_FORMAT_NONE = 0x00, - CSSM_CRL_PARSE_FORMAT_CUSTOM = 0x01, - CSSM_CRL_PARSE_FORMAT_SEXPR = 0x02, - CSSM_CRL_PARSE_FORMAT_COMPLEX = 0x03, - CSSM_CRL_PARSE_FORMAT_OID_NAMED = 0x04, - CSSM_CRL_PARSE_FORMAT_TUPLE = 0x05, - CSSM_CRL_PARSE_FORMAT_MULTIPLE = 0x7FFE, - CSSM_CRL_PARSE_FORMAT_LAST = 0x7FFF, - - - - CSSM_CL_CUSTOM_CRL_PARSE_FORMAT = 0x8000 -}; - - -typedef uint32 CSSM_CRL_TYPE, *CSSM_CRL_TYPE_PTR; -enum { - CSSM_CRL_TYPE_UNKNOWN = 0x00, - CSSM_CRL_TYPE_X_509v1 = 0x01, - CSSM_CRL_TYPE_X_509v2 = 0x02, - CSSM_CRL_TYPE_SPKI = 0x03, - CSSM_CRL_TYPE_MULTIPLE = 0x7FFE -}; - -typedef uint32 CSSM_CRL_ENCODING, *CSSM_CRL_ENCODING_PTR; -enum { - CSSM_CRL_ENCODING_UNKNOWN = 0x00, - CSSM_CRL_ENCODING_CUSTOM = 0x01, - CSSM_CRL_ENCODING_BER = 0x02, - CSSM_CRL_ENCODING_DER = 0x03, - CSSM_CRL_ENCODING_BLOOM = 0x04, - CSSM_CRL_ENCODING_SEXPR = 0x05, - CSSM_CRL_ENCODING_MULTIPLE = 0x7FFE -}; - -typedef struct cssm_encoded_crl { - CSSM_CRL_TYPE CrlType; - CSSM_CRL_ENCODING CrlEncoding; - CSSM_DATA CrlBlob; -} CSSM_ENCODED_CRL __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_ENCODED_CRL_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_parsed_crl { - CSSM_CRL_TYPE CrlType; - CSSM_CRL_PARSE_FORMAT ParsedCrlFormat; - - void *ParsedCrl; -} CSSM_PARSED_CRL __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_PARSED_CRL_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_crl_pair { - CSSM_ENCODED_CRL EncodedCrl; - CSSM_PARSED_CRL ParsedCrl; -} CSSM_CRL_PAIR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_CRL_PAIR_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_CRLGROUP_TYPE, * CSSM_CRLGROUP_TYPE_PTR; -enum { - CSSM_CRLGROUP_DATA = 0x00, - CSSM_CRLGROUP_ENCODED_CRL = 0x01, - CSSM_CRLGROUP_PARSED_CRL = 0x02, - CSSM_CRLGROUP_CRL_PAIR = 0x03 -}; - -typedef struct cssm_crlgroup { - CSSM_CRL_TYPE CrlType; - CSSM_CRL_ENCODING CrlEncoding; - uint32 NumberOfCrls; - union { - CSSM_DATA_PTR CrlList; - CSSM_ENCODED_CRL_PTR EncodedCrlList; - CSSM_PARSED_CRL_PTR ParsedCrlList; - CSSM_CRL_PAIR_PTR PairCrlList; - } GroupCrlList; - CSSM_CRLGROUP_TYPE CrlGroupType; -} CSSM_CRLGROUP, *CSSM_CRLGROUP_PTR; - -typedef struct cssm_fieldgroup { - int NumberOfFields; - CSSM_FIELD_PTR Fields; -} CSSM_FIELDGROUP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_FIELDGROUP_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_EVIDENCE_FORM; -enum { - CSSM_EVIDENCE_FORM_UNSPECIFIC = 0x0, - CSSM_EVIDENCE_FORM_CERT = 0x1, - CSSM_EVIDENCE_FORM_CRL = 0x2, - CSSM_EVIDENCE_FORM_CERT_ID = 0x3, - CSSM_EVIDENCE_FORM_CRL_ID = 0x4, - CSSM_EVIDENCE_FORM_VERIFIER_TIME = 0x5, - CSSM_EVIDENCE_FORM_CRL_THISTIME = 0x6, - CSSM_EVIDENCE_FORM_CRL_NEXTTIME = 0x7, - CSSM_EVIDENCE_FORM_POLICYINFO = 0x8, - CSSM_EVIDENCE_FORM_TUPLEGROUP = 0x9 -}; - -typedef struct cssm_evidence { - CSSM_EVIDENCE_FORM EvidenceForm; - void *Evidence; -} CSSM_EVIDENCE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_EVIDENCE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_tp_verify_context { - CSSM_TP_ACTION Action; - CSSM_DATA ActionData; - CSSM_CRLGROUP Crls; - CSSM_TP_CALLERAUTH_CONTEXT_PTR Cred; -} CSSM_TP_VERIFY_CONTEXT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_VERIFY_CONTEXT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_tp_verify_context_result { - uint32 NumberOfEvidences; - CSSM_EVIDENCE_PTR Evidence; -} CSSM_TP_VERIFY_CONTEXT_RESULT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_VERIFY_CONTEXT_RESULT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_tp_request_set { - uint32 NumberOfRequests; - void *Requests; -} CSSM_TP_REQUEST_SET __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_REQUEST_SET_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_tp_result_set { - uint32 NumberOfResults; - void *Results; -} CSSM_TP_RESULT_SET __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_RESULT_SET_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_CONFIRM_STATUS, *CSSM_TP_CONFIRM_STATUS_PTR; -enum { - CSSM_TP_CONFIRM_STATUS_UNKNOWN = 0x0, - - CSSM_TP_CONFIRM_ACCEPT = 0x1, - - - CSSM_TP_CONFIRM_REJECT = 0x2 - - -}; - -typedef struct cssm_tp_confirm_response { - uint32 NumberOfResponses; - CSSM_TP_CONFIRM_STATUS_PTR Responses; -} CSSM_TP_CONFIRM_RESPONSE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CONFIRM_RESPONSE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -enum { - CSSM_ESTIMATED_TIME_UNKNOWN = -1 -}; - -enum { - CSSM_ELAPSED_TIME_UNKNOWN = -1, - CSSM_ELAPSED_TIME_COMPLETE = -2 -}; - -typedef struct cssm_tp_certissue_input { - CSSM_SUBSERVICE_UID CSPSubserviceUid; - CSSM_CL_HANDLE CLHandle; - uint32 NumberOfTemplateFields; - CSSM_FIELD_PTR SubjectCertFields; - CSSM_TP_SERVICES MoreServiceRequests; - uint32 NumberOfServiceControls; - CSSM_FIELD_PTR ServiceControls; - CSSM_ACCESS_CREDENTIALS_PTR UserCredentials; -} CSSM_TP_CERTISSUE_INPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTISSUE_INPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_CERTISSUE_STATUS; -enum { - CSSM_TP_CERTISSUE_STATUS_UNKNOWN = 0x0, - - CSSM_TP_CERTISSUE_OK = 0x1, - - CSSM_TP_CERTISSUE_OKWITHCERTMODS = 0x2, - - - CSSM_TP_CERTISSUE_OKWITHSERVICEMODS = 0x3, - - - - CSSM_TP_CERTISSUE_REJECTED = 0x4, - - - CSSM_TP_CERTISSUE_NOT_AUTHORIZED = 0x5, - - - CSSM_TP_CERTISSUE_WILL_BE_REVOKED = 0x6 - - -}; - -typedef struct cssm_tp_certissue_output { - CSSM_TP_CERTISSUE_STATUS IssueStatus; - CSSM_CERTGROUP_PTR CertGroup; - CSSM_TP_SERVICES PerformedServiceRequests; -} CSSM_TP_CERTISSUE_OUTPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTISSUE_OUTPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_CERTCHANGE_ACTION; -enum { - CSSM_TP_CERTCHANGE_NONE = 0x0, - CSSM_TP_CERTCHANGE_REVOKE = 0x1, - - - - - CSSM_TP_CERTCHANGE_HOLD = 0x2, - CSSM_TP_CERTCHANGE_RELEASE = 0x3 - - - - - -}; - -typedef uint32 CSSM_TP_CERTCHANGE_REASON; -enum { - CSSM_TP_CERTCHANGE_REASON_UNKNOWN = 0x0, - - CSSM_TP_CERTCHANGE_REASON_KEYCOMPROMISE = 0x1, - - CSSM_TP_CERTCHANGE_REASON_CACOMPROMISE = 0x2, - - CSSM_TP_CERTCHANGE_REASON_CEASEOPERATION = 0x3, - - - CSSM_TP_CERTCHANGE_REASON_AFFILIATIONCHANGE = 0x4, - - - CSSM_TP_CERTCHANGE_REASON_SUPERCEDED = 0x5, - - - CSSM_TP_CERTCHANGE_REASON_SUSPECTEDCOMPROMISE = 0x6, - - CSSM_TP_CERTCHANGE_REASON_HOLDRELEASE = 0x7 - - -}; - -typedef struct cssm_tp_certchange_input { - CSSM_TP_CERTCHANGE_ACTION Action; - CSSM_TP_CERTCHANGE_REASON Reason; - CSSM_CL_HANDLE CLHandle; - CSSM_DATA_PTR Cert; - CSSM_FIELD_PTR ChangeInfo; - CSSM_TIMESTRING StartTime; - CSSM_ACCESS_CREDENTIALS_PTR CallerCredentials; -} CSSM_TP_CERTCHANGE_INPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTCHANGE_INPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_CERTCHANGE_STATUS; -enum { - CSSM_TP_CERTCHANGE_STATUS_UNKNOWN = 0x0, - - CSSM_TP_CERTCHANGE_OK = 0x1, - - - CSSM_TP_CERTCHANGE_OKWITHNEWTIME = 0x2, - - - CSSM_TP_CERTCHANGE_WRONGCA = 0x3, - - - - CSSM_TP_CERTCHANGE_REJECTED = 0x4, - - - CSSM_TP_CERTCHANGE_NOT_AUTHORIZED = 0x5 - - - -}; - -typedef struct cssm_tp_certchange_output { - CSSM_TP_CERTCHANGE_STATUS ActionStatus; - CSSM_FIELD RevokeInfo; -} CSSM_TP_CERTCHANGE_OUTPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTCHANGE_OUTPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_tp_certverify_input { - CSSM_CL_HANDLE CLHandle; - CSSM_DATA_PTR Cert; - CSSM_TP_VERIFY_CONTEXT_PTR VerifyContext; -} CSSM_TP_CERTVERIFY_INPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTVERIFY_INPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_CERTVERIFY_STATUS; -enum { - CSSM_TP_CERTVERIFY_UNKNOWN = 0x0, - CSSM_TP_CERTVERIFY_VALID = 0x1, - CSSM_TP_CERTVERIFY_INVALID = 0x2, - CSSM_TP_CERTVERIFY_REVOKED = 0x3, - CSSM_TP_CERTVERIFY_SUSPENDED = 0x4, - CSSM_TP_CERTVERIFY_EXPIRED = 0x5, - CSSM_TP_CERTVERIFY_NOT_VALID_YET = 0x6, - CSSM_TP_CERTVERIFY_INVALID_AUTHORITY = 0x7, - CSSM_TP_CERTVERIFY_INVALID_SIGNATURE = 0x8, - CSSM_TP_CERTVERIFY_INVALID_CERT_VALUE = 0x9, - CSSM_TP_CERTVERIFY_INVALID_CERTGROUP = 0xA, - CSSM_TP_CERTVERIFY_INVALID_POLICY = 0xB, - CSSM_TP_CERTVERIFY_INVALID_POLICY_IDS = 0xC, - CSSM_TP_CERTVERIFY_INVALID_BASIC_CONSTRAINTS = 0xD, - CSSM_TP_CERTVERIFY_INVALID_CRL_DIST_PT = 0xE, - CSSM_TP_CERTVERIFY_INVALID_NAME_TREE = 0xF, - CSSM_TP_CERTVERIFY_UNKNOWN_CRITICAL_EXT = 0x10 -}; - -typedef struct cssm_tp_certverify_output { - CSSM_TP_CERTVERIFY_STATUS VerifyStatus; - uint32 NumberOfEvidence; - CSSM_EVIDENCE_PTR Evidence; -} CSSM_TP_CERTVERIFY_OUTPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTVERIFY_OUTPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_tp_certnotarize_input { - CSSM_CL_HANDLE CLHandle; - uint32 NumberOfFields; - CSSM_FIELD_PTR MoreFields; - CSSM_FIELD_PTR SignScope; - uint32 ScopeSize; - CSSM_TP_SERVICES MoreServiceRequests; - uint32 NumberOfServiceControls; - CSSM_FIELD_PTR ServiceControls; - CSSM_ACCESS_CREDENTIALS_PTR UserCredentials; -} CSSM_TP_CERTNOTARIZE_INPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTNOTARIZE_INPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_CERTNOTARIZE_STATUS; -enum { - CSSM_TP_CERTNOTARIZE_STATUS_UNKNOWN = 0x0, - - CSSM_TP_CERTNOTARIZE_OK = 0x1, - - - CSSM_TP_CERTNOTARIZE_OKWITHOUTFIELDS = 0x2, - - - - CSSM_TP_CERTNOTARIZE_OKWITHSERVICEMODS = 0x3, - - - - - CSSM_TP_CERTNOTARIZE_REJECTED = 0x4, - - - CSSM_TP_CERTNOTARIZE_NOT_AUTHORIZED = 0x5 - - -}; - -typedef struct cssm_tp_certnotarize_output { - CSSM_TP_CERTNOTARIZE_STATUS NotarizeStatus; - CSSM_CERTGROUP_PTR NotarizedCertGroup; - CSSM_TP_SERVICES PerformedServiceRequests; -} CSSM_TP_CERTNOTARIZE_OUTPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTNOTARIZE_OUTPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_tp_certreclaim_input { - CSSM_CL_HANDLE CLHandle; - uint32 NumberOfSelectionFields; - CSSM_FIELD_PTR SelectionFields; - CSSM_ACCESS_CREDENTIALS_PTR UserCredentials; -} CSSM_TP_CERTRECLAIM_INPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTRECLAIM_INPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_CERTRECLAIM_STATUS; -enum { - CSSM_TP_CERTRECLAIM_STATUS_UNKNOWN = 0x0, - - CSSM_TP_CERTRECLAIM_OK = 0x1, - - - - CSSM_TP_CERTRECLAIM_NOMATCH = 0x2, - - - - CSSM_TP_CERTRECLAIM_REJECTED = 0x3, - - - CSSM_TP_CERTRECLAIM_NOT_AUTHORIZED = 0x4 - - - -}; - -typedef struct cssm_tp_certreclaim_output { - CSSM_TP_CERTRECLAIM_STATUS ReclaimStatus; - CSSM_CERTGROUP_PTR ReclaimedCertGroup; - CSSM_LONG_HANDLE KeyCacheHandle; -} CSSM_TP_CERTRECLAIM_OUTPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CERTRECLAIM_OUTPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_tp_crlissue_input { - CSSM_CL_HANDLE CLHandle; - uint32 CrlIdentifier; - CSSM_TIMESTRING CrlThisTime; - CSSM_FIELD_PTR PolicyIdentifier; - CSSM_ACCESS_CREDENTIALS_PTR CallerCredentials; -} CSSM_TP_CRLISSUE_INPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CRLISSUE_INPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_CRLISSUE_STATUS; -enum { - CSSM_TP_CRLISSUE_STATUS_UNKNOWN = 0x0, - - CSSM_TP_CRLISSUE_OK = 0x1, - - - - CSSM_TP_CRLISSUE_NOT_CURRENT = 0x2, - - - - - - - CSSM_TP_CRLISSUE_INVALID_DOMAIN = 0x3, - - - - - CSSM_TP_CRLISSUE_UNKNOWN_IDENTIFIER = 0x4, - - - - CSSM_TP_CRLISSUE_REJECTED = 0x5, - - - - CSSM_TP_CRLISSUE_NOT_AUTHORIZED = 0x6 - - - -}; - -typedef struct cssm_tp_crlissue_output { - CSSM_TP_CRLISSUE_STATUS IssueStatus; - CSSM_ENCODED_CRL_PTR Crl; - CSSM_TIMESTRING CrlNextTime; -} CSSM_TP_CRLISSUE_OUTPUT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_TP_CRLISSUE_OUTPUT_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_TP_FORM_TYPE; -enum { - CSSM_TP_FORM_TYPE_GENERIC = 0x0, - CSSM_TP_FORM_TYPE_REGISTRATION = 0x1 -}; - - - -typedef uint32 CSSM_CL_TEMPLATE_TYPE; -enum { - CSSM_CL_TEMPLATE_INTERMEDIATE_CERT = 1, - - - CSSM_CL_TEMPLATE_PKIX_CERTTEMPLATE = 2 - -}; - -typedef uint32 CSSM_CERT_BUNDLE_TYPE; -enum { - CSSM_CERT_BUNDLE_UNKNOWN = 0x00, - CSSM_CERT_BUNDLE_CUSTOM = 0x01, - CSSM_CERT_BUNDLE_PKCS7_SIGNED_DATA = 0x02, - CSSM_CERT_BUNDLE_PKCS7_SIGNED_ENVELOPED_DATA = 0x03, - CSSM_CERT_BUNDLE_PKCS12 = 0x04, - CSSM_CERT_BUNDLE_PFX = 0x05, - CSSM_CERT_BUNDLE_SPKI_SEQUENCE = 0x06, - CSSM_CERT_BUNDLE_PGP_KEYRING = 0x07, - CSSM_CERT_BUNDLE_LAST = 0x7FFF, - - - - CSSM_CL_CUSTOM_CERT_BUNDLE_TYPE = 0x8000 -}; - -typedef uint32 CSSM_CERT_BUNDLE_ENCODING; -enum { - CSSM_CERT_BUNDLE_ENCODING_UNKNOWN = 0x00, - CSSM_CERT_BUNDLE_ENCODING_CUSTOM = 0x01, - CSSM_CERT_BUNDLE_ENCODING_BER = 0x02, - CSSM_CERT_BUNDLE_ENCODING_DER = 0x03, - CSSM_CERT_BUNDLE_ENCODING_SEXPR = 0x04, - CSSM_CERT_BUNDLE_ENCODING_PGP = 0x05 -}; - -typedef struct cssm_cert_bundle_header { - CSSM_CERT_BUNDLE_TYPE BundleType; - CSSM_CERT_BUNDLE_ENCODING BundleEncoding; -} CSSM_CERT_BUNDLE_HEADER __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_CERT_BUNDLE_HEADER_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_cert_bundle { - CSSM_CERT_BUNDLE_HEADER BundleHeader; - CSSM_DATA Bundle; -} CSSM_CERT_BUNDLE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_CERT_BUNDLE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -enum { - CSSM_FIELDVALUE_COMPLEX_DATA_TYPE = 0xFFFFFFFF -}; - - - -typedef uint32 CSSM_DB_ATTRIBUTE_NAME_FORMAT, *CSSM_DB_ATTRIBUTE_NAME_FORMAT_PTR; -enum { - CSSM_DB_ATTRIBUTE_NAME_AS_STRING = 0, - CSSM_DB_ATTRIBUTE_NAME_AS_OID = 1, - CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER = 2 -}; - -typedef uint32 CSSM_DB_ATTRIBUTE_FORMAT, *CSSM_DB_ATTRIBUTE_FORMAT_PTR; -enum { - CSSM_DB_ATTRIBUTE_FORMAT_STRING = 0, - CSSM_DB_ATTRIBUTE_FORMAT_SINT32 = 1, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 = 2, - CSSM_DB_ATTRIBUTE_FORMAT_BIG_NUM = 3, - CSSM_DB_ATTRIBUTE_FORMAT_REAL = 4, - CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE = 5, - CSSM_DB_ATTRIBUTE_FORMAT_BLOB = 6, - CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32 = 7, - CSSM_DB_ATTRIBUTE_FORMAT_COMPLEX = 8 -}; - -typedef struct cssm_db_attribute_info { - CSSM_DB_ATTRIBUTE_NAME_FORMAT AttributeNameFormat; - union cssm_db_attribute_label { - char *AttributeName; - CSSM_OID AttributeOID; - uint32 AttributeID; - } Label; - CSSM_DB_ATTRIBUTE_FORMAT AttributeFormat; -} CSSM_DB_ATTRIBUTE_INFO, *CSSM_DB_ATTRIBUTE_INFO_PTR; - -typedef struct cssm_db_attribute_data { - CSSM_DB_ATTRIBUTE_INFO Info; - uint32 NumberOfValues; - CSSM_DATA_PTR Value; -} CSSM_DB_ATTRIBUTE_DATA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DB_ATTRIBUTE_DATA_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_DB_RECORDTYPE; -enum { - - CSSM_DB_RECORDTYPE_SCHEMA_START = 0x00000000, - CSSM_DB_RECORDTYPE_SCHEMA_END = CSSM_DB_RECORDTYPE_SCHEMA_START + 4, - - CSSM_DB_RECORDTYPE_OPEN_GROUP_START = 0x0000000A, - CSSM_DB_RECORDTYPE_OPEN_GROUP_END = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 8, - - CSSM_DB_RECORDTYPE_APP_DEFINED_START = 0x80000000, - CSSM_DB_RECORDTYPE_APP_DEFINED_END = 0xffffffff, - - CSSM_DL_DB_SCHEMA_INFO = CSSM_DB_RECORDTYPE_SCHEMA_START + 0, - CSSM_DL_DB_SCHEMA_INDEXES = CSSM_DB_RECORDTYPE_SCHEMA_START + 1, - CSSM_DL_DB_SCHEMA_ATTRIBUTES = CSSM_DB_RECORDTYPE_SCHEMA_START + 2, - CSSM_DL_DB_SCHEMA_PARSING_MODULE = CSSM_DB_RECORDTYPE_SCHEMA_START + 3, - - CSSM_DL_DB_RECORD_ANY = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 0, - CSSM_DL_DB_RECORD_CERT = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 1, - CSSM_DL_DB_RECORD_CRL = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 2, - CSSM_DL_DB_RECORD_POLICY = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 3, - CSSM_DL_DB_RECORD_GENERIC = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 4, - CSSM_DL_DB_RECORD_PUBLIC_KEY = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 5, - CSSM_DL_DB_RECORD_PRIVATE_KEY = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 6, - CSSM_DL_DB_RECORD_SYMMETRIC_KEY = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 7, - CSSM_DL_DB_RECORD_ALL_KEYS = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 8 -}; - -enum { - CSSM_DB_CERT_USE_TRUSTED = 0x00000001, - CSSM_DB_CERT_USE_SYSTEM = 0x00000002, - CSSM_DB_CERT_USE_OWNER = 0x00000004, - CSSM_DB_CERT_USE_REVOKED = 0x00000008, - CSSM_DB_CERT_USE_SIGNING = 0x00000010, - CSSM_DB_CERT_USE_PRIVACY = 0x00000020 -}; - -typedef struct cssm_db_record_attribute_info { - CSSM_DB_RECORDTYPE DataRecordType; - uint32 NumberOfAttributes; - CSSM_DB_ATTRIBUTE_INFO_PTR AttributeInfo; -} CSSM_DB_RECORD_ATTRIBUTE_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DB_RECORD_ATTRIBUTE_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_db_record_attribute_data { - CSSM_DB_RECORDTYPE DataRecordType; - uint32 SemanticInformation; - uint32 NumberOfAttributes; - CSSM_DB_ATTRIBUTE_DATA_PTR AttributeData; -} CSSM_DB_RECORD_ATTRIBUTE_DATA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_db_parsing_module_info { - CSSM_DB_RECORDTYPE RecordType; - CSSM_SUBSERVICE_UID ModuleSubserviceUid; -} CSSM_DB_PARSING_MODULE_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DB_PARSING_MODULE_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_DB_INDEX_TYPE; -enum { - CSSM_DB_INDEX_UNIQUE = 0, - CSSM_DB_INDEX_NONUNIQUE = 1 -}; - -typedef uint32 CSSM_DB_INDEXED_DATA_LOCATION; -enum { - CSSM_DB_INDEX_ON_UNKNOWN = 0, - CSSM_DB_INDEX_ON_ATTRIBUTE = 1, - CSSM_DB_INDEX_ON_RECORD = 2 -}; - -typedef struct cssm_db_index_info { - CSSM_DB_INDEX_TYPE IndexType; - CSSM_DB_INDEXED_DATA_LOCATION IndexedDataLocation; - CSSM_DB_ATTRIBUTE_INFO Info; -} CSSM_DB_INDEX_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DB_INDEX_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_db_unique_record { - CSSM_DB_INDEX_INFO RecordLocator; - CSSM_DATA RecordIdentifier; -} CSSM_DB_UNIQUE_RECORD __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DB_UNIQUE_RECORD_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_db_record_index_info { - CSSM_DB_RECORDTYPE DataRecordType; - uint32 NumberOfIndexes; - CSSM_DB_INDEX_INFO_PTR IndexInfo; -} CSSM_DB_RECORD_INDEX_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DB_RECORD_INDEX_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_DB_ACCESS_TYPE, *CSSM_DB_ACCESS_TYPE_PTR; -enum { - CSSM_DB_ACCESS_READ = 0x00001, - CSSM_DB_ACCESS_WRITE = 0x00002, - CSSM_DB_ACCESS_PRIVILEGED = 0x00004 -}; - -typedef uint32 CSSM_DB_MODIFY_MODE; -enum { - CSSM_DB_MODIFY_ATTRIBUTE_NONE = 0, - CSSM_DB_MODIFY_ATTRIBUTE_ADD = CSSM_DB_MODIFY_ATTRIBUTE_NONE + 1, - CSSM_DB_MODIFY_ATTRIBUTE_DELETE = CSSM_DB_MODIFY_ATTRIBUTE_NONE + 2, - CSSM_DB_MODIFY_ATTRIBUTE_REPLACE = CSSM_DB_MODIFY_ATTRIBUTE_NONE + 3 -}; - -typedef struct cssm_dbinfo { - - - - uint32 NumberOfRecordTypes; - CSSM_DB_PARSING_MODULE_INFO_PTR DefaultParsingModules; - CSSM_DB_RECORD_ATTRIBUTE_INFO_PTR RecordAttributeNames; - CSSM_DB_RECORD_INDEX_INFO_PTR RecordIndexes; - - CSSM_BOOL IsLocal; - char *AccessPath; - void *Reserved; -} CSSM_DBINFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DBINFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_DB_OPERATOR, *CSSM_DB_OPERATOR_PTR; -enum { - CSSM_DB_EQUAL = 0, - CSSM_DB_NOT_EQUAL = 1, - CSSM_DB_LESS_THAN = 2, - CSSM_DB_GREATER_THAN = 3, - CSSM_DB_CONTAINS = 4, - CSSM_DB_CONTAINS_INITIAL_SUBSTRING = 5, - CSSM_DB_CONTAINS_FINAL_SUBSTRING = 6 -}; - -typedef uint32 CSSM_DB_CONJUNCTIVE, *CSSM_DB_CONJUNCTIVE_PTR; -enum { - CSSM_DB_NONE = 0, - CSSM_DB_AND = 1, - CSSM_DB_OR = 2 -}; - -typedef struct cssm_selection_predicate { - CSSM_DB_OPERATOR DbOperator; - CSSM_DB_ATTRIBUTE_DATA Attribute; -} CSSM_SELECTION_PREDICATE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SELECTION_PREDICATE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -enum { - CSSM_QUERY_TIMELIMIT_NONE = 0 -}; - -enum { - CSSM_QUERY_SIZELIMIT_NONE = 0 -}; - -typedef struct cssm_query_limits { - uint32 TimeLimit; - uint32 SizeLimit; -} CSSM_QUERY_LIMITS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_QUERY_LIMITS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_QUERY_FLAGS; -enum { - CSSM_QUERY_RETURN_DATA = 0x01 -}; - -typedef struct cssm_query { - CSSM_DB_RECORDTYPE RecordType; - CSSM_DB_CONJUNCTIVE Conjunctive; - uint32 NumSelectionPredicates; - CSSM_SELECTION_PREDICATE_PTR SelectionPredicate; - CSSM_QUERY_LIMITS QueryLimits; - CSSM_QUERY_FLAGS QueryFlags; -} CSSM_QUERY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_QUERY_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_DLTYPE, *CSSM_DLTYPE_PTR; -enum { - CSSM_DL_UNKNOWN = 0, - CSSM_DL_CUSTOM = 1, - CSSM_DL_LDAP = 2, - CSSM_DL_ODBC = 3, - CSSM_DL_PKCS11 = 4, - CSSM_DL_FFS = 5, - CSSM_DL_MEMORY = 6, - CSSM_DL_REMOTEDIR = 7 -}; - -typedef void *CSSM_DL_CUSTOM_ATTRIBUTES; -typedef void *CSSM_DL_LDAP_ATTRIBUTES; -typedef void *CSSM_DL_ODBC_ATTRIBUTES; -typedef void *CSSM_DL_FFS_ATTRIBUTES; - -typedef struct cssm_dl_pkcs11_attributes { - uint32 DeviceAccessFlags; -} *CSSM_DL_PKCS11_ATTRIBUTE, *CSSM_DL_PKCS11_ATTRIBUTE_PTR; - -enum { - CSSM_DB_DATASTORES_UNKNOWN = 0xFFFFFFFF -}; - -typedef struct cssm_name_list { - uint32 NumStrings; - char **String; -} CSSM_NAME_LIST __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_NAME_LIST_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef uint32 CSSM_DB_RETRIEVAL_MODES; -enum { - CSSM_DB_TRANSACTIONAL_MODE = 0, - CSSM_DB_FILESYSTEMSCAN_MODE = 1 -}; - -typedef struct cssm_db_schema_attribute_info { - uint32 AttributeId; - char *AttributeName; - CSSM_OID AttributeNameID; - CSSM_DB_ATTRIBUTE_FORMAT DataType; -} CSSM_DB_SCHEMA_ATTRIBUTE_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DB_SCHEMA_ATTRIBUTE_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_db_schema_index_info { - uint32 AttributeId; - uint32 IndexId; - CSSM_DB_INDEX_TYPE IndexType; - CSSM_DB_INDEXED_DATA_LOCATION IndexedDataLocation; -} CSSM_DB_SCHEMA_INDEX_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_DB_SCHEMA_INDEX_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} -extern "C" { - - -typedef uint8 CSSM_BER_TAG; -typedef struct cssm_x509_algorithm_identifier { - CSSM_OID algorithm; - CSSM_DATA parameters; -} CSSM_X509_ALGORITHM_IDENTIFIER __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_ALGORITHM_IDENTIFIER_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_x509_type_value_pair { - CSSM_OID type; - CSSM_BER_TAG valueType; - - CSSM_DATA value; -} CSSM_X509_TYPE_VALUE_PAIR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_TYPE_VALUE_PAIR_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509_rdn { - uint32 numberOfPairs; - CSSM_X509_TYPE_VALUE_PAIR_PTR AttributeTypeAndValue; -} CSSM_X509_RDN __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_RDN_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509_name { - uint32 numberOfRDNs; - CSSM_X509_RDN_PTR RelativeDistinguishedName; -} CSSM_X509_NAME __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_NAME_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_x509_subject_public_key_info { - CSSM_X509_ALGORITHM_IDENTIFIER algorithm; - CSSM_DATA subjectPublicKey; -} CSSM_X509_SUBJECT_PUBLIC_KEY_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_SUBJECT_PUBLIC_KEY_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509_time { - CSSM_BER_TAG timeType; - CSSM_DATA time; -} CSSM_X509_TIME __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_TIME_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct x509_validity { - CSSM_X509_TIME notBefore; - CSSM_X509_TIME notAfter; -} CSSM_X509_VALIDITY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_VALIDITY_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - -typedef CSSM_BOOL CSSM_X509_OPTION; - -typedef struct cssm_x509ext_basicConstraints { - CSSM_BOOL cA; - CSSM_X509_OPTION pathLenConstraintPresent; - uint32 pathLenConstraint; -} CSSM_X509EXT_BASICCONSTRAINTS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509EXT_BASICCONSTRAINTS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef enum extension_data_format { - CSSM_X509_DATAFORMAT_ENCODED = 0, - CSSM_X509_DATAFORMAT_PARSED, - CSSM_X509_DATAFORMAT_PAIR -} CSSM_X509EXT_DATA_FORMAT; - -typedef struct cssm_x509_extensionTagAndValue { - CSSM_BER_TAG type; - CSSM_DATA value; -} CSSM_X509EXT_TAGandVALUE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509EXT_TAGandVALUE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509ext_pair { - CSSM_X509EXT_TAGandVALUE tagAndValue; - void *parsedValue; -} CSSM_X509EXT_PAIR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509EXT_PAIR_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_x509_extension { - CSSM_OID extnId; - CSSM_BOOL critical; - CSSM_X509EXT_DATA_FORMAT format; - union cssm_x509ext_value { - CSSM_X509EXT_TAGandVALUE *tagAndValue; - void *parsedValue; - CSSM_X509EXT_PAIR *valuePair; - } value; - CSSM_DATA BERvalue; -} CSSM_X509_EXTENSION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_EXTENSION_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509_extensions { - uint32 numberOfExtensions; - CSSM_X509_EXTENSION_PTR extensions; -} CSSM_X509_EXTENSIONS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_EXTENSIONS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_x509_tbs_certificate { - CSSM_DATA version; - CSSM_DATA serialNumber; - CSSM_X509_ALGORITHM_IDENTIFIER signature; - CSSM_X509_NAME issuer; - CSSM_X509_VALIDITY validity; - CSSM_X509_NAME subject; - CSSM_X509_SUBJECT_PUBLIC_KEY_INFO subjectPublicKeyInfo; - CSSM_DATA issuerUniqueIdentifier; - CSSM_DATA subjectUniqueIdentifier; - CSSM_X509_EXTENSIONS extensions; -} CSSM_X509_TBS_CERTIFICATE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_TBS_CERTIFICATE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_x509_signature { - CSSM_X509_ALGORITHM_IDENTIFIER algorithmIdentifier; - CSSM_DATA encrypted; -} CSSM_X509_SIGNATURE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_SIGNATURE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_x509_signed_certificate { - CSSM_X509_TBS_CERTIFICATE certificate; - CSSM_X509_SIGNATURE signature; -} CSSM_X509_SIGNED_CERTIFICATE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_SIGNED_CERTIFICATE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509ext_policyQualifierInfo { - CSSM_OID policyQualifierId; - CSSM_DATA value; -} CSSM_X509EXT_POLICYQUALIFIERINFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509EXT_POLICYQUALIFIERINFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509ext_policyQualifiers { - uint32 numberOfPolicyQualifiers; - CSSM_X509EXT_POLICYQUALIFIERINFO *policyQualifier; -} CSSM_X509EXT_POLICYQUALIFIERS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509EXT_POLICYQUALIFIERS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509ext_policyInfo { - CSSM_OID policyIdentifier; - CSSM_X509EXT_POLICYQUALIFIERS policyQualifiers; -} CSSM_X509EXT_POLICYINFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509EXT_POLICYINFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -typedef struct cssm_x509_revoked_cert_entry { - CSSM_DATA certificateSerialNumber; - CSSM_X509_TIME revocationDate; - CSSM_X509_EXTENSIONS extensions; -} CSSM_X509_REVOKED_CERT_ENTRY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_REVOKED_CERT_ENTRY_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509_revoked_cert_list { - uint32 numberOfRevokedCertEntries; - CSSM_X509_REVOKED_CERT_ENTRY_PTR revokedCertEntry; -} CSSM_X509_REVOKED_CERT_LIST __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_REVOKED_CERT_LIST_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef struct cssm_x509_tbs_certlist { - CSSM_DATA version; - CSSM_X509_ALGORITHM_IDENTIFIER signature; - CSSM_X509_NAME issuer; - CSSM_X509_TIME thisUpdate; - CSSM_X509_TIME nextUpdate; - CSSM_X509_REVOKED_CERT_LIST_PTR revokedCertificates; - CSSM_X509_EXTENSIONS extensions; -} CSSM_X509_TBS_CERTLIST __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_TBS_CERTLIST_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_x509_signed_crl { - CSSM_X509_TBS_CERTLIST tbsCertList; - CSSM_X509_SIGNATURE signature; -} CSSM_X509_SIGNED_CRL __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_X509_SIGNED_CRL_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} -typedef enum __CE_GeneralNameType { - GNT_OtherName = 0, - GNT_RFC822Name, - GNT_DNSName, - GNT_X400Address, - GNT_DirectoryName, - GNT_EdiPartyName, - GNT_URI, - GNT_IPAddress, - GNT_RegisteredID -} CE_GeneralNameType; - -typedef struct __CE_OtherName { - CSSM_OID typeId; - CSSM_DATA value; -} CE_OtherName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_GeneralName { - CE_GeneralNameType nameType; - CSSM_BOOL berEncoded; - CSSM_DATA name; -} CE_GeneralName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_GeneralNames { - uint32 numNames; - CE_GeneralName *generalName; -} CE_GeneralNames __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef struct __CE_AuthorityKeyID { - CSSM_BOOL keyIdentifierPresent; - CSSM_DATA keyIdentifier; - CSSM_BOOL generalNamesPresent; - CE_GeneralNames *generalNames; - CSSM_BOOL serialNumberPresent; - CSSM_DATA serialNumber; -} CE_AuthorityKeyID __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - -typedef CSSM_DATA CE_SubjectKeyID __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef uint16 CE_KeyUsage __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef uint32 CE_CrlReason __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef struct __CE_ExtendedKeyUsage { - uint32 numPurposes; - CSSM_OID_PTR purposes; -} CE_ExtendedKeyUsage; -typedef struct __CE_BasicConstraints { - CSSM_BOOL cA; - CSSM_BOOL pathLenConstraintPresent; - uint32 pathLenConstraint; -} CE_BasicConstraints __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef struct __CE_PolicyQualifierInfo { - CSSM_OID policyQualifierId; - CSSM_DATA qualifier; - -} CE_PolicyQualifierInfo __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_PolicyInformation { - CSSM_OID certPolicyId; - uint32 numPolicyQualifiers; - CE_PolicyQualifierInfo *policyQualifiers; -} CE_PolicyInformation __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_CertPolicies { - uint32 numPolicies; - CE_PolicyInformation *policies; -} CE_CertPolicies __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef uint16 CE_NetscapeCertType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef uint8 CE_CrlDistReasonFlags __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef enum __CE_CrlDistributionPointNameType { - CE_CDNT_FullName, - CE_CDNT_NameRelativeToCrlIssuer -} CE_CrlDistributionPointNameType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_DistributionPointName { - CE_CrlDistributionPointNameType nameType; - union { - CE_GeneralNames *fullName; - CSSM_X509_RDN_PTR rdn; - } dpn; -} CE_DistributionPointName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -typedef struct __CE_CRLDistributionPoint { - CE_DistributionPointName *distPointName; - CSSM_BOOL reasonsPresent; - CE_CrlDistReasonFlags reasons; - CE_GeneralNames *crlIssuer; -} CE_CRLDistributionPoint __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_CRLDistPointsSyntax { - uint32 numDistPoints; - CE_CRLDistributionPoint *distPoints; -} CE_CRLDistPointsSyntax __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef struct __CE_AccessDescription { - CSSM_OID accessMethod; - CE_GeneralName accessLocation; -} CE_AccessDescription __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_AuthorityInfoAccess { - uint32 numAccessDescriptions; - CE_AccessDescription *accessDescriptions; -} CE_AuthorityInfoAccess __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef CE_GeneralNames CE_NameRegistrationAuthorities __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -typedef struct __CE_SemanticsInformation { - CSSM_OID *semanticsIdentifier; - CE_NameRegistrationAuthorities *nameRegistrationAuthorities; -} CE_SemanticsInformation __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef struct __CE_QC_Statement { - CSSM_OID statementId; - CE_SemanticsInformation *semanticsInfo; - CSSM_DATA *otherInfo; -} CE_QC_Statement __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -typedef struct __CE_QC_Statements { - uint32 numQCStatements; - CE_QC_Statement *qcStatements; -} CE_QC_Statements __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef uint32 CE_CrlNumber; - - - - - - -typedef uint32 CE_DeltaCrl; -typedef struct __CE_IssuingDistributionPoint { - CE_DistributionPointName *distPointName; - CSSM_BOOL onlyUserCertsPresent; - CSSM_BOOL onlyUserCerts; - CSSM_BOOL onlyCACertsPresent; - CSSM_BOOL onlyCACerts; - CSSM_BOOL onlySomeReasonsPresent; - CE_CrlDistReasonFlags onlySomeReasons; - CSSM_BOOL indirectCrlPresent; - CSSM_BOOL indirectCrl; -} CE_IssuingDistributionPoint __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef struct __CE_GeneralSubtree { - CE_GeneralNames *base; - uint32 minimum; - CSSM_BOOL maximumPresent; - uint32 maximum; -} CE_GeneralSubtree __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_GeneralSubtrees { - uint32 numSubtrees; - CE_GeneralSubtree *subtrees; -} CE_GeneralSubtrees __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_NameConstraints { - CE_GeneralSubtrees *permitted; - CE_GeneralSubtrees *excluded; -} CE_NameConstraints __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef struct __CE_PolicyMapping { - CSSM_OID issuerDomainPolicy; - CSSM_OID subjectDomainPolicy; -} CE_PolicyMapping __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_PolicyMappings { - uint32 numPolicyMappings; - CE_PolicyMapping *policyMappings; -} CE_PolicyMappings __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef struct __CE_PolicyConstraints { - CSSM_BOOL requireExplicitPolicyPresent; - uint32 requireExplicitPolicy; - CSSM_BOOL inhibitPolicyMappingPresent; - uint32 inhibitPolicyMapping; -} CE_PolicyConstraints __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -typedef uint32 CE_InhibitAnyPolicy __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -typedef enum __CE_DataType { - DT_AuthorityKeyID, - DT_SubjectKeyID, - DT_KeyUsage, - DT_SubjectAltName, - DT_IssuerAltName, - DT_ExtendedKeyUsage, - DT_BasicConstraints, - DT_CertPolicies, - DT_NetscapeCertType, - DT_CrlNumber, - DT_DeltaCrl, - DT_CrlReason, - DT_CrlDistributionPoints, - DT_IssuingDistributionPoint, - DT_AuthorityInfoAccess, - DT_Other, - DT_QC_Statements, - DT_NameConstraints, - DT_PolicyMappings, - DT_PolicyConstraints, - DT_InhibitAnyPolicy -} CE_DataType; - - - - -typedef union { - CE_AuthorityKeyID authorityKeyID; - CE_SubjectKeyID subjectKeyID; - CE_KeyUsage keyUsage; - CE_GeneralNames subjectAltName; - CE_GeneralNames issuerAltName; - CE_ExtendedKeyUsage extendedKeyUsage; - CE_BasicConstraints basicConstraints; - CE_CertPolicies certPolicies; - CE_NetscapeCertType netscapeCertType; - CE_CrlNumber crlNumber; - CE_DeltaCrl deltaCrl; - CE_CrlReason crlReason; - CE_CRLDistPointsSyntax crlDistPoints; - CE_IssuingDistributionPoint issuingDistPoint; - CE_AuthorityInfoAccess authorityInfoAccess; - CE_QC_Statements qualifiedCertStatements; - CE_NameConstraints nameConstraints; - CE_PolicyMappings policyMappings; - CE_PolicyConstraints policyConstraints; - CE_InhibitAnyPolicy inhibitAnyPolicy; - CSSM_DATA rawData; -} CE_Data __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct __CE_DataAndType { - CE_DataType type; - CE_Data extension; - CSSM_BOOL critical; -} CE_DataAndType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -extern "C" { - - - - - -extern const CSSM_GUID gGuidCssm; - - -extern const CSSM_GUID gGuidAppleFileDL; - - -extern const CSSM_GUID gGuidAppleCSP; - - -extern const CSSM_GUID gGuidAppleCSPDL; - - -extern const CSSM_GUID gGuidAppleX509CL; - - -extern const CSSM_GUID gGuidAppleX509TP; - - -extern const CSSM_GUID gGuidAppleLDAPDL; - - -extern const CSSM_GUID gGuidAppleDotMacTP; - - -extern const CSSM_GUID gGuidAppleSdCSPDL; - - -extern const CSSM_GUID gGuidAppleDotMacDL; - - - -enum -{ - CSSM_WORDID_KEYCHAIN_PROMPT = CSSM_WORDID_VENDOR_START, - CSSM_WORDID_KEYCHAIN_LOCK, - CSSM_WORDID_KEYCHAIN_CHANGE_LOCK, - CSSM_WORDID_PROCESS, - CSSM_WORDID__RESERVED_1, - CSSM_WORDID_SYMMETRIC_KEY, - CSSM_WORDID_SYSTEM, - CSSM_WORDID_KEY, - CSSM_WORDID_PIN, - CSSM_WORDID_PREAUTH, - CSSM_WORDID_PREAUTH_SOURCE, - CSSM_WORDID_ASYMMETRIC_KEY, - CSSM_WORDID__FIRST_UNUSED -}; - - -enum -{ - CSSM_ACL_SUBJECT_TYPE_KEYCHAIN_PROMPT = CSSM_WORDID_KEYCHAIN_PROMPT, - CSSM_ACL_SUBJECT_TYPE_PROCESS = CSSM_WORDID_PROCESS, - CSSM_ACL_SUBJECT_TYPE_CODE_SIGNATURE = CSSM_WORDID_SIGNATURE, - CSSM_ACL_SUBJECT_TYPE_COMMENT = CSSM_WORDID_COMMENT, - CSSM_ACL_SUBJECT_TYPE_SYMMETRIC_KEY = CSSM_WORDID_SYMMETRIC_KEY, - CSSM_ACL_SUBJECT_TYPE_PREAUTH = CSSM_WORDID_PREAUTH, - CSSM_ACL_SUBJECT_TYPE_PREAUTH_SOURCE = CSSM_WORDID_PREAUTH_SOURCE, - CSSM_ACL_SUBJECT_TYPE_ASYMMETRIC_KEY = CSSM_WORDID_ASYMMETRIC_KEY -}; - -enum -{ - CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT = CSSM_WORDID_KEYCHAIN_PROMPT, - CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK = CSSM_WORDID_KEYCHAIN_LOCK, - CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK = CSSM_WORDID_KEYCHAIN_CHANGE_LOCK, - CSSM_SAMPLE_TYPE_PROCESS = CSSM_WORDID_PROCESS, - CSSM_SAMPLE_TYPE_COMMENT = CSSM_WORDID_COMMENT, - CSSM_SAMPLE_TYPE_RETRY_ID = CSSM_WORDID_PROPAGATE, - CSSM_SAMPLE_TYPE_SYMMETRIC_KEY = CSSM_WORDID_SYMMETRIC_KEY, - CSSM_SAMPLE_TYPE_PREAUTH = CSSM_WORDID_PREAUTH, - CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY = CSSM_WORDID_ASYMMETRIC_KEY - -}; - - - -enum { - CSSM_ACL_AUTHORIZATION_CHANGE_ACL = CSSM_ACL_AUTHORIZATION_TAG_VENDOR_DEFINED_START, - CSSM_ACL_AUTHORIZATION_CHANGE_OWNER, - - - CSSM_ACL_AUTHORIZATION_PREAUTH_BASE = - CSSM_ACL_AUTHORIZATION_TAG_VENDOR_DEFINED_START + 0x1000000, - CSSM_ACL_AUTHORIZATION_PREAUTH_END = CSSM_ACL_AUTHORIZATION_PREAUTH_BASE + 0x10000 -}; -enum { - CSSM_ACL_CODE_SIGNATURE_INVALID = 0, - CSSM_ACL_CODE_SIGNATURE_OSX = 1 -}; - - - -enum { - CSSM_ACL_MATCH_UID = 0x01, - CSSM_ACL_MATCH_GID = 0x02, - CSSM_ACL_MATCH_HONOR_ROOT = 0x100, - CSSM_ACL_MATCH_BITS = CSSM_ACL_MATCH_UID | CSSM_ACL_MATCH_GID -}; - -enum { - CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION = 0x101 -}; - -typedef struct cssm_acl_process_subject_selector { - uint16 version; - uint16 mask; - uint32 uid; - uint32 gid; -} CSSM_ACL_PROCESS_SUBJECT_SELECTOR; - - - -enum { - CSSM_ACL_KEYCHAIN_PROMPT_CURRENT_VERSION = 0x101 -}; - -enum { - CSSM_ACL_KEYCHAIN_PROMPT_REQUIRE_PASSPHRASE = 0x0001, - - CSSM_ACL_KEYCHAIN_PROMPT_UNSIGNED = 0x0010, - CSSM_ACL_KEYCHAIN_PROMPT_UNSIGNED_ACT = 0x0020, - CSSM_ACL_KEYCHAIN_PROMPT_INVALID = 0x0040, - CSSM_ACL_KEYCHAIN_PROMPT_INVALID_ACT = 0x0080, -}; - -typedef struct cssm_acl_keychain_prompt_selector { - uint16 version; - uint16 flags; -} CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR; - - -typedef uint32 CSSM_ACL_PREAUTH_TRACKING_STATE; -enum { - CSSM_ACL_PREAUTH_TRACKING_COUNT_MASK = 0xff, - CSSM_ACL_PREAUTH_TRACKING_BLOCKED = 0, - - - - CSSM_ACL_PREAUTH_TRACKING_UNKNOWN = 0x40000000, - CSSM_ACL_PREAUTH_TRACKING_AUTHORIZED = 0x80000000 -}; - - - -enum { - CSSM_DB_ACCESS_RESET = 0x10000 -}; - - - -enum -{ - CSSM_ALGID_APPLE_YARROW = CSSM_ALGID_VENDOR_DEFINED, - CSSM_ALGID_AES, - CSSM_ALGID_FEE, - CSSM_ALGID_FEE_MD5, - CSSM_ALGID_FEE_SHA1, - CSSM_ALGID_FEED, - CSSM_ALGID_FEEDEXP, - CSSM_ALGID_ASC, - CSSM_ALGID_SHA1HMAC_LEGACY, - CSSM_ALGID_KEYCHAIN_KEY, - CSSM_ALGID_PKCS12_PBE_ENCR, - CSSM_ALGID_PKCS12_PBE_MAC, - CSSM_ALGID_SECURE_PASSPHRASE, - CSSM_ALGID_PBE_OPENSSL_MD5, - CSSM_ALGID_SHA256, - CSSM_ALGID_SHA384, - CSSM_ALGID_SHA512, - CSSM_ALGID_ENTROPY_DEFAULT, - CSSM_ALGID_SHA224, - CSSM_ALGID_SHA224WithRSA, - CSSM_ALGID_SHA256WithRSA, - CSSM_ALGID_SHA384WithRSA, - CSSM_ALGID_SHA512WithRSA, - CSSM_ALGID_OPENSSH1, - CSSM_ALGID_SHA224WithECDSA, - CSSM_ALGID_SHA256WithECDSA, - CSSM_ALGID_SHA384WithECDSA, - CSSM_ALGID_SHA512WithECDSA, - CSSM_ALGID_ECDSA_SPECIFIED, - CSSM_ALGID_ECDH_X963_KDF, - CSSM_ALGID__FIRST_UNUSED -}; - - -enum -{ - - CSSM_PADDING_APPLE_SSLv2 = CSSM_PADDING_VENDOR_DEFINED -}; - - - -enum { - CSSM_KEYBLOB_RAW_FORMAT_VENDOR_DEFINED = 0x80000000 -}; -enum { - - CSSM_KEYBLOB_RAW_FORMAT_X509 = CSSM_KEYBLOB_RAW_FORMAT_VENDOR_DEFINED, - - CSSM_KEYBLOB_RAW_FORMAT_OPENSSH, - - CSSM_KEYBLOB_RAW_FORMAT_OPENSSL, - - CSSM_KEYBLOB_RAW_FORMAT_OPENSSH2 -}; - - -enum -{ - CSSM_CUSTOM_COMMON_ERROR_EXTENT = 0x00e0, - - CSSM_ERRCODE_NO_USER_INTERACTION = 0x00e0, - CSSM_ERRCODE_USER_CANCELED = 0x00e1, - CSSM_ERRCODE_SERVICE_NOT_AVAILABLE = 0x00e2, - CSSM_ERRCODE_INSUFFICIENT_CLIENT_IDENTIFICATION = 0x00e3, - CSSM_ERRCODE_DEVICE_RESET = 0x00e4, - CSSM_ERRCODE_DEVICE_FAILED = 0x00e5, - CSSM_ERRCODE_IN_DARK_WAKE = 0x00e6 -}; - -enum { - CSSMERR_CSSM_NO_USER_INTERACTION = CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_NO_USER_INTERACTION, - CSSMERR_AC_NO_USER_INTERACTION = CSSM_AC_BASE_ERROR + CSSM_ERRCODE_NO_USER_INTERACTION, - CSSMERR_CSP_NO_USER_INTERACTION = CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_NO_USER_INTERACTION, - CSSMERR_CL_NO_USER_INTERACTION = CSSM_CL_BASE_ERROR + CSSM_ERRCODE_NO_USER_INTERACTION, - CSSMERR_DL_NO_USER_INTERACTION = CSSM_DL_BASE_ERROR + CSSM_ERRCODE_NO_USER_INTERACTION, - CSSMERR_TP_NO_USER_INTERACTION = CSSM_TP_BASE_ERROR + CSSM_ERRCODE_NO_USER_INTERACTION, - - CSSMERR_CSSM_USER_CANCELED = CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_USER_CANCELED, - CSSMERR_AC_USER_CANCELED = CSSM_AC_BASE_ERROR + CSSM_ERRCODE_USER_CANCELED, - CSSMERR_CSP_USER_CANCELED = CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_USER_CANCELED, - CSSMERR_CL_USER_CANCELED = CSSM_CL_BASE_ERROR + CSSM_ERRCODE_USER_CANCELED, - CSSMERR_DL_USER_CANCELED = CSSM_DL_BASE_ERROR + CSSM_ERRCODE_USER_CANCELED, - CSSMERR_TP_USER_CANCELED = CSSM_TP_BASE_ERROR + CSSM_ERRCODE_USER_CANCELED, - - CSSMERR_CSSM_SERVICE_NOT_AVAILABLE = CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_SERVICE_NOT_AVAILABLE, - CSSMERR_AC_SERVICE_NOT_AVAILABLE = CSSM_AC_BASE_ERROR + CSSM_ERRCODE_SERVICE_NOT_AVAILABLE, - CSSMERR_CSP_SERVICE_NOT_AVAILABLE = CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_SERVICE_NOT_AVAILABLE, - CSSMERR_CL_SERVICE_NOT_AVAILABLE = CSSM_CL_BASE_ERROR + CSSM_ERRCODE_SERVICE_NOT_AVAILABLE, - CSSMERR_DL_SERVICE_NOT_AVAILABLE = CSSM_DL_BASE_ERROR + CSSM_ERRCODE_SERVICE_NOT_AVAILABLE, - CSSMERR_TP_SERVICE_NOT_AVAILABLE = CSSM_TP_BASE_ERROR + CSSM_ERRCODE_SERVICE_NOT_AVAILABLE, - - CSSMERR_CSSM_INSUFFICIENT_CLIENT_IDENTIFICATION = CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_INSUFFICIENT_CLIENT_IDENTIFICATION, - CSSMERR_AC_INSUFFICIENT_CLIENT_IDENTIFICATION = CSSM_AC_BASE_ERROR + CSSM_ERRCODE_INSUFFICIENT_CLIENT_IDENTIFICATION, - CSSMERR_CSP_INSUFFICIENT_CLIENT_IDENTIFICATION = CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_INSUFFICIENT_CLIENT_IDENTIFICATION, - CSSMERR_CL_INSUFFICIENT_CLIENT_IDENTIFICATION = CSSM_CL_BASE_ERROR + CSSM_ERRCODE_INSUFFICIENT_CLIENT_IDENTIFICATION, - CSSMERR_DL_INSUFFICIENT_CLIENT_IDENTIFICATION = CSSM_DL_BASE_ERROR + CSSM_ERRCODE_INSUFFICIENT_CLIENT_IDENTIFICATION, - CSSMERR_TP_INSUFFICIENT_CLIENT_IDENTIFICATION = CSSM_TP_BASE_ERROR + CSSM_ERRCODE_INSUFFICIENT_CLIENT_IDENTIFICATION, - - CSSMERR_CSSM_DEVICE_RESET = CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_DEVICE_RESET, - CSSMERR_AC_DEVICE_RESET = CSSM_AC_BASE_ERROR + CSSM_ERRCODE_DEVICE_RESET, - CSSMERR_CSP_DEVICE_RESET = CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_DEVICE_RESET, - CSSMERR_CL_DEVICE_RESET = CSSM_CL_BASE_ERROR + CSSM_ERRCODE_DEVICE_RESET, - CSSMERR_DL_DEVICE_RESET = CSSM_DL_BASE_ERROR + CSSM_ERRCODE_DEVICE_RESET, - CSSMERR_TP_DEVICE_RESET = CSSM_TP_BASE_ERROR + CSSM_ERRCODE_DEVICE_RESET, - - CSSMERR_CSSM_DEVICE_FAILED = CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_DEVICE_FAILED, - CSSMERR_AC_DEVICE_FAILED = CSSM_AC_BASE_ERROR + CSSM_ERRCODE_DEVICE_FAILED, - CSSMERR_CSP_DEVICE_FAILED = CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_DEVICE_FAILED, - CSSMERR_CL_DEVICE_FAILED = CSSM_CL_BASE_ERROR + CSSM_ERRCODE_DEVICE_FAILED, - CSSMERR_DL_DEVICE_FAILED = CSSM_DL_BASE_ERROR + CSSM_ERRCODE_DEVICE_FAILED, - CSSMERR_TP_DEVICE_FAILED = CSSM_TP_BASE_ERROR + CSSM_ERRCODE_DEVICE_FAILED, - - CSSMERR_CSSM_IN_DARK_WAKE = CSSM_CSSM_BASE_ERROR + CSSM_ERRCODE_IN_DARK_WAKE, - CSSMERR_AC_IN_DARK_WAKE = CSSM_AC_BASE_ERROR + CSSM_ERRCODE_IN_DARK_WAKE, - CSSMERR_CSP_IN_DARK_WAKE = CSSM_CSP_BASE_ERROR + CSSM_ERRCODE_IN_DARK_WAKE, - CSSMERR_CL_IN_DARK_WAKE = CSSM_CL_BASE_ERROR + CSSM_ERRCODE_IN_DARK_WAKE, - CSSMERR_DL_IN_DARK_WAKE = CSSM_DL_BASE_ERROR + CSSM_ERRCODE_IN_DARK_WAKE, - CSSMERR_TP_IN_DARK_WAKE = CSSM_TP_BASE_ERROR + CSSM_ERRCODE_IN_DARK_WAKE -}; - - -enum { - CSSMERR_CSP_APPLE_ADD_APPLICATION_ACL_SUBJECT = CSSM_CSP_PRIVATE_ERROR + 0, - - - - - CSSMERR_CSP_APPLE_PUBLIC_KEY_INCOMPLETE = CSSM_CSP_PRIVATE_ERROR + 1, - - - CSSMERR_CSP_APPLE_SIGNATURE_MISMATCH = CSSM_CSP_PRIVATE_ERROR + 2, - - - CSSMERR_CSP_APPLE_INVALID_KEY_START_DATE = CSSM_CSP_PRIVATE_ERROR + 3, - CSSMERR_CSP_APPLE_INVALID_KEY_END_DATE = CSSM_CSP_PRIVATE_ERROR + 4, - - - CSSMERR_CSPDL_APPLE_DL_CONVERSION_ERROR = CSSM_CSP_PRIVATE_ERROR + 5, - - - CSSMERR_CSP_APPLE_SSLv2_ROLLBACK = CSSM_CSP_PRIVATE_ERROR + 6 -}; - - - -enum -{ - CSSM_DL_DB_RECORD_GENERIC_PASSWORD = CSSM_DB_RECORDTYPE_APP_DEFINED_START + 0, - CSSM_DL_DB_RECORD_INTERNET_PASSWORD = CSSM_DB_RECORDTYPE_APP_DEFINED_START + 1, - CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD = CSSM_DB_RECORDTYPE_APP_DEFINED_START + 2, - - CSSM_DL_DB_RECORD_X509_CERTIFICATE = CSSM_DB_RECORDTYPE_APP_DEFINED_START + 0x1000, - CSSM_DL_DB_RECORD_USER_TRUST, - CSSM_DL_DB_RECORD_X509_CRL, - CSSM_DL_DB_RECORD_UNLOCK_REFERRAL, - CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE, - CSSM_DL_DB_RECORD_METADATA = CSSM_DB_RECORDTYPE_APP_DEFINED_START + 0x8000 -}; - - -enum { - - - - CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT, - - - CSSM_APPLEFILEDL_COMMIT, - - - CSSM_APPLEFILEDL_ROLLBACK -}; - - -enum { - CSSM_APPLE_UNLOCK_TYPE_KEY_DIRECT = 1, - CSSM_APPLE_UNLOCK_TYPE_WRAPPED_PRIVATE = 2 -}; - - -enum -{ - - - - CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS = CSSM_DL_PRIVATE_ERROR + 0, - - - CSSMERR_APPLEDL_DISK_FULL = CSSM_DL_PRIVATE_ERROR + 1, - - - CSSMERR_APPLEDL_QUOTA_EXCEEDED = CSSM_DL_PRIVATE_ERROR + 2, - - - CSSMERR_APPLEDL_FILE_TOO_BIG = CSSM_DL_PRIVATE_ERROR + 3, - - - CSSMERR_APPLEDL_INVALID_DATABASE_BLOB = CSSM_DL_PRIVATE_ERROR + 4, - CSSMERR_APPLEDL_INVALID_KEY_BLOB = CSSM_DL_PRIVATE_ERROR + 5, - - - CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB = CSSM_DL_PRIVATE_ERROR + 6, - CSSMERR_APPLEDL_INCOMPATIBLE_KEY_BLOB = CSSM_DL_PRIVATE_ERROR + 7, -}; - - -enum -{ - - CSSMERR_APPLETP_HOSTNAME_MISMATCH = CSSM_TP_PRIVATE_ERROR + 0, - - CSSMERR_APPLETP_UNKNOWN_CRITICAL_EXTEN = CSSM_TP_PRIVATE_ERROR + 1, - - CSSMERR_APPLETP_NO_BASIC_CONSTRAINTS = CSSM_TP_PRIVATE_ERROR + 2, - - CSSMERR_APPLETP_INVALID_CA = CSSM_TP_PRIVATE_ERROR + 3, - - CSSMERR_APPLETP_INVALID_AUTHORITY_ID = CSSM_TP_PRIVATE_ERROR + 4, - - CSSMERR_APPLETP_INVALID_SUBJECT_ID = CSSM_TP_PRIVATE_ERROR + 5, - - CSSMERR_APPLETP_INVALID_KEY_USAGE = CSSM_TP_PRIVATE_ERROR + 6, - - CSSMERR_APPLETP_INVALID_EXTENDED_KEY_USAGE = CSSM_TP_PRIVATE_ERROR + 7, - - CSSMERR_APPLETP_INVALID_ID_LINKAGE = CSSM_TP_PRIVATE_ERROR + 8, - - CSSMERR_APPLETP_PATH_LEN_CONSTRAINT = CSSM_TP_PRIVATE_ERROR + 9, - - CSSMERR_APPLETP_INVALID_ROOT = CSSM_TP_PRIVATE_ERROR + 10, - - CSSMERR_APPLETP_CRL_EXPIRED = CSSM_TP_PRIVATE_ERROR + 11, - CSSMERR_APPLETP_CRL_NOT_VALID_YET = CSSM_TP_PRIVATE_ERROR + 12, - - CSSMERR_APPLETP_CRL_NOT_FOUND = CSSM_TP_PRIVATE_ERROR + 13, - - CSSMERR_APPLETP_CRL_SERVER_DOWN = CSSM_TP_PRIVATE_ERROR + 14, - - CSSMERR_APPLETP_CRL_BAD_URI = CSSM_TP_PRIVATE_ERROR + 15, - - CSSMERR_APPLETP_UNKNOWN_CERT_EXTEN = CSSM_TP_PRIVATE_ERROR + 16, - CSSMERR_APPLETP_UNKNOWN_CRL_EXTEN = CSSM_TP_PRIVATE_ERROR + 17, - - CSSMERR_APPLETP_CRL_NOT_TRUSTED = CSSM_TP_PRIVATE_ERROR + 18, - - CSSMERR_APPLETP_CRL_INVALID_ANCHOR_CERT = CSSM_TP_PRIVATE_ERROR + 19, - - CSSMERR_APPLETP_CRL_POLICY_FAIL = CSSM_TP_PRIVATE_ERROR + 20, - - CSSMERR_APPLETP_IDP_FAIL = CSSM_TP_PRIVATE_ERROR + 21, - - CSSMERR_APPLETP_CERT_NOT_FOUND_FROM_ISSUER = CSSM_TP_PRIVATE_ERROR + 22, - - CSSMERR_APPLETP_BAD_CERT_FROM_ISSUER = CSSM_TP_PRIVATE_ERROR + 23, - - CSSMERR_APPLETP_SMIME_EMAIL_ADDRS_NOT_FOUND = CSSM_TP_PRIVATE_ERROR + 24, - - CSSMERR_APPLETP_SMIME_BAD_EXT_KEY_USE = CSSM_TP_PRIVATE_ERROR + 25, - - CSSMERR_APPLETP_SMIME_BAD_KEY_USE = CSSM_TP_PRIVATE_ERROR + 26, - - CSSMERR_APPLETP_SMIME_KEYUSAGE_NOT_CRITICAL = CSSM_TP_PRIVATE_ERROR + 27, - - - CSSMERR_APPLETP_SMIME_NO_EMAIL_ADDRS = CSSM_TP_PRIVATE_ERROR + 28, - - - CSSMERR_APPLETP_SMIME_SUBJ_ALT_NAME_NOT_CRIT = CSSM_TP_PRIVATE_ERROR + 29, - - CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE = CSSM_TP_PRIVATE_ERROR + 30, - - CSSMERR_APPLETP_OCSP_BAD_RESPONSE = CSSM_TP_PRIVATE_ERROR + 31, - - CSSMERR_APPLETP_OCSP_BAD_REQUEST = CSSM_TP_PRIVATE_ERROR + 32, - - CSSMERR_APPLETP_OCSP_UNAVAILABLE = CSSM_TP_PRIVATE_ERROR + 33, - - CSSMERR_APPLETP_OCSP_STATUS_UNRECOGNIZED = CSSM_TP_PRIVATE_ERROR + 34, - - CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK = CSSM_TP_PRIVATE_ERROR + 35, - - CSSMERR_APPLETP_NETWORK_FAILURE = CSSM_TP_PRIVATE_ERROR + 36, - - CSSMERR_APPLETP_OCSP_NOT_TRUSTED = CSSM_TP_PRIVATE_ERROR + 37, - - CSSMERR_APPLETP_OCSP_INVALID_ANCHOR_CERT = CSSM_TP_PRIVATE_ERROR + 38, - - CSSMERR_APPLETP_OCSP_SIG_ERROR = CSSM_TP_PRIVATE_ERROR + 39, - - CSSMERR_APPLETP_OCSP_NO_SIGNER = CSSM_TP_PRIVATE_ERROR + 40, - - CSSMERR_APPLETP_OCSP_RESP_MALFORMED_REQ = CSSM_TP_PRIVATE_ERROR + 41, - - CSSMERR_APPLETP_OCSP_RESP_INTERNAL_ERR = CSSM_TP_PRIVATE_ERROR + 42, - - CSSMERR_APPLETP_OCSP_RESP_TRY_LATER = CSSM_TP_PRIVATE_ERROR + 43, - - CSSMERR_APPLETP_OCSP_RESP_SIG_REQUIRED = CSSM_TP_PRIVATE_ERROR + 44, - - CSSMERR_APPLETP_OCSP_RESP_UNAUTHORIZED = CSSM_TP_PRIVATE_ERROR + 45, - - CSSMERR_APPLETP_OCSP_NONCE_MISMATCH = CSSM_TP_PRIVATE_ERROR + 46, - - CSSMERR_APPLETP_CS_BAD_CERT_CHAIN_LENGTH = CSSM_TP_PRIVATE_ERROR + 47, - - CSSMERR_APPLETP_CS_NO_BASIC_CONSTRAINTS = CSSM_TP_PRIVATE_ERROR + 48, - - CSSMERR_APPLETP_CS_BAD_PATH_LENGTH = CSSM_TP_PRIVATE_ERROR + 49, - - CSSMERR_APPLETP_CS_NO_EXTENDED_KEY_USAGE = CSSM_TP_PRIVATE_ERROR + 50, - - CSSMERR_APPLETP_CODE_SIGN_DEVELOPMENT = CSSM_TP_PRIVATE_ERROR + 51, - - CSSMERR_APPLETP_RS_BAD_CERT_CHAIN_LENGTH = CSSM_TP_PRIVATE_ERROR + 52, - - CSSMERR_APPLETP_RS_BAD_EXTENDED_KEY_USAGE = CSSM_TP_PRIVATE_ERROR + 53, - - CSSMERR_APPLETP_TRUST_SETTING_DENY = CSSM_TP_PRIVATE_ERROR + 54, - - CSSMERR_APPLETP_INVALID_EMPTY_SUBJECT = CSSM_TP_PRIVATE_ERROR + 55, - - CSSMERR_APPLETP_UNKNOWN_QUAL_CERT_STATEMENT = CSSM_TP_PRIVATE_ERROR + 56, - - CSSMERR_APPLETP_MISSING_REQUIRED_EXTENSION = CSSM_TP_PRIVATE_ERROR + 57, - - CSSMERR_APPLETP_EXT_KEYUSAGE_NOT_CRITICAL = CSSM_TP_PRIVATE_ERROR + 58, - - CSSMERR_APPLETP_IDENTIFIER_MISSING = CSSM_TP_PRIVATE_ERROR + 59, - - CSSMERR_APPLETP_CA_PIN_MISMATCH = CSSM_TP_PRIVATE_ERROR + 60 -}; - - -enum -{ - - CSSMERR_APPLE_DOTMAC_REQ_QUEUED = CSSM_TP_PRIVATE_ERROR + 100, - - CSSMERR_APPLE_DOTMAC_REQ_REDIRECT = CSSM_TP_PRIVATE_ERROR + 101, - - CSSMERR_APPLE_DOTMAC_REQ_SERVER_ERR = CSSM_TP_PRIVATE_ERROR + 102, - - CSSMERR_APPLE_DOTMAC_REQ_SERVER_PARAM = CSSM_TP_PRIVATE_ERROR + 103, - - CSSMERR_APPLE_DOTMAC_REQ_SERVER_AUTH = CSSM_TP_PRIVATE_ERROR + 104, - - CSSMERR_APPLE_DOTMAC_REQ_SERVER_UNIMPL = CSSM_TP_PRIVATE_ERROR + 105, - - CSSMERR_APPLE_DOTMAC_REQ_SERVER_NOT_AVAIL = CSSM_TP_PRIVATE_ERROR + 106, - - CSSMERR_APPLE_DOTMAC_REQ_SERVER_ALREADY_EXIST = CSSM_TP_PRIVATE_ERROR + 107, - - CSSMERR_APPLE_DOTMAC_REQ_SERVER_SERVICE_ERROR = CSSM_TP_PRIVATE_ERROR + 108, - - CSSMERR_APPLE_DOTMAC_REQ_IS_PENDING = CSSM_TP_PRIVATE_ERROR + 109, - - CSSMERR_APPLE_DOTMAC_NO_REQ_PENDING = CSSM_TP_PRIVATE_ERROR + 110, - - CSSMERR_APPLE_DOTMAC_CSR_VERIFY_FAIL = CSSM_TP_PRIVATE_ERROR + 111, - - CSSMERR_APPLE_DOTMAC_FAILED_CONSISTENCY_CHECK = CSSM_TP_PRIVATE_ERROR + 112 -}; - -enum -{ - CSSM_APPLEDL_OPEN_PARAMETERS_VERSION = 1 -}; - -enum cssm_appledl_open_parameters_mask -{ - kCSSM_APPLEDL_MASK_MODE = (1 << 0) -}; - - - - - -typedef struct cssm_appledl_open_parameters -{ - uint32 length; - uint32 version; - CSSM_BOOL autoCommit; - - - uint32 mask; - - - mode_t mode; -} CSSM_APPLEDL_OPEN_PARAMETERS, *CSSM_APPLEDL_OPEN_PARAMETERS_PTR; - - - -enum -{ - - - CSSM_APPLECSPDL_DB_LOCK = 0, - - - - - - - - CSSM_APPLECSPDL_DB_UNLOCK = 1, - CSSM_APPLECSPDL_DB_GET_SETTINGS = 2, - - - - - - - - CSSM_APPLECSPDL_DB_SET_SETTINGS = 3, - CSSM_APPLECSPDL_DB_IS_LOCKED = 4, - CSSM_APPLECSPDL_DB_CHANGE_PASSWORD =5, - - - CSSM_APPLECSPDL_DB_GET_HANDLE = 6, - - - CSSM_APPLESCPDL_CSP_GET_KEYHANDLE = 7, - - CSSM_APPLE_PRIVATE_CSPDL_CODE_8 = 8, - CSSM_APPLE_PRIVATE_CSPDL_CODE_9 = 9, - CSSM_APPLE_PRIVATE_CSPDL_CODE_10 = 10, - CSSM_APPLE_PRIVATE_CSPDL_CODE_11 = 11, - CSSM_APPLE_PRIVATE_CSPDL_CODE_12 = 12, - CSSM_APPLE_PRIVATE_CSPDL_CODE_13 = 13, - CSSM_APPLE_PRIVATE_CSPDL_CODE_14 = 14, - CSSM_APPLE_PRIVATE_CSPDL_CODE_15 = 15, - CSSM_APPLE_PRIVATE_CSPDL_CODE_16 = 16, - CSSM_APPLE_PRIVATE_CSPDL_CODE_17 = 17, - CSSM_APPLE_PRIVATE_CSPDL_CODE_18 = 18, - - - - - - - CSSM_APPLECSP_KEYDIGEST = 0x100 -}; - - - - -typedef struct cssm_applecspdl_db_settings_parameters -{ - uint32 idleTimeout; - uint8 lockOnSleep; -} CSSM_APPLECSPDL_DB_SETTINGS_PARAMETERS, *CSSM_APPLECSPDL_DB_SETTINGS_PARAMETERS_PTR; - - -typedef struct cssm_applecspdl_db_is_locked_parameters -{ - uint8 isLocked; -} CSSM_APPLECSPDL_DB_IS_LOCKED_PARAMETERS, *CSSM_APPLECSPDL_DB_IS_LOCKED_PARAMETERS_PTR; - - -typedef struct cssm_applecspdl_db_change_password_parameters -{ - CSSM_ACCESS_CREDENTIALS *accessCredentials; -} CSSM_APPLECSPDL_DB_CHANGE_PASSWORD_PARAMETERS, *CSSM_APPLECSPDL_DB_CHANGE_PASSWORD_PARAMETERS_PTR; - - -enum { - CSSM_KEYBLOB_WRAPPED_FORMAT_APPLE_CUSTOM = 100, - CSSM_KEYBLOB_WRAPPED_FORMAT_OPENSSL, - CSSM_KEYBLOB_WRAPPED_FORMAT_OPENSSH1 -}; - - - - -enum { - CSSM_ATTRIBUTE_VENDOR_DEFINED = 0x800000 -}; - -enum { - - - - CSSM_ATTRIBUTE_PUBLIC_KEY = - (CSSM_ATTRIBUTE_DATA_KEY | (CSSM_ATTRIBUTE_VENDOR_DEFINED + 0)), - - - - - - CSSM_ATTRIBUTE_FEE_PRIME_TYPE = - (CSSM_ATTRIBUTE_DATA_UINT32 | (CSSM_ATTRIBUTE_VENDOR_DEFINED + 1)), - CSSM_ATTRIBUTE_FEE_CURVE_TYPE = - (CSSM_ATTRIBUTE_DATA_UINT32 | (CSSM_ATTRIBUTE_VENDOR_DEFINED + 2)), - - - - - - CSSM_ATTRIBUTE_ASC_OPTIMIZATION = - (CSSM_ATTRIBUTE_DATA_UINT32 | (CSSM_ATTRIBUTE_VENDOR_DEFINED + 3)), - - - - - CSSM_ATTRIBUTE_RSA_BLINDING = - (CSSM_ATTRIBUTE_DATA_UINT32 | (CSSM_ATTRIBUTE_VENDOR_DEFINED + 4)), - - - - - - CSSM_ATTRIBUTE_PARAM_KEY = - (CSSM_ATTRIBUTE_DATA_KEY | (CSSM_ATTRIBUTE_VENDOR_DEFINED + 5)), - - - - - - CSSM_ATTRIBUTE_PROMPT = - (CSSM_ATTRIBUTE_DATA_CSSM_DATA | (CSSM_ATTRIBUTE_VENDOR_DEFINED + 6)), - - - - - - CSSM_ATTRIBUTE_ALERT_TITLE = - (CSSM_ATTRIBUTE_DATA_CSSM_DATA | (CSSM_ATTRIBUTE_VENDOR_DEFINED + 7)), - - - - - - - CSSM_ATTRIBUTE_VERIFY_PASSPHRASE = - (CSSM_ATTRIBUTE_DATA_UINT32 | (CSSM_ATTRIBUTE_VENDOR_DEFINED + 8)) - -}; - - - - -enum { - CSSM_FEE_PRIME_TYPE_DEFAULT = 0, - CSSM_FEE_PRIME_TYPE_MERSENNE, - CSSM_FEE_PRIME_TYPE_FEE, - CSSM_FEE_PRIME_TYPE_GENERAL -}; - - - - - - -enum { - CSSM_FEE_CURVE_TYPE_DEFAULT = 0, - CSSM_FEE_CURVE_TYPE_MONTGOMERY, - CSSM_FEE_CURVE_TYPE_WEIERSTRASS, - CSSM_FEE_CURVE_TYPE_ANSI_X9_62 -}; - - - - -enum { - CSSM_ASC_OPTIMIZE_DEFAULT = 0, - CSSM_ASC_OPTIMIZE_SIZE, - CSSM_ASC_OPTIMIZE_SECURITY, - CSSM_ASC_OPTIMIZE_TIME, - CSSM_ASC_OPTIMIZE_TIME_SIZE, - CSSM_ASC_OPTIMIZE_ASCII, -}; - - - - -enum { - - - - - CSSM_KEYATTR_PARTIAL = 0x00010000, - - - - - - CSSM_KEYATTR_PUBLIC_KEY_ENCRYPT = 0x00020000 -}; - - - - -typedef struct { - const char *string; - const CSSM_OID *oid; -} CSSM_APPLE_TP_NAME_OID; - - - - - - - -typedef struct { - CSSM_CSP_HANDLE cspHand; - CSSM_CL_HANDLE clHand; - uint32 serialNumber; - uint32 numSubjectNames; - CSSM_APPLE_TP_NAME_OID *subjectNames; - - - - - - - - uint32 numIssuerNames; - CSSM_APPLE_TP_NAME_OID *issuerNames; - - CSSM_X509_NAME_PTR issuerNameX509; - const CSSM_KEY *certPublicKey; - const CSSM_KEY *issuerPrivateKey; - - - - CSSM_ALGORITHMS signatureAlg; - CSSM_OID signatureOid; - uint32 notBefore; - uint32 notAfter; - uint32 numExtensions; - CE_DataAndType *extensions; - - - - - const char *challengeString; -} CSSM_APPLE_TP_CERT_REQUEST; -typedef struct { - uint32 Version; - - - - - - - - uint32 ServerNameLen; - const char *ServerName; - - - uint32 Flags; -} CSSM_APPLE_TP_SSL_OPTIONS; -typedef uint32 CSSM_APPLE_TP_CRL_OPT_FLAGS; -enum { - - CSSM_TP_ACTION_REQUIRE_CRL_PER_CERT = 0x00000001, - - CSSM_TP_ACTION_FETCH_CRL_FROM_NET = 0x00000002, - - - CSSM_TP_ACTION_CRL_SUFFICIENT = 0x00000004, - - CSSM_TP_ACTION_REQUIRE_CRL_IF_PRESENT = 0x00000008 -}; - -typedef struct { - uint32 Version; - CSSM_APPLE_TP_CRL_OPT_FLAGS CrlFlags; - - - - - - - - CSSM_DL_DB_HANDLE_PTR crlStore; -} CSSM_APPLE_TP_CRL_OPTIONS; -typedef struct { - uint32 Version; - - - - - - CE_KeyUsage IntendedUsage; - uint32 SenderEmailLen; - const char *SenderEmail; -} CSSM_APPLE_TP_SMIME_OPTIONS; - - - - - - - -typedef uint32 CSSM_APPLE_TP_ACTION_FLAGS; -enum { - CSSM_TP_ACTION_ALLOW_EXPIRED = 0x00000001, - CSSM_TP_ACTION_LEAF_IS_CA = 0x00000002, - CSSM_TP_ACTION_FETCH_CERT_FROM_NET = 0x00000004, - CSSM_TP_ACTION_ALLOW_EXPIRED_ROOT = 0x00000008, - CSSM_TP_ACTION_REQUIRE_REV_PER_CERT = 0x00000010, - - CSSM_TP_ACTION_TRUST_SETTINGS = 0x00000020, - - CSSM_TP_ACTION_IMPLICIT_ANCHORS = 0x00000040 - -}; - - -typedef struct { - uint32 Version; - CSSM_APPLE_TP_ACTION_FLAGS ActionFlags; -} CSSM_APPLE_TP_ACTION_DATA; -typedef uint32 CSSM_TP_APPLE_CERT_STATUS; -enum -{ - CSSM_CERT_STATUS_EXPIRED = 0x00000001, - CSSM_CERT_STATUS_NOT_VALID_YET = 0x00000002, - CSSM_CERT_STATUS_IS_IN_INPUT_CERTS = 0x00000004, - CSSM_CERT_STATUS_IS_IN_ANCHORS = 0x00000008, - CSSM_CERT_STATUS_IS_ROOT = 0x00000010, - CSSM_CERT_STATUS_IS_FROM_NET = 0x00000020, - - CSSM_CERT_STATUS_TRUST_SETTINGS_FOUND_USER = 0x00000040, - - CSSM_CERT_STATUS_TRUST_SETTINGS_FOUND_ADMIN = 0x00000080, - - CSSM_CERT_STATUS_TRUST_SETTINGS_FOUND_SYSTEM = 0x00000100, - - CSSM_CERT_STATUS_TRUST_SETTINGS_TRUST = 0x00000200, - - CSSM_CERT_STATUS_TRUST_SETTINGS_DENY = 0x00000400, - - CSSM_CERT_STATUS_TRUST_SETTINGS_IGNORED_ERROR = 0x00000800 -}; - -typedef struct { - CSSM_TP_APPLE_CERT_STATUS StatusBits; - uint32 NumStatusCodes; - CSSM_RETURN *StatusCodes; - - - uint32 Index; - - - CSSM_DL_DB_HANDLE DlDbHandle; - CSSM_DB_UNIQUE_RECORD_PTR UniqueRecord; - -} CSSM_TP_APPLE_EVIDENCE_INFO; - - - - - - -typedef struct -{ - uint32 Version; -} CSSM_TP_APPLE_EVIDENCE_HEADER; -enum -{ - CSSM_EVIDENCE_FORM_APPLE_HEADER = 0x80000000 + 0, - CSSM_EVIDENCE_FORM_APPLE_CERTGROUP = 0x80000000 + 1, - CSSM_EVIDENCE_FORM_APPLE_CERT_INFO = 0x80000000 + 2 -}; - - -enum { - - - - - - CSSM_APPLEX509CL_OBTAIN_CSR, - - - - - - - - CSSM_APPLEX509CL_VERIFY_CSR -}; - - - - - - -typedef struct { - CSSM_X509_NAME_PTR subjectNameX509; - - - - CSSM_ALGORITHMS signatureAlg; - CSSM_OID signatureOid; - - CSSM_CSP_HANDLE cspHand; - const CSSM_KEY *subjectPublicKey; - const CSSM_KEY *subjectPrivateKey; - - - - - const char *challengeString; -} CSSM_APPLE_CL_CSR_REQUEST; -void cssmPerror(const char *how, CSSM_RETURN error); - - -bool cssmOidToAlg(const CSSM_OID *oid, CSSM_ALGORITHMS *alg); -const CSSM_OID *cssmAlgToOid(CSSM_ALGORITHMS algId); -} - -extern "C" { - - - - -typedef uint32 CSSM_MANAGER_EVENT_TYPES; - - - -typedef struct cssm_manager_event_notification { - CSSM_SERVICE_MASK DestinationModuleManagerType; - CSSM_SERVICE_MASK SourceModuleManagerType; - CSSM_MANAGER_EVENT_TYPES Event; - uint32 EventId; - CSSM_DATA EventData; -} CSSM_MANAGER_EVENT_NOTIFICATION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_MANAGER_EVENT_NOTIFICATION_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} -extern "C" { -CSSM_RETURN -CSSM_Init (const CSSM_VERSION *Version, - CSSM_PRIVILEGE_SCOPE Scope, - const CSSM_GUID *CallerGuid, - CSSM_KEY_HIERARCHY KeyHierarchy, - CSSM_PVC_MODE *PvcPolicy, - const void *Reserved) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_Terminate (void) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_ModuleLoad (const CSSM_GUID *ModuleGuid, - CSSM_KEY_HIERARCHY KeyHierarchy, - CSSM_API_ModuleEventHandler AppNotifyCallback, - void *AppNotifyCallbackCtx) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_ModuleUnload (const CSSM_GUID *ModuleGuid, - CSSM_API_ModuleEventHandler AppNotifyCallback, - void *AppNotifyCallbackCtx) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_Introduce (const CSSM_GUID *ModuleID, - CSSM_KEY_HIERARCHY KeyHierarchy) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_Unintroduce (const CSSM_GUID *ModuleID) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_ModuleAttach (const CSSM_GUID *ModuleGuid, - const CSSM_VERSION *Version, - const CSSM_API_MEMORY_FUNCS *MemoryFuncs, - uint32 SubserviceID, - CSSM_SERVICE_TYPE SubServiceType, - CSSM_ATTACH_FLAGS AttachFlags, - CSSM_KEY_HIERARCHY KeyHierarchy, - CSSM_FUNC_NAME_ADDR *FunctionTable, - uint32 NumFunctionTable, - const void *Reserved, - CSSM_MODULE_HANDLE_PTR NewModuleHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_ModuleDetach (CSSM_MODULE_HANDLE ModuleHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_SetPrivilege (CSSM_PRIVILEGE Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_GetPrivilege (CSSM_PRIVILEGE *Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GetModuleGUIDFromHandle (CSSM_MODULE_HANDLE ModuleHandle, - CSSM_GUID_PTR ModuleGUID) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GetSubserviceUIDFromHandle (CSSM_MODULE_HANDLE ModuleHandle, - CSSM_SUBSERVICE_UID_PTR SubserviceUID) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_ListAttachedModuleManagers (uint32 *NumberOfModuleManagers, - CSSM_GUID_PTR ModuleManagerGuids) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GetAPIMemoryFunctions (CSSM_MODULE_HANDLE AddInHandle, - CSSM_API_MEMORY_FUNCS_PTR AppMemoryFuncs) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_CSP_CreateSignatureContext (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS AlgorithmID, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_KEY *Key, - CSSM_CC_HANDLE *NewContextHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_CreateSymmetricContext (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS AlgorithmID, - CSSM_ENCRYPT_MODE Mode, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_KEY *Key, - const CSSM_DATA *InitVector, - CSSM_PADDING Padding, - void *Reserved, - CSSM_CC_HANDLE *NewContextHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_CreateDigestContext (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS AlgorithmID, - CSSM_CC_HANDLE *NewContextHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_CreateMacContext (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS AlgorithmID, - const CSSM_KEY *Key, - CSSM_CC_HANDLE *NewContextHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_CreateRandomGenContext (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS AlgorithmID, - const CSSM_CRYPTO_DATA *Seed, - CSSM_SIZE Length, - CSSM_CC_HANDLE *NewContextHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - -CSSM_RETURN -CSSM_CSP_CreateAsymmetricContext (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS AlgorithmID, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_KEY *Key, - CSSM_PADDING Padding, - CSSM_CC_HANDLE *NewContextHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_CreateDeriveKeyContext (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS AlgorithmID, - CSSM_KEY_TYPE DeriveKeyType, - uint32 DeriveKeyLengthInBits, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_KEY *BaseKey, - uint32 IterationCount, - const CSSM_DATA *Salt, - const CSSM_CRYPTO_DATA *Seed, - CSSM_CC_HANDLE *NewContextHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_CreateKeyGenContext (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS AlgorithmID, - uint32 KeySizeInBits, - const CSSM_CRYPTO_DATA *Seed, - const CSSM_DATA *Salt, - const CSSM_DATE *StartDate, - const CSSM_DATE *EndDate, - const CSSM_DATA *Params, - CSSM_CC_HANDLE *NewContextHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_CreatePassThroughContext (CSSM_CSP_HANDLE CSPHandle, - const CSSM_KEY *Key, - CSSM_CC_HANDLE *NewContextHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GetContext (CSSM_CC_HANDLE CCHandle, - CSSM_CONTEXT_PTR *Context) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_FreeContext (CSSM_CONTEXT_PTR Context) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_SetContext (CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DeleteContext (CSSM_CC_HANDLE CCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GetContextAttribute (const CSSM_CONTEXT *Context, - uint32 AttributeType, - CSSM_CONTEXT_ATTRIBUTE_PTR *ContextAttribute) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_UpdateContextAttributes (CSSM_CC_HANDLE CCHandle, - uint32 NumberOfAttributes, - const CSSM_CONTEXT_ATTRIBUTE *ContextAttributes) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DeleteContextAttributes (CSSM_CC_HANDLE CCHandle, - uint32 NumberOfAttributes, - const CSSM_CONTEXT_ATTRIBUTE *ContextAttributes) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_CSP_Login (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_DATA *LoginName, - const void *Reserved) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_Logout (CSSM_CSP_HANDLE CSPHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_GetLoginAcl (CSSM_CSP_HANDLE CSPHandle, - const CSSM_STRING *SelectionTag, - uint32 *NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR *AclInfos) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_ChangeLoginAcl (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_EDIT *AclEdit) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_GetKeyAcl (CSSM_CSP_HANDLE CSPHandle, - const CSSM_KEY *Key, - const CSSM_STRING *SelectionTag, - uint32 *NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR *AclInfos) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_ChangeKeyAcl (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_EDIT *AclEdit, - const CSSM_KEY *Key) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_GetKeyOwner (CSSM_CSP_HANDLE CSPHandle, - const CSSM_KEY *Key, - CSSM_ACL_OWNER_PROTOTYPE_PTR Owner) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_ChangeKeyOwner (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_KEY *Key, - const CSSM_ACL_OWNER_PROTOTYPE *NewOwner) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_GetLoginOwner (CSSM_CSP_HANDLE CSPHandle, - CSSM_ACL_OWNER_PROTOTYPE_PTR Owner) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CSP_ChangeLoginOwner (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_OWNER_PROTOTYPE *NewOwner) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_SignData (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - CSSM_ALGORITHMS DigestAlgorithm, - CSSM_DATA_PTR Signature) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_SignDataInit (CSSM_CC_HANDLE CCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_SignDataUpdate (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_SignDataFinal (CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR Signature) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_VerifyData (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - CSSM_ALGORITHMS DigestAlgorithm, - const CSSM_DATA *Signature) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_VerifyDataInit (CSSM_CC_HANDLE CCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_VerifyDataUpdate (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_VerifyDataFinal (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *Signature) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DigestData (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - CSSM_DATA_PTR Digest) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DigestDataInit (CSSM_CC_HANDLE CCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DigestDataUpdate (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DigestDataClone (CSSM_CC_HANDLE CCHandle, - CSSM_CC_HANDLE *ClonednewCCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DigestDataFinal (CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR Digest) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GenerateMac (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - CSSM_DATA_PTR Mac) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GenerateMacInit (CSSM_CC_HANDLE CCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GenerateMacUpdate (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GenerateMacFinal (CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR Mac) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_VerifyMac (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - const CSSM_DATA *Mac) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_VerifyMacInit (CSSM_CC_HANDLE CCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_VerifyMacUpdate (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_VerifyMacFinal (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *Mac) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_QuerySize (CSSM_CC_HANDLE CCHandle, - CSSM_BOOL Encrypt, - uint32 QuerySizeCount, - CSSM_QUERY_SIZE_DATA_PTR DataBlockSizes) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - -CSSM_RETURN -CSSM_EncryptData (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *ClearBufs, - uint32 ClearBufCount, - CSSM_DATA_PTR CipherBufs, - uint32 CipherBufCount, - CSSM_SIZE *bytesEncrypted, - CSSM_DATA_PTR RemData) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_EncryptDataP (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *ClearBufs, - uint32 ClearBufCount, - CSSM_DATA_PTR CipherBufs, - uint32 CipherBufCount, - CSSM_SIZE *bytesEncrypted, - CSSM_DATA_PTR RemData, - CSSM_PRIVILEGE Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_EncryptDataInit (CSSM_CC_HANDLE CCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_EncryptDataInitP (CSSM_CC_HANDLE CCHandle, - CSSM_PRIVILEGE Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_EncryptDataUpdate (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *ClearBufs, - uint32 ClearBufCount, - CSSM_DATA_PTR CipherBufs, - uint32 CipherBufCount, - CSSM_SIZE *bytesEncrypted) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_EncryptDataFinal (CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR RemData) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DecryptData (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CipherBufs, - uint32 CipherBufCount, - CSSM_DATA_PTR ClearBufs, - uint32 ClearBufCount, - CSSM_SIZE *bytesDecrypted, - CSSM_DATA_PTR RemData) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DecryptDataP (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CipherBufs, - uint32 CipherBufCount, - CSSM_DATA_PTR ClearBufs, - uint32 ClearBufCount, - CSSM_SIZE *bytesDecrypted, - CSSM_DATA_PTR RemData, - CSSM_PRIVILEGE Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DecryptDataInit (CSSM_CC_HANDLE CCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DecryptDataInitP (CSSM_CC_HANDLE CCHandle, - CSSM_PRIVILEGE Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DecryptDataUpdate (CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CipherBufs, - uint32 CipherBufCount, - CSSM_DATA_PTR ClearBufs, - uint32 ClearBufCount, - CSSM_SIZE *bytesDecrypted) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DecryptDataFinal (CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR RemData) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_QueryKeySizeInBits (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_KEY *Key, - CSSM_KEY_SIZE_PTR KeySize) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_GenerateKey (CSSM_CC_HANDLE CCHandle, - uint32 KeyUsage, - uint32 KeyAttr, - const CSSM_DATA *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR Key) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_GenerateKeyP (CSSM_CC_HANDLE CCHandle, - uint32 KeyUsage, - uint32 KeyAttr, - const CSSM_DATA *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR Key, - CSSM_PRIVILEGE Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_GenerateKeyPair (CSSM_CC_HANDLE CCHandle, - uint32 PublicKeyUsage, - uint32 PublicKeyAttr, - const CSSM_DATA *PublicKeyLabel, - CSSM_KEY_PTR PublicKey, - uint32 PrivateKeyUsage, - uint32 PrivateKeyAttr, - const CSSM_DATA *PrivateKeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR PrivateKey) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_GenerateKeyPairP (CSSM_CC_HANDLE CCHandle, - uint32 PublicKeyUsage, - uint32 PublicKeyAttr, - const CSSM_DATA *PublicKeyLabel, - CSSM_KEY_PTR PublicKey, - uint32 PrivateKeyUsage, - uint32 PrivateKeyAttr, - const CSSM_DATA *PrivateKeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR PrivateKey, - CSSM_PRIVILEGE Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_GenerateRandom (CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR RandomNumber) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CSP_ObtainPrivateKeyFromPublicKey (CSSM_CSP_HANDLE CSPHandle, - const CSSM_KEY *PublicKey, - CSSM_KEY_PTR PrivateKey) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_WrapKey (CSSM_CC_HANDLE CCHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_KEY *Key, - const CSSM_DATA *DescriptiveData, - CSSM_WRAP_KEY_PTR WrappedKey) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_UnwrapKey (CSSM_CC_HANDLE CCHandle, - const CSSM_KEY *PublicKey, - const CSSM_WRAP_KEY *WrappedKey, - uint32 KeyUsage, - uint32 KeyAttr, - const CSSM_DATA *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR UnwrappedKey, - CSSM_DATA_PTR DescriptiveData) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_WrapKeyP (CSSM_CC_HANDLE CCHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_KEY *Key, - const CSSM_DATA *DescriptiveData, - CSSM_WRAP_KEY_PTR WrappedKey, - CSSM_PRIVILEGE Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_UnwrapKeyP (CSSM_CC_HANDLE CCHandle, - const CSSM_KEY *PublicKey, - const CSSM_WRAP_KEY *WrappedKey, - uint32 KeyUsage, - uint32 KeyAttr, - const CSSM_DATA *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR UnwrappedKey, - CSSM_DATA_PTR DescriptiveData, - CSSM_PRIVILEGE Privilege) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_DeriveKey (CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR Param, - uint32 KeyUsage, - uint32 KeyAttr, - const CSSM_DATA *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR DerivedKey) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - -CSSM_RETURN -CSSM_FreeKey (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - CSSM_KEY_PTR KeyPtr, - CSSM_BOOL Delete) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_GenerateAlgorithmParams (CSSM_CC_HANDLE CCHandle, - uint32 ParamBits, - CSSM_DATA_PTR Param) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_CSP_GetOperationalStatistics (CSSM_CSP_HANDLE CSPHandle, - CSSM_CSP_OPERATIONAL_STATISTICS *Statistics) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - -CSSM_RETURN -CSSM_GetTimeValue (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS TimeAlgorithm, - CSSM_DATA *TimeData) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_RetrieveUniqueId (CSSM_CSP_HANDLE CSPHandle, - CSSM_DATA_PTR UniqueID) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_RetrieveCounter (CSSM_CSP_HANDLE CSPHandle, - CSSM_DATA_PTR Counter) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_VerifyDevice (CSSM_CSP_HANDLE CSPHandle, - const CSSM_DATA *DeviceCert) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_CSP_PassThrough (CSSM_CC_HANDLE CCHandle, - uint32 PassThroughId, - const void *InData, - void **OutData) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_TP_SubmitCredRequest (CSSM_TP_HANDLE TPHandle, - const CSSM_TP_AUTHORITY_ID *PreferredAuthority, - CSSM_TP_AUTHORITY_REQUEST_TYPE RequestType, - const CSSM_TP_REQUEST_SET *RequestInput, - const CSSM_TP_CALLERAUTH_CONTEXT *CallerAuthContext, - sint32 *EstimatedTime, - CSSM_DATA_PTR ReferenceIdentifier) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_RetrieveCredResult (CSSM_TP_HANDLE TPHandle, - const CSSM_DATA *ReferenceIdentifier, - const CSSM_TP_CALLERAUTH_CONTEXT *CallerAuthCredentials, - sint32 *EstimatedTime, - CSSM_BOOL *ConfirmationRequired, - CSSM_TP_RESULT_SET_PTR *RetrieveOutput) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_ConfirmCredResult (CSSM_TP_HANDLE TPHandle, - const CSSM_DATA *ReferenceIdentifier, - const CSSM_TP_CALLERAUTH_CONTEXT *CallerAuthCredentials, - const CSSM_TP_CONFIRM_RESPONSE *Responses, - const CSSM_TP_AUTHORITY_ID *PreferredAuthority) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_ReceiveConfirmation (CSSM_TP_HANDLE TPHandle, - const CSSM_DATA *ReferenceIdentifier, - CSSM_TP_CONFIRM_RESPONSE_PTR *Responses, - sint32 *ElapsedTime) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertReclaimKey (CSSM_TP_HANDLE TPHandle, - const CSSM_CERTGROUP *CertGroup, - uint32 CertIndex, - CSSM_LONG_HANDLE KeyCacheHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertReclaimAbort (CSSM_TP_HANDLE TPHandle, - CSSM_LONG_HANDLE KeyCacheHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_FormRequest (CSSM_TP_HANDLE TPHandle, - const CSSM_TP_AUTHORITY_ID *PreferredAuthority, - CSSM_TP_FORM_TYPE FormType, - CSSM_DATA_PTR BlankForm) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_FormSubmit (CSSM_TP_HANDLE TPHandle, - CSSM_TP_FORM_TYPE FormType, - const CSSM_DATA *Form, - const CSSM_TP_AUTHORITY_ID *ClearanceAuthority, - const CSSM_TP_AUTHORITY_ID *RepresentedAuthority, - CSSM_ACCESS_CREDENTIALS_PTR Credentials) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertGroupVerify (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_CERTGROUP *CertGroupToBeVerified, - const CSSM_TP_VERIFY_CONTEXT *VerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR VerifyContextResult) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertCreateTemplate (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CertFields, - CSSM_DATA_PTR CertTemplate) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertGetAllTemplateFields (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *CertTemplate, - uint32 *NumberOfFields, - CSSM_FIELD_PTR *CertFields) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertSign (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CertTemplateToBeSigned, - const CSSM_CERTGROUP *SignerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *SignerVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR SignerVerifyResult, - CSSM_DATA_PTR SignedCert) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CrlVerify (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_ENCODED_CRL *CrlToBeVerified, - const CSSM_CERTGROUP *SignerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *VerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR RevokerVerifyResult) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CrlCreateTemplate (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CrlFields, - CSSM_DATA_PTR NewCrlTemplate) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertRevoke (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_DATA *OldCrlTemplate, - const CSSM_CERTGROUP *CertGroupToBeRevoked, - const CSSM_CERTGROUP *RevokerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *RevokerVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR RevokerVerifyResult, - CSSM_TP_CERTCHANGE_REASON Reason, - CSSM_DATA_PTR NewCrlTemplate) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertRemoveFromCrlTemplate (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_DATA *OldCrlTemplate, - const CSSM_CERTGROUP *CertGroupToBeRemoved, - const CSSM_CERTGROUP *RevokerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *RevokerVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR RevokerVerifyResult, - CSSM_DATA_PTR NewCrlTemplate) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CrlSign (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_ENCODED_CRL *CrlToBeSigned, - const CSSM_CERTGROUP *SignerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *SignerVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR SignerVerifyResult, - CSSM_DATA_PTR SignedCrl) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_ApplyCrlToDb (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_ENCODED_CRL *CrlToBeApplied, - const CSSM_CERTGROUP *SignerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *ApplyCrlVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR ApplyCrlVerifyResult) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertGroupConstruct (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_DL_DB_LIST *DBList, - const void *ConstructParams, - const CSSM_CERTGROUP *CertGroupFrag, - CSSM_CERTGROUP_PTR *CertGroup) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertGroupPrune (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - const CSSM_DL_DB_LIST *DBList, - const CSSM_CERTGROUP *OrderedCertGroup, - CSSM_CERTGROUP_PTR *PrunedCertGroup) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_CertGroupToTupleGroup (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - const CSSM_CERTGROUP *CertGroup, - CSSM_TUPLEGROUP_PTR *TupleGroup) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_TP_TupleGroupToCertGroup (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - const CSSM_TUPLEGROUP *TupleGroup, - CSSM_CERTGROUP_PTR *CertTemplates) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_TP_PassThrough (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DL_DB_LIST *DBList, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_AC_AuthCompute (CSSM_AC_HANDLE ACHandle, - const CSSM_TUPLEGROUP *BaseAuthorizations, - const CSSM_TUPLEGROUP *Credentials, - uint32 NumberOfRequestors, - const CSSM_LIST *Requestors, - const CSSM_LIST *RequestedAuthorizationPeriod, - const CSSM_LIST *RequestedAuthorization, - CSSM_TUPLEGROUP_PTR AuthorizationResult) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_AC_PassThrough (CSSM_AC_HANDLE ACHandle, - CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DL_DB_LIST *DBList, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_CL_CertCreateTemplate (CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CertFields, - CSSM_DATA_PTR CertTemplate) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertGetAllTemplateFields (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *CertTemplate, - uint32 *NumberOfFields, - CSSM_FIELD_PTR *CertFields) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertSign (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CertTemplate, - const CSSM_FIELD *SignScope, - uint32 ScopeSize, - CSSM_DATA_PTR SignedCert) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertVerify (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CertToBeVerified, - const CSSM_DATA *SignerCert, - const CSSM_FIELD *VerifyScope, - uint32 ScopeSize) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertVerifyWithKey (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CertToBeVerified) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertGetFirstFieldValue (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - const CSSM_OID *CertField, - CSSM_HANDLE_PTR ResultsHandle, - uint32 *NumberOfMatchedFields, - CSSM_DATA_PTR *Value) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertGetNextFieldValue (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DATA_PTR *Value) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CertAbortQuery (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertGetKeyInfo (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - CSSM_KEY_PTR *Key) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertGetAllFields (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - uint32 *NumberOfFields, - CSSM_FIELD_PTR *CertFields) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_FreeFields (CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - CSSM_FIELD_PTR *Fields) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_FreeFieldValue (CSSM_CL_HANDLE CLHandle, - const CSSM_OID *CertOrCrlOid, - CSSM_DATA_PTR Value) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CertCache (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - CSSM_HANDLE_PTR CertHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertGetFirstCachedFieldValue (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CertHandle, - const CSSM_OID *CertField, - CSSM_HANDLE_PTR ResultsHandle, - uint32 *NumberOfMatchedFields, - CSSM_DATA_PTR *Value) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CertGetNextCachedFieldValue (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DATA_PTR *Value) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CertAbortCache (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CertHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CertGroupToSignedBundle (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CERTGROUP *CertGroupToBundle, - const CSSM_CERT_BUNDLE_HEADER *BundleInfo, - CSSM_DATA_PTR SignedBundle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CertGroupFromVerifiedBundle (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CERT_BUNDLE *CertBundle, - const CSSM_DATA *SignerCert, - CSSM_CERTGROUP_PTR *CertGroup) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CertDescribeFormat (CSSM_CL_HANDLE CLHandle, - uint32 *NumberOfFields, - CSSM_OID_PTR *OidList) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CrlCreateTemplate (CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CrlTemplate, - CSSM_DATA_PTR NewCrl) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CrlSetFields (CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CrlTemplate, - const CSSM_DATA *OldCrl, - CSSM_DATA_PTR ModifiedCrl) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlAddCert (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *Cert, - uint32 NumberOfFields, - const CSSM_FIELD *CrlEntryFields, - const CSSM_DATA *OldCrl, - CSSM_DATA_PTR NewCrl) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlRemoveCert (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - const CSSM_DATA *OldCrl, - CSSM_DATA_PTR NewCrl) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlSign (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *UnsignedCrl, - const CSSM_FIELD *SignScope, - uint32 ScopeSize, - CSSM_DATA_PTR SignedCrl) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlVerify (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CrlToBeVerified, - const CSSM_DATA *SignerCert, - const CSSM_FIELD *VerifyScope, - uint32 ScopeSize) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlVerifyWithKey (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CrlToBeVerified) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_IsCertInCrl (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - const CSSM_DATA *Crl, - CSSM_BOOL *CertFound) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlGetFirstFieldValue (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Crl, - const CSSM_OID *CrlField, - CSSM_HANDLE_PTR ResultsHandle, - uint32 *NumberOfMatchedFields, - CSSM_DATA_PTR *Value) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlGetNextFieldValue (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DATA_PTR *Value) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CrlAbortQuery (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlGetAllFields (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Crl, - uint32 *NumberOfCrlFields, - CSSM_FIELD_PTR *CrlFields) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CrlCache (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Crl, - CSSM_HANDLE_PTR CrlHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_IsCertInCachedCrl (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - CSSM_HANDLE CrlHandle, - CSSM_BOOL *CertFound, - CSSM_DATA_PTR CrlRecordIndex) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlGetFirstCachedFieldValue (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CrlHandle, - const CSSM_DATA *CrlRecordIndex, - const CSSM_OID *CrlField, - CSSM_HANDLE_PTR ResultsHandle, - uint32 *NumberOfMatchedFields, - CSSM_DATA_PTR *Value) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlGetNextCachedFieldValue (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DATA_PTR *Value) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_CL_CrlGetAllCachedRecordFields (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CrlHandle, - const CSSM_DATA *CrlRecordIndex, - uint32 *NumberOfFields, - CSSM_FIELD_PTR *CrlFields) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CrlAbortCache (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CrlHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_CrlDescribeFormat (CSSM_CL_HANDLE CLHandle, - uint32 *NumberOfFields, - CSSM_OID_PTR *OidList) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_CL_PassThrough (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -CSSM_RETURN -CSSM_DL_DbOpen (CSSM_DL_HANDLE DLHandle, - const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - CSSM_DB_ACCESS_TYPE AccessRequest, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const void *OpenParameters, - CSSM_DB_HANDLE *DbHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_DL_DbClose (CSSM_DL_DB_HANDLE DLDBHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_DL_DbCreate (CSSM_DL_HANDLE DLHandle, - const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - const CSSM_DBINFO *DBInfo, - CSSM_DB_ACCESS_TYPE AccessRequest, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - const void *OpenParameters, - CSSM_DB_HANDLE *DbHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_DL_DbDelete (CSSM_DL_HANDLE DLHandle, - const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - const CSSM_ACCESS_CREDENTIALS *AccessCred) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_CreateRelation (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_RECORDTYPE RelationID, - const char *RelationName, - uint32 NumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *pAttributeInfo, - uint32 NumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO *pIndexInfo) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_DestroyRelation (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_RECORDTYPE RelationID) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_DL_Authenticate (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_ACCESS_TYPE AccessRequest, - const CSSM_ACCESS_CREDENTIALS *AccessCred) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_GetDbAcl (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_STRING *SelectionTag, - uint32 *NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR *AclInfos) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_ChangeDbAcl (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_EDIT *AclEdit) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_GetDbOwner (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_ACL_OWNER_PROTOTYPE_PTR Owner) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_ChangeDbOwner (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_OWNER_PROTOTYPE *NewOwner) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_GetDbNames (CSSM_DL_HANDLE DLHandle, - CSSM_NAME_LIST_PTR *NameList) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_GetDbNameFromHandle (CSSM_DL_DB_HANDLE DLDBHandle, - char **DbName) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_FreeNameList (CSSM_DL_HANDLE DLHandle, - CSSM_NAME_LIST_PTR NameList) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_DataInsert (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_RECORDTYPE RecordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *Attributes, - const CSSM_DATA *Data, - CSSM_DB_UNIQUE_RECORD_PTR *UniqueId) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_DL_DataDelete (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_DB_UNIQUE_RECORD *UniqueRecordIdentifier) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - -CSSM_RETURN -CSSM_DL_DataModify (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_RECORDTYPE RecordType, - CSSM_DB_UNIQUE_RECORD_PTR UniqueRecordIdentifier, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *AttributesToBeModified, - const CSSM_DATA *DataToBeModified, - CSSM_DB_MODIFY_MODE ModifyMode) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - -CSSM_RETURN -CSSM_DL_DataGetFirst (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_QUERY *Query, - CSSM_HANDLE_PTR ResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CSSM_DATA_PTR Data, - CSSM_DB_UNIQUE_RECORD_PTR *UniqueId) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - -CSSM_RETURN -CSSM_DL_DataGetNext (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CSSM_DATA_PTR Data, - CSSM_DB_UNIQUE_RECORD_PTR *UniqueId) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_DataAbortQuery (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_HANDLE ResultsHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_DataGetFromUniqueRecordId (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_DB_UNIQUE_RECORD *UniqueRecord, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CSSM_DATA_PTR Data) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_FreeUniqueRecord (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_UNIQUE_RECORD_PTR UniqueRecord) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -CSSM_RETURN -CSSM_DL_PassThrough (CSSM_DL_DB_HANDLE DLDBHandle, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} -extern "C" { - - -typedef struct cssm_spi_ac_funcs { - CSSM_RETURN ( *AuthCompute) - (CSSM_AC_HANDLE ACHandle, - const CSSM_TUPLEGROUP *BaseAuthorizations, - const CSSM_TUPLEGROUP *Credentials, - uint32 NumberOfRequestors, - const CSSM_LIST *Requestors, - const CSSM_LIST *RequestedAuthorizationPeriod, - const CSSM_LIST *RequestedAuthorization, - CSSM_TUPLEGROUP_PTR AuthorizationResult); - CSSM_RETURN ( *PassThrough) - (CSSM_AC_HANDLE ACHandle, - CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DL_DB_LIST *DBList, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams); -} CSSM_SPI_AC_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SPI_AC_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} - -extern "C" { - - -typedef struct cssm_spi_cl_funcs { - CSSM_RETURN ( *CertCreateTemplate) - (CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CertFields, - CSSM_DATA_PTR CertTemplate); - CSSM_RETURN ( *CertGetAllTemplateFields) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *CertTemplate, - uint32 *NumberOfFields, - CSSM_FIELD_PTR *CertFields); - CSSM_RETURN ( *CertSign) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CertTemplate, - const CSSM_FIELD *SignScope, - uint32 ScopeSize, - CSSM_DATA_PTR SignedCert); - CSSM_RETURN ( *CertVerify) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CertToBeVerified, - const CSSM_DATA *SignerCert, - const CSSM_FIELD *VerifyScope, - uint32 ScopeSize); - CSSM_RETURN ( *CertVerifyWithKey) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CertToBeVerified); - CSSM_RETURN ( *CertGetFirstFieldValue) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - const CSSM_OID *CertField, - CSSM_HANDLE_PTR ResultsHandle, - uint32 *NumberOfMatchedFields, - CSSM_DATA_PTR *Value); - CSSM_RETURN ( *CertGetNextFieldValue) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DATA_PTR *Value); - CSSM_RETURN ( *CertAbortQuery) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle); - CSSM_RETURN ( *CertGetKeyInfo) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - CSSM_KEY_PTR *Key); - CSSM_RETURN ( *CertGetAllFields) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - uint32 *NumberOfFields, - CSSM_FIELD_PTR *CertFields); - CSSM_RETURN ( *FreeFields) - (CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - CSSM_FIELD_PTR *FieldArray); - CSSM_RETURN ( *FreeFieldValue) - (CSSM_CL_HANDLE CLHandle, - const CSSM_OID *CertOrCrlOid, - CSSM_DATA_PTR Value); - CSSM_RETURN ( *CertCache) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - CSSM_HANDLE_PTR CertHandle); - CSSM_RETURN ( *CertGetFirstCachedFieldValue) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CertHandle, - const CSSM_OID *CertField, - CSSM_HANDLE_PTR ResultsHandle, - uint32 *NumberOfMatchedFields, - CSSM_DATA_PTR *Value); - CSSM_RETURN ( *CertGetNextCachedFieldValue) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DATA_PTR *Value); - CSSM_RETURN ( *CertAbortCache) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CertHandle); - CSSM_RETURN ( *CertGroupToSignedBundle) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CERTGROUP *CertGroupToBundle, - const CSSM_CERT_BUNDLE_HEADER *BundleInfo, - CSSM_DATA_PTR SignedBundle); - CSSM_RETURN ( *CertGroupFromVerifiedBundle) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CERT_BUNDLE *CertBundle, - const CSSM_DATA *SignerCert, - CSSM_CERTGROUP_PTR *CertGroup); - CSSM_RETURN ( *CertDescribeFormat) - (CSSM_CL_HANDLE CLHandle, - uint32 *NumberOfFields, - CSSM_OID_PTR *OidList); - CSSM_RETURN ( *CrlCreateTemplate) - (CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CrlTemplate, - CSSM_DATA_PTR NewCrl); - CSSM_RETURN ( *CrlSetFields) - (CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CrlTemplate, - const CSSM_DATA *OldCrl, - CSSM_DATA_PTR ModifiedCrl); - CSSM_RETURN ( *CrlAddCert) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *Cert, - uint32 NumberOfFields, - const CSSM_FIELD *CrlEntryFields, - const CSSM_DATA *OldCrl, - CSSM_DATA_PTR NewCrl); - CSSM_RETURN ( *CrlRemoveCert) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - const CSSM_DATA *OldCrl, - CSSM_DATA_PTR NewCrl); - CSSM_RETURN ( *CrlSign) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *UnsignedCrl, - const CSSM_FIELD *SignScope, - uint32 ScopeSize, - CSSM_DATA_PTR SignedCrl); - CSSM_RETURN ( *CrlVerify) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CrlToBeVerified, - const CSSM_DATA *SignerCert, - const CSSM_FIELD *VerifyScope, - uint32 ScopeSize); - CSSM_RETURN ( *CrlVerifyWithKey) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CrlToBeVerified); - CSSM_RETURN ( *IsCertInCrl) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - const CSSM_DATA *Crl, - CSSM_BOOL *CertFound); - CSSM_RETURN ( *CrlGetFirstFieldValue) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Crl, - const CSSM_OID *CrlField, - CSSM_HANDLE_PTR ResultsHandle, - uint32 *NumberOfMatchedFields, - CSSM_DATA_PTR *Value); - CSSM_RETURN ( *CrlGetNextFieldValue) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DATA_PTR *Value); - CSSM_RETURN ( *CrlAbortQuery) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle); - CSSM_RETURN ( *CrlGetAllFields) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Crl, - uint32 *NumberOfCrlFields, - CSSM_FIELD_PTR *CrlFields); - CSSM_RETURN ( *CrlCache) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Crl, - CSSM_HANDLE_PTR CrlHandle); - CSSM_RETURN ( *IsCertInCachedCrl) - (CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *Cert, - CSSM_HANDLE CrlHandle, - CSSM_BOOL *CertFound, - CSSM_DATA_PTR CrlRecordIndex); - CSSM_RETURN ( *CrlGetFirstCachedFieldValue) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CrlHandle, - const CSSM_DATA *CrlRecordIndex, - const CSSM_OID *CrlField, - CSSM_HANDLE_PTR ResultsHandle, - uint32 *NumberOfMatchedFields, - CSSM_DATA_PTR *Value); - CSSM_RETURN ( *CrlGetNextCachedFieldValue) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DATA_PTR *Value); - CSSM_RETURN ( *CrlGetAllCachedRecordFields) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CrlHandle, - const CSSM_DATA *CrlRecordIndex, - uint32 *NumberOfFields, - CSSM_FIELD_PTR *CrlFields); - CSSM_RETURN ( *CrlAbortCache) - (CSSM_CL_HANDLE CLHandle, - CSSM_HANDLE CrlHandle); - CSSM_RETURN ( *CrlDescribeFormat) - (CSSM_CL_HANDLE CLHandle, - uint32 *NumberOfFields, - CSSM_OID_PTR *OidList); - CSSM_RETURN ( *PassThrough) - (CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams); -} CSSM_SPI_CL_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SPI_CL_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} -extern "C" { - - -typedef CSSM_RETURN ( *CSSM_SPI_ModuleEventHandler) - (const CSSM_GUID *ModuleGuid, - void *CssmNotifyCallbackCtx, - uint32 SubserviceId, - CSSM_SERVICE_TYPE ServiceType, - CSSM_MODULE_EVENT EventType); - -typedef uint32 CSSM_CONTEXT_EVENT; -enum { - CSSM_CONTEXT_EVENT_CREATE = 1, - CSSM_CONTEXT_EVENT_DELETE = 2, - CSSM_CONTEXT_EVENT_UPDATE = 3 -}; - -typedef struct cssm_module_funcs { - CSSM_SERVICE_TYPE ServiceType; - uint32 NumberOfServiceFuncs; - const CSSM_PROC_ADDR *ServiceFuncs; -} CSSM_MODULE_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_MODULE_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef void *( *CSSM_UPCALLS_MALLOC) - (CSSM_HANDLE AddInHandle, - size_t size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef void ( *CSSM_UPCALLS_FREE) - (CSSM_HANDLE AddInHandle, - void *memblock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef void *( *CSSM_UPCALLS_REALLOC) - (CSSM_HANDLE AddInHandle, - void *memblock, - size_t size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef void *( *CSSM_UPCALLS_CALLOC) - (CSSM_HANDLE AddInHandle, - size_t num, - size_t size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_upcalls { - CSSM_UPCALLS_MALLOC malloc_func; - CSSM_UPCALLS_FREE free_func; - CSSM_UPCALLS_REALLOC realloc_func; - CSSM_UPCALLS_CALLOC calloc_func; - CSSM_RETURN ( *CcToHandle_func) - (CSSM_CC_HANDLE Cc, - CSSM_MODULE_HANDLE_PTR ModuleHandle); - CSSM_RETURN ( *GetModuleInfo_func) - (CSSM_MODULE_HANDLE Module, - CSSM_GUID_PTR Guid, - CSSM_VERSION_PTR Version, - uint32 *SubServiceId, - CSSM_SERVICE_TYPE *SubServiceType, - CSSM_ATTACH_FLAGS *AttachFlags, - CSSM_KEY_HIERARCHY *KeyHierarchy, - CSSM_API_MEMORY_FUNCS_PTR AttachedMemFuncs, - CSSM_FUNC_NAME_ADDR_PTR FunctionTable, - uint32 NumFunctions); -} CSSM_UPCALLS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_UPCALLS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_SPI_ModuleLoad (const CSSM_GUID *CssmGuid, - const CSSM_GUID *ModuleGuid, - CSSM_SPI_ModuleEventHandler CssmNotifyCallback, - void *CssmNotifyCallbackCtx) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_SPI_ModuleUnload (const CSSM_GUID *CssmGuid, - const CSSM_GUID *ModuleGuid, - CSSM_SPI_ModuleEventHandler CssmNotifyCallback, - void *CssmNotifyCallbackCtx) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_SPI_ModuleAttach (const CSSM_GUID *ModuleGuid, - const CSSM_VERSION *Version, - uint32 SubserviceID, - CSSM_SERVICE_TYPE SubServiceType, - CSSM_ATTACH_FLAGS AttachFlags, - CSSM_MODULE_HANDLE ModuleHandle, - CSSM_KEY_HIERARCHY KeyHierarchy, - const CSSM_GUID *CssmGuid, - const CSSM_GUID *ModuleManagerGuid, - const CSSM_GUID *CallerGuid, - const CSSM_UPCALLS *Upcalls, - CSSM_MODULE_FUNCS_PTR *FuncTbl) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_SPI_ModuleDetach (CSSM_MODULE_HANDLE ModuleHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - -} - - -extern "C" { - - -typedef struct cssm_spi_csp_funcs { - CSSM_RETURN ( *EventNotify) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CONTEXT_EVENT Event, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context); - CSSM_RETURN ( *QuerySize) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - CSSM_BOOL Encrypt, - uint32 QuerySizeCount, - CSSM_QUERY_SIZE_DATA_PTR DataBlock); - CSSM_RETURN ( *SignData) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - CSSM_ALGORITHMS DigestAlgorithm, - CSSM_DATA_PTR Signature); - CSSM_RETURN ( *SignDataInit) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context); - CSSM_RETURN ( *SignDataUpdate) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount); - CSSM_RETURN ( *SignDataFinal) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR Signature); - CSSM_RETURN ( *VerifyData) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - CSSM_ALGORITHMS DigestAlgorithm, - const CSSM_DATA *Signature); - CSSM_RETURN ( *VerifyDataInit) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context); - CSSM_RETURN ( *VerifyDataUpdate) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount); - CSSM_RETURN ( *VerifyDataFinal) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *Signature); - CSSM_RETURN ( *DigestData) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - CSSM_DATA_PTR Digest); - CSSM_RETURN ( *DigestDataInit) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context); - CSSM_RETURN ( *DigestDataUpdate) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount); - CSSM_RETURN ( *DigestDataClone) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - CSSM_CC_HANDLE ClonedCCHandle); - CSSM_RETURN ( *DigestDataFinal) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR Digest); - CSSM_RETURN ( *GenerateMac) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - CSSM_DATA_PTR Mac); - CSSM_RETURN ( *GenerateMacInit) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context); - CSSM_RETURN ( *GenerateMacUpdate) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount); - CSSM_RETURN ( *GenerateMacFinal) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR Mac); - CSSM_RETURN ( *VerifyMac) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_DATA *DataBufs, - uint32 DataBufCount, - const CSSM_DATA *Mac); - CSSM_RETURN ( *VerifyMacInit) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context); - CSSM_RETURN ( *VerifyMacUpdate) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *DataBufs, - uint32 DataBufCount); - CSSM_RETURN ( *VerifyMacFinal) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *Mac); - CSSM_RETURN ( *EncryptData) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_DATA *ClearBufs, - uint32 ClearBufCount, - CSSM_DATA_PTR CipherBufs, - uint32 CipherBufCount, - CSSM_SIZE *bytesEncrypted, - CSSM_DATA_PTR RemData, - CSSM_PRIVILEGE Privilege); - CSSM_RETURN ( *EncryptDataInit) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - CSSM_PRIVILEGE Privilege); - CSSM_RETURN ( *EncryptDataUpdate) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *ClearBufs, - uint32 ClearBufCount, - CSSM_DATA_PTR CipherBufs, - uint32 CipherBufCount, - CSSM_SIZE *bytesEncrypted); - CSSM_RETURN ( *EncryptDataFinal) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR RemData); - CSSM_RETURN ( *DecryptData) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_DATA *CipherBufs, - uint32 CipherBufCount, - CSSM_DATA_PTR ClearBufs, - uint32 ClearBufCount, - CSSM_SIZE *bytesDecrypted, - CSSM_DATA_PTR RemData, - CSSM_PRIVILEGE Privilege); - CSSM_RETURN ( *DecryptDataInit) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - CSSM_PRIVILEGE Privilege); - CSSM_RETURN ( *DecryptDataUpdate) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CipherBufs, - uint32 CipherBufCount, - CSSM_DATA_PTR ClearBufs, - uint32 ClearBufCount, - CSSM_SIZE *bytesDecrypted); - CSSM_RETURN ( *DecryptDataFinal) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - CSSM_DATA_PTR RemData); - CSSM_RETURN ( *QueryKeySizeInBits) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_KEY *Key, - CSSM_KEY_SIZE_PTR KeySize); - CSSM_RETURN ( *GenerateKey) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - uint32 KeyUsage, - uint32 KeyAttr, - const CSSM_DATA *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR Key, - CSSM_PRIVILEGE Privilege); - CSSM_RETURN ( *GenerateKeyPair) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - uint32 PublicKeyUsage, - uint32 PublicKeyAttr, - const CSSM_DATA *PublicKeyLabel, - CSSM_KEY_PTR PublicKey, - uint32 PrivateKeyUsage, - uint32 PrivateKeyAttr, - const CSSM_DATA *PrivateKeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR PrivateKey, - CSSM_PRIVILEGE Privilege); - CSSM_RETURN ( *GenerateRandom) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - CSSM_DATA_PTR RandomNumber); - CSSM_RETURN ( *GenerateAlgorithmParams) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - uint32 ParamBits, - CSSM_DATA_PTR Param, - uint32 *NumberOfUpdatedAttibutes, - CSSM_CONTEXT_ATTRIBUTE_PTR *UpdatedAttributes); - CSSM_RETURN ( *WrapKey) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_KEY *Key, - const CSSM_DATA *DescriptiveData, - CSSM_WRAP_KEY_PTR WrappedKey, - CSSM_PRIVILEGE Privilege); - CSSM_RETURN ( *UnwrapKey) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - const CSSM_KEY *PublicKey, - const CSSM_WRAP_KEY *WrappedKey, - uint32 KeyUsage, - uint32 KeyAttr, - const CSSM_DATA *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR UnwrappedKey, - CSSM_DATA_PTR DescriptiveData, - CSSM_PRIVILEGE Privilege); - CSSM_RETURN ( *DeriveKey) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - CSSM_DATA_PTR Param, - uint32 KeyUsage, - uint32 KeyAttr, - const CSSM_DATA *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CSSM_KEY_PTR DerivedKey); - CSSM_RETURN ( *FreeKey) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - CSSM_KEY_PTR KeyPtr, - CSSM_BOOL Delete); - CSSM_RETURN ( *PassThrough) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_CONTEXT *Context, - uint32 PassThroughId, - const void *InData, - void **OutData); - CSSM_RETURN ( *Login) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_DATA *LoginName, - const void *Reserved); - CSSM_RETURN ( *Logout) - (CSSM_CSP_HANDLE CSPHandle); - CSSM_RETURN ( *ChangeLoginAcl) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_EDIT *AclEdit); - CSSM_RETURN ( *ObtainPrivateKeyFromPublicKey) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_KEY *PublicKey, - CSSM_KEY_PTR PrivateKey); - CSSM_RETURN ( *RetrieveUniqueId) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_DATA_PTR UniqueID); - CSSM_RETURN ( *RetrieveCounter) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_DATA_PTR Counter); - CSSM_RETURN ( *VerifyDevice) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_DATA *DeviceCert); - CSSM_RETURN ( *GetTimeValue) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_ALGORITHMS TimeAlgorithm, - CSSM_DATA *TimeData); - CSSM_RETURN ( *GetOperationalStatistics) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_CSP_OPERATIONAL_STATISTICS *Statistics); - CSSM_RETURN ( *GetLoginAcl) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_STRING *SelectionTag, - uint32 *NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR *AclInfos); - CSSM_RETURN ( *GetKeyAcl) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_KEY *Key, - const CSSM_STRING *SelectionTag, - uint32 *NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR *AclInfos); - CSSM_RETURN ( *ChangeKeyAcl) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_EDIT *AclEdit, - const CSSM_KEY *Key); - CSSM_RETURN ( *GetKeyOwner) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_KEY *Key, - CSSM_ACL_OWNER_PROTOTYPE_PTR Owner); - CSSM_RETURN ( *ChangeKeyOwner) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_KEY *Key, - const CSSM_ACL_OWNER_PROTOTYPE *NewOwner); - CSSM_RETURN ( *GetLoginOwner) - (CSSM_CSP_HANDLE CSPHandle, - CSSM_ACL_OWNER_PROTOTYPE_PTR Owner); - CSSM_RETURN ( *ChangeLoginOwner) - (CSSM_CSP_HANDLE CSPHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_OWNER_PROTOTYPE *NewOwner); -} CSSM_SPI_CSP_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SPI_CSP_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} -extern "C" { - - -typedef struct cssm_spi_dl_funcs { - CSSM_RETURN ( *DbOpen) - (CSSM_DL_HANDLE DLHandle, - const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - CSSM_DB_ACCESS_TYPE AccessRequest, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const void *OpenParameters, - CSSM_DB_HANDLE *DbHandle); - CSSM_RETURN ( *DbClose) - (CSSM_DL_DB_HANDLE DLDBHandle); - CSSM_RETURN ( *DbCreate) - (CSSM_DL_HANDLE DLHandle, - const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - const CSSM_DBINFO *DBInfo, - CSSM_DB_ACCESS_TYPE AccessRequest, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - const void *OpenParameters, - CSSM_DB_HANDLE *DbHandle); - CSSM_RETURN ( *DbDelete) - (CSSM_DL_HANDLE DLHandle, - const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - const CSSM_ACCESS_CREDENTIALS *AccessCred); - CSSM_RETURN ( *CreateRelation) - (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_RECORDTYPE RelationID, - const char *RelationName, - uint32 NumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *pAttributeInfo, - uint32 NumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO *pIndexInfo); - CSSM_RETURN ( *DestroyRelation) - (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_RECORDTYPE RelationID); - CSSM_RETURN ( *Authenticate) - (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_ACCESS_TYPE AccessRequest, - const CSSM_ACCESS_CREDENTIALS *AccessCred); - CSSM_RETURN ( *GetDbAcl) - (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_STRING *SelectionTag, - uint32 *NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR *AclInfos); - CSSM_RETURN ( *ChangeDbAcl) - (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_EDIT *AclEdit); - CSSM_RETURN ( *GetDbOwner) - (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_ACL_OWNER_PROTOTYPE_PTR Owner); - CSSM_RETURN ( *ChangeDbOwner) - (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const CSSM_ACL_OWNER_PROTOTYPE *NewOwner); - CSSM_RETURN ( *GetDbNames) - (CSSM_DL_HANDLE DLHandle, - CSSM_NAME_LIST_PTR *NameList); - CSSM_RETURN ( *GetDbNameFromHandle) - (CSSM_DL_DB_HANDLE DLDBHandle, - char **DbName); - CSSM_RETURN ( *FreeNameList) - (CSSM_DL_HANDLE DLHandle, - CSSM_NAME_LIST_PTR NameList); - CSSM_RETURN ( *DataInsert) - (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_RECORDTYPE RecordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *Attributes, - const CSSM_DATA *Data, - CSSM_DB_UNIQUE_RECORD_PTR *UniqueId); - CSSM_RETURN ( *DataDelete) - (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_DB_UNIQUE_RECORD *UniqueRecordIdentifier); - CSSM_RETURN ( *DataModify) - (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_RECORDTYPE RecordType, - CSSM_DB_UNIQUE_RECORD_PTR UniqueRecordIdentifier, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *AttributesToBeModified, - const CSSM_DATA *DataToBeModified, - CSSM_DB_MODIFY_MODE ModifyMode); - CSSM_RETURN ( *DataGetFirst) - (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_QUERY *Query, - CSSM_HANDLE_PTR ResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CSSM_DATA_PTR Data, - CSSM_DB_UNIQUE_RECORD_PTR *UniqueId); - CSSM_RETURN ( *DataGetNext) - (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CSSM_DATA_PTR Data, - CSSM_DB_UNIQUE_RECORD_PTR *UniqueId); - CSSM_RETURN ( *DataAbortQuery) - (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_HANDLE ResultsHandle); - CSSM_RETURN ( *DataGetFromUniqueRecordId) - (CSSM_DL_DB_HANDLE DLDBHandle, - const CSSM_DB_UNIQUE_RECORD *UniqueRecord, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CSSM_DATA_PTR Data); - CSSM_RETURN ( *FreeUniqueRecord) - (CSSM_DL_DB_HANDLE DLDBHandle, - CSSM_DB_UNIQUE_RECORD_PTR UniqueRecord); - CSSM_RETURN ( *PassThrough) - (CSSM_DL_DB_HANDLE DLDBHandle, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams); -} CSSM_SPI_DL_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SPI_DL_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} - -extern "C" { - - -typedef uint32 CSSM_KRSP_HANDLE; - -typedef struct cssm_kr_name { - uint8 Type; - uint8 Length; - char *Name; -} CSSM_KR_NAME __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_kr_profile { - CSSM_KR_NAME UserName; - CSSM_CERTGROUP_PTR UserCertificate; - CSSM_CERTGROUP_PTR KRSCertChain; - uint8 LE_KRANum; - CSSM_CERTGROUP_PTR LE_KRACertChainList; - uint8 ENT_KRANum; - CSSM_CERTGROUP_PTR ENT_KRACertChainList; - uint8 INDIV_KRANum; - CSSM_CERTGROUP_PTR INDIV_KRACertChainList; - CSSM_DATA_PTR INDIV_AuthenticationInfo; - uint32 KRSPFlags; - CSSM_DATA_PTR KRSPExtensions; -} CSSM_KR_PROFILE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_KR_PROFILE_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_kr_wrappedproductinfo { - CSSM_VERSION StandardVersion; - CSSM_STRING StandardDescription; - CSSM_VERSION ProductVersion; - CSSM_STRING ProductDescription; - CSSM_STRING ProductVendor; - uint32 ProductFlags; -} CSSM_KR_WRAPPEDPRODUCT_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_KR_WRAPPEDPRODUCT_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_krsubservice { - uint32 SubServiceId; - char *Description; - CSSM_KR_WRAPPEDPRODUCT_INFO WrappedProduct; -} CSSM_KRSUBSERVICE, *CSSM_KRSUBSERVICE_PTR; - -typedef uint32 CSSM_KR_POLICY_TYPE; - - - - - -typedef uint32 CSSM_KR_POLICY_FLAGS; -typedef struct cssm_kr_policy_list_item { - struct kr_policy_list_item *next; - CSSM_ALGORITHMS AlgorithmId; - CSSM_ENCRYPT_MODE Mode; - uint32 MaxKeyLength; - uint32 MaxRounds; - uint8 WorkFactor; - CSSM_KR_POLICY_FLAGS PolicyFlags; - CSSM_CONTEXT_TYPE AlgClass; -} CSSM_KR_POLICY_LIST_ITEM __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_KR_POLICY_LIST_ITEM_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_kr_policy_info { - CSSM_BOOL krbNotAllowed; - uint32 numberOfEntries; - CSSM_KR_POLICY_LIST_ITEM *policyEntry; -} CSSM_KR_POLICY_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_KR_POLICY_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -CSSM_RETURN -CSSM_KR_SetEnterpriseRecoveryPolicy (const CSSM_DATA *RecoveryPolicyFileName, - const CSSM_ACCESS_CREDENTIALS *OldPassPhrase, - const CSSM_ACCESS_CREDENTIALS *NewPassPhrase) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -CSSM_RETURN -CSSM_KR_CreateRecoveryRegistrationContext (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_CC_HANDLE *NewContext) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_KR_CreateRecoveryEnablementContext (CSSM_KRSP_HANDLE KRSPHandle, - const CSSM_KR_PROFILE *LocalProfile, - const CSSM_KR_PROFILE *RemoteProfile, - CSSM_CC_HANDLE *NewContext) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_KR_CreateRecoveryRequestContext (CSSM_KRSP_HANDLE KRSPHandle, - const CSSM_KR_PROFILE *LocalProfile, - CSSM_CC_HANDLE *NewContext) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_KR_GetPolicyInfo (CSSM_CC_HANDLE CCHandle, - CSSM_KR_POLICY_FLAGS *EncryptionProhibited, - uint32 *WorkFactor) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -CSSM_RETURN -CSSM_KR_RegistrationRequest (CSSM_CC_HANDLE RecoveryRegistrationContext, - const CSSM_DATA *KRInData, - const CSSM_ACCESS_CREDENTIALS *AccessCredentials, - CSSM_KR_POLICY_FLAGS KRFlags, - sint32 *EstimatedTime, - CSSM_HANDLE_PTR ReferenceHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_KR_RegistrationRetrieve (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_HANDLE ReferenceHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCredentials, - sint32 *EstimatedTime, - CSSM_KR_PROFILE_PTR KRProfile) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -CSSM_RETURN -CSSM_KR_GenerateRecoveryFields (CSSM_CC_HANDLE KeyRecoveryContext, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *KRSPOptions, - CSSM_KR_POLICY_FLAGS KRFlags, - CSSM_DATA_PTR KRFields, - CSSM_CC_HANDLE *NewCCHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_KR_ProcessRecoveryFields (CSSM_CC_HANDLE KeyRecoveryContext, - CSSM_CC_HANDLE CryptoContext, - const CSSM_DATA *KRSPOptions, - CSSM_KR_POLICY_FLAGS KRFlags, - const CSSM_DATA *KRFields, - CSSM_CC_HANDLE *NewCryptoContext) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -CSSM_RETURN -CSSM_KR_RecoveryRequest (CSSM_CC_HANDLE RecoveryRequestContext, - const CSSM_DATA *KRInData, - const CSSM_ACCESS_CREDENTIALS *AccessCredentials, - sint32 *EstimatedTime, - CSSM_HANDLE_PTR ReferenceHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_KR_RecoveryRetrieve (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_HANDLE ReferenceHandle, - const CSSM_ACCESS_CREDENTIALS *AccessCredentials, - sint32 *EstimatedTime, - CSSM_HANDLE_PTR CacheHandle, - uint32 *NumberOfRecoveredKeys) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_KR_GetRecoveredObject (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_HANDLE CacheHandle, - uint32 IndexInResults, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - uint32 Flags, - CSSM_KEY_PTR RecoveredKey, - CSSM_DATA_PTR OtherInfo) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_KR_RecoveryRequestAbort (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_HANDLE CacheHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -CSSM_KR_QueryPolicyInfo (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_ALGORITHMS AlgorithmID, - CSSM_ENCRYPT_MODE Mode, - CSSM_CONTEXT_TYPE Class, - CSSM_KR_POLICY_INFO_PTR *PolicyInfoData) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -CSSM_RETURN -CSSM_KR_PassThrough (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_CC_HANDLE KeyRecoveryContext, - CSSM_CC_HANDLE CryptoContext, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} -extern "C" { - - - - -typedef struct cssm_spi_kr_funcs { - CSSM_RETURN ( *RegistrationRequest) - (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_CC_HANDLE KRRegistrationContextHandle, - const CSSM_CONTEXT *KRRegistrationContext, - const CSSM_DATA *KRInData, - const CSSM_ACCESS_CREDENTIALS *AccessCredentials, - CSSM_KR_POLICY_FLAGS KRFlags, - sint32 *EstimatedTime, - CSSM_HANDLE_PTR ReferenceHandle); - CSSM_RETURN ( *RegistrationRetrieve) - (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_HANDLE ReferenceHandle, - sint32 *EstimatedTime, - CSSM_KR_PROFILE_PTR KRProfile); - CSSM_RETURN ( *GenerateRecoveryFields) - (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_CC_HANDLE KREnablementContextHandle, - const CSSM_CONTEXT *KREnablementContext, - CSSM_CC_HANDLE CryptoContextHandle, - const CSSM_CONTEXT *CryptoContext, - const CSSM_DATA *KRSPOptions, - CSSM_KR_POLICY_FLAGS KRFlags, - CSSM_DATA_PTR KRFields); - CSSM_RETURN ( *ProcessRecoveryFields) - (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_CC_HANDLE KREnablementContextHandle, - const CSSM_CONTEXT *KREnablementContext, - CSSM_CC_HANDLE CryptoContextHandle, - const CSSM_CONTEXT *CryptoContext, - const CSSM_DATA *KRSPOptions, - CSSM_KR_POLICY_FLAGS KRFlags, - const CSSM_DATA *KRFields); - CSSM_RETURN ( *RecoveryRequest) - (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_CC_HANDLE KRRequestContextHandle, - const CSSM_CONTEXT *KRRequestContext, - const CSSM_DATA *KRInData, - const CSSM_ACCESS_CREDENTIALS *AccessCredentials, - sint32 *EstimatedTime, - CSSM_HANDLE_PTR ReferenceHandle); - CSSM_RETURN ( *RecoveryRetrieve) - (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_HANDLE ReferenceHandle, - sint32 *EstimatedTime, - CSSM_HANDLE_PTR CacheHandle, - uint32 *NumberOfRecoveredKeys); - CSSM_RETURN ( *GetRecoveredObject) - (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_HANDLE CacheHandle, - uint32 IndexInResults, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - uint32 Flags, - CSSM_KEY_PTR RecoveredKey, - CSSM_DATA_PTR OtherInfo); - CSSM_RETURN ( *RecoveryRequestAbort) - (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_HANDLE ResultsHandle); - CSSM_RETURN ( *PassThrough) - (CSSM_KRSP_HANDLE KRSPHandle, - CSSM_CC_HANDLE KeyRecoveryContextHandle, - const CSSM_CONTEXT *KeyRecoveryContext, - CSSM_CC_HANDLE CryptoContextHandle, - const CSSM_CONTEXT *CryptoContext, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams); -} CSSM_SPI_KR_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SPI_KR_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} - -extern "C" { - - -typedef struct cssm_spi_tp_funcs { - CSSM_RETURN ( *SubmitCredRequest) - (CSSM_TP_HANDLE TPHandle, - const CSSM_TP_AUTHORITY_ID *PreferredAuthority, - CSSM_TP_AUTHORITY_REQUEST_TYPE RequestType, - const CSSM_TP_REQUEST_SET *RequestInput, - const CSSM_TP_CALLERAUTH_CONTEXT *CallerAuthContext, - sint32 *EstimatedTime, - CSSM_DATA_PTR ReferenceIdentifier); - CSSM_RETURN ( *RetrieveCredResult) - (CSSM_TP_HANDLE TPHandle, - const CSSM_DATA *ReferenceIdentifier, - const CSSM_TP_CALLERAUTH_CONTEXT *CallerAuthCredentials, - sint32 *EstimatedTime, - CSSM_BOOL *ConfirmationRequired, - CSSM_TP_RESULT_SET_PTR *RetrieveOutput); - CSSM_RETURN ( *ConfirmCredResult) - (CSSM_TP_HANDLE TPHandle, - const CSSM_DATA *ReferenceIdentifier, - const CSSM_TP_CALLERAUTH_CONTEXT *CallerAuthCredentials, - const CSSM_TP_CONFIRM_RESPONSE *Responses, - const CSSM_TP_AUTHORITY_ID *PreferredAuthority); - CSSM_RETURN ( *ReceiveConfirmation) - (CSSM_TP_HANDLE TPHandle, - const CSSM_DATA *ReferenceIdentifier, - CSSM_TP_CONFIRM_RESPONSE_PTR *Responses, - sint32 *ElapsedTime); - CSSM_RETURN ( *CertReclaimKey) - (CSSM_TP_HANDLE TPHandle, - const CSSM_CERTGROUP *CertGroup, - uint32 CertIndex, - CSSM_LONG_HANDLE KeyCacheHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry); - CSSM_RETURN ( *CertReclaimAbort) - (CSSM_TP_HANDLE TPHandle, - CSSM_LONG_HANDLE KeyCacheHandle); - CSSM_RETURN ( *FormRequest) - (CSSM_TP_HANDLE TPHandle, - const CSSM_TP_AUTHORITY_ID *PreferredAuthority, - CSSM_TP_FORM_TYPE FormType, - CSSM_DATA_PTR BlankForm); - CSSM_RETURN ( *FormSubmit) - (CSSM_TP_HANDLE TPHandle, - CSSM_TP_FORM_TYPE FormType, - const CSSM_DATA *Form, - const CSSM_TP_AUTHORITY_ID *ClearanceAuthority, - const CSSM_TP_AUTHORITY_ID *RepresentedAuthority, - CSSM_ACCESS_CREDENTIALS_PTR Credentials); - CSSM_RETURN ( *CertGroupVerify) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_CERTGROUP *CertGroupToBeVerified, - const CSSM_TP_VERIFY_CONTEXT *VerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR VerifyContextResult); - CSSM_RETURN ( *CertCreateTemplate) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CertFields, - CSSM_DATA_PTR CertTemplate); - CSSM_RETURN ( *CertGetAllTemplateFields) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - const CSSM_DATA *CertTemplate, - uint32 *NumberOfFields, - CSSM_FIELD_PTR *CertFields); - CSSM_RETURN ( *CertSign) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DATA *CertTemplateToBeSigned, - const CSSM_CERTGROUP *SignerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *SignerVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR SignerVerifyResult, - CSSM_DATA_PTR SignedCert); - CSSM_RETURN ( *CrlVerify) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_ENCODED_CRL *CrlToBeVerified, - const CSSM_CERTGROUP *SignerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *VerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR RevokerVerifyResult); - CSSM_RETURN ( *CrlCreateTemplate) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - uint32 NumberOfFields, - const CSSM_FIELD *CrlFields, - CSSM_DATA_PTR NewCrlTemplate); - CSSM_RETURN ( *CertRevoke) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_DATA *OldCrlTemplate, - const CSSM_CERTGROUP *CertGroupToBeRevoked, - const CSSM_CERTGROUP *RevokerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *RevokerVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR RevokerVerifyResult, - CSSM_TP_CERTCHANGE_REASON Reason, - CSSM_DATA_PTR NewCrlTemplate); - CSSM_RETURN ( *CertRemoveFromCrlTemplate) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_DATA *OldCrlTemplate, - const CSSM_CERTGROUP *CertGroupToBeRemoved, - const CSSM_CERTGROUP *RevokerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *RevokerVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR RevokerVerifyResult, - CSSM_DATA_PTR NewCrlTemplate); - CSSM_RETURN ( *CrlSign) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_ENCODED_CRL *CrlToBeSigned, - const CSSM_CERTGROUP *SignerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *SignerVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR SignerVerifyResult, - CSSM_DATA_PTR SignedCrl); - CSSM_RETURN ( *ApplyCrlToDb) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_ENCODED_CRL *CrlToBeApplied, - const CSSM_CERTGROUP *SignerCertGroup, - const CSSM_TP_VERIFY_CONTEXT *ApplyCrlVerifyContext, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR ApplyCrlVerifyResult); - CSSM_RETURN ( *CertGroupConstruct) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CSP_HANDLE CSPHandle, - const CSSM_DL_DB_LIST *DBList, - const void *ConstructParams, - const CSSM_CERTGROUP *CertGroupFrag, - CSSM_CERTGROUP_PTR *CertGroup); - CSSM_RETURN ( *CertGroupPrune) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - const CSSM_DL_DB_LIST *DBList, - const CSSM_CERTGROUP *OrderedCertGroup, - CSSM_CERTGROUP_PTR *PrunedCertGroup); - CSSM_RETURN ( *CertGroupToTupleGroup) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - const CSSM_CERTGROUP *CertGroup, - CSSM_TUPLEGROUP_PTR *TupleGroup); - CSSM_RETURN ( *TupleGroupToCertGroup) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - const CSSM_TUPLEGROUP *TupleGroup, - CSSM_CERTGROUP_PTR *CertTemplates); - CSSM_RETURN ( *PassThrough) - (CSSM_TP_HANDLE TPHandle, - CSSM_CL_HANDLE CLHandle, - CSSM_CC_HANDLE CCHandle, - const CSSM_DL_DB_LIST *DBList, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams); -} CSSM_SPI_TP_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_SPI_TP_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} - -extern "C" { - - -typedef struct cssm_state_funcs { - CSSM_RETURN ( *cssm_GetAttachFunctions) - (CSSM_MODULE_HANDLE hAddIn, - CSSM_SERVICE_MASK AddinType, - void **SPFunctions, - CSSM_GUID_PTR Guid, - CSSM_BOOL *Serialized); - CSSM_RETURN ( *cssm_ReleaseAttachFunctions) - (CSSM_MODULE_HANDLE hAddIn); - CSSM_RETURN ( *cssm_GetAppMemoryFunctions) - (CSSM_MODULE_HANDLE hAddIn, - CSSM_UPCALLS_PTR UpcallTable); - CSSM_RETURN ( *cssm_IsFuncCallValid) - (CSSM_MODULE_HANDLE hAddin, - CSSM_PROC_ADDR SrcAddress, - CSSM_PROC_ADDR DestAddress, - CSSM_PRIVILEGE InPriv, - CSSM_PRIVILEGE *OutPriv, - CSSM_BITMASK Hints, - CSSM_BOOL *IsOK); - CSSM_RETURN ( *cssm_DeregisterManagerServices) - (const CSSM_GUID *GUID); - CSSM_RETURN ( *cssm_DeliverModuleManagerEvent) - (const CSSM_MANAGER_EVENT_NOTIFICATION *EventDescription); -} CSSM_STATE_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_STATE_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -typedef struct cssm_manager_registration_info { - - CSSM_RETURN ( *Initialize) - (uint32 VerMajor, - uint32 VerMinor); - CSSM_RETURN ( *Terminate) (void); - CSSM_RETURN ( *RegisterDispatchTable) - (CSSM_STATE_FUNCS_PTR CssmStateCallTable); - CSSM_RETURN ( *DeregisterDispatchTable) (void); - CSSM_RETURN ( *EventNotifyManager) - (const CSSM_MANAGER_EVENT_NOTIFICATION *EventDescription); - CSSM_RETURN ( *RefreshFunctionTable) - (CSSM_FUNC_NAME_ADDR_PTR FuncNameAddrPtr, - uint32 NumOfFuncNameAddr); -} CSSM_MANAGER_REGISTRATION_INFO __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *CSSM_MANAGER_REGISTRATION_INFO_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -enum { - CSSM_HINT_NONE = 0, - CSSM_HINT_ADDRESS_APP = 1 << 0, - CSSM_HINT_ADDRESS_SP = 1 << 1 -}; - -CSSM_RETURN -ModuleManagerAuthenticate (CSSM_KEY_HIERARCHY KeyHierarchy, - const CSSM_GUID *CssmGuid, - const CSSM_GUID *AppGuid, - CSSM_MANAGER_REGISTRATION_INFO_PTR FunctionTable) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} - -extern "C" { - - -typedef CSSM_DL_HANDLE MDS_HANDLE; - -typedef CSSM_DL_DB_HANDLE MDS_DB_HANDLE; - -typedef struct mds_funcs { - CSSM_RETURN ( *DbOpen) - (MDS_HANDLE MdsHandle, - const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - CSSM_DB_ACCESS_TYPE AccessRequest, - const CSSM_ACCESS_CREDENTIALS *AccessCred, - const void *OpenParameters, - CSSM_DB_HANDLE *hMds); - - CSSM_RETURN ( *DbClose) - (MDS_DB_HANDLE MdsDbHandle); - - CSSM_RETURN ( *GetDbNames) - (MDS_HANDLE MdsHandle, - CSSM_NAME_LIST_PTR *NameList); - - CSSM_RETURN ( *GetDbNameFromHandle) - (MDS_DB_HANDLE MdsDbHandle, - char **DbName); - - CSSM_RETURN ( *FreeNameList) - (MDS_HANDLE MdsHandle, - CSSM_NAME_LIST_PTR NameList); - - CSSM_RETURN ( *DataInsert) - (MDS_DB_HANDLE MdsDbHandle, - CSSM_DB_RECORDTYPE RecordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *Attributes, - const CSSM_DATA *Data, - CSSM_DB_UNIQUE_RECORD_PTR *UniqueId); - - CSSM_RETURN ( *DataDelete) - (MDS_DB_HANDLE MdsDbHandle, - const CSSM_DB_UNIQUE_RECORD *UniqueRecordIdentifier); - - CSSM_RETURN ( *DataModify) - (MDS_DB_HANDLE MdsDbHandle, - CSSM_DB_RECORDTYPE RecordType, - CSSM_DB_UNIQUE_RECORD_PTR UniqueRecordIdentifier, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *AttributesToBeModified, - const CSSM_DATA *DataToBeModified, - CSSM_DB_MODIFY_MODE ModifyMode); - - CSSM_RETURN ( *DataGetFirst) - (MDS_DB_HANDLE MdsDbHandle, - const CSSM_QUERY *Query, - CSSM_HANDLE_PTR ResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CSSM_DATA_PTR Data, - CSSM_DB_UNIQUE_RECORD_PTR *UniqueId); - - CSSM_RETURN ( *DataGetNext) - (MDS_DB_HANDLE MdsDbHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CSSM_DATA_PTR Data, - CSSM_DB_UNIQUE_RECORD_PTR *UniqueId); - - CSSM_RETURN ( *DataAbortQuery) - (MDS_DB_HANDLE MdsDbHandle, - CSSM_HANDLE ResultsHandle); - - CSSM_RETURN ( *DataGetFromUniqueRecordId) - (MDS_DB_HANDLE MdsDbHandle, - const CSSM_DB_UNIQUE_RECORD *UniqueRecord, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CSSM_DATA_PTR Data); - - CSSM_RETURN ( *FreeUniqueRecord) - (MDS_DB_HANDLE MdsDbHandle, - CSSM_DB_UNIQUE_RECORD_PTR UniqueRecord); - - CSSM_RETURN ( *CreateRelation) - (MDS_DB_HANDLE MdsDbHandle, - CSSM_DB_RECORDTYPE RelationID, - const char *RelationName, - uint32 NumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *pAttributeInfo, - uint32 NumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO *pIndexInfo); - - CSSM_RETURN ( *DestroyRelation) - (MDS_DB_HANDLE MdsDbHandle, - CSSM_DB_RECORDTYPE RelationID); -} MDS_FUNCS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), *MDS_FUNCS_PTR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -CSSM_RETURN -MDS_Initialize (const CSSM_GUID *pCallerGuid, - const CSSM_MEMORY_FUNCS *pMemoryFunctions, - MDS_FUNCS_PTR pDlFunctions, - MDS_HANDLE *hMds) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -MDS_Terminate (MDS_HANDLE MdsHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -MDS_Install (MDS_HANDLE MdsHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -CSSM_RETURN -MDS_Uninstall (MDS_HANDLE MdsHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} -extern "C" { -} -typedef CSSM_DATA SecAsn1Item; -typedef CSSM_OID SecAsn1Oid; -typedef CSSM_X509_ALGORITHM_IDENTIFIER SecAsn1AlgId; -typedef CSSM_X509_SUBJECT_PUBLIC_KEY_INFO SecAsn1PubKeyInfo; -typedef struct SecAsn1Template_struct { - - - - uint32_t kind; - - - - - - - - uint32_t offset; - const void *sub; - - - - - - - - uint32_t size; -} SecAsn1Template; -typedef const SecAsn1Template * SecAsn1TemplateChooser( - void *arg, - Boolean enc, - const char *buf, - size_t len, - void *dest); - -typedef SecAsn1TemplateChooser * SecAsn1TemplateChooserPtr; - - -extern "C" { - - -extern const SecAsn1Oid - CSSMOID_MD2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_MD4 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_MD5 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_RSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_MD2WithRSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_MD4WithRSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_MD5WithRSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA1WithRSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA224WithRSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA256WithRSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA384WithRSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA512WithRSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA1WithRSA_OIW __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_RSAWithOAEP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_OAEP_MGF1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_OAEP_ID_PSPECIFIED __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DES_CBC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_PUB_NUMBER __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_STATIC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_ONE_FLOW __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_EPHEM __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_HYBRID1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_HYBRID2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_HYBRID_ONEFLOW __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_MQV1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_MQV2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_STATIC_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_ONE_FLOW_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_EPHEM_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_HYBRID1_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_DH_HYBRID2_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_MQV1_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ANSI_MQV2_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS3 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DH __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DSA_CMS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DSA_JDK __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA1WithDSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA1WithDSA_CMS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA1WithDSA_JDK __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA224 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA256 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA384 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SHA512 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ecPublicKey __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ECDSA_WithSHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ECDSA_WithSHA224 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ECDSA_WithSHA256 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ECDSA_WithSHA384 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ECDSA_WithSHA512 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ECDSA_WithSpecified __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_ISIGN __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_X509_BASIC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_SSL __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_LOCAL_CERT_GEN __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_CSR_GEN __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_REVOCATION_CRL __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_REVOCATION_OCSP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_SMIME __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_EAP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_CODE_SIGN __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_SW_UPDATE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_IP_SEC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_ICHAT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_RESOURCE_SIGN __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_PKINIT_CLIENT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_PKINIT_SERVER __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_CODE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_PACKAGE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_MACAPPSTORE_RECEIPT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_APPLEID_SHARING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_TIMESTAMPING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_REVOCATION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_PASSBOOK_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_MOBILE_STORE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_ESCROW_SERVICE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_PROFILE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_QA_PROFILE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_TEST_MOBILE_STORE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_PCS_ESCROW_SERVICE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_TP_PROVISIONING_PROFILE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_FEE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_ASC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_FEE_MD5 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_FEE_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_FEED __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_FEEDEXP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_ECDSA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_IDENTITY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_EMAIL_SIGN __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_EMAIL_ENCRYPT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_LIST __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_STORE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_FETCH __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_REMOVE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_SHARED_SERVICES __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_VALUE_USERNAME __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_VALUE_PASSWORD __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_VALUE_HOSTNAME __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_VALUE_RENEW __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_VALUE_ASYNC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_REQ_VALUE_IS_PENDING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_DIGEST_ALG __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_ENCRYPT_ALG __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_HMAC_SHA1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_pbeWithMD2AndDES __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_pbeWithMD2AndRC2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_pbeWithMD5AndDES __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_pbeWithMD5AndRC2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_pbeWithSHA1AndDES __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_pbeWithSHA1AndRC2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_PBKDF2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_PBES2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_PBMAC1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_RC2_CBC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_DES_EDE3_CBC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS5_RC5_CBC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_pbeWithSHAAnd128BitRC4 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_pbeWithSHAAnd40BitRC4 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_pbeWithSHAAnd3Key3DESCBC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_pbeWithSHAAnd2Key3DESCBC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_pbeWithSHAAnd128BitRC2CBC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_pbewithSHAAnd40BitRC2CBC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -} -extern "C" { -} - - - - - - - -extern const SecAsn1Oid - CSSMOID_ObjectClass __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_AliasedEntryName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_KnowledgeInformation __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CommonName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_Surname __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SerialNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CountryName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_LocalityName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_StateProvinceName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectiveStateProvinceName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_StreetAddress __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectiveStreetAddress __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_OrganizationName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectiveOrganizationName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_OrganizationalUnitName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectiveOrganizationalUnitName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_Title __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_Description __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SearchGuide __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_BusinessCategory __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PostalAddress __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectivePostalAddress __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PostalCode __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectivePostalCode __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PostOfficeBox __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectivePostOfficeBox __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PhysicalDeliveryOfficeName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectivePhysicalDeliveryOfficeName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_TelephoneNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectiveTelephoneNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_TelexNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectiveTelexNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_TelexTerminalIdentifier __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectiveTelexTerminalIdentifier __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_FacsimileTelephoneNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectiveFacsimileTelephoneNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X_121Address __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_InternationalISDNNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CollectiveInternationalISDNNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_RegisteredAddress __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DestinationIndicator __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PreferredDeliveryMethod __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PresentationAddress __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SupportedApplicationContext __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_Member __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_Owner __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_RoleOccupant __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SeeAlso __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_UserPassword __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_UserCertificate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CACertificate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_AuthorityRevocationList __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CertificateRevocationList __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CrossCertificatePair __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_Name __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_GivenName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_Initials __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_GenerationQualifier __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_UniqueIdentifier __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DNQualifier __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_EnhancedSearchGuide __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ProtocolInformation __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DistinguishedName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_UniqueMember __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_HouseIdentifier __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -extern const SecAsn1Oid - CSSMOID_EmailAddress __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_UnstructuredName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ContentType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_MessageDigest __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SigningTime __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CounterSignature __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ChallengePassword __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_UnstructuredAddress __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ExtendedCertificateAttributes __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -extern const SecAsn1Oid - CSSMOID_PKCS9_Id_Ct_TSTInfo __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS9_TimeStampToken __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -extern const SecAsn1Oid - CSSMOID_QT_CPS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_QT_UNOTICE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_AD_OCSP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_AD_CA_ISSUERS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_AD_TIME_STAMPING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_AD_CA_REPOSITORY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PDA_DATE_OF_BIRTH __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PDA_PLACE_OF_BIRTH __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PDA_GENDER __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PDA_COUNTRY_CITIZEN __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PDA_COUNTRY_RESIDENCE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_OID_QCS_SYNTAX_V1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_OID_QCS_SYNTAX_V2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -extern const SecAsn1Oid - CSSMOID_ETSI_QCS_QC_COMPLIANCE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ETSI_QCS_QC_LIMIT_VALUE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ETSI_QCS_QC_RETENTION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ETSI_QCS_QC_SSCD __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -extern const SecAsn1Oid - CSSMOID_PKCS7_Data __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS7_SignedData __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS7_EnvelopedData __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS7_SignedAndEnvelopedData __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS7_DigestedData __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS7_EncryptedData __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS7_DataWithAttributes __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS7_EncryptedPrivateKeyInfo __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_PKCS9_FriendlyName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS9_LocalKeyId __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS9_CertTypes __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS9_CrlTypes __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS9_X509Certificate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS9_SdsiCertificate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS9_X509Crl __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_PKCS12_keyBag __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_shroudedKeyBag __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_certBag __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_crlBag __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_secretBag __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKCS12_safeContentsBag __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_UserID __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_DomainComponent __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_KERBv5_PKINIT_AUTH_DATA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_KERBv5_PKINIT_DH_KEY_DATA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_KERBv5_PKINIT_RKEY_DATA __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -extern const SecAsn1Oid - CSSMOID_X9_62 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X9_62_FieldType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X9_62_PubKeyType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X9_62_EllCurve __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X9_62_C_TwoCurve __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X9_62_PrimeCurve __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X9_62_SigType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp192r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp256r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_Certicom __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CerticomEllCurve __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp112r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp112r2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp128r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp128r2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp160k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp160r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp160r2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp192k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp224k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp224r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp256k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp384r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_secp521r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect113r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect113r2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect131r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect131r2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect163k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect163r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect163r2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect193r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect193r2 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect233k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect233r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect239k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect283k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect283r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect409k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect409r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect571k1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_sect571r1 __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -extern "C" { -extern const CSSM_OID - - CSSMOID_X509V3SignedCertificate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3SignedCertificateCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3Certificate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1Version __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SerialNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1IssuerName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1IssuerNameStd __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1IssuerNameCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1IssuerNameLDAP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1ValidityNotBefore __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1ValidityNotAfter __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SubjectName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SubjectNameStd __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SubjectNameCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SubjectNameLDAP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CSSMKeyStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SubjectPublicKeyCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SubjectPublicKeyAlgorithm __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SubjectPublicKeyAlgorithmParameters __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SubjectPublicKey __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CertificateIssuerUniqueId __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CertificateSubjectUniqueId __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateExtensionsStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateExtensionsCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateNumberOfExtensions __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateExtensionStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateExtensionCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateExtensionId __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateExtensionCritical __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateExtensionType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V3CertificateExtensionValue __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_X509V1SignatureStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SignatureCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SignatureAlgorithm __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SignatureAlgorithmTBS __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1SignatureAlgorithmParameters __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1Signature __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_SubjectSignatureBitmap __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SubjectPicture __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SubjectEmailAddress __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_UseExemptions __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern const CSSM_OID - CSSMOID_SubjectDirectoryAttributes __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SubjectKeyIdentifier __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_KeyUsage __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PrivateKeyUsagePeriod __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SubjectAltName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_IssuerAltName __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_BasicConstraints __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CrlNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CrlReason __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_HoldInstructionCode __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_InvalidityDate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DeltaCrlIndicator __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_IssuingDistributionPoint __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_IssuingDistributionPoints __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CertIssuer __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_NameConstraints __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CrlDistributionPoints __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_CertificatePolicies __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PolicyMappings __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PolicyConstraints __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_AuthorityKeyIdentifier __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ExtendedKeyUsage __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_InhibitAnyPolicy __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_AuthorityInfoAccess __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_BiometricInfo __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_QC_Statements __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_SubjectInfoAccess __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ExtendedKeyUsageAny __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ServerAuth __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ClientAuth __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ExtendedUseCodeSigning __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_EmailProtection __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_TimeStamping __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_OCSPSigning __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_KERBv5_PKINIT_KP_CLIENT_AUTH __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_KERBv5_PKINIT_KP_KDC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_EKU_IPSec __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_EXTENSION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_IDENTITY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_EMAIL_SIGN __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_EMAIL_ENCRYPT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_CERT_POLICY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_DOTMAC_CERT_POLICY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_ADC_CERT_POLICY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_MACAPPSTORE_CERT_POLICY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_MACAPPSTORE_RECEIPT_CERT_POLICY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLEID_CERT_POLICY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLEID_SHARING_CERT_POLICY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_MOBILE_STORE_SIGNING_POLICY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_TEST_MOBILE_STORE_SIGNING_POLICY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EKU_CODE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EKU_CODE_SIGNING_DEV __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EKU_RESOURCE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EKU_ICHAT_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EKU_ICHAT_ENCRYPTION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EKU_SYSTEM_IDENTITY __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EKU_PASSBOOK_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EKU_PROFILE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EKU_QA_PROFILE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_CODE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_APPLE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_ADC_DEV_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_ADC_APPLE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_PASSBOOK_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_MACAPPSTORE_RECEIPT __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_INTERMEDIATE_MARKER __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_WWDR_INTERMEDIATE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_ITMS_INTERMEDIATE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_AAI_INTERMEDIATE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_APPLEID_INTERMEDIATE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_APPLEID_SHARING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_SYSINT2_INTERMEDIATE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_DEVELOPER_AUTHENTICATION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_SERVER_AUTHENTICATION __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_ESCROW_SERVICE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_APPLE_EXTENSION_PROVISIONING_PROFILE_SIGNING __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))) -; - - - - -extern const CSSM_OID - CSSMOID_NetscapeCertType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_NetscapeCertSequence __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_NetscapeSGC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - -extern const CSSM_OID CSSMOID_MicrosoftSGC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -} -extern "C" { - - - - - - -extern const CSSM_OID - - CSSMOID_X509V2CRLSignedCrlStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLSignedCrlCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLTbsCertListStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLTbsCertListCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLVersion __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLIssuerStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLIssuerNameCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLIssuerNameLDAP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLThisUpdate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLNextUpdate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_X509V1CRLRevokedCertificatesStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLRevokedCertificatesCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLNumberOfRevokedCertEntries __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLRevokedEntryStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLRevokedEntryCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLRevokedEntrySerialNumber __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V1CRLRevokedEntryRevocationDate __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_X509V2CRLRevokedEntryAllExtensionsStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLRevokedEntryAllExtensionsCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLRevokedEntryNumberOfExtensions __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLRevokedEntrySingleExtensionStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLRevokedEntrySingleExtensionCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLRevokedEntryExtensionId __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLRevokedEntryExtensionCritical __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLRevokedEntryExtensionType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLRevokedEntryExtensionValue __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_X509V2CRLAllExtensionsStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLAllExtensionsCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLNumberOfExtensions __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLSingleExtensionStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLSingleExtensionCStruct __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLExtensionId __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLExtensionCritical __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_X509V2CRLExtensionType __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - - - CSSMOID_PKIX_OCSP __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKIX_OCSP_BASIC __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKIX_OCSP_NONCE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKIX_OCSP_CRL __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKIX_OCSP_RESPONSE __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKIX_OCSP_NOCHECK __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKIX_OCSP_ARCHIVE_CUTOFF __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))), - CSSMOID_PKIX_OCSP_SERVICE_LOCATOR __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - -} - - - -extern "C" { -typedef struct __attribute__((objc_bridge(id))) OpaqueSecKeychainRef *SecKeychainRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecKeychainItemRef *SecKeychainItemRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecKeychainSearchRef *SecKeychainSearchRef; - - - - - -typedef OSType SecKeychainAttrType; -struct SecKeychainAttribute -{ - SecKeychainAttrType tag; - UInt32 length; - void *data; -}; -typedef struct SecKeychainAttribute SecKeychainAttribute; - - - - - -typedef SecKeychainAttribute *SecKeychainAttributePtr; - - - - - - - -struct SecKeychainAttributeList -{ - UInt32 count; - SecKeychainAttribute *attr; -}; -typedef struct SecKeychainAttributeList SecKeychainAttributeList; - - - - - -typedef UInt32 SecKeychainStatus; - - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecTrustedApplicationRef *SecTrustedApplicationRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecPolicyRef *SecPolicyRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecCertificateRef *SecCertificateRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecAccessRef *SecAccessRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecIdentityRef *SecIdentityRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecKeyRef *SecKeyRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecTrustRef *SecACLRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecAccessControl *SecAccessControlRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) OpaqueSecPasswordRef *SecPasswordRef; -struct SecKeychainAttributeInfo -{ - UInt32 count; - UInt32 *tag; - UInt32 *format; -}; -typedef struct SecKeychainAttributeInfo SecKeychainAttributeInfo; -_Nullable -CFStringRef SecCopyErrorMessageString(OSStatus status, void * _Nullable reserved) - __attribute__((availability(macosx,introduced=10.3))); -enum -{ - errSecSuccess = 0, - errSecUnimplemented = -4, - errSecDskFull = -34, - errSecIO = -36, - - errSecParam = -50, - errSecWrPerm = -61, - errSecAllocate = -108, - errSecUserCanceled = -128, - errSecBadReq = -909, - - errSecInternalComponent = -2070, - errSecCoreFoundationUnknown = -4960, - - errSecNotAvailable = -25291, - errSecReadOnly = -25292, - errSecAuthFailed = -25293, - errSecNoSuchKeychain = -25294, - errSecInvalidKeychain = -25295, - errSecDuplicateKeychain = -25296, - errSecDuplicateCallback = -25297, - errSecInvalidCallback = -25298, - errSecDuplicateItem = -25299, - errSecItemNotFound = -25300, - errSecBufferTooSmall = -25301, - errSecDataTooLarge = -25302, - errSecNoSuchAttr = -25303, - errSecInvalidItemRef = -25304, - errSecInvalidSearchRef = -25305, - errSecNoSuchClass = -25306, - errSecNoDefaultKeychain = -25307, - errSecInteractionNotAllowed = -25308, - errSecReadOnlyAttr = -25309, - errSecWrongSecVersion = -25310, - errSecKeySizeNotAllowed = -25311, - errSecNoStorageModule = -25312, - errSecNoCertificateModule = -25313, - errSecNoPolicyModule = -25314, - errSecInteractionRequired = -25315, - errSecDataNotAvailable = -25316, - errSecDataNotModifiable = -25317, - errSecCreateChainFailed = -25318, - errSecInvalidPrefsDomain = -25319, - errSecInDarkWake = -25320, - - errSecACLNotSimple = -25240, - errSecPolicyNotFound = -25241, - errSecInvalidTrustSetting = -25242, - errSecNoAccessForItem = -25243, - errSecInvalidOwnerEdit = -25244, - errSecTrustNotAvailable = -25245, - errSecUnsupportedFormat = -25256, - errSecUnknownFormat = -25257, - errSecKeyIsSensitive = -25258, - errSecMultiplePrivKeys = -25259, - errSecPassphraseRequired = -25260, - errSecInvalidPasswordRef = -25261, - errSecInvalidTrustSettings = -25262, - errSecNoTrustSettings = -25263, - errSecPkcs12VerifyFailure = -25264, - errSecNotSigner = -26267, - - errSecDecode = -26275, - - errSecServiceNotAvailable = -67585, - errSecInsufficientClientID = -67586, - errSecDeviceReset = -67587, - errSecDeviceFailed = -67588, - errSecAppleAddAppACLSubject = -67589, - errSecApplePublicKeyIncomplete = -67590, - errSecAppleSignatureMismatch = -67591, - errSecAppleInvalidKeyStartDate = -67592, - errSecAppleInvalidKeyEndDate = -67593, - errSecConversionError = -67594, - errSecAppleSSLv2Rollback = -67595, - errSecDiskFull = -34, - errSecQuotaExceeded = -67596, - errSecFileTooBig = -67597, - errSecInvalidDatabaseBlob = -67598, - errSecInvalidKeyBlob = -67599, - errSecIncompatibleDatabaseBlob = -67600, - errSecIncompatibleKeyBlob = -67601, - errSecHostNameMismatch = -67602, - errSecUnknownCriticalExtensionFlag = -67603, - errSecNoBasicConstraints = -67604, - errSecNoBasicConstraintsCA = -67605, - errSecInvalidAuthorityKeyID = -67606, - errSecInvalidSubjectKeyID = -67607, - errSecInvalidKeyUsageForPolicy = -67608, - errSecInvalidExtendedKeyUsage = -67609, - errSecInvalidIDLinkage = -67610, - errSecPathLengthConstraintExceeded = -67611, - errSecInvalidRoot = -67612, - errSecCRLExpired = -67613, - errSecCRLNotValidYet = -67614, - errSecCRLNotFound = -67615, - errSecCRLServerDown = -67616, - errSecCRLBadURI = -67617, - errSecUnknownCertExtension = -67618, - errSecUnknownCRLExtension = -67619, - errSecCRLNotTrusted = -67620, - errSecCRLPolicyFailed = -67621, - errSecIDPFailure = -67622, - errSecSMIMEEmailAddressesNotFound = -67623, - errSecSMIMEBadExtendedKeyUsage = -67624, - errSecSMIMEBadKeyUsage = -67625, - errSecSMIMEKeyUsageNotCritical = -67626, - errSecSMIMENoEmailAddress = -67627, - errSecSMIMESubjAltNameNotCritical = -67628, - errSecSSLBadExtendedKeyUsage = -67629, - errSecOCSPBadResponse = -67630, - errSecOCSPBadRequest = -67631, - errSecOCSPUnavailable = -67632, - errSecOCSPStatusUnrecognized = -67633, - errSecEndOfData = -67634, - errSecIncompleteCertRevocationCheck = -67635, - errSecNetworkFailure = -67636, - errSecOCSPNotTrustedToAnchor = -67637, - errSecRecordModified = -67638, - errSecOCSPSignatureError = -67639, - errSecOCSPNoSigner = -67640, - errSecOCSPResponderMalformedReq = -67641, - errSecOCSPResponderInternalError = -67642, - errSecOCSPResponderTryLater = -67643, - errSecOCSPResponderSignatureRequired = -67644, - errSecOCSPResponderUnauthorized = -67645, - errSecOCSPResponseNonceMismatch = -67646, - errSecCodeSigningBadCertChainLength = -67647, - errSecCodeSigningNoBasicConstraints = -67648, - errSecCodeSigningBadPathLengthConstraint= -67649, - errSecCodeSigningNoExtendedKeyUsage = -67650, - errSecCodeSigningDevelopment = -67651, - errSecResourceSignBadCertChainLength = -67652, - errSecResourceSignBadExtKeyUsage = -67653, - errSecTrustSettingDeny = -67654, - errSecInvalidSubjectName = -67655, - errSecUnknownQualifiedCertStatement = -67656, - errSecMobileMeRequestQueued = -67657, - errSecMobileMeRequestRedirected = -67658, - errSecMobileMeServerError = -67659, - errSecMobileMeServerNotAvailable = -67660, - errSecMobileMeServerAlreadyExists = -67661, - errSecMobileMeServerServiceErr = -67662, - errSecMobileMeRequestAlreadyPending = -67663, - errSecMobileMeNoRequestPending = -67664, - errSecMobileMeCSRVerifyFailure = -67665, - errSecMobileMeFailedConsistencyCheck = -67666, - errSecNotInitialized = -67667, - errSecInvalidHandleUsage = -67668, - errSecPVCReferentNotFound = -67669, - errSecFunctionIntegrityFail = -67670, - errSecInternalError = -67671, - errSecMemoryError = -67672, - errSecInvalidData = -67673, - errSecMDSError = -67674, - errSecInvalidPointer = -67675, - errSecSelfCheckFailed = -67676, - errSecFunctionFailed = -67677, - errSecModuleManifestVerifyFailed = -67678, - errSecInvalidGUID = -67679, - errSecInvalidHandle = -67680, - errSecInvalidDBList = -67681, - errSecInvalidPassthroughID = -67682, - errSecInvalidNetworkAddress = -67683, - errSecCRLAlreadySigned = -67684, - errSecInvalidNumberOfFields = -67685, - errSecVerificationFailure = -67686, - errSecUnknownTag = -67687, - errSecInvalidSignature = -67688, - errSecInvalidName = -67689, - errSecInvalidCertificateRef = -67690, - errSecInvalidCertificateGroup = -67691, - errSecTagNotFound = -67692, - errSecInvalidQuery = -67693, - errSecInvalidValue = -67694, - errSecCallbackFailed = -67695, - errSecACLDeleteFailed = -67696, - errSecACLReplaceFailed = -67697, - errSecACLAddFailed = -67698, - errSecACLChangeFailed = -67699, - errSecInvalidAccessCredentials = -67700, - errSecInvalidRecord = -67701, - errSecInvalidACL = -67702, - errSecInvalidSampleValue = -67703, - errSecIncompatibleVersion = -67704, - errSecPrivilegeNotGranted = -67705, - errSecInvalidScope = -67706, - errSecPVCAlreadyConfigured = -67707, - errSecInvalidPVC = -67708, - errSecEMMLoadFailed = -67709, - errSecEMMUnloadFailed = -67710, - errSecAddinLoadFailed = -67711, - errSecInvalidKeyRef = -67712, - errSecInvalidKeyHierarchy = -67713, - errSecAddinUnloadFailed = -67714, - errSecLibraryReferenceNotFound = -67715, - errSecInvalidAddinFunctionTable = -67716, - errSecInvalidServiceMask = -67717, - errSecModuleNotLoaded = -67718, - errSecInvalidSubServiceID = -67719, - errSecAttributeNotInContext = -67720, - errSecModuleManagerInitializeFailed = -67721, - errSecModuleManagerNotFound = -67722, - errSecEventNotificationCallbackNotFound = -67723, - errSecInputLengthError = -67724, - errSecOutputLengthError = -67725, - errSecPrivilegeNotSupported = -67726, - errSecDeviceError = -67727, - errSecAttachHandleBusy = -67728, - errSecNotLoggedIn = -67729, - errSecAlgorithmMismatch = -67730, - errSecKeyUsageIncorrect = -67731, - errSecKeyBlobTypeIncorrect = -67732, - errSecKeyHeaderInconsistent = -67733, - errSecUnsupportedKeyFormat = -67734, - errSecUnsupportedKeySize = -67735, - errSecInvalidKeyUsageMask = -67736, - errSecUnsupportedKeyUsageMask = -67737, - errSecInvalidKeyAttributeMask = -67738, - errSecUnsupportedKeyAttributeMask = -67739, - errSecInvalidKeyLabel = -67740, - errSecUnsupportedKeyLabel = -67741, - errSecInvalidKeyFormat = -67742, - errSecUnsupportedVectorOfBuffers = -67743, - errSecInvalidInputVector = -67744, - errSecInvalidOutputVector = -67745, - errSecInvalidContext = -67746, - errSecInvalidAlgorithm = -67747, - errSecInvalidAttributeKey = -67748, - errSecMissingAttributeKey = -67749, - errSecInvalidAttributeInitVector = -67750, - errSecMissingAttributeInitVector = -67751, - errSecInvalidAttributeSalt = -67752, - errSecMissingAttributeSalt = -67753, - errSecInvalidAttributePadding = -67754, - errSecMissingAttributePadding = -67755, - errSecInvalidAttributeRandom = -67756, - errSecMissingAttributeRandom = -67757, - errSecInvalidAttributeSeed = -67758, - errSecMissingAttributeSeed = -67759, - errSecInvalidAttributePassphrase = -67760, - errSecMissingAttributePassphrase = -67761, - errSecInvalidAttributeKeyLength = -67762, - errSecMissingAttributeKeyLength = -67763, - errSecInvalidAttributeBlockSize = -67764, - errSecMissingAttributeBlockSize = -67765, - errSecInvalidAttributeOutputSize = -67766, - errSecMissingAttributeOutputSize = -67767, - errSecInvalidAttributeRounds = -67768, - errSecMissingAttributeRounds = -67769, - errSecInvalidAlgorithmParms = -67770, - errSecMissingAlgorithmParms = -67771, - errSecInvalidAttributeLabel = -67772, - errSecMissingAttributeLabel = -67773, - errSecInvalidAttributeKeyType = -67774, - errSecMissingAttributeKeyType = -67775, - errSecInvalidAttributeMode = -67776, - errSecMissingAttributeMode = -67777, - errSecInvalidAttributeEffectiveBits = -67778, - errSecMissingAttributeEffectiveBits = -67779, - errSecInvalidAttributeStartDate = -67780, - errSecMissingAttributeStartDate = -67781, - errSecInvalidAttributeEndDate = -67782, - errSecMissingAttributeEndDate = -67783, - errSecInvalidAttributeVersion = -67784, - errSecMissingAttributeVersion = -67785, - errSecInvalidAttributePrime = -67786, - errSecMissingAttributePrime = -67787, - errSecInvalidAttributeBase = -67788, - errSecMissingAttributeBase = -67789, - errSecInvalidAttributeSubprime = -67790, - errSecMissingAttributeSubprime = -67791, - errSecInvalidAttributeIterationCount = -67792, - errSecMissingAttributeIterationCount = -67793, - errSecInvalidAttributeDLDBHandle = -67794, - errSecMissingAttributeDLDBHandle = -67795, - errSecInvalidAttributeAccessCredentials = -67796, - errSecMissingAttributeAccessCredentials = -67797, - errSecInvalidAttributePublicKeyFormat = -67798, - errSecMissingAttributePublicKeyFormat = -67799, - errSecInvalidAttributePrivateKeyFormat = -67800, - errSecMissingAttributePrivateKeyFormat = -67801, - errSecInvalidAttributeSymmetricKeyFormat = -67802, - errSecMissingAttributeSymmetricKeyFormat = -67803, - errSecInvalidAttributeWrappedKeyFormat = -67804, - errSecMissingAttributeWrappedKeyFormat = -67805, - errSecStagedOperationInProgress = -67806, - errSecStagedOperationNotStarted = -67807, - errSecVerifyFailed = -67808, - errSecQuerySizeUnknown = -67809, - errSecBlockSizeMismatch = -67810, - errSecPublicKeyInconsistent = -67811, - errSecDeviceVerifyFailed = -67812, - errSecInvalidLoginName = -67813, - errSecAlreadyLoggedIn = -67814, - errSecInvalidDigestAlgorithm = -67815, - errSecInvalidCRLGroup = -67816, - errSecCertificateCannotOperate = -67817, - errSecCertificateExpired = -67818, - errSecCertificateNotValidYet = -67819, - errSecCertificateRevoked = -67820, - errSecCertificateSuspended = -67821, - errSecInsufficientCredentials = -67822, - errSecInvalidAction = -67823, - errSecInvalidAuthority = -67824, - errSecVerifyActionFailed = -67825, - errSecInvalidCertAuthority = -67826, - errSecInvaldCRLAuthority = -67827, - errSecInvalidCRLEncoding = -67828, - errSecInvalidCRLType = -67829, - errSecInvalidCRL = -67830, - errSecInvalidFormType = -67831, - errSecInvalidID = -67832, - errSecInvalidIdentifier = -67833, - errSecInvalidIndex = -67834, - errSecInvalidPolicyIdentifiers = -67835, - errSecInvalidTimeString = -67836, - errSecInvalidReason = -67837, - errSecInvalidRequestInputs = -67838, - errSecInvalidResponseVector = -67839, - errSecInvalidStopOnPolicy = -67840, - errSecInvalidTuple = -67841, - errSecMultipleValuesUnsupported = -67842, - errSecNotTrusted = -67843, - errSecNoDefaultAuthority = -67844, - errSecRejectedForm = -67845, - errSecRequestLost = -67846, - errSecRequestRejected = -67847, - errSecUnsupportedAddressType = -67848, - errSecUnsupportedService = -67849, - errSecInvalidTupleGroup = -67850, - errSecInvalidBaseACLs = -67851, - errSecInvalidTupleCredendtials = -67852, - errSecInvalidEncoding = -67853, - errSecInvalidValidityPeriod = -67854, - errSecInvalidRequestor = -67855, - errSecRequestDescriptor = -67856, - errSecInvalidBundleInfo = -67857, - errSecInvalidCRLIndex = -67858, - errSecNoFieldValues = -67859, - errSecUnsupportedFieldFormat = -67860, - errSecUnsupportedIndexInfo = -67861, - errSecUnsupportedLocality = -67862, - errSecUnsupportedNumAttributes = -67863, - errSecUnsupportedNumIndexes = -67864, - errSecUnsupportedNumRecordTypes = -67865, - errSecFieldSpecifiedMultiple = -67866, - errSecIncompatibleFieldFormat = -67867, - errSecInvalidParsingModule = -67868, - errSecDatabaseLocked = -67869, - errSecDatastoreIsOpen = -67870, - errSecMissingValue = -67871, - errSecUnsupportedQueryLimits = -67872, - errSecUnsupportedNumSelectionPreds = -67873, - errSecUnsupportedOperator = -67874, - errSecInvalidDBLocation = -67875, - errSecInvalidAccessRequest = -67876, - errSecInvalidIndexInfo = -67877, - errSecInvalidNewOwner = -67878, - errSecInvalidModifyMode = -67879, - errSecMissingRequiredExtension = -67880, - errSecExtendedKeyUsageNotCritical = -67881, - errSecTimestampMissing = -67882, - errSecTimestampInvalid = -67883, - errSecTimestampNotTrusted = -67884, - errSecTimestampServiceNotAvailable = -67885, - errSecTimestampBadAlg = -67886, - errSecTimestampBadRequest = -67887, - errSecTimestampBadDataFormat = -67888, - errSecTimestampTimeNotAvailable = -67889, - errSecTimestampUnacceptedPolicy = -67890, - errSecTimestampUnacceptedExtension = -67891, - errSecTimestampAddInfoNotAvailable = -67892, - errSecTimestampSystemFailure = -67893, - errSecSigningTimeMissing = -67894, - errSecTimestampRejection = -67895, - errSecTimestampWaiting = -67896, - errSecTimestampRevocationWarning = -67897, - errSecTimestampRevocationNotification = -67898, -}; - - - - - -} -extern "C" { - - - - - -typedef UInt32 SecAccessOwnerType; -enum -{ - kSecUseOnlyUID = 1, - kSecUseOnlyGID = 2, - kSecHonorRoot = 0x100, - kSecMatchBits = (kSecUseOnlyUID | kSecUseOnlyGID) -}; - - - -extern const CFStringRef kSecACLAuthorizationAny - __attribute__((availability(macosx,introduced=10.7))); - -extern const CFStringRef kSecACLAuthorizationLogin - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationGenKey - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationDelete - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationExportWrapped - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationExportClear - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationImportWrapped - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationImportClear - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationSign - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationEncrypt - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationDecrypt - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationMAC - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationDerive - __attribute__((availability(macosx,introduced=10.7))); - - -extern const CFStringRef kSecACLAuthorizationKeychainCreate - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationKeychainDelete - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationKeychainItemRead - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationKeychainItemInsert - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationKeychainItemModify - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationKeychainItemDelete - __attribute__((availability(macosx,introduced=10.7))); - -extern const CFStringRef kSecACLAuthorizationChangeACL - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecACLAuthorizationChangeOwner - __attribute__((availability(macosx,introduced=10.7))); - - - - - - -CFTypeID SecAccessGetTypeID(void); -OSStatus SecAccessCreate(CFStringRef descriptor, CFArrayRef _Nullable trustedlist, SecAccessRef * _Nonnull __attribute__((cf_returns_retained)) accessRef); -OSStatus SecAccessCreateFromOwnerAndACL(const CSSM_ACL_OWNER_PROTOTYPE *owner, uint32 aclCount, const CSSM_ACL_ENTRY_INFO *acls, SecAccessRef * _Nonnull __attribute__((cf_returns_retained)) accessRef) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -_Nullable -SecAccessRef SecAccessCreateWithOwnerAndACL(uid_t userId, gid_t groupId, SecAccessOwnerType ownerType, CFArrayRef _Nullable acls, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus SecAccessGetOwnerAndACL(SecAccessRef accessRef, CSSM_ACL_OWNER_PROTOTYPE_PTR _Nullable * _Nonnull owner, uint32 *aclCount, CSSM_ACL_ENTRY_INFO_PTR _Nullable * _Nonnull acls) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecAccessCopyOwnerAndACL(SecAccessRef accessRef, uid_t * _Nullable userId, gid_t * _Nullable groupId, SecAccessOwnerType * _Nullable ownerType, CFArrayRef * _Nullable __attribute__((cf_returns_retained)) aclList) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus SecAccessCopyACLList(SecAccessRef accessRef, CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) aclList); -OSStatus SecAccessCopySelectedACLList(SecAccessRef accessRef, CSSM_ACL_AUTHORIZATION_TAG action, CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) aclList) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -_Nullable -CFArrayRef SecAccessCopyMatchingACLList(SecAccessRef accessRef, CFTypeRef authorizationTag) - __attribute__((availability(macosx,introduced=10.7))); - - - - - -} -extern "C" { -CFTypeID SecAccessControlGetTypeID(void) -__attribute__((availability(macosx,introduced=10.10))); - -typedef CFIndex SecAccessControlCreateFlags; enum { - kSecAccessControlUserPresence = 1 << 0, - kSecAccessControlTouchIDAny __attribute__((availability(macosx,introduced=NA))) = 1 << 1, - kSecAccessControlTouchIDCurrentSet __attribute__((availability(macosx,introduced=NA))) = 1 << 3, - kSecAccessControlDevicePasscode __attribute__((availability(macosx,introduced=10_11))) = 1 << 4, - kSecAccessControlOr __attribute__((availability(macosx,introduced=NA))) = 1 << 14, - kSecAccessControlAnd __attribute__((availability(macosx,introduced=NA))) = 1 << 15, - kSecAccessControlPrivateKeyUsage __attribute__((availability(macosx,introduced=NA))) = 1 << 30, - kSecAccessControlApplicationPassword __attribute__((availability(macosx,introduced=NA))) = 1 << 31, -} __attribute__((availability(macosx,introduced=10.10))); -_Nullable -SecAccessControlRef SecAccessControlCreateWithFlags(CFAllocatorRef _Nullable allocator, CFTypeRef protection, - SecAccessControlCreateFlags flags, CFErrorRef *error) -__attribute__((availability(macosx,introduced=10.10))); - - - - -} -extern "C" { - - - - - - typedef uint16 SecKeychainPromptSelector; enum - { - kSecKeychainPromptRequirePassphase = 0x0001, - - kSecKeychainPromptUnsigned = 0x0010, - kSecKeychainPromptUnsignedAct = 0x0020, - kSecKeychainPromptInvalid = 0x0040, - kSecKeychainPromptInvalidAct = 0x0080, - }; - - - - - - - - CFTypeID SecACLGetTypeID(void) - __attribute__((availability(macosx,introduced=10.3))); - OSStatus SecACLCreateFromSimpleContents(SecAccessRef access, - CFArrayRef _Nullable applicationList, - CFStringRef description, - const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector, - SecACLRef * _Nonnull __attribute__((cf_returns_retained)) newAcl) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - OSStatus SecACLCreateWithSimpleContents(SecAccessRef access, - CFArrayRef _Nullable applicationList, - CFStringRef description, - SecKeychainPromptSelector promptSelector, - SecACLRef * _Nonnull __attribute__((cf_returns_retained)) newAcl) - __attribute__((availability(macosx,introduced=10.7))); - - - - - - - - OSStatus SecACLRemove(SecACLRef aclRef) - __attribute__((availability(macosx,introduced=10.3))); - OSStatus SecACLCopySimpleContents(SecACLRef acl, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) applicationList, - CFStringRef * _Nonnull __attribute__((cf_returns_retained)) description, - CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - OSStatus SecACLCopyContents(SecACLRef acl, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) applicationList, - CFStringRef * _Nonnull __attribute__((cf_returns_retained)) description, - SecKeychainPromptSelector *promptSelector) - __attribute__((availability(macosx,introduced=10.7))); - OSStatus SecACLSetSimpleContents(SecACLRef acl, - CFArrayRef _Nullable applicationList, - CFStringRef description, - const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - OSStatus SecACLSetContents(SecACLRef acl, - CFArrayRef _Nullable applicationList, - CFStringRef description, - SecKeychainPromptSelector promptSelector) - __attribute__((availability(macosx,introduced=10.7))); - OSStatus SecACLGetAuthorizations(SecACLRef acl, - CSSM_ACL_AUTHORIZATION_TAG *tags, uint32 *tagCount) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - - CFArrayRef SecACLCopyAuthorizations(SecACLRef acl) - __attribute__((availability(macosx,introduced=10.7))); - OSStatus SecACLSetAuthorizations(SecACLRef acl, - CSSM_ACL_AUTHORIZATION_TAG *tags, uint32 tagCount) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - OSStatus SecACLUpdateAuthorizations(SecACLRef acl, CFArrayRef authorizations) - __attribute__((availability(macosx,introduced=10.7))); - - - - - -} -extern "C" { -enum -{ - kSecSubjectItemAttr = 'subj', - kSecIssuerItemAttr = 'issu', - kSecSerialNumberItemAttr = 'snbr', - kSecPublicKeyHashItemAttr = 'hpky', - kSecSubjectKeyIdentifierItemAttr = 'skid', - kSecCertTypeItemAttr = 'ctyp', - kSecCertEncodingItemAttr = 'cenc' -} ; - - - - - - -CFTypeID SecCertificateGetTypeID(void) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecCertificateCreateFromData(const CSSM_DATA *data, CSSM_CERT_TYPE type, CSSM_CERT_ENCODING encoding, SecCertificateRef * _Nonnull __attribute__((cf_returns_retained)) certificate) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -_Nullable -SecCertificateRef SecCertificateCreateWithData(CFAllocatorRef _Nullable allocator, CFDataRef data) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus SecCertificateAddToKeychain(SecCertificateRef certificate, SecKeychainRef _Nullable keychain) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecCertificateGetData(SecCertificateRef certificate, CSSM_DATA_PTR data) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - -CFDataRef SecCertificateCopyData(SecCertificateRef certificate) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus SecCertificateGetType(SecCertificateRef certificate, CSSM_CERT_TYPE *certificateType) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecCertificateGetSubject(SecCertificateRef certificate, const CSSM_X509_NAME * _Nullable * _Nonnull subject) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecCertificateGetIssuer(SecCertificateRef certificate, const CSSM_X509_NAME * _Nullable * _Nonnull issuer) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecCertificateGetCLHandle(SecCertificateRef certificate, CSSM_CL_HANDLE *clHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecCertificateGetAlgorithmID(SecCertificateRef certificate, const CSSM_X509_ALGORITHM_IDENTIFIER * _Nullable * _Nonnull algid) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecCertificateCopyPublicKey(SecCertificateRef certificate, SecKeyRef * _Nonnull __attribute__((cf_returns_retained)) key) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecCertificateCopyCommonName(SecCertificateRef certificate, CFStringRef * _Nonnull __attribute__((cf_returns_retained)) commonName) - __attribute__((availability(macosx,introduced=10.5))); -CFStringRef SecCertificateCopySubjectSummary(SecCertificateRef certificate) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus SecCertificateCopyEmailAddresses(SecCertificateRef certificate, CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) emailAddresses) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus SecCertificateCopyPreference(CFStringRef name, uint32 keyUsage, SecCertificateRef * _Nonnull __attribute__((cf_returns_retained)) certificate) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -_Nullable -SecCertificateRef SecCertificateCopyPreferred(CFStringRef name, CFArrayRef _Nullable keyUsage) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus SecCertificateSetPreference(SecCertificateRef certificate, CFStringRef name, uint32 keyUsage, CFDateRef _Nullable date) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus SecCertificateSetPreferred(SecCertificateRef _Nullable certificate, CFStringRef name, CFArrayRef _Nullable keyUsage) - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyKeyType __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyKeyLabel __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyKeyLocalizedLabel __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyKeyValue __attribute__((availability(macosx,introduced=10.7))); - - - - - - -extern const CFStringRef kSecPropertyTypeWarning __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyTypeSuccess __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyTypeSection __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyTypeData __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyTypeString __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyTypeURL __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyTypeDate __attribute__((availability(macosx,introduced=10.7))); -_Nullable -CFDictionaryRef SecCertificateCopyValues(SecCertificateRef certificate, CFArrayRef _Nullable keys, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecCertificateUsageSigning __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecCertificateUsageSigningAndEncrypting __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecCertificateUsageDeriveAndSign __attribute__((availability(macosx,introduced=10.7))); -_Nullable -CFStringRef SecCertificateCopyLongDescription(CFAllocatorRef _Nullable alloc, SecCertificateRef certificate, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -CFStringRef SecCertificateCopyShortDescription(CFAllocatorRef _Nullable alloc, SecCertificateRef certificate, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -CFDataRef SecCertificateCopySerialNumber(SecCertificateRef certificate, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -CFDataRef SecCertificateCopyNormalizedIssuerContent(SecCertificateRef certificate, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -CFDataRef SecCertificateCopyNormalizedSubjectContent(SecCertificateRef certificate, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); - - - - - -} -extern "C" { - - - - -extern const CFStringRef kSecOIDADC_CERT_POLICY __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_CERT_POLICY __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EKU_CODE_SIGNING __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EKU_CODE_SIGNING_DEV __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EKU_ICHAT_ENCRYPTION __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EKU_ICHAT_SIGNING __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EKU_RESOURCE_SIGNING __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EKU_SYSTEM_IDENTITY __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_ADC_APPLE_SIGNING __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_ADC_DEV_SIGNING __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_APPLE_SIGNING __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_CODE_SIGNING __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_INTERMEDIATE_MARKER __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_WWDR_INTERMEDIATE __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_ITMS_INTERMEDIATE __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_AAI_INTERMEDIATE __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_APPLEID_INTERMEDIATE __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAuthorityInfoAccess __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDAuthorityKeyIdentifier __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDBasicConstraints __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDBiometricInfo __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCSSMKeyStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCertIssuer __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCertificatePolicies __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDClientAuth __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCollectiveStateProvinceName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCollectiveStreetAddress __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCommonName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCountryName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCrlDistributionPoints __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCrlNumber __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDCrlReason __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDDOTMAC_CERT_EMAIL_ENCRYPT __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDDOTMAC_CERT_EMAIL_SIGN __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDDOTMAC_CERT_EXTENSION __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDDOTMAC_CERT_IDENTITY __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDDOTMAC_CERT_POLICY __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDDeltaCrlIndicator __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDDescription __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDEKU_IPSec __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDEmailAddress __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDEmailProtection __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDExtendedKeyUsage __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDExtendedKeyUsageAny __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDExtendedUseCodeSigning __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDGivenName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDHoldInstructionCode __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDInvalidityDate __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDIssuerAltName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDIssuingDistributionPoint __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDIssuingDistributionPoints __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDKERBv5_PKINIT_KP_CLIENT_AUTH __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDKERBv5_PKINIT_KP_KDC __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDKeyUsage __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDLocalityName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDMS_NTPrincipalName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDMicrosoftSGC __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDNameConstraints __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDNetscapeCertSequence __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDNetscapeCertType __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDNetscapeSGC __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDOCSPSigning __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDOrganizationName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDOrganizationalUnitName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDPolicyConstraints __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDPolicyMappings __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDPrivateKeyUsagePeriod __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDQC_Statements __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSerialNumber __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDServerAuth __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDStateProvinceName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDStreetAddress __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSubjectAltName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSubjectDirectoryAttributes __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSubjectEmailAddress __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSubjectInfoAccess __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSubjectKeyIdentifier __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSubjectPicture __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSubjectSignatureBitmap __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSurname __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDTimeStamping __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDTitle __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDUseExemptions __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1CertificateIssuerUniqueId __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1CertificateSubjectUniqueId __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1IssuerName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1IssuerNameCStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1IssuerNameLDAP __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1IssuerNameStd __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SerialNumber __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1Signature __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SignatureAlgorithm __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SignatureAlgorithmParameters __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SignatureAlgorithmTBS __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SignatureCStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SignatureStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SubjectName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SubjectNameCStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SubjectNameLDAP __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SubjectNameStd __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SubjectPublicKey __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SubjectPublicKeyAlgorithm __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SubjectPublicKeyAlgorithmParameters __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1SubjectPublicKeyCStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1ValidityNotAfter __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1ValidityNotBefore __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V1Version __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3Certificate __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateCStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateExtensionCStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateExtensionCritical __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateExtensionId __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateExtensionStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateExtensionType __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateExtensionValue __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateExtensionsCStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateExtensionsStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3CertificateNumberOfExtensions __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3SignedCertificate __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDX509V3SignedCertificateCStruct __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecOIDSRVName __attribute__((availability(macosx,introduced=10.8))); - - - - -} -extern "C" { -CFTypeID SecIdentityGetTypeID(void) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecIdentityCreateWithCertificate( - CFTypeRef _Nullable keychainOrArray, - SecCertificateRef certificateRef, - SecIdentityRef * _Nonnull __attribute__((cf_returns_retained)) identityRef) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus SecIdentityCopyCertificate( - SecIdentityRef identityRef, - SecCertificateRef * _Nonnull __attribute__((cf_returns_retained)) certificateRef) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecIdentityCopyPrivateKey( - SecIdentityRef identityRef, - SecKeyRef * _Nonnull __attribute__((cf_returns_retained)) privateKeyRef) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecIdentityCopyPreference(CFStringRef name, CSSM_KEYUSE keyUsage, CFArrayRef _Nullable validIssuers, SecIdentityRef * _Nonnull __attribute__((cf_returns_retained)) identity) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -_Nullable -SecIdentityRef SecIdentityCopyPreferred(CFStringRef name, CFArrayRef _Nullable keyUsage, CFArrayRef _Nullable validIssuers) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus SecIdentitySetPreference(SecIdentityRef identity, CFStringRef name, CSSM_KEYUSE keyUsage) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecIdentitySetPreferred(SecIdentityRef _Nullable identity, CFStringRef name, CFArrayRef _Nullable keyUsage) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus SecIdentityCopySystemIdentity( - CFStringRef domain, - SecIdentityRef * _Nonnull __attribute__((cf_returns_retained)) idRef, - CFStringRef * _Nullable __attribute__((cf_returns_retained)) actualDomain) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus SecIdentitySetSystemIdentity( - CFStringRef domain, - SecIdentityRef _Nullable idRef) - __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kSecIdentityDomainDefault __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kSecIdentityDomainKerberosKDC __attribute__((availability(macosx,introduced=10.5))); - - - - - -} -extern "C" { -typedef struct __attribute__((objc_bridge(id))) OpaqueSecIdentitySearchRef *SecIdentitySearchRef; - - - - - - - -CFTypeID SecIdentitySearchGetTypeID(void) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecIdentitySearchCreate(CFTypeRef _Nullable keychainOrArray, CSSM_KEYUSE keyUsage, SecIdentitySearchRef * _Nullable __attribute__((cf_returns_retained)) searchRef) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecIdentitySearchCopyNext(SecIdentitySearchRef searchRef, SecIdentityRef * _Nullable __attribute__((cf_returns_retained)) identity) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -} -extern "C" { -extern const CFStringRef kSecClass - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecClassInternetPassword - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecClassGenericPassword - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecClassCertificate - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecClassKey - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecClassIdentity - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrAccessible - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrAccess - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrAccessControl - __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kSecAttrAccessGroup - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrSynchronizable - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrSynchronizableAny - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrCreationDate - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrModificationDate - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrDescription - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrComment - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCreator - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrType - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrLabel - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrIsInvisible - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrIsNegative - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAccount - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrService - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrGeneric - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrSecurityDomain - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrServer - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocol - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAuthenticationType - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrPort - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrPath - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrSubject - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrIssuer - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrSerialNumber - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrSubjectKeyID - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrPublicKeyHash - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCertificateType - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCertificateEncoding - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrKeyClass - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrApplicationLabel - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrIsPermanent - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrIsSensitive - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrIsExtractable - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrApplicationTag - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrKeyType - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrPRF - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrSalt - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrRounds - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeySizeInBits - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrEffectiveKeySize - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCanEncrypt - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCanDecrypt - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCanDerive - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCanSign - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCanVerify - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCanWrap - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrCanUnwrap - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAccessibleWhenUnlocked - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrAccessibleAfterFirstUnlock - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrAccessibleAlways - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly - __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kSecAttrAccessibleWhenUnlockedThisDeviceOnly - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrAccessibleAlwaysThisDeviceOnly - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrProtocolFTP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolFTPAccount - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolHTTP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolIRC - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolNNTP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolPOP3 - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolSMTP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolSOCKS - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolIMAP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolLDAP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolAppleTalk - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolAFP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolTelnet - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolSSH - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolFTPS - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolHTTPS - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolHTTPProxy - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolHTTPSProxy - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolFTPProxy - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolSMB - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolRTSP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolRTSPProxy - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolDAAP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolEPPC - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolIPP - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolNNTPS - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolLDAPS - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolTelnetS - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolIMAPS - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolIRCS - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrProtocolPOP3S - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAuthenticationTypeNTLM - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAuthenticationTypeMSN - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAuthenticationTypeDPA - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAuthenticationTypeRPA - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAuthenticationTypeHTTPBasic - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAuthenticationTypeHTTPDigest - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAuthenticationTypeHTMLForm - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrAuthenticationTypeDefault - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecAttrKeyClassPublic - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyClassPrivate - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyClassSymmetric - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyTypeRSA - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyTypeDSA - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyTypeAES - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyTypeDES - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyType3DES - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyTypeRC4 - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyTypeRC2 - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyTypeCAST - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyTypeECDSA - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrKeyTypeEC - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecAttrPRFHmacAlgSHA1 - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrPRFHmacAlgSHA224 - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrPRFHmacAlgSHA256 - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrPRFHmacAlgSHA384 - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecAttrPRFHmacAlgSHA512 - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecMatchPolicy - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchItemList - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchSearchList - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchIssuers - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchEmailAddressIfPresent - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchSubjectContains - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchSubjectStartsWith - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecMatchSubjectEndsWith - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecMatchSubjectWholeString - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecMatchCaseInsensitive - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchDiacriticInsensitive - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecMatchWidthInsensitive - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecMatchTrustedOnly - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchValidOnDate - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchLimit - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchLimitOne - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecMatchLimitAll - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecReturnData - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecReturnAttributes - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecReturnRef - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecReturnPersistentRef - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecValueData - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecValueRef - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecValuePersistentRef - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecUseItemList - __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kSecUseKeychain - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecUseOperationPrompt - __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kSecUseAuthenticationUI - __attribute__((availability(macosx,introduced=10.11))); -extern const CFStringRef kSecUseAuthenticationContext - __attribute__((availability(macosx,introduced=10.11))); -extern const CFStringRef kSecUseAuthenticationUIAllow - __attribute__((availability(macosx,introduced=10.11))); -extern const CFStringRef kSecUseAuthenticationUIFail - __attribute__((availability(macosx,introduced=10.11))); -extern const CFStringRef kSecUseAuthenticationUISkip - __attribute__((availability(macosx,introduced=10.11))); -OSStatus SecItemCopyMatching(CFDictionaryRef query, CFTypeRef * _Nullable __attribute__((cf_returns_retained)) result) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus SecItemAdd(CFDictionaryRef attributes, CFTypeRef * _Nullable __attribute__((cf_returns_retained)) result) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus SecItemUpdate(CFDictionaryRef query, CFDictionaryRef attributesToUpdate) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus SecItemDelete(CFDictionaryRef query) - __attribute__((availability(macosx,introduced=10.6))); - - - - - -} -extern "C" { -enum -{ - kSecKeyKeyClass = 0, - kSecKeyPrintName = 1, - kSecKeyAlias = 2, - kSecKeyPermanent = 3, - kSecKeyPrivate = 4, - kSecKeyModifiable = 5, - kSecKeyLabel = 6, - kSecKeyApplicationTag = 7, - kSecKeyKeyCreator = 8, - kSecKeyKeyType = 9, - kSecKeyKeySizeInBits = 10, - kSecKeyEffectiveKeySize = 11, - kSecKeyStartDate = 12, - kSecKeyEndDate = 13, - kSecKeySensitive = 14, - kSecKeyAlwaysSensitive = 15, - kSecKeyExtractable = 16, - kSecKeyNeverExtractable = 17, - kSecKeyEncrypt = 18, - kSecKeyDecrypt = 19, - kSecKeyDerive = 20, - kSecKeySign = 21, - kSecKeyVerify = 22, - kSecKeySignRecover = 23, - kSecKeyVerifyRecover = 24, - kSecKeyWrap = 25, - kSecKeyUnwrap = 26 -}; -typedef uint32 SecCredentialType; enum -{ - kSecCredentialTypeDefault = 0, - kSecCredentialTypeWithUI, - kSecCredentialTypeNoUI -}; - - - - - -typedef uint32_t SecPadding; enum -{ - kSecPaddingNone = 0, - kSecPaddingPKCS1 = 1, - - - - - kSecPaddingSigRaw = 0x4000, - - - - - kSecPaddingPKCS1MD2 = 0x8000, - - - - - kSecPaddingPKCS1MD5 = 0x8001, - - - - - kSecPaddingPKCS1SHA1 = 0x8002, -}; - - - - - -typedef uint32_t SecKeySizes; enum -{ - kSecDefaultKeySize = 0, - - - kSec3DES192 = 192, - kSecAES128 = 128, - kSecAES192 = 192, - kSecAES256 = 256, - - - - kSecp192r1 = 192, - kSecp256r1 = 256, - kSecp384r1 = 384, - kSecp521r1 = 521, - - - - kSecRSAMin = 1024, - kSecRSAMax = 4096 -}; -extern const CFStringRef kSecPrivateKeyAttrs - __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kSecPublicKeyAttrs - __attribute__((availability(macosx,introduced=10.8))); - - - - - - - -CFTypeID SecKeyGetTypeID(void) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecKeyCreatePair( - SecKeychainRef _Nullable keychainRef, - CSSM_ALGORITHMS algorithm, - uint32 keySizeInBits, - CSSM_CC_HANDLE contextHandle, - CSSM_KEYUSE publicKeyUsage, - uint32 publicKeyAttr, - CSSM_KEYUSE privateKeyUsage, - uint32 privateKeyAttr, - SecAccessRef _Nullable initialAccess, - SecKeyRef* _Nullable __attribute__((cf_returns_retained)) publicKey, - SecKeyRef* _Nullable __attribute__((cf_returns_retained)) privateKey) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecKeyGenerate( - SecKeychainRef _Nullable keychainRef, - CSSM_ALGORITHMS algorithm, - uint32 keySizeInBits, - CSSM_CC_HANDLE contextHandle, - CSSM_KEYUSE keyUsage, - uint32 keyAttr, - SecAccessRef _Nullable initialAccess, - SecKeyRef* _Nullable __attribute__((cf_returns_retained)) keyRef) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecKeyGetCSSMKey(SecKeyRef key, const CSSM_KEY * _Nullable * _Nonnull cssmKey) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7)));; -OSStatus SecKeyGetCSPHandle(SecKeyRef keyRef, CSSM_CSP_HANDLE *cspHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecKeyGetCredentials( - SecKeyRef keyRef, - CSSM_ACL_AUTHORIZATION_TAG operation, - SecCredentialType credentialType, - const CSSM_ACCESS_CREDENTIALS * _Nullable * _Nonnull outCredentials) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -size_t SecKeyGetBlockSize(SecKeyRef key) - __attribute__((availability(macosx,introduced=10.6))); -_Nullable -SecKeyRef SecKeyGenerateSymmetric(CFDictionaryRef parameters, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -SecKeyRef SecKeyCreateFromData(CFDictionaryRef parameters, - CFDataRef keyData, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus SecKeyGeneratePair(CFDictionaryRef parameters, - SecKeyRef * _Nullable __attribute__((cf_returns_retained)) publicKey, SecKeyRef * _Nullable __attribute__((cf_returns_retained)) privateKey) - __attribute__((availability(macosx,introduced=10.7))); -typedef void (*SecKeyGeneratePairBlock)(SecKeyRef publicKey, SecKeyRef privateKey, CFErrorRef error); -void SecKeyGeneratePairAsync(CFDictionaryRef parameters, - dispatch_queue_t deliveryQueue, SecKeyGeneratePairBlock result) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -SecKeyRef SecKeyDeriveFromPassword(CFStringRef password, - CFDictionaryRef parameters, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -CFDataRef SecKeyWrapSymmetric(SecKeyRef keyToWrap, - SecKeyRef wrappingKey, CFDictionaryRef parameters, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -SecKeyRef SecKeyUnwrapSymmetric(CFDataRef _Nullable * _Nonnull keyToUnwrap, - SecKeyRef unwrappingKey, CFDictionaryRef parameters, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); - - - - - -} -extern "C" { -enum -{ - kSecUnlockStateStatus = 1, - kSecReadPermStatus = 2, - kSecWritePermStatus = 4 -}; -struct SecKeychainSettings -{ - UInt32 version; - Boolean lockOnSleep; - Boolean useLockInterval; - UInt32 lockInterval; -}; -typedef struct SecKeychainSettings SecKeychainSettings; -typedef FourCharCode SecAuthenticationType; enum -{ - kSecAuthenticationTypeNTLM = ((__uint32_t)((((__uint32_t)('ntlm') & 0xff000000) >> 24) | (((__uint32_t)('ntlm') & 0x00ff0000) >> 8) | (((__uint32_t)('ntlm') & 0x0000ff00) << 8) | (((__uint32_t)('ntlm') & 0x000000ff) << 24))), - kSecAuthenticationTypeMSN = ((__uint32_t)((((__uint32_t)('msna') & 0xff000000) >> 24) | (((__uint32_t)('msna') & 0x00ff0000) >> 8) | (((__uint32_t)('msna') & 0x0000ff00) << 8) | (((__uint32_t)('msna') & 0x000000ff) << 24))), - kSecAuthenticationTypeDPA = ((__uint32_t)((((__uint32_t)('dpaa') & 0xff000000) >> 24) | (((__uint32_t)('dpaa') & 0x00ff0000) >> 8) | (((__uint32_t)('dpaa') & 0x0000ff00) << 8) | (((__uint32_t)('dpaa') & 0x000000ff) << 24))), - kSecAuthenticationTypeRPA = ((__uint32_t)((((__uint32_t)('rpaa') & 0xff000000) >> 24) | (((__uint32_t)('rpaa') & 0x00ff0000) >> 8) | (((__uint32_t)('rpaa') & 0x0000ff00) << 8) | (((__uint32_t)('rpaa') & 0x000000ff) << 24))), - kSecAuthenticationTypeHTTPBasic = ((__uint32_t)((((__uint32_t)('http') & 0xff000000) >> 24) | (((__uint32_t)('http') & 0x00ff0000) >> 8) | (((__uint32_t)('http') & 0x0000ff00) << 8) | (((__uint32_t)('http') & 0x000000ff) << 24))), - kSecAuthenticationTypeHTTPDigest = ((__uint32_t)((((__uint32_t)('httd') & 0xff000000) >> 24) | (((__uint32_t)('httd') & 0x00ff0000) >> 8) | (((__uint32_t)('httd') & 0x0000ff00) << 8) | (((__uint32_t)('httd') & 0x000000ff) << 24))), - kSecAuthenticationTypeHTMLForm = ((__uint32_t)((((__uint32_t)('form') & 0xff000000) >> 24) | (((__uint32_t)('form') & 0x00ff0000) >> 8) | (((__uint32_t)('form') & 0x0000ff00) << 8) | (((__uint32_t)('form') & 0x000000ff) << 24))), - kSecAuthenticationTypeDefault = ((__uint32_t)((((__uint32_t)('dflt') & 0xff000000) >> 24) | (((__uint32_t)('dflt') & 0x00ff0000) >> 8) | (((__uint32_t)('dflt') & 0x0000ff00) << 8) | (((__uint32_t)('dflt') & 0x000000ff) << 24))), - kSecAuthenticationTypeAny = ((__uint32_t)((((__uint32_t)(0) & 0xff000000) >> 24) | (((__uint32_t)(0) & 0x00ff0000) >> 8) | (((__uint32_t)(0) & 0x0000ff00) << 8) | (((__uint32_t)(0) & 0x000000ff) << 24))) -}; -typedef FourCharCode SecProtocolType; enum -{ - kSecProtocolTypeFTP = 'ftp ', - kSecProtocolTypeFTPAccount = 'ftpa', - kSecProtocolTypeHTTP = 'http', - kSecProtocolTypeIRC = 'irc ', - kSecProtocolTypeNNTP = 'nntp', - kSecProtocolTypePOP3 = 'pop3', - kSecProtocolTypeSMTP = 'smtp', - kSecProtocolTypeSOCKS = 'sox ', - kSecProtocolTypeIMAP = 'imap', - kSecProtocolTypeLDAP = 'ldap', - kSecProtocolTypeAppleTalk = 'atlk', - kSecProtocolTypeAFP = 'afp ', - kSecProtocolTypeTelnet = 'teln', - kSecProtocolTypeSSH = 'ssh ', - kSecProtocolTypeFTPS = 'ftps', - kSecProtocolTypeHTTPS = 'htps', - kSecProtocolTypeHTTPProxy = 'htpx', - kSecProtocolTypeHTTPSProxy = 'htsx', - kSecProtocolTypeFTPProxy = 'ftpx', - kSecProtocolTypeCIFS = 'cifs', - kSecProtocolTypeSMB = 'smb ', - kSecProtocolTypeRTSP = 'rtsp', - kSecProtocolTypeRTSPProxy = 'rtsx', - kSecProtocolTypeDAAP = 'daap', - kSecProtocolTypeEPPC = 'eppc', - kSecProtocolTypeIPP = 'ipp ', - kSecProtocolTypeNNTPS = 'ntps', - kSecProtocolTypeLDAPS = 'ldps', - kSecProtocolTypeTelnetS = 'tels', - kSecProtocolTypeIMAPS = 'imps', - kSecProtocolTypeIRCS = 'ircs', - kSecProtocolTypePOP3S = 'pops', - kSecProtocolTypeCVSpserver = 'cvsp', - kSecProtocolTypeSVN = 'svn ', - kSecProtocolTypeAny = 0 -}; -typedef UInt32 SecKeychainEvent; enum -{ - kSecLockEvent = 1, - kSecUnlockEvent = 2, - kSecAddEvent = 3, - kSecDeleteEvent = 4, - kSecUpdateEvent = 5, - kSecPasswordChangedEvent = 6, - kSecDefaultChangedEvent = 9, - kSecDataAccessEvent = 10, - kSecKeychainListChangedEvent = 11, - kSecTrustSettingsChangedEvent = 12 -}; -typedef UInt32 SecKeychainEventMask; enum -{ - kSecLockEventMask = 1 << kSecLockEvent, - kSecUnlockEventMask = 1 << kSecUnlockEvent, - kSecAddEventMask = 1 << kSecAddEvent, - kSecDeleteEventMask = 1 << kSecDeleteEvent, - kSecUpdateEventMask = 1 << kSecUpdateEvent, - kSecPasswordChangedEventMask = 1 << kSecPasswordChangedEvent, - kSecDefaultChangedEventMask = 1 << kSecDefaultChangedEvent, - kSecDataAccessEventMask = 1 << kSecDataAccessEvent, - kSecKeychainListChangedMask = 1 << kSecKeychainListChangedEvent, - kSecTrustSettingsChangedEventMask = 1 << kSecTrustSettingsChangedEvent, - kSecEveryEventMask = 0xffffffff -}; -struct SecKeychainCallbackInfo -{ - UInt32 version; - SecKeychainItemRef _Nonnull item; - SecKeychainRef _Nonnull keychain; - pid_t pid; -}; -typedef struct SecKeychainCallbackInfo SecKeychainCallbackInfo; - - - - - - -CFTypeID SecKeychainGetTypeID(void); - - - - - - - -OSStatus SecKeychainGetVersion(UInt32 * _Nonnull returnVers); -OSStatus SecKeychainOpen(const char *pathName, SecKeychainRef * _Nonnull __attribute__((cf_returns_retained)) keychain); -OSStatus SecKeychainCreate(const char *pathName, UInt32 passwordLength, const void * _Nullable password, Boolean promptUser, SecAccessRef _Nullable initialAccess, SecKeychainRef * _Nonnull __attribute__((cf_returns_retained)) keychain); - - - - - - - -OSStatus SecKeychainDelete(SecKeychainRef _Nullable keychainOrArray); -OSStatus SecKeychainSetSettings(SecKeychainRef _Nullable keychain, const SecKeychainSettings *newSettings); -OSStatus SecKeychainCopySettings(SecKeychainRef _Nullable keychain, SecKeychainSettings *outSettings); -OSStatus SecKeychainUnlock(SecKeychainRef _Nullable keychain, UInt32 passwordLength, const void * _Nullable password, Boolean usePassword); - - - - - - - -OSStatus SecKeychainLock(SecKeychainRef _Nullable keychain); - - - - - - -OSStatus SecKeychainLockAll(void); - - - - - - - -OSStatus SecKeychainCopyDefault(SecKeychainRef * _Nonnull __attribute__((cf_returns_retained)) keychain); - - - - - - - -OSStatus SecKeychainSetDefault(SecKeychainRef _Nullable keychain); - - - - - - - -OSStatus SecKeychainCopySearchList(CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) searchList); - - - - - - - -OSStatus SecKeychainSetSearchList(CFArrayRef searchList); - - - - - - -typedef int SecPreferencesDomain; enum { - kSecPreferencesDomainUser, - kSecPreferencesDomainSystem, - kSecPreferencesDomainCommon, - kSecPreferencesDomainDynamic -}; - -OSStatus SecKeychainCopyDomainDefault(SecPreferencesDomain domain, SecKeychainRef * _Nonnull __attribute__((cf_returns_retained)) keychain); -OSStatus SecKeychainSetDomainDefault(SecPreferencesDomain domain, SecKeychainRef _Nullable keychain); -OSStatus SecKeychainCopyDomainSearchList(SecPreferencesDomain domain, CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) searchList); -OSStatus SecKeychainSetDomainSearchList(SecPreferencesDomain domain, CFArrayRef searchList); -OSStatus SecKeychainSetPreferenceDomain(SecPreferencesDomain domain); -OSStatus SecKeychainGetPreferenceDomain(SecPreferencesDomain *domain); -OSStatus SecKeychainGetStatus(SecKeychainRef _Nullable keychain, SecKeychainStatus *keychainStatus); -OSStatus SecKeychainGetPath(SecKeychainRef _Nullable keychain, UInt32 *ioPathLength, char *pathName); -OSStatus SecKeychainAttributeInfoForItemID(SecKeychainRef _Nullable keychain, UInt32 itemID, SecKeychainAttributeInfo * _Nullable * _Nonnull info); - - - - - - - -OSStatus SecKeychainFreeAttributeInfo(SecKeychainAttributeInfo *info); -typedef OSStatus (*SecKeychainCallback)(SecKeychainEvent keychainEvent, SecKeychainCallbackInfo *info, void * _Nullable context); -OSStatus SecKeychainAddCallback(SecKeychainCallback callbackFunction, SecKeychainEventMask eventMask, void * _Nullable userContext); - - - - - - - -OSStatus SecKeychainRemoveCallback(SecKeychainCallback callbackFunction); -OSStatus SecKeychainAddInternetPassword(SecKeychainRef _Nullable keychain, UInt32 serverNameLength, const char * _Nullable serverName, UInt32 securityDomainLength, const char * _Nullable securityDomain, UInt32 accountNameLength, const char * _Nullable accountName, UInt32 pathLength, const char * _Nullable path, UInt16 port, SecProtocolType protocol, SecAuthenticationType authenticationType, UInt32 passwordLength, const void *passwordData, SecKeychainItemRef * _Nullable __attribute__((cf_returns_retained)) itemRef); -OSStatus SecKeychainFindInternetPassword(CFTypeRef _Nullable keychainOrArray, UInt32 serverNameLength, const char * _Nullable serverName, UInt32 securityDomainLength, const char * _Nullable securityDomain, UInt32 accountNameLength, const char * _Nullable accountName, UInt32 pathLength, const char * _Nullable path, UInt16 port, SecProtocolType protocol, SecAuthenticationType authenticationType, UInt32 * _Nullable passwordLength, void * _Nullable * _Nullable passwordData, SecKeychainItemRef * _Nullable __attribute__((cf_returns_retained)) itemRef); -OSStatus SecKeychainAddGenericPassword(SecKeychainRef _Nullable keychain, UInt32 serviceNameLength, const char * _Nullable serviceName, UInt32 accountNameLength, const char * _Nullable accountName, UInt32 passwordLength, const void *passwordData, SecKeychainItemRef * _Nullable __attribute__((cf_returns_retained)) itemRef); -OSStatus SecKeychainFindGenericPassword(CFTypeRef _Nullable keychainOrArray, UInt32 serviceNameLength, const char * _Nullable serviceName, UInt32 accountNameLength, const char * _Nullable accountName, UInt32 * _Nullable passwordLength, void * _Nullable * _Nullable passwordData, SecKeychainItemRef * _Nullable __attribute__((cf_returns_retained)) itemRef); -OSStatus SecKeychainSetUserInteractionAllowed(Boolean state); - - - - - - - -OSStatus SecKeychainGetUserInteractionAllowed(Boolean *state); -OSStatus SecKeychainGetCSPHandle(SecKeychainRef _Nullable keychain, CSSM_CSP_HANDLE *cspHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecKeychainGetDLDBHandle(SecKeychainRef _Nullable keychain, CSSM_DL_DB_HANDLE *dldbHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecKeychainCopyAccess(SecKeychainRef _Nullable keychain, SecAccessRef * _Nonnull __attribute__((cf_returns_retained)) access); -OSStatus SecKeychainSetAccess(SecKeychainRef _Nullable keychain, SecAccessRef access); - - - - -} -extern "C" { -typedef FourCharCode SecItemClass; enum -{ - kSecInternetPasswordItemClass = 'inet', - kSecGenericPasswordItemClass = 'genp', - kSecAppleSharePasswordItemClass __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))) = 'ashp', - kSecCertificateItemClass = 0x80001000, - kSecPublicKeyItemClass = 0x0000000F, - kSecPrivateKeyItemClass = 0x00000010, - kSecSymmetricKeyItemClass = 0x00000011 -}; -typedef FourCharCode SecItemAttr; enum -{ - kSecCreationDateItemAttr = 'cdat', - kSecModDateItemAttr = 'mdat', - kSecDescriptionItemAttr = 'desc', - kSecCommentItemAttr = 'icmt', - kSecCreatorItemAttr = 'crtr', - kSecTypeItemAttr = 'type', - kSecScriptCodeItemAttr = 'scrp', - kSecLabelItemAttr = 'labl', - kSecInvisibleItemAttr = 'invi', - kSecNegativeItemAttr = 'nega', - kSecCustomIconItemAttr = 'cusi', - kSecAccountItemAttr = 'acct', - kSecServiceItemAttr = 'svce', - kSecGenericItemAttr = 'gena', - kSecSecurityDomainItemAttr = 'sdmn', - kSecServerItemAttr = 'srvr', - kSecAuthenticationTypeItemAttr = 'atyp', - kSecPortItemAttr = 'port', - kSecPathItemAttr = 'path', - kSecVolumeItemAttr = 'vlme', - kSecAddressItemAttr = 'addr', - kSecSignatureItemAttr = 'ssig', - kSecProtocolItemAttr = 'ptcl', - kSecCertificateType = 'ctyp', - kSecCertificateEncoding = 'cenc', - kSecCrlType = 'crtp', - kSecCrlEncoding = 'crnc', - kSecAlias = 'alis' -}; - - - - - -typedef UInt8 SecAFPServerSignature[16]; - - - - - -typedef UInt8 SecPublicKeyHash[20]; - - - - - - - -CFTypeID SecKeychainItemGetTypeID(void); -OSStatus SecKeychainItemModifyAttributesAndData(SecKeychainItemRef itemRef, const SecKeychainAttributeList * _Nullable attrList, UInt32 length, const void * _Nullable data); -OSStatus SecKeychainItemCreateFromContent(SecItemClass itemClass, SecKeychainAttributeList *attrList, - UInt32 length, const void * _Nullable data, SecKeychainRef _Nullable keychainRef, - SecAccessRef _Nullable initialAccess, SecKeychainItemRef * _Nullable __attribute__((cf_returns_retained)) itemRef); -OSStatus SecKeychainItemModifyContent(SecKeychainItemRef itemRef, const SecKeychainAttributeList * _Nullable attrList, UInt32 length, const void * _Nullable data); -OSStatus SecKeychainItemCopyContent(SecKeychainItemRef itemRef, SecItemClass * _Nullable itemClass, SecKeychainAttributeList * _Nullable attrList, UInt32 * _Nullable length, void * _Nullable * _Nullable outData); - - - - - - - -OSStatus SecKeychainItemFreeContent(SecKeychainAttributeList * _Nullable attrList, void * _Nullable data); -OSStatus SecKeychainItemCopyAttributesAndData(SecKeychainItemRef itemRef, SecKeychainAttributeInfo * _Nullable info, SecItemClass * _Nullable itemClass, SecKeychainAttributeList * _Nullable * _Nullable attrList, UInt32 * _Nullable length, void * _Nullable * _Nullable outData); -OSStatus SecKeychainItemFreeAttributesAndData(SecKeychainAttributeList * _Nullable attrList, void * _Nullable data); -OSStatus SecKeychainItemDelete(SecKeychainItemRef itemRef); -OSStatus SecKeychainItemCopyKeychain(SecKeychainItemRef itemRef, SecKeychainRef * _Nonnull __attribute__((cf_returns_retained)) keychainRef); -OSStatus SecKeychainItemCreateCopy(SecKeychainItemRef itemRef, SecKeychainRef _Nullable destKeychainRef, - SecAccessRef initialAccess, SecKeychainItemRef * _Nonnull __attribute__((cf_returns_retained)) itemCopy); -OSStatus SecKeychainItemCreatePersistentReference(SecKeychainItemRef itemRef, CFDataRef * _Nonnull __attribute__((cf_returns_retained)) persistentItemRef); -OSStatus SecKeychainItemCopyFromPersistentReference(CFDataRef persistentItemRef, SecKeychainItemRef * _Nonnull __attribute__((cf_returns_retained)) itemRef); -OSStatus SecKeychainItemGetDLDBHandle(SecKeychainItemRef keyItemRef, CSSM_DL_DB_HANDLE * _Nonnull dldbHandle) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecKeychainItemGetUniqueRecordID(SecKeychainItemRef itemRef, const CSSM_DB_UNIQUE_RECORD * _Nullable * _Nonnull uniqueRecordID) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecKeychainItemCopyAccess(SecKeychainItemRef itemRef, SecAccessRef * _Nonnull __attribute__((cf_returns_retained)) access); -OSStatus SecKeychainItemSetAccess(SecKeychainItemRef itemRef, SecAccessRef access); - - - - -} -extern "C" { -CFTypeID SecKeychainSearchGetTypeID(void) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecKeychainSearchCreateFromAttributes(CFTypeRef _Nullable keychainOrArray, SecItemClass itemClass, const SecKeychainAttributeList * _Nullable attrList, SecKeychainSearchRef * _Nonnull __attribute__((cf_returns_retained)) searchRef) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecKeychainSearchCopyNext(SecKeychainSearchRef searchRef, SecKeychainItemRef * _Nonnull __attribute__((cf_returns_retained)) itemRef) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -} -extern "C" { -extern const CFStringRef kSecPolicyAppleX509Basic - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyAppleSSL - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyAppleSMIME - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyAppleEAP - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyAppleIPsec - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyAppleiChat - __attribute__((availability(macosx,introduced=10.7,deprecated=10.9))); -extern const CFStringRef kSecPolicyApplePKINITClient - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyApplePKINITServer - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyAppleCodeSigning - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyMacAppStoreReceipt - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyAppleIDValidation - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyAppleTimeStamping - __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kSecPolicyAppleRevocation - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecPolicyApplePassbookSigning - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecPolicyApplePayIssuerEncryption - __attribute__((availability(macosx,introduced=10.11))); -extern const CFStringRef kSecPolicyOid - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyName - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyClient - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyRevocationFlags - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecPolicyTeamIdentifier - __attribute__((availability(macosx,introduced=10.9))); - - - - - - - -CFTypeID SecPolicyGetTypeID(void) - __attribute__((availability(macosx,introduced=10.3))); -CFDictionaryRef SecPolicyCopyProperties(SecPolicyRef policyRef) - __attribute__((availability(macosx,introduced=10.7))); - - - - - - - -SecPolicyRef SecPolicyCreateBasicX509(void) - __attribute__((availability(macosx,introduced=10.6))); -SecPolicyRef SecPolicyCreateSSL(Boolean server, CFStringRef _Nullable hostname) - __attribute__((availability(macosx,introduced=10.6))); -enum { - kSecRevocationOCSPMethod = (1 << 0), - kSecRevocationCRLMethod = (1 << 1), - kSecRevocationPreferCRL = (1 << 2), - kSecRevocationRequirePositiveResponse = (1 << 3), - kSecRevocationNetworkAccessDisabled = (1 << 4), - kSecRevocationUseAnyAvailableMethod = (kSecRevocationOCSPMethod | - kSecRevocationCRLMethod) -}; -SecPolicyRef SecPolicyCreateRevocation(CFOptionFlags revocationFlags) - __attribute__((availability(macosx,introduced=10.9))); -_Nullable -SecPolicyRef SecPolicyCreateWithProperties(CFTypeRef policyIdentifier, - CFDictionaryRef _Nullable properties) - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecPolicyKU_DigitalSignature - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyKU_NonRepudiation - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyKU_KeyEncipherment - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyKU_DataEncipherment - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyKU_KeyAgreement - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyKU_KeyCertSign - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyKU_CRLSign - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyKU_EncipherOnly - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPolicyKU_DecipherOnly - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -SecPolicyRef SecPolicyCreateWithOID(CFTypeRef policyOID) - __attribute__((availability(macosx,introduced=10.7,deprecated=10.9))); -OSStatus SecPolicyGetOID(SecPolicyRef policyRef, CSSM_OID *oid) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -OSStatus SecPolicyGetValue(SecPolicyRef policyRef, CSSM_DATA *value) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -OSStatus SecPolicySetValue(SecPolicyRef policyRef, const CSSM_DATA *value) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -OSStatus SecPolicySetProperties(SecPolicyRef policyRef, - CFDictionaryRef properties) - __attribute__((availability(macosx,introduced=10.7,deprecated=10.9))); -OSStatus SecPolicyGetTPHandle(SecPolicyRef policyRef, CSSM_TP_HANDLE *tpHandle) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); - - - - - - - -} -extern "C" { -typedef struct __attribute__((objc_bridge(id))) OpaquePolicySearchRef *SecPolicySearchRef; - - - - - - - -CFTypeID SecPolicySearchGetTypeID(void) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecPolicySearchCreate(CSSM_CERT_TYPE certType, const CSSM_OID *policyOID, const CSSM_DATA * _Nullable value, SecPolicySearchRef * _Nonnull __attribute__((cf_returns_retained)) searchRef) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecPolicySearchCopyNext(SecPolicySearchRef searchRef, SecPolicyRef * _Nonnull __attribute__((cf_returns_retained)) policyRef) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - -} -extern "C" { -typedef uint32_t SecTrustResultType; -enum { - kSecTrustResultInvalid = 0, - kSecTrustResultProceed = 1, - kSecTrustResultConfirm __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))) = 2, - kSecTrustResultDeny = 3, - kSecTrustResultUnspecified = 4, - kSecTrustResultRecoverableTrustFailure = 5, - kSecTrustResultFatalTrustFailure = 6, - kSecTrustResultOtherError = 7 -}; - - - - - -typedef struct __attribute__((objc_bridge(id))) __SecTrust *SecTrustRef; -extern const CFStringRef kSecPropertyTypeTitle - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecPropertyTypeError - __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecTrustEvaluationDate - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecTrustExtendedValidation - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecTrustOrganizationName - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecTrustResultValue - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecTrustRevocationChecked - __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kSecTrustRevocationValidUntilDate - __attribute__((availability(macosx,introduced=10.9))); -typedef void (*SecTrustCallback)(SecTrustRef trustRef, SecTrustResultType trustResult); -CFTypeID SecTrustGetTypeID(void) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecTrustCreateWithCertificates(CFTypeRef certificates, - CFTypeRef _Nullable policies, SecTrustRef * _Nonnull __attribute__((cf_returns_retained)) trust) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecTrustSetPolicies(SecTrustRef trust, CFTypeRef policies) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecTrustCopyPolicies(SecTrustRef trust, CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) policies) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecTrustSetNetworkFetchAllowed(SecTrustRef trust, - Boolean allowFetch) - __attribute__((availability(macosx,introduced=10.9))); -OSStatus SecTrustGetNetworkFetchAllowed(SecTrustRef trust, - Boolean *allowFetch) - __attribute__((availability(macosx,introduced=10.9))); -OSStatus SecTrustSetAnchorCertificates(SecTrustRef trust, - CFArrayRef anchorCertificates) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecTrustSetAnchorCertificatesOnly(SecTrustRef trust, - Boolean anchorCertificatesOnly) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus SecTrustCopyCustomAnchorCertificates(SecTrustRef trust, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) anchors) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus SecTrustSetVerifyDate(SecTrustRef trust, CFDateRef verifyDate) - __attribute__((availability(macosx,introduced=10.3))); -CFAbsoluteTime SecTrustGetVerifyTime(SecTrustRef trust) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus SecTrustEvaluate(SecTrustRef trust, SecTrustResultType * _Nullable result) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecTrustEvaluateAsync(SecTrustRef trust, - dispatch_queue_t _Nullable queue, SecTrustCallback result) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus SecTrustGetTrustResult(SecTrustRef trust, - SecTrustResultType *result) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -SecKeyRef SecTrustCopyPublicKey(SecTrustRef trust) - __attribute__((availability(macosx,introduced=10.7))); -CFIndex SecTrustGetCertificateCount(SecTrustRef trust) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -SecCertificateRef SecTrustGetCertificateAtIndex(SecTrustRef trust, CFIndex ix) - __attribute__((availability(macosx,introduced=10.7))); -CFDataRef SecTrustCopyExceptions(SecTrustRef trust) - __attribute__((availability(macosx,introduced=10.9))); -bool SecTrustSetExceptions(SecTrustRef trust, CFDataRef exceptions) - __attribute__((availability(macosx,introduced=10.9))); -_Nullable -CFArrayRef SecTrustCopyProperties(SecTrustRef trust) - __attribute__((availability(macosx,introduced=10.7))); -_Nullable -CFDictionaryRef SecTrustCopyResult(SecTrustRef trust) - __attribute__((availability(macosx,introduced=10.9))); -OSStatus SecTrustSetOCSPResponse(SecTrustRef trust, CFTypeRef _Nullable responseData) - __attribute__((availability(macosx,introduced=10.9))); -typedef SecTrustResultType SecTrustUserSetting - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -typedef uint32_t SecTrustOptionFlags; enum -{ - kSecTrustOptionAllowExpired = 0x00000001, - kSecTrustOptionLeafIsCA = 0x00000002, - kSecTrustOptionFetchIssuerFromNet = 0x00000004, - kSecTrustOptionAllowExpiredRoot = 0x00000008, - kSecTrustOptionRequireRevPerCert = 0x00000010, - kSecTrustOptionUseTrustSettings = 0x00000020, - kSecTrustOptionImplicitAnchors = 0x00000040 -}; -OSStatus SecTrustSetOptions(SecTrustRef trustRef, SecTrustOptionFlags options) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus SecTrustSetParameters(SecTrustRef trustRef, - CSSM_TP_ACTION action, CFDataRef actionData) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -OSStatus SecTrustSetKeychains(SecTrustRef trust, CFTypeRef _Nullable keychainOrArray) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SecTrustGetResult(SecTrustRef trustRef, SecTrustResultType * _Nullable result, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) certChain, CSSM_TP_APPLE_EVIDENCE_INFO * _Nullable * _Nonnull statusChain) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -OSStatus SecTrustGetCssmResult(SecTrustRef trust, - CSSM_TP_VERIFY_CONTEXT_RESULT_PTR _Nullable * _Nonnull result) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -OSStatus SecTrustGetCssmResultCode(SecTrustRef trust, OSStatus *resultCode) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -OSStatus SecTrustGetTPHandle(SecTrustRef trust, CSSM_TP_HANDLE *handle) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -OSStatus SecTrustCopyAnchorCertificates(CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) anchors) - __attribute__((availability(macosx,introduced=10.3))); - - - - - - - -} -extern "C" { -CFTypeID SecTrustedApplicationGetTypeID(void); -OSStatus SecTrustedApplicationCreateFromPath(const char * _Nullable path, SecTrustedApplicationRef * _Nonnull __attribute__((cf_returns_retained)) app); -OSStatus SecTrustedApplicationCopyData(SecTrustedApplicationRef appRef, CFDataRef * _Nonnull __attribute__((cf_returns_retained)) data); -OSStatus SecTrustedApplicationSetData(SecTrustedApplicationRef appRef, CFDataRef data); - - - - -} -extern "C" { -typedef uint32 SecTrustSettingsKeyUsage; enum { - - kSecTrustSettingsKeyUseSignature = 0x00000001, - - kSecTrustSettingsKeyUseEnDecryptData = 0x00000002, - - kSecTrustSettingsKeyUseEnDecryptKey = 0x00000004, - - kSecTrustSettingsKeyUseSignCert = 0x00000008, - - kSecTrustSettingsKeyUseSignRevocation = 0x00000010, - - kSecTrustSettingsKeyUseKeyExchange = 0x00000020, - - kSecTrustSettingsKeyUseAny = 0xffffffff -}; - - - - -typedef uint32 SecTrustSettingsResult; enum { - kSecTrustSettingsResultInvalid = 0, - - kSecTrustSettingsResultTrustRoot, - kSecTrustSettingsResultTrustAsRoot, - kSecTrustSettingsResultDeny, - kSecTrustSettingsResultUnspecified - -}; - - - - - - -typedef uint32 SecTrustSettingsDomain; enum { - kSecTrustSettingsDomainUser = 0, - kSecTrustSettingsDomainAdmin, - kSecTrustSettingsDomainSystem -}; -OSStatus SecTrustSettingsCopyTrustSettings( - SecCertificateRef certRef, - SecTrustSettingsDomain domain, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) trustSettings); -OSStatus SecTrustSettingsSetTrustSettings( - SecCertificateRef certRef, - SecTrustSettingsDomain domain, - CFTypeRef _Nullable trustSettingsDictOrArray); - - - - - -OSStatus SecTrustSettingsRemoveTrustSettings( - SecCertificateRef certRef, - SecTrustSettingsDomain domain); -OSStatus SecTrustSettingsCopyCertificates( - SecTrustSettingsDomain domain, - CFArrayRef * _Nullable __attribute__((cf_returns_retained)) certArray); - - - - - - - -OSStatus SecTrustSettingsCopyModificationDate( - SecCertificateRef certRef, - SecTrustSettingsDomain domain, - CFDateRef * _Nonnull __attribute__((cf_returns_retained)) modificationDate); - - - - - - - -OSStatus SecTrustSettingsCreateExternalRepresentation( - SecTrustSettingsDomain domain, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) trustSettings); - - - - - -OSStatus SecTrustSettingsImportExternalRepresentation( - SecTrustSettingsDomain domain, - CFDataRef trustSettings); - - - - -} -extern "C" { -typedef uint32_t SecExternalFormat; enum -{ - - - - - kSecFormatUnknown = 0, - - - - - - kSecFormatOpenSSL, - kSecFormatSSH, - kSecFormatBSAFE, - - - kSecFormatRawKey, - - - kSecFormatWrappedPKCS8, - kSecFormatWrappedOpenSSL, - kSecFormatWrappedSSH, - kSecFormatWrappedLSH, - - - kSecFormatX509Cert, - - - kSecFormatPEMSequence, - - kSecFormatPKCS7, - kSecFormatPKCS12, - kSecFormatNetscapeCertSequence, - - - kSecFormatSSHv2 - - -}; - - - - -typedef uint32_t SecExternalItemType; enum { - kSecItemTypeUnknown, - kSecItemTypePrivateKey, - kSecItemTypePublicKey, - kSecItemTypeSessionKey, - kSecItemTypeCertificate, - kSecItemTypeAggregate -}; - - - - -typedef uint32_t SecItemImportExportFlags; enum -{ - kSecItemPemArmour = 0x00000001, -}; - - - - -typedef uint32_t SecKeyImportExportFlags; enum -{ - - - - - kSecKeyImportOnlyOne = 0x00000001, - kSecKeySecurePassphrase = 0x00000002, - - - - - - - - kSecKeyNoAccessControl = 0x00000004 -}; -typedef struct -{ - - uint32_t version; - SecKeyImportExportFlags flags; - CFTypeRef passphrase; - - - CFStringRef alertTitle; - CFStringRef alertPrompt; - - - SecAccessRef _Nullable accessRef; - - CSSM_KEYUSE keyUsage; - - CSSM_KEYATTR_FLAGS keyAttributes; -} SecKeyImportExportParameters; - - -typedef struct -{ - - uint32_t version; - SecKeyImportExportFlags flags; - CFTypeRef passphrase; - - - CFStringRef alertTitle; - CFStringRef alertPrompt; - - - SecAccessRef _Nullable accessRef; - - CFArrayRef _Nullable keyUsage; - - - - CFArrayRef _Nullable keyAttributes; - - - - - - - -} SecItemImportExportKeyParameters; -OSStatus SecKeychainItemExport( - CFTypeRef keychainItemOrArray, - SecExternalFormat outputFormat, - SecItemImportExportFlags flags, - const SecKeyImportExportParameters * _Nullable keyParams, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) exportedData) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecItemExport( - CFTypeRef secItemOrArray, - SecExternalFormat outputFormat, - SecItemImportExportFlags flags, - const SecItemImportExportKeyParameters * _Nullable keyParams, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) exportedData) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus SecKeychainItemImport( - CFDataRef importedData, - CFStringRef _Nullable fileNameOrExtension, - SecExternalFormat * _Nullable inputFormat, - SecExternalItemType * _Nullable itemType, - SecItemImportExportFlags flags, - const SecKeyImportExportParameters * _Nullable keyParams, - SecKeychainRef _Nullable importKeychain, - CFArrayRef * _Nullable __attribute__((cf_returns_retained)) outItems) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -OSStatus SecItemImport( - CFDataRef importedData, - CFStringRef _Nullable fileNameOrExtension, - SecExternalFormat * _Nullable inputFormat, - SecExternalItemType * _Nullable itemType, - SecItemImportExportFlags flags, - const SecItemImportExportKeyParameters * _Nullable keyParams, - SecKeychainRef _Nullable importKeychain, - CFArrayRef * _Nullable __attribute__((cf_returns_retained)) outItems) - __attribute__((availability(macosx,introduced=10.7))); - - - - - - - -extern const CFStringRef kSecImportExportPassphrase; -extern const CFStringRef kSecImportExportKeychain; -extern const CFStringRef kSecImportExportAccess; -extern const CFStringRef kSecImportItemLabel; -extern const CFStringRef kSecImportItemKeyID; -extern const CFStringRef kSecImportItemTrust; -extern const CFStringRef kSecImportItemCertChain; -extern const CFStringRef kSecImportItemIdentity; -OSStatus SecPKCS12Import(CFDataRef pkcs12_data, CFDictionaryRef options, CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) items); - - - - - -} -extern "C" { -typedef const struct __SecRandom * SecRandomRef; - - - -extern const SecRandomRef kSecRandomDefault - __attribute__((availability(macosx,introduced=10.7))); - - - - - - - -int SecRandomCopyBytes(SecRandomRef _Nullable rnd, size_t count, uint8_t *bytes) - __attribute__((availability(macosx,introduced=10.7))); - - - - - -} - - -extern "C" { -enum { - errSecCSUnimplemented = -67072, - errSecCSInvalidObjectRef = -67071, - errSecCSInvalidFlags = -67070, - errSecCSObjectRequired = -67069, - errSecCSStaticCodeNotFound = -67068, - errSecCSUnsupportedGuestAttributes = -67067, - errSecCSInvalidAttributeValues = -67066, - errSecCSNoSuchCode = -67065, - errSecCSMultipleGuests = -67064, - errSecCSGuestInvalid = -67063, - errSecCSUnsigned = -67062, - errSecCSSignatureFailed = -67061, - errSecCSSignatureNotVerifiable = -67060, - errSecCSSignatureUnsupported = -67059, - errSecCSBadDictionaryFormat = -67058, - errSecCSResourcesNotSealed = -67057, - errSecCSResourcesNotFound = -67056, - errSecCSResourcesInvalid = -67055, - errSecCSBadResource = -67054, - errSecCSResourceRulesInvalid = -67053, - errSecCSReqInvalid = -67052, - errSecCSReqUnsupported = -67051, - errSecCSReqFailed = -67050, - errSecCSBadObjectFormat = -67049, - errSecCSInternalError = -67048, - errSecCSHostReject = -67047, - errSecCSNotAHost = -67046, - errSecCSSignatureInvalid = -67045, - errSecCSHostProtocolRelativePath = -67044, - errSecCSHostProtocolContradiction = -67043, - errSecCSHostProtocolDedicationError = -67042, - errSecCSHostProtocolNotProxy = -67041, - errSecCSHostProtocolStateError = -67040, - errSecCSHostProtocolUnrelated = -67039, - - errSecCSNotSupported = -67037, - errSecCSCMSTooLarge = -67036, - errSecCSHostProtocolInvalidHash = -67035, - errSecCSStaticCodeChanged = -67034, - errSecCSDBDenied = -67033, - errSecCSDBAccess = -67032, - errSecCSSigDBDenied = errSecCSDBDenied, - errSecCSSigDBAccess = errSecCSDBAccess, - errSecCSHostProtocolInvalidAttribute = -67031, - errSecCSInfoPlistFailed = -67030, - errSecCSNoMainExecutable = -67029, - errSecCSBadBundleFormat = -67028, - errSecCSNoMatches = -67027, - errSecCSFileHardQuarantined = -67026, - errSecCSOutdated = -67025, - errSecCSDbCorrupt = -67024, - errSecCSResourceDirectoryFailed = -67023, - errSecCSUnsignedNestedCode = -67022, - errSecCSBadNestedCode = -67021, - errSecCSBadCallbackValue = -67020, - errSecCSHelperFailed = -67019, - errSecCSVetoed = -67018, - errSecCSBadLVArch = -67017, - errSecCSResourceNotSupported = -67016, - errSecCSRegularFile = -67015, - errSecCSUnsealedAppRoot = -67014, - errSecCSWeakResourceRules = -67013, - errSecCSDSStoreSymlink = -67012, - errSecCSAmbiguousBundleFormat = -67011, - errSecCSBadMainExecutable = -67010, - errSecCSBadFrameworkVersion = -67009, - errSecCSUnsealedFrameworkRoot = -67008, - errSecCSWeakResourceEnvelope = -67007, - errSecCSCancelled = -67006, - errSecCSInvalidPlatform = -67005, - errSecCSTooBig = -67004, - errSecCSInvalidSymlink = -67003, -}; -extern const CFStringRef kSecCFErrorArchitecture; -extern const CFStringRef kSecCFErrorPattern; -extern const CFStringRef kSecCFErrorResourceSeal; -extern const CFStringRef kSecCFErrorResourceAdded; -extern const CFStringRef kSecCFErrorResourceAltered; -extern const CFStringRef kSecCFErrorResourceMissing; -extern const CFStringRef kSecCFErrorInfoPlist; -extern const CFStringRef kSecCFErrorGuestAttributes; -extern const CFStringRef kSecCFErrorRequirementSyntax; -extern const CFStringRef kSecCFErrorPath; -typedef struct __attribute__((objc_bridge(id))) __SecCode *SecCodeRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) __SecCode const *SecStaticCodeRef; - - - - - -typedef struct __attribute__((objc_bridge(id))) __SecRequirement *SecRequirementRef; -typedef u_int32_t SecGuestRef; - -enum { - kSecNoGuest = 0, -}; -typedef uint32_t SecCSFlags; enum { - kSecCSDefaultFlags = 0, - - kSecCSConsiderExpiration = 1 << 31, - kSecCSEnforceRevocationChecks = 1 << 30, - kSecCSNoNetworkAccess = 1 << 29, - kSecCSReportProgress = 1 << 28, - kSecCSCheckTrustedAnchors = 1 << 27, -}; -typedef uint32_t SecCodeSignatureFlags; enum { - kSecCodeSignatureHost = 0x0001, - kSecCodeSignatureAdhoc = 0x0002, - kSecCodeSignatureForceHard = 0x0100, - kSecCodeSignatureForceKill = 0x0200, - kSecCodeSignatureForceExpiration = 0x0400, - kSecCodeSignatureRestrict = 0x0800, - kSecCodeSignatureEnforcement = 0x1000, - kSecCodeSignatureLibraryValidation = 0x2000, -}; -typedef uint32_t SecCodeStatus; enum { - kSecCodeStatusValid = 0x0001, - kSecCodeStatusHard = 0x0100, - kSecCodeStatusKill = 0x0200, -}; - - - - - - -typedef uint32_t SecRequirementType; enum { - kSecHostRequirementType = 1, - kSecGuestRequirementType = 2, - kSecDesignatedRequirementType = 3, - kSecLibraryRequirementType = 4, - kSecPluginRequirementType = 5, - kSecInvalidRequirementType, - kSecRequirementTypeCount = kSecInvalidRequirementType -}; - - - - -} - - -extern "C" { -CFTypeID SecStaticCodeGetTypeID(void); -extern const CFStringRef kSecCodeAttributeArchitecture; -extern const CFStringRef kSecCodeAttributeSubarchitecture; -extern const CFStringRef kSecCodeAttributeUniversalFileOffset; -extern const CFStringRef kSecCodeAttributeBundleVersion; - -OSStatus SecStaticCodeCreateWithPath(CFURLRef path, SecCSFlags flags, SecStaticCodeRef * _Nonnull __attribute__((cf_returns_retained)) staticCode); - -OSStatus SecStaticCodeCreateWithPathAndAttributes(CFURLRef path, SecCSFlags flags, CFDictionaryRef attributes, - SecStaticCodeRef * _Nonnull __attribute__((cf_returns_retained)) staticCode); -enum { - kSecCSCheckAllArchitectures = 1 << 0, - kSecCSDoNotValidateExecutable = 1 << 1, - kSecCSDoNotValidateResources = 1 << 2, - kSecCSBasicValidateOnly = kSecCSDoNotValidateExecutable | kSecCSDoNotValidateResources, - kSecCSCheckNestedCode = 1 << 3, - kSecCSStrictValidate = 1 << 4, - kSecCSFullReport = 1 << 5, - kSecCSCheckGatekeeperArchitectures = (1 << 6) | kSecCSCheckAllArchitectures, - kSecCSRestrictSymlinks = 1 << 7, -}; - -OSStatus SecStaticCodeCheckValidity(SecStaticCodeRef staticCode, SecCSFlags flags, - SecRequirementRef _Nullable requirement); - -OSStatus SecStaticCodeCheckValidityWithErrors(SecStaticCodeRef staticCode, SecCSFlags flags, - SecRequirementRef _Nullable requirement, CFErrorRef *errors); - - - - -} -extern "C" { -CFTypeID SecCodeGetTypeID(void); -OSStatus SecCodeCopySelf(SecCSFlags flags, SecCodeRef * _Nonnull __attribute__((cf_returns_retained)) self); -enum { - kSecCSUseAllArchitectures = 1 << 0, -}; - -OSStatus SecCodeCopyStaticCode(SecCodeRef code, SecCSFlags flags, SecStaticCodeRef * _Nonnull __attribute__((cf_returns_retained)) staticCode); -OSStatus SecCodeCopyHost(SecCodeRef guest, SecCSFlags flags, SecCodeRef * _Nonnull __attribute__((cf_returns_retained)) host); -extern const CFStringRef kSecGuestAttributeCanonical; -extern const CFStringRef kSecGuestAttributeHash; -extern const CFStringRef kSecGuestAttributeMachPort; -extern const CFStringRef kSecGuestAttributePid; -extern const CFStringRef kSecGuestAttributeDynamicCode; -extern const CFStringRef kSecGuestAttributeDynamicCodeInfoPlist; -extern const CFStringRef kSecGuestAttributeArchitecture; -extern const CFStringRef kSecGuestAttributeSubarchitecture; - -OSStatus SecCodeCopyGuestWithAttributes(SecCodeRef _Nullable host, - CFDictionaryRef _Nullable attributes, SecCSFlags flags, SecCodeRef * _Nonnull __attribute__((cf_returns_retained)) guest); -OSStatus SecCodeCheckValidity(SecCodeRef code, SecCSFlags flags, - SecRequirementRef _Nullable requirement); - -OSStatus SecCodeCheckValidityWithErrors(SecCodeRef code, SecCSFlags flags, - SecRequirementRef _Nullable requirement, CFErrorRef *errors); -OSStatus SecCodeCopyPath(SecStaticCodeRef staticCode, SecCSFlags flags, - CFURLRef * _Nonnull __attribute__((cf_returns_retained)) path); -OSStatus SecCodeCopyDesignatedRequirement(SecStaticCodeRef code, SecCSFlags flags, - SecRequirementRef * _Nonnull __attribute__((cf_returns_retained)) requirement); -enum { - kSecCSInternalInformation = 1 << 0, - kSecCSSigningInformation = 1 << 1, - kSecCSRequirementInformation = 1 << 2, - kSecCSDynamicInformation = 1 << 3, - kSecCSContentInformation = 1 << 4 -}; - -extern const CFStringRef kSecCodeInfoCertificates; -extern const CFStringRef kSecCodeInfoChangedFiles; -extern const CFStringRef kSecCodeInfoCMS; -extern const CFStringRef kSecCodeInfoDesignatedRequirement; -extern const CFStringRef kSecCodeInfoEntitlements; -extern const CFStringRef kSecCodeInfoEntitlementsDict; -extern const CFStringRef kSecCodeInfoFlags; -extern const CFStringRef kSecCodeInfoFormat; -extern const CFStringRef kSecCodeInfoDigestAlgorithm; -extern const CFStringRef kSecCodeInfoPlatformIdentifier; -extern const CFStringRef kSecCodeInfoIdentifier; -extern const CFStringRef kSecCodeInfoImplicitDesignatedRequirement; -extern const CFStringRef kSecCodeInfoMainExecutable; -extern const CFStringRef kSecCodeInfoPList; -extern const CFStringRef kSecCodeInfoRequirements; -extern const CFStringRef kSecCodeInfoRequirementData; -extern const CFStringRef kSecCodeInfoSource; -extern const CFStringRef kSecCodeInfoStatus; -extern const CFStringRef kSecCodeInfoTeamIdentifier; -extern const CFStringRef kSecCodeInfoTime; -extern const CFStringRef kSecCodeInfoTimestamp; -extern const CFStringRef kSecCodeInfoTrust; -extern const CFStringRef kSecCodeInfoUnique; - -OSStatus SecCodeCopySigningInformation(SecStaticCodeRef code, SecCSFlags flags, - CFDictionaryRef * _Nonnull __attribute__((cf_returns_retained)) information); -OSStatus SecCodeMapMemory(SecStaticCodeRef code, SecCSFlags flags); - - - - -} -extern "C" { -enum { - kSecCSDedicatedHost = 1 << 0, - kSecCSGenerateGuestHash = 1 << 1, -}; - -OSStatus SecHostCreateGuest(SecGuestRef host, - uint32_t status, CFURLRef path, CFDictionaryRef _Nullable attributes, - SecCSFlags flags, SecGuestRef * _Nonnull newGuest); -OSStatus SecHostRemoveGuest(SecGuestRef host, SecGuestRef guest, SecCSFlags flags); -OSStatus SecHostSelectGuest(SecGuestRef guestRef, SecCSFlags flags); -OSStatus SecHostSelectedGuest(SecCSFlags flags, SecGuestRef * _Nonnull guestRef); -OSStatus SecHostSetGuestStatus(SecGuestRef guestRef, - uint32_t status, CFDictionaryRef _Nullable attributes, - SecCSFlags flags); -OSStatus SecHostSetHostingPort(mach_port_t hostingPort, SecCSFlags flags); - - - - -} -extern "C" { -CFTypeID SecRequirementGetTypeID(void); -OSStatus SecRequirementCreateWithData(CFDataRef data, SecCSFlags flags, - SecRequirementRef * _Nonnull __attribute__((cf_returns_retained)) requirement); -OSStatus SecRequirementCreateWithString(CFStringRef text, SecCSFlags flags, - SecRequirementRef * _Nonnull __attribute__((cf_returns_retained)) requirement); - -OSStatus SecRequirementCreateWithStringAndErrors(CFStringRef text, SecCSFlags flags, - CFErrorRef *errors, SecRequirementRef * _Nonnull __attribute__((cf_returns_retained)) requirement); -OSStatus SecRequirementCopyData(SecRequirementRef requirement, SecCSFlags flags, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) data); -OSStatus SecRequirementCopyString(SecRequirementRef requirement, SecCSFlags flags, - CFStringRef * _Nonnull __attribute__((cf_returns_retained)) text); - - - - -} -extern "C" { -typedef struct __attribute__((objc_bridge(id))) __SecTask *SecTaskRef; - - - - - - -CFTypeID SecTaskGetTypeID(void); -_Nullable -SecTaskRef SecTaskCreateWithAuditToken(CFAllocatorRef _Nullable allocator, audit_token_t token); - - - - - - - -_Nullable -SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef _Nullable allocator); -_Nullable -CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error); -_Nullable -CFDictionaryRef SecTaskCopyValuesForEntitlements(SecTaskRef task, CFArrayRef entitlements, CFErrorRef *error); - - - - - -} - - -extern "C" { -enum { - errAuthorizationSuccess = 0, - errAuthorizationInvalidSet = -60001, - errAuthorizationInvalidRef = -60002, - errAuthorizationInvalidTag = -60003, - errAuthorizationInvalidPointer = -60004, - errAuthorizationDenied = -60005, - errAuthorizationCanceled = -60006, - errAuthorizationInteractionNotAllowed = -60007, - errAuthorizationInternal = -60008, - errAuthorizationExternalizeNotAllowed = -60009, - errAuthorizationInternalizeNotAllowed = -60010, - errAuthorizationInvalidFlags = -60011, - errAuthorizationToolExecuteFailure = -60031, - errAuthorizationToolEnvironmentError = -60032, - errAuthorizationBadAddress = -60033, -}; - - - - - - - -typedef UInt32 AuthorizationFlags; enum { - kAuthorizationFlagDefaults = 0, - kAuthorizationFlagInteractionAllowed = (1 << 0), - kAuthorizationFlagExtendRights = (1 << 1), - kAuthorizationFlagPartialRights = (1 << 2), - kAuthorizationFlagDestroyRights = (1 << 3), - kAuthorizationFlagPreAuthorize = (1 << 4), - - - kAuthorizationFlagNoData = (1 << 20) -}; - - - - - - -enum { - kAuthorizationFlagCanNotPreAuthorize = (1 << 0) -}; - - - - - - -typedef const struct AuthorizationOpaqueRef *AuthorizationRef; - - - - - - -typedef const char *AuthorizationString; -typedef struct { - AuthorizationString name; - size_t valueLength; - void *value; - UInt32 flags; -} AuthorizationItem; -typedef struct { - UInt32 count; - AuthorizationItem *items; -} AuthorizationItemSet; -enum { - kAuthorizationExternalFormLength = 32 -}; - -typedef struct { - char bytes[kAuthorizationExternalFormLength]; -} AuthorizationExternalForm; -typedef AuthorizationItemSet AuthorizationRights; - - - - - - - -typedef AuthorizationItemSet AuthorizationEnvironment; -OSStatus AuthorizationCreate(const AuthorizationRights * _Nullable rights, - const AuthorizationEnvironment * _Nullable environment, - AuthorizationFlags flags, - AuthorizationRef _Nullable * _Nullable authorization); -OSStatus AuthorizationFree(AuthorizationRef authorization, AuthorizationFlags flags); -OSStatus AuthorizationCopyRights(AuthorizationRef authorization, - const AuthorizationRights *rights, - const AuthorizationEnvironment * _Nullable environment, - AuthorizationFlags flags, - AuthorizationRights * _Nullable * _Nullable authorizedRights); -typedef void (*AuthorizationAsyncCallback)(OSStatus err, AuthorizationRights * _Nullable blockAuthorizedRights); - - - - - - - -void AuthorizationCopyRightsAsync(AuthorizationRef authorization, - const AuthorizationRights *rights, - const AuthorizationEnvironment * _Nullable environment, - AuthorizationFlags flags, - AuthorizationAsyncCallback callbackBlock); -OSStatus AuthorizationCopyInfo(AuthorizationRef authorization, - AuthorizationString _Nullable tag, - AuthorizationItemSet * _Nullable * _Nonnull info); -OSStatus AuthorizationMakeExternalForm(AuthorizationRef authorization, - AuthorizationExternalForm * _Nonnull extForm); -OSStatus AuthorizationCreateFromExternalForm(const AuthorizationExternalForm *extForm, - AuthorizationRef _Nullable * _Nonnull authorization); -OSStatus AuthorizationFreeItemSet(AuthorizationItemSet *set); -OSStatus AuthorizationExecuteWithPrivileges(AuthorizationRef authorization, - const char *pathToTool, - AuthorizationFlags options, - char * _Nonnull const * _Nonnull arguments, - FILE * _Nullable * _Nullable communicationsPipe) __attribute__((availability(macosx,introduced=10.1,deprecated=10.7))); -OSStatus AuthorizationCopyPrivilegedReference(AuthorizationRef _Nullable * _Nonnull authorization, - AuthorizationFlags flags) __attribute__((availability(macosx,introduced=10.1,deprecated=10.7))); - - - - -} -extern "C" { -OSStatus AuthorizationRightGet(const char *rightName, - CFDictionaryRef * _Nullable __attribute__((cf_returns_retained)) rightDefinition); -OSStatus AuthorizationRightSet(AuthorizationRef authRef, - const char *rightName, - CFTypeRef rightDefinition, - CFStringRef _Nullable descriptionKey, - CFBundleRef _Nullable bundle, - CFStringRef _Nullable localeTableName); -OSStatus AuthorizationRightRemove(AuthorizationRef authRef, - const char *rightName); - - - - -} - - -extern "C" { -typedef struct __attribute__((objc_bridge(id))) _CMSDecoder *CMSDecoderRef; - -CFTypeID CMSDecoderGetTypeID(void); - - - - -typedef uint32_t CMSSignerStatus; enum { - kCMSSignerUnsigned = 0, - kCMSSignerValid, - kCMSSignerNeedsDetachedContent, - - kCMSSignerInvalidSignature, - kCMSSignerInvalidCert, - - kCMSSignerInvalidIndex -}; - - - - -OSStatus CMSDecoderCreate( - CMSDecoderRef * _Nonnull __attribute__((cf_returns_retained)) cmsDecoderOut) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -OSStatus CMSDecoderUpdateMessage( - CMSDecoderRef cmsDecoder, - const void *msgBytes, - size_t msgBytesLen) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -OSStatus CMSDecoderFinalizeMessage( - CMSDecoderRef cmsDecoder) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSDecoderSetDetachedContent( - CMSDecoderRef cmsDecoder, - CFDataRef detachedContent) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -OSStatus CMSDecoderCopyDetachedContent( - CMSDecoderRef cmsDecoder, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) detachedContentOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSDecoderSetSearchKeychain( - CMSDecoderRef cmsDecoder, - CFTypeRef keychainOrArray) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -OSStatus CMSDecoderGetNumSigners( - CMSDecoderRef cmsDecoder, - size_t *numSignersOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSDecoderCopySignerStatus( - CMSDecoderRef cmsDecoder, - size_t signerIndex, - CFTypeRef policyOrArray, - Boolean evaluateSecTrust, - CMSSignerStatus * _Nullable signerStatusOut, - SecTrustRef * _Nullable __attribute__((cf_returns_retained)) secTrustOut, - OSStatus * _Nullable certVerifyResultCodeOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSDecoderCopySignerEmailAddress( - CMSDecoderRef cmsDecoder, - size_t signerIndex, - CFStringRef * _Nonnull __attribute__((cf_returns_retained)) signerEmailAddressOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSDecoderCopySignerCert( - CMSDecoderRef cmsDecoder, - size_t signerIndex, - SecCertificateRef * _Nonnull __attribute__((cf_returns_retained)) signerCertOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSDecoderIsContentEncrypted( - CMSDecoderRef cmsDecoder, - Boolean *isEncryptedOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSDecoderCopyEncapsulatedContentType( - CMSDecoderRef cmsDecoder, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) eContentTypeOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSDecoderCopyAllCerts( - CMSDecoderRef cmsDecoder, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) certsOut) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -OSStatus CMSDecoderCopyContent( - CMSDecoderRef cmsDecoder, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) contentOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSDecoderCopySignerSigningTime( - CMSDecoderRef cmsDecoder, - size_t signerIndex, - CFAbsoluteTime *signingTime) - __attribute__((availability(macosx,introduced=10.8))); -OSStatus CMSDecoderCopySignerTimestamp( - CMSDecoderRef cmsDecoder, - size_t signerIndex, - CFAbsoluteTime *timestamp) - __attribute__((availability(macosx,introduced=10.8))); -OSStatus CMSDecoderCopySignerTimestampWithPolicy( - CMSDecoderRef cmsDecoder, - CFTypeRef _Nullable timeStampPolicy, - size_t signerIndex, - CFAbsoluteTime *timestamp) - __attribute__((availability(macosx,introduced=10.10))); -OSStatus CMSDecoderCopySignerTimestampCertificates( - CMSDecoderRef cmsDecoder, - size_t signerIndex, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) certificateRefs) - __attribute__((availability(macosx,introduced=10.8))); - - - - -} -extern "C" { -typedef struct __attribute__((objc_bridge(id))) _CMSEncoder *CMSEncoderRef; - -CFTypeID CMSEncoderGetTypeID(void) - __attribute__((availability(macosx,introduced=10.5))); - - - - -OSStatus CMSEncoderCreate( - CMSEncoderRef * _Nonnull __attribute__((cf_returns_retained)) cmsEncoderOut) - __attribute__((availability(macosx,introduced=10.5))); - -extern const CFStringRef kCMSEncoderDigestAlgorithmSHA1; -extern const CFStringRef kCMSEncoderDigestAlgorithmSHA256; - -OSStatus CMSEncoderSetSignerAlgorithm( - CMSEncoderRef cmsEncoder, - CFStringRef digestAlgorithm) - __attribute__((availability(macosx,introduced=10.11))); -OSStatus CMSEncoderAddSigners( - CMSEncoderRef cmsEncoder, - CFTypeRef signerOrArray) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -OSStatus CMSEncoderCopySigners( - CMSEncoderRef cmsEncoder, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) signersOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSEncoderAddRecipients( - CMSEncoderRef cmsEncoder, - CFTypeRef recipientOrArray) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -OSStatus CMSEncoderCopyRecipients( - CMSEncoderRef cmsEncoder, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) recipientsOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSEncoderSetHasDetachedContent( - CMSEncoderRef cmsEncoder, - Boolean detachedContent) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -OSStatus CMSEncoderGetHasDetachedContent( - CMSEncoderRef cmsEncoder, - Boolean *detachedContentOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSEncoderSetEncapsulatedContentType( - CMSEncoderRef cmsEncoder, - const CSSM_OID *eContentType) - - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSEncoderSetEncapsulatedContentTypeOID( - CMSEncoderRef cmsEncoder, - CFTypeRef eContentTypeOID) - __attribute__((availability(macosx,introduced=10.7))); -OSStatus CMSEncoderCopyEncapsulatedContentType( - CMSEncoderRef cmsEncoder, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) eContentTypeOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSEncoderAddSupportingCerts( - CMSEncoderRef cmsEncoder, - CFTypeRef certOrArray) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -OSStatus CMSEncoderCopySupportingCerts( - CMSEncoderRef cmsEncoder, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) certsOut) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -typedef uint32_t CMSSignedAttributes; enum { - kCMSAttrNone = 0x0000, - - - - - kCMSAttrSmimeCapabilities = 0x0001, - - - - kCMSAttrSmimeEncryptionKeyPrefs = 0x0002, - - - - - kCMSAttrSmimeMSEncryptionKeyPrefs = 0x0004, - - - - kCMSAttrSigningTime = 0x0008 -}; - - - - - - -OSStatus CMSEncoderAddSignedAttributes( - CMSEncoderRef cmsEncoder, - CMSSignedAttributes signedAttributes) - __attribute__((availability(macosx,introduced=10.5))); - - - - -typedef uint32_t CMSCertificateChainMode; enum { - kCMSCertificateNone = 0, - kCMSCertificateSignerOnly, - kCMSCertificateChain, - - kCMSCertificateChainWithRoot -}; -OSStatus CMSEncoderSetCertificateChainMode( - CMSEncoderRef cmsEncoder, - CMSCertificateChainMode chainMode) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -OSStatus CMSEncoderGetCertificateChainMode( - CMSEncoderRef cmsEncoder, - CMSCertificateChainMode *chainModeOut) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -OSStatus CMSEncoderUpdateContent( - CMSEncoderRef cmsEncoder, - const void *content, - size_t contentLen) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -OSStatus CMSEncoderCopyEncodedContent( - CMSEncoderRef cmsEncoder, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) encodedContentOut) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSEncode( - CFTypeRef _Nullable signers, - CFTypeRef _Nullable recipients, - const CSSM_OID * _Nullable eContentType, - Boolean detachedContent, - CMSSignedAttributes signedAttributes, - const void * content, - size_t contentLen, - CFDataRef * _Nonnull __attribute__((cf_returns_retained)) encodedContentOut) - - __attribute__((availability(macosx,introduced=10.5))); -OSStatus CMSEncodeContent( - CFTypeRef _Nullable signers, - CFTypeRef _Nullable recipients, - CFTypeRef _Nullable eContentTypeOID, - Boolean detachedContent, - CMSSignedAttributes signedAttributes, - const void *content, - size_t contentLen, - CFDataRef * _Nullable __attribute__((cf_returns_retained)) encodedContentOut) - __attribute__((availability(macosx,introduced=10.7))); - -OSStatus CMSEncoderCopySignerTimestamp( - CMSEncoderRef cmsEncoder, - size_t signerIndex, - CFAbsoluteTime *timestamp) - __attribute__((availability(macosx,introduced=10.8))); - -OSStatus CMSEncoderCopySignerTimestampWithPolicy( - CMSEncoderRef cmsEncoder, - CFTypeRef _Nullable timeStampPolicy, - size_t signerIndex, - CFAbsoluteTime *timestamp) - __attribute__((availability(macosx,introduced=10.10))); - - - - -} - - -typedef uint32_t SSLCipherSuite; - - - - - -enum -{ SSL_NULL_WITH_NULL_NULL = 0x0000, - SSL_RSA_WITH_NULL_MD5 = 0x0001, - SSL_RSA_WITH_NULL_SHA = 0x0002, - SSL_RSA_EXPORT_WITH_RC4_40_MD5 = 0x0003, - SSL_RSA_WITH_RC4_128_MD5 = 0x0004, - SSL_RSA_WITH_RC4_128_SHA = 0x0005, - SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = 0x0006, - SSL_RSA_WITH_IDEA_CBC_SHA = 0x0007, - SSL_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x0008, - SSL_RSA_WITH_DES_CBC_SHA = 0x0009, - SSL_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A, - SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x000B, - SSL_DH_DSS_WITH_DES_CBC_SHA = 0x000C, - SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA = 0x000D, - SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x000E, - SSL_DH_RSA_WITH_DES_CBC_SHA = 0x000F, - SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA = 0x0010, - SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x0011, - SSL_DHE_DSS_WITH_DES_CBC_SHA = 0x0012, - SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0x0013, - SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x0014, - SSL_DHE_RSA_WITH_DES_CBC_SHA = 0x0015, - SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016, - SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 = 0x0017, - SSL_DH_anon_WITH_RC4_128_MD5 = 0x0018, - SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA = 0x0019, - SSL_DH_anon_WITH_DES_CBC_SHA = 0x001A, - SSL_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x001B, - SSL_FORTEZZA_DMS_WITH_NULL_SHA = 0x001C, - SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA = 0x001D, - - - TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F, - TLS_DH_DSS_WITH_AES_128_CBC_SHA = 0x0030, - TLS_DH_RSA_WITH_AES_128_CBC_SHA = 0x0031, - TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x0032, - TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033, - TLS_DH_anon_WITH_AES_128_CBC_SHA = 0x0034, - TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035, - TLS_DH_DSS_WITH_AES_256_CBC_SHA = 0x0036, - TLS_DH_RSA_WITH_AES_256_CBC_SHA = 0x0037, - TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x0038, - TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039, - TLS_DH_anon_WITH_AES_256_CBC_SHA = 0x003A, - - - TLS_ECDH_ECDSA_WITH_NULL_SHA = 0xC001, - TLS_ECDH_ECDSA_WITH_RC4_128_SHA = 0xC002, - TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC003, - TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = 0xC004, - TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = 0xC005, - TLS_ECDHE_ECDSA_WITH_NULL_SHA = 0xC006, - TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = 0xC007, - TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC008, - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009, - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A, - TLS_ECDH_RSA_WITH_NULL_SHA = 0xC00B, - TLS_ECDH_RSA_WITH_RC4_128_SHA = 0xC00C, - TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = 0xC00D, - TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = 0xC00E, - TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = 0xC00F, - TLS_ECDHE_RSA_WITH_NULL_SHA = 0xC010, - TLS_ECDHE_RSA_WITH_RC4_128_SHA = 0xC011, - TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = 0xC012, - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013, - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014, - TLS_ECDH_anon_WITH_NULL_SHA = 0xC015, - TLS_ECDH_anon_WITH_RC4_128_SHA = 0xC016, - TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA = 0xC017, - TLS_ECDH_anon_WITH_AES_128_CBC_SHA = 0xC018, - TLS_ECDH_anon_WITH_AES_256_CBC_SHA = 0xC019, - - - - - TLS_NULL_WITH_NULL_NULL = 0x0000, - - - TLS_RSA_WITH_NULL_MD5 = 0x0001, - TLS_RSA_WITH_NULL_SHA = 0x0002, - TLS_RSA_WITH_RC4_128_MD5 = 0x0004, - TLS_RSA_WITH_RC4_128_SHA = 0x0005, - TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A, - - - TLS_RSA_WITH_NULL_SHA256 = 0x003B, - TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C, - TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D, - - - TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = 0x000D, - TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = 0x0010, - TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0x0013, - TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016, - TLS_DH_DSS_WITH_AES_128_CBC_SHA256 = 0x003E, - TLS_DH_RSA_WITH_AES_128_CBC_SHA256 = 0x003F, - TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = 0x0040, - TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067, - TLS_DH_DSS_WITH_AES_256_CBC_SHA256 = 0x0068, - TLS_DH_RSA_WITH_AES_256_CBC_SHA256 = 0x0069, - TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = 0x006A, - TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B, - - - TLS_DH_anon_WITH_RC4_128_MD5 = 0x0018, - TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x001B, - - - TLS_DH_anon_WITH_AES_128_CBC_SHA256 = 0x006C, - TLS_DH_anon_WITH_AES_256_CBC_SHA256 = 0x006D, - - - - TLS_PSK_WITH_RC4_128_SHA = 0x008A, - TLS_PSK_WITH_3DES_EDE_CBC_SHA = 0x008B, - TLS_PSK_WITH_AES_128_CBC_SHA = 0x008C, - TLS_PSK_WITH_AES_256_CBC_SHA = 0x008D, - TLS_DHE_PSK_WITH_RC4_128_SHA = 0x008E, - TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA = 0x008F, - TLS_DHE_PSK_WITH_AES_128_CBC_SHA = 0x0090, - TLS_DHE_PSK_WITH_AES_256_CBC_SHA = 0x0091, - TLS_RSA_PSK_WITH_RC4_128_SHA = 0x0092, - TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA = 0x0093, - TLS_RSA_PSK_WITH_AES_128_CBC_SHA = 0x0094, - TLS_RSA_PSK_WITH_AES_256_CBC_SHA = 0x0095, - - - - TLS_PSK_WITH_NULL_SHA = 0x002C, - TLS_DHE_PSK_WITH_NULL_SHA = 0x002D, - TLS_RSA_PSK_WITH_NULL_SHA = 0x002E, - - - - TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C, - TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D, - TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E, - TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F, - TLS_DH_RSA_WITH_AES_128_GCM_SHA256 = 0x00A0, - TLS_DH_RSA_WITH_AES_256_GCM_SHA384 = 0x00A1, - TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = 0x00A2, - TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = 0x00A3, - TLS_DH_DSS_WITH_AES_128_GCM_SHA256 = 0x00A4, - TLS_DH_DSS_WITH_AES_256_GCM_SHA384 = 0x00A5, - TLS_DH_anon_WITH_AES_128_GCM_SHA256 = 0x00A6, - TLS_DH_anon_WITH_AES_256_GCM_SHA384 = 0x00A7, - - - TLS_PSK_WITH_AES_128_GCM_SHA256 = 0x00A8, - TLS_PSK_WITH_AES_256_GCM_SHA384 = 0x00A9, - TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 = 0x00AA, - TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 = 0x00AB, - TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 = 0x00AC, - TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 = 0x00AD, - - TLS_PSK_WITH_AES_128_CBC_SHA256 = 0x00AE, - TLS_PSK_WITH_AES_256_CBC_SHA384 = 0x00AF, - TLS_PSK_WITH_NULL_SHA256 = 0x00B0, - TLS_PSK_WITH_NULL_SHA384 = 0x00B1, - - TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = 0x00B2, - TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = 0x00B3, - TLS_DHE_PSK_WITH_NULL_SHA256 = 0x00B4, - TLS_DHE_PSK_WITH_NULL_SHA384 = 0x00B5, - - TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 = 0x00B6, - TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 = 0x00B7, - TLS_RSA_PSK_WITH_NULL_SHA256 = 0x00B8, - TLS_RSA_PSK_WITH_NULL_SHA384 = 0x00B9, - - - - - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023, - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024, - TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC025, - TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC026, - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027, - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028, - TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 = 0xC029, - TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 = 0xC02A, - - - - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B, - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C, - TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02D, - TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02E, - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F, - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030, - TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 = 0xC031, - TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 = 0xC032, - - - TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00FF, - - - - - SSL_RSA_WITH_RC2_CBC_MD5 = 0xFF80, - SSL_RSA_WITH_IDEA_CBC_MD5 = 0xFF81, - SSL_RSA_WITH_DES_CBC_MD5 = 0xFF82, - SSL_RSA_WITH_3DES_EDE_CBC_MD5 = 0xFF83, - SSL_NO_SUCH_CIPHERSUITE = 0xFFFF -}; -extern "C" { -struct SSLContext; -typedef struct __attribute__((objc_bridge(id))) SSLContext *SSLContextRef; - - -typedef const void * SSLConnectionRef; - - -typedef int SSLProtocol; enum { - kSSLProtocolUnknown = 0, - kSSLProtocol3 = 2, - kTLSProtocol1 = 4, - kTLSProtocol11 = 7, - kTLSProtocol12 = 8, - kDTLSProtocol1 = 9, - - - kSSLProtocol2 = 1, - kSSLProtocol3Only = 3, - kTLSProtocol1Only = 5, - kSSLProtocolAll = 6, - -}; - - -typedef int SSLSessionOption; enum { - - - - - - - - kSSLSessionOptionBreakOnServerAuth = 0, - - - - - kSSLSessionOptionBreakOnCertRequested = 1, - - - - - - - kSSLSessionOptionBreakOnClientAuth = 2, - - - - - - kSSLSessionOptionFalseStart = 3, - - - - - - kSSLSessionOptionSendOneByteRecord = 4, - - - - - kSSLSessionOptionAllowServerIdentityChange = 5, - - - - - kSSLSessionOptionFallback = 6, - - - - kSSLSessionOptionBreakOnClientHello = 7, - -}; - - -typedef int SSLSessionState; enum { - kSSLIdle, - kSSLHandshake, - kSSLConnected, - kSSLClosed, - kSSLAborted -}; - - - - - -typedef int SSLClientCertificateState; enum { - - kSSLClientCertNone, - - kSSLClientCertRequested, - - - - - - - kSSLClientCertSent, - - - - - kSSLClientCertRejected -} ; -typedef OSStatus -(*SSLReadFunc) (SSLConnectionRef connection, - void *data, - - - size_t *dataLength); -typedef OSStatus -(*SSLWriteFunc) (SSLConnectionRef connection, - const void *data, - size_t *dataLength); -enum { - errSSLProtocol = -9800, - errSSLNegotiation = -9801, - errSSLFatalAlert = -9802, - errSSLWouldBlock = -9803, - errSSLSessionNotFound = -9804, - errSSLClosedGraceful = -9805, - errSSLClosedAbort = -9806, - errSSLXCertChainInvalid = -9807, - errSSLBadCert = -9808, - errSSLCrypto = -9809, - errSSLInternal = -9810, - errSSLModuleAttach = -9811, - errSSLUnknownRootCert = -9812, - errSSLNoRootCert = -9813, - errSSLCertExpired = -9814, - errSSLCertNotYetValid = -9815, - errSSLClosedNoNotify = -9816, - errSSLBufferOverflow = -9817, - errSSLBadCipherSuite = -9818, - - - errSSLPeerUnexpectedMsg = -9819, - errSSLPeerBadRecordMac = -9820, - errSSLPeerDecryptionFail = -9821, - errSSLPeerRecordOverflow = -9822, - errSSLPeerDecompressFail = -9823, - errSSLPeerHandshakeFail = -9824, - errSSLPeerBadCert = -9825, - errSSLPeerUnsupportedCert = -9826, - errSSLPeerCertRevoked = -9827, - errSSLPeerCertExpired = -9828, - errSSLPeerCertUnknown = -9829, - errSSLIllegalParam = -9830, - errSSLPeerUnknownCA = -9831, - errSSLPeerAccessDenied = -9832, - errSSLPeerDecodeError = -9833, - errSSLPeerDecryptError = -9834, - errSSLPeerExportRestriction = -9835, - errSSLPeerProtocolVersion = -9836, - errSSLPeerInsufficientSecurity = -9837, - errSSLPeerInternalError = -9838, - errSSLPeerUserCancelled = -9839, - errSSLPeerNoRenegotiation = -9840, - - - errSSLPeerAuthCompleted = -9841, - errSSLClientCertRequested = -9842, - - - errSSLHostNameMismatch = -9843, - errSSLConnectionRefused = -9844, - errSSLDecryptionFail = -9845, - errSSLBadRecordMac = -9846, - errSSLRecordOverflow = -9847, - errSSLBadConfiguration = -9848, - errSSLUnexpectedRecord = -9849, - errSSLWeakPeerEphemeralDHKey = -9850, - - - errSSLClientHelloReceived = -9851, -}; -typedef int SSLProtocolSide; enum -{ - kSSLServerSide, - kSSLClientSide -}; - -typedef int SSLConnectionType; enum -{ - kSSLStreamType, - kSSLDatagramType -}; -CFTypeID -SSLContextGetTypeID(void) - __attribute__((availability(macosx,introduced=10.8))); - - - - -_Nullable -SSLContextRef -SSLCreateContext(CFAllocatorRef _Nullable alloc, SSLProtocolSide protocolSide, SSLConnectionType connectionType) - __attribute__((availability(macosx,introduced=10.8))); -OSStatus -SSLNewContext (Boolean isServer, - SSLContextRef * _Nonnull __attribute__((cf_returns_retained)) contextPtr) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLDisposeContext (SSLContextRef context) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); - - - - - - -OSStatus -SSLGetSessionState (SSLContextRef context, - SSLSessionState *state) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -OSStatus -SSLSetSessionOption (SSLContextRef context, - SSLSessionOption option, - Boolean value) - __attribute__((availability(macosx,introduced=10.6))); - - - - -OSStatus -SSLGetSessionOption (SSLContextRef context, - SSLSessionOption option, - Boolean *value) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus -SSLSetIOFuncs (SSLContextRef context, - SSLReadFunc readFunc, - SSLWriteFunc writeFunc) - __attribute__((availability(macosx,introduced=10.2))); -OSStatus -SSLSetProtocolVersionMin (SSLContextRef context, - SSLProtocol minVersion) - __attribute__((availability(macosx,introduced=10.8))); - - - - -OSStatus -SSLGetProtocolVersionMin (SSLContextRef context, - SSLProtocol *minVersion) - __attribute__((availability(macosx,introduced=10.8))); -OSStatus -SSLSetProtocolVersionMax (SSLContextRef context, - SSLProtocol maxVersion) - __attribute__((availability(macosx,introduced=10.8))); - - - - -OSStatus -SSLGetProtocolVersionMax (SSLContextRef context, - SSLProtocol *maxVersion) - __attribute__((availability(macosx,introduced=10.8))); -OSStatus -SSLSetProtocolVersionEnabled (SSLContextRef context, - SSLProtocol protocol, - Boolean enable) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLGetProtocolVersionEnabled(SSLContextRef context, - SSLProtocol protocol, - Boolean *enable) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLSetProtocolVersion (SSLContextRef context, - SSLProtocol version) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -OSStatus -SSLGetProtocolVersion (SSLContextRef context, - SSLProtocol *protocol) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -OSStatus -SSLSetCertificate (SSLContextRef context, - CFArrayRef certRefs) - __attribute__((availability(macosx,introduced=10.2))); -OSStatus -SSLSetConnection (SSLContextRef context, - SSLConnectionRef _Nullable connection) - __attribute__((availability(macosx,introduced=10.2))); - -OSStatus -SSLGetConnection (SSLContextRef context, - SSLConnectionRef * _Nonnull __attribute__((cf_returns_not_retained)) connection) - __attribute__((availability(macosx,introduced=10.2))); -OSStatus -SSLSetPeerDomainName (SSLContextRef context, - const char * _Nullable peerName, - size_t peerNameLen) - __attribute__((availability(macosx,introduced=10.2))); - - - - -OSStatus -SSLGetPeerDomainNameLength (SSLContextRef context, - size_t *peerNameLen) - __attribute__((availability(macosx,introduced=10.2))); - - - - -OSStatus -SSLGetPeerDomainName (SSLContextRef context, - char *peerName, - size_t *peerNameLen) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -OSStatus -SSLSetDatagramHelloCookie (SSLContextRef dtlsContext, - const void * _Nullable cookie, - size_t cookieLen) - __attribute__((availability(macosx,introduced=10.8))); -OSStatus -SSLSetMaxDatagramRecordSize (SSLContextRef dtlsContext, - size_t maxSize) - __attribute__((availability(macosx,introduced=10.8))); - - - - - -OSStatus -SSLGetMaxDatagramRecordSize (SSLContextRef dtlsContext, - size_t *maxSize) - __attribute__((availability(macosx,introduced=10.8))); - - - - - - - -OSStatus -SSLGetNegotiatedProtocolVersion (SSLContextRef context, - SSLProtocol *protocol) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - - -OSStatus -SSLGetNumberSupportedCiphers (SSLContextRef context, - size_t *numCiphers) - __attribute__((availability(macosx,introduced=10.2))); - -OSStatus -SSLGetSupportedCiphers (SSLContextRef context, - SSLCipherSuite *ciphers, - size_t *numCiphers) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - - -OSStatus -SSLSetEnabledCiphers (SSLContextRef context, - const SSLCipherSuite *ciphers, - size_t numCiphers) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - - -OSStatus -SSLGetNumberEnabledCiphers (SSLContextRef context, - size_t *numCiphers) - __attribute__((availability(macosx,introduced=10.2))); - -OSStatus -SSLGetEnabledCiphers (SSLContextRef context, - SSLCipherSuite *ciphers, - size_t *numCiphers) - __attribute__((availability(macosx,introduced=10.2))); - - - -typedef int SSLSessionStrengthPolicy; enum -{ - kSSLSessionStrengthPolicyDefault, - kSSLSessionStrengthPolicyATSv1, - kSSLSessionStrengthPolicyATSv1_noPFS, -}; - -OSStatus -SSLSetSessionStrengthPolicy(SSLContextRef context, - SSLSessionStrengthPolicy policyStrength); -OSStatus -SSLSetEnableCertVerify (SSLContextRef context, - Boolean enableVerify) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLGetEnableCertVerify (SSLContextRef context, - Boolean *enableVerify) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLSetAllowsExpiredCerts (SSLContextRef context, - Boolean allowsExpired) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLGetAllowsExpiredCerts (SSLContextRef context, - Boolean *allowsExpired) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLSetAllowsExpiredRoots (SSLContextRef context, - Boolean allowsExpired) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLGetAllowsExpiredRoots (SSLContextRef context, - Boolean *allowsExpired) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLSetAllowsAnyRoot (SSLContextRef context, - Boolean anyRoot) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLGetAllowsAnyRoot (SSLContextRef context, - Boolean *anyRoot) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLSetTrustedRoots (SSLContextRef context, - CFArrayRef trustedRoots, - Boolean replaceExisting) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLCopyTrustedRoots (SSLContextRef context, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) trustedRoots) - __attribute__((availability(macosx,introduced=10.5,deprecated=10.9))); -OSStatus -SSLCopyPeerCertificates (SSLContextRef context, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) certs) - __attribute__((availability(macosx,introduced=10.5,deprecated=10.9))); -OSStatus -SSLCopyPeerTrust (SSLContextRef context, - SecTrustRef * _Nonnull __attribute__((cf_returns_retained)) trust) - __attribute__((availability(macosx,introduced=10.6))); -OSStatus -SSLSetPeerID (SSLContextRef context, - const void * _Nullable peerID, - size_t peerIDLen) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -OSStatus -SSLGetPeerID (SSLContextRef context, - const void * _Nullable * _Nonnull peerID, - size_t *peerIDLen) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -OSStatus -SSLGetNegotiatedCipher (SSLContextRef context, - SSLCipherSuite *cipherSuite) - __attribute__((availability(macosx,introduced=10.2))); -OSStatus -SSLSetEncryptionCertificate (SSLContextRef context, - CFArrayRef certRefs) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.11))); - - - - - - - -typedef int SSLAuthenticate; enum { - kNeverAuthenticate, - kAlwaysAuthenticate, - kTryAuthenticate - -}; - -OSStatus -SSLSetClientSideAuthenticate (SSLContextRef context, - SSLAuthenticate auth) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -OSStatus -SSLAddDistinguishedName (SSLContextRef context, - const void * _Nullable derDN, - size_t derDNLen) - __attribute__((availability(macosx,introduced=10.4))); -OSStatus -SSLSetCertificateAuthorities(SSLContextRef context, - CFTypeRef certificateOrArray, - Boolean replaceExisting) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus -SSLCopyCertificateAuthorities(SSLContextRef context, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) certificates) - __attribute__((availability(macosx,introduced=10.5))); -OSStatus -SSLCopyDistinguishedNames (SSLContextRef context, - CFArrayRef * _Nonnull __attribute__((cf_returns_retained)) names) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -OSStatus -SSLGetClientCertificateState (SSLContextRef context, - SSLClientCertificateState *clientState) - __attribute__((availability(macosx,introduced=10.3))); -OSStatus SSLSetDiffieHellmanParams (SSLContextRef context, - const void * _Nullable dhParams, - size_t dhParamsLen) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - - -OSStatus SSLGetDiffieHellmanParams (SSLContextRef context, - const void * _Nullable * _Nonnull dhParams, - size_t *dhParamsLen) - __attribute__((availability(macosx,introduced=10.2))); -OSStatus SSLSetRsaBlinding (SSLContextRef context, - Boolean blinding) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); - -OSStatus SSLGetRsaBlinding (SSLContextRef context, - Boolean *blinding) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -OSStatus -SSLHandshake (SSLContextRef context) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -OSStatus -SSLWrite (SSLContextRef context, - const void * _Nullable data, - size_t dataLength, - size_t *processed) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -OSStatus -SSLRead (SSLContextRef context, - void * data, - size_t dataLength, - size_t *processed) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -OSStatus -SSLGetBufferedReadSize (SSLContextRef context, - size_t *bufSize) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - - -OSStatus -SSLGetDatagramWriteSize (SSLContextRef dtlsContext, - size_t *bufSize) - __attribute__((availability(macosx,introduced=10.8))); - - - - -OSStatus -SSLClose (SSLContextRef context) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -} - - -extern "C" { -extern const CFStringRef kSecTransformErrorDomain; -extern const CFStringRef kSecTransformPreviousErrorKey; - - - - - - -extern const CFStringRef kSecTransformAbortOriginatorKey; -enum -{ - kSecTransformErrorAttributeNotFound = 1, - kSecTransformErrorInvalidOperation = 2, - kSecTransformErrorNotInitializedCorrectly = 3, - kSecTransformErrorMoreThanOneOutput = 4, - kSecTransformErrorInvalidInputDictionary = 5, - kSecTransformErrorInvalidAlgorithm = 6, - kSecTransformErrorInvalidLength = 7, - kSecTransformErrorInvalidType = 8, - kSecTransformErrorInvalidInput = 10, - kSecTransformErrorNameAlreadyRegistered = 11, - kSecTransformErrorUnsupportedAttribute = 12, - kSecTransformOperationNotSupportedOnGroup = 13, - kSecTransformErrorMissingParameter = 14, - kSecTransformErrorInvalidConnection = 15, - kSecTransformTransformIsExecuting = 16, - kSecTransformInvalidOverride = 17, - kSecTransformTransformIsNotRegistered = 18, - kSecTransformErrorAbortInProgress = 19, - kSecTransformErrorAborted = 20, - kSecTransformInvalidArgument = 21 - -}; - -typedef CFTypeRef SecTransformRef; -typedef CFTypeRef SecGroupTransformRef; - - - - - - - -extern CFTypeID SecTransformGetTypeID(void); -extern CFTypeID SecGroupTransformGetTypeID(void); - - - - - - - -extern const CFStringRef kSecTransformInputAttributeName __attribute__((availability(macosx,introduced=10.7))); - - - - - -extern const CFStringRef kSecTransformOutputAttributeName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kSecTransformDebugAttributeName __attribute__((availability(macosx,introduced=10.7))); - - - - - -extern const CFStringRef kSecTransformTransformName __attribute__((availability(macosx,introduced=10.7))); - - - - - -extern const CFStringRef kSecTransformAbortAttributeName __attribute__((availability(macosx,introduced=10.7))); -extern _Nullable -SecTransformRef SecTransformCreateFromExternalRepresentation( - CFDictionaryRef dictionary, - CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -extern -CFDictionaryRef SecTransformCopyExternalRepresentation( - SecTransformRef transformRef) - __attribute__((availability(macosx,introduced=10.7))); -extern -SecGroupTransformRef SecTransformCreateGroupTransform(void); -extern _Nullable -SecGroupTransformRef SecTransformConnectTransforms(SecTransformRef sourceTransformRef, - CFStringRef sourceAttributeName, - SecTransformRef destinationTransformRef, - CFStringRef destinationAttributeName, - SecGroupTransformRef group, - CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -extern -Boolean SecTransformSetAttribute(SecTransformRef transformRef, - CFStringRef key, - CFTypeRef value, - CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -extern _Nullable -CFTypeRef SecTransformGetAttribute(SecTransformRef transformRef, - CFStringRef key) - __attribute__((availability(macosx,introduced=10.7))); -extern _Nullable -SecTransformRef SecTransformFindByName(SecGroupTransformRef transform, - CFStringRef name) - __attribute__((availability(macosx,introduced=10.7))); -extern __attribute__((cf_returns_retained)) -CFTypeRef SecTransformExecute(SecTransformRef transformRef, CFErrorRef* errorRef) - __attribute__((availability(macosx,introduced=10.7))) __attribute__((cf_returns_retained)); -typedef void (*SecMessageBlock)(CFTypeRef _Nullable message, CFErrorRef _Nullable error, - Boolean isFinal); -extern -void SecTransformExecuteAsync(SecTransformRef transformRef, - dispatch_queue_t deliveryQueue, - SecMessageBlock deliveryBlock) - __attribute__((availability(macosx,introduced=10.7))); - - - -} -extern "C" { -typedef CFIndex SecTransformMetaAttributeType; enum -{ - kSecTransformMetaAttributeValue, - kSecTransformMetaAttributeName, - kSecTransformMetaAttributeRef, - kSecTransformMetaAttributeRequired, - kSecTransformMetaAttributeRequiresOutboundConnection, - kSecTransformMetaAttributeDeferred, - kSecTransformMetaAttributeStream, - kSecTransformMetaAttributeCanCycle, - kSecTransformMetaAttributeExternalize, - kSecTransformMetaAttributeHasOutboundConnections, - kSecTransformMetaAttributeHasInboundConnection -}; -typedef CFTypeRef SecTransformAttributeRef; -typedef CFTypeRef SecTransformStringOrAttributeRef; -typedef CFTypeRef _Nullable (*SecTransformActionBlock)(void); -typedef CFTypeRef _Nullable (*SecTransformAttributeActionBlock)( - SecTransformAttributeRef attribute, - CFTypeRef value); -typedef CFTypeRef _Nullable (*SecTransformDataBlock)(CFTypeRef data); -typedef CFErrorRef _Nullable (*SecTransformInstanceBlock)(void); -typedef const struct OpaqueSecTransformImplementation* SecTransformImplementationRef; -extern _Nullable -CFErrorRef SecTransformSetAttributeAction(SecTransformImplementationRef ref, - CFStringRef action, - SecTransformStringOrAttributeRef _Nullable attribute, - SecTransformAttributeActionBlock newAction); -extern _Nullable -CFErrorRef SecTransformSetDataAction(SecTransformImplementationRef ref, - CFStringRef action, - SecTransformDataBlock newAction); -extern _Nullable -CFErrorRef SecTransformSetTransformAction(SecTransformImplementationRef ref, - CFStringRef action, - SecTransformActionBlock newAction); -extern _Nullable -CFTypeRef SecTranformCustomGetAttribute(SecTransformImplementationRef ref, - SecTransformStringOrAttributeRef attribute, - SecTransformMetaAttributeType type) __attribute__((availability(macosx,introduced=10.7,deprecated=10.8))); -extern _Nullable -CFTypeRef SecTransformCustomGetAttribute(SecTransformImplementationRef ref, - SecTransformStringOrAttributeRef attribute, - SecTransformMetaAttributeType type) __asm__("_SecTranformCustomGetAttribute"); -extern _Nullable -CFTypeRef SecTransformCustomSetAttribute(SecTransformImplementationRef ref, - SecTransformStringOrAttributeRef attribute, - SecTransformMetaAttributeType type, - CFTypeRef _Nullable value); -extern _Nullable -CFTypeRef SecTransformPushbackAttribute(SecTransformImplementationRef ref, - SecTransformStringOrAttributeRef attribute, - CFTypeRef value); -typedef SecTransformInstanceBlock _Nonnull (*SecTransformCreateFP)(CFStringRef name, - SecTransformRef newTransform, - SecTransformImplementationRef ref); -extern const CFStringRef kSecTransformActionCanExecute; - - - - - - - -extern const CFStringRef kSecTransformActionStartingExecution; -extern const CFStringRef kSecTransformActionFinalize; -extern const CFStringRef kSecTransformActionExternalizeExtraData; -extern const CFStringRef kSecTransformActionProcessData; -extern const CFStringRef kSecTransformActionInternalizeExtraData; -extern const CFStringRef kSecTransformActionAttributeNotification; -extern const CFStringRef kSecTransformActionAttributeValidation; -extern -Boolean SecTransformRegister(CFStringRef uniqueName, - SecTransformCreateFP createTransformFunction, - CFErrorRef* error) - __attribute__((availability(macosx,introduced=10.7))); -extern _Nullable -SecTransformRef SecTransformCreate(CFStringRef name, CFErrorRef *error) - __attribute__((availability(macosx,introduced=10.7))); -extern -CFTypeRef SecTransformNoData(void); - - - - -} -extern "C" { -extern const CFStringRef kSecBase64Encoding; - - - - -extern const CFStringRef kSecBase32Encoding; - - - - -extern const CFStringRef kSecZLibEncoding; - - - - - - - -extern const CFStringRef kSecEncodeTypeAttribute; - - -extern const CFStringRef kSecLineLength64; -extern const CFStringRef kSecLineLength76; -extern const CFStringRef kSecEncodeLineLengthAttribute; - -extern const CFStringRef kSecCompressionRatio; -_Nullable -SecTransformRef SecEncodeTransformCreate(CFTypeRef encodeType, - CFErrorRef* error - ) -__attribute__((availability(macosx,introduced=10.7))); - - - - - -} - - -extern "C" { - extern const CFStringRef kSecDecodeTypeAttribute; - _Nullable - SecTransformRef SecDecodeTransformCreate(CFTypeRef DecodeType, - CFErrorRef* error - ) - __attribute__((availability(macosx,introduced=10.7))); - - - - - -} -extern "C" { -extern const CFStringRef kSecDigestMD2; - - - - - -extern const CFStringRef kSecDigestMD4; - - - - - -extern const CFStringRef kSecDigestMD5; - - - - - -extern const CFStringRef kSecDigestSHA1; - - - - - -extern const CFStringRef kSecDigestSHA2; - - - - - -extern const CFStringRef kSecDigestHMACMD5; - - - - - -extern const CFStringRef kSecDigestHMACSHA1; - - - - - -extern const CFStringRef kSecDigestHMACSHA2; - - - - - - - -extern const CFStringRef kSecDigestTypeAttribute; - - - - - - -extern const CFStringRef kSecDigestLengthAttribute; -extern const CFStringRef kSecDigestHMACKeyAttribute; -SecTransformRef SecDigestTransformCreate(CFTypeRef _Nullable digestType, - CFIndex digestLength, - CFErrorRef* error - ) - __attribute__((availability(macosx,introduced=10.7))); -CFTypeID SecDigestTransformGetTypeID() - __attribute__((availability(macosx,introduced=10.7))); - - - - - -}; - -extern "C" { - - - - - - - extern const CFStringRef kSecPaddingNoneKey; - - extern const CFStringRef kSecPaddingPKCS1Key; - - extern const CFStringRef kSecPaddingPKCS5Key; - - extern const CFStringRef kSecPaddingPKCS7Key; - - extern const CFStringRef kSecPaddingOAEPKey - __attribute__((availability(macosx,introduced=10.8))); - - extern const CFStringRef kSecModeNoneKey; - - extern const CFStringRef kSecModeECBKey; - - extern const CFStringRef kSecModeCBCKey; - - extern const CFStringRef kSecModeCFBKey; - - extern const CFStringRef kSecModeOFBKey; - - - - - - extern const CFStringRef kSecEncryptKey; - extern const CFStringRef kSecPaddingKey; - extern const CFStringRef kSecIVKey; - extern const CFStringRef kSecEncryptionMode; - extern const CFStringRef kSecOAEPMessageLengthAttributeName - __attribute__((availability(macosx,introduced=10.8))); - extern const CFStringRef kSecOAEPEncodingParametersAttributeName - __attribute__((availability(macosx,introduced=10.8))); - - - - - - - - extern const CFStringRef kSecOAEPMGF1DigestAlgorithmAttributeName - __attribute__((availability(macosx,introduced=10.8))); - SecTransformRef SecEncryptTransformCreate(SecKeyRef keyRef, - CFErrorRef* error) - __attribute__((availability(macosx,introduced=10.7))); - SecTransformRef SecDecryptTransformCreate(SecKeyRef keyRef, - CFErrorRef* error) - __attribute__((availability(macosx,introduced=10.7))); - - - - - - - - CFTypeID SecDecryptTransformGetTypeID() - __attribute__((availability(macosx,introduced=10.7))); - - - - - - - - CFTypeID SecEncryptTransformGetTypeID() - __attribute__((availability(macosx,introduced=10.7))); - - - - - -}; -extern "C" { - - - - - - extern const CFStringRef kSecKeyAttributeName, kSecSignatureAttributeName, kSecInputIsAttributeName; - - extern const CFStringRef kSecInputIsPlainText, kSecInputIsDigest, kSecInputIsRaw; - _Nullable - SecTransformRef SecSignTransformCreate(SecKeyRef key, - CFErrorRef* error - ) - __attribute__((availability(macosx,introduced=10.7))); - _Nullable - SecTransformRef SecVerifyTransformCreate(SecKeyRef key, - CFDataRef _Nullable signature, - CFErrorRef* error - ) - __attribute__((availability(macosx,introduced=10.7))); - - - - - -}; -extern "C" { -SecTransformRef SecTransformCreateReadTransformWithReadStream(CFReadStreamRef inputStream) - __attribute__((availability(macosx,introduced=10.7))); - - - - - -}; - - - -extern "C" { - - - - - -typedef uint8_t DERByte; -typedef size_t DERSize; - - - - -typedef struct { - DERByte *data; - DERSize length; -} DERItem; - - -extern const DERItem - oidRsa, - oidMd2Rsa, - oidMd4Rsa, - oidMd5Rsa, - oidSha1Rsa, - oidSha256Rsa, - oidSha384Rsa, - oidSha512Rsa, - oidSha224Rsa, - oidEcPubKey, - oidSha1Ecdsa, - oidSha224Ecdsa, - oidSha256Ecdsa, - oidSha384Ecdsa, - oidSha512Ecdsa, - oidSha1Dsa, - oidMd2, - oidMd4, - oidMd5, - oidSha1, - oidSha1DsaOIW, - oidSha1DsaCommonOIW, - oidSha1RsaOIW, - oidSha256, - oidSha384, - oidSha512, - oidSha224, - oidFee, - oidMd5Fee, - oidSha1Fee; - - -extern const DERItem - oidSubjectKeyIdentifier, - oidKeyUsage, - oidPrivateKeyUsagePeriod, - oidSubjectAltName, - oidIssuerAltName, - oidBasicConstraints, - oidNameConstraints, - oidCrlDistributionPoints, - oidCertificatePolicies, - oidAnyPolicy, - oidPolicyMappings, - oidAuthorityKeyIdentifier, - oidPolicyConstraints, - oidExtendedKeyUsage, - oidAnyExtendedKeyUsage, - oidInhibitAnyPolicy, - oidAuthorityInfoAccess, - oidSubjectInfoAccess, - oidAdOCSP, - oidAdCAIssuer, - oidNetscapeCertType, - oidEntrustVersInfo, - oidMSNTPrincipalName; - - -extern const DERItem - oidQtCps, - oidQtUNotice; - - -extern const DERItem - oidCommonName, - oidCountryName, - oidLocalityName, - oidStateOrProvinceName, - oidOrganizationName, - oidOrganizationalUnitName, - oidDescription, - oidEmailAddress, - oidFriendlyName, - oidLocalKeyId; - - -extern const DERItem - oidExtendedKeyUsageServerAuth, - oidExtendedKeyUsageClientAuth, - oidExtendedKeyUsageCodeSigning, - oidExtendedKeyUsageEmailProtection, - oidExtendedKeyUsageTimeStamping, - oidExtendedKeyUsageOCSPSigning, - oidExtendedKeyUsageIPSec, - oidExtendedKeyUsageMicrosoftSGC, - oidExtendedKeyUsageNetscapeSGC; - - -extern const DERItem - oidGoogleEmbeddedSignedCertificateTimestamp, - oidGoogleOCSPSignedCertificateTimestamp; - - -} - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -typedef NSUInteger NSURLCredentialPersistence; enum { - NSURLCredentialPersistenceNone, - NSURLCredentialPersistenceForSession, - NSURLCredentialPersistencePermanent, - NSURLCredentialPersistenceSynchronizable __attribute__((availability(macosx,introduced=10_8))) -}; - -// @class NSURLCredentialInternal; -#ifndef _REWRITER_typedef_NSURLCredentialInternal -#define _REWRITER_typedef_NSURLCredentialInternal -typedef struct objc_object NSURLCredentialInternal; -typedef struct {} _objc_exc_NSURLCredentialInternal; -#endif - - - - - - - - -#ifndef _REWRITER_typedef_NSURLCredential -#define _REWRITER_typedef_NSURLCredential -typedef struct objc_object NSURLCredential; -typedef struct {} _objc_exc_NSURLCredential; -#endif - -struct NSURLCredential_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLCredentialInternal *_internal; -}; - - - - - - - -// @property (readonly) NSURLCredentialPersistence persistence; - -/* @end */ - - - - - - -// @interface NSURLCredential(NSInternetPassword) -// - (instancetype)initWithUser:(NSString *)user password:(NSString *)password persistence:(NSURLCredentialPersistence)persistence; -// + (NSURLCredential *)credentialWithUser:(NSString *)user password:(NSString *)password persistence:(NSURLCredentialPersistence)persistence; - - - - - - -// @property (nullable, readonly, copy) NSString *user; -// @property (nullable, readonly, copy) NSString *password; -// @property (readonly) BOOL hasPassword; - -/* @end */ - - - - - - -// @interface NSURLCredential(NSClientCertificate) -// - (instancetype)initWithIdentity:(SecIdentityRef)identity certificates:(nullable NSArray *)certArray persistence:(NSURLCredentialPersistence)persistence __attribute__((availability(macosx,introduced=10_6))); -// + (NSURLCredential *)credentialWithIdentity:(SecIdentityRef)identity certificates:(nullable NSArray *)certArray persistence:(NSURLCredentialPersistence)persistence __attribute__((availability(macosx,introduced=10_6))); - - - - - - -// @property (nullable, readonly) SecIdentityRef identity; - - - - - - -// @property (readonly, copy) NSArray *certificates __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -// @interface NSURLCredential(NSServerTrust) - - - - - - -// - (instancetype)initWithTrust:(SecTrustRef)trust __attribute__((availability(macosx,introduced=10_6))); - - - - - - -// + (NSURLCredential *)credentialForTrust:(SecTrustRef)trust __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - - - - - - - - -extern "C" NSString * const NSURLProtectionSpaceHTTP __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern "C" NSString * const NSURLProtectionSpaceHTTPS __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern "C" NSString * const NSURLProtectionSpaceFTP __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern "C" NSString * const NSURLProtectionSpaceHTTPProxy; - - - - - -extern "C" NSString * const NSURLProtectionSpaceHTTPSProxy; - - - - - -extern "C" NSString * const NSURLProtectionSpaceFTPProxy; - - - - - -extern "C" NSString * const NSURLProtectionSpaceSOCKSProxy; - - - - - -extern "C" NSString * const NSURLAuthenticationMethodDefault; - - - - - - -extern "C" NSString * const NSURLAuthenticationMethodHTTPBasic; - - - - - -extern "C" NSString * const NSURLAuthenticationMethodHTTPDigest; - - - - - -extern "C" NSString * const NSURLAuthenticationMethodHTMLForm; - - - - - -extern "C" NSString * const NSURLAuthenticationMethodNTLM __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern "C" NSString * const NSURLAuthenticationMethodNegotiate __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern "C" NSString * const NSURLAuthenticationMethodClientCertificate __attribute__((availability(macosx,introduced=10_6))); - - - - - -extern "C" NSString * const NSURLAuthenticationMethodServerTrust __attribute__((availability(macosx,introduced=10_6))); - -// @class NSURLProtectionSpaceInternal; -#ifndef _REWRITER_typedef_NSURLProtectionSpaceInternal -#define _REWRITER_typedef_NSURLProtectionSpaceInternal -typedef struct objc_object NSURLProtectionSpaceInternal; -typedef struct {} _objc_exc_NSURLProtectionSpaceInternal; -#endif - - - - - - - - -#ifndef _REWRITER_typedef_NSURLProtectionSpace -#define _REWRITER_typedef_NSURLProtectionSpace -typedef struct objc_object NSURLProtectionSpace; -typedef struct {} _objc_exc_NSURLProtectionSpace; -#endif - -struct NSURLProtectionSpace_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLProtectionSpaceInternal *_internal; -}; - -// - (instancetype)initWithHost:(NSString *)host port:(NSInteger)port protocol:(nullable NSString *)protocol realm:(nullable NSString *)realm authenticationMethod:(nullable NSString *)authenticationMethod; -// - (instancetype)initWithProxyHost:(NSString *)host port:(NSInteger)port type:(nullable NSString *)type realm:(nullable NSString *)realm authenticationMethod:(nullable NSString *)authenticationMethod; -// @property (nullable, readonly, copy) NSString *realm; - - - - - - -// @property (readonly) BOOL receivesCredentialSecurely; - - - - - - -// @property (readonly) BOOL isProxy; - - - - - - -// @property (readonly, copy) NSString *host; - - - - - - -// @property (readonly) NSInteger port; - - - - - - -// @property (nullable, readonly, copy) NSString *proxyType; - - - - - - -// @property (nullable, readonly, copy) NSString *protocol; - - - - - - -// @property (readonly, copy) NSString *authenticationMethod; - -/* @end */ - - - - - - -// @interface NSURLProtectionSpace(NSClientCertificateSpace) - - - - - - -// @property (nullable, readonly, copy) NSArray<NSData *> *distinguishedNames __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - - - - - -// @interface NSURLProtectionSpace(NSServerTrustValidationSpace) - - - - - - -// @property (nullable, readonly) SecTrustRef serverTrust __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSURLCredential; -#ifndef _REWRITER_typedef_NSURLCredential -#define _REWRITER_typedef_NSURLCredential -typedef struct objc_object NSURLCredential; -typedef struct {} _objc_exc_NSURLCredential; -#endif - -// @class NSURLSessionTask; -#ifndef _REWRITER_typedef_NSURLSessionTask -#define _REWRITER_typedef_NSURLSessionTask -typedef struct objc_object NSURLSessionTask; -typedef struct {} _objc_exc_NSURLSessionTask; -#endif - - -// @class NSURLCredentialStorageInternal; -#ifndef _REWRITER_typedef_NSURLCredentialStorageInternal -#define _REWRITER_typedef_NSURLCredentialStorageInternal -typedef struct objc_object NSURLCredentialStorageInternal; -typedef struct {} _objc_exc_NSURLCredentialStorageInternal; -#endif - - -#ifndef _REWRITER_typedef_NSURLCredentialStorage -#define _REWRITER_typedef_NSURLCredentialStorage -typedef struct objc_object NSURLCredentialStorage; -typedef struct {} _objc_exc_NSURLCredentialStorage; -#endif - -struct NSURLCredentialStorage_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLCredentialStorageInternal *_internal; -}; - - - - - - - -// + (NSURLCredentialStorage *)sharedCredentialStorage; - - - - - - - -// - (nullable NSDictionary<NSString *, NSURLCredential *> *)credentialsForProtectionSpace:(NSURLProtectionSpace *)space; -// @property (readonly, copy) NSDictionary<NSURLProtectionSpace *, NSDictionary<NSString *, NSURLCredential *> *> *allCredentials; -// - (void)setCredential:(NSURLCredential *)credential forProtectionSpace:(NSURLProtectionSpace *)space; -// - (void)removeCredential:(NSURLCredential *)credential forProtectionSpace:(NSURLProtectionSpace *)space; -// - (void)removeCredential:(NSURLCredential *)credential forProtectionSpace:(NSURLProtectionSpace *)space options:(nullable NSDictionary<NSString *, id> *)options __attribute__((availability(macosx,introduced=10_9))); - - - - - - -// - (nullable NSURLCredential *)defaultCredentialForProtectionSpace:(NSURLProtectionSpace *)space; -// - (void)setDefaultCredential:(NSURLCredential *)credential forProtectionSpace:(NSURLProtectionSpace *)space; - -/* @end */ - - -// @interface NSURLCredentialStorage (NSURLSessionTaskAdditions) -// - (void)getCredentialsForProtectionSpace:(NSURLProtectionSpace *)protectionSpace task:(NSURLSessionTask *)task completionHandler:(void (^) (NSDictionary<NSString *, NSURLCredential *> * _Nullable credentials))completionHandler __attribute__((availability(macosx,introduced=10_10))); -// - (void)setCredential:(NSURLCredential *)credential forProtectionSpace:(NSURLProtectionSpace *)protectionSpace task:(NSURLSessionTask *)task __attribute__((availability(macosx,introduced=10_10))); -// - (void)removeCredential:(NSURLCredential *)credential forProtectionSpace:(NSURLProtectionSpace *)protectionSpace options:(nullable NSDictionary<NSString *, id> *)options task:(NSURLSessionTask *)task __attribute__((availability(macosx,introduced=10_10))); -// - (void)getDefaultCredentialForProtectionSpace:(NSURLProtectionSpace *)space task:(NSURLSessionTask *)task completionHandler:(void (^) (NSURLCredential * _Nullable credential))completionHandler __attribute__((availability(macosx,introduced=10_10))); -// - (void)setDefaultCredential:(NSURLCredential *)credential forProtectionSpace:(NSURLProtectionSpace *)protectionSpace task:(NSURLSessionTask *)task __attribute__((availability(macosx,introduced=10_10))); -/* @end */ - - - - - - - -extern "C" NSString *const NSURLCredentialStorageChangedNotification; - - - - - - - -extern "C" NSString *const NSURLCredentialStorageRemoveSynchronizableCredentials __attribute__((availability(macosx,introduced=10_9))); -#pragma pack(push, 2) - - -enum { - kClippingCreator = 'drag', - kClippingPictureType = 'clpp', - kClippingTextType = 'clpt', - kClippingSoundType = 'clps', - kClippingUnknownType = 'clpu' -}; - - - -enum { - kInternetLocationCreator = 'drag', - kInternetLocationHTTP = 'ilht', - kInternetLocationFTP = 'ilft', - kInternetLocationFile = 'ilfi', - kInternetLocationMail = 'ilma', - kInternetLocationNNTP = 'ilnw', - kInternetLocationAFP = 'ilaf', - kInternetLocationAppleTalk = 'ilat', - kInternetLocationNSL = 'ilns', - kInternetLocationGeneric = 'ilge' -}; - - - -enum { - kCustomIconResource = -16455 -}; - - - - - - -enum { - kCustomBadgeResourceType = 'badg', - kCustomBadgeResourceID = kCustomIconResource, - kCustomBadgeResourceVersion = 0 -}; - -struct CustomBadgeResource { - SInt16 version; - SInt16 customBadgeResourceID; - - OSType customBadgeType; - OSType customBadgeCreator; - OSType windowBadgeType; - OSType windowBadgeCreator; - - OSType overrideType; - OSType overrideCreator; -}; -typedef struct CustomBadgeResource CustomBadgeResource; -typedef CustomBadgeResource * CustomBadgeResourcePtr; -typedef CustomBadgeResourcePtr * CustomBadgeResourceHandle; -enum { - kRoutingResourceType = 'rout', - kRoutingResourceID = 0 -}; - -struct RoutingResourceEntry { - OSType creator; - OSType fileType; - OSType targetFolder; - OSType destinationFolder; - OSType reservedField; -}; -typedef struct RoutingResourceEntry RoutingResourceEntry; -typedef RoutingResourceEntry * RoutingResourcePtr; -typedef RoutingResourcePtr * RoutingResourceHandle; - - -enum { - kContainerFolderAliasType = 'fdrp', - kContainerTrashAliasType = 'trsh', - kContainerHardDiskAliasType = 'hdsk', - kContainerFloppyAliasType = 'flpy', - kContainerServerAliasType = 'srvr', - kApplicationAliasType = 'adrp', - kContainerAliasType = 'drop', - kDesktopPrinterAliasType = 'dtpa', - kContainerCDROMAliasType = 'cddr', - kApplicationCPAliasType = 'acdp', - kApplicationDAAliasType = 'addp', - kPackageAliasType = 'fpka', - kAppPackageAliasType = 'fapa' -}; - - -enum { - kSystemFolderAliasType = 'fasy', - kAppleMenuFolderAliasType = 'faam', - kStartupFolderAliasType = 'fast', - kPrintMonitorDocsFolderAliasType = 'fapn', - kPreferencesFolderAliasType = 'fapf', - kControlPanelFolderAliasType = 'fact', - kExtensionFolderAliasType = 'faex' -}; - - -enum { - kExportedFolderAliasType = 'faet', - kDropFolderAliasType = 'fadr', - kSharedFolderAliasType = 'fash', - kMountedFolderAliasType = 'famn' -}; - - - - - -enum { - kIsOnDesk = 0x0001, - kColor = 0x000E, - - kIsShared = 0x0040, - - - - kHasNoINITs = 0x0080, - - kHasBeenInited = 0x0100, - - - - - - kHasCustomIcon = 0x0400, - kIsStationery = 0x0800, - kNameLocked = 0x1000, - kHasBundle = 0x2000, - - - kIsInvisible = 0x4000, - kIsAlias = 0x8000 -}; - - -enum { - fOnDesk = kIsOnDesk, - fHasBundle = kHasBundle, - fInvisible = kIsInvisible -}; - - -enum { - fTrash = -3, - fDesktop = -2, - fDisk = 0 -}; -enum { - kExtendedFlagsAreInvalid = 0x8000, - kExtendedFlagHasCustomBadge = 0x0100, - kExtendedFlagObjectIsBusy = 0x0080, - kExtendedFlagHasRoutingInfo = 0x0004 -}; -enum { - kFirstMagicBusyFiletype = 'bzy ', - kLastMagicBusyFiletype = 'bzy?' -}; - - - - - - -enum { - kMagicBusyCreationDate = 0x4F3AFDB0 -}; -struct FileInfo { - OSType fileType; - OSType fileCreator; - UInt16 finderFlags; - Point location; - - UInt16 reservedField; -}; -typedef struct FileInfo FileInfo; -struct FolderInfo { - Rect windowBounds; - UInt16 finderFlags; - Point location; - - UInt16 reservedField; -}; -typedef struct FolderInfo FolderInfo; -struct ExtendedFileInfo { - SInt16 reserved1[4]; - UInt16 extendedFinderFlags; - SInt16 reserved2; - SInt32 putAwayFolderID; -}; -typedef struct ExtendedFileInfo ExtendedFileInfo; -struct ExtendedFolderInfo { - Point scrollPosition; - SInt32 reserved1; - UInt16 extendedFinderFlags; - SInt16 reserved2; - SInt32 putAwayFolderID; -}; -typedef struct ExtendedFolderInfo ExtendedFolderInfo; -struct FInfo { - OSType fdType; - OSType fdCreator; - UInt16 fdFlags; - Point fdLocation; - - SInt16 fdFldr; -}; -typedef struct FInfo FInfo; - - - - - - - -struct FXInfo { - SInt16 fdIconID; - SInt16 fdReserved[3]; - SInt8 fdScript; - SInt8 fdXFlags; - SInt16 fdComment; - SInt32 fdPutAway; -}; -typedef struct FXInfo FXInfo; - - - - - - -struct DInfo { - Rect frRect; - UInt16 frFlags; - Point frLocation; - - SInt16 frView; -}; -typedef struct DInfo DInfo; - - - - - - - -struct DXInfo { - Point frScroll; - SInt32 frOpenChain; - SInt8 frScript; - SInt8 frXFlags; - SInt16 frComment; - SInt32 frPutAway; -}; -typedef struct DXInfo DXInfo; - - -#pragma pack(pop) - - - -extern "C" { -extern Fixed -FixRatio( - short numer, - short denom) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fixed -FixMul( - Fixed a, - Fixed b) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern short -FixRound(Fixed x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fract -Fix2Frac(Fixed x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -Fix2Long(Fixed x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fixed -Long2Fix(SInt32 x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fixed -Frac2Fix(Fract x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fract -FracMul( - Fract x, - Fract y) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fixed -FixDiv( - Fixed x, - Fixed y) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fract -FracDiv( - Fract x, - Fract y) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fract -FracSqrt(Fract x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fract -FracSin(Fixed x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fract -FracCos(Fixed x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fixed -FixATan2( - SInt32 x, - SInt32 y) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern double -Frac2X(Fract x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern double -Fix2X(Fixed x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fixed -X2Fix(double x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Fract -X2Frac(double x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern short -WideCompare( - const wide * target, - const wide * source) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern wide * -WideAdd( - wide * target, - const wide * source) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern wide * -WideSubtract( - wide * target, - const wide * source) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern wide * -WideNegate(wide * target) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern wide * -WideShift( - wide * target, - SInt32 shift) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt32 -WideSquareRoot(const wide * source) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern wide * -WideMultiply( - SInt32 multiplicand, - SInt32 multiplier, - wide * target) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -WideDivide( - const wide * dividend, - SInt32 divisor, - SInt32 * remainder) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern wide * -WideWideDivide( - wide * dividend, - SInt32 divisor, - SInt32 * remainder) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern wide * -WideBitShift( - wide * target, - SInt32 shift) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UnsignedFixed -UnsignedFixedMulDiv( - UnsignedFixed value, - UnsignedFixed multiplier, - UnsignedFixed divisor) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); - - - - - -} - - - -#pragma pack(push, 2) - -enum { - - itlcShowIcon = 7, - itlcDualCaret = 6, - - itlcSysDirection = 15 -}; - -enum { - - itlcDisableKeyScriptSync = 3 -}; - -enum { - - itlcDisableKeyScriptSyncMask = 1 << itlcDisableKeyScriptSync -}; - - -enum { - tokLeftQuote = 1, - tokRightQuote = 2, - tokLeadPlacer = 3, - tokLeader = 4, - tokNonLeader = 5, - tokZeroLead = 6, - tokPercent = 7, - tokPlusSign = 8, - tokMinusSign = 9, - tokThousands = 10, - tokReserved = 11, - tokSeparator = 12, - tokEscape = 13, - tokDecPoint = 14, - tokEPlus = 15, - tokEMinus = 16, - tokMaxSymbols = 31, - curNumberPartsVersion = 1 -}; - -enum { - currSymLead = 16, - currNegSym = 32, - currTrailingZ = 64, - currLeadingZ = 128 -}; - -enum { - mdy = 0, - dmy = 1, - ymd = 2, - myd = 3, - dym = 4, - ydm = 5 -}; - -typedef SInt8 DateOrders; -enum { - timeCycle24 = 0, - timeCycleZero = 1, - timeCycle12 = 255, - zeroCycle = 1, - longDay = 0, - longWeek = 1, - longMonth = 2, - longYear = 3, - supDay = 1, - supWeek = 2, - supMonth = 4, - supYear = 8, - dayLdingZ = 32, - mntLdingZ = 64, - century = 128, - secLeadingZ = 32, - minLeadingZ = 64, - hrLeadingZ = 128 -}; - - -struct OffPair { - short offFirst; - short offSecond; -}; -typedef struct OffPair OffPair; -typedef OffPair OffsetTable[3]; -struct Intl0Rec { - char decimalPt; - char thousSep; - char listSep; - char currSym1; - char currSym2; - char currSym3; - UInt8 currFmt; - UInt8 dateOrder; - UInt8 shrtDateFmt; - char dateSep; - UInt8 timeCycle; - UInt8 timeFmt; - char mornStr[4]; - char eveStr[4]; - char timeSep; - char time1Suff; - char time2Suff; - char time3Suff; - char time4Suff; - char time5Suff; - char time6Suff; - char time7Suff; - char time8Suff; - UInt8 metricSys; - short intl0Vers; -}; -typedef struct Intl0Rec Intl0Rec; -typedef Intl0Rec * Intl0Ptr; -typedef Intl0Ptr * Intl0Hndl; -struct Intl1Rec { - Str15 days[7]; - Str15 months[12]; - UInt8 suppressDay; - UInt8 lngDateFmt; - UInt8 dayLeading0; - UInt8 abbrLen; - char st0[4]; - char st1[4]; - char st2[4]; - char st3[4]; - char st4[4]; - short intl1Vers; - short localRtn[1]; -}; -typedef struct Intl1Rec Intl1Rec; -typedef Intl1Rec * Intl1Ptr; -typedef Intl1Ptr * Intl1Hndl; - -struct Itl1ExtRec { - Intl1Rec base; - short version; - short format; - short calendarCode; - SInt32 extraDaysTableOffset; - SInt32 extraDaysTableLength; - SInt32 extraMonthsTableOffset; - SInt32 extraMonthsTableLength; - SInt32 abbrevDaysTableOffset; - SInt32 abbrevDaysTableLength; - SInt32 abbrevMonthsTableOffset; - SInt32 abbrevMonthsTableLength; - SInt32 extraSepsTableOffset; - SInt32 extraSepsTableLength; - short tables[1]; -}; -typedef struct Itl1ExtRec Itl1ExtRec; -struct UntokenTable { - short len; - short lastToken; - short index[256]; -}; -typedef struct UntokenTable UntokenTable; -typedef UntokenTable * UntokenTablePtr; -typedef UntokenTablePtr * UntokenTableHandle; -union WideChar { - struct { - char lo; - char hi; - } a; - short b; -}; -typedef union WideChar WideChar; -struct WideCharArr { - short size; - WideChar data[10]; -}; -typedef struct WideCharArr WideCharArr; -struct NumberParts { - short version; - WideChar data[31]; - WideCharArr pePlus; - WideCharArr peMinus; - WideCharArr peMinusPlus; - WideCharArr altNumTable; - char reserved[20]; -}; -typedef struct NumberParts NumberParts; -typedef NumberParts * NumberPartsPtr; - -struct Itl4Rec { - short flags; - SInt32 resourceType; - short resourceNum; - short version; - SInt32 resHeader1; - SInt32 resHeader2; - short numTables; - SInt32 mapOffset; - SInt32 strOffset; - SInt32 fetchOffset; - SInt32 unTokenOffset; - SInt32 defPartsOffset; - SInt32 resOffset6; - SInt32 resOffset7; - SInt32 resOffset8; -}; -typedef struct Itl4Rec Itl4Rec; -typedef Itl4Rec * Itl4Ptr; -typedef Itl4Ptr * Itl4Handle; - -struct NItl4Rec { - short flags; - SInt32 resourceType; - short resourceNum; - short version; - short format; - short resHeader; - SInt32 resHeader2; - short numTables; - SInt32 mapOffset; - SInt32 strOffset; - SInt32 fetchOffset; - SInt32 unTokenOffset; - SInt32 defPartsOffset; - SInt32 whtSpListOffset; - SInt32 resOffset7; - SInt32 resOffset8; - short resLength1; - short resLength2; - short resLength3; - short unTokenLength; - short defPartsLength; - short whtSpListLength; - short resLength7; - short resLength8; -}; -typedef struct NItl4Rec NItl4Rec; -typedef NItl4Rec * NItl4Ptr; -typedef NItl4Ptr * NItl4Handle; - -struct TableDirectoryRecord { - OSType tableSignature; - UInt32 reserved; - UInt32 tableStartOffset; - UInt32 tableSize; -}; -typedef struct TableDirectoryRecord TableDirectoryRecord; -struct Itl5Record { - Fixed versionNumber; - unsigned short numberOfTables; - unsigned short reserved[3]; - TableDirectoryRecord tableDirectory[1]; -}; -typedef struct Itl5Record Itl5Record; -struct RuleBasedTrslRecord { - short sourceType; - short targetType; - short formatNumber; - short propertyFlag; - short numberOfRules; -}; -typedef struct RuleBasedTrslRecord RuleBasedTrslRecord; - -struct ItlcRecord { - short itlcSystem; - short itlcReserved; - SInt8 itlcFontForce; - SInt8 itlcIntlForce; - SInt8 itlcOldKybd; - SInt8 itlcFlags; - short itlcIconOffset; - SInt8 itlcIconSide; - SInt8 itlcIconRsvd; - short itlcRegionCode; - short itlcSysFlags; - SInt8 itlcReserved4[32]; -}; -typedef struct ItlcRecord ItlcRecord; -struct ItlbRecord { - short itlbNumber; - short itlbDate; - short itlbSort; - short itlbFlags; - short itlbToken; - short itlbEncoding; - short itlbLang; - SInt8 itlbNumRep; - SInt8 itlbDateRep; - short itlbKeys; - short itlbIcon; -}; -typedef struct ItlbRecord ItlbRecord; - -struct ItlbExtRecord { - ItlbRecord base; - SInt32 itlbLocalSize; - short itlbMonoFond; - short itlbMonoSize; - short itlbPrefFond; - short itlbPrefSize; - short itlbSmallFond; - short itlbSmallSize; - short itlbSysFond; - short itlbSysSize; - short itlbAppFond; - short itlbAppSize; - short itlbHelpFond; - short itlbHelpSize; - Style itlbValidStyles; - Style itlbAliasStyle; -}; -typedef struct ItlbExtRecord ItlbExtRecord; - - - -#pragma pack(pop) -extern "C" { - - -#pragma pack(push, 2) - - -enum { - smSystemScript = -1, - smCurrentScript = -2, - smAllScripts = -3 -}; -enum { - smRoman = 0, - smJapanese = 1, - smTradChinese = 2, - smKorean = 3, - smArabic = 4, - smHebrew = 5, - smGreek = 6, - smCyrillic = 7, - smRSymbol = 8, - smDevanagari = 9, - smGurmukhi = 10, - smGujarati = 11, - smOriya = 12, - smBengali = 13, - smTamil = 14, - smTelugu = 15, - smKannada = 16, - smMalayalam = 17, - smSinhalese = 18, - smBurmese = 19, - smKhmer = 20, - smThai = 21, - smLao = 22, - smGeorgian = 23, - smArmenian = 24, - smSimpChinese = 25, - smTibetan = 26, - smMongolian = 27, - smEthiopic = 28, - smGeez = 28, - smCentralEuroRoman = 29, - smVietnamese = 30, - smExtArabic = 31, - smUninterp = 32 -}; - - -enum { - smUnicodeScript = 0x7E -}; - - -enum { - smChinese = 2, - smRussian = 7, - - smLaotian = 22, - smAmharic = 28, - smSlavic = 29, - smEastEurRoman = 29, - smSindhi = 31, - smKlingon = 32 -}; - - - - - - -enum { - langEnglish = 0, - langFrench = 1, - langGerman = 2, - langItalian = 3, - langDutch = 4, - langSwedish = 5, - langSpanish = 6, - langDanish = 7, - langPortuguese = 8, - langNorwegian = 9, - langHebrew = 10, - langJapanese = 11, - langArabic = 12, - langFinnish = 13, - langGreek = 14, - langIcelandic = 15, - langMaltese = 16, - langTurkish = 17, - langCroatian = 18, - langTradChinese = 19, - langUrdu = 20, - langHindi = 21, - langThai = 22, - langKorean = 23 -}; - -enum { - langLithuanian = 24, - langPolish = 25, - langHungarian = 26, - langEstonian = 27, - langLatvian = 28, - langSami = 29, - langFaroese = 30, - langFarsi = 31, - langPersian = 31, - langRussian = 32, - langSimpChinese = 33, - langFlemish = 34, - langIrishGaelic = 35, - langAlbanian = 36, - langRomanian = 37, - langCzech = 38, - langSlovak = 39, - langSlovenian = 40, - langYiddish = 41, - langSerbian = 42, - langMacedonian = 43, - langBulgarian = 44, - langUkrainian = 45, - langByelorussian = 46, - langBelorussian = 46 -}; - -enum { - langUzbek = 47, - langKazakh = 48, - langAzerbaijani = 49, - langAzerbaijanAr = 50, - langArmenian = 51, - langGeorgian = 52, - langMoldavian = 53, - langKirghiz = 54, - langTajiki = 55, - langTurkmen = 56, - langMongolian = 57, - langMongolianCyr = 58, - langPashto = 59, - langKurdish = 60, - langKashmiri = 61, - langSindhi = 62, - langTibetan = 63, - langNepali = 64, - langSanskrit = 65, - langMarathi = 66, - langBengali = 67, - langAssamese = 68, - langGujarati = 69, - langPunjabi = 70 -}; - -enum { - langOriya = 71, - langMalayalam = 72, - langKannada = 73, - langTamil = 74, - langTelugu = 75, - langSinhalese = 76, - langBurmese = 77, - langKhmer = 78, - langLao = 79, - langVietnamese = 80, - langIndonesian = 81, - langTagalog = 82, - langMalayRoman = 83, - langMalayArabic = 84, - langAmharic = 85, - langTigrinya = 86, - langOromo = 87, - langSomali = 88, - langSwahili = 89, - langKinyarwanda = 90, - langRuanda = 90, - langRundi = 91, - langNyanja = 92, - langChewa = 92, - langMalagasy = 93, - langEsperanto = 94 -}; - -enum { - langWelsh = 128, - langBasque = 129, - langCatalan = 130, - langLatin = 131, - langQuechua = 132, - langGuarani = 133, - langAymara = 134, - langTatar = 135, - langUighur = 136, - langDzongkha = 137, - langJavaneseRom = 138, - langSundaneseRom = 139, - langGalician = 140, - langAfrikaans = 141 -}; - -enum { - langBreton = 142, - langInuktitut = 143, - langScottishGaelic = 144, - langManxGaelic = 145, - langIrishGaelicScript = 146, - langTongan = 147, - langGreekAncient = 148, - langGreenlandic = 149, - langAzerbaijanRoman = 150, - langNynorsk = 151 -}; - -enum { - langUnspecified = 32767 -}; - - - - - -enum { - langPortugese = 8, - langMalta = 16, - langYugoslavian = 18, - langChinese = 19, - langLettish = 28, - langLapponian = 29, - langLappish = 29, - langSaamisk = 29, - langFaeroese = 30, - langIrish = 35, - langGalla = 87, - langAfricaans = 141, - langGreekPoly = 148 -}; -enum { - - verUS = 0, - verFrance = 1, - verBritain = 2, - verGermany = 3, - verItaly = 4, - verNetherlands = 5, - verFlemish = 6, - verSweden = 7, - verSpain = 8, - verDenmark = 9, - verPortugal = 10, - verFrCanada = 11, - verNorway = 12, - verIsrael = 13, - verJapan = 14, - verAustralia = 15, - verArabic = 16, - verFinland = 17, - verFrSwiss = 18, - verGrSwiss = 19, - verGreece = 20, - verIceland = 21, - verMalta = 22, - verCyprus = 23, - verTurkey = 24, - verYugoCroatian = 25 -}; - -enum { - verNetherlandsComma = 26, - verFlemishPoint = 27, - verCanadaComma = 28, - verCanadaPoint = 29, - vervariantPortugal = 30, - vervariantNorway = 31, - vervariantDenmark = 32 -}; - -enum { - verIndiaHindi = 33, - verPakistanUrdu = 34, - verTurkishModified = 35, - verItalianSwiss = 36, - verInternational = 37, - - verRomania = 39, - verGreekAncient = 40, - verLithuania = 41, - verPoland = 42, - verHungary = 43, - verEstonia = 44, - verLatvia = 45, - verSami = 46, - verFaroeIsl = 47, - verIran = 48, - verRussia = 49, - verIreland = 50, - verKorea = 51, - verChina = 52, - verTaiwan = 53, - verThailand = 54, - verScriptGeneric = 55, - verCzech = 56, - verSlovak = 57, - verEastAsiaGeneric = 58, - verMagyar = 59, - verBengali = 60, - verBelarus = 61 -}; - -enum { - verUkraine = 62, - - verGreeceAlt = 64, - verSerbian = 65, - verSlovenian = 66, - verMacedonian = 67, - verCroatia = 68, - - verGermanReformed = 70, - verBrazil = 71, - verBulgaria = 72, - verCatalonia = 73, - verMultilingual = 74, - verScottishGaelic = 75, - verManxGaelic = 76, - verBreton = 77, - verNunavut = 78, - verWelsh = 79, - - verIrishGaelicScript = 81, - verEngCanada = 82, - verBhutan = 83, - verArmenian = 84, - verGeorgian = 85, - verSpLatinAmerica = 86, - - verTonga = 88, - - - verFrenchUniversal = 91, - verAustria = 92, - - verGujarati = 94, - verPunjabi = 95, - verIndiaUrdu = 96, - verVietnam = 97 -}; - -enum { - verFrBelgium = 98, - verUzbek = 99, - verSingapore = 100, - verNynorsk = 101, - verAfrikaans = 102, - verEsperanto = 103, - verMarathi = 104, - verTibetan = 105, - verNepal = 106, - verGreenland = 107, - verIrelandEnglish = 108 -}; -enum { - verFrBelgiumLux = 6, - verBelgiumLux = 6, - verArabia = 16, - verYugoslavia = 25, - verBelgiumLuxPoint = 27, - verIndia = 33, - verPakistan = 34, - verRumania = 39, - verGreecePoly = 40, - verLapland = 46, - verFaeroeIsl = 47, - verGenericFE = 58, - verFarEastGeneric = 58, - verByeloRussian = 61, - verUkrania = 62, - verAlternateGr = 64, - verSerbia = 65, - verSlovenia = 66, - verMacedonia = 67, - verBrittany = 77, - verWales = 79, - verArmenia = 84, - verGeorgia = 85, - verAustriaGerman = 92, - verTibet = 105 -}; - -enum { - minCountry = verUS, - maxCountry = verIrelandEnglish -}; - -enum { - - calGregorian = 0, - calArabicCivil = 1, - calArabicLunar = 2, - calJapanese = 3, - calJewish = 4, - calCoptic = 5, - calPersian = 6 -}; - -enum { - - intWestern = 0, - intArabic = 1, - intRoman = 2, - intJapanese = 3, - intEuropean = 4, - intOutputMask = 0x8000 -}; - -enum { - - smSingleByte = 0, - smFirstByte = -1, - smLastByte = 1, - smMiddleByte = 2 -}; - -enum { - - smcTypeMask = 0x000F, - smcReserved = 0x00F0, - smcClassMask = 0x0F00, - smcOrientationMask = 0x1000, - smcRightMask = 0x2000, - smcUpperMask = 0x4000, - smcDoubleMask = 0x8000 -}; - -enum { - - smCharPunct = 0x0000, - smCharAscii = 0x0001, - smCharEuro = 0x0007, - smCharExtAscii = 0x0007, - - smCharKatakana = 0x0002, - smCharHiragana = 0x0003, - smCharIdeographic = 0x0004, - smCharTwoByteGreek = 0x0005, - smCharTwoByteRussian = 0x0006, - smCharBidirect = 0x0008, - smCharContextualLR = 0x0009, - smCharNonContextualLR = 0x000A, - smCharHangul = 0x000C, - smCharJamo = 0x000D, - smCharBopomofo = 0x000E, - smCharGanaKana = 0x000F, - - smCharFISKana = 0x0002, - smCharFISGana = 0x0003, - smCharFISIdeo = 0x0004 -}; - -enum { - smCharFISGreek = 0x0005, - smCharFISRussian = 0x0006, - - smPunctNormal = 0x0000, - smPunctNumber = 0x0100, - smPunctSymbol = 0x0200, - smPunctBlank = 0x0300, - smPunctRepeat = 0x0400, - smPunctGraphic = 0x0500, - - smKanaSmall = 0x0100, - smKanaHardOK = 0x0200, - smKanaSoftOK = 0x0300, - - smIdeographicLevel1 = 0x0000, - smIdeographicLevel2 = 0x0100, - smIdeographicUser = 0x0200, - - smFISClassLvl1 = 0x0000, - smFISClassLvl2 = 0x0100, - smFISClassUser = 0x0200, - - smJamoJaeum = 0x0000, - smJamoBogJaeum = 0x0100, - smJamoMoeum = 0x0200, - smJamoBogMoeum = 0x0300 -}; - -enum { - - smCharHorizontal = 0x0000, - smCharVertical = 0x1000, - - smCharLeft = 0x0000, - smCharRight = 0x2000, - smCharLower = 0x0000, - smCharUpper = 0x4000, - smChar1byte = 0x0000, - smChar2byte = 0x8000 -}; - -enum { - - smTransAscii = 0, - smTransNative = 1, - smTransCase = 0xFE, - smTransSystem = 0xFF, - - smTransAscii1 = 2, - smTransAscii2 = 3, - smTransKana1 = 4, - smTransKana2 = 5 -}; - -enum { - smTransGana2 = 7, - smTransHangul2 = 8, - smTransJamo2 = 9, - smTransBopomofo2 = 10, - - smTransLower = 0x4000, - smTransUpper = 0x8000, - - smTransRuleBaseFormat = 1, - smTransHangulFormat = 2, - - smTransPreDoubleByting = 1, - smTransPreLowerCasing = 2 -}; - -enum { - - smMaskAll = (int)0xFFFFFFFF, - - smMaskAscii = 0x00000001, - smMaskNative = 0x00000002, - - smMaskAscii1 = 0x00000004, - smMaskAscii2 = 0x00000008, - smMaskKana1 = 0x00000010, - smMaskKana2 = 0x00000020, - smMaskGana2 = 0x00000080, - smMaskHangul2 = 0x00000100, - smMaskJamo2 = 0x00000200, - smMaskBopomofo2 = 0x00000400 -}; - -enum { - - iuSystemScript = -1, - iuCurrentScript = -2 -}; - -enum { - - smKeyNextScript = -1, - smKeySysScript = -2, - smKeySwapScript = -3, - - smKeyNextKybd = -4, - smKeySwapKybd = -5, - smKeyDisableKybds = -6, - smKeyEnableKybds = -7, - smKeyToggleInline = -8, - smKeyToggleDirection = -9, - smKeyNextInputMethod = -10, - smKeySwapInputMethod = -11, - smKeyDisableKybdSwitch = -12, - smKeySetDirLeftRight = -15, - smKeySetDirRightLeft = -16, - smKeyRoman = -17 -}; - -enum { - - smKeyForceKeyScriptBit = 7, - smKeyForceKeyScriptMask = 1 << smKeyForceKeyScriptBit -}; - -enum { - - - - romanSysFond = 0x3FFF, - romanAppFond = 3, - romanFlags = 0x0007, - - smFondStart = 0x4000, - smFondEnd = 0xC000, - - smUprHalfCharSet = 0x80 -}; - -enum { - - diaeresisUprY = 0xD9, - fraction = 0xDA, - intlCurrency = 0xDB, - leftSingGuillemet = 0xDC, - rightSingGuillemet = 0xDD, - fiLigature = 0xDE, - flLigature = 0xDF, - dblDagger = 0xE0, - centeredDot = 0xE1, - baseSingQuote = 0xE2, - baseDblQuote = 0xE3, - perThousand = 0xE4, - circumflexUprA = 0xE5, - circumflexUprE = 0xE6, - acuteUprA = 0xE7, - diaeresisUprE = 0xE8, - graveUprE = 0xE9, - acuteUprI = 0xEA, - circumflexUprI = 0xEB, - diaeresisUprI = 0xEC, - graveUprI = 0xED, - acuteUprO = 0xEE, - circumflexUprO = 0xEF, - appleLogo = 0xF0, - graveUprO = 0xF1, - acuteUprU = 0xF2, - circumflexUprU = 0xF3, - graveUprU = 0xF4, - dotlessLwrI = 0xF5, - circumflex = 0xF6, - tilde = 0xF7, - macron = 0xF8, - breveMark = 0xF9, - overDot = 0xFA, - ringMark = 0xFB, - cedilla = 0xFC, - doubleAcute = 0xFD, - ogonek = 0xFE, - hachek = 0xFF -}; - -enum { - - tokenIntl = 4, - tokenEmpty = -1 -}; - -enum { - tokenUnknown = 0, - tokenWhite = 1, - tokenLeftLit = 2, - tokenRightLit = 3, - tokenAlpha = 4, - tokenNumeric = 5, - tokenNewLine = 6, - tokenLeftComment = 7, - tokenRightComment = 8, - tokenLiteral = 9, - tokenEscape = 10, - tokenAltNum = 11, - tokenRealNum = 12, - tokenAltReal = 13, - tokenReserve1 = 14, - tokenReserve2 = 15, - tokenLeftParen = 16, - tokenRightParen = 17, - tokenLeftBracket = 18, - tokenRightBracket = 19 -}; - -enum { - tokenLeftCurly = 20, - tokenRightCurly = 21, - tokenLeftEnclose = 22, - tokenRightEnclose = 23, - tokenPlus = 24, - tokenMinus = 25, - tokenAsterisk = 26, - tokenDivide = 27, - tokenPlusMinus = 28, - tokenSlash = 29, - tokenBackSlash = 30, - tokenLess = 31, - tokenGreat = 32, - tokenEqual = 33, - tokenLessEqual2 = 34, - tokenLessEqual1 = 35, - tokenGreatEqual2 = 36, - tokenGreatEqual1 = 37, - token2Equal = 38, - tokenColonEqual = 39 -}; - -enum { - tokenNotEqual = 40, - tokenLessGreat = 41, - tokenExclamEqual = 42, - tokenExclam = 43, - tokenTilde = 44, - tokenComma = 45, - tokenPeriod = 46, - tokenLeft2Quote = 47, - tokenRight2Quote = 48, - tokenLeft1Quote = 49, - tokenRight1Quote = 50, - token2Quote = 51, - token1Quote = 52, - tokenSemicolon = 53, - tokenPercent = 54, - tokenCaret = 55, - tokenUnderline = 56, - tokenAmpersand = 57, - tokenAtSign = 58, - tokenBar = 59 -}; - -enum { - tokenQuestion = 60, - tokenPi = 61, - tokenRoot = 62, - tokenSigma = 63, - tokenIntegral = 64, - tokenMicro = 65, - tokenCapPi = 66, - tokenInfinity = 67, - tokenColon = 68, - tokenHash = 69, - tokenDollar = 70, - tokenNoBreakSpace = 71, - tokenFraction = 72, - tokenIntlCurrency = 73, - tokenLeftSingGuillemet = 74, - tokenRightSingGuillemet = 75, - tokenPerThousand = 76, - tokenEllipsis = 77, - tokenCenterDot = 78, - tokenNil = 127 -}; - -enum { - delimPad = -2, - tokenTilda = 44, - tokenCarat = 55 -}; - -enum { - - smWordSelectTable = 0, - smWordWrapTable = 1, - smNumberPartsTable = 2, - smUnTokenTable = 3, - smWhiteSpaceList = 4, - iuWordSelectTable = 0, - iuWordWrapTable = 1, - iuNumberPartsTable = 2, - iuUnTokenTable = 3, - iuWhiteSpaceList = 4 -}; - - -enum { - tokenOK = 0, - tokenOverflow = 1, - stringOverflow = 2, - badDelim = 3, - badEnding = 4, - crash = 5 -}; - -typedef SInt8 TokenResults; -typedef char CharByteTable[256]; - -typedef short ScriptTokenType; -typedef ScriptTokenType DelimType[2]; -typedef ScriptTokenType CommentType[4]; -struct TokenRec { - ScriptTokenType theToken; - Ptr position; - long length; - StringPtr stringPosition; -}; -typedef struct TokenRec TokenRec; -typedef TokenRec * TokenRecPtr; -struct TokenBlock { - Ptr source; - long sourceLength; - Ptr tokenList; - long tokenLength; - long tokenCount; - Ptr stringList; - long stringLength; - long stringCount; - Boolean doString; - Boolean doAppend; - Boolean doAlphanumeric; - Boolean doNest; - ScriptTokenType leftDelims[2]; - ScriptTokenType rightDelims[2]; - ScriptTokenType leftComment[4]; - ScriptTokenType rightComment[4]; - ScriptTokenType escapeCode; - ScriptTokenType decimalCode; - Handle itlResource; - long reserved[8]; -}; -typedef struct TokenBlock TokenBlock; -typedef TokenBlock * TokenBlockPtr; - - -enum { - smNotInstalled = 0, - smBadVerb = -1, - smBadScript = -2 -}; - - - -enum { - smfShowIcon = 31, - smfDualCaret = 30, - smfNameTagEnab = 29, - smfUseAssocFontInfo = 28, - smfDisableKeyScriptSync = 27 -}; - - -enum { - smfDisableKeyScriptSyncMask = 1L << smfDisableKeyScriptSync -}; - - -enum { - smSysScript = 18, - smKeyScript = 22, - smKCHRCache = 38, - smRegionCode = 40 -}; -extern long -GetScriptManagerVariable(short selector) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern OSErr -SetScriptManagerVariable( - short selector, - long param) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -enum { - smsfIntellCP = 0, - smsfSingByte = 1, - smsfNatCase = 2, - smsfContext = 3, - smsfNoForceFont = 4, - smsfB0Digits = 5, - smsfAutoInit = 6, - smsfUnivExt = 7, - smsfSynchUnstyledTE = 8, - smsfForms = 13, - smsfLigatures = 14, - smsfReverse = 15 -}; -#pragma pack(pop) - - -} - - - -extern "C" { - - -enum { - paramErr = -50, - noHardwareErr = -200, - notEnoughHardwareErr = -201, - userCanceledErr = -128, - qErr = -1, - vTypErr = -2, - corErr = -3, - unimpErr = -4, - SlpTypeErr = -5, - seNoDB = -8, - controlErr = -17, - statusErr = -18, - readErr = -19, - writErr = -20, - badUnitErr = -21, - unitEmptyErr = -22, - openErr = -23, - closErr = -24, - dRemovErr = -25, - dInstErr = -26 -}; - -enum { - abortErr = -27, - iIOAbortErr = -27, - notOpenErr = -28, - unitTblFullErr = -29, - dceExtErr = -30, - slotNumErr = -360, - gcrOnMFMErr = -400, - dirFulErr = -33, - dskFulErr = -34, - nsvErr = -35, - ioErr = -36, - bdNamErr = -37, - fnOpnErr = -38, - eofErr = -39, - posErr = -40, - mFulErr = -41, - tmfoErr = -42, - fnfErr = -43, - wPrErr = -44, - fLckdErr = -45 -}; - -enum { - vLckdErr = -46, - fBsyErr = -47, - dupFNErr = -48, - opWrErr = -49, - rfNumErr = -51, - gfpErr = -52, - volOffLinErr = -53, - permErr = -54, - volOnLinErr = -55, - nsDrvErr = -56, - noMacDskErr = -57, - extFSErr = -58, - fsRnErr = -59, - badMDBErr = -60, - wrPermErr = -61, - dirNFErr = -120, - tmwdoErr = -121, - badMovErr = -122, - wrgVolTypErr = -123, - volGoneErr = -124 -}; - -enum { - fidNotFound = -1300, - fidExists = -1301, - notAFileErr = -1302, - diffVolErr = -1303, - catChangedErr = -1304, - desktopDamagedErr = -1305, - sameFileErr = -1306, - badFidErr = -1307, - notARemountErr = -1308, - fileBoundsErr = -1309, - fsDataTooBigErr = -1310, - volVMBusyErr = -1311, - badFCBErr = -1327, - errFSUnknownCall = -1400, - errFSBadFSRef = -1401, - errFSBadForkName = -1402, - errFSBadBuffer = -1403, - errFSBadForkRef = -1404, - errFSBadInfoBitmap = -1405, - errFSMissingCatInfo = -1406, - errFSNotAFolder = -1407, - errFSForkNotFound = -1409, - errFSNameTooLong = -1410, - errFSMissingName = -1411, - errFSBadPosMode = -1412, - errFSBadAllocFlags = -1413, - errFSNoMoreItems = -1417, - errFSBadItemCount = -1418, - errFSBadSearchParams = -1419, - errFSRefsDifferent = -1420, - errFSForkExists = -1421, - errFSBadIteratorFlags = -1422, - errFSIteratorNotFound = -1423, - errFSIteratorNotSupported = -1424, - errFSQuotaExceeded = -1425, - errFSOperationNotSupported = -1426, - errFSAttributeNotFound = -1427, - errFSPropertyNotValid = -1428, - errFSNotEnoughSpaceForOperation = -1429, - envNotPresent = -5500, - envBadVers = -5501, - envVersTooBig = -5502, - fontDecError = -64, - fontNotDeclared = -65, - fontSubErr = -66, - fontNotOutlineErr = -32615, - firstDskErr = -84, - lastDskErr = -64, - noDriveErr = -64, - offLinErr = -65, - noNybErr = -66 -}; - -enum { - noAdrMkErr = -67, - dataVerErr = -68, - badCksmErr = -69, - badBtSlpErr = -70, - noDtaMkErr = -71, - badDCksum = -72, - badDBtSlp = -73, - wrUnderrun = -74, - cantStepErr = -75, - tk0BadErr = -76, - initIWMErr = -77, - twoSideErr = -78, - spdAdjErr = -79, - seekErr = -80, - sectNFErr = -81, - fmt1Err = -82, - fmt2Err = -83, - verErr = -84, - clkRdErr = -85, - clkWrErr = -86, - prWrErr = -87, - prInitErr = -88, - rcvrErr = -89, - breakRecd = -90 -}; - -enum { - - noScrapErr = -100, - noTypeErr = -102 -}; - -enum { - - eLenErr = -92, - eMultiErr = -91 -}; - -enum { - ddpSktErr = -91, - ddpLenErr = -92, - noBridgeErr = -93, - lapProtErr = -94, - excessCollsns = -95, - portNotPwr = -96, - portInUse = -97, - portNotCf = -98 -}; - -enum { - - memROZWarn = -99, - memROZError = -99, - memROZErr = -99, - memFullErr = -108, - nilHandleErr = -109, - memWZErr = -111, - memPurErr = -112, - memAdrErr = -110, - memAZErr = -113, - memPCErr = -114, - memBCErr = -115, - memSCErr = -116, - memLockedErr = -117 -}; - -enum { - - iMemFullErr = -108, - iIOAbort = -27 -}; - - -enum { - resourceInMemory = -188, - writingPastEnd = -189, - inputOutOfBounds = -190, - resNotFound = -192, - resFNotFound = -193, - addResFailed = -194, - addRefFailed = -195, - rmvResFailed = -196, - rmvRefFailed = -197, - resAttrErr = -198, - mapReadErr = -199, - CantDecompress = -186, - badExtResource = -185, - noMemForPictPlaybackErr = -145, - rgnOverflowErr = -147, - rgnTooBigError = -147, - pixMapTooDeepErr = -148, - insufficientStackErr = -149, - nsStackErr = -149 -}; - -enum { - evtNotEnb = 1 -}; - - -enum { - cMatchErr = -150, - cTempMemErr = -151, - cNoMemErr = -152, - cRangeErr = -153, - cProtectErr = -154, - cDevErr = -155, - cResErr = -156, - cDepthErr = -157, - rgnTooBigErr = -500, - updPixMemErr = -125, - pictInfoVersionErr = -11000, - pictInfoIDErr = -11001, - pictInfoVerbErr = -11002, - cantLoadPickMethodErr = -11003, - colorsRequestedErr = -11004, - pictureDataErr = -11005 -}; - - -enum { - - cmProfileError = -170, - cmMethodError = -171, - cmMethodNotFound = -175, - cmProfileNotFound = -176, - cmProfilesIdentical = -177, - cmCantConcatenateError = -178, - cmCantXYZ = -179, - cmCantDeleteProfile = -180, - cmUnsupportedDataType = -181, - cmNoCurrentProfile = -182 -}; - - -enum { - - noHardware = noHardwareErr, - notEnoughHardware = notEnoughHardwareErr, - queueFull = -203, - resProblem = -204, - badChannel = -205, - badFormat = -206, - notEnoughBufferSpace = -207, - badFileFormat = -208, - channelBusy = -209, - buffersTooSmall = -210, - channelNotBusy = -211, - noMoreRealTime = -212, - siVBRCompressionNotSupported = -213, - siNoSoundInHardware = -220, - siBadSoundInDevice = -221, - siNoBufferSpecified = -222, - siInvalidCompression = -223, - siHardDriveTooSlow = -224, - siInvalidSampleRate = -225, - siInvalidSampleSize = -226, - siDeviceBusyErr = -227, - siBadDeviceName = -228, - siBadRefNum = -229, - siInputDeviceErr = -230, - siUnknownInfoType = -231, - siUnknownQuality = -232 -}; - - -enum { - noSynthFound = -240, - synthOpenFailed = -241, - synthNotReady = -242, - bufTooSmall = -243, - voiceNotFound = -244, - incompatibleVoice = -245, - badDictFormat = -246, - badInputText = -247 -}; - - -enum { - midiNoClientErr = -250, - midiNoPortErr = -251, - midiTooManyPortsErr = -252, - midiTooManyConsErr = -253, - midiVConnectErr = -254, - midiVConnectMade = -255, - midiVConnectRmvd = -256, - midiNoConErr = -257, - midiWriteErr = -258, - midiNameLenErr = -259, - midiDupIDErr = -260, - midiInvalidCmdErr = -261 -}; - - -enum { - nmTypErr = -299 -}; - - -enum { - siInitSDTblErr = 1, - siInitVBLQsErr = 2, - siInitSPTblErr = 3, - sdmJTInitErr = 10, - sdmInitErr = 11, - sdmSRTInitErr = 12, - sdmPRAMInitErr = 13, - sdmPriInitErr = 14 -}; - -enum { - smSDMInitErr = -290, - smSRTInitErr = -291, - smPRAMInitErr = -292, - smPriInitErr = -293, - smEmptySlot = -300, - smCRCFail = -301, - smFormatErr = -302, - smRevisionErr = -303, - smNoDir = -304, - smDisabledSlot = -305, - smNosInfoArray = -306 -}; - - -enum { - smResrvErr = -307, - smUnExBusErr = -308, - smBLFieldBad = -309, - smFHBlockRdErr = -310, - smFHBlkDispErr = -311, - smDisposePErr = -312, - smNoBoardSRsrc = -313, - smGetPRErr = -314, - smNoBoardId = -315, - smInitStatVErr = -316, - smInitTblVErr = -317, - smNoJmpTbl = -318, - smReservedSlot = -318, - smBadBoardId = -319, - smBusErrTO = -320, - - svTempDisable = -32768L, - svDisabled = -32640, - smBadRefId = -330, - smBadsList = -331, - smReservedErr = -332, - smCodeRevErr = -333 -}; - -enum { - smCPUErr = -334, - smsPointerNil = -335, - smNilsBlockErr = -336, - smSlotOOBErr = -337, - smSelOOBErr = -338, - smNewPErr = -339, - smBlkMoveErr = -340, - smCkStatusErr = -341, - smGetDrvrNamErr = -342, - smDisDrvrNamErr = -343, - smNoMoresRsrcs = -344, - smsGetDrvrErr = -345, - smBadsPtrErr = -346, - smByteLanesErr = -347, - smOffsetErr = -348, - smNoGoodOpens = -349, - smSRTOvrFlErr = -350, - smRecNotFnd = -351 -}; - - -enum { - - notBTree = -410, - btNoSpace = -413, - btDupRecErr = -414, - btRecNotFnd = -415, - btKeyLenErr = -416, - btKeyAttrErr = -417, - unknownInsertModeErr = -20000, - recordDataTooBigErr = -20001, - invalidIndexErr = -20002 -}; - - - - - -enum { - fsmFFSNotFoundErr = -431, - fsmBusyFFSErr = -432, - fsmBadFFSNameErr = -433, - fsmBadFSDLenErr = -434, - fsmDuplicateFSIDErr = -435, - fsmBadFSDVersionErr = -436, - fsmNoAlternateStackErr = -437, - fsmUnknownFSMMessageErr = -438 -}; - - -enum { - - editionMgrInitErr = -450, - badSectionErr = -451, - notRegisteredSectionErr = -452, - badEditionFileErr = -453, - badSubPartErr = -454, - multiplePublisherWrn = -460, - containerNotFoundWrn = -461, - containerAlreadyOpenWrn = -462, - notThePublisherWrn = -463 -}; - -enum { - teScrapSizeErr = -501, - hwParamErr = -502, - driverHardwareGoneErr = -503 -}; - -enum { - - procNotFound = -600, - memFragErr = -601, - appModeErr = -602, - protocolErr = -603, - hardwareConfigErr = -604, - appMemFullErr = -605, - appIsDaemon = -606, - bufferIsSmall = -607, - noOutstandingHLE = -608, - connectionInvalid = -609, - noUserInteractionAllowed = -610 -}; - -enum { - - wrongApplicationPlatform = -875, - appVersionTooOld = -876, - notAppropriateForClassic = -877 -}; - - -enum { - threadTooManyReqsErr = -617, - threadNotFoundErr = -618, - threadProtocolErr = -619 -}; - -enum { - threadBadAppContextErr = -616 -}; - - -enum { - notEnoughMemoryErr = -620, - notHeldErr = -621, - cannotMakeContiguousErr = -622, - notLockedErr = -623, - interruptsMaskedErr = -624, - cannotDeferErr = -625, - noMMUErr = -626 -}; - - -enum { - vmMorePhysicalThanVirtualErr = -628, - vmKernelMMUInitErr = -629, - vmOffErr = -630, - vmMemLckdErr = -631, - vmBadDriver = -632, - vmNoVectorErr = -633 -}; - - -enum { - vmInvalidBackingFileIDErr = -640, - vmMappingPrivilegesErr = -641, - vmBusyBackingFileErr = -642, - vmNoMoreBackingFilesErr = -643, - vmInvalidFileViewIDErr = -644, - vmFileViewAccessErr = -645, - vmNoMoreFileViewsErr = -646, - vmAddressNotInFileViewErr = -647, - vmInvalidOwningProcessErr = -648 -}; - - -enum { - rcDBNull = -800, - rcDBValue = -801, - rcDBError = -802, - rcDBBadType = -803, - rcDBBreak = -804, - rcDBExec = -805, - rcDBBadSessID = -806, - rcDBBadSessNum = -807, - rcDBBadDDEV = -808, - rcDBAsyncNotSupp = -809, - rcDBBadAsyncPB = -810, - rcDBNoHandler = -811, - rcDBWrongVersion = -812, - rcDBPackNotInited = -813 -}; - - - -enum { - hmHelpDisabled = -850, - hmBalloonAborted = -853, - hmSameAsLastBalloon = -854, - hmHelpManagerNotInited = -855, - hmSkippedBalloon = -857, - hmWrongVersion = -858, - hmUnknownHelpType = -859, - hmOperationUnsupported = -861, - hmNoBalloonUp = -862, - hmCloseViewActive = -863 -}; - - - -enum { - - notInitErr = -900, - nameTypeErr = -902, - noPortErr = -903, - - - noGlobalsErr = -904, - localOnlyErr = -905, - destPortErr = -906, - sessTableErr = -907, - noSessionErr = -908, - badReqErr = -909, - portNameExistsErr = -910, - noUserNameErr = -911, - userRejectErr = -912, - noMachineNameErr = -913, - noToolboxNameErr = -914, - noResponseErr = -915, - portClosedErr = -916, - sessClosedErr = -917, - badPortNameErr = -919, - noDefaultUserErr = -922, - notLoggedInErr = -923, - noUserRefErr = -924, - networkErr = -925, - noInformErr = -926, - authFailErr = -927, - noUserRecErr = -928, - badServiceMethodErr = -930, - badLocNameErr = -931, - guestNotAllowedErr = -932 -}; - - -enum { - kFMIterationCompleted = -980L, - kFMInvalidFontFamilyErr = -981L, - kFMInvalidFontErr = -982L, - kFMIterationScopeModifiedErr = -983L, - kFMFontTableAccessErr = -984L, - kFMFontContainerAccessErr = -985L -}; - -enum { - noMaskFoundErr = -1000 -}; - -enum { - nbpBuffOvr = -1024, - nbpNoConfirm = -1025, - nbpConfDiff = -1026, - nbpDuplicate = -1027, - nbpNotFound = -1028, - nbpNISErr = -1029 -}; - -enum { - aspBadVersNum = -1066, - aspBufTooSmall = -1067, - aspNoMoreSess = -1068, - aspNoServers = -1069, - aspParamErr = -1070, - aspServerBusy = -1071, - aspSessClosed = -1072, - aspSizeErr = -1073, - aspTooMany = -1074, - aspNoAck = -1075 -}; - -enum { - reqFailed = -1096, - tooManyReqs = -1097, - tooManySkts = -1098, - badATPSkt = -1099, - badBuffNum = -1100, - noRelErr = -1101, - cbNotFound = -1102, - noSendResp = -1103, - noDataArea = -1104, - reqAborted = -1105 -}; - - -enum { - - errRefNum = -1280, - errAborted = -1279, - errState = -1278, - errOpening = -1277, - errAttention = -1276, - errFwdReset = -1275, - errDSPQueueSize = -1274, - errOpenDenied = -1273 -}; - - - - - - -enum { - errAECoercionFail = -1700, - errAEDescNotFound = -1701, - errAECorruptData = -1702, - errAEWrongDataType = -1703, - errAENotAEDesc = -1704, - errAEBadListItem = -1705, - errAENewerVersion = -1706, - errAENotAppleEvent = -1707, - errAEEventNotHandled = -1708, - errAEReplyNotValid = -1709, - errAEUnknownSendMode = -1710, - errAEWaitCanceled = -1711, - errAETimeout = -1712, - errAENoUserInteraction = -1713, - errAENotASpecialFunction = -1714, - errAEParamMissed = -1715, - errAEUnknownAddressType = -1716, - errAEHandlerNotFound = -1717, - errAEReplyNotArrived = -1718, - errAEIllegalIndex = -1719, - errAEImpossibleRange = -1720, - errAEWrongNumberArgs = -1721, - errAEAccessorNotFound = -1723, - errAENoSuchLogical = -1725, - errAEBadTestKey = -1726, - errAENotAnObjSpec = -1727, - errAENoSuchObject = -1728, - errAENegativeCount = -1729, - errAEEmptyListContainer = -1730, - errAEUnknownObjectType = -1731, - errAERecordingIsAlreadyOn = -1732, - errAEReceiveTerminate = -1733, - errAEReceiveEscapeCurrent = -1734, - errAEEventFiltered = -1735, - errAEDuplicateHandler = -1736, - errAEStreamBadNesting = -1737, - errAEStreamAlreadyConverted = -1738, - errAEDescIsNull = -1739, - errAEBuildSyntaxError = -1740, - errAEBufferTooSmall = -1741 -}; - -enum { - errOSASystemError = -1750, - errOSAInvalidID = -1751, - errOSABadStorageType = -1752, - errOSAScriptError = -1753, - errOSABadSelector = -1754, - errOSASourceNotAvailable = -1756, - errOSANoSuchDialect = -1757, - errOSADataFormatObsolete = -1758, - errOSADataFormatTooNew = -1759, - errOSACorruptData = errAECorruptData, - errOSARecordingIsAlreadyOn = errAERecordingIsAlreadyOn, - errOSAComponentMismatch = -1761, - errOSACantOpenComponent = -1762, - errOSACantStorePointers = -1763 -}; - - - - -enum { - errOffsetInvalid = -1800, - errOffsetIsOutsideOfView = -1801, - errTopOfDocument = -1810, - errTopOfBody = -1811, - errEndOfDocument = -1812, - errEndOfBody = -1813 -}; - - -enum { - - badDragRefErr = -1850, - badDragItemErr = -1851, - badDragFlavorErr = -1852, - duplicateFlavorErr = -1853, - cantGetFlavorErr = -1854, - duplicateHandlerErr = -1855, - handlerNotFoundErr = -1856, - dragNotAcceptedErr = -1857, - unsupportedForPlatformErr = -1858, - noSuitableDisplaysErr = -1859, - badImageRgnErr = -1860, - badImageErr = -1861, - nonDragOriginatorErr = -1862 -}; - - - -enum { - couldNotResolveDataRef = -2000, - badImageDescription = -2001, - badPublicMovieAtom = -2002, - cantFindHandler = -2003, - cantOpenHandler = -2004, - badComponentType = -2005, - noMediaHandler = -2006, - noDataHandler = -2007, - invalidMedia = -2008, - invalidTrack = -2009, - invalidMovie = -2010, - invalidSampleTable = -2011, - invalidDataRef = -2012, - invalidHandler = -2013, - invalidDuration = -2014, - invalidTime = -2015, - cantPutPublicMovieAtom = -2016, - badEditList = -2017, - mediaTypesDontMatch = -2018, - progressProcAborted = -2019, - movieToolboxUninitialized = -2020, - noRecordOfApp = movieToolboxUninitialized, - wfFileNotFound = -2021, - cantCreateSingleForkFile = -2022, - invalidEditState = -2023, - nonMatchingEditState = -2024, - staleEditState = -2025, - userDataItemNotFound = -2026, - maxSizeToGrowTooSmall = -2027, - badTrackIndex = -2028, - trackIDNotFound = -2029, - trackNotInMovie = -2030, - timeNotInTrack = -2031, - timeNotInMedia = -2032, - badEditIndex = -2033, - internalQuickTimeError = -2034, - cantEnableTrack = -2035, - invalidRect = -2036, - invalidSampleNum = -2037, - invalidChunkNum = -2038, - invalidSampleDescIndex = -2039, - invalidChunkCache = -2040, - invalidSampleDescription = -2041, - dataNotOpenForRead = -2042, - dataNotOpenForWrite = -2043, - dataAlreadyOpenForWrite = -2044, - dataAlreadyClosed = -2045, - endOfDataReached = -2046, - dataNoDataRef = -2047, - noMovieFound = -2048, - invalidDataRefContainer = -2049, - badDataRefIndex = -2050, - noDefaultDataRef = -2051, - couldNotUseAnExistingSample = -2052, - featureUnsupported = -2053, - noVideoTrackInMovieErr = -2054, - noSoundTrackInMovieErr = -2055, - soundSupportNotAvailableErr = -2056, - unsupportedAuxiliaryImportData = -2057, - auxiliaryExportDataUnavailable = -2058, - samplesAlreadyInMediaErr = -2059, - noSourceTreeFoundErr = -2060, - sourceNotFoundErr = -2061, - movieTextNotFoundErr = -2062, - missingRequiredParameterErr = -2063, - invalidSpriteWorldPropertyErr = -2064, - invalidSpritePropertyErr = -2065, - gWorldsNotSameDepthAndSizeErr = -2066, - invalidSpriteIndexErr = -2067, - invalidImageIndexErr = -2068, - invalidSpriteIDErr = -2069 -}; - -enum { - internalComponentErr = -2070, - notImplementedMusicOSErr = -2071, - cantSendToSynthesizerOSErr = -2072, - cantReceiveFromSynthesizerOSErr = -2073, - illegalVoiceAllocationOSErr = -2074, - illegalPartOSErr = -2075, - illegalChannelOSErr = -2076, - illegalKnobOSErr = -2077, - illegalKnobValueOSErr = -2078, - illegalInstrumentOSErr = -2079, - illegalControllerOSErr = -2080, - midiManagerAbsentOSErr = -2081, - synthesizerNotRespondingOSErr = -2082, - synthesizerOSErr = -2083, - illegalNoteChannelOSErr = -2084, - noteChannelNotAllocatedOSErr = -2085, - tunePlayerFullOSErr = -2086, - tuneParseOSErr = -2087, - noExportProcAvailableErr = -2089, - videoOutputInUseErr = -2090 -}; - -enum { - componentDllLoadErr = -2091, - componentDllEntryNotFoundErr = -2092, - qtmlDllLoadErr = -2093, - qtmlDllEntryNotFoundErr = -2094, - qtmlUninitialized = -2095, - unsupportedOSErr = -2096, - unsupportedProcessorErr = -2097, - componentNotThreadSafeErr = -2098 -}; - -enum { - cannotFindAtomErr = -2101, - notLeafAtomErr = -2102, - atomsNotOfSameTypeErr = -2103, - atomIndexInvalidErr = -2104, - duplicateAtomTypeAndIDErr = -2105, - invalidAtomErr = -2106, - invalidAtomContainerErr = -2107, - invalidAtomTypeErr = -2108, - cannotBeLeafAtomErr = -2109, - pathTooLongErr = -2110, - emptyPathErr = -2111, - noPathMappingErr = -2112, - pathNotVerifiedErr = -2113, - unknownFormatErr = -2114, - wackBadFileErr = -2115, - wackForkNotFoundErr = -2116, - wackBadMetaDataErr = -2117, - qfcbNotFoundErr = -2118, - qfcbNotCreatedErr = -2119, - AAPNotCreatedErr = -2120, - AAPNotFoundErr = -2121, - ASDBadHeaderErr = -2122, - ASDBadForkErr = -2123, - ASDEntryNotFoundErr = -2124, - fileOffsetTooBigErr = -2125, - notAllowedToSaveMovieErr = -2126, - qtNetworkAlreadyAllocatedErr = -2127, - urlDataHHTTPProtocolErr = -2129, - urlDataHHTTPNoNetDriverErr = -2130, - urlDataHHTTPURLErr = -2131, - urlDataHHTTPRedirectErr = -2132, - urlDataHFTPProtocolErr = -2133, - urlDataHFTPShutdownErr = -2134, - urlDataHFTPBadUserErr = -2135, - urlDataHFTPBadPasswordErr = -2136, - urlDataHFTPServerErr = -2137, - urlDataHFTPDataConnectionErr = -2138, - urlDataHFTPNoDirectoryErr = -2139, - urlDataHFTPQuotaErr = -2140, - urlDataHFTPPermissionsErr = -2141, - urlDataHFTPFilenameErr = -2142, - urlDataHFTPNoNetDriverErr = -2143, - urlDataHFTPBadNameListErr = -2144, - urlDataHFTPNeedPasswordErr = -2145, - urlDataHFTPNoPasswordErr = -2146, - urlDataHFTPServerDisconnectedErr = -2147, - urlDataHFTPURLErr = -2148, - notEnoughDataErr = -2149, - qtActionNotHandledErr = -2157, - qtXMLParseErr = -2158, - qtXMLApplicationErr = -2159 -}; - - -enum { - digiUnimpErr = -2201, - qtParamErr = -2202, - matrixErr = -2203, - notExactMatrixErr = -2204, - noMoreKeyColorsErr = -2205, - notExactSizeErr = -2206, - badDepthErr = -2207, - noDMAErr = -2208, - badCallOrderErr = -2209 -}; - - - -enum { - kernelIncompleteErr = -2401, - kernelCanceledErr = -2402, - kernelOptionsErr = -2403, - kernelPrivilegeErr = -2404, - kernelUnsupportedErr = -2405, - kernelObjectExistsErr = -2406, - kernelWritePermissionErr = -2407, - kernelReadPermissionErr = -2408, - kernelExecutePermissionErr = -2409, - kernelDeletePermissionErr = -2410, - kernelExecutionLevelErr = -2411, - kernelAttributeErr = -2412, - kernelAsyncSendLimitErr = -2413, - kernelAsyncReceiveLimitErr = -2414, - kernelTimeoutErr = -2415, - kernelInUseErr = -2416, - kernelTerminatedErr = -2417, - kernelExceptionErr = -2418, - kernelIDErr = -2419, - kernelAlreadyFreeErr = -2421, - kernelReturnValueErr = -2422, - kernelUnrecoverableErr = -2499 -}; - - - -enum { - - tsmComponentNoErr = 0, - tsmUnsupScriptLanguageErr = -2500, - tsmInputMethodNotFoundErr = -2501, - tsmNotAnAppErr = -2502, - tsmAlreadyRegisteredErr = -2503, - tsmNeverRegisteredErr = -2504, - tsmInvalidDocIDErr = -2505, - tsmTSMDocBusyErr = -2506, - tsmDocNotActiveErr = -2507, - tsmNoOpenTSErr = -2508, - tsmCantOpenComponentErr = -2509, - tsmTextServiceNotFoundErr = -2510, - tsmDocumentOpenErr = -2511, - tsmUseInputWindowErr = -2512, - tsmTSHasNoMenuErr = -2513, - tsmTSNotOpenErr = -2514, - tsmComponentAlreadyOpenErr = -2515, - tsmInputMethodIsOldErr = -2516, - tsmScriptHasNoIMErr = -2517, - tsmUnsupportedTypeErr = -2518, - tsmUnknownErr = -2519, - tsmInvalidContext = -2520, - tsmNoHandler = -2521, - tsmNoMoreTokens = -2522, - tsmNoStem = -2523, - tsmDefaultIsNotInputMethodErr = -2524, - tsmDocPropertyNotFoundErr = -2528, - tsmDocPropertyBufferTooSmallErr = -2529, - tsmCantChangeForcedClassStateErr = -2530, - tsmComponentPropertyUnsupportedErr = -2531, - tsmComponentPropertyNotFoundErr = -2532, - tsmInputModeChangeFailedErr = -2533 -}; - - -enum { - - mmInternalError = -2526 -}; - - -enum { - nrLockedErr = -2536, - nrNotEnoughMemoryErr = -2537, - nrInvalidNodeErr = -2538, - nrNotFoundErr = -2539, - nrNotCreatedErr = -2540, - nrNameErr = -2541, - nrNotSlotDeviceErr = -2542, - nrDataTruncatedErr = -2543, - nrPowerErr = -2544, - nrPowerSwitchAbortErr = -2545, - nrTypeMismatchErr = -2546, - nrNotModifiedErr = -2547, - nrOverrunErr = -2548, - nrResultCodeBase = -2549, - nrPathNotFound = -2550, - nrPathBufferTooSmall = -2551, - nrInvalidEntryIterationOp = -2552, - nrPropertyAlreadyExists = -2553, - nrIterationDone = -2554, - nrExitedIteratorScope = -2555, - nrTransactionAborted = -2556, - nrCallNotSupported = -2557 -}; - - -enum { - invalidIconRefErr = -2580, - noSuchIconErr = -2581, - noIconDataAvailableErr = -2582 -}; -enum { - errOSACantCoerce = errAECoercionFail, - errOSACantAccess = errAENoSuchObject, - errOSACantAssign = -10006, - errOSAGeneralError = -2700, - errOSADivideByZero = -2701, - errOSANumericOverflow = -2702, - errOSACantLaunch = -2703, - errOSAAppNotHighLevelEventAware = -2704, - errOSACorruptTerminology = -2705, - errOSAStackOverflow = -2706, - errOSAInternalTableOverflow = -2707, - errOSADataBlockTooLarge = -2708, - errOSACantGetTerminology = -2709, - errOSACantCreate = -2710 -}; -enum { - errOSATypeError = errAEWrongDataType, - OSAMessageNotUnderstood = errAEEventNotHandled, - OSAUndefinedHandler = errAEHandlerNotFound, - OSAIllegalAccess = errAEAccessorNotFound, - OSAIllegalIndex = errAEIllegalIndex, - OSAIllegalRange = errAEImpossibleRange, - OSAIllegalAssign = -10003, - OSASyntaxError = -2740, - OSASyntaxTypeError = -2741, - OSATokenTooLong = -2742, - OSAMissingParameter = errAEDescNotFound, - OSAParameterMismatch = errAEWrongNumberArgs, - OSADuplicateParameter = -2750, - OSADuplicateProperty = -2751, - OSADuplicateHandler = -2752, - OSAUndefinedVariable = -2753, - OSAInconsistentDeclarations = -2754, - OSAControlFlowError = -2755 -}; -enum { - errASCantConsiderAndIgnore = -2720, - errASCantCompareMoreThan32k = -2721, - errASTerminologyNestingTooDeep = -2760, - errASIllegalFormalParameter = -2761, - errASParameterNotForEvent = -2762, - errASNoResultReturned = -2763, - errASInconsistentNames = -2780 -}; - - - -enum { - cfragFirstErrCode = -2800, - cfragContextIDErr = -2800, - cfragConnectionIDErr = -2801, - cfragNoSymbolErr = -2802, - cfragNoSectionErr = -2803, - cfragNoLibraryErr = -2804, - cfragDupRegistrationErr = -2805, - cfragFragmentFormatErr = -2806, - cfragUnresolvedErr = -2807, - cfragNoPositionErr = -2808, - cfragNoPrivateMemErr = -2809, - cfragNoClientMemErr = -2810, - cfragNoIDsErr = -2811, - cfragInitOrderErr = -2812, - cfragImportTooOldErr = -2813, - cfragImportTooNewErr = -2814, - cfragInitLoopErr = -2815, - cfragInitAtBootErr = -2816, - cfragLibConnErr = -2817, - cfragCFMStartupErr = -2818, - cfragCFMInternalErr = -2819, - cfragFragmentCorruptErr = -2820, - cfragInitFunctionErr = -2821, - cfragNoApplicationErr = -2822, - cfragArchitectureErr = -2823, - cfragFragmentUsageErr = -2824, - cfragFileSizeErr = -2825, - cfragNotClosureErr = -2826, - cfragNoRegistrationErr = -2827, - cfragContainerIDErr = -2828, - cfragClosureIDErr = -2829, - cfragAbortClosureErr = -2830, - cfragOutputLengthErr = -2831, - cfragMapFileErr = -2851, - cfragExecFileRefErr = -2854, - cfragStdFolderErr = -2855, - cfragRsrcForkErr = -2856, - cfragCFragRsrcErr = -2857, - cfragLastErrCode = -2899 -}; - -enum { - - cfragFirstReservedCode = -2897, - cfragReservedCode_3 = -2897, - cfragReservedCode_2 = -2898, - cfragReservedCode_1 = -2899 -}; -enum { - invalidComponentID = -3000, - validInstancesExist = -3001, - componentNotCaptured = -3002, - componentDontRegister = -3003, - unresolvedComponentDLLErr = -3004, - retryComponentRegistrationErr = -3005 -}; - - -enum { - invalidTranslationPathErr = -3025, - couldNotParseSourceFileErr = -3026, - noTranslationPathErr = -3030, - badTranslationSpecErr = -3031, - noPrefAppErr = -3032 -}; - -enum { - buf2SmallErr = -3101, - noMPPErr = -3102, - ckSumErr = -3103, - extractErr = -3104, - readQErr = -3105, - atpLenErr = -3106, - atpBadRsp = -3107, - recNotFnd = -3108, - sktClosedErr = -3109 -}; - - - -enum { - kOTNoError = 0, - kOTOutOfMemoryErr = -3211, - kOTNotFoundErr = -3201, - kOTDuplicateFoundErr = -3216, - kOTBadAddressErr = -3150, - kOTBadOptionErr = -3151, - kOTAccessErr = -3152, - kOTBadReferenceErr = -3153, - kOTNoAddressErr = -3154, - kOTOutStateErr = -3155, - kOTBadSequenceErr = -3156, - kOTSysErrorErr = -3157, - kOTLookErr = -3158, - kOTBadDataErr = -3159, - kOTBufferOverflowErr = -3160, - kOTFlowErr = -3161, - kOTNoDataErr = -3162, - kOTNoDisconnectErr = -3163, - kOTNoUDErrErr = -3164, - kOTBadFlagErr = -3165, - kOTNoReleaseErr = -3166, - kOTNotSupportedErr = -3167, - kOTStateChangeErr = -3168, - kOTNoStructureTypeErr = -3169, - kOTBadNameErr = -3170, - kOTBadQLenErr = -3171, - kOTAddressBusyErr = -3172, - kOTIndOutErr = -3173, - kOTProviderMismatchErr = -3174, - kOTResQLenErr = -3175, - kOTResAddressErr = -3176, - kOTQFullErr = -3177, - kOTProtocolErr = -3178, - kOTBadSyncErr = -3179, - kOTCanceledErr = -3180, - kEPERMErr = -3200, - kENOENTErr = -3201, - kENORSRCErr = -3202, - kEINTRErr = -3203, - kEIOErr = -3204, - kENXIOErr = -3205, - kEBADFErr = -3208, - kEAGAINErr = -3210, - kENOMEMErr = -3211, - kEACCESErr = -3212, - kEFAULTErr = -3213, - kEBUSYErr = -3215, - kEEXISTErr = -3216, - kENODEVErr = -3218, - kEINVALErr = -3221, - kENOTTYErr = -3224, - kEPIPEErr = -3231, - kERANGEErr = -3233, - kEWOULDBLOCKErr = -3234, - kEDEADLKErr = -3234, - kEALREADYErr = -3236, - kENOTSOCKErr = -3237, - kEDESTADDRREQErr = -3238, - kEMSGSIZEErr = -3239, - kEPROTOTYPEErr = -3240, - kENOPROTOOPTErr = -3241, - kEPROTONOSUPPORTErr = -3242, - kESOCKTNOSUPPORTErr = -3243, - kEOPNOTSUPPErr = -3244, - kEADDRINUSEErr = -3247, - kEADDRNOTAVAILErr = -3248, - kENETDOWNErr = -3249, - kENETUNREACHErr = -3250, - kENETRESETErr = -3251, - kECONNABORTEDErr = -3252, - kECONNRESETErr = -3253, - kENOBUFSErr = -3254, - kEISCONNErr = -3255, - kENOTCONNErr = -3256, - kESHUTDOWNErr = -3257, - kETOOMANYREFSErr = -3258, - kETIMEDOUTErr = -3259, - kECONNREFUSEDErr = -3260, - kEHOSTDOWNErr = -3263, - kEHOSTUNREACHErr = -3264, - kEPROTOErr = -3269, - kETIMEErr = -3270, - kENOSRErr = -3271, - kEBADMSGErr = -3272, - kECANCELErr = -3273, - kENOSTRErr = -3274, - kENODATAErr = -3275, - kEINPROGRESSErr = -3276, - kESRCHErr = -3277, - kENOMSGErr = -3278, - kOTClientNotInittedErr = -3279, - kOTPortHasDiedErr = -3280, - kOTPortWasEjectedErr = -3281, - kOTBadConfigurationErr = -3282, - kOTConfigurationChangedErr = -3283, - kOTUserRequestedErr = -3284, - kOTPortLostConnection = -3285 -}; - - - -enum { - kQDNoPalette = -3950, - kQDNoColorHWCursorSupport = -3951, - kQDCursorAlreadyRegistered = -3952, - kQDCursorNotRegistered = -3953, - kQDCorruptPICTDataErr = -3954 -}; - - - - -enum { - firstPickerError = -4000, - invalidPickerType = firstPickerError, - requiredFlagsDontMatch = -4001, - pickerResourceError = -4002, - cantLoadPicker = -4003, - cantCreatePickerWindow = -4004, - cantLoadPackage = -4005, - pickerCantLive = -4006, - colorSyncNotInstalled = -4007, - badProfileError = -4008, - noHelpForItem = -4009 -}; - - - - -enum { - kNSL68kContextNotSupported = -4170, - kNSLSchedulerError = -4171, - kNSLBadURLSyntax = -4172, - kNSLNoCarbonLib = -4173, - kNSLUILibraryNotAvailable = -4174, - kNSLNotImplementedYet = -4175, - kNSLErrNullPtrError = -4176, - kNSLSomePluginsFailedToLoad = -4177, - kNSLNullNeighborhoodPtr = -4178, - kNSLNoPluginsForSearch = -4179, - kNSLSearchAlreadyInProgress = -4180, - kNSLNoPluginsFound = -4181, - kNSLPluginLoadFailed = -4182, - kNSLBadProtocolTypeErr = -4183, - kNSLNullListPtr = -4184, - kNSLBadClientInfoPtr = -4185, - kNSLCannotContinueLookup = -4186, - kNSLBufferTooSmallForData = -4187, - kNSLNoContextAvailable = -4188, - kNSLRequestBufferAlreadyInList = -4189, - kNSLInvalidPluginSpec = -4190, - kNSLNoSupportForService = -4191, - kNSLBadNetConnection = -4192, - kNSLBadDataTypeErr = -4193, - kNSLBadServiceTypeErr = -4194, - kNSLBadReferenceErr = -4195, - kNSLNoElementsInList = -4196, - kNSLInsufficientOTVer = -4197, - kNSLInsufficientSysVer = -4198, - kNSLNotInitialized = -4199, - kNSLInitializationFailed = -4200 -}; - - - - -enum { - kDTPHoldJobErr = -4200, - kDTPStopQueueErr = -4201, - kDTPTryAgainErr = -4202, - kDTPAbortJobErr = 128 -}; - - - -enum { - - cmElementTagNotFound = -4200, - cmIndexRangeErr = -4201, - cmCantDeleteElement = -4202, - cmFatalProfileErr = -4203, - cmInvalidProfile = -4204, - cmInvalidProfileLocation = -4205, - cmCantCopyModifiedV1Profile = -4215, - - cmInvalidSearch = -4206, - cmSearchError = -4207, - cmErrIncompatibleProfile = -4208, - cmInvalidColorSpace = -4209, - cmInvalidSrcMap = -4210, - cmInvalidDstMap = -4211, - cmNoGDevicesError = -4212, - cmInvalidProfileComment = -4213, - cmRangeOverFlow = -4214, - cmNamedColorNotFound = -4216, - cmCantGamutCheckError = -4217 -}; - - -enum { - badFolderDescErr = -4270, - duplicateFolderDescErr = -4271, - noMoreFolderDescErr = -4272, - invalidFolderTypeErr = -4273, - duplicateRoutingErr = -4274, - routingNotFoundErr = -4275, - badRoutingSizeErr = -4276 -}; - - - -enum { - coreFoundationUnknownErr = -4960 -}; - - -enum { - errCoreEndianDataTooShortForFormat = -4940, - errCoreEndianDataTooLongForFormat = -4941, - errCoreEndianDataDoesNotMatchFormat = -4942 -}; - - - -enum { - internalScrapErr = -4988, - duplicateScrapFlavorErr = -4989, - badScrapRefErr = -4990, - processStateIncorrectErr = -4991, - scrapPromiseNotKeptErr = -4992, - noScrapPromiseKeeperErr = -4993, - nilScrapFlavorDataErr = -4994, - scrapFlavorFlagsMismatchErr = -4995, - scrapFlavorSizeMismatchErr = -4996, - illegalScrapFlavorFlagsErr = -4997, - illegalScrapFlavorTypeErr = -4998, - illegalScrapFlavorSizeErr = -4999, - scrapFlavorNotFoundErr = -102, - needClearScrapErr = -100 -}; - - -enum { - - afpAccessDenied = -5000, - afpAuthContinue = -5001, - afpBadUAM = -5002, - afpBadVersNum = -5003, - afpBitmapErr = -5004, - afpCantMove = -5005, - afpDenyConflict = -5006, - afpDirNotEmpty = -5007, - afpDiskFull = -5008, - afpEofError = -5009, - afpFileBusy = -5010, - afpFlatVol = -5011, - afpItemNotFound = -5012, - afpLockErr = -5013, - afpMiscErr = -5014, - afpNoMoreLocks = -5015, - afpNoServer = -5016, - afpObjectExists = -5017, - afpObjectNotFound = -5018, - afpParmErr = -5019, - afpRangeNotLocked = -5020, - afpRangeOverlap = -5021, - afpSessClosed = -5022, - afpUserNotAuth = -5023, - afpCallNotSupported = -5024, - afpObjectTypeErr = -5025, - afpTooManyFilesOpen = -5026, - afpServerGoingDown = -5027, - afpCantRename = -5028, - afpDirNotFound = -5029, - afpIconTypeError = -5030, - afpVolLocked = -5031, - afpObjectLocked = -5032, - afpContainsSharedErr = -5033, - afpIDNotFound = -5034, - afpIDExists = -5035, - afpDiffVolErr = -5036, - afpCatalogChanged = -5037, - afpSameObjectErr = -5038, - afpBadIDErr = -5039, - afpPwdSameErr = -5040, - afpPwdTooShortErr = -5041, - afpPwdExpiredErr = -5042, - afpInsideSharedErr = -5043, - - afpInsideTrashErr = -5044, - - afpPwdNeedsChangeErr = -5045, - afpPwdPolicyErr = -5046, - afpAlreadyLoggedInErr = -5047, - afpCallNotAllowed = -5048 -}; - -enum { - - afpBadDirIDType = -5060, - afpCantMountMoreSrvre = -5061, - afpAlreadyMounted = -5062, - afpSameNodeErr = -5063 -}; - - - - - - -enum { - numberFormattingNotANumberErr = -5200, - numberFormattingOverflowInDestinationErr = -5201, - numberFormattingBadNumberFormattingObjectErr = -5202, - numberFormattingSpuriousCharErr = -5203, - numberFormattingLiteralMissingErr = -5204, - numberFormattingDelimiterMissingErr = -5205, - numberFormattingEmptyFormatErr = -5206, - numberFormattingBadFormatErr = -5207, - numberFormattingBadOptionsErr = -5208, - numberFormattingBadTokenErr = -5209, - numberFormattingUnOrderedCurrencyRangeErr = -5210, - numberFormattingBadCurrencyPositionErr = -5211, - numberFormattingNotADigitErr = -5212, - numberFormattingUnOrdredCurrencyRangeErr = -5210, - numberFortmattingNotADigitErr = -5212 -}; - - -enum { - textParserBadParamErr = -5220, - textParserObjectNotFoundErr = -5221, - textParserBadTokenValueErr = -5222, - textParserBadParserObjectErr = -5223, - textParserParamErr = -5224, - textParserNoMoreTextErr = -5225, - textParserBadTextLanguageErr = -5226, - textParserBadTextEncodingErr = -5227, - textParserNoSuchTokenFoundErr = -5228, - textParserNoMoreTokensErr = -5229 -}; - -enum { - errUnknownAttributeTag = -5240, - errMarginWilllNotFit = -5241, - errNotInImagingMode = -5242, - errAlreadyInImagingMode = -5243, - errEngineNotFound = -5244, - errIteratorReachedEnd = -5245, - errInvalidRange = -5246, - errOffsetNotOnElementBounday = -5247, - errNoHiliteText = -5248, - errEmptyScrap = -5249, - errReadOnlyText = -5250, - errUnknownElement = -5251, - errNonContiuousAttribute = -5252, - errCannotUndo = -5253 -}; - - - -enum { - hrHTMLRenderingLibNotInstalledErr = -5360, - hrMiscellaneousExceptionErr = -5361, - hrUnableToResizeHandleErr = -5362, - hrURLNotHandledErr = -5363 -}; - - - -enum { - errIANoErr = 0, - errIAUnknownErr = -5380, - errIAAllocationErr = -5381, - errIAParamErr = -5382, - errIANoMoreItems = -5383, - errIABufferTooSmall = -5384, - errIACanceled = -5385, - errIAInvalidDocument = -5386, - errIATextExtractionErr = -5387, - errIAEndOfTextRun = -5388 -}; - - - -enum { - qtsBadSelectorErr = -5400, - qtsBadStateErr = -5401, - qtsBadDataErr = -5402, - qtsUnsupportedDataTypeErr = -5403, - qtsUnsupportedRateErr = -5404, - qtsUnsupportedFeatureErr = -5405, - qtsTooMuchDataErr = -5406, - qtsUnknownValueErr = -5407, - qtsTimeoutErr = -5408, - qtsConnectionFailedErr = -5420, - qtsAddressBusyErr = -5421 -}; - - -enum { - - gestaltUnknownErr = -5550, - gestaltUndefSelectorErr = -5551, - gestaltDupSelectorErr = -5552, - gestaltLocationErr = -5553 -}; - - - -enum { - menuPropertyInvalidErr = -5603, - menuPropertyInvalid = menuPropertyInvalidErr, - menuPropertyNotFoundErr = -5604, - menuNotFoundErr = -5620, - menuUsesSystemDefErr = -5621, - menuItemNotFoundErr = -5622, - menuInvalidErr = -5623 -}; - - - -enum { - errInvalidWindowPtr = -5600, - errInvalidWindowRef = -5600, - errUnsupportedWindowAttributesForClass = -5601, - errWindowDoesNotHaveProxy = -5602, - errInvalidWindowProperty = -5603, - errWindowPropertyNotFound = -5604, - errUnrecognizedWindowClass = -5605, - errCorruptWindowDescription = -5606, - errUserWantsToDragWindow = -5607, - errWindowsAlreadyInitialized = -5608, - errFloatingWindowsNotInitialized = -5609, - errWindowNotFound = -5610, - errWindowDoesNotFitOnscreen = -5611, - windowAttributeImmutableErr = -5612, - windowAttributesConflictErr = -5613, - windowManagerInternalErr = -5614, - windowWrongStateErr = -5615, - windowGroupInvalidErr = -5616, - windowAppModalStateAlreadyExistsErr = -5617, - windowNoAppModalStateErr = -5618, - errWindowDoesntSupportFocus = -30583, - errWindowRegionCodeInvalid = -30593 -}; - - - -enum { - dialogNoTimeoutErr = -5640 -}; - - - -enum { - kNavWrongDialogStateErr = -5694, - kNavWrongDialogClassErr = -5695, - kNavInvalidSystemConfigErr = -5696, - kNavCustomControlMessageFailedErr = -5697, - kNavInvalidCustomControlMessageErr = -5698, - kNavMissingKindStringErr = -5699 -}; - - - -enum { - collectionItemLockedErr = -5750, - collectionItemNotFoundErr = -5751, - collectionIndexRangeErr = -5752, - collectionVersionErr = -5753 -}; - - - -enum { - kQTSSUnknownErr = -6150 -}; - - -enum { - - kDMGenErr = -6220, - - kDMMirroringOnAlready = -6221, - kDMWrongNumberOfDisplays = -6222, - kDMMirroringBlocked = -6223, - kDMCantBlock = -6224, - kDMMirroringNotOn = -6225, - - kSysSWTooOld = -6226, - kDMSWNotInitializedErr = -6227, - kDMDriverNotDisplayMgrAwareErr = -6228, - kDMDisplayNotFoundErr = -6229, - kDMNotFoundErr = -6229, - kDMDisplayAlreadyInstalledErr = -6230, - kDMMainDisplayCannotMoveErr = -6231, - kDMNoDeviceTableclothErr = -6231, - kDMFoundErr = -6232 -}; - - - - - -enum { - laTooSmallBufferErr = -6984, - laEnvironmentBusyErr = -6985, - laEnvironmentNotFoundErr = -6986, - laEnvironmentExistErr = -6987, - laInvalidPathErr = -6988, - laNoMoreMorphemeErr = -6989, - laFailAnalysisErr = -6990, - laTextOverFlowErr = -6991, - laDictionaryNotOpenedErr = -6992, - laDictionaryUnknownErr = -6993, - laDictionaryTooManyErr = -6994, - laPropertyValueErr = -6995, - laPropertyUnknownErr = -6996, - laPropertyIsReadOnlyErr = -6997, - laPropertyNotFoundErr = -6998, - laPropertyErr = -6999, - laEngineNotFoundErr = -7000 -}; - - -enum { - kUSBNoErr = 0, - kUSBNoTran = 0, - kUSBNoDelay = 0, - kUSBPending = 1 -}; -enum { - kUSBNotSent2Err = -6901, - kUSBNotSent1Err = -6902, - kUSBBufUnderRunErr = -6903, - kUSBBufOvrRunErr = -6904, - kUSBRes2Err = -6905, - kUSBRes1Err = -6906, - kUSBUnderRunErr = -6907, - kUSBOverRunErr = -6908, - kUSBWrongPIDErr = -6909, - kUSBPIDCheckErr = -6910, - kUSBNotRespondingErr = -6911, - kUSBEndpointStallErr = -6912, - kUSBDataToggleErr = -6913, - kUSBBitstufErr = -6914, - kUSBCRCErr = -6915, - kUSBLinkErr = -6916 -}; - - - - - - -enum { - kUSBQueueFull = -6948, - kUSBNotHandled = -6987, - kUSBUnknownNotification = -6949, - kUSBBadDispatchTable = -6950 -}; - - - - - - - -enum { - kUSBInternalReserved10 = -6951, - kUSBInternalReserved9 = -6952, - kUSBInternalReserved8 = -6953, - kUSBInternalReserved7 = -6954, - kUSBInternalReserved6 = -6955, - kUSBInternalReserved5 = -6956, - kUSBInternalReserved4 = -6957, - kUSBInternalReserved3 = -6958, - kUSBInternalReserved2 = -6959, - kUSBInternalReserved1 = -6960 -}; - - -enum { - kUSBPortDisabled = -6969, - kUSBQueueAborted = -6970, - kUSBTimedOut = -6971, - kUSBDeviceDisconnected = -6972, - kUSBDeviceNotSuspended = -6973, - kUSBDeviceSuspended = -6974, - kUSBInvalidBuffer = -6975, - kUSBDevicePowerProblem = -6976, - kUSBDeviceBusy = -6977, - kUSBUnknownInterfaceErr = -6978, - kUSBPipeStalledError = -6979, - kUSBPipeIdleError = -6980, - kUSBNoBandwidthError = -6981, - kUSBAbortedError = -6982, - kUSBFlagsError = -6983, - kUSBCompletionError = -6984, - kUSBPBLengthError = -6985, - kUSBPBVersionError = -6986, - kUSBNotFound = -6987, - kUSBOutOfMemoryErr = -6988, - kUSBDeviceErr = -6989, - kUSBNoDeviceErr = -6990, - kUSBAlreadyOpenErr = -6991, - kUSBTooManyTransactionsErr = -6992, - kUSBUnknownRequestErr = -6993, - kUSBRqErr = -6994, - kUSBIncorrectTypeErr = -6995, - kUSBTooManyPipesErr = -6996, - kUSBUnknownPipeErr = -6997, - kUSBUnknownDeviceErr = -6998, - kUSBInternalErr = -6999 -}; - - - - - -enum { - dcmParamErr = -7100, - dcmNotDictionaryErr = -7101, - dcmBadDictionaryErr = -7102, - dcmPermissionErr = -7103, - dcmDictionaryNotOpenErr = -7104, - dcmDictionaryBusyErr = -7105, - dcmBlockFullErr = -7107, - dcmNoRecordErr = -7108, - dcmDupRecordErr = -7109, - dcmNecessaryFieldErr = -7110, - dcmBadFieldInfoErr = -7111, - dcmBadFieldTypeErr = -7112, - dcmNoFieldErr = -7113, - dcmBadKeyErr = -7115, - dcmTooManyKeyErr = -7116, - dcmBadDataSizeErr = -7117, - dcmBadFindMethodErr = -7118, - dcmBadPropertyErr = -7119, - dcmProtectedErr = -7121, - dcmNoAccessMethodErr = -7122, - dcmBadFeatureErr = -7124, - dcmIterationCompleteErr = -7126, - dcmBufferOverflowErr = -7127 -}; - - - -enum { - kRAInvalidParameter = -7100, - kRAInvalidPort = -7101, - kRAStartupFailed = -7102, - kRAPortSetupFailed = -7103, - kRAOutOfMemory = -7104, - kRANotSupported = -7105, - kRAMissingResources = -7106, - kRAIncompatiblePrefs = -7107, - kRANotConnected = -7108, - kRAConnectionCanceled = -7109, - kRAUnknownUser = -7110, - kRAInvalidPassword = -7111, - kRAInternalError = -7112, - kRAInstallationDamaged = -7113, - kRAPortBusy = -7114, - kRAUnknownPortState = -7115, - kRAInvalidPortState = -7116, - kRAInvalidSerialProtocol = -7117, - kRAUserLoginDisabled = -7118, - kRAUserPwdChangeRequired = -7119, - kRAUserPwdEntryRequired = -7120, - kRAUserInteractionRequired = -7121, - kRAInitOpenTransportFailed = -7122, - kRARemoteAccessNotReady = -7123, - kRATCPIPInactive = -7124, - kRATCPIPNotConfigured = -7125, - kRANotPrimaryInterface = -7126, - kRAConfigurationDBInitErr = -7127, - kRAPPPProtocolRejected = -7128, - kRAPPPAuthenticationFailed = -7129, - kRAPPPNegotiationFailed = -7130, - kRAPPPUserDisconnected = -7131, - kRAPPPPeerDisconnected = -7132, - kRAPeerNotResponding = -7133, - kRAATalkInactive = -7134, - kRAExtAuthenticationFailed = -7135, - kRANCPRejectedbyPeer = -7136, - kRADuplicateIPAddr = -7137, - kRACallBackFailed = -7138, - kRANotEnabled = -7139 -}; -enum { - kATSUInvalidTextLayoutErr = -8790, - - - kATSUInvalidStyleErr = -8791, - - - kATSUInvalidTextRangeErr = -8792, - - - kATSUFontsMatched = -8793, - - - kATSUFontsNotMatched = -8794, - - - kATSUNoCorrespondingFontErr = -8795, - - - - - - - kATSUInvalidFontErr = -8796, - kATSUInvalidAttributeValueErr = -8797, - - kATSUInvalidAttributeSizeErr = -8798, - - kATSUInvalidAttributeTagErr = -8799, - - kATSUInvalidCacheErr = -8800, - - - - - kATSUNotSetErr = -8801, - - - - kATSUNoStyleRunsAssignedErr = -8802, - - kATSUQuickDrawTextErr = -8803, - - kATSULowLevelErr = -8804, - - kATSUNoFontCmapAvailableErr = -8805, - - kATSUNoFontScalerAvailableErr = -8806, - - kATSUCoordinateOverflowErr = -8807, - - kATSULineBreakInWord = -8808, - - - kATSUBusyObjectErr = -8809 -}; -enum { - - kTextUnsupportedEncodingErr = -8738, - kTextMalformedInputErr = -8739, - kTextUndefinedElementErr = -8740, - kTECMissingTableErr = -8745, - kTECTableChecksumErr = -8746, - kTECTableFormatErr = -8747, - kTECCorruptConverterErr = -8748, - kTECNoConversionPathErr = -8749, - kTECBufferBelowMinimumSizeErr = -8750, - kTECArrayFullErr = -8751, - kTECBadTextRunErr = -8752, - kTECPartialCharErr = -8753, - kTECUnmappableElementErr = -8754, - kTECIncompleteElementErr = -8755, - kTECDirectionErr = -8756, - kTECGlobalsUnavailableErr = -8770, - kTECItemUnavailableErr = -8771, - - kTECUsedFallbacksStatus = -8783, - kTECNeedFlushStatus = -8784, - kTECOutputBufferFullStatus = -8785, - - unicodeChecksumErr = -8769, - unicodeNoTableErr = -8768, - unicodeVariantErr = -8767, - unicodeFallbacksErr = -8766, - unicodePartConvertErr = -8765, - unicodeBufErr = -8764, - unicodeCharErr = -8763, - unicodeElementErr = -8762, - unicodeNotFoundErr = -8761, - unicodeTableFormatErr = -8760, - unicodeDirectionErr = -8759, - unicodeContextualErr = -8758, - unicodeTextEncodingDataErr = -8757 -}; - - - -enum { - kUTCUnderflowErr = -8850, - kUTCOverflowErr = -8851, - kIllegalClockValueErr = -8852 -}; - - - - - -enum { - kATSUInvalidFontFallbacksErr = -8900, - - kATSUUnsupportedStreamFormatErr = -8901, - - kATSUBadStreamErr = -8902, - - - kATSUOutputBufferTooSmallErr = -8903, - - kATSUInvalidCallInsideCallbackErr = -8904, - - kATSUNoFontNameErr = -8905, - - kATSULastErr = -8959 -}; - - - -enum { - codecErr = -8960, - noCodecErr = -8961, - codecUnimpErr = -8962, - codecSizeErr = -8963, - codecScreenBufErr = -8964, - codecImageBufErr = -8965, - codecSpoolErr = -8966, - codecAbortErr = -8967, - codecWouldOffscreenErr = -8968, - codecBadDataErr = -8969, - codecDataVersErr = -8970, - codecExtensionNotFoundErr = -8971, - scTypeNotFoundErr = codecExtensionNotFoundErr, - codecConditionErr = -8972, - codecOpenErr = -8973, - codecCantWhenErr = -8974, - codecCantQueueErr = -8975, - codecNothingToBlitErr = -8976, - codecNoMemoryPleaseWaitErr = -8977, - codecDisabledErr = -8978, - codecNeedToFlushChainErr = -8979, - lockPortBitsBadSurfaceErr = -8980, - lockPortBitsWindowMovedErr = -8981, - lockPortBitsWindowResizedErr = -8982, - lockPortBitsWindowClippedErr = -8983, - lockPortBitsBadPortErr = -8984, - lockPortBitsSurfaceLostErr = -8985, - codecParameterDialogConfirm = -8986, - codecNeedAccessKeyErr = -8987, - codecOffscreenFailedErr = -8988, - codecDroppedFrameErr = -8989, - directXObjectAlreadyExists = -8990, - lockPortBitsWrongGDeviceErr = -8991, - codecOffscreenFailedPleaseRetryErr = -8992, - badCodecCharacterizationErr = -8993, - noThumbnailFoundErr = -8994 -}; - - - -enum { - kBadAdapterErr = -9050, - kBadAttributeErr = -9051, - kBadBaseErr = -9052, - kBadEDCErr = -9053, - kBadIRQErr = -9054, - kBadOffsetErr = -9055, - kBadPageErr = -9056, - kBadSizeErr = -9057, - kBadSocketErr = -9058, - kBadTypeErr = -9059, - kBadVccErr = -9060, - kBadVppErr = -9061, - kBadWindowErr = -9062, - kBadArgLengthErr = -9063, - kBadArgsErr = -9064, - kBadHandleErr = -9065, - kBadCISErr = -9066, - kBadSpeedErr = -9067, - kReadFailureErr = -9068, - kWriteFailureErr = -9069, - kGeneralFailureErr = -9070, - kNoCardErr = -9071, - kUnsupportedFunctionErr = -9072, - kUnsupportedModeErr = -9073, - kBusyErr = -9074, - kWriteProtectedErr = -9075, - kConfigurationLockedErr = -9076, - kInUseErr = -9077, - kNoMoreItemsErr = -9078, - kOutOfResourceErr = -9079, - kNoCardSevicesSocketsErr = -9080, - kInvalidRegEntryErr = -9081, - kBadLinkErr = -9082, - kBadDeviceErr = -9083, - k16BitCardErr = -9084, - kCardBusCardErr = -9085, - kPassCallToChainErr = -9086, - kCantConfigureCardErr = -9087, - kPostCardEventErr = -9088, - kInvalidDeviceNumber = -9089, - kUnsupportedVsErr = -9090, - kInvalidCSClientErr = -9091, - kBadTupleDataErr = -9092, - kBadCustomIFIDErr = -9093, - kNoIOWindowRequestedErr = -9094, - kNoMoreTimerClientsErr = -9095, - kNoMoreInterruptSlotsErr = -9096, - kNoClientTableErr = -9097, - kUnsupportedCardErr = -9098, - kNoCardEnablersFoundErr = -9099, - kNoEnablerForCardErr = -9100, - kNoCompatibleNameErr = -9101, - kClientRequestDenied = -9102, - - kNotReadyErr = -9103, - kTooManyIOWindowsErr = -9104, - kAlreadySavedStateErr = -9105, - kAttemptDupCardEntryErr = -9106, - kCardPowerOffErr = -9107, - kNotZVCapableErr = -9108, - kNoCardBusCISErr = -9109 -}; - - -enum { - noDeviceForChannel = -9400, - grabTimeComplete = -9401, - cantDoThatInCurrentMode = -9402, - notEnoughMemoryToGrab = -9403, - notEnoughDiskSpaceToGrab = -9404, - couldntGetRequiredComponent = -9405, - badSGChannel = -9406, - seqGrabInfoNotAvailable = -9407, - deviceCantMeetRequest = -9408, - badControllerHeight = -9994, - editingNotAllowed = -9995, - controllerBoundsNotExact = -9996, - cannotSetWidthOfAttachedController = -9997, - controllerHasFixedHeight = -9998, - cannotMoveAttachedController = -9999 -}; - - -enum { - errAEBadKeyForm = -10002, - errAECantHandleClass = -10010, - errAECantSupplyType = -10009, - errAECantUndo = -10015, - errAEEventFailed = -10000, - errAEIndexTooLarge = -10007, - errAEInTransaction = -10011, - errAELocalOnly = -10016, - errAENoSuchTransaction = -10012, - errAENotAnElement = -10008, - errAENotASingleObject = -10014, - errAENotModifiable = -10003, - errAENoUserSelection = -10013, - errAEPrivilegeError = -10004, - errAEReadDenied = -10005, - errAETypeError = -10001, - errAEWriteDenied = -10006, - errAENotAnEnumMember = -10023, - errAECantPutThatThere = -10024, - errAEPropertiesClash = -10025 -}; - - -enum { - telGenericError = -1, - telNoErr = 0, - telNoTools = 8, - telBadTermErr = -10001, - telBadDNErr = -10002, - telBadCAErr = -10003, - telBadHandErr = -10004, - telBadProcErr = -10005, - telCAUnavail = -10006, - telNoMemErr = -10007, - telNoOpenErr = -10008, - telBadHTypeErr = -10010, - telHTypeNotSupp = -10011, - telBadLevelErr = -10012, - telBadVTypeErr = -10013, - telVTypeNotSupp = -10014, - telBadAPattErr = -10015, - telAPattNotSupp = -10016, - telBadIndex = -10017, - telIndexNotSupp = -10018, - telBadStateErr = -10019, - telStateNotSupp = -10020, - telBadIntExt = -10021, - telIntExtNotSupp = -10022, - telBadDNDType = -10023, - telDNDTypeNotSupp = -10024, - telFeatNotSub = -10030, - telFeatNotAvail = -10031, - telFeatActive = -10032, - telFeatNotSupp = -10033, - telConfLimitErr = -10040, - telConfNoLimit = -10041, - telConfErr = -10042, - telConfRej = -10043, - telTransferErr = -10044, - telTransferRej = -10045, - telCBErr = -10046, - telConfLimitExceeded = -10047, - telBadDNType = -10050, - telBadPageID = -10051, - telBadIntercomID = -10052, - telBadFeatureID = -10053, - telBadFwdType = -10054, - telBadPickupGroupID = -10055, - telBadParkID = -10056, - telBadSelect = -10057, - telBadBearerType = -10058, - telBadRate = -10059, - telDNTypeNotSupp = -10060, - telFwdTypeNotSupp = -10061, - telBadDisplayMode = -10062, - telDisplayModeNotSupp = -10063, - telNoCallbackRef = -10064, - telAlreadyOpen = -10070, - telStillNeeded = -10071, - telTermNotOpen = -10072, - telCANotAcceptable = -10080, - telCANotRejectable = -10081, - telCANotDeflectable = -10082, - telPBErr = -10090, - telBadFunction = -10091, - - telNoSuchTool = -10102, - telUnknownErr = -10103, - telNoCommFolder = -10106, - telInitFailed = -10107, - telBadCodeResource = -10108, - telDeviceNotFound = -10109, - telBadProcID = -10110, - telValidateFailed = -10111, - telAutoAnsNotOn = -10112, - telDetAlreadyOn = -10113, - telBadSWErr = -10114, - telBadSampleRate = -10115, - telNotEnoughdspBW = -10116 -}; - -enum { - errTaskNotFound = -10780 -}; - - - - - -enum { - - pmBusyErr = -13000, - pmReplyTOErr = -13001, - pmSendStartErr = -13002, - pmSendEndErr = -13003, - pmRecvStartErr = -13004, - pmRecvEndErr = -13005 -}; - - -enum { - kPowerHandlerExistsForDeviceErr = -13006, - kPowerHandlerNotFoundForDeviceErr = -13007, - kPowerHandlerNotFoundForProcErr = -13008, - kPowerMgtMessageNotHandled = -13009, - kPowerMgtRequestDenied = -13010, - kCantReportProcessorTemperatureErr = -13013, - kProcessorTempRoutineRequiresMPLib2 = -13014, - kNoSuchPowerSource = -13020, - kBridgeSoftwareRunningCantSleep = -13038 -}; - - - -enum { - debuggingExecutionContextErr = -13880, - debuggingDuplicateSignatureErr = -13881, - debuggingDuplicateOptionErr = -13882, - debuggingInvalidSignatureErr = -13883, - debuggingInvalidOptionErr = -13884, - debuggingInvalidNameErr = -13885, - debuggingNoCallbackErr = -13886, - debuggingNoMatchErr = -13887 -}; - - - -enum { - kHIDVersionIncompatibleErr = -13909, - kHIDDeviceNotReady = -13910 -}; - - - -enum { - kHIDSuccess = 0, - kHIDInvalidRangePageErr = -13923, - kHIDReportIDZeroErr = -13924, - kHIDReportCountZeroErr = -13925, - kHIDReportSizeZeroErr = -13926, - kHIDUnmatchedDesignatorRangeErr = -13927, - kHIDUnmatchedStringRangeErr = -13928, - kHIDInvertedUsageRangeErr = -13929, - kHIDUnmatchedUsageRangeErr = -13930, - kHIDInvertedPhysicalRangeErr = -13931, - kHIDInvertedLogicalRangeErr = -13932, - kHIDBadLogicalMaximumErr = -13933, - kHIDBadLogicalMinimumErr = -13934, - kHIDUsagePageZeroErr = -13935, - kHIDEndOfDescriptorErr = -13936, - kHIDNotEnoughMemoryErr = -13937, - kHIDBadParameterErr = -13938, - kHIDNullPointerErr = -13939, - kHIDInvalidReportLengthErr = -13940, - kHIDInvalidReportTypeErr = -13941, - kHIDBadLogPhysValuesErr = -13942, - kHIDIncompatibleReportErr = -13943, - kHIDInvalidPreparsedDataErr = -13944, - kHIDNotValueArrayErr = -13945, - kHIDUsageNotFoundErr = -13946, - kHIDValueOutOfRangeErr = -13947, - kHIDBufferTooSmallErr = -13948, - kHIDNullStateErr = -13949, - kHIDBaseError = -13950 -}; - - - -enum { - kModemOutOfMemory = -14000, - kModemPreferencesMissing = -14001, - kModemScriptMissing = -14002 -}; - - - - -enum { - kTXNEndIterationErr = -22000, - kTXNCannotAddFrameErr = -22001, - kTXNInvalidFrameIDErr = -22002, - kTXNIllegalToCrossDataBoundariesErr = -22003, - kTXNUserCanceledOperationErr = -22004, - kTXNBadDefaultFileTypeWarning = -22005, - kTXNCannotSetAutoIndentErr = -22006, - kTXNRunIndexOutofBoundsErr = -22007, - kTXNNoMatchErr = -22008, - kTXNAttributeTagInvalidForRunErr = -22009, - kTXNSomeOrAllTagsInvalidForRunErr = -22010, - kTXNInvalidRunIndex = -22011, - kTXNAlreadyInitializedErr = -22012, - kTXNCannotTurnTSMOffWhenUsingUnicodeErr = -22013, - kTXNCopyNotAllowedInEchoModeErr = -22014, - kTXNDataTypeNotAllowedErr = -22015, - kTXNATSUIIsNotInstalledErr = -22016, - kTXNOutsideOfLineErr = -22017, - kTXNOutsideOfFrameErr = -22018 -}; - - - - - -enum { - printerStatusOpCodeNotSupportedErr = -25280 -}; - - - -enum { - errKCNotAvailable = -25291, - errKCReadOnly = -25292, - errKCAuthFailed = -25293, - errKCNoSuchKeychain = -25294, - errKCInvalidKeychain = -25295, - errKCDuplicateKeychain = -25296, - errKCDuplicateCallback = -25297, - errKCInvalidCallback = -25298, - errKCDuplicateItem = -25299, - errKCItemNotFound = -25300, - errKCBufferTooSmall = -25301, - errKCDataTooLarge = -25302, - errKCNoSuchAttr = -25303, - errKCInvalidItemRef = -25304, - errKCInvalidSearchRef = -25305, - errKCNoSuchClass = -25306, - errKCNoDefaultKeychain = -25307, - errKCInteractionNotAllowed = -25308, - errKCReadOnlyAttr = -25309, - errKCWrongKCVersion = -25310, - errKCKeySizeNotAllowed = -25311, - errKCNoStorageModule = -25312, - errKCNoCertificateModule = -25313, - errKCNoPolicyModule = -25314, - errKCInteractionRequired = -25315, - errKCDataNotAvailable = -25316, - errKCDataNotModifiable = -25317, - errKCCreateChainFailed = -25318 -}; - - - -enum { - kUCOutputBufferTooSmall = -25340, - kUCTextBreakLocatorMissingType = -25341 -}; - -enum { - kUCTSNoKeysAddedToObjectErr = -25342, - kUCTSSearchListErr = -25343 -}; - -enum { - kUCTokenizerIterationFinished = -25344, - kUCTokenizerUnknownLang = -25345, - kUCTokenNotFound = -25346 -}; - - -enum { - kMPIterationEndErr = -29275, - kMPPrivilegedErr = -29276, - kMPProcessCreatedErr = -29288, - kMPProcessTerminatedErr = -29289, - kMPTaskCreatedErr = -29290, - kMPTaskBlockedErr = -29291, - kMPTaskStoppedErr = -29292, - kMPBlueBlockingErr = -29293, - kMPDeletedErr = -29295, - kMPTimeoutErr = -29296, - kMPTaskAbortedErr = -29297, - kMPInsufficientResourcesErr = -29298, - kMPInvalidIDErr = -29299 -}; - -enum { - kMPNanokernelNeedsMemoryErr = -29294 -}; - - -enum { - kCollateAttributesNotFoundErr = -29500, - kCollateInvalidOptions = -29501, - kCollateMissingUnicodeTableErr = -29502, - kCollateUnicodeConvertFailedErr = -29503, - kCollatePatternNotFoundErr = -29504, - kCollateInvalidChar = -29505, - kCollateBufferTooSmall = -29506, - kCollateInvalidCollationRef = -29507 -}; - - - -enum { - kFNSInvalidReferenceErr = -29580, - kFNSBadReferenceVersionErr = -29581, - kFNSInvalidProfileErr = -29582, - kFNSBadProfileVersionErr = -29583, - kFNSDuplicateReferenceErr = -29584, - kFNSMismatchErr = -29585, - kFNSInsufficientDataErr = -29586, - kFNSBadFlattenedSizeErr = -29587, - kFNSNameNotFoundErr = -29589 -}; - - - - -enum { - kLocalesBufferTooSmallErr = -30001, - kLocalesTableFormatErr = -30002, - kLocalesDefaultDisplayStatus = -30029 -}; - - - -enum { - kALMInternalErr = -30049, - kALMGroupNotFoundErr = -30048, - kALMNoSuchModuleErr = -30047, - kALMModuleCommunicationErr = -30046, - kALMDuplicateModuleErr = -30045, - kALMInstallationErr = -30044, - kALMDeferSwitchErr = -30043, - kALMRebootFlagsLevelErr = -30042 -}; - -enum { - kALMLocationNotFoundErr = kALMGroupNotFoundErr -}; - - - -enum { - kSSpInternalErr = -30340, - kSSpVersionErr = -30341, - kSSpCantInstallErr = -30342, - kSSpParallelUpVectorErr = -30343, - kSSpScaleToZeroErr = -30344 -}; - - - -enum { - kNSpInitializationFailedErr = -30360, - kNSpAlreadyInitializedErr = -30361, - kNSpTopologyNotSupportedErr = -30362, - kNSpPipeFullErr = -30364, - kNSpHostFailedErr = -30365, - kNSpProtocolNotAvailableErr = -30366, - kNSpInvalidGameRefErr = -30367, - kNSpInvalidParameterErr = -30369, - kNSpOTNotPresentErr = -30370, - kNSpOTVersionTooOldErr = -30371, - kNSpMemAllocationErr = -30373, - kNSpAlreadyAdvertisingErr = -30374, - kNSpNotAdvertisingErr = -30376, - kNSpInvalidAddressErr = -30377, - kNSpFreeQExhaustedErr = -30378, - kNSpRemovePlayerFailedErr = -30379, - kNSpAddressInUseErr = -30380, - kNSpFeatureNotImplementedErr = -30381, - kNSpNameRequiredErr = -30382, - kNSpInvalidPlayerIDErr = -30383, - kNSpInvalidGroupIDErr = -30384, - kNSpNoPlayersErr = -30385, - kNSpNoGroupsErr = -30386, - kNSpNoHostVolunteersErr = -30387, - kNSpCreateGroupFailedErr = -30388, - kNSpAddPlayerFailedErr = -30389, - kNSpInvalidDefinitionErr = -30390, - kNSpInvalidProtocolRefErr = -30391, - kNSpInvalidProtocolListErr = -30392, - kNSpTimeoutErr = -30393, - kNSpGameTerminatedErr = -30394, - kNSpConnectFailedErr = -30395, - kNSpSendFailedErr = -30396, - kNSpMessageTooBigErr = -30397, - kNSpCantBlockErr = -30398, - kNSpJoinFailedErr = -30399 -}; - - - -enum { - kISpInternalErr = -30420, - kISpSystemListErr = -30421, - kISpBufferToSmallErr = -30422, - kISpElementInListErr = -30423, - kISpElementNotInListErr = -30424, - kISpSystemInactiveErr = -30425, - kISpDeviceInactiveErr = -30426, - kISpSystemActiveErr = -30427, - kISpDeviceActiveErr = -30428, - kISpListBusyErr = -30429 -}; - - -enum { - kDSpNotInitializedErr = -30440L, - kDSpSystemSWTooOldErr = -30441L, - kDSpInvalidContextErr = -30442L, - kDSpInvalidAttributesErr = -30443L, - kDSpContextAlreadyReservedErr = -30444L, - kDSpContextNotReservedErr = -30445L, - kDSpContextNotFoundErr = -30446L, - kDSpFrameRateNotReadyErr = -30447L, - kDSpConfirmSwitchWarning = -30448L, - kDSpInternalErr = -30449L, - kDSpStereoContextErr = -30450L -}; - - - - - - - -enum { - kFBCvTwinExceptionErr = -30500, - kFBCnoIndexesFound = -30501, - kFBCallocFailed = -30502, - kFBCbadParam = -30503, - kFBCfileNotIndexed = -30504, - kFBCbadIndexFile = -30505, - kFBCcompactionFailed = -30506, - kFBCvalidationFailed = -30507, - kFBCindexingFailed = -30508, - kFBCcommitFailed = -30509, - kFBCdeletionFailed = -30510, - kFBCmoveFailed = -30511, - kFBCtokenizationFailed = -30512, - kFBCmergingFailed = -30513, - kFBCindexCreationFailed = -30514, - kFBCaccessorStoreFailed = -30515, - kFBCaddDocFailed = -30516, - kFBCflushFailed = -30517, - kFBCindexNotFound = -30518, - kFBCnoSearchSession = -30519, - kFBCindexingCanceled = -30520, - kFBCaccessCanceled = -30521, - kFBCindexFileDestroyed = -30522, - kFBCindexNotAvailable = -30523, - kFBCsearchFailed = -30524, - kFBCsomeFilesNotIndexed = -30525, - kFBCillegalSessionChange = -30526, - - kFBCanalysisNotAvailable = -30527, - kFBCbadIndexFileVersion = -30528, - kFBCsummarizationCanceled = -30529, - kFBCindexDiskIOFailed = -30530, - kFBCbadSearchSession = -30531, - kFBCnoSuchHit = -30532 -}; - - - -enum { - notAQTVRMovieErr = -30540, - constraintReachedErr = -30541, - callNotSupportedByNodeErr = -30542, - selectorNotSupportedByNodeErr = -30543, - invalidNodeIDErr = -30544, - invalidViewStateErr = -30545, - timeNotInViewErr = -30546, - propertyNotSupportedByNodeErr = -30547, - settingNotSupportedByNodeErr = -30548, - limitReachedErr = -30549, - invalidNodeFormatErr = -30550, - invalidHotSpotIDErr = -30551, - noMemoryNodeFailedInitialize = -30552, - streamingNodeNotReadyErr = -30553, - qtvrLibraryLoadErr = -30554, - qtvrUninitialized = -30555 -}; - - - -enum { - themeInvalidBrushErr = -30560, - themeProcessRegisteredErr = -30561, - themeProcessNotRegisteredErr = -30562, - themeBadTextColorErr = -30563, - themeHasNoAccentsErr = -30564, - themeBadCursorIndexErr = -30565, - themeScriptFontNotFoundErr = -30566, - themeMonitorDepthNotSupportedErr = -30567, - themeNoAppropriateBrushErr = -30568 -}; - - - - - - - -enum { - - - - - - - errMessageNotSupported = -30580, - - - - - - - - errDataNotSupported = -30581, - - - - - - - errControlDoesntSupportFocus = -30582, - - - - - - - - errUnknownControl = -30584, - errCouldntSetFocus = -30585, - errNoRootControl = -30586, - - - - - - errRootAlreadyExists = -30587, - - - - - - errInvalidPartCode = -30588, - errControlsAlreadyExist = -30589, - - - - - - errControlIsNotEmbedder = -30590, - - - - - - - errDataSizeMismatch = -30591, - - - - - - - errControlHiddenOrDisabled = -30592, - - - - - - - errCantEmbedIntoSelf = -30594, - - - - - - - errCantEmbedRoot = -30595, - - - - - - errItemNotControl = -30596, - - - - - - - - controlInvalidDataVersionErr = -30597, - - - - - - controlPropertyInvalid = -5603, - - - - - - - controlPropertyNotFoundErr = -5604, - - - - - controlHandleInvalidErr = -30599 -}; - - - - - -enum { - kURLInvalidURLReferenceError = -30770, - kURLProgressAlreadyDisplayedError = -30771, - kURLDestinationExistsError = -30772, - kURLInvalidURLError = -30773, - kURLUnsupportedSchemeError = -30774, - kURLServerBusyError = -30775, - kURLAuthenticationError = -30776, - kURLPropertyNotYetKnownError = -30777, - kURLUnknownPropertyError = -30778, - kURLPropertyBufferTooSmallError = -30779, - kURLUnsettablePropertyError = -30780, - kURLInvalidCallError = -30781, - kURLFileEmptyError = -30783, - kURLExtensionFailureError = -30785, - kURLInvalidConfigurationError = -30786, - kURLAccessNotAvailableError = -30787, - kURL68kNotSupportedError = -30788 -}; -enum { - errCppGeneral = -32000, - errCppbad_alloc = -32001, - errCppbad_cast = -32002, - errCppbad_exception = -32003, - errCppbad_typeid = -32004, - errCpplogic_error = -32005, - errCppdomain_error = -32006, - errCppinvalid_argument = -32007, - errCpplength_error = -32008, - errCppout_of_range = -32009, - errCppruntime_error = -32010, - errCppoverflow_error = -32011, - errCpprange_error = -32012, - errCppunderflow_error = -32013, - errCppios_base_failure = -32014, - errCppLastSystemDefinedError = -32020, - errCppLastUserDefinedError = -32049 -}; - - -enum { - badComponentInstance = (int)0x80008001, - badComponentSelector = (int)0x80008002 -}; - - - -enum { - dsBusError = 1, - dsAddressErr = 2, - dsIllInstErr = 3, - dsZeroDivErr = 4, - dsChkErr = 5, - dsOvflowErr = 6, - dsPrivErr = 7, - dsTraceErr = 8, - dsLineAErr = 9, - dsLineFErr = 10, - dsMiscErr = 11, - dsCoreErr = 12, - dsIrqErr = 13, - dsIOCoreErr = 14, - dsLoadErr = 15, - dsFPErr = 16, - dsNoPackErr = 17, - dsNoPk1 = 18, - dsNoPk2 = 19 -}; - -enum { - dsNoPk3 = 20, - dsNoPk4 = 21, - dsNoPk5 = 22, - dsNoPk6 = 23, - dsNoPk7 = 24, - dsMemFullErr = 25, - dsBadLaunch = 26, - dsFSErr = 27, - dsStknHeap = 28, - negZcbFreeErr = 33, - dsFinderErr = 41, - dsBadSlotInt = 51, - dsBadSANEOpcode = 81, - dsBadPatchHeader = 83, - menuPrgErr = 84, - dsMBarNFnd = 85, - dsHMenuFindErr = 86, - dsWDEFNotFound = 87, - dsCDEFNotFound = 88, - dsMDEFNotFound = 89 -}; - -enum { - dsNoFPU = 90, - dsNoPatch = 98, - dsBadPatch = 99, - dsParityErr = 101, - dsOldSystem = 102, - ds32BitMode = 103, - dsNeedToWriteBootBlocks = 104, - dsNotEnoughRAMToBoot = 105, - dsBufPtrTooLow = 106, - dsVMDeferredFuncTableFull = 112, - dsVMBadBackingStore = 113, - dsCantHoldSystemHeap = 114, - dsSystemRequiresPowerPC = 116, - dsGibblyMovedToDisabledFolder = 117, - dsUnBootableSystem = 118, - dsMustUseFCBAccessors = 119, - dsMacOSROMVersionTooOld = 120, - dsLostConnectionToNetworkDisk = 121, - dsRAMDiskTooBig = 122, - dsWriteToSupervisorStackGuardPage = 128, - dsReinsert = 30, - shutDownAlert = 42, - dsShutDownOrRestart = 20000, - dsSwitchOffOrRestart = 20001, - dsForcedQuit = 20002, - dsRemoveDisk = 20003, - dsDirtyDisk = 20004, - dsShutDownOrResume = 20109, - dsSCSIWarn = 20010, - dsMBSysError = 29200, - dsMBFlpySysError = 29201, - dsMBATASysError = 29202, - dsMBATAPISysError = 29203, - dsMBExternFlpySysError = 29204, - dsPCCardATASysError = 29205 -}; - - - - - - -enum { - dsNoExtsMacsBug = -1, - dsNoExtsDisassembler = -2, - dsMacsBugInstalled = -10, - dsDisassemblerInstalled = -11, - dsExtensionsDisabled = -13, - dsGreeting = 40, - dsSysErr = 32767, - - WDEFNFnd = dsWDEFNotFound -}; - -enum { - CDEFNFnd = dsCDEFNotFound, - dsNotThe1 = 31, - dsBadStartupDisk = 42, - dsSystemFileErr = 43, - dsHD20Installed = -12, - mBarNFnd = -126, - fsDSIntErr = -127, - hMenuFindErr = -127, - userBreak = -490, - strUserBreak = -491, - exUserBreak = -492 -}; - - -enum { - - dsBadLibrary = 1010, - dsMixedModeFailure = 1011 -}; -enum { - kPOSIXErrorBase = 100000, - kPOSIXErrorEPERM = 100001, - kPOSIXErrorENOENT = 100002, - kPOSIXErrorESRCH = 100003, - kPOSIXErrorEINTR = 100004, - kPOSIXErrorEIO = 100005, - kPOSIXErrorENXIO = 100006, - kPOSIXErrorE2BIG = 100007, - kPOSIXErrorENOEXEC = 100008, - kPOSIXErrorEBADF = 100009, - kPOSIXErrorECHILD = 100010, - kPOSIXErrorEDEADLK = 100011, - kPOSIXErrorENOMEM = 100012, - kPOSIXErrorEACCES = 100013, - kPOSIXErrorEFAULT = 100014, - kPOSIXErrorENOTBLK = 100015, - kPOSIXErrorEBUSY = 100016, - kPOSIXErrorEEXIST = 100017, - kPOSIXErrorEXDEV = 100018, - kPOSIXErrorENODEV = 100019, - kPOSIXErrorENOTDIR = 100020, - kPOSIXErrorEISDIR = 100021, - kPOSIXErrorEINVAL = 100022, - kPOSIXErrorENFILE = 100023, - kPOSIXErrorEMFILE = 100024, - kPOSIXErrorENOTTY = 100025, - kPOSIXErrorETXTBSY = 100026, - kPOSIXErrorEFBIG = 100027, - kPOSIXErrorENOSPC = 100028, - kPOSIXErrorESPIPE = 100029, - kPOSIXErrorEROFS = 100030, - kPOSIXErrorEMLINK = 100031, - kPOSIXErrorEPIPE = 100032, - kPOSIXErrorEDOM = 100033, - kPOSIXErrorERANGE = 100034, - kPOSIXErrorEAGAIN = 100035, - kPOSIXErrorEINPROGRESS = 100036, - kPOSIXErrorEALREADY = 100037, - kPOSIXErrorENOTSOCK = 100038, - kPOSIXErrorEDESTADDRREQ = 100039, - kPOSIXErrorEMSGSIZE = 100040, - kPOSIXErrorEPROTOTYPE = 100041, - kPOSIXErrorENOPROTOOPT = 100042, - kPOSIXErrorEPROTONOSUPPORT = 100043, - kPOSIXErrorESOCKTNOSUPPORT = 100044, - kPOSIXErrorENOTSUP = 100045, - kPOSIXErrorEPFNOSUPPORT = 100046, - kPOSIXErrorEAFNOSUPPORT = 100047, - kPOSIXErrorEADDRINUSE = 100048, - kPOSIXErrorEADDRNOTAVAIL = 100049, - kPOSIXErrorENETDOWN = 100050, - kPOSIXErrorENETUNREACH = 100051, - kPOSIXErrorENETRESET = 100052, - kPOSIXErrorECONNABORTED = 100053, - kPOSIXErrorECONNRESET = 100054, - kPOSIXErrorENOBUFS = 100055, - kPOSIXErrorEISCONN = 100056, - kPOSIXErrorENOTCONN = 100057, - kPOSIXErrorESHUTDOWN = 100058, - kPOSIXErrorETOOMANYREFS = 100059, - kPOSIXErrorETIMEDOUT = 100060, - kPOSIXErrorECONNREFUSED = 100061, - kPOSIXErrorELOOP = 100062, - kPOSIXErrorENAMETOOLONG = 100063, - kPOSIXErrorEHOSTDOWN = 100064, - kPOSIXErrorEHOSTUNREACH = 100065, - kPOSIXErrorENOTEMPTY = 100066, - kPOSIXErrorEPROCLIM = 100067, - kPOSIXErrorEUSERS = 100068, - kPOSIXErrorEDQUOT = 100069, - kPOSIXErrorESTALE = 100070, - kPOSIXErrorEREMOTE = 100071, - kPOSIXErrorEBADRPC = 100072, - kPOSIXErrorERPCMISMATCH = 100073, - kPOSIXErrorEPROGUNAVAIL = 100074, - kPOSIXErrorEPROGMISMATCH = 100075, - kPOSIXErrorEPROCUNAVAIL = 100076, - kPOSIXErrorENOLCK = 100077, - kPOSIXErrorENOSYS = 100078, - kPOSIXErrorEFTYPE = 100079, - kPOSIXErrorEAUTH = 100080, - kPOSIXErrorENEEDAUTH = 100081, - kPOSIXErrorEPWROFF = 100082, - kPOSIXErrorEDEVERR = 100083, - kPOSIXErrorEOVERFLOW = 100084, - kPOSIXErrorEBADEXEC = 100085, - kPOSIXErrorEBADARCH = 100086, - kPOSIXErrorESHLIBVERS = 100087, - kPOSIXErrorEBADMACHO = 100088, - kPOSIXErrorECANCELED = 100089, - kPOSIXErrorEIDRM = 100090, - kPOSIXErrorENOMSG = 100091, - kPOSIXErrorEILSEQ = 100092, - kPOSIXErrorENOATTR = 100093, - kPOSIXErrorEBADMSG = 100094, - kPOSIXErrorEMULTIHOP = 100095, - kPOSIXErrorENODATA = 100096, - kPOSIXErrorENOLINK = 100097, - kPOSIXErrorENOSR = 100098, - kPOSIXErrorENOSTR = 100099, - kPOSIXErrorEPROTO = 100100, - kPOSIXErrorETIME = 100101, - kPOSIXErrorEOPNOTSUPP = 100102 -}; -extern void -SysError(short errorCode) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - - - -} -extern "C" { - - -#pragma pack(push, 2) - - -enum { - kUTCDefaultOptions = 0 -}; - - -struct UTCDateTime { - UInt16 highSeconds; - UInt32 lowSeconds; - UInt16 fraction; -}; -typedef struct UTCDateTime UTCDateTime; -typedef UTCDateTime * UTCDateTimePtr; -typedef UTCDateTimePtr * UTCDateTimeHandle; -struct LocalDateTime { - UInt16 highSeconds; - UInt32 lowSeconds; - UInt16 fraction; -}; -typedef struct LocalDateTime LocalDateTime; -typedef LocalDateTime * LocalDateTimePtr; -typedef LocalDateTimePtr * LocalDateTimeHandle; -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -enum { - - - - - kTextFlushDefault = 0, - - - - - kTextCenter = 1, - - - - - kTextFlushRight = -1, - - - - - kTextFlushLeft = -2 -}; - - - -typedef UInt32 TextEncodingBase; -enum { - - kTextEncodingMacRoman = 0, - kTextEncodingMacJapanese = 1, - kTextEncodingMacChineseTrad = 2, - kTextEncodingMacKorean = 3, - kTextEncodingMacArabic = 4, - kTextEncodingMacHebrew = 5, - kTextEncodingMacGreek = 6, - kTextEncodingMacCyrillic = 7, - kTextEncodingMacDevanagari = 9, - kTextEncodingMacGurmukhi = 10, - kTextEncodingMacGujarati = 11, - kTextEncodingMacOriya = 12, - kTextEncodingMacBengali = 13, - kTextEncodingMacTamil = 14, - kTextEncodingMacTelugu = 15, - kTextEncodingMacKannada = 16, - kTextEncodingMacMalayalam = 17, - kTextEncodingMacSinhalese = 18, - kTextEncodingMacBurmese = 19, - kTextEncodingMacKhmer = 20, - kTextEncodingMacThai = 21, - kTextEncodingMacLaotian = 22, - kTextEncodingMacGeorgian = 23, - kTextEncodingMacArmenian = 24, - kTextEncodingMacChineseSimp = 25, - kTextEncodingMacTibetan = 26, - kTextEncodingMacMongolian = 27, - kTextEncodingMacEthiopic = 28, - kTextEncodingMacCentralEurRoman = 29, - kTextEncodingMacVietnamese = 30, - kTextEncodingMacExtArabic = 31, - kTextEncodingMacSymbol = 33, - kTextEncodingMacDingbats = 34, - kTextEncodingMacTurkish = 35, - kTextEncodingMacCroatian = 36, - kTextEncodingMacIcelandic = 37, - kTextEncodingMacRomanian = 38, - kTextEncodingMacCeltic = 39, - kTextEncodingMacGaelic = 40, - kTextEncodingMacKeyboardGlyphs = 41 -}; - - -enum { - kTextEncodingMacTradChinese = kTextEncodingMacChineseTrad, - kTextEncodingMacRSymbol = 8, - kTextEncodingMacSimpChinese = kTextEncodingMacChineseSimp, - kTextEncodingMacGeez = kTextEncodingMacEthiopic, - kTextEncodingMacEastEurRoman = kTextEncodingMacCentralEurRoman, - kTextEncodingMacUninterp = 32 -}; -enum { - kTextEncodingMacUnicode = 0x7E -}; - - -enum { - - kTextEncodingMacFarsi = 0x8C, - - kTextEncodingMacUkrainian = 0x98, - - kTextEncodingMacInuit = 0xEC, - kTextEncodingMacVT100 = 0xFC -}; - - -enum { - kTextEncodingMacHFS = 0xFF -}; - - -enum { - kTextEncodingUnicodeDefault = 0x0100, - kTextEncodingUnicodeV1_1 = 0x0101, - kTextEncodingISO10646_1993 = 0x0101, - kTextEncodingUnicodeV2_0 = 0x0103, - kTextEncodingUnicodeV2_1 = 0x0103, - kTextEncodingUnicodeV3_0 = 0x0104, - kTextEncodingUnicodeV3_1 = 0x0105, - kTextEncodingUnicodeV3_2 = 0x0106, - kTextEncodingUnicodeV4_0 = 0x0108, - kTextEncodingUnicodeV5_0 = 0x010A, - kTextEncodingUnicodeV5_1 = 0x010B, - kTextEncodingUnicodeV6_0 = 0x010D, - kTextEncodingUnicodeV6_1 = 0x010E, - kTextEncodingUnicodeV6_3 = 0x0110, - kTextEncodingUnicodeV7_0 = 0x0111 -}; - - -enum { - kTextEncodingISOLatin1 = 0x0201, - kTextEncodingISOLatin2 = 0x0202, - kTextEncodingISOLatin3 = 0x0203, - kTextEncodingISOLatin4 = 0x0204, - kTextEncodingISOLatinCyrillic = 0x0205, - kTextEncodingISOLatinArabic = 0x0206, - kTextEncodingISOLatinGreek = 0x0207, - kTextEncodingISOLatinHebrew = 0x0208, - kTextEncodingISOLatin5 = 0x0209, - kTextEncodingISOLatin6 = 0x020A, - kTextEncodingISOLatin7 = 0x020D, - kTextEncodingISOLatin8 = 0x020E, - kTextEncodingISOLatin9 = 0x020F, - kTextEncodingISOLatin10 = 0x0210 -}; - - -enum { - kTextEncodingDOSLatinUS = 0x0400, - kTextEncodingDOSGreek = 0x0405, - kTextEncodingDOSBalticRim = 0x0406, - kTextEncodingDOSLatin1 = 0x0410, - kTextEncodingDOSGreek1 = 0x0411, - kTextEncodingDOSLatin2 = 0x0412, - kTextEncodingDOSCyrillic = 0x0413, - kTextEncodingDOSTurkish = 0x0414, - kTextEncodingDOSPortuguese = 0x0415, - kTextEncodingDOSIcelandic = 0x0416, - kTextEncodingDOSHebrew = 0x0417, - kTextEncodingDOSCanadianFrench = 0x0418, - kTextEncodingDOSArabic = 0x0419, - kTextEncodingDOSNordic = 0x041A, - kTextEncodingDOSRussian = 0x041B, - kTextEncodingDOSGreek2 = 0x041C, - kTextEncodingDOSThai = 0x041D, - kTextEncodingDOSJapanese = 0x0420, - kTextEncodingDOSChineseSimplif = 0x0421, - kTextEncodingDOSKorean = 0x0422, - kTextEncodingDOSChineseTrad = 0x0423, - kTextEncodingWindowsLatin1 = 0x0500, - kTextEncodingWindowsANSI = 0x0500, - kTextEncodingWindowsLatin2 = 0x0501, - kTextEncodingWindowsCyrillic = 0x0502, - kTextEncodingWindowsGreek = 0x0503, - kTextEncodingWindowsLatin5 = 0x0504, - kTextEncodingWindowsHebrew = 0x0505, - kTextEncodingWindowsArabic = 0x0506, - kTextEncodingWindowsBalticRim = 0x0507, - kTextEncodingWindowsVietnamese = 0x0508, - kTextEncodingWindowsKoreanJohab = 0x0510 -}; - - -enum { - kTextEncodingUS_ASCII = 0x0600, - kTextEncodingANSEL = 0x0601, - kTextEncodingJIS_X0201_76 = 0x0620, - kTextEncodingJIS_X0208_83 = 0x0621, - kTextEncodingJIS_X0208_90 = 0x0622, - kTextEncodingJIS_X0212_90 = 0x0623, - kTextEncodingJIS_C6226_78 = 0x0624, - kTextEncodingShiftJIS_X0213 = 0x0628, - kTextEncodingJIS_X0213_MenKuTen = 0x0629, - kTextEncodingGB_2312_80 = 0x0630, - kTextEncodingGBK_95 = 0x0631, - kTextEncodingGB_18030_2000 = 0x0632, - kTextEncodingGB_18030_2005 = 0x0632, - kTextEncodingKSC_5601_87 = 0x0640, - kTextEncodingKSC_5601_92_Johab = 0x0641, - kTextEncodingCNS_11643_92_P1 = 0x0651, - kTextEncodingCNS_11643_92_P2 = 0x0652, - kTextEncodingCNS_11643_92_P3 = 0x0653 -}; - - -enum { - kTextEncodingISO_2022_JP = 0x0820, - kTextEncodingISO_2022_JP_2 = 0x0821, - kTextEncodingISO_2022_JP_1 = 0x0822, - kTextEncodingISO_2022_JP_3 = 0x0823, - kTextEncodingISO_2022_CN = 0x0830, - kTextEncodingISO_2022_CN_EXT = 0x0831, - kTextEncodingISO_2022_KR = 0x0840 -}; - - -enum { - kTextEncodingEUC_JP = 0x0920, - kTextEncodingEUC_CN = 0x0930, - kTextEncodingEUC_TW = 0x0931, - kTextEncodingEUC_KR = 0x0940 -}; - - -enum { - kTextEncodingShiftJIS = 0x0A01, - kTextEncodingKOI8_R = 0x0A02, - kTextEncodingBig5 = 0x0A03, - kTextEncodingMacRomanLatin1 = 0x0A04, - kTextEncodingHZ_GB_2312 = 0x0A05, - kTextEncodingBig5_HKSCS_1999 = 0x0A06, - kTextEncodingVISCII = 0x0A07, - kTextEncodingKOI8_U = 0x0A08, - kTextEncodingBig5_E = 0x0A09 -}; - - -enum { - kTextEncodingNextStepLatin = 0x0B01, - kTextEncodingNextStepJapanese = 0x0B02 -}; - - -enum { - kTextEncodingEBCDIC_LatinCore = 0x0C01, - kTextEncodingEBCDIC_CP037 = 0x0C02 -}; - - -enum { - kTextEncodingMultiRun = 0x0FFF, - kTextEncodingUnknown = 0xFFFF -}; - - -enum { - kTextEncodingEBCDIC_US = 0x0C01 -}; - - - -typedef UInt32 TextEncodingVariant; - -enum { - kTextEncodingDefaultVariant = 0 -}; - - -enum { - kMacRomanDefaultVariant = 0, - kMacRomanCurrencySignVariant = 1, - kMacRomanEuroSignVariant = 2 -}; - - -enum { - kMacCyrillicDefaultVariant = 0, - kMacCyrillicCurrSignStdVariant = 1, - kMacCyrillicCurrSignUkrVariant = 2, - kMacCyrillicEuroSignVariant = 3 -}; - - -enum { - kMacIcelandicStdDefaultVariant = 0, - kMacIcelandicTTDefaultVariant = 1, - - kMacIcelandicStdCurrSignVariant = 2, - kMacIcelandicTTCurrSignVariant = 3, - - kMacIcelandicStdEuroSignVariant = 4, - kMacIcelandicTTEuroSignVariant = 5 -}; - - -enum { - kMacCroatianDefaultVariant = 0, - kMacCroatianCurrencySignVariant = 1, - kMacCroatianEuroSignVariant = 2 -}; - - - -enum { - kMacRomanianDefaultVariant = 0, - kMacRomanianCurrencySignVariant = 1, - kMacRomanianEuroSignVariant = 2 -}; - - - -enum { - kMacJapaneseStandardVariant = 0, - kMacJapaneseStdNoVerticalsVariant = 1, - kMacJapaneseBasicVariant = 2, - kMacJapanesePostScriptScrnVariant = 3, - kMacJapanesePostScriptPrintVariant = 4, - kMacJapaneseVertAtKuPlusTenVariant = 5 -}; - - -enum { - kMacArabicStandardVariant = 0, - kMacArabicTrueTypeVariant = 1, - kMacArabicThuluthVariant = 2, - kMacArabicAlBayanVariant = 3 -}; - - -enum { - kMacFarsiStandardVariant = 0, - kMacFarsiTrueTypeVariant = 1 -}; - - -enum { - kMacHebrewStandardVariant = 0, - kMacHebrewFigureSpaceVariant = 1 -}; - - -enum { - kMacGreekDefaultVariant = 0, - kMacGreekNoEuroSignVariant = 1, - kMacGreekEuroSignVariant = 2 -}; - - -enum { - kMacVT100DefaultVariant = 0, - kMacVT100CurrencySignVariant = 1, - kMacVT100EuroSignVariant = 2 -}; - - -enum { - kUnicodeNoSubset = 0, - kUnicodeNormalizationFormD = 5, - kUnicodeNormalizationFormC = 3, - kUnicodeHFSPlusDecompVariant = 8, - kUnicodeHFSPlusCompVariant = 9 -}; - - -enum { - kISOLatin1StandardVariant = 0, - kISOLatin1MusicCDVariant = 1 -}; -enum { - kISOLatinArabicImplicitOrderVariant = 0, - kISOLatinArabicVisualOrderVariant = 1, - kISOLatinArabicExplicitOrderVariant = 2 -}; - -enum { - kISOLatinHebrewImplicitOrderVariant = 0, - kISOLatinHebrewVisualOrderVariant = 1, - kISOLatinHebrewExplicitOrderVariant = 2 -}; - - -enum { - kWindowsLatin1StandardVariant = 0, - kWindowsLatin1PalmVariant = 1 -}; - - -enum { - kDOSJapaneseStandardVariant = 0, - kDOSJapanesePalmVariant = 1 -}; - - - - - - -enum { - kEUC_CN_BasicVariant = 0, - kEUC_CN_DOSVariant = 1 -}; - - - - - - -enum { - kEUC_KR_BasicVariant = 0, - kEUC_KR_DOSVariant = 1 -}; - - - - - - -enum { - kShiftJIS_BasicVariant = 0, - kShiftJIS_DOSVariant = 1, - kShiftJIS_MusicCDVariant = 2 -}; - - - - - - -enum { - kBig5_BasicVariant = 0, - kBig5_StandardVariant = 1, - kBig5_ETenVariant = 2, - kBig5_DOSVariant = 3 -}; - - -enum { - kMacRomanLatin1DefaultVariant = 0, - kMacRomanLatin1StandardVariant = 2, - kMacRomanLatin1TurkishVariant = 6, - kMacRomanLatin1CroatianVariant = 8, - kMacRomanLatin1IcelandicVariant = 11, - kMacRomanLatin1RomanianVariant = 14 -}; - - -enum { - kUnicodeNoCompatibilityVariant = 1, - kUnicodeNoCorporateVariant = 4 -}; - - -enum { - kMacRomanStandardVariant = 0, - kMacIcelandicStandardVariant = 0, - kMacIcelandicTrueTypeVariant = 1, - kJapaneseStandardVariant = 0, - kJapaneseStdNoVerticalsVariant = 1, - kJapaneseBasicVariant = 2, - kJapanesePostScriptScrnVariant = 3, - kJapanesePostScriptPrintVariant = 4, - kJapaneseVertAtKuPlusTenVariant = 5, - kTextEncodingShiftJIS_X0213_00 = 0x0628, - - - kHebrewStandardVariant = 0, - kHebrewFigureSpaceVariant = 1, - - - - - - - kUnicodeCanonicalDecompVariant = 2, - kUnicodeMaxDecomposedVariant = 2, - kUnicodeCanonicalCompVariant = 3, - kUnicodeNoComposedVariant = 3 -}; - - -typedef UInt32 TextEncodingFormat; -enum { - - kTextEncodingDefaultFormat = 0, - kUnicodeUTF16Format = 0, - kUnicodeUTF7Format = 1, - kUnicodeUTF8Format = 2, - kUnicodeUTF32Format = 3, - kUnicodeUTF16BEFormat = 4, - kUnicodeUTF16LEFormat = 5, - kUnicodeUTF32BEFormat = 6, - kUnicodeUTF32LEFormat = 7, - kUnicodeSCSUFormat = 8, - kUnicode16BitFormat = 0, - kUnicode32BitFormat = 3 -}; - - -typedef UInt32 TextEncoding; - -typedef UInt32 TextEncodingNameSelector; -enum { - kTextEncodingFullName = 0, - kTextEncodingBaseName = 1, - kTextEncodingVariantName = 2, - kTextEncodingFormatName = 3 -}; - - -struct TextEncodingRun { - ByteOffset offset; - TextEncoding textEncoding; -}; -typedef struct TextEncodingRun TextEncodingRun; -typedef TextEncodingRun * TextEncodingRunPtr; -typedef const TextEncodingRun * ConstTextEncodingRunPtr; -struct ScriptCodeRun { - ByteOffset offset; - ScriptCode script; -}; -typedef struct ScriptCodeRun ScriptCodeRun; -typedef ScriptCodeRun * ScriptCodeRunPtr; -typedef const ScriptCodeRun * ConstScriptCodeRunPtr; -typedef UInt8 * TextPtr; -typedef const UInt8 * ConstTextPtr; - -typedef UniChar * UniCharArrayPtr; -typedef const UniChar * ConstUniCharArrayPtr; - - - - -typedef UniCharArrayPtr * UniCharArrayHandle; - - - - -typedef unsigned long UniCharArrayOffset; - -enum { - kTextScriptDontCare = -128, - kTextLanguageDontCare = -128, - kTextRegionDontCare = -128 -}; - - - -struct TECInfo { - UInt16 format; - UInt16 tecVersion; - UInt32 tecTextConverterFeatures; - UInt32 tecUnicodeConverterFeatures; - UInt32 tecTextCommonFeatures; - Str31 tecTextEncodingsFolderName; - Str31 tecExtensionFileName; - UInt16 tecLowestTEFileVersion; - UInt16 tecHighestTEFileVersion; -}; -typedef struct TECInfo TECInfo; -typedef TECInfo * TECInfoPtr; -typedef TECInfoPtr * TECInfoHandle; - -enum { - kTECInfoCurrentFormat = 2 -}; -enum { - kTECKeepInfoFixBit = 0, - kTECFallbackTextLengthFixBit = 1, - kTECTextRunBitClearFixBit = 2, - kTECTextToUnicodeScanFixBit = 3, - kTECAddForceASCIIChangesBit = 4, - kTECPreferredEncodingFixBit = 5, - kTECAddTextRunHeuristicsBit = 6, - kTECAddFallbackInterruptBit = 7 -}; - -enum { - kTECKeepInfoFixMask = 1L << kTECKeepInfoFixBit, - kTECFallbackTextLengthFixMask = 1L << kTECFallbackTextLengthFixBit, - kTECTextRunBitClearFixMask = 1L << kTECTextRunBitClearFixBit, - kTECTextToUnicodeScanFixMask = 1L << kTECTextToUnicodeScanFixBit, - kTECAddForceASCIIChangesMask = 1L << kTECAddForceASCIIChangesBit, - kTECPreferredEncodingFixMask = 1L << kTECPreferredEncodingFixBit, - kTECAddTextRunHeuristicsMask = 1L << kTECAddTextRunHeuristicsBit, - kTECAddFallbackInterruptMask = 1L << kTECAddFallbackInterruptBit -}; - - - - - - - -enum { - kUnicodeByteOrderMark = 0xFEFF, - kUnicodeObjectReplacement = 0xFFFC, - kUnicodeReplacementChar = 0xFFFD, - kUnicodeSwappedByteOrderMark = 0xFFFE, - kUnicodeNotAChar = 0xFFFF -}; -typedef SInt32 UCCharPropertyType; -enum { - kUCCharPropTypeGenlCategory = 1, - kUCCharPropTypeCombiningClass = 2, - kUCCharPropTypeBidiCategory = 3, - kUCCharPropTypeDecimalDigitValue = 4 -}; - -typedef UInt32 UCCharPropertyValue; - -enum { - - kUCGenlCatOtherNotAssigned = 0, - kUCGenlCatOtherControl = 1, - kUCGenlCatOtherFormat = 2, - kUCGenlCatOtherSurrogate = 3, - kUCGenlCatOtherPrivateUse = 4, - kUCGenlCatMarkNonSpacing = 5, - kUCGenlCatMarkSpacingCombining = 6, - kUCGenlCatMarkEnclosing = 7, - kUCGenlCatNumberDecimalDigit = 8, - kUCGenlCatNumberLetter = 9, - kUCGenlCatNumberOther = 10, - kUCGenlCatSeparatorSpace = 11, - kUCGenlCatSeparatorLine = 12, - kUCGenlCatSeparatorParagraph = 13, - kUCGenlCatLetterUppercase = 14, - kUCGenlCatLetterLowercase = 15, - kUCGenlCatLetterTitlecase = 16, - - kUCGenlCatLetterModifier = 17, - kUCGenlCatLetterOther = 18, - kUCGenlCatPunctConnector = 20, - kUCGenlCatPunctDash = 21, - kUCGenlCatPunctOpen = 22, - kUCGenlCatPunctClose = 23, - kUCGenlCatPunctInitialQuote = 24, - kUCGenlCatPunctFinalQuote = 25, - kUCGenlCatPunctOther = 26, - kUCGenlCatSymbolMath = 28, - kUCGenlCatSymbolCurrency = 29, - kUCGenlCatSymbolModifier = 30, - kUCGenlCatSymbolOther = 31 -}; - - -enum { - kUCBidiCatNotApplicable = 0, - - kUCBidiCatLeftRight = 1, - kUCBidiCatRightLeft = 2, - - kUCBidiCatEuroNumber = 3, - kUCBidiCatEuroNumberSeparator = 4, - kUCBidiCatEuroNumberTerminator = 5, - kUCBidiCatArabicNumber = 6, - kUCBidiCatCommonNumberSeparator = 7, - - kUCBidiCatBlockSeparator = 8, - kUCBidiCatSegmentSeparator = 9, - - kUCBidiCatWhitespace = 10, - kUCBidiCatOtherNeutral = 11, - - kUCBidiCatRightLeftArabic = 12, - kUCBidiCatLeftRightEmbedding = 13, - kUCBidiCatRightLeftEmbedding = 14, - kUCBidiCatLeftRightOverride = 15, - kUCBidiCatRightLeftOverride = 16, - kUCBidiCatPopDirectionalFormat = 17, - kUCBidiCatNonSpacingMark = 18, - kUCBidiCatBoundaryNeutral = 19, - - kUCBidiCatLeftRightIsolate = 20, - kUCBidiCatRightLeftIsolate = 21, - kUCBidiCatFirstStrongIsolate = 22, - kUCBidiCatPopDirectionalIsolate = 23 -}; -extern TextEncoding -CreateTextEncoding( - TextEncodingBase encodingBase, - TextEncodingVariant encodingVariant, - TextEncodingFormat encodingFormat) __attribute__((availability(macosx,introduced=10.0))); -extern TextEncodingBase -GetTextEncodingBase(TextEncoding encoding) __attribute__((availability(macosx,introduced=10.0))); -extern TextEncodingVariant -GetTextEncodingVariant(TextEncoding encoding) __attribute__((availability(macosx,introduced=10.0))); -extern TextEncodingFormat -GetTextEncodingFormat(TextEncoding encoding) __attribute__((availability(macosx,introduced=10.0))); -extern TextEncoding -ResolveDefaultTextEncoding(TextEncoding encoding) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -GetTextEncodingName( - TextEncoding iEncoding, - TextEncodingNameSelector iNamePartSelector, - RegionCode iPreferredRegion, - TextEncoding iPreferredEncoding, - ByteCount iOutputBufLen, - ByteCount * oNameLength, - RegionCode * oActualRegion, - TextEncoding * oActualEncoding, - TextPtr oEncodingName) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetInfo(TECInfoHandle * tecInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UpgradeScriptInfoToTextEncoding( - ScriptCode iTextScriptID, - LangCode iTextLanguageID, - RegionCode iRegionID, - ConstStr255Param iTextFontname, - TextEncoding * oEncoding) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -RevertTextEncodingToScriptInfo( - TextEncoding iEncoding, - ScriptCode * oTextScriptID, - LangCode * oTextLanguageID, - Str255 oTextFontname) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -GetTextEncodingFromScriptInfo( - ScriptCode iTextScriptID, - LangCode iTextLanguageID, - RegionCode iTextRegionID, - TextEncoding * oEncoding) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -GetScriptInfoFromTextEncoding( - TextEncoding iEncoding, - ScriptCode * oTextScriptID, - LangCode * oTextLanguageID) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -NearestMacTextEncodings( - TextEncoding generalEncoding, - TextEncoding * bestMacEncoding, - TextEncoding * alternateMacEncoding) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UCGetCharProperty( - const UniChar * charPtr, - UniCharCount textLength, - UCCharPropertyType propType, - UCCharPropertyValue * propValue) __attribute__((availability(macosx,introduced=10.0))); -enum { - kUCHighSurrogateRangeStart = 0xD800, - kUCHighSurrogateRangeEnd = 0xDBFF, - kUCLowSurrogateRangeStart = 0xDC00, - kUCLowSurrogateRangeEnd = 0xDFFF -}; -static __inline__ Boolean UCIsSurrogateHighCharacter( UniChar character ) { - - return ( ( character & 0xFC00 ) == kUCHighSurrogateRangeStart ); -} - - - - - - - -static __inline__ Boolean UCIsSurrogateLowCharacter( UniChar character ) { - - return ( ( character & 0xFC00 ) == kUCLowSurrogateRangeStart ); -} -static __inline__ UnicodeScalarValue UCGetUnicodeScalarValueForSurrogatePair( UniChar surrogateHigh, UniChar surrogateLow ) { - return ( (UnicodeScalarValue)( surrogateHigh - kUCHighSurrogateRangeStart ) << 10 ) + ( surrogateLow - kUCLowSurrogateRangeStart ) + 0x0010000; -} - - - -#pragma pack(pop) - - -} - - - -#pragma pack(push, 2) -enum { - kRoutineDescriptorVersion = 7 -}; - - -enum { - _MixedModeMagic = 0xAAFE -}; - - -enum { - kCurrentMixedModeStateRecord = 1 -}; - - -typedef unsigned short CallingConventionType; -enum { - kPascalStackBased = 0, - kCStackBased = 1, - kRegisterBased = 2, - kD0DispatchedPascalStackBased = 8, - kD1DispatchedPascalStackBased = 12, - kD0DispatchedCStackBased = 9, - kStackDispatchedPascalStackBased = 14, - kThinkCStackBased = 5 -}; - - -typedef SInt8 ISAType; -enum { - kM68kISA = 0, - kPowerPCISA = 1 -}; - -enum { - kX86ISA = 2 -}; - - -typedef SInt8 RTAType; -enum { - kOld68kRTA = 0 << 4, - kPowerPCRTA = 0 << 4, - kCFM68kRTA = 1 << 4 -}; - -enum { - kX86RTA = 2 << 4 -}; -enum { - kRegisterD0 = 0, - kRegisterD1 = 1, - kRegisterD2 = 2, - kRegisterD3 = 3, - kRegisterD4 = 8, - kRegisterD5 = 9, - kRegisterD6 = 10, - kRegisterD7 = 11, - kRegisterA0 = 4, - kRegisterA1 = 5, - kRegisterA2 = 6, - kRegisterA3 = 7, - kRegisterA4 = 12, - kRegisterA5 = 13, - kRegisterA6 = 14, - kCCRegisterCBit = 16, - kCCRegisterVBit = 17, - kCCRegisterZBit = 18, - kCCRegisterNBit = 19, - kCCRegisterXBit = 20 -}; - -typedef unsigned short registerSelectorType; - -enum { - kNoByteCode = 0, - kOneByteCode = 1, - kTwoByteCode = 2, - kFourByteCode = 3 -}; - - -typedef unsigned long ProcInfoType; - -typedef unsigned short RoutineFlagsType; -enum { - kProcDescriptorIsAbsolute = 0x00, - kProcDescriptorIsRelative = 0x01 -}; - -enum { - kFragmentIsPrepared = 0x00, - kFragmentNeedsPreparing = 0x02 -}; - -enum { - kUseCurrentISA = 0x00, - kUseNativeISA = 0x04 -}; - -enum { - kPassSelector = 0x00, - kDontPassSelector = 0x08 -}; - -enum { - kRoutineIsNotDispatchedDefaultRoutine = 0x00, - kRoutineIsDispatchedDefaultRoutine = 0x10 -}; - -enum { - kProcDescriptorIsProcPtr = 0x00, - kProcDescriptorIsIndex = 0x20 -}; - -struct RoutineRecord { - ProcInfoType procInfo; - SInt8 reserved1; - ISAType ISA; - RoutineFlagsType routineFlags; - ProcPtr procDescriptor; - UInt32 reserved2; - UInt32 selector; -}; -typedef struct RoutineRecord RoutineRecord; -typedef RoutineRecord * RoutineRecordPtr; -typedef RoutineRecordPtr * RoutineRecordHandle; - - -typedef UInt8 RDFlagsType; -enum { - kSelectorsAreNotIndexable = 0x00, - kSelectorsAreIndexable = 0x01 -}; - - -struct RoutineDescriptor { - UInt16 goMixedModeTrap; - SInt8 version; - RDFlagsType routineDescriptorFlags; - UInt32 reserved1; - UInt8 reserved2; - UInt8 selectorInfo; - UInt16 routineCount; - RoutineRecord routineRecords[1]; -}; -typedef struct RoutineDescriptor RoutineDescriptor; -typedef RoutineDescriptor * RoutineDescriptorPtr; -typedef RoutineDescriptorPtr * RoutineDescriptorHandle; - -struct MixedModeStateRecord { - UInt32 state1; - UInt32 state2; - UInt32 state3; - UInt32 state4; -}; -typedef struct MixedModeStateRecord MixedModeStateRecord; -enum { - - kCallingConventionWidth = 4, - kCallingConventionPhase = 0, - kCallingConventionMask = 0x0F, - kResultSizeWidth = 2, - kResultSizePhase = kCallingConventionWidth, - kResultSizeMask = 0x30, - kStackParameterWidth = 2, - kStackParameterPhase = (kCallingConventionWidth + kResultSizeWidth), - kStackParameterMask = (int)0xFFFFFFC0, - kRegisterResultLocationWidth = 5, - kRegisterResultLocationPhase = (kCallingConventionWidth + kResultSizeWidth), - kRegisterParameterWidth = 5, - kRegisterParameterPhase = (kCallingConventionWidth + kResultSizeWidth + kRegisterResultLocationWidth), - kRegisterParameterMask = 0x7FFFF800, - kRegisterParameterSizePhase = 0, - kRegisterParameterSizeWidth = 2, - kRegisterParameterWhichPhase = kRegisterParameterSizeWidth, - kRegisterParameterWhichWidth = 3, - kDispatchedSelectorSizeWidth = 2, - kDispatchedSelectorSizePhase = (kCallingConventionWidth + kResultSizeWidth), - kDispatchedParameterPhase = (kCallingConventionWidth + kResultSizeWidth + kDispatchedSelectorSizeWidth), - kSpecialCaseSelectorWidth = 6, - kSpecialCaseSelectorPhase = kCallingConventionWidth, - kSpecialCaseSelectorMask = 0x03F0 -}; - -enum { - kSpecialCase = 0x000F -}; - -enum { - - kSpecialCaseHighHook = 0, - kSpecialCaseCaretHook = 0, - kSpecialCaseEOLHook = 1, - kSpecialCaseWidthHook = 2, - kSpecialCaseTextWidthHook = 2, - kSpecialCaseNWidthHook = 3, - kSpecialCaseDrawHook = 4, - kSpecialCaseHitTestHook = 5, - kSpecialCaseTEFindWord = 6, - kSpecialCaseProtocolHandler = 7, - kSpecialCaseSocketListener = 8, - kSpecialCaseTERecalc = 9, - kSpecialCaseTEDoText = 10, - kSpecialCaseGNEFilterProc = 11, - kSpecialCaseMBarHook = 12 -}; -#pragma pack(pop) -extern "C" { - - - - - - -enum { - kCollectionDontWantTag = 0, - kCollectionDontWantId = 0, - kCollectionDontWantSize = 0, - kCollectionDontWantAttributes = 0, - kCollectionDontWantIndex = 0, - kCollectionDontWantData = 0 -}; - - - -enum { - kCollectionNoAttributes = 0x00000000, - kCollectionAllAttributes = (int)0xFFFFFFFF, - kCollectionUserAttributes = 0x0000FFFF, - kCollectionDefaultAttributes = 0x40000000 -}; - - - - - - - -enum { - kCollectionUser0Bit = 0, - kCollectionUser1Bit = 1, - kCollectionUser2Bit = 2, - kCollectionUser3Bit = 3, - kCollectionUser4Bit = 4, - kCollectionUser5Bit = 5, - kCollectionUser6Bit = 6, - kCollectionUser7Bit = 7, - kCollectionUser8Bit = 8, - kCollectionUser9Bit = 9, - kCollectionUser10Bit = 10, - kCollectionUser11Bit = 11, - kCollectionUser12Bit = 12, - kCollectionUser13Bit = 13, - kCollectionUser14Bit = 14, - kCollectionUser15Bit = 15, - kCollectionReserved0Bit = 16, - kCollectionReserved1Bit = 17, - kCollectionReserved2Bit = 18, - kCollectionReserved3Bit = 19, - kCollectionReserved4Bit = 20, - kCollectionReserved5Bit = 21, - kCollectionReserved6Bit = 22, - kCollectionReserved7Bit = 23, - kCollectionReserved8Bit = 24, - kCollectionReserved9Bit = 25, - kCollectionReserved10Bit = 26, - kCollectionReserved11Bit = 27, - kCollectionReserved12Bit = 28, - kCollectionReserved13Bit = 29, - kCollectionPersistenceBit = 30, - kCollectionLockBit = 31 -}; - - - -enum { - kCollectionUser0Mask = 1UL << kCollectionUser0Bit, - kCollectionUser1Mask = 1UL << kCollectionUser1Bit, - kCollectionUser2Mask = 1UL << kCollectionUser2Bit, - kCollectionUser3Mask = 1UL << kCollectionUser3Bit, - kCollectionUser4Mask = 1UL << kCollectionUser4Bit, - kCollectionUser5Mask = 1UL << kCollectionUser5Bit, - kCollectionUser6Mask = 1UL << kCollectionUser6Bit, - kCollectionUser7Mask = 1UL << kCollectionUser7Bit, - kCollectionUser8Mask = 1UL << kCollectionUser8Bit, - kCollectionUser9Mask = 1UL << kCollectionUser9Bit, - kCollectionUser10Mask = 1UL << kCollectionUser10Bit, - kCollectionUser11Mask = 1UL << kCollectionUser11Bit, - kCollectionUser12Mask = 1UL << kCollectionUser12Bit, - kCollectionUser13Mask = 1UL << kCollectionUser13Bit, - kCollectionUser14Mask = 1UL << kCollectionUser14Bit, - kCollectionUser15Mask = 1UL << kCollectionUser15Bit, - kCollectionReserved0Mask = 1UL << kCollectionReserved0Bit, - kCollectionReserved1Mask = 1UL << kCollectionReserved1Bit, - kCollectionReserved2Mask = 1UL << kCollectionReserved2Bit, - kCollectionReserved3Mask = 1UL << kCollectionReserved3Bit, - kCollectionReserved4Mask = 1UL << kCollectionReserved4Bit, - kCollectionReserved5Mask = 1UL << kCollectionReserved5Bit, - kCollectionReserved6Mask = 1UL << kCollectionReserved6Bit, - kCollectionReserved7Mask = 1UL << kCollectionReserved7Bit, - kCollectionReserved8Mask = 1UL << kCollectionReserved8Bit, - kCollectionReserved9Mask = 1UL << kCollectionReserved9Bit, - kCollectionReserved10Mask = 1UL << kCollectionReserved10Bit, - kCollectionReserved11Mask = 1UL << kCollectionReserved11Bit, - kCollectionReserved12Mask = 1UL << kCollectionReserved12Bit, - kCollectionReserved13Mask = 1UL << kCollectionReserved13Bit, - kCollectionPersistenceMask = 1UL << kCollectionPersistenceBit, - kCollectionLockMask = 1UL << kCollectionLockBit -}; - - - - - - -typedef struct OpaqueCollection* Collection; - -typedef FourCharCode CollectionTag; -typedef OSErr ( * CollectionFlattenProcPtr)(SInt32 size, void *data, void *refCon); -typedef OSErr ( * CollectionExceptionProcPtr)(Collection c, OSErr status); -typedef CollectionFlattenProcPtr CollectionFlattenUPP; -typedef CollectionExceptionProcPtr CollectionExceptionUPP; -extern CollectionFlattenUPP -NewCollectionFlattenUPP(CollectionFlattenProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern CollectionExceptionUPP -NewCollectionExceptionUPP(CollectionExceptionProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeCollectionFlattenUPP(CollectionFlattenUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeCollectionExceptionUPP(CollectionExceptionUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -InvokeCollectionFlattenUPP( - SInt32 size, - void * data, - void * refCon, - CollectionFlattenUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -InvokeCollectionExceptionUPP( - Collection c, - OSErr status, - CollectionExceptionUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline CollectionFlattenUPP NewCollectionFlattenUPP(CollectionFlattenProcPtr userRoutine) { return userRoutine; } - inline CollectionExceptionUPP NewCollectionExceptionUPP(CollectionExceptionProcPtr userRoutine) { return userRoutine; } - inline void DisposeCollectionFlattenUPP(CollectionFlattenUPP) { } - inline void DisposeCollectionExceptionUPP(CollectionExceptionUPP) { } - inline OSErr InvokeCollectionFlattenUPP(SInt32 size, void * data, void * refCon, CollectionFlattenUPP userUPP) { return (*userUPP)(size, data, refCon); } - inline OSErr InvokeCollectionExceptionUPP(Collection c, OSErr status, CollectionExceptionUPP userUPP) { return (*userUPP)(c, status); } -extern Collection -NewCollection(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeCollection(Collection c) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Collection -CloneCollection(Collection c) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -CountCollectionOwners(Collection c) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -RetainCollection(Collection c) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern OSStatus -ReleaseCollection(Collection c) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern ItemCount -GetCollectionRetainCount(Collection c) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern Collection -CopyCollection( - Collection srcCollection, - Collection dstCollection) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -GetCollectionDefaultAttributes(Collection c) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetCollectionDefaultAttributes( - Collection c, - SInt32 whichAttributes, - SInt32 newAttributes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -CountCollectionItems(Collection c) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -AddCollectionItem( - Collection c, - CollectionTag tag, - SInt32 id, - SInt32 itemSize, - const void * itemData) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetCollectionItem( - Collection c, - CollectionTag tag, - SInt32 id, - SInt32 * itemSize, - void * itemData) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -RemoveCollectionItem( - Collection c, - CollectionTag tag, - SInt32 id) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -SetCollectionItemInfo( - Collection c, - CollectionTag tag, - SInt32 id, - SInt32 whichAttributes, - SInt32 newAttributes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetCollectionItemInfo( - Collection c, - CollectionTag tag, - SInt32 id, - SInt32 * itemIndex, - SInt32 * itemSize, - SInt32 * attributes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -ReplaceIndexedCollectionItem( - Collection c, - SInt32 itemIndex, - SInt32 itemSize, - const void * itemData) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetIndexedCollectionItem( - Collection c, - SInt32 itemIndex, - SInt32 * itemSize, - void * itemData) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -RemoveIndexedCollectionItem( - Collection c, - SInt32 itemIndex) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -SetIndexedCollectionItemInfo( - Collection c, - SInt32 itemIndex, - SInt32 whichAttributes, - SInt32 newAttributes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetIndexedCollectionItemInfo( - Collection c, - SInt32 itemIndex, - CollectionTag * tag, - SInt32 * id, - SInt32 * itemSize, - SInt32 * attributes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Boolean -CollectionTagExists( - Collection c, - CollectionTag tag) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -CountCollectionTags(Collection c) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetIndexedCollectionTag( - Collection c, - SInt32 tagIndex, - CollectionTag * tag) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -CountTaggedCollectionItems( - Collection c, - CollectionTag tag) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetTaggedCollectionItem( - Collection c, - CollectionTag tag, - SInt32 whichItem, - SInt32 * itemSize, - void * itemData) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetTaggedCollectionItemInfo( - Collection c, - CollectionTag tag, - SInt32 whichItem, - SInt32 * id, - SInt32 * itemIndex, - SInt32 * itemSize, - SInt32 * attributes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -PurgeCollection( - Collection c, - SInt32 whichAttributes, - SInt32 matchingAttributes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -PurgeCollectionTag( - Collection c, - CollectionTag tag) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -EmptyCollection(Collection c) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FlattenCollection( - Collection c, - CollectionFlattenUPP flattenProc, - void * refCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FlattenPartialCollection( - Collection c, - CollectionFlattenUPP flattenProc, - void * refCon, - SInt32 whichAttributes, - SInt32 matchingAttributes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -UnflattenCollection( - Collection c, - CollectionFlattenUPP flattenProc, - void * refCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern CollectionExceptionUPP -GetCollectionExceptionProc(Collection c) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetCollectionExceptionProc( - Collection c, - CollectionExceptionUPP exceptionProc) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Collection -GetNewCollection(SInt16 collectionID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -AddCollectionItemHdl( - Collection aCollection, - CollectionTag tag, - SInt32 id, - Handle itemData) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetCollectionItemHdl( - Collection aCollection, - CollectionTag tag, - SInt32 id, - Handle itemData) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -ReplaceIndexedCollectionItemHdl( - Collection aCollection, - SInt32 itemIndex, - Handle itemData) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetIndexedCollectionItemHdl( - Collection aCollection, - SInt32 itemIndex, - Handle itemData) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FlattenCollectionToHdl( - Collection aCollection, - Handle flattened) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -UnflattenCollectionFromHdl( - Collection aCollection, - Handle flattened) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -} - - - -extern "C" { - - - - - - -#pragma pack(push, 2) -struct BigEndianUInt32 { - UInt32 bigEndianValue; -}; -typedef struct BigEndianUInt32 BigEndianUInt32; -struct BigEndianLong { - long bigEndianValue; -}; -typedef struct BigEndianLong BigEndianLong; -struct BigEndianUnsignedLong { - unsigned long bigEndianValue; -}; -typedef struct BigEndianUnsignedLong BigEndianUnsignedLong; -struct BigEndianShort { - short bigEndianValue; -}; -typedef struct BigEndianShort BigEndianShort; -struct BigEndianUnsignedShort { - unsigned short bigEndianValue; -}; -typedef struct BigEndianUnsignedShort BigEndianUnsignedShort; -struct BigEndianFixed { - Fixed bigEndianValue; -}; -typedef struct BigEndianFixed BigEndianFixed; -struct BigEndianUnsignedFixed { - UnsignedFixed bigEndianValue; -}; -typedef struct BigEndianUnsignedFixed BigEndianUnsignedFixed; -struct BigEndianOSType { - OSType bigEndianValue; -}; -typedef struct BigEndianOSType BigEndianOSType; -enum { - kCoreEndianResourceManagerDomain = 'rsrc', - kCoreEndianAppleEventManagerDomain = 'aevt' -}; -typedef OSStatus ( * CoreEndianFlipProc)(OSType dataDomain, OSType dataType, SInt16 id, void *dataPtr, ByteCount dataSize, Boolean currentlyNative, void *refcon); -extern OSStatus -CoreEndianInstallFlipper( - OSType dataDomain, - OSType dataType, - CoreEndianFlipProc proc, - void * refcon) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern OSStatus -CoreEndianGetFlipper( - OSType dataDomain, - OSType dataType, - CoreEndianFlipProc * proc, - void ** refcon) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern OSStatus -CoreEndianFlipData( - OSType dataDomain, - OSType dataType, - SInt16 id, - void * data, - ByteCount dataLen, - Boolean currentlyNative) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); - - - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - - - -typedef OSErr ( * SelectorFunctionProcPtr)(OSType selector, SInt32 *response); -typedef SelectorFunctionProcPtr SelectorFunctionUPP; -extern OSErr -Gestalt( - OSType selector, - SInt32 * response) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -NewGestaltValue( - OSType selector, - SInt32 newValue) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -ReplaceGestaltValue( - OSType selector, - SInt32 replacementValue) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -SetGestaltValue( - OSType selector, - SInt32 newValue) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -DeleteGestaltValue(OSType selector) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SelectorFunctionUPP -NewSelectorFunctionUPP(SelectorFunctionProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeSelectorFunctionUPP(SelectorFunctionUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -InvokeSelectorFunctionUPP( - OSType selector, - SInt32 * response, - SelectorFunctionUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline SelectorFunctionUPP NewSelectorFunctionUPP(SelectorFunctionProcPtr userRoutine) { return userRoutine; } - inline void DisposeSelectorFunctionUPP(SelectorFunctionUPP) { } - inline OSErr InvokeSelectorFunctionUPP(OSType selector, SInt32 * response, SelectorFunctionUPP userUPP) { return (*userUPP)(selector, response); } -enum { - gestaltAddressingModeAttr = 'addr', - gestalt32BitAddressing = 0, - gestalt32BitSysZone = 1, - gestalt32BitCapable = 2 -}; - -enum { - gestaltAFPClient = 'afps', - gestaltAFPClientVersionMask = 0x0000FFFF, - - gestaltAFPClient3_5 = 0x0001, - gestaltAFPClient3_6 = 0x0002, - gestaltAFPClient3_6_1 = 0x0003, - gestaltAFPClient3_6_2 = 0x0004, - gestaltAFPClient3_6_3 = 0x0005, - gestaltAFPClient3_7 = 0x0006, - gestaltAFPClient3_7_2 = 0x0007, - gestaltAFPClient3_8 = 0x0008, - gestaltAFPClient3_8_1 = 0x0009, - gestaltAFPClient3_8_3 = 0x000A, - gestaltAFPClient3_8_4 = 0x000B, - gestaltAFPClientAttributeMask = (int)0xFFFF0000, - - gestaltAFPClientCfgRsrc = 16, - gestaltAFPClientSupportsIP = 29, - gestaltAFPClientVMUI = 30, - gestaltAFPClientMultiReq = 31 -}; - - -enum { - gestaltAliasMgrAttr = 'alis', - gestaltAliasMgrPresent = 0, - gestaltAliasMgrSupportsRemoteAppletalk = 1, - gestaltAliasMgrSupportsAOCEKeychain = 2, - gestaltAliasMgrResolveAliasFileWithMountOptions = 3, - gestaltAliasMgrFollowsAliasesWhenResolving = 4, - gestaltAliasMgrSupportsExtendedCalls = 5, - gestaltAliasMgrSupportsFSCalls = 6, - gestaltAliasMgrPrefersPath = 7, - gestaltAliasMgrRequiresAccessors = 8 -}; - - -enum { - gestaltAppearanceAttr = 'appr', - gestaltAppearanceExists = 0, - gestaltAppearanceCompatMode = 1 -}; - - - - - - - -enum { - gestaltAppearanceVersion = 'apvr' -}; - -enum { - gestaltArbitorAttr = 'arb ', - gestaltSerialArbitrationExists = 0 -}; - -enum { - gestaltAppleScriptVersion = 'ascv' -}; - -enum { - gestaltAppleScriptAttr = 'ascr', - gestaltAppleScriptPresent = 0, - gestaltAppleScriptPowerPCSupport = 1 -}; - -enum { - gestaltATAAttr = 'ata ', - gestaltATAPresent = 0 -}; - -enum { - gestaltATalkVersion = 'atkv' -}; - -enum { - gestaltAppleTalkVersion = 'atlk' -}; -enum { - gestaltAUXVersion = 'a/ux' -}; - -enum { - gestaltMacOSCompatibilityBoxAttr = 'bbox', - gestaltMacOSCompatibilityBoxPresent = 0, - gestaltMacOSCompatibilityBoxHasSerial = 1, - gestaltMacOSCompatibilityBoxless = 2 -}; - -enum { - gestaltBusClkSpeed = 'bclk' -}; - -enum { - gestaltBusClkSpeedMHz = 'bclm' -}; - -enum { - gestaltCloseViewAttr = 'BSDa', - gestaltCloseViewEnabled = 0, - gestaltCloseViewDisplayMgrFriendly = 1 -}; - -enum { - gestaltCarbonVersion = 'cbon' -}; - -enum { - gestaltCFMAttr = 'cfrg', - gestaltCFMPresent = 0, - gestaltCFMPresentMask = 0x0001, - gestaltCFM99Present = 2, - gestaltCFM99PresentMask = 0x0004 -}; - -enum { - gestaltProcessorCacheLineSize = 'csiz' -}; - -enum { - gestaltCollectionMgrVersion = 'cltn' -}; - -enum { - gestaltColorMatchingAttr = 'cmta', - gestaltHighLevelMatching = 0, - gestaltColorMatchingLibLoaded = 1 -}; - -enum { - gestaltColorMatchingVersion = 'cmtc', - gestaltColorSync10 = 0x0100, - gestaltColorSync11 = 0x0110, - gestaltColorSync104 = 0x0104, - gestaltColorSync105 = 0x0105, - gestaltColorSync20 = 0x0200, - gestaltColorSync21 = 0x0210, - gestaltColorSync211 = 0x0211, - gestaltColorSync212 = 0x0212, - gestaltColorSync213 = 0x0213, - gestaltColorSync25 = 0x0250, - gestaltColorSync26 = 0x0260, - gestaltColorSync261 = 0x0261, - gestaltColorSync30 = 0x0300 -}; - -enum { - gestaltControlMgrVersion = 'cmvr' -}; - -enum { - gestaltControlMgrAttr = 'cntl', - gestaltControlMgrPresent = (1L << 0), - - - gestaltControlMgrPresentBit = 0, - gestaltControlMsgPresentMask = (1L << gestaltControlMgrPresentBit) -}; - -enum { - gestaltConnMgrAttr = 'conn', - gestaltConnMgrPresent = 0, - gestaltConnMgrCMSearchFix = 1, - gestaltConnMgrErrorString = 2, - gestaltConnMgrMultiAsyncIO = 3 -}; - -enum { - gestaltColorPickerVersion = 'cpkr', - gestaltColorPicker = 'cpkr' -}; - -enum { - gestaltComponentMgr = 'cpnt', - gestaltComponentPlatform = 'copl' -}; -enum { - gestaltNativeCPUtype = 'cput', - gestaltNativeCPUfamily = 'cpuf', - gestaltCPU68000 = 0, - gestaltCPU68010 = 1, - gestaltCPU68020 = 2, - gestaltCPU68030 = 3, - gestaltCPU68040 = 4, - gestaltCPU601 = 0x0101, - gestaltCPU603 = 0x0103, - gestaltCPU604 = 0x0104, - gestaltCPU603e = 0x0106, - gestaltCPU603ev = 0x0107, - gestaltCPU750 = 0x0108, - gestaltCPU604e = 0x0109, - gestaltCPU604ev = 0x010A, - gestaltCPUG4 = 0x010C, - gestaltCPUG47450 = 0x0110 -}; - -enum { - gestaltCPUApollo = 0x0111, - gestaltCPUG47447 = 0x0112, - gestaltCPU750FX = 0x0120, - gestaltCPU970 = 0x0139, - gestaltCPU970FX = 0x013C, - gestaltCPU970MP = 0x0144 -}; - -enum { - - gestaltCPU486 = 'i486', - gestaltCPUPentium = 'i586', - gestaltCPUPentiumPro = 'i5pr', - gestaltCPUPentiumII = 'i5ii', - gestaltCPUX86 = 'ixxx', - gestaltCPUPentium4 = 'i5iv' -}; - -enum { - gestaltCRMAttr = 'crm ', - gestaltCRMPresent = 0, - gestaltCRMPersistentFix = 1, - gestaltCRMToolRsrcCalls = 2 -}; - -enum { - gestaltControlStripVersion = 'csvr' -}; - -enum { - gestaltCountOfCPUs = 'cpus' -}; - -enum { - gestaltCTBVersion = 'ctbv' -}; - -enum { - gestaltDBAccessMgrAttr = 'dbac', - gestaltDBAccessMgrPresent = 0 -}; - -enum { - gestaltDiskCacheSize = 'dcsz' -}; - -enum { - gestaltSDPFindVersion = 'dfnd' -}; - -enum { - gestaltDictionaryMgrAttr = 'dict', - gestaltDictionaryMgrPresent = 0 -}; - -enum { - gestaltDITLExtAttr = 'ditl', - gestaltDITLExtPresent = 0, - gestaltDITLExtSupportsIctb = 1 -}; - -enum { - gestaltDialogMgrAttr = 'dlog', - gestaltDialogMgrPresent = (1L << 0), - - - gestaltDialogMgrPresentBit = 0, - gestaltDialogMgrHasAquaAlertBit = 2, - gestaltDialogMgrPresentMask = (1L << gestaltDialogMgrPresentBit), - gestaltDialogMgrHasAquaAlertMask = (1L << gestaltDialogMgrHasAquaAlertBit), - gestaltDialogMsgPresentMask = gestaltDialogMgrPresentMask -}; - -enum { - gestaltDesktopPicturesAttr = 'dkpx', - gestaltDesktopPicturesInstalled = 0, - gestaltDesktopPicturesDisplayed = 1 -}; - -enum { - gestaltDisplayMgrVers = 'dplv' -}; - -enum { - gestaltDisplayMgrAttr = 'dply', - gestaltDisplayMgrPresent = 0, - gestaltDisplayMgrCanSwitchMirrored = 2, - gestaltDisplayMgrSetDepthNotifies = 3, - gestaltDisplayMgrCanConfirm = 4, - gestaltDisplayMgrColorSyncAware = 5, - gestaltDisplayMgrGeneratesProfiles = 6, - gestaltDisplayMgrSleepNotifies = 7 -}; - -enum { - gestaltDragMgrAttr = 'drag', - gestaltDragMgrPresent = 0, - gestaltDragMgrFloatingWind = 1, - gestaltPPCDragLibPresent = 2, - gestaltDragMgrHasImageSupport = 3, - gestaltCanStartDragInFloatWindow = 4, - gestaltSetDragImageUpdates = 5 -}; - -enum { - gestaltDrawSprocketVersion = 'dspv' -}; - -enum { - gestaltDigitalSignatureVersion = 'dsig' -}; - - - - - -enum { - gestaltDTPFeatures = 'dtpf', - kDTPThirdPartySupported = 0x00000004 -}; - - - - - - -enum { - gestaltDTPInfo = 'dtpx' -}; - -enum { - gestaltEasyAccessAttr = 'easy', - gestaltEasyAccessOff = 0, - gestaltEasyAccessOn = 1, - gestaltEasyAccessSticky = 2, - gestaltEasyAccessLocked = 3 -}; - -enum { - gestaltEditionMgrAttr = 'edtn', - gestaltEditionMgrPresent = 0, - gestaltEditionMgrTranslationAware = 1 -}; - -enum { - gestaltAppleEventsAttr = 'evnt', - gestaltAppleEventsPresent = 0, - gestaltScriptingSupport = 1, - gestaltOSLInSystem = 2, - gestaltSupportsApplicationURL = 4 -}; - -enum { - gestaltExtensionTableVersion = 'etbl' -}; - - -enum { - gestaltFBCIndexingState = 'fbci', - gestaltFBCindexingSafe = 0, - gestaltFBCindexingCritical = 1 -}; - -enum { - gestaltFBCVersion = 'fbcv', - gestaltFBCCurrentVersion = 0x0011, - gestaltOSXFBCCurrentVersion = 0x0100 -}; - - -enum { - gestaltFileMappingAttr = 'flmp', - gestaltFileMappingPresent = 0, - gestaltFileMappingMultipleFilesFix = 1 -}; - -enum { - gestaltFloppyAttr = 'flpy', - gestaltFloppyIsMFMOnly = 0, - gestaltFloppyIsManualEject = 1, - gestaltFloppyUsesDiskInPlace = 2 -}; - -enum { - gestaltFinderAttr = 'fndr', - gestaltFinderDropEvent = 0, - gestaltFinderMagicPlacement = 1, - gestaltFinderCallsAEProcess = 2, - gestaltOSLCompliantFinder = 3, - gestaltFinderSupports4GBVolumes = 4, - gestaltFinderHasClippings = 6, - gestaltFinderFullDragManagerSupport = 7, - gestaltFinderFloppyRootComments = 8, - gestaltFinderLargeAndNotSavedFlavorsOK = 9, - gestaltFinderUsesExtensibleFolderManager = 10, - gestaltFinderUnderstandsRedirectedDesktopFolder = 11 -}; - -enum { - gestaltFindFolderAttr = 'fold', - gestaltFindFolderPresent = 0, - gestaltFolderDescSupport = 1, - gestaltFolderMgrFollowsAliasesWhenResolving = 2, - gestaltFolderMgrSupportsExtendedCalls = 3, - gestaltFolderMgrSupportsDomains = 4, - gestaltFolderMgrSupportsFSCalls = 5 -}; - -enum { - gestaltFindFolderRedirectionAttr = 'fole' -}; - - -enum { - gestaltFontMgrAttr = 'font', - gestaltOutlineFonts = 0 -}; - -enum { - gestaltFPUType = 'fpu ', - gestaltNoFPU = 0, - gestalt68881 = 1, - gestalt68882 = 2, - gestalt68040FPU = 3 -}; - -enum { - gestaltFSAttr = 'fs ', - gestaltFullExtFSDispatching = 0, - gestaltHasFSSpecCalls = 1, - gestaltHasFileSystemManager = 2, - gestaltFSMDoesDynamicLoad = 3, - gestaltFSSupports4GBVols = 4, - gestaltFSSupports2TBVols = 5, - gestaltHasExtendedDiskInit = 6, - gestaltDTMgrSupportsFSM = 7, - gestaltFSNoMFSVols = 8, - gestaltFSSupportsHFSPlusVols = 9, - gestaltFSIncompatibleDFA82 = 10 -}; - -enum { - gestaltFSSupportsDirectIO = 11 -}; - -enum { - gestaltHasHFSPlusAPIs = 12, - gestaltMustUseFCBAccessors = 13, - gestaltFSUsesPOSIXPathsForConversion = 14, - gestaltFSSupportsExclusiveLocks = 15, - gestaltFSSupportsHardLinkDetection = 16, - gestaltFSAllowsConcurrentAsyncIO = 17 -}; - -enum { - gestaltAdminFeaturesFlagsAttr = 'fred', - gestaltFinderUsesSpecialOpenFoldersFile = 0 -}; - -enum { - gestaltFSMVersion = 'fsm ' -}; - -enum { - gestaltFXfrMgrAttr = 'fxfr', - gestaltFXfrMgrPresent = 0, - gestaltFXfrMgrMultiFile = 1, - gestaltFXfrMgrErrorString = 2, - gestaltFXfrMgrAsync = 3 -}; - -enum { - gestaltGraphicsAttr = 'gfxa', - gestaltGraphicsIsDebugging = 0x00000001, - gestaltGraphicsIsLoaded = 0x00000002, - gestaltGraphicsIsPowerPC = 0x00000004 -}; - -enum { - gestaltGraphicsVersion = 'grfx', - gestaltCurrentGraphicsVersion = 0x00010200 -}; - -enum { - gestaltHardwareAttr = 'hdwr', - gestaltHasVIA1 = 0, - gestaltHasVIA2 = 1, - gestaltHasASC = 3, - gestaltHasSCC = 4, - gestaltHasSCSI = 7, - gestaltHasSoftPowerOff = 19, - gestaltHasSCSI961 = 21, - gestaltHasSCSI962 = 22, - gestaltHasUniversalROM = 24, - gestaltHasEnhancedLtalk = 30 -}; - -enum { - gestaltHelpMgrAttr = 'help', - gestaltHelpMgrPresent = 0, - gestaltHelpMgrExtensions = 1, - gestaltAppleGuideIsDebug = 30, - gestaltAppleGuidePresent = 31 -}; - -enum { - gestaltHardwareVendorCode = 'hrad', - gestaltHardwareVendorApple = 'Appl' -}; - -enum { - gestaltCompressionMgr = 'icmp' -}; - -enum { - gestaltIconUtilitiesAttr = 'icon', - gestaltIconUtilitiesPresent = 0, - gestaltIconUtilitiesHas48PixelIcons = 1, - gestaltIconUtilitiesHas32BitIcons = 2, - gestaltIconUtilitiesHas8BitDeepMasks = 3, - gestaltIconUtilitiesHasIconServices = 4 -}; - -enum { - gestaltInternalDisplay = 'idsp' -}; - - - - - -enum { - gestaltKeyboardType = 'kbd ', - gestaltMacKbd = 1, - gestaltMacAndPad = 2, - gestaltMacPlusKbd = 3, - gestaltUnknownThirdPartyKbd = 3, - gestaltExtADBKbd = 4, - gestaltStdADBKbd = 5, - gestaltPrtblADBKbd = 6, - gestaltPrtblISOKbd = 7, - gestaltStdISOADBKbd = 8, - gestaltExtISOADBKbd = 9, - gestaltADBKbdII = 10, - gestaltADBISOKbdII = 11, - gestaltPwrBookADBKbd = 12, - gestaltPwrBookISOADBKbd = 13, - gestaltAppleAdjustKeypad = 14, - gestaltAppleAdjustADBKbd = 15, - gestaltAppleAdjustISOKbd = 16, - gestaltJapanAdjustADBKbd = 17, - gestaltPwrBkExtISOKbd = 20, - gestaltPwrBkExtJISKbd = 21, - gestaltPwrBkExtADBKbd = 24, - gestaltPS2Keyboard = 27, - gestaltPwrBkSubDomKbd = 28, - gestaltPwrBkSubISOKbd = 29, - gestaltPwrBkSubJISKbd = 30, - gestaltPortableUSBANSIKbd = 37, - gestaltPortableUSBISOKbd = 38, - gestaltPortableUSBJISKbd = 39, - gestaltThirdPartyANSIKbd = 40, - gestaltThirdPartyISOKbd = 41, - gestaltThirdPartyJISKbd = 42, - gestaltPwrBkEKDomKbd = 195, - gestaltPwrBkEKISOKbd = 196, - gestaltPwrBkEKJISKbd = 197, - gestaltUSBCosmoANSIKbd = 198, - gestaltUSBCosmoISOKbd = 199, - gestaltUSBCosmoJISKbd = 200, - gestaltPwrBk99JISKbd = 201, - gestaltUSBAndyANSIKbd = 204, - gestaltUSBAndyISOKbd = 205, - gestaltUSBAndyJISKbd = 206 -}; - - -enum { - gestaltPortable2001ANSIKbd = 202, - gestaltPortable2001ISOKbd = 203, - gestaltPortable2001JISKbd = 207 -}; - -enum { - gestaltUSBProF16ANSIKbd = 34, - gestaltUSBProF16ISOKbd = 35, - gestaltUSBProF16JISKbd = 36, - gestaltProF16ANSIKbd = 31, - gestaltProF16ISOKbd = 32, - gestaltProF16JISKbd = 33 -}; - - - - - -enum { - gestaltUDFSupport = 'kudf' -}; - -enum { - gestaltLowMemorySize = 'lmem' -}; - -enum { - gestaltLogicalRAMSize = 'lram' -}; -enum { - gestaltMachineType = 'mach', - gestaltClassic = 1, - gestaltMacXL = 2, - gestaltMac512KE = 3, - gestaltMacPlus = 4, - gestaltMacSE = 5, - gestaltMacII = 6, - gestaltMacIIx = 7, - gestaltMacIIcx = 8, - gestaltMacSE030 = 9, - gestaltPortable = 10, - gestaltMacIIci = 11, - gestaltPowerMac8100_120 = 12, - gestaltMacIIfx = 13, - gestaltMacClassic = 17, - gestaltMacIIsi = 18, - gestaltMacLC = 19, - gestaltMacQuadra900 = 20, - gestaltPowerBook170 = 21, - gestaltMacQuadra700 = 22, - gestaltClassicII = 23, - gestaltPowerBook100 = 24, - gestaltPowerBook140 = 25, - gestaltMacQuadra950 = 26, - gestaltMacLCIII = 27, - gestaltPerforma450 = gestaltMacLCIII, - gestaltPowerBookDuo210 = 29, - gestaltMacCentris650 = 30, - gestaltPowerBookDuo230 = 32, - gestaltPowerBook180 = 33, - gestaltPowerBook160 = 34, - gestaltMacQuadra800 = 35, - gestaltMacQuadra650 = 36, - gestaltMacLCII = 37, - gestaltPowerBookDuo250 = 38, - gestaltAWS9150_80 = 39, - gestaltPowerMac8100_110 = 40, - gestaltAWS8150_110 = gestaltPowerMac8100_110, - gestaltPowerMac5200 = 41, - gestaltPowerMac5260 = gestaltPowerMac5200, - gestaltPerforma5300 = gestaltPowerMac5200, - gestaltPowerMac6200 = 42, - gestaltPerforma6300 = gestaltPowerMac6200, - gestaltMacIIvi = 44, - gestaltMacIIvm = 45, - gestaltPerforma600 = gestaltMacIIvm, - gestaltPowerMac7100_80 = 47, - gestaltMacIIvx = 48, - gestaltMacColorClassic = 49, - gestaltPerforma250 = gestaltMacColorClassic, - gestaltPowerBook165c = 50, - gestaltMacCentris610 = 52, - gestaltMacQuadra610 = 53, - gestaltPowerBook145 = 54, - gestaltPowerMac8100_100 = 55, - gestaltMacLC520 = 56, - gestaltAWS9150_120 = 57, - gestaltPowerMac6400 = 58, - gestaltPerforma6400 = gestaltPowerMac6400, - gestaltPerforma6360 = gestaltPerforma6400, - gestaltMacCentris660AV = 60, - gestaltMacQuadra660AV = gestaltMacCentris660AV, - gestaltPerforma46x = 62, - gestaltPowerMac8100_80 = 65, - gestaltAWS8150_80 = gestaltPowerMac8100_80, - gestaltPowerMac9500 = 67, - gestaltPowerMac9600 = gestaltPowerMac9500, - gestaltPowerMac7500 = 68, - gestaltPowerMac7600 = gestaltPowerMac7500, - gestaltPowerMac8500 = 69, - gestaltPowerMac8600 = gestaltPowerMac8500, - gestaltAWS8550 = gestaltPowerMac7500, - gestaltPowerBook180c = 71, - gestaltPowerBook520 = 72, - gestaltPowerBook520c = gestaltPowerBook520, - gestaltPowerBook540 = gestaltPowerBook520, - gestaltPowerBook540c = gestaltPowerBook520, - gestaltPowerMac5400 = 74, - gestaltPowerMac6100_60 = 75, - gestaltAWS6150_60 = gestaltPowerMac6100_60, - gestaltPowerBookDuo270c = 77, - gestaltMacQuadra840AV = 78, - gestaltPerforma550 = 80, - gestaltPowerBook165 = 84, - gestaltPowerBook190 = 85, - gestaltMacTV = 88, - gestaltMacLC475 = 89, - gestaltPerforma47x = gestaltMacLC475, - gestaltMacLC575 = 92, - gestaltMacQuadra605 = 94, - gestaltMacQuadra630 = 98, - gestaltMacLC580 = 99, - gestaltPerforma580 = gestaltMacLC580, - gestaltPowerMac6100_66 = 100, - gestaltAWS6150_66 = gestaltPowerMac6100_66, - gestaltPowerBookDuo280 = 102, - gestaltPowerBookDuo280c = 103, - gestaltPowerMacLC475 = 104, - gestaltPowerMacPerforma47x = gestaltPowerMacLC475, - gestaltPowerMacLC575 = 105, - gestaltPowerMacPerforma57x = gestaltPowerMacLC575, - gestaltPowerMacQuadra630 = 106, - gestaltPowerMacLC630 = gestaltPowerMacQuadra630, - gestaltPowerMacPerforma63x = gestaltPowerMacQuadra630, - gestaltPowerMac7200 = 108, - gestaltPowerMac7300 = 109, - gestaltPowerMac7100_66 = 112, - gestaltPowerBook150 = 115, - gestaltPowerMacQuadra700 = 116, - gestaltPowerMacQuadra900 = 117, - gestaltPowerMacQuadra950 = 118, - gestaltPowerMacCentris610 = 119, - gestaltPowerMacCentris650 = 120, - gestaltPowerMacQuadra610 = 121, - gestaltPowerMacQuadra650 = 122, - gestaltPowerMacQuadra800 = 123, - gestaltPowerBookDuo2300 = 124, - gestaltPowerBook500PPCUpgrade = 126, - gestaltPowerBook5300 = 128, - gestaltPowerBook1400 = 310, - gestaltPowerBook3400 = 306, - gestaltPowerBook2400 = 307, - gestaltPowerBookG3Series = 312, - gestaltPowerBookG3 = 313, - gestaltPowerBookG3Series2 = 314, - gestaltPowerMacNewWorld = 406, - gestaltPowerMacG3 = 510, - gestaltPowerMac5500 = 512, - gestalt20thAnniversary = gestaltPowerMac5500, - gestaltPowerMac6500 = 513, - gestaltPowerMac4400_160 = 514, - gestaltPowerMac4400 = 515, - gestaltMacOSCompatibility = 1206 -}; - - -enum { - gestaltQuadra605 = gestaltMacQuadra605, - gestaltQuadra610 = gestaltMacQuadra610, - gestaltQuadra630 = gestaltMacQuadra630, - gestaltQuadra650 = gestaltMacQuadra650, - gestaltQuadra660AV = gestaltMacQuadra660AV, - gestaltQuadra700 = gestaltMacQuadra700, - gestaltQuadra800 = gestaltMacQuadra800, - gestaltQuadra840AV = gestaltMacQuadra840AV, - gestaltQuadra900 = gestaltMacQuadra900, - gestaltQuadra950 = gestaltMacQuadra950 -}; - -enum { - kMachineNameStrID = -16395 -}; - -enum { - gestaltSMPMailerVersion = 'malr' -}; - -enum { - gestaltMediaBay = 'mbeh', - gestaltMBLegacy = 0, - gestaltMBSingleBay = 1, - gestaltMBMultipleBays = 2 -}; - -enum { - gestaltMessageMgrVersion = 'mess' -}; - - - -enum { - gestaltMenuMgrAttr = 'menu', - gestaltMenuMgrPresent = (1L << 0), - - - gestaltMenuMgrPresentBit = 0, - gestaltMenuMgrAquaLayoutBit = 1, - gestaltMenuMgrMultipleItemsWithCommandIDBit = 2, - gestaltMenuMgrRetainsIconRefBit = 3, - gestaltMenuMgrSendsMenuBoundsToDefProcBit = 4, - gestaltMenuMgrMoreThanFiveMenusDeepBit = 5, - gestaltMenuMgrCGImageMenuTitleBit = 6, - - gestaltMenuMgrPresentMask = (1L << gestaltMenuMgrPresentBit), - gestaltMenuMgrAquaLayoutMask = (1L << gestaltMenuMgrAquaLayoutBit), - gestaltMenuMgrMultipleItemsWithCommandIDMask = (1L << gestaltMenuMgrMultipleItemsWithCommandIDBit), - gestaltMenuMgrRetainsIconRefMask = (1L << gestaltMenuMgrRetainsIconRefBit), - gestaltMenuMgrSendsMenuBoundsToDefProcMask = (1L << gestaltMenuMgrSendsMenuBoundsToDefProcBit), - gestaltMenuMgrMoreThanFiveMenusDeepMask = (1L << gestaltMenuMgrMoreThanFiveMenusDeepBit), - gestaltMenuMgrCGImageMenuTitleMask = (1L << gestaltMenuMgrCGImageMenuTitleBit) -}; - - -enum { - gestaltMultipleUsersState = 'mfdr' -}; - - -enum { - gestaltMachineIcon = 'micn' -}; - -enum { - gestaltMiscAttr = 'misc', - gestaltScrollingThrottle = 0, - gestaltSquareMenuBar = 2 -}; -enum { - gestaltMixedModeVersion = 'mixd' -}; - -enum { - gestaltMixedModeAttr = 'mixd', - gestaltMixedModePowerPC = 0, - gestaltPowerPCAware = 0, - gestaltMixedModeCFM68K = 1, - gestaltMixedModeCFM68KHasTrap = 2, - gestaltMixedModeCFM68KHasState = 3 -}; - -enum { - gestaltQuickTimeConferencing = 'mtlk' -}; - -enum { - gestaltMemoryMapAttr = 'mmap', - gestaltMemoryMapSparse = 0 -}; - -enum { - gestaltMMUType = 'mmu ', - gestaltNoMMU = 0, - gestaltAMU = 1, - gestalt68851 = 2, - gestalt68030MMU = 3, - gestalt68040MMU = 4, - gestaltEMMU1 = 5 -}; - -enum { - - - - gestaltUserVisibleMachineName = 'mnam' -}; - -enum { - gestaltMPCallableAPIsAttr = 'mpsc', - gestaltMPFileManager = 0, - gestaltMPDeviceManager = 1, - gestaltMPTrapCalls = 2 -}; - -enum { - gestaltStdNBPAttr = 'nlup', - gestaltStdNBPPresent = 0, - gestaltStdNBPSupportsAutoPosition = 1 -}; - -enum { - gestaltNotificationMgrAttr = 'nmgr', - gestaltNotificationPresent = 0 -}; - -enum { - gestaltNameRegistryVersion = 'nreg' -}; - -enum { - gestaltNuBusSlotCount = 'nubs' -}; - -enum { - gestaltOCEToolboxVersion = 'ocet', - gestaltOCETB = 0x0102, - gestaltSFServer = 0x0100 -}; - -enum { - gestaltOCEToolboxAttr = 'oceu', - gestaltOCETBPresent = 0x01, - gestaltOCETBAvailable = 0x02, - gestaltOCESFServerAvailable = 0x04, - gestaltOCETBNativeGlueAvailable = 0x10 -}; - -enum { - gestaltOpenFirmwareInfo = 'opfw' -}; - -enum { - gestaltOSAttr = 'os ', - gestaltSysZoneGrowable = 0, - gestaltLaunchCanReturn = 1, - gestaltLaunchFullFileSpec = 2, - gestaltLaunchControl = 3, - gestaltTempMemSupport = 4, - gestaltRealTempMemory = 5, - gestaltTempMemTracked = 6, - gestaltIPCSupport = 7, - gestaltSysDebuggerSupport = 8, - gestaltNativeProcessMgrBit = 19, - gestaltAltivecRegistersSwappedCorrectlyBit = 20 -}; - -enum { - gestaltOSTable = 'ostt' -}; -enum { - gestaltOpenTptNetworkSetup = 'otcf', - gestaltOpenTptNetworkSetupLegacyImport = 0, - gestaltOpenTptNetworkSetupLegacyExport = 1, - gestaltOpenTptNetworkSetupSupportsMultihoming = 2 -}; - -enum { - gestaltOpenTptNetworkSetupVersion = 'otcv' -}; - - - - - - - -enum { - gestaltOpenTptRemoteAccess = 'otra', - gestaltOpenTptRemoteAccessPresent = 0, - gestaltOpenTptRemoteAccessLoaded = 1, - gestaltOpenTptRemoteAccessClientOnly = 2, - gestaltOpenTptRemoteAccessPServer = 3, - gestaltOpenTptRemoteAccessMPServer = 4, - gestaltOpenTptPPPPresent = 5, - gestaltOpenTptARAPPresent = 6 -}; - -enum { - gestaltOpenTptRemoteAccessVersion = 'otrv' -}; - - - - - -enum { - gestaltOpenTptVersions = 'otvr' -}; - -enum { - gestaltOpenTpt = 'otan', - gestaltOpenTptPresentMask = 0x00000001, - gestaltOpenTptLoadedMask = 0x00000002, - gestaltOpenTptAppleTalkPresentMask = 0x00000004, - gestaltOpenTptAppleTalkLoadedMask = 0x00000008, - gestaltOpenTptTCPPresentMask = 0x00000010, - gestaltOpenTptTCPLoadedMask = 0x00000020, - gestaltOpenTptIPXSPXPresentMask = 0x00000040, - gestaltOpenTptIPXSPXLoadedMask = 0x00000080, - gestaltOpenTptPresentBit = 0, - gestaltOpenTptLoadedBit = 1, - gestaltOpenTptAppleTalkPresentBit = 2, - gestaltOpenTptAppleTalkLoadedBit = 3, - gestaltOpenTptTCPPresentBit = 4, - gestaltOpenTptTCPLoadedBit = 5, - gestaltOpenTptIPXSPXPresentBit = 6, - gestaltOpenTptIPXSPXLoadedBit = 7 -}; - - -enum { - gestaltPCCard = 'pccd', - gestaltCardServicesPresent = 0, - gestaltPCCardFamilyPresent = 1, - gestaltPCCardHasPowerControl = 2, - gestaltPCCardSupportsCardBus = 3 -}; - -enum { - gestaltProcClkSpeed = 'pclk' -}; - -enum { - gestaltProcClkSpeedMHz = 'mclk' -}; - -enum { - gestaltPCXAttr = 'pcxg', - gestaltPCXHas8and16BitFAT = 0, - gestaltPCXHasProDOS = 1, - gestaltPCXNewUI = 2, - gestaltPCXUseICMapping = 3 -}; - -enum { - gestaltLogicalPageSize = 'pgsz' -}; -enum { - gestaltScreenCaptureMain = 'pic1', - gestaltScreenCaptureDir = 'pic2' -}; - -enum { - gestaltGXPrintingMgrVersion = 'pmgr' -}; - -enum { - gestaltPopupAttr = 'pop!', - gestaltPopupPresent = 0 -}; - -enum { - gestaltPowerMgrAttr = 'powr', - gestaltPMgrExists = 0, - gestaltPMgrCPUIdle = 1, - gestaltPMgrSCC = 2, - gestaltPMgrSound = 3, - gestaltPMgrDispatchExists = 4, - gestaltPMgrSupportsAVPowerStateAtSleepWake = 5 -}; - -enum { - gestaltPowerMgrVers = 'pwrv' -}; - - - - - - - -enum { - gestaltPPCToolboxAttr = 'ppc ', - gestaltPPCToolboxPresent = 0x0000, - gestaltPPCSupportsRealTime = 0x1000, - gestaltPPCSupportsIncoming = 0x0001, - gestaltPPCSupportsOutGoing = 0x0002, - gestaltPPCSupportsTCP_IP = 0x0004, - gestaltPPCSupportsIncomingAppleTalk = 0x0010, - gestaltPPCSupportsIncomingTCP_IP = 0x0020, - gestaltPPCSupportsOutgoingAppleTalk = 0x0100, - gestaltPPCSupportsOutgoingTCP_IP = 0x0200 -}; - - - - - - -enum { - gestaltPowerPCProcessorFeatures = 'ppcf', - gestaltPowerPCHasGraphicsInstructions = 0, - gestaltPowerPCHasSTFIWXInstruction = 1, - gestaltPowerPCHasSquareRootInstructions = 2, - gestaltPowerPCHasDCBAInstruction = 3, - gestaltPowerPCHasVectorInstructions = 4, - gestaltPowerPCHasDataStreams = 5, - gestaltPowerPCHas64BitSupport = 6, - gestaltPowerPCHasDCBTStreams = 7, - gestaltPowerPCASArchitecture = 8, - gestaltPowerPCIgnoresDCBST = 9 -}; - -enum { - gestaltProcessorType = 'proc', - gestalt68000 = 1, - gestalt68010 = 2, - gestalt68020 = 3, - gestalt68030 = 4, - gestalt68040 = 5 -}; - -enum { - gestaltSDPPromptVersion = 'prpv' -}; - -enum { - gestaltParityAttr = 'prty', - gestaltHasParityCapability = 0, - gestaltParityEnabled = 1 -}; - -enum { - gestaltQD3DVersion = 'q3v ' -}; - -enum { - gestaltQD3DViewer = 'q3vc', - gestaltQD3DViewerPresent = 0 -}; -enum { - gestaltQuickdrawVersion = 'qd ', - gestaltOriginalQD = 0x0000, - gestalt8BitQD = 0x0100, - gestalt32BitQD = 0x0200, - gestalt32BitQD11 = 0x0201, - gestalt32BitQD12 = 0x0220, - gestalt32BitQD13 = 0x0230, - gestaltAllegroQD = 0x0250, - gestaltMacOSXQD = 0x0300 -}; - -enum { - gestaltQD3D = 'qd3d', - gestaltQD3DPresent = 0 -}; -enum { - gestaltGXVersion = 'qdgx' -}; - -enum { - gestaltQuickdrawFeatures = 'qdrw', - gestaltHasColor = 0, - gestaltHasDeepGWorlds = 1, - gestaltHasDirectPixMaps = 2, - gestaltHasGrayishTextOr = 3, - gestaltSupportsMirroring = 4, - gestaltQDHasLongRowBytes = 5 -}; - -enum { - gestaltQDTextVersion = 'qdtx', - gestaltOriginalQDText = 0x0000, - gestaltAllegroQDText = 0x0100, - gestaltMacOSXQDText = 0x0200 -}; - -enum { - gestaltQDTextFeatures = 'qdtf', - gestaltWSIISupport = 0, - gestaltSbitFontSupport = 1, - gestaltAntiAliasedTextAvailable = 2, - gestaltOFA2available = 3, - gestaltCreatesAliasFontRsrc = 4, - gestaltNativeType1FontSupport = 5, - gestaltCanUseCGTextRendering = 6 -}; - - -enum { - gestaltQuickTimeConferencingInfo = 'qtci' -}; - -enum { - gestaltQuickTimeVersion = 'qtim', - gestaltQuickTime = 'qtim' -}; - -enum { - gestaltQuickTimeFeatures = 'qtrs', - gestaltPPCQuickTimeLibPresent = 0 -}; - -enum { - gestaltQuickTimeStreamingFeatures = 'qtsf' -}; - -enum { - gestaltQuickTimeStreamingVersion = 'qtst' -}; - -enum { - gestaltQuickTimeThreadSafeFeaturesAttr = 'qtth', - gestaltQuickTimeThreadSafeICM = 0, - gestaltQuickTimeThreadSafeMovieToolbox = 1, - gestaltQuickTimeThreadSafeMovieImport = 2, - gestaltQuickTimeThreadSafeMovieExport = 3, - gestaltQuickTimeThreadSafeGraphicsImport = 4, - gestaltQuickTimeThreadSafeGraphicsExport = 5, - gestaltQuickTimeThreadSafeMoviePlayback = 6 -}; - -enum { - gestaltQTVRMgrAttr = 'qtvr', - gestaltQTVRMgrPresent = 0, - gestaltQTVRObjMoviesPresent = 1, - gestaltQTVRCylinderPanosPresent = 2, - gestaltQTVRCubicPanosPresent = 3 -}; - -enum { - gestaltQTVRMgrVers = 'qtvv' -}; -enum { - gestaltPhysicalRAMSize = 'ram ' -}; - -enum { - gestaltPhysicalRAMSizeInMegabytes = 'ramm' -}; - -enum { - gestaltRBVAddr = 'rbv ' -}; - -enum { - gestaltROMSize = 'rom ' -}; - -enum { - gestaltROMVersion = 'romv' -}; - -enum { - gestaltResourceMgrAttr = 'rsrc', - gestaltPartialRsrcs = 0, - gestaltHasResourceOverrides = 1 -}; - -enum { - gestaltResourceMgrBugFixesAttrs = 'rmbg', - gestaltRMForceSysHeapRolledIn = 0, - gestaltRMFakeAppleMenuItemsRolledIn = 1, - gestaltSanityCheckResourceFiles = 2, - gestaltSupportsFSpResourceFileAlreadyOpenBit = 3, - gestaltRMSupportsFSCalls = 4, - gestaltRMTypeIndexOrderingReverse = 8 -}; - - -enum { - gestaltRealtimeMgrAttr = 'rtmr', - gestaltRealtimeMgrPresent = 0 -}; - - -enum { - gestaltSafeOFAttr = 'safe', - gestaltVMZerosPagesBit = 0, - gestaltInitHeapZerosOutHeapsBit = 1, - gestaltNewHandleReturnsZeroedMemoryBit = 2, - gestaltNewPtrReturnsZeroedMemoryBit = 3, - gestaltFileAllocationZeroedBlocksBit = 4 -}; - - -enum { - gestaltSCCReadAddr = 'sccr' -}; - -enum { - gestaltSCCWriteAddr = 'sccw' -}; - -enum { - gestaltScrapMgrAttr = 'scra', - gestaltScrapMgrTranslationAware = 0 -}; - -enum { - gestaltScriptMgrVersion = 'scri' -}; - -enum { - gestaltScriptCount = 'scr#' -}; - -enum { - gestaltSCSI = 'scsi', - gestaltAsyncSCSI = 0, - gestaltAsyncSCSIINROM = 1, - gestaltSCSISlotBoot = 2, - gestaltSCSIPollSIH = 3 -}; - -enum { - gestaltControlStripAttr = 'sdev', - gestaltControlStripExists = 0, - gestaltControlStripVersionFixed = 1, - gestaltControlStripUserFont = 2, - gestaltControlStripUserHotKey = 3 -}; - -enum { - gestaltSDPStandardDirectoryVersion = 'sdvr' -}; - -enum { - gestaltSerialAttr = 'ser ', - gestaltHasGPIaToDCDa = 0, - gestaltHasGPIaToRTxCa = 1, - gestaltHasGPIbToDCDb = 2, - gestaltHidePortA = 3, - gestaltHidePortB = 4, - gestaltPortADisabled = 5, - gestaltPortBDisabled = 6 -}; - -enum { - gestaltShutdownAttributes = 'shut', - gestaltShutdownHassdOnBootVolUnmount = 0 -}; - -enum { - gestaltNuBusConnectors = 'sltc' -}; - -enum { - gestaltSlotAttr = 'slot', - gestaltSlotMgrExists = 0, - gestaltNuBusPresent = 1, - gestaltSESlotPresent = 2, - gestaltSE30SlotPresent = 3, - gestaltPortableSlotPresent = 4 -}; - -enum { - gestaltFirstSlotNumber = 'slt1' -}; - -enum { - gestaltSoundAttr = 'snd ', - gestaltStereoCapability = 0, - gestaltStereoMixing = 1, - gestaltSoundIOMgrPresent = 3, - gestaltBuiltInSoundInput = 4, - gestaltHasSoundInputDevice = 5, - gestaltPlayAndRecord = 6, - gestalt16BitSoundIO = 7, - gestaltStereoInput = 8, - gestaltLineLevelInput = 9, - - gestaltSndPlayDoubleBuffer = 10, - gestaltMultiChannels = 11, - gestalt16BitAudioSupport = 12 -}; - -enum { - gestaltSplitOSAttr = 'spos', - gestaltSplitOSBootDriveIsNetworkVolume = 0, - gestaltSplitOSAware = 1, - gestaltSplitOSEnablerVolumeIsDifferentFromBootVolume = 2, - gestaltSplitOSMachineNameSetToNetworkNameTemp = 3, - gestaltSplitOSMachineNameStartupDiskIsNonPersistent = 5 -}; - -enum { - gestaltSMPSPSendLetterVersion = 'spsl' -}; - -enum { - gestaltSpeechRecognitionAttr = 'srta', - gestaltDesktopSpeechRecognition = 1, - gestaltTelephoneSpeechRecognition = 2 -}; - -enum { - gestaltSpeechRecognitionVersion = 'srtb' -}; - -enum { - gestaltSoftwareVendorCode = 'srad', - gestaltSoftwareVendorApple = 'Appl', - gestaltSoftwareVendorLicensee = 'Lcns' -}; - -enum { - gestaltStandardFileAttr = 'stdf', - gestaltStandardFile58 = 0, - gestaltStandardFileTranslationAware = 1, - gestaltStandardFileHasColorIcons = 2, - gestaltStandardFileUseGenericIcons = 3, - gestaltStandardFileHasDynamicVolumeAllocation = 4 -}; - -enum { - gestaltSysArchitecture = 'sysa', - gestalt68k = 1, - gestaltPowerPC = 2, - gestaltIntel = 10 -}; - -enum { - gestaltSystemUpdateVersion = 'sysu' -}; -enum { - gestaltSystemVersion = 'sysv', - gestaltSystemVersionMajor = 'sys1', - gestaltSystemVersionMinor = 'sys2', - gestaltSystemVersionBugFix = 'sys3' -} __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use NSProcessInfo's operatingSystemVersion property instead."))); - -enum { - gestaltToolboxTable = 'tbtt' -}; - -enum { - gestaltTextEditVersion = 'te ', - gestaltTE1 = 1, - gestaltTE2 = 2, - gestaltTE3 = 3, - gestaltTE4 = 4, - gestaltTE5 = 5 -}; - -enum { - gestaltTE6 = 6 -}; - -enum { - gestaltTEAttr = 'teat', - gestaltTEHasGetHiliteRgn = 0, - gestaltTESupportsInlineInput = 1, - gestaltTESupportsTextObjects = 2, - gestaltTEHasWhiteBackground = 3 -}; - -enum { - gestaltTeleMgrAttr = 'tele', - gestaltTeleMgrPresent = 0, - gestaltTeleMgrPowerPCSupport = 1, - gestaltTeleMgrSoundStreams = 2, - gestaltTeleMgrAutoAnswer = 3, - gestaltTeleMgrIndHandset = 4, - gestaltTeleMgrSilenceDetect = 5, - gestaltTeleMgrNewTELNewSupport = 6 -}; - -enum { - gestaltTermMgrAttr = 'term', - gestaltTermMgrPresent = 0, - gestaltTermMgrErrorString = 2 -}; - -enum { - gestaltThreadMgrAttr = 'thds', - gestaltThreadMgrPresent = 0, - gestaltSpecificMatchSupport = 1, - gestaltThreadsLibraryPresent = 2 -}; - -enum { - gestaltTimeMgrVersion = 'tmgr', - gestaltStandardTimeMgr = 1, - gestaltRevisedTimeMgr = 2, - gestaltExtendedTimeMgr = 3, - gestaltNativeTimeMgr = 4 -}; - -enum { - gestaltTSMTEVersion = 'tmTV', - gestaltTSMTE1 = 0x0100, - gestaltTSMTE15 = 0x0150, - gestaltTSMTE152 = 0x0152 -}; - -enum { - gestaltTSMTEAttr = 'tmTE', - gestaltTSMTEPresent = 0, - gestaltTSMTE = 0 -}; - -enum { - gestaltAVLTreeAttr = 'tree', - gestaltAVLTreePresentBit = 0, - gestaltAVLTreeSupportsHandleBasedTreeBit = 1, - gestaltAVLTreeSupportsTreeLockingBit = 2 -}; - -enum { - gestaltALMAttr = 'trip', - gestaltALMPresent = 0, - gestaltALMHasSFGroup = 1, - gestaltALMHasCFMSupport = 2, - gestaltALMHasRescanNotifiers = 3 -}; - -enum { - gestaltALMHasSFLocation = gestaltALMHasSFGroup -}; - -enum { - gestaltTSMgrVersion = 'tsmv', - gestaltTSMgr15 = 0x0150, - gestaltTSMgr20 = 0x0200, - gestaltTSMgr22 = 0x0220, - gestaltTSMgr23 = 0x0230 -}; - -enum { - gestaltTSMgrAttr = 'tsma', - gestaltTSMDisplayMgrAwareBit = 0, - gestaltTSMdoesTSMTEBit = 1 -}; - -enum { - gestaltSpeechAttr = 'ttsc', - gestaltSpeechMgrPresent = 0, - gestaltSpeechHasPPCGlue = 1 -}; - -enum { - gestaltTVAttr = 'tv ', - gestaltHasTVTuner = 0, - gestaltHasSoundFader = 1, - gestaltHasHWClosedCaptioning = 2, - gestaltHasIRRemote = 3, - gestaltHasVidDecoderScaler = 4, - gestaltHasStereoDecoder = 5, - gestaltHasSerialFader = 6, - gestaltHasFMTuner = 7, - gestaltHasSystemIRFunction = 8, - gestaltIRDisabled = 9, - gestaltINeedIRPowerOffConfirm = 10, - gestaltHasZoomedVideo = 11 -}; - - -enum { - gestaltATSUVersion = 'uisv', - gestaltOriginalATSUVersion = (1 << 16), - gestaltATSUUpdate1 = (2 << 16), - gestaltATSUUpdate2 = (3 << 16), - gestaltATSUUpdate3 = (4 << 16), - gestaltATSUUpdate4 = (5 << 16), - gestaltATSUUpdate5 = (6 << 16), - gestaltATSUUpdate6 = (7 << 16), - gestaltATSUUpdate7 = (8 << 16) -}; - -enum { - gestaltATSUFeatures = 'uisf', - gestaltATSUTrackingFeature = 0x00000001, - gestaltATSUMemoryFeature = 0x00000001, - gestaltATSUFallbacksFeature = 0x00000001, - gestaltATSUGlyphBoundsFeature = 0x00000001, - gestaltATSULineControlFeature = 0x00000001, - gestaltATSULayoutCreateAndCopyFeature = 0x00000001, - gestaltATSULayoutCacheClearFeature = 0x00000001, - gestaltATSUTextLocatorUsageFeature = 0x00000002, - gestaltATSULowLevelOrigFeatures = 0x00000004, - gestaltATSUFallbacksObjFeatures = 0x00000008, - gestaltATSUIgnoreLeadingFeature = 0x00000008, - gestaltATSUByCharacterClusterFeature = 0x00000010, - gestaltATSUAscentDescentControlsFeature = 0x00000010, - gestaltATSUHighlightInactiveTextFeature = 0x00000010, - gestaltATSUPositionToCursorFeature = 0x00000010, - gestaltATSUBatchBreakLinesFeature = 0x00000010, - gestaltATSUTabSupportFeature = 0x00000010, - gestaltATSUDirectAccess = 0x00000010, - gestaltATSUDecimalTabFeature = 0x00000020, - gestaltATSUBiDiCursorPositionFeature = 0x00000020, - gestaltATSUNearestCharLineBreakFeature = 0x00000020, - gestaltATSUHighlightColorControlFeature = 0x00000020, - gestaltATSUUnderlineOptionsStyleFeature = 0x00000020, - gestaltATSUStrikeThroughStyleFeature = 0x00000020, - gestaltATSUDropShadowStyleFeature = 0x00000020 -}; - -enum { - gestaltUSBAttr = 'usb ', - gestaltUSBPresent = 0, - gestaltUSBHasIsoch = 1 -}; - -enum { - gestaltUSBVersion = 'usbv' -}; - -enum { - gestaltVersion = 'vers', - gestaltValueImplementedVers = 5 -}; - -enum { - gestaltVIA1Addr = 'via1' -}; - -enum { - gestaltVIA2Addr = 'via2' -}; - -enum { - gestaltVMAttr = 'vm ', - gestaltVMPresent = 0, - gestaltVMHasLockMemoryForOutput = 1, - gestaltVMFilemappingOn = 3, - gestaltVMHasPagingControl = 4 -}; - -enum { - gestaltVMInfoType = 'vmin', - - gestaltVMInfoSizeStorageType = 0, - gestaltVMInfoSizeType = 1, - gestaltVMInfoSimpleType = 2, - gestaltVMInfoNoneType = 3 -}; - -enum { - gestaltVMBackingStoreFileRefNum = 'vmbs' -}; - - - -enum { - gestaltALMVers = 'walk' -}; - -enum { - gestaltWindowMgrAttr = 'wind', - gestaltWindowMgrPresent = (1L << 0), - - - gestaltWindowMgrPresentBit = 0, - gestaltExtendedWindowAttributes = 1, - gestaltExtendedWindowAttributesBit = 1, - gestaltHasFloatingWindows = 2, - gestaltHasFloatingWindowsBit = 2, - gestaltHasWindowBuffering = 3, - gestaltHasWindowBufferingBit = 3, - gestaltWindowLiveResizeBit = 4, - gestaltWindowMinimizeToDockBit = 5, - gestaltHasWindowShadowsBit = 6, - gestaltSheetsAreWindowModalBit = 7, - gestaltFrontWindowMayBeHiddenBit = 8, - - gestaltWindowMgrPresentMask = (1L << gestaltWindowMgrPresentBit), - gestaltExtendedWindowAttributesMask = (1L << gestaltExtendedWindowAttributesBit), - gestaltHasFloatingWindowsMask = (1L << gestaltHasFloatingWindowsBit), - gestaltHasWindowBufferingMask = (1L << gestaltHasWindowBufferingBit), - gestaltWindowLiveResizeMask = (1L << gestaltWindowLiveResizeBit), - gestaltWindowMinimizeToDockMask = (1L << gestaltWindowMinimizeToDockBit), - gestaltHasWindowShadowsMask = (1L << gestaltHasWindowShadowsBit), - gestaltSheetsAreWindowModalMask = (1L << gestaltSheetsAreWindowModalBit), - gestaltFrontWindowMayBeHiddenMask = (1L << gestaltFrontWindowMayBeHiddenBit) -}; - -enum { - gestaltHasSingleWindowModeBit = 8, - gestaltHasSingleWindowModeMask = (1L << gestaltHasSingleWindowModeBit) -}; - - - - - - -enum { - gestaltX86Features = 'x86f', - gestaltX86HasFPU = 0, - gestaltX86HasVME = 1, - gestaltX86HasDE = 2, - gestaltX86HasPSE = 3, - gestaltX86HasTSC = 4, - gestaltX86HasMSR = 5, - gestaltX86HasPAE = 6, - gestaltX86HasMCE = 7, - gestaltX86HasCX8 = 8, - gestaltX86HasAPIC = 9, - gestaltX86HasSEP = 11, - gestaltX86HasMTRR = 12, - gestaltX86HasPGE = 13, - gestaltX86HasMCA = 14, - gestaltX86HasCMOV = 15, - - gestaltX86HasPAT = 16, - gestaltX86HasPSE36 = 17, - gestaltX86HasPSN = 18, - gestaltX86HasCLFSH = 19, - gestaltX86Serviced20 = 20, - gestaltX86HasDS = 21, - gestaltX86ResACPI = 22, - gestaltX86HasMMX = 23, - gestaltX86HasFXSR = 24, - gestaltX86HasSSE = 25, - gestaltX86HasSSE2 = 26, - gestaltX86HasSS = 27, - gestaltX86HasHTT = 28, - gestaltX86HasTM = 29 -}; - - - - -enum { - gestaltX86AdditionalFeatures = 'x86a', - gestaltX86HasSSE3 = 0, - gestaltX86HasMONITOR = 3, - gestaltX86HasDSCPL = 4, - gestaltX86HasVMX = 5, - gestaltX86HasSMX = 6, - gestaltX86HasEST = 7, - gestaltX86HasTM2 = 8, - gestaltX86HasSupplementalSSE3 = 9, - gestaltX86HasCID = 10, - gestaltX86HasCX16 = 13, - gestaltX86HasxTPR = 14 -}; - -enum { - gestaltTranslationAttr = 'xlat', - gestaltTranslationMgrExists = 0, - gestaltTranslationMgrHintOrder = 1, - gestaltTranslationPPCAvail = 2, - gestaltTranslationGetPathAPIAvail = 3 -}; - -enum { - gestaltExtToolboxTable = 'xttt' -}; - -enum { - gestaltUSBPrinterSharingVersion = 'zak ', - gestaltUSBPrinterSharingVersionMask = 0x0000FFFF, - gestaltUSBPrinterSharingAttr = 'zak ', - gestaltUSBPrinterSharingAttrMask = (int)0xFFFF0000, - gestaltUSBPrinterSharingAttrRunning = (int)0x80000000, - gestaltUSBPrinterSharingAttrBooted = 0x40000000 -}; - - -enum { - gestaltWorldScriptIIVersion = 'doub', - gestaltWorldScriptIIAttr = 'wsat', - gestaltWSIICanPrintWithoutPrGeneralBit = 0 -}; - - - - - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - -enum { - kMacMemoryMaximumMemoryManagerBlockSize = 0x7FFFFFF0 -}; -enum { - defaultPhysicalEntryCount = 8 -}; - -enum { - - kPageInMemory = 0, - kPageOnDisk = 1, - kNotPaged = 2 -}; - -enum { - - k32BitHeap = 1, - kNewStyleHeap = 2, - kNewDebugHeap = 4 -}; - - - - - -enum { - kHandleIsResourceBit = 5, - kHandlePurgeableBit = 6, - kHandleLockedBit = 7 -}; - - -enum { - kHandleIsResourceMask = 0x20, - kHandlePurgeableMask = 0x40, - kHandleLockedMask = 0x80 -}; -extern OSErr -MemError(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt16 -LMGetMemErr(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -LMSetMemErr(SInt16 value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -NewHandle(Size byteCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -NewHandleClear(Size byteCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -RecoverHandle(Ptr p) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Ptr -NewPtr(Size byteCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Ptr -NewPtrClear(Size byteCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -NewEmptyHandle(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -HLock(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -HLockHi(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -HUnlock(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -TempNewHandle( - Size logicalSize, - OSErr * resultCode) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposePtr(Ptr p) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Size -GetPtrSize(Ptr p) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetPtrSize( - Ptr p, - Size newSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeHandle(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetHandleSize( - Handle h, - Size newSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Size -GetHandleSize(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -ReallocateHandle( - Handle h, - Size byteCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -EmptyHandle(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -HSetRBit(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -HClrRBit(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt8 -HGetState(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -HSetState( - Handle h, - SInt8 flags) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -HandToHand(Handle * theHndl) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -PtrToXHand( - const void * srcPtr, - Handle dstHndl, - long size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -PtrToHand( - const void * srcPtr, - Handle * dstHndl, - long size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -HandAndHand( - Handle hand1, - Handle hand2) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -PtrAndHand( - const void * ptr1, - Handle hand2, - long size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Boolean -IsHeapValid(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Boolean -IsHandleValid(Handle h) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Boolean -IsPointerValid(Ptr p) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -#pragma pack(pop) - - -} - - - -extern "C" { -extern SInt64 -S64Max(void); -extern SInt64 -S64Min(void); -extern SInt64 -S64Add( - SInt64 left, - SInt64 right); -extern SInt64 -S64Subtract( - SInt64 left, - SInt64 right); -extern SInt64 -S64Negate(SInt64 value); -extern SInt64 -S64Multiply( - SInt64 left, - SInt64 right); -extern SInt64 -S64Mod( - SInt64 dividend, - SInt64 divisor); -extern SInt64 -S64Divide( - SInt64 dividend, - SInt64 divisor, - SInt64 * remainder); -extern SInt64 -S64Div( - SInt64 dividend, - SInt64 divisor); -extern SInt64 -S64Set(SInt32 value); -extern SInt64 -S64SetU(UInt32 value); -extern SInt32 -S32Set(SInt64 value); -extern Boolean -S64And( - SInt64 left, - SInt64 right); -extern Boolean -S64Or( - SInt64 left, - SInt64 right); -extern Boolean -S64Eor( - SInt64 left, - SInt64 right); -extern Boolean -S64Not(SInt64 value); -extern SInt32 -S64Compare( - SInt64 left, - SInt64 right) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt64 -S64BitwiseAnd( - SInt64 left, - SInt64 right); -extern SInt64 -S64BitwiseOr( - SInt64 left, - SInt64 right); -extern SInt64 -S64BitwiseEor( - SInt64 left, - SInt64 right); -extern SInt64 -S64BitwiseNot(SInt64 value); -extern SInt64 -S64ShiftRight( - SInt64 value, - UInt32 shift); -extern SInt64 -S64ShiftLeft( - SInt64 value, - UInt32 shift); -extern long double -SInt64ToLongDouble(SInt64 value); -extern SInt64 -LongDoubleToSInt64(long double value); -extern UInt64 -U64Max(void); -extern UInt64 -U64Add( - UInt64 left, - UInt64 right); -extern UInt64 -U64Subtract( - UInt64 left, - UInt64 right); -extern UInt64 -U64Multiply( - UInt64 left, - UInt64 right); -extern UInt64 -U64Mod( - UInt64 dividend, - UInt64 divisor); -extern UInt64 -U64Divide( - UInt64 dividend, - UInt64 divisor, - UInt64 * remainder); -extern UInt64 -U64Div( - UInt64 dividend, - UInt64 divisor); -extern UInt64 -U64Set(SInt32 value); -extern UInt64 -U64SetU(UInt32 value); -extern UInt32 -U32SetU(UInt64 value); -extern Boolean -U64And( - UInt64 left, - UInt64 right); -extern Boolean -U64Or( - UInt64 left, - UInt64 right); -extern Boolean -U64Eor( - UInt64 left, - UInt64 right); -extern Boolean -U64Not(UInt64 value); -extern SInt32 -U64Compare( - UInt64 left, - UInt64 right) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt64 -U64BitwiseAnd( - UInt64 left, - UInt64 right); -extern UInt64 -U64BitwiseOr( - UInt64 left, - UInt64 right); -extern UInt64 -U64BitwiseEor( - UInt64 left, - UInt64 right); -extern UInt64 -U64BitwiseNot(UInt64 value); -extern UInt64 -U64ShiftRight( - UInt64 value, - UInt32 shift); -extern UInt64 -U64ShiftLeft( - UInt64 value, - UInt32 shift); -extern long double -UInt64ToLongDouble(UInt64 value); -extern UInt64 -LongDoubleToUInt64(long double value); -extern SInt64 -UInt64ToSInt64(UInt64 value); -extern UInt64 -SInt64ToUInt64(SInt64 value); - static inline wide SInt64ToWide(SInt64 s) { wide result; result.hi = (SInt32)(((UInt64)s >> 32) & 0xffffffffUL); result.lo = (UInt32)((UInt64)s & 0xffffffffUL); return result; } - static inline SInt64 WideToSInt64(wide w) { SInt64 result = w.hi; result = (result << 32) | w.lo; return result; } - - static inline UnsignedWide UInt64ToUnsignedWide(UInt64 u) { UnsignedWide result; result.hi = (UInt32)((u >> 32) & 0xffffffffUL); result.lo = (UInt32)(u & 0xffffffffUL); return result; } - static inline UInt64 UnsignedWideToUInt64(UnsignedWide uw) { UInt64 result = uw.hi; result = (result << 32) | uw.lo; return result; } -} -extern "C" { -extern OSStatus -CSBackupSetItemExcluded( - CFURLRef item, - Boolean exclude, - Boolean excludeByPath) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -CSBackupIsItemExcluded( - CFURLRef item, - Boolean * excludeByPath) __attribute__((availability(macosx,introduced=10.5))); - - - - -} - - - -extern "C" { - - - - - - -enum { - kCSDiskSpaceRecoveryOptionNoUI = (1 << 0) -}; - -typedef int CSDiskSpaceRecoveryOptions; - - -typedef void (*CSDiskSpaceRecoveryCallback)(Boolean succeeded, UInt64 bytesFree, CFErrorRef error); -extern void -CSDiskSpaceStartRecovery( - CFURLRef volumeURL, - UInt64 bytesNeeded, - CSDiskSpaceRecoveryOptions options, - CFUUIDRef * outOperationUUID, - dispatch_queue_t callbackQueue, - CSDiskSpaceRecoveryCallback callback) __attribute__((availability(macosx,introduced=10.7))); -extern void -CSDiskSpaceCancelRecovery(CFUUIDRef operationUUID) __attribute__((availability(macosx,introduced=10.7))); -extern UInt64 -CSDiskSpaceGetRecoveryEstimate(CFURLRef volumeURL) __attribute__((availability(macosx,introduced=10.7))); -} - - - -extern "C" { - - -#pragma pack(push, 2) -typedef SInt16 ToggleResults; -enum { - - toggleUndefined = 0, - toggleOK = 1, - toggleBadField = 2, - toggleBadDelta = 3, - toggleBadChar = 4, - toggleUnknown = 5, - toggleBadNum = 6, - toggleOutOfRange = 7, - toggleErr3 = 7, - toggleErr4 = 8, - toggleErr5 = 9 -}; - -enum { - - smallDateBit = 31, - togChar12HourBit = 30, - togCharZCycleBit = 29, - togDelta12HourBit = 28, - genCdevRangeBit = 27, - validDateFields = -1, - maxDateField = 10 -}; - -enum { - eraMask = 0x0001, - yearMask = 0x0002, - monthMask = 0x0004, - dayMask = 0x0008, - hourMask = 0x0010, - minuteMask = 0x0020, - secondMask = 0x0040, - dayOfWeekMask = 0x0080, - dayOfYearMask = 0x0100, - weekOfYearMask = 0x0200, - pmMask = 0x0400, - dateStdMask = 0x007F -}; - -typedef SInt8 LongDateField; -enum { - eraField = 0, - yearField = 1, - monthField = 2, - dayField = 3, - hourField = 4, - minuteField = 5, - secondField = 6, - dayOfWeekField = 7, - dayOfYearField = 8, - weekOfYearField = 9, - pmField = 10, - res1Field = 11, - res2Field = 12, - res3Field = 13 -}; - -typedef SInt8 DateForm; -enum { - shortDate = 0, - longDate = 1, - abbrevDate = 2 -}; - -enum { - - fatalDateTime = 0x8000, - longDateFound = 1, - leftOverChars = 2, - sepNotIntlSep = 4, - fieldOrderNotIntl = 8, - extraneousStrings = 16, - tooManySeps = 32, - sepNotConsistent = 64, - tokenErr = 0x8100, - cantReadUtilities = 0x8200, - dateTimeNotFound = 0x8400, - dateTimeInvalid = 0x8800 -}; - -typedef short StringToDateStatus; -typedef StringToDateStatus String2DateStatus; -struct DateCacheRecord { - short hidden[256]; -}; -typedef struct DateCacheRecord DateCacheRecord; -typedef DateCacheRecord * DateCachePtr; -struct DateTimeRec { - short year; - short month; - short day; - short hour; - short minute; - short second; - short dayOfWeek; -}; -typedef struct DateTimeRec DateTimeRec; - -typedef SInt64 LongDateTime; -union LongDateCvt { - SInt64 c; - struct { - UInt32 lLow; - UInt32 lHigh; - } hl; -}; -typedef union LongDateCvt LongDateCvt; - - -union LongDateRec { - struct { - short era; - short year; - short month; - short day; - short hour; - short minute; - short second; - short dayOfWeek; - short dayOfYear; - short weekOfYear; - short pm; - short res1; - short res2; - short res3; - } ld; - short list[14]; - struct { - short eraAlt; - DateTimeRec oldDate; - } od; -}; -typedef union LongDateRec LongDateRec; - -typedef SInt8 DateDelta; -struct TogglePB { - long togFlags; - ResType amChars; - ResType pmChars; - long reserved[4]; -}; -typedef struct TogglePB TogglePB; -extern OSStatus -UCConvertUTCDateTimeToCFAbsoluteTime( - const UTCDateTime * iUTCDate, - CFAbsoluteTime * oCFTime) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -UCConvertSecondsToCFAbsoluteTime( - UInt32 iSeconds, - CFAbsoluteTime * oCFTime) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -UCConvertLongDateTimeToCFAbsoluteTime( - LongDateTime iLongTime, - CFAbsoluteTime * oCFTime) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -UCConvertCFAbsoluteTimeToUTCDateTime( - CFAbsoluteTime iCFTime, - UTCDateTime * oUTCDate) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -UCConvertCFAbsoluteTimeToSeconds( - CFAbsoluteTime iCFTime, - UInt32 * oSeconds) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -UCConvertCFAbsoluteTimeToLongDateTime( - CFAbsoluteTime iCFTime, - LongDateTime * oLongDate) __attribute__((availability(macosx,introduced=10.2))); -#pragma pack(pop) - - -} -extern "C" { - - -#pragma pack(push, 2) - -enum { - - sortsBefore = -1, - sortsEqual = 0, - sortsAfter = 1 -}; - -enum { - dummyType = 0, - vType = 1, - ioQType = 2, - drvQType = 3, - evType = 4, - fsQType = 5, - sIQType = 6, - dtQType = 7, - nmType = 8 -}; - -typedef SignedByte QTypes; -struct QElem { - struct QElem * qLink; - short qType; - short qData[1]; -}; -typedef struct QElem QElem; -typedef QElem * QElemPtr; -struct QHdr { - volatile short qFlags; - volatile QElemPtr qHead; - volatile QElemPtr qTail; -}; -typedef struct QHdr QHdr; -typedef QHdr * QHdrPtr; -struct MachineLocation { - Fract latitude; - Fract longitude; - union { - - - - long gmtDelta; - struct { - - SInt8 pad[3]; - - SInt8 Delta; - } dls; - } u; -}; -typedef struct MachineLocation MachineLocation; -extern Boolean -IsMetric(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -Delay( - unsigned long numTicks, - unsigned long * finalTicks) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -Enqueue( - QElemPtr qElement, - QHdrPtr qHeader) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -Dequeue( - QElemPtr qElement, - QHdrPtr qHeader) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -ReadLocation(MachineLocation * loc) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt32 -TickCount(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern CFStringRef -CSCopyUserName(Boolean useShortName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern CFStringRef -CSCopyMachineName(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - -enum { - useFree = 0, - useATalk = 1, - useAsync = 2, - useExtClk = 3, - useMIDI = 4 -}; - -enum { - false32b = 0, - true32b = 1 -} __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -typedef void * SysPPtr; -typedef void ( * DeferredTaskProcPtr)(long dtParam); -typedef DeferredTaskProcPtr DeferredTaskUPP; -extern DeferredTaskUPP -NewDeferredTaskUPP(DeferredTaskProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeDeferredTaskUPP(DeferredTaskUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeDeferredTaskUPP( - long dtParam, - DeferredTaskUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline DeferredTaskUPP NewDeferredTaskUPP(DeferredTaskProcPtr userRoutine) { return userRoutine; } - inline void DisposeDeferredTaskUPP(DeferredTaskUPP) { } - inline void InvokeDeferredTaskUPP(long dtParam, DeferredTaskUPP userUPP) { (*userUPP)(dtParam); } - - - - - - - -struct DeferredTask { - volatile QElemPtr qLink; - short qType; - volatile short dtFlags; - DeferredTaskUPP dtAddr; - long dtParam; - long dtReserved; -}; -typedef struct DeferredTask DeferredTask; -typedef DeferredTask * DeferredTaskPtr; -#pragma pack(pop) - - -} -struct vm_statistics { - natural_t free_count; - natural_t active_count; - natural_t inactive_count; - natural_t wire_count; - natural_t zero_fill_count; - natural_t reactivations; - natural_t pageins; - natural_t pageouts; - natural_t faults; - natural_t cow_faults; - natural_t lookups; - natural_t hits; - - - natural_t purgeable_count; - natural_t purges; - natural_t speculative_count; -}; - - -typedef struct vm_statistics *vm_statistics_t; -typedef struct vm_statistics vm_statistics_data_t; -struct vm_statistics64 { - natural_t free_count; - natural_t active_count; - natural_t inactive_count; - natural_t wire_count; - uint64_t zero_fill_count; - uint64_t reactivations; - uint64_t pageins; - uint64_t pageouts; - uint64_t faults; - uint64_t cow_faults; - uint64_t lookups; - uint64_t hits; - uint64_t purges; - natural_t purgeable_count; - - - - - - - natural_t speculative_count; - - - uint64_t decompressions; - uint64_t compressions; - uint64_t swapins; - uint64_t swapouts; - natural_t compressor_page_count; - natural_t throttled_count; - natural_t external_page_count; - natural_t internal_page_count; - uint64_t total_uncompressed_pages_in_compressor; -} __attribute__((aligned(8))); - -typedef struct vm_statistics64 *vm_statistics64_t; -typedef struct vm_statistics64 vm_statistics64_data_t; -struct vm_extmod_statistics { - int64_t task_for_pid_count; - int64_t task_for_pid_caller_count; - int64_t thread_creation_count; - int64_t thread_creation_caller_count; - int64_t thread_set_state_count; - int64_t thread_set_state_caller_count; -} __attribute__((aligned(8))); - -typedef struct vm_extmod_statistics *vm_extmod_statistics_t; -typedef struct vm_extmod_statistics vm_extmod_statistics_data_t; - -typedef struct vm_purgeable_stat { - uint64_t count; - uint64_t size; -}vm_purgeable_stat_t; - -struct vm_purgeable_info { - vm_purgeable_stat_t fifo_data[8]; - vm_purgeable_stat_t obsolete_data; - vm_purgeable_stat_t lifo_data[8]; -}; - -typedef struct vm_purgeable_info *vm_purgeable_info_t; -typedef integer_t cpu_type_t; -typedef integer_t cpu_subtype_t; -typedef integer_t cpu_threadtype_t; - - - - - - - - -typedef integer_t *host_info_t; -typedef integer_t *host_info64_t; - - -typedef integer_t host_info_data_t[(1024)]; - - -typedef char kernel_version_t[(512)]; - - -typedef char kernel_boot_info_t[(4096)]; - - - - - -typedef integer_t host_flavor_t; -#pragma pack(4) - -struct host_basic_info { - integer_t max_cpus; - integer_t avail_cpus; - natural_t memory_size; - cpu_type_t cpu_type; - cpu_subtype_t cpu_subtype; - cpu_threadtype_t cpu_threadtype; - integer_t physical_cpu; - integer_t physical_cpu_max; - integer_t logical_cpu; - integer_t logical_cpu_max; - uint64_t max_mem; -}; - -#pragma pack() - -typedef struct host_basic_info host_basic_info_data_t; -typedef struct host_basic_info *host_basic_info_t; - - - -struct host_sched_info { - integer_t min_timeout; - integer_t min_quantum; -}; - -typedef struct host_sched_info host_sched_info_data_t; -typedef struct host_sched_info *host_sched_info_t; - - - -struct kernel_resource_sizes { - natural_t task; - natural_t thread; - natural_t port; - natural_t memory_region; - natural_t memory_object; -}; - -typedef struct kernel_resource_sizes kernel_resource_sizes_data_t; -typedef struct kernel_resource_sizes *kernel_resource_sizes_t; - - - -struct host_priority_info { - integer_t kernel_priority; - integer_t system_priority; - integer_t server_priority; - integer_t user_priority; - integer_t depress_priority; - integer_t idle_priority; - integer_t minimum_priority; - integer_t maximum_priority; -}; - -typedef struct host_priority_info host_priority_info_data_t; -typedef struct host_priority_info *host_priority_info_t; -struct host_load_info { - integer_t avenrun[3]; - integer_t mach_factor[3]; -}; - -typedef struct host_load_info host_load_info_data_t; -typedef struct host_load_info *host_load_info_t; - - - -typedef struct vm_purgeable_info host_purgable_info_data_t; -typedef struct vm_purgeable_info *host_purgable_info_t; -struct host_cpu_load_info { - natural_t cpu_ticks[4]; -}; - -typedef struct host_cpu_load_info host_cpu_load_info_data_t; -typedef struct host_cpu_load_info *host_cpu_load_info_t; - - -typedef int vm_prot_t; -typedef unsigned vm_sync_t; -typedef vm_offset_t pointer_t; -typedef vm_offset_t vm_address_t; - - - - - - - -typedef uint64_t addr64_t; -typedef uint32_t reg64_t; - - - - - - -typedef uint32_t ppnum_t; - - - - -typedef mach_port_t vm_map_t; -typedef uint64_t vm_object_offset_t; -typedef uint64_t vm_object_size_t; - - - - -typedef mach_port_t upl_t; -typedef mach_port_t vm_named_entry_t; - - - - - - -typedef unsigned long long memory_object_offset_t; -typedef unsigned long long memory_object_size_t; -typedef natural_t memory_object_cluster_size_t; -typedef natural_t * memory_object_fault_info_t; - -typedef unsigned long long vm_object_id_t; - - - - - - - -typedef mach_port_t memory_object_t; -typedef mach_port_t memory_object_control_t; - - -typedef memory_object_t *memory_object_array_t; - - - - -typedef mach_port_t memory_object_name_t; - - - -typedef mach_port_t memory_object_default_t; -typedef int memory_object_copy_strategy_t; -typedef int memory_object_return_t; -typedef int *memory_object_info_t; -typedef int memory_object_flavor_t; -typedef int memory_object_info_data_t[(1024)]; - - - - - - - -struct memory_object_perf_info { - memory_object_cluster_size_t cluster_size; - boolean_t may_cache; -}; - -struct memory_object_attr_info { - memory_object_copy_strategy_t copy_strategy; - memory_object_cluster_size_t cluster_size; - boolean_t may_cache_object; - boolean_t temporary; -}; - -struct memory_object_behave_info { - memory_object_copy_strategy_t copy_strategy; - boolean_t temporary; - boolean_t invalidate; - boolean_t silent_overwrite; - boolean_t advisory_pageout; -}; - - -typedef struct memory_object_behave_info *memory_object_behave_info_t; -typedef struct memory_object_behave_info memory_object_behave_info_data_t; - -typedef struct memory_object_perf_info *memory_object_perf_info_t; -typedef struct memory_object_perf_info memory_object_perf_info_data_t; - -typedef struct memory_object_attr_info *memory_object_attr_info_t; -typedef struct memory_object_attr_info memory_object_attr_info_data_t; - -struct x86_state_hdr { - int flavor; - int count; -}; -typedef struct x86_state_hdr x86_state_hdr_t; -typedef struct __darwin_i386_thread_state i386_thread_state_t; - - - -typedef struct __darwin_i386_thread_state x86_thread_state32_t; - - - - - - -typedef struct __darwin_i386_float_state i386_float_state_t; - - - -typedef struct __darwin_i386_float_state x86_float_state32_t; - - - -typedef struct __darwin_i386_avx_state x86_avx_state32_t; - - - - - - -typedef struct __darwin_i386_exception_state i386_exception_state_t; - - - -typedef struct __darwin_i386_exception_state x86_exception_state32_t; - - - - - -typedef struct __darwin_x86_debug_state32 x86_debug_state32_t; - - - - - -typedef struct __darwin_x86_thread_state64 x86_thread_state64_t; - - - -typedef struct __darwin_x86_float_state64 x86_float_state64_t; - - - -typedef struct __darwin_x86_avx_state64 x86_avx_state64_t; - - - -typedef struct __darwin_x86_exception_state64 x86_exception_state64_t; - - - - - -typedef struct __darwin_x86_debug_state64 x86_debug_state64_t; -struct x86_thread_state { - x86_state_hdr_t tsh; - union { - x86_thread_state32_t ts32; - x86_thread_state64_t ts64; - } uts; -}; - -struct x86_float_state { - x86_state_hdr_t fsh; - union { - x86_float_state32_t fs32; - x86_float_state64_t fs64; - } ufs; -}; - -struct x86_exception_state { - x86_state_hdr_t esh; - union { - x86_exception_state32_t es32; - x86_exception_state64_t es64; - } ues; -}; - -struct x86_debug_state { - x86_state_hdr_t dsh; - union { - x86_debug_state32_t ds32; - x86_debug_state64_t ds64; - } uds; -}; - -struct x86_avx_state { - x86_state_hdr_t ash; - union { - x86_avx_state32_t as32; - x86_avx_state64_t as64; - } ufs; -}; - -typedef struct x86_thread_state x86_thread_state_t; - - - -typedef struct x86_float_state x86_float_state_t; - - - -typedef struct x86_exception_state x86_exception_state_t; - - - -typedef struct x86_debug_state x86_debug_state_t; - - - -typedef struct x86_avx_state x86_avx_state_t; - - - - - -typedef natural_t *thread_state_t; - - -typedef natural_t thread_state_data_t[(224)]; - - - - - -typedef int thread_state_flavor_t; -typedef thread_state_flavor_t *thread_state_flavor_array_t; - - - - - -typedef int exception_type_t; -typedef integer_t exception_data_type_t; -typedef int64_t mach_exception_data_type_t; -typedef int exception_behavior_t; -typedef exception_data_type_t *exception_data_t; -typedef mach_exception_data_type_t *mach_exception_data_t; -typedef unsigned int exception_mask_t; -typedef exception_mask_t *exception_mask_array_t; -typedef exception_behavior_t *exception_behavior_array_t; -typedef thread_state_flavor_t *exception_flavor_array_t; -typedef mach_port_t *exception_port_array_t; -typedef mach_exception_data_type_t mach_exception_code_t; -typedef mach_exception_data_type_t mach_exception_subcode_t; - -typedef mach_port_t mach_voucher_t; - - -typedef mach_port_name_t mach_voucher_name_t; - - -typedef mach_voucher_name_t *mach_voucher_name_array_t; - - - - - - -typedef mach_voucher_t ipc_voucher_t; - - - - - - - -typedef uint32_t mach_voucher_selector_t; -typedef uint32_t mach_voucher_attr_key_t; -typedef mach_voucher_attr_key_t *mach_voucher_attr_key_array_t; -typedef uint8_t *mach_voucher_attr_content_t; -typedef uint32_t mach_voucher_attr_content_size_t; - - - - - -typedef uint32_t mach_voucher_attr_command_t; -typedef uint32_t mach_voucher_attr_recipe_command_t; -typedef mach_voucher_attr_recipe_command_t *mach_voucher_attr_recipe_command_array_t; -#pragma pack(1) - -typedef struct mach_voucher_attr_recipe_data { - mach_voucher_attr_key_t key; - mach_voucher_attr_recipe_command_t command; - mach_voucher_name_t previous_voucher; - mach_voucher_attr_content_size_t content_size; - uint8_t content[]; -} mach_voucher_attr_recipe_data_t; -typedef mach_voucher_attr_recipe_data_t *mach_voucher_attr_recipe_t; -typedef mach_msg_type_number_t mach_voucher_attr_recipe_size_t; - - -typedef uint8_t *mach_voucher_attr_raw_recipe_t; -typedef mach_voucher_attr_raw_recipe_t mach_voucher_attr_raw_recipe_array_t; -typedef mach_msg_type_number_t mach_voucher_attr_raw_recipe_size_t; -typedef mach_msg_type_number_t mach_voucher_attr_raw_recipe_array_size_t; - -#pragma pack() -typedef mach_port_t mach_voucher_attr_manager_t; -typedef mach_port_t mach_voucher_attr_control_t; - - - - - - - -typedef mach_port_t ipc_voucher_attr_manager_t; -typedef mach_port_t ipc_voucher_attr_control_t; -typedef uint64_t mach_voucher_attr_value_handle_t; -typedef mach_voucher_attr_value_handle_t *mach_voucher_attr_value_handle_array_t; - -typedef mach_msg_type_number_t mach_voucher_attr_value_handle_array_size_t; - - -typedef uint32_t mach_voucher_attr_value_reference_t; - - -typedef uint32_t mach_voucher_attr_control_flags_t; -typedef uint32_t mach_voucher_attr_importance_refs; - - - - -typedef integer_t *processor_info_t; -typedef integer_t *processor_info_array_t; - - -typedef integer_t processor_info_data_t[(1024)]; - - -typedef integer_t *processor_set_info_t; - - -typedef integer_t processor_set_info_data_t[(1024)]; - - - - -typedef int processor_flavor_t; - - - - - -struct processor_basic_info { - cpu_type_t cpu_type; - cpu_subtype_t cpu_subtype; - boolean_t running; - int slot_num; - boolean_t is_master; -}; - -typedef struct processor_basic_info processor_basic_info_data_t; -typedef struct processor_basic_info *processor_basic_info_t; - - - -struct processor_cpu_load_info { - unsigned int cpu_ticks[4]; -}; - -typedef struct processor_cpu_load_info processor_cpu_load_info_data_t; -typedef struct processor_cpu_load_info *processor_cpu_load_info_t; -typedef int processor_set_flavor_t; - - -struct processor_set_basic_info { - int processor_count; - int default_policy; -}; - -typedef struct processor_set_basic_info processor_set_basic_info_data_t; -typedef struct processor_set_basic_info *processor_set_basic_info_t; - - - - - -struct processor_set_load_info { - int task_count; - int thread_count; - integer_t load_average; - integer_t mach_factor; -}; - -typedef struct processor_set_load_info processor_set_load_info_data_t; -typedef struct processor_set_load_info *processor_set_load_info_t; -typedef int policy_t; -typedef integer_t *policy_info_t; -typedef integer_t *policy_base_t; -typedef integer_t *policy_limit_t; -struct policy_timeshare_base { - integer_t base_priority; -}; -struct policy_timeshare_limit { - integer_t max_priority; -}; -struct policy_timeshare_info { - integer_t max_priority; - integer_t base_priority; - integer_t cur_priority; - boolean_t depressed; - integer_t depress_priority; -}; - -typedef struct policy_timeshare_base *policy_timeshare_base_t; -typedef struct policy_timeshare_limit *policy_timeshare_limit_t; -typedef struct policy_timeshare_info *policy_timeshare_info_t; - -typedef struct policy_timeshare_base policy_timeshare_base_data_t; -typedef struct policy_timeshare_limit policy_timeshare_limit_data_t; -typedef struct policy_timeshare_info policy_timeshare_info_data_t; -struct policy_rr_base { - integer_t base_priority; - integer_t quantum; -}; -struct policy_rr_limit { - integer_t max_priority; -}; -struct policy_rr_info { - integer_t max_priority; - integer_t base_priority; - integer_t quantum; - boolean_t depressed; - integer_t depress_priority; -}; - -typedef struct policy_rr_base *policy_rr_base_t; -typedef struct policy_rr_limit *policy_rr_limit_t; -typedef struct policy_rr_info *policy_rr_info_t; - -typedef struct policy_rr_base policy_rr_base_data_t; -typedef struct policy_rr_limit policy_rr_limit_data_t; -typedef struct policy_rr_info policy_rr_info_data_t; -struct policy_fifo_base { - integer_t base_priority; -}; -struct policy_fifo_limit { - integer_t max_priority; -}; -struct policy_fifo_info { - integer_t max_priority; - integer_t base_priority; - boolean_t depressed; - integer_t depress_priority; -}; - -typedef struct policy_fifo_base *policy_fifo_base_t; -typedef struct policy_fifo_limit *policy_fifo_limit_t; -typedef struct policy_fifo_info *policy_fifo_info_t; - -typedef struct policy_fifo_base policy_fifo_base_data_t; -typedef struct policy_fifo_limit policy_fifo_limit_data_t; -typedef struct policy_fifo_info policy_fifo_info_data_t; -struct policy_bases { - policy_timeshare_base_data_t ts; - policy_rr_base_data_t rr; - policy_fifo_base_data_t fifo; -}; - -struct policy_limits { - policy_timeshare_limit_data_t ts; - policy_rr_limit_data_t rr; - policy_fifo_limit_data_t fifo; -}; - -struct policy_infos { - policy_timeshare_info_data_t ts; - policy_rr_info_data_t rr; - policy_fifo_info_data_t fifo; -}; - -typedef struct policy_bases policy_base_data_t; -typedef struct policy_limits policy_limit_data_t; -typedef struct policy_infos policy_info_data_t; - - - - - - - - -typedef natural_t task_flavor_t; -typedef integer_t *task_info_t; - - - -typedef integer_t task_info_data_t[(1024)]; - - - - - -#pragma pack(4) - - - - - -struct task_basic_info_32 { - integer_t suspend_count; - natural_t virtual_size; - natural_t resident_size; - time_value_t user_time; - - time_value_t system_time; - - policy_t policy; -}; -typedef struct task_basic_info_32 task_basic_info_32_data_t; -typedef struct task_basic_info_32 *task_basic_info_32_t; - - - - -struct task_basic_info_64 { - integer_t suspend_count; - mach_vm_size_t virtual_size; - mach_vm_size_t resident_size; - time_value_t user_time; - - time_value_t system_time; - - policy_t policy; -}; -typedef struct task_basic_info_64 task_basic_info_64_data_t; -typedef struct task_basic_info_64 *task_basic_info_64_t; -struct task_basic_info { - integer_t suspend_count; - vm_size_t virtual_size; - vm_size_t resident_size; - time_value_t user_time; - - time_value_t system_time; - - policy_t policy; -}; - -typedef struct task_basic_info task_basic_info_data_t; -typedef struct task_basic_info *task_basic_info_t; -struct task_events_info { - integer_t faults; - integer_t pageins; - integer_t cow_faults; - integer_t messages_sent; - integer_t messages_received; - integer_t syscalls_mach; - integer_t syscalls_unix; - integer_t csw; -}; -typedef struct task_events_info task_events_info_data_t; -typedef struct task_events_info *task_events_info_t; - - - - - - -struct task_thread_times_info { - time_value_t user_time; - - time_value_t system_time; - -}; - -typedef struct task_thread_times_info task_thread_times_info_data_t; -typedef struct task_thread_times_info *task_thread_times_info_t; - - - - - -struct task_absolutetime_info { - uint64_t total_user; - uint64_t total_system; - uint64_t threads_user; - uint64_t threads_system; -}; - -typedef struct task_absolutetime_info task_absolutetime_info_data_t; -typedef struct task_absolutetime_info *task_absolutetime_info_t; - - - - - -struct task_kernelmemory_info { - uint64_t total_palloc; - uint64_t total_pfree; - uint64_t total_salloc; - uint64_t total_sfree; -}; - -typedef struct task_kernelmemory_info task_kernelmemory_info_data_t; -typedef struct task_kernelmemory_info *task_kernelmemory_info_t; -struct task_affinity_tag_info { - integer_t set_count; - integer_t min; - integer_t max; - integer_t task_count; -}; -typedef struct task_affinity_tag_info task_affinity_tag_info_data_t; -typedef struct task_affinity_tag_info *task_affinity_tag_info_t; - - - - - -struct task_dyld_info { - mach_vm_address_t all_image_info_addr; - mach_vm_size_t all_image_info_size; - integer_t all_image_info_format; -}; -typedef struct task_dyld_info task_dyld_info_data_t; -typedef struct task_dyld_info *task_dyld_info_t; -struct task_extmod_info { - unsigned char task_uuid[16]; - vm_extmod_statistics_data_t extmod_statistics; -}; -typedef struct task_extmod_info task_extmod_info_data_t; -typedef struct task_extmod_info *task_extmod_info_t; - - - - - -struct mach_task_basic_info { - mach_vm_size_t virtual_size; - mach_vm_size_t resident_size; - mach_vm_size_t resident_size_max; - time_value_t user_time; - - time_value_t system_time; - - policy_t policy; - integer_t suspend_count; -}; -typedef struct mach_task_basic_info mach_task_basic_info_data_t; -typedef struct mach_task_basic_info *mach_task_basic_info_t; - - - - - - -struct task_power_info { - uint64_t total_user; - uint64_t total_system; - uint64_t task_interrupt_wakeups; - uint64_t task_platform_idle_wakeups; - uint64_t task_timer_wakeups_bin_1; - uint64_t task_timer_wakeups_bin_2; -}; - -typedef struct task_power_info task_power_info_data_t; -typedef struct task_power_info *task_power_info_t; - - - - - - - -struct task_vm_info { - mach_vm_size_t virtual_size; - integer_t region_count; - integer_t page_size; - mach_vm_size_t resident_size; - mach_vm_size_t resident_size_peak; - - mach_vm_size_t device; - mach_vm_size_t device_peak; - mach_vm_size_t internal; - mach_vm_size_t internal_peak; - mach_vm_size_t external; - mach_vm_size_t external_peak; - mach_vm_size_t reusable; - mach_vm_size_t reusable_peak; - mach_vm_size_t purgeable_volatile_pmap; - mach_vm_size_t purgeable_volatile_resident; - mach_vm_size_t purgeable_volatile_virtual; - mach_vm_size_t compressed; - mach_vm_size_t compressed_peak; - mach_vm_size_t compressed_lifetime; - - - mach_vm_size_t phys_footprint; -}; -typedef struct task_vm_info task_vm_info_data_t; -typedef struct task_vm_info *task_vm_info_t; - - - - - - -typedef struct vm_purgeable_info task_purgable_info_t; - - - -struct task_trace_memory_info { - uint64_t user_memory_address; - uint64_t buffer_size; - uint64_t mailbox_array_size; -}; -typedef struct task_trace_memory_info task_trace_memory_info_data_t; -typedef struct task_trace_memory_info * task_trace_memory_info_t; - - - - -struct task_wait_state_info { - uint64_t total_wait_state_time; - uint64_t total_wait_sfi_state_time; - uint32_t _reserved[4]; -}; -typedef struct task_wait_state_info task_wait_state_info_data_t; -typedef struct task_wait_state_info * task_wait_state_info_t; - - - - - -typedef struct { - uint64_t task_gpu_utilisation; - uint64_t task_gpu_stat_reserved0; - uint64_t task_gpu_stat_reserved1; - uint64_t task_gpu_stat_reserved2; -} gpu_energy_data; - -typedef gpu_energy_data *gpu_energy_data_t; -struct task_power_info_v2 { - task_power_info_data_t cpu_energy; - gpu_energy_data gpu_energy; -}; - -typedef struct task_power_info_v2 task_power_info_v2_data_t; -typedef struct task_power_info_v2 *task_power_info_v2_t; -struct task_flags_info { - uint32_t flags; -}; -typedef struct task_flags_info task_flags_info_data_t; -typedef struct task_flags_info * task_flags_info_t; -#pragma pack() -typedef natural_t task_policy_flavor_t; -typedef integer_t *task_policy_t; -enum task_role { - TASK_RENICED = -1, - TASK_UNSPECIFIED = 0, - TASK_FOREGROUND_APPLICATION, - TASK_BACKGROUND_APPLICATION, - TASK_CONTROL_APPLICATION, - TASK_GRAPHICS_SERVER, - TASK_THROTTLE_APPLICATION, - TASK_NONUI_APPLICATION, - TASK_DEFAULT_APPLICATION -}; - -typedef integer_t task_role_t; - -struct task_category_policy { - task_role_t role; -}; - -typedef struct task_category_policy task_category_policy_data_t; -typedef struct task_category_policy *task_category_policy_t; - - - - - -enum task_latency_qos { - LATENCY_QOS_TIER_UNSPECIFIED = 0x0, - LATENCY_QOS_TIER_0 = ((0xFF<<16) | 1), - LATENCY_QOS_TIER_1 = ((0xFF<<16) | 2), - LATENCY_QOS_TIER_2 = ((0xFF<<16) | 3), - LATENCY_QOS_TIER_3 = ((0xFF<<16) | 4), - LATENCY_QOS_TIER_4 = ((0xFF<<16) | 5), - LATENCY_QOS_TIER_5 = ((0xFF<<16) | 6) - -}; -typedef integer_t task_latency_qos_t; -enum task_throughput_qos { - THROUGHPUT_QOS_TIER_UNSPECIFIED = 0x0, - THROUGHPUT_QOS_TIER_0 = ((0xFE<<16) | 1), - THROUGHPUT_QOS_TIER_1 = ((0xFE<<16) | 2), - THROUGHPUT_QOS_TIER_2 = ((0xFE<<16) | 3), - THROUGHPUT_QOS_TIER_3 = ((0xFE<<16) | 4), - THROUGHPUT_QOS_TIER_4 = ((0xFE<<16) | 5), - THROUGHPUT_QOS_TIER_5 = ((0xFE<<16) | 6), -}; - - - - -typedef integer_t task_throughput_qos_t; - -struct task_qos_policy { - task_latency_qos_t task_latency_qos_tier; - task_throughput_qos_t task_throughput_qos_tier; -}; - -typedef struct task_qos_policy *task_qos_policy_t; -typedef int task_special_port_t; -typedef natural_t thread_flavor_t; -typedef integer_t *thread_info_t; - - -typedef integer_t thread_info_data_t[(32)]; - - - - - - -struct thread_basic_info { - time_value_t user_time; - time_value_t system_time; - integer_t cpu_usage; - policy_t policy; - integer_t run_state; - integer_t flags; - integer_t suspend_count; - integer_t sleep_time; - -}; - -typedef struct thread_basic_info thread_basic_info_data_t; -typedef struct thread_basic_info *thread_basic_info_t; - - - - - -struct thread_identifier_info { - uint64_t thread_id; - uint64_t thread_handle; - uint64_t dispatch_qaddr; -}; - -typedef struct thread_identifier_info thread_identifier_info_data_t; -typedef struct thread_identifier_info *thread_identifier_info_t; -struct thread_extended_info { - uint64_t pth_user_time; - uint64_t pth_system_time; - int32_t pth_cpu_usage; - int32_t pth_policy; - int32_t pth_run_state; - int32_t pth_flags; - int32_t pth_sleep_time; - int32_t pth_curpri; - int32_t pth_priority; - int32_t pth_maxpriority; - char pth_name[64]; -}; -typedef struct thread_extended_info thread_extended_info_data_t; -typedef struct thread_extended_info * thread_extended_info_t; -struct io_stat_entry { - uint64_t count; - uint64_t size; -}; - -struct io_stat_info { - struct io_stat_entry disk_reads; - struct io_stat_entry io_priority[4]; - struct io_stat_entry paging; - struct io_stat_entry metadata; - struct io_stat_entry total_io; -}; - -typedef struct io_stat_info *io_stat_info_t; -typedef natural_t thread_policy_flavor_t; -typedef integer_t *thread_policy_t; -struct thread_standard_policy { - natural_t no_data; -}; - -typedef struct thread_standard_policy thread_standard_policy_data_t; -typedef struct thread_standard_policy *thread_standard_policy_t; -struct thread_extended_policy { - boolean_t timeshare; -}; - -typedef struct thread_extended_policy thread_extended_policy_data_t; -typedef struct thread_extended_policy *thread_extended_policy_t; -struct thread_time_constraint_policy { - uint32_t period; - uint32_t computation; - uint32_t constraint; - boolean_t preemptible; -}; - -typedef struct thread_time_constraint_policy thread_time_constraint_policy_data_t; - -typedef struct thread_time_constraint_policy *thread_time_constraint_policy_t; -struct thread_precedence_policy { - integer_t importance; -}; - -typedef struct thread_precedence_policy thread_precedence_policy_data_t; -typedef struct thread_precedence_policy *thread_precedence_policy_t; -struct thread_affinity_policy { - integer_t affinity_tag; -}; - - - -typedef struct thread_affinity_policy thread_affinity_policy_data_t; -typedef struct thread_affinity_policy *thread_affinity_policy_t; -struct thread_background_policy { - integer_t priority; -}; - -typedef struct thread_background_policy thread_background_policy_data_t; -typedef struct thread_background_policy *thread_background_policy_t; - - - - - - -typedef integer_t thread_latency_qos_t; - -struct thread_latency_qos_policy { - thread_latency_qos_t thread_latency_qos_tier; -}; - -typedef struct thread_latency_qos_policy thread_latency_qos_policy_data_t; -typedef struct thread_latency_qos_policy *thread_latency_qos_policy_t; - - - - - -typedef integer_t thread_throughput_qos_t; - -struct thread_throughput_qos_policy { - thread_throughput_qos_t thread_throughput_qos_tier; -}; - -typedef struct thread_throughput_qos_policy thread_throughput_qos_policy_data_t; -typedef struct thread_throughput_qos_policy *thread_throughput_qos_policy_t; - - - -typedef unsigned int vm_machine_attribute_t; -typedef int vm_machine_attribute_val_t; -typedef unsigned int vm_inherit_t; -typedef int vm_purgable_t; -typedef int vm_behavior_t; - - - - - - - - - -#pragma pack(4) - - - - -typedef uint32_t vm32_object_id_t; -typedef int *vm_region_info_t; -typedef int *vm_region_info_64_t; -typedef int *vm_region_recurse_info_t; -typedef int *vm_region_recurse_info_64_t; -typedef int vm_region_flavor_t; -typedef int vm_region_info_data_t[(1024)]; - - -struct vm_region_basic_info_64 { - vm_prot_t protection; - vm_prot_t max_protection; - vm_inherit_t inheritance; - boolean_t shared; - boolean_t reserved; - memory_object_offset_t offset; - vm_behavior_t behavior; - unsigned short user_wired_count; -}; -typedef struct vm_region_basic_info_64 *vm_region_basic_info_64_t; -typedef struct vm_region_basic_info_64 vm_region_basic_info_data_64_t; -struct vm_region_basic_info { - vm_prot_t protection; - vm_prot_t max_protection; - vm_inherit_t inheritance; - boolean_t shared; - boolean_t reserved; - uint32_t offset; - vm_behavior_t behavior; - unsigned short user_wired_count; -}; - -typedef struct vm_region_basic_info *vm_region_basic_info_t; -typedef struct vm_region_basic_info vm_region_basic_info_data_t; -struct vm_region_extended_info { - vm_prot_t protection; - unsigned int user_tag; - unsigned int pages_resident; - unsigned int pages_shared_now_private; - unsigned int pages_swapped_out; - unsigned int pages_dirtied; - unsigned int ref_count; - unsigned short shadow_depth; - unsigned char external_pager; - unsigned char share_mode; - unsigned int pages_reusable; -}; -typedef struct vm_region_extended_info *vm_region_extended_info_t; -typedef struct vm_region_extended_info vm_region_extended_info_data_t; -struct vm_region_top_info { - unsigned int obj_id; - unsigned int ref_count; - unsigned int private_pages_resident; - unsigned int shared_pages_resident; - unsigned char share_mode; -}; - -typedef struct vm_region_top_info *vm_region_top_info_t; -typedef struct vm_region_top_info vm_region_top_info_data_t; -struct vm_region_submap_info { - vm_prot_t protection; - vm_prot_t max_protection; - vm_inherit_t inheritance; - uint32_t offset; - unsigned int user_tag; - unsigned int pages_resident; - unsigned int pages_shared_now_private; - unsigned int pages_swapped_out; - unsigned int pages_dirtied; - unsigned int ref_count; - unsigned short shadow_depth; - unsigned char external_pager; - unsigned char share_mode; - boolean_t is_submap; - vm_behavior_t behavior; - vm32_object_id_t object_id; - unsigned short user_wired_count; -}; - -typedef struct vm_region_submap_info *vm_region_submap_info_t; -typedef struct vm_region_submap_info vm_region_submap_info_data_t; - - - - - -struct vm_region_submap_info_64 { - vm_prot_t protection; - vm_prot_t max_protection; - vm_inherit_t inheritance; - memory_object_offset_t offset; - unsigned int user_tag; - unsigned int pages_resident; - unsigned int pages_shared_now_private; - unsigned int pages_swapped_out; - unsigned int pages_dirtied; - unsigned int ref_count; - unsigned short shadow_depth; - unsigned char external_pager; - unsigned char share_mode; - boolean_t is_submap; - vm_behavior_t behavior; - vm32_object_id_t object_id; - unsigned short user_wired_count; - unsigned int pages_reusable; -}; - -typedef struct vm_region_submap_info_64 *vm_region_submap_info_64_t; -typedef struct vm_region_submap_info_64 vm_region_submap_info_data_64_t; -struct vm_region_submap_short_info_64 { - vm_prot_t protection; - vm_prot_t max_protection; - vm_inherit_t inheritance; - memory_object_offset_t offset; - unsigned int user_tag; - unsigned int ref_count; - unsigned short shadow_depth; - unsigned char external_pager; - unsigned char share_mode; - boolean_t is_submap; - vm_behavior_t behavior; - vm32_object_id_t object_id; - unsigned short user_wired_count; -}; - -typedef struct vm_region_submap_short_info_64 *vm_region_submap_short_info_64_t; -typedef struct vm_region_submap_short_info_64 vm_region_submap_short_info_data_64_t; - - - - - - - -struct mach_vm_read_entry { - mach_vm_address_t address; - mach_vm_size_t size; -}; - -struct vm_read_entry { - vm_address_t address; - vm_size_t size; -}; -typedef struct mach_vm_read_entry mach_vm_read_entry_t[(256)]; -typedef struct vm_read_entry vm_read_entry_t[(256)]; - - - - -#pragma pack() - - - -typedef int *vm_page_info_t; -typedef int vm_page_info_data_t[]; -typedef int vm_page_info_flavor_t; - - -struct vm_page_info_basic { - int disposition; - int ref_count; - vm_object_id_t object_id; - memory_object_offset_t offset; - int depth; - int __pad; -}; -typedef struct vm_page_info_basic *vm_page_info_basic_t; -typedef struct vm_page_info_basic vm_page_info_basic_data_t; - - - -extern "C" { -typedef int kmod_t; - -struct kmod_info; -typedef kern_return_t kmod_start_func_t(struct kmod_info * ki, void * data); -typedef kern_return_t kmod_stop_func_t(struct kmod_info * ki, void * data); -#pragma pack(4) - - -typedef struct kmod_reference { - struct kmod_reference * next; - struct kmod_info * info; -} kmod_reference_t; -typedef struct kmod_info { - struct kmod_info * next; - int32_t info_version; - uint32_t id; - char name[64]; - char version[64]; - int32_t reference_count; - kmod_reference_t * reference_list; - vm_address_t address; - vm_size_t size; - vm_size_t hdr_size; - kmod_start_func_t * start; - kmod_stop_func_t * stop; -} kmod_info_t; - - - -typedef struct kmod_info_32_v1 { - uint32_t next_addr; - int32_t info_version; - uint32_t id; - uint8_t name[64]; - uint8_t version[64]; - int32_t reference_count; - uint32_t reference_list_addr; - uint32_t address; - uint32_t size; - uint32_t hdr_size; - uint32_t start_addr; - uint32_t stop_addr; -} kmod_info_32_v1_t; - - - -typedef struct kmod_info_64_v1 { - uint64_t next_addr; - int32_t info_version; - uint32_t id; - uint8_t name[64]; - uint8_t version[64]; - int32_t reference_count; - uint64_t reference_list_addr; - uint64_t address; - uint64_t size; - uint64_t hdr_size; - uint64_t start_addr; - uint64_t stop_addr; -} kmod_info_64_v1_t; - -#pragma pack() -typedef void * kmod_args_t; -typedef int kmod_control_flavor_t; -typedef kmod_info_t * kmod_info_array_t; - -} - - - - - - -typedef mach_port_t task_t; -typedef mach_port_t task_name_t; -typedef mach_port_t task_suspension_token_t; -typedef mach_port_t thread_t; -typedef mach_port_t thread_act_t; -typedef mach_port_t ipc_space_t; -typedef mach_port_t coalition_t; -typedef mach_port_t host_t; -typedef mach_port_t host_priv_t; -typedef mach_port_t host_security_t; -typedef mach_port_t processor_t; -typedef mach_port_t processor_set_t; -typedef mach_port_t processor_set_control_t; -typedef mach_port_t semaphore_t; -typedef mach_port_t lock_set_t; -typedef mach_port_t ledger_t; -typedef mach_port_t alarm_t; -typedef mach_port_t clock_serv_t; -typedef mach_port_t clock_ctrl_t; - - - - - - - -typedef processor_set_t processor_set_name_t; - - - - -typedef mach_port_t clock_reply_t; -typedef mach_port_t bootstrap_t; -typedef mach_port_t mem_entry_name_port_t; -typedef mach_port_t exception_handler_t; -typedef exception_handler_t *exception_handler_array_t; -typedef mach_port_t vm_task_entry_t; -typedef mach_port_t io_master_t; -typedef mach_port_t UNDServerRef; -typedef task_t *task_array_t; -typedef thread_t *thread_array_t; -typedef processor_set_t *processor_set_array_t; -typedef processor_set_t *processor_set_name_array_t; -typedef processor_t *processor_array_t; -typedef thread_act_t *thread_act_array_t; -typedef ledger_t *ledger_array_t; - - - - - - - -typedef task_t task_port_t; -typedef task_array_t task_port_array_t; -typedef thread_t thread_port_t; -typedef thread_array_t thread_port_array_t; -typedef ipc_space_t ipc_space_port_t; -typedef host_t host_name_t; -typedef host_t host_name_port_t; -typedef processor_set_t processor_set_port_t; -typedef processor_set_t processor_set_name_port_t; -typedef processor_set_array_t processor_set_name_port_array_t; -typedef processor_set_t processor_set_control_port_t; -typedef processor_t processor_port_t; -typedef processor_array_t processor_port_array_t; -typedef thread_act_t thread_act_port_t; -typedef thread_act_array_t thread_act_port_array_t; -typedef semaphore_t semaphore_port_t; -typedef lock_set_t lock_set_port_t; -typedef ledger_t ledger_port_t; -typedef ledger_array_t ledger_port_array_t; -typedef alarm_t alarm_port_t; -typedef clock_serv_t clock_serv_port_t; -typedef clock_ctrl_t clock_ctrl_port_t; -typedef exception_handler_t exception_port_t; -typedef exception_handler_array_t exception_port_arrary_t; -typedef natural_t ledger_item_t; - - -typedef int64_t ledger_amount_t; - - -typedef mach_vm_offset_t *emulation_vector_t; -typedef char *user_subsystem_t; - -typedef char *labelstr_t; -extern "C" { - - - - - -extern vm_size_t vm_page_size; -extern vm_size_t vm_page_mask; -extern int vm_page_shift; -extern vm_size_t vm_kernel_page_size __attribute__((availability(macosx,introduced=10.9))); -extern vm_size_t vm_kernel_page_mask __attribute__((availability(macosx,introduced=10.9))); -extern int vm_kernel_page_shift __attribute__((availability(macosx,introduced=10.9))); - - - - -} - - - - - - - - -extern "C" { -extern mach_port_t mach_host_self(void); -extern mach_port_t mach_thread_self(void); -extern kern_return_t host_page_size(host_t, vm_size_t *); - -extern mach_port_t mach_task_self_; - - - -} - -extern "C" { - - - -extern kern_return_t clock_sleep_trap( - mach_port_name_t clock_name, - sleep_type_t sleep_type, - int sleep_sec, - int sleep_nsec, - mach_timespec_t *wakeup_time); - -extern kern_return_t _kernelrpc_mach_vm_allocate_trap( - mach_port_name_t target, - mach_vm_offset_t *addr, - mach_vm_size_t size, - int flags); - -extern kern_return_t _kernelrpc_mach_vm_deallocate_trap( - mach_port_name_t target, - mach_vm_address_t address, - mach_vm_size_t size -); - -extern kern_return_t _kernelrpc_mach_vm_protect_trap( - mach_port_name_t target, - mach_vm_address_t address, - mach_vm_size_t size, - boolean_t set_maximum, - vm_prot_t new_protection -); - -extern kern_return_t _kernelrpc_mach_vm_map_trap( - mach_port_name_t target, - mach_vm_offset_t *address, - mach_vm_size_t size, - mach_vm_offset_t mask, - int flags, - vm_prot_t cur_protection -); - -extern kern_return_t _kernelrpc_mach_port_allocate_trap( - mach_port_name_t target, - mach_port_right_t right, - mach_port_name_t *name -); - - -extern kern_return_t _kernelrpc_mach_port_destroy_trap( - mach_port_name_t target, - mach_port_name_t name -); - -extern kern_return_t _kernelrpc_mach_port_deallocate_trap( - mach_port_name_t target, - mach_port_name_t name -); - -extern kern_return_t _kernelrpc_mach_port_mod_refs_trap( - mach_port_name_t target, - mach_port_name_t name, - mach_port_right_t right, - mach_port_delta_t delta -); - -extern kern_return_t _kernelrpc_mach_port_move_member_trap( - mach_port_name_t target, - mach_port_name_t member, - mach_port_name_t after -); - -extern kern_return_t _kernelrpc_mach_port_insert_right_trap( - mach_port_name_t target, - mach_port_name_t name, - mach_port_name_t poly, - mach_msg_type_name_t polyPoly -); - -extern kern_return_t _kernelrpc_mach_port_insert_member_trap( - mach_port_name_t target, - mach_port_name_t name, - mach_port_name_t pset -); - -extern kern_return_t _kernelrpc_mach_port_extract_member_trap( - mach_port_name_t target, - mach_port_name_t name, - mach_port_name_t pset -); - -extern kern_return_t _kernelrpc_mach_port_construct_trap( - mach_port_name_t target, - mach_port_options_t *options, - uint64_t context, - mach_port_name_t *name -); - -extern kern_return_t _kernelrpc_mach_port_destruct_trap( - mach_port_name_t target, - mach_port_name_t name, - mach_port_delta_t srdelta, - uint64_t guard -); - -extern kern_return_t _kernelrpc_mach_port_guard_trap( - mach_port_name_t target, - mach_port_name_t name, - uint64_t guard, - boolean_t strict -); - -extern kern_return_t _kernelrpc_mach_port_unguard_trap( - mach_port_name_t target, - mach_port_name_t name, - uint64_t guard -); - -extern kern_return_t macx_swapon( - uint64_t filename, - int flags, - int size, - int priority); - -extern kern_return_t macx_swapoff( - uint64_t filename, - int flags); - -extern kern_return_t macx_triggers( - int hi_water, - int low_water, - int flags, - mach_port_t alert_port); - -extern kern_return_t macx_backing_store_suspend( - boolean_t suspend); - -extern kern_return_t macx_backing_store_recovery( - int pid); - -extern boolean_t swtch_pri(int pri); - -extern boolean_t swtch(void); - -extern kern_return_t thread_switch( - mach_port_name_t thread_name, - int option, - mach_msg_timeout_t option_time); - -extern mach_port_name_t task_self_trap(void); - - - - - -extern kern_return_t task_for_pid( - mach_port_name_t target_tport, - int pid, - mach_port_name_t *t); - -extern kern_return_t task_name_for_pid( - mach_port_name_t target_tport, - int pid, - mach_port_name_t *tn); - -extern kern_return_t pid_for_task( - mach_port_name_t t, - int *x); - - -} -extern "C" { - - - - - -extern mach_port_t bootstrap_port; -extern int (*vprintf_stderr_func)(const char *format, va_list ap); - -} - - - - - -extern "C" { - - - -typedef kern_return_t mach_error_t; -typedef mach_error_t (* mach_error_fn_t)( void ); - -typedef kern_return_t IOReturn; -} - - -extern "C" { -typedef unsigned int UInt; -typedef signed int SInt; - - -typedef UInt32 IOOptionBits; -typedef SInt32 IOFixed; -typedef UInt32 IOVersion; -typedef UInt32 IOItemCount; -typedef UInt32 IOCacheMode; - -typedef UInt32 IOByteCount32; -typedef UInt64 IOByteCount64; - -typedef UInt32 IOPhysicalAddress32; -typedef UInt64 IOPhysicalAddress64; -typedef UInt32 IOPhysicalLength32; -typedef UInt64 IOPhysicalLength64; - - -typedef mach_vm_address_t IOVirtualAddress; - - - - - - - -typedef IOByteCount32 IOByteCount; - - -typedef IOVirtualAddress IOLogicalAddress; -typedef IOPhysicalAddress32 IOPhysicalAddress; -typedef IOPhysicalLength32 IOPhysicalLength; - - - - - - -typedef struct -{ - IOPhysicalAddress address; - IOByteCount length; -} IOPhysicalRange; - -typedef struct -{ - IOVirtualAddress address; - IOByteCount length; -} IOVirtualRange; - - -typedef IOVirtualRange IOAddressRange; -typedef struct { - int value; - const char *name; -} IONamedValue; - - - - - -typedef unsigned int IOAlignment; -typedef mach_port_t io_object_t; - - - -typedef char * io_buf_ptr_t; -typedef char io_name_t[128]; -typedef char io_string_t[512]; -typedef char io_string_inband_t[4096]; -typedef char io_struct_inband_t[4096]; - - -typedef uint64_t io_user_scalar_t; -typedef uint64_t io_user_reference_t; -typedef io_user_scalar_t io_scalar_inband_t[16]; -typedef io_user_reference_t io_async_ref_t[8]; -typedef io_user_scalar_t io_scalar_inband64_t[16]; -typedef io_user_reference_t io_async_ref64_t[8]; - -typedef io_object_t io_connect_t; -typedef io_object_t io_enumerator_t; -typedef io_object_t io_iterator_t; -typedef io_object_t io_registry_entry_t; -typedef io_object_t io_service_t; - - - - - - -enum { - kIODefaultMemoryType = 0 -}; - -enum { - kIODefaultCache = 0, - kIOInhibitCache = 1, - kIOWriteThruCache = 2, - kIOCopybackCache = 3, - kIOWriteCombineCache = 4, - kIOCopybackInnerCache = 5 -}; - - -enum { - kIOMapAnywhere = 0x00000001, - - kIOMapCacheMask = 0x00000700, - kIOMapCacheShift = 8, - kIOMapDefaultCache = kIODefaultCache << kIOMapCacheShift, - kIOMapInhibitCache = kIOInhibitCache << kIOMapCacheShift, - kIOMapWriteThruCache = kIOWriteThruCache << kIOMapCacheShift, - kIOMapCopybackCache = kIOCopybackCache << kIOMapCacheShift, - kIOMapWriteCombineCache = kIOWriteCombineCache << kIOMapCacheShift, - kIOMapCopybackInnerCache = kIOCopybackInnerCache << kIOMapCacheShift, - - kIOMapUserOptionsMask = 0x00000fff, - - kIOMapReadOnly = 0x00001000, - - kIOMapStatic = 0x01000000, - kIOMapReference = 0x02000000, - kIOMapUnique = 0x04000000, - kIOMapPrefault = 0x10000000, - kIOMapOverwrite = 0x20000000 -}; -enum { - kNanosecondScale = 1, - kMicrosecondScale = 1000, - kMillisecondScale = 1000 * 1000, - kSecondScale = 1000 * 1000 * 1000, - kTickScale = (kSecondScale / 100) -}; - -enum { - kIOConnectMethodVarOutputSize = -3 -}; - - - - -typedef unsigned int IODeviceNumber; - - - -} - -extern "C" { - - - - - - -enum { - kFirstIOKitNotificationType = 100, - kIOServicePublishNotificationType = 100, - kIOServiceMatchedNotificationType = 101, - kIOServiceTerminatedNotificationType = 102, - kIOAsyncCompletionNotificationType = 150, - kIOServiceMessageNotificationType = 160, - kLastIOKitNotificationType = 199, - - - kIOKitNoticationTypeMask = 0x00000FFF, - kIOKitNoticationTypeSizeAdjShift = 30, - kIOKitNoticationMsgSizeMask = 3, -}; - -enum { - kOSNotificationMessageID = 53, - kOSAsyncCompleteMessageID = 57, - kMaxAsyncArgs = 16 -}; - -enum { - kIOAsyncReservedIndex = 0, - kIOAsyncReservedCount, - - kIOAsyncCalloutFuncIndex = kIOAsyncReservedCount, - kIOAsyncCalloutRefconIndex, - kIOAsyncCalloutCount, - - kIOMatchingCalloutFuncIndex = kIOAsyncReservedCount, - kIOMatchingCalloutRefconIndex, - kIOMatchingCalloutCount, - - kIOInterestCalloutFuncIndex = kIOAsyncReservedCount, - kIOInterestCalloutRefconIndex, - kIOInterestCalloutServiceIndex, - kIOInterestCalloutCount -}; - - - - -enum { - kOSAsyncRef64Count = 8, - kOSAsyncRef64Size = kOSAsyncRef64Count * ((int) sizeof(io_user_reference_t)) -}; -typedef io_user_reference_t OSAsyncReference64[kOSAsyncRef64Count]; - -struct OSNotificationHeader64 { - mach_msg_size_t size; - natural_t type; - OSAsyncReference64 reference; - - - - - unsigned char content[0]; - -}; - -#pragma pack(4) -struct IOServiceInterestContent64 { - natural_t messageType; - io_user_reference_t messageArgument[1]; -}; -#pragma pack() - - - - -enum { - kOSAsyncRefCount = 8, - kOSAsyncRefSize = 32 -}; -typedef natural_t OSAsyncReference[kOSAsyncRefCount]; - -struct OSNotificationHeader { - mach_msg_size_t size; - natural_t type; - OSAsyncReference reference; - - - - - unsigned char content[0]; - -}; - -#pragma pack(4) -struct IOServiceInterestContent { - natural_t messageType; - void * messageArgument[1]; -}; -#pragma pack() - - - -struct IOAsyncCompletionContent { - IOReturn result; - - - - void * args[0] __attribute__ ((packed)); - -}; -} - - - - - -extern "C" { -typedef struct IONotificationPort * IONotificationPortRef; - - - - - - - -typedef void -(*IOServiceMatchingCallback)( - void * refcon, - io_iterator_t iterator ); -typedef void -(*IOServiceInterestCallback)( - void * refcon, - io_service_t service, - uint32_t messageType, - void * messageArgument ); -extern -const mach_port_t kIOMasterPortDefault; -kern_return_t -IOMasterPort( mach_port_t bootstrapPort, - mach_port_t * masterPort ); -IONotificationPortRef -IONotificationPortCreate( - mach_port_t masterPort ); -void -IONotificationPortDestroy( - IONotificationPortRef notify ); -CFRunLoopSourceRef -IONotificationPortGetRunLoopSource( - IONotificationPortRef notify ); -mach_port_t -IONotificationPortGetMachPort( - IONotificationPortRef notify ); - - - - - - - -void -IONotificationPortSetDispatchQueue( - IONotificationPortRef notify, dispatch_queue_t queue ) -__attribute__((availability(macosx,introduced=10.6))); -void -IODispatchCalloutFromMessage( - void *unused, - mach_msg_header_t *msg, - void *reference ); -kern_return_t -IOCreateReceivePort( uint32_t msgType, mach_port_t * recvPort ); -kern_return_t -IOObjectRelease( - io_object_t object ); - - - - - - - -kern_return_t -IOObjectRetain( - io_object_t object ); -kern_return_t -IOObjectGetClass( - io_object_t object, - io_name_t className ); - - - - - - - -CFStringRef -IOObjectCopyClass(io_object_t object) -__attribute__((availability(macosx,introduced=10.4))); - - - - - - - -CFStringRef -IOObjectCopySuperclassForClass(CFStringRef classname) -__attribute__((availability(macosx,introduced=10.4))); - - - - - - - -CFStringRef -IOObjectCopyBundleIdentifierForClass(CFStringRef classname) -__attribute__((availability(macosx,introduced=10.4))); -boolean_t -IOObjectConformsTo( - io_object_t object, - const io_name_t className ); -boolean_t -IOObjectIsEqualTo( - io_object_t object, - io_object_t anObject ); - - - - - - - -uint32_t -IOObjectGetKernelRetainCount( - io_object_t object ) -__attribute__((availability(macosx,introduced=10.6))); - - - - - - - -uint32_t -IOObjectGetUserRetainCount( - io_object_t object ) -__attribute__((availability(macosx,introduced=10.6))); - - - - - - - -uint32_t -IOObjectGetRetainCount( - io_object_t object ); -io_object_t -IOIteratorNext( - io_iterator_t iterator ); - - - - - - -void -IOIteratorReset( - io_iterator_t iterator ); - - - - - - - -boolean_t -IOIteratorIsValid( - io_iterator_t iterator ); -io_service_t -IOServiceGetMatchingService( - mach_port_t masterPort, - CFDictionaryRef matching __attribute__((cf_consumed))); -kern_return_t -IOServiceGetMatchingServices( - mach_port_t masterPort, - CFDictionaryRef matching __attribute__((cf_consumed)), - io_iterator_t * existing ); - - -kern_return_t -IOServiceAddNotification( - mach_port_t masterPort, - const io_name_t notificationType, - CFDictionaryRef matching, - mach_port_t wakePort, - uintptr_t reference, - io_iterator_t * notification ) __attribute__((deprecated)); -kern_return_t -IOServiceAddMatchingNotification( - IONotificationPortRef notifyPort, - const io_name_t notificationType, - CFDictionaryRef matching __attribute__((cf_consumed)), - IOServiceMatchingCallback callback, - void * refCon, - io_iterator_t * notification ); -kern_return_t -IOServiceAddInterestNotification( - IONotificationPortRef notifyPort, - io_service_t service, - const io_name_t interestType, - IOServiceInterestCallback callback, - void * refCon, - io_object_t * notification ); -kern_return_t -IOServiceMatchPropertyTable( - io_service_t service, - CFDictionaryRef matching, - boolean_t * matches ); -kern_return_t -IOServiceGetBusyState( - io_service_t service, - uint32_t * busyState ); -kern_return_t -IOServiceWaitQuiet( - io_service_t service, - mach_timespec_t * waitTime ); -kern_return_t -IOKitGetBusyState( - mach_port_t masterPort, - uint32_t * busyState ); -kern_return_t -IOKitWaitQuiet( - mach_port_t masterPort, - mach_timespec_t * waitTime ); -kern_return_t -IOServiceOpen( - io_service_t service, - task_port_t owningTask, - uint32_t type, - io_connect_t * connect ); -kern_return_t -IOServiceRequestProbe( - io_service_t service, - uint32_t options ); - - -enum { - kIOServiceInteractionAllowed = 0x00000001 -}; -kern_return_t -IOServiceAuthorize( - io_service_t service, - uint32_t options ); - -int -IOServiceOpenAsFileDescriptor( - io_service_t service, - int oflag ); -kern_return_t -IOServiceClose( - io_connect_t connect ); - - - - - - - -kern_return_t -IOConnectAddRef( - io_connect_t connect ); - - - - - - - -kern_return_t -IOConnectRelease( - io_connect_t connect ); -kern_return_t -IOConnectGetService( - io_connect_t connect, - io_service_t * service ); -kern_return_t -IOConnectSetNotificationPort( - io_connect_t connect, - uint32_t type, - mach_port_t port, - uintptr_t reference ); -kern_return_t -IOConnectMapMemory( - io_connect_t connect, - uint32_t memoryType, - task_port_t intoTask, - mach_vm_address_t *atAddress, - mach_vm_size_t *ofSize, - IOOptionBits options ); -kern_return_t IOConnectMapMemory64( - io_connect_t connect, - uint32_t memoryType, - task_port_t intoTask, - mach_vm_address_t *atAddress, - mach_vm_size_t *ofSize, - IOOptionBits options ); -kern_return_t -IOConnectUnmapMemory( - io_connect_t connect, - uint32_t memoryType, - task_port_t fromTask, - mach_vm_address_t atAddress ); -kern_return_t IOConnectUnmapMemory64( - io_connect_t connect, - uint32_t memoryType, - task_port_t fromTask, - mach_vm_address_t atAddress ); -kern_return_t -IOConnectSetCFProperties( - io_connect_t connect, - CFTypeRef properties ); -kern_return_t -IOConnectSetCFProperty( - io_connect_t connect, - CFStringRef propertyName, - CFTypeRef property ); - - - - - -kern_return_t -IOConnectCallMethod( - mach_port_t connection, - uint32_t selector, - const uint64_t *input, - uint32_t inputCnt, - const void *inputStruct, - size_t inputStructCnt, - uint64_t *output, - uint32_t *outputCnt, - void *outputStruct, - size_t *outputStructCnt) -__attribute__((availability(macosx,introduced=10.5))); - -kern_return_t -IOConnectCallAsyncMethod( - mach_port_t connection, - uint32_t selector, - mach_port_t wake_port, - uint64_t *reference, - uint32_t referenceCnt, - const uint64_t *input, - uint32_t inputCnt, - const void *inputStruct, - size_t inputStructCnt, - uint64_t *output, - uint32_t *outputCnt, - void *outputStruct, - size_t *outputStructCnt) -__attribute__((availability(macosx,introduced=10.5))); - -kern_return_t -IOConnectCallStructMethod( - mach_port_t connection, - uint32_t selector, - const void *inputStruct, - size_t inputStructCnt, - void *outputStruct, - size_t *outputStructCnt) -__attribute__((availability(macosx,introduced=10.5))); - -kern_return_t -IOConnectCallAsyncStructMethod( - mach_port_t connection, - uint32_t selector, - mach_port_t wake_port, - uint64_t *reference, - uint32_t referenceCnt, - const void *inputStruct, - size_t inputStructCnt, - void *outputStruct, - size_t *outputStructCnt) -__attribute__((availability(macosx,introduced=10.5))); - -kern_return_t -IOConnectCallScalarMethod( - mach_port_t connection, - uint32_t selector, - const uint64_t *input, - uint32_t inputCnt, - uint64_t *output, - uint32_t *outputCnt) -__attribute__((availability(macosx,introduced=10.5))); - -kern_return_t -IOConnectCallAsyncScalarMethod( - mach_port_t connection, - uint32_t selector, - mach_port_t wake_port, - uint64_t *reference, - uint32_t referenceCnt, - const uint64_t *input, - uint32_t inputCnt, - uint64_t *output, - uint32_t *outputCnt) -__attribute__((availability(macosx,introduced=10.5))); - - - -kern_return_t -IOConnectTrap0(io_connect_t connect, - uint32_t index ); - -kern_return_t -IOConnectTrap1(io_connect_t connect, - uint32_t index, - uintptr_t p1 ); - -kern_return_t -IOConnectTrap2(io_connect_t connect, - uint32_t index, - uintptr_t p1, - uintptr_t p2); - -kern_return_t -IOConnectTrap3(io_connect_t connect, - uint32_t index, - uintptr_t p1, - uintptr_t p2, - uintptr_t p3); - -kern_return_t -IOConnectTrap4(io_connect_t connect, - uint32_t index, - uintptr_t p1, - uintptr_t p2, - uintptr_t p3, - uintptr_t p4); - -kern_return_t -IOConnectTrap5(io_connect_t connect, - uint32_t index, - uintptr_t p1, - uintptr_t p2, - uintptr_t p3, - uintptr_t p4, - uintptr_t p5); - -kern_return_t -IOConnectTrap6(io_connect_t connect, - uint32_t index, - uintptr_t p1, - uintptr_t p2, - uintptr_t p3, - uintptr_t p4, - uintptr_t p5, - uintptr_t p6); -kern_return_t -IOConnectAddClient( - io_connect_t connect, - io_connect_t client ); -io_registry_entry_t -IORegistryGetRootEntry( - mach_port_t masterPort ); -io_registry_entry_t -IORegistryEntryFromPath( - mach_port_t masterPort, - const io_string_t path ); -io_registry_entry_t -IORegistryEntryCopyFromPath( - mach_port_t masterPort, - CFStringRef path ) - -__attribute__((availability(macosx,introduced=10.11))) - -; - - -enum { - kIORegistryIterateRecursively = 0x00000001, - kIORegistryIterateParents = 0x00000002 -}; -kern_return_t -IORegistryCreateIterator( - mach_port_t masterPort, - const io_name_t plane, - IOOptionBits options, - io_iterator_t * iterator ); -kern_return_t -IORegistryEntryCreateIterator( - io_registry_entry_t entry, - const io_name_t plane, - IOOptionBits options, - io_iterator_t * iterator ); -kern_return_t -IORegistryIteratorEnterEntry( - io_iterator_t iterator ); - - - - - - -kern_return_t -IORegistryIteratorExitEntry( - io_iterator_t iterator ); -kern_return_t -IORegistryEntryGetName( - io_registry_entry_t entry, - io_name_t name ); -kern_return_t -IORegistryEntryGetNameInPlane( - io_registry_entry_t entry, - const io_name_t plane, - io_name_t name ); -kern_return_t -IORegistryEntryGetLocationInPlane( - io_registry_entry_t entry, - const io_name_t plane, - io_name_t location ); -kern_return_t -IORegistryEntryGetPath( - io_registry_entry_t entry, - const io_name_t plane, - io_string_t path ); -CFStringRef -IORegistryEntryCopyPath( - io_registry_entry_t entry, - const io_name_t plane) - -__attribute__((availability(macosx,introduced=10.11))) - -; -kern_return_t -IORegistryEntryGetRegistryEntryID( - io_registry_entry_t entry, - uint64_t * entryID ); -kern_return_t -IORegistryEntryCreateCFProperties( - io_registry_entry_t entry, - CFMutableDictionaryRef * properties, - CFAllocatorRef allocator, - IOOptionBits options ); -CFTypeRef -IORegistryEntryCreateCFProperty( - io_registry_entry_t entry, - CFStringRef key, - CFAllocatorRef allocator, - IOOptionBits options ); -CFTypeRef -IORegistryEntrySearchCFProperty( - io_registry_entry_t entry, - const io_name_t plane, - CFStringRef key, - CFAllocatorRef allocator, - IOOptionBits options ) __attribute__((cf_returns_retained)); - - - - -kern_return_t -IORegistryEntryGetProperty( - io_registry_entry_t entry, - const io_name_t propertyName, - io_struct_inband_t buffer, - uint32_t * size ); -kern_return_t -IORegistryEntrySetCFProperties( - io_registry_entry_t entry, - CFTypeRef properties ); -kern_return_t -IORegistryEntrySetCFProperty( - io_registry_entry_t entry, - CFStringRef propertyName, - CFTypeRef property ); -kern_return_t -IORegistryEntryGetChildIterator( - io_registry_entry_t entry, - const io_name_t plane, - io_iterator_t * iterator ); -kern_return_t -IORegistryEntryGetChildEntry( - io_registry_entry_t entry, - const io_name_t plane, - io_registry_entry_t * child ); -kern_return_t -IORegistryEntryGetParentIterator( - io_registry_entry_t entry, - const io_name_t plane, - io_iterator_t * iterator ); -kern_return_t -IORegistryEntryGetParentEntry( - io_registry_entry_t entry, - const io_name_t plane, - io_registry_entry_t * parent ); -boolean_t -IORegistryEntryInPlane( - io_registry_entry_t entry, - const io_name_t plane ); -CFMutableDictionaryRef -IOServiceMatching( - const char * name ) __attribute__((cf_returns_retained)); - - - - - - - -CFMutableDictionaryRef -IOServiceNameMatching( - const char * name ) __attribute__((cf_returns_retained)); -CFMutableDictionaryRef -IOBSDNameMatching( - mach_port_t masterPort, - uint32_t options, - const char * bsdName ) __attribute__((cf_returns_retained)); - -CFMutableDictionaryRef -IOOpenFirmwarePathMatching( - mach_port_t masterPort, - uint32_t options, - const char * path ) __attribute__((deprecated)); - - - - - - - -CFMutableDictionaryRef -IORegistryEntryIDMatching( - uint64_t entryID ) __attribute__((cf_returns_retained)); - - - -kern_return_t -IOServiceOFPathToBSDName(mach_port_t masterPort, - const io_name_t openFirmwarePath, - io_name_t bsdName) __attribute__((deprecated)); -typedef void (*IOAsyncCallback0)(void *refcon, IOReturn result); -typedef void (*IOAsyncCallback1)(void *refcon, IOReturn result, void *arg0); -typedef void (*IOAsyncCallback2)(void *refcon, IOReturn result, void *arg0, void *arg1); -typedef void (*IOAsyncCallback)(void *refcon, IOReturn result, void **args, - uint32_t numArgs); - - - - -kern_return_t -OSGetNotificationFromMessage( - mach_msg_header_t * msg, - uint32_t index, - uint32_t * type, - uintptr_t * reference, - void ** content, - vm_size_t * size ); - - - - - -kern_return_t -IOCatalogueSendData( - mach_port_t masterPort, - uint32_t flag, - const char *buffer, - uint32_t size ); - -kern_return_t -IOCatalogueTerminate( - mach_port_t masterPort, - uint32_t flag, - io_name_t description ); - -kern_return_t -IOCatalogueGetData( - mach_port_t masterPort, - uint32_t flag, - char **buffer, - uint32_t *size ); - -kern_return_t -IOCatalogueModuleLoaded( - mach_port_t masterPort, - io_name_t name ); - - - - - -kern_return_t -IOCatalogueReset( - mach_port_t masterPort, - uint32_t flag ); -} - -extern "C" { -typedef struct __attribute__((objc_bridge(id))) __DASession * DASessionRef; - - - - - - -extern CFTypeID DASessionGetTypeID( void ); -extern DASessionRef _Nullable DASessionCreate( CFAllocatorRef _Nullable allocator ); -extern void DASessionScheduleWithRunLoop( DASessionRef session, CFRunLoopRef runLoop, CFStringRef runLoopMode ); -extern void DASessionUnscheduleFromRunLoop( DASessionRef session, CFRunLoopRef runLoop, CFStringRef runLoopMode ); -extern void DASessionSetDispatchQueue( DASessionRef session, dispatch_queue_t _Nullable queue ); - - - - - - -typedef struct __attribute__((objc_bridge(id))) __DASession * DAApprovalSessionRef __attribute__((availability(swift, unavailable, message="Use DASessionRef instead"))); - - - - - - -extern CFTypeID DAApprovalSessionGetTypeID( void ) __attribute__((availability(swift, unavailable, message="Use DASessionGetTypeID instead"))); -extern DAApprovalSessionRef _Nullable DAApprovalSessionCreate( CFAllocatorRef _Nullable allocator ) __attribute__((availability(swift, unavailable, message="Use DASessionCreate instead"))); -extern void DAApprovalSessionScheduleWithRunLoop( DAApprovalSessionRef session, CFRunLoopRef runLoop, CFStringRef runLoopMode ) __attribute__((availability(swift, unavailable, message="Use DASessionSetDispatchQueue instead"))); -extern void DAApprovalSessionUnscheduleFromRunLoop( DAApprovalSessionRef session, CFRunLoopRef runLoop, CFStringRef runLoopMode ) __attribute__((availability(swift, unavailable, message="Use DASessionSetDispatchQueue instead"))); - - - - - - - -} - - -extern "C" { - - - - - -extern const CFStringRef kDADiskDescriptionVolumeKindKey; -extern const CFStringRef kDADiskDescriptionVolumeMountableKey; -extern const CFStringRef kDADiskDescriptionVolumeNameKey; -extern const CFStringRef kDADiskDescriptionVolumeNetworkKey; -extern const CFStringRef kDADiskDescriptionVolumePathKey; -extern const CFStringRef kDADiskDescriptionVolumeTypeKey; -extern const CFStringRef kDADiskDescriptionVolumeUUIDKey; - -extern const CFStringRef kDADiskDescriptionMediaBlockSizeKey; -extern const CFStringRef kDADiskDescriptionMediaBSDMajorKey; -extern const CFStringRef kDADiskDescriptionMediaBSDMinorKey; -extern const CFStringRef kDADiskDescriptionMediaBSDNameKey; -extern const CFStringRef kDADiskDescriptionMediaBSDUnitKey; -extern const CFStringRef kDADiskDescriptionMediaContentKey; -extern const CFStringRef kDADiskDescriptionMediaEjectableKey; -extern const CFStringRef kDADiskDescriptionMediaIconKey; -extern const CFStringRef kDADiskDescriptionMediaKindKey; -extern const CFStringRef kDADiskDescriptionMediaLeafKey; -extern const CFStringRef kDADiskDescriptionMediaNameKey; -extern const CFStringRef kDADiskDescriptionMediaPathKey; -extern const CFStringRef kDADiskDescriptionMediaRemovableKey; -extern const CFStringRef kDADiskDescriptionMediaSizeKey; -extern const CFStringRef kDADiskDescriptionMediaTypeKey; -extern const CFStringRef kDADiskDescriptionMediaUUIDKey; -extern const CFStringRef kDADiskDescriptionMediaWholeKey; -extern const CFStringRef kDADiskDescriptionMediaWritableKey; - -extern const CFStringRef kDADiskDescriptionDeviceGUIDKey; -extern const CFStringRef kDADiskDescriptionDeviceInternalKey; -extern const CFStringRef kDADiskDescriptionDeviceModelKey; -extern const CFStringRef kDADiskDescriptionDevicePathKey; -extern const CFStringRef kDADiskDescriptionDeviceProtocolKey; -extern const CFStringRef kDADiskDescriptionDeviceRevisionKey; -extern const CFStringRef kDADiskDescriptionDeviceUnitKey; -extern const CFStringRef kDADiskDescriptionDeviceVendorKey; - -extern const CFStringRef kDADiskDescriptionBusNameKey; -extern const CFStringRef kDADiskDescriptionBusPathKey; -typedef struct __attribute__((objc_bridge(id))) __DADisk * DADiskRef; - - - - - - -extern CFTypeID DADiskGetTypeID( void ); -extern DADiskRef _Nullable DADiskCreateFromBSDName( CFAllocatorRef _Nullable allocator, DASessionRef session, const char * name ); -extern DADiskRef _Nullable DADiskCreateFromIOMedia( CFAllocatorRef _Nullable allocator, DASessionRef session, io_service_t media ); -extern DADiskRef _Nullable DADiskCreateFromVolumePath( CFAllocatorRef _Nullable allocator, DASessionRef session, CFURLRef path ); -extern const char * _Nullable DADiskGetBSDName( DADiskRef disk ); -extern io_service_t DADiskCopyIOMedia( DADiskRef disk ); -extern CFDictionaryRef _Nullable DADiskCopyDescription( DADiskRef disk ); -extern DADiskRef _Nullable DADiskCopyWholeDisk( DADiskRef disk ); - - - - - - - -} -extern "C" { - - - - - - -struct HFSUniStr255 { - u_int16_t length; - u_int16_t unicode[255]; -} __attribute__((aligned(2), packed)); -typedef struct HFSUniStr255 HFSUniStr255; -typedef const HFSUniStr255 *ConstHFSUniStr255Param; - - - - -} - - - - - - - - -extern "C" { - - -#pragma pack(push, 2) -enum { - fsCurPerm = 0x00, - fsRdPerm = 0x01, - fsWrPerm = 0x02, - fsRdWrPerm = 0x03, - fsRdWrShPerm = 0x04 -}; -enum { - fsRdAccessPerm = 0x01, - fsWrAccessPerm = 0x02, - fsRdDenyPerm = 0x10, - fsWrDenyPerm = 0x20 -}; - -enum { - fsRtParID = 1, - fsRtDirID = 2 -}; - -enum { - fsAtMark = 0, - fsFromStart = 1, - fsFromLEOF = 2, - fsFromMark = 3 -}; - -enum { - - kFSAllowConcurrentAsyncIOBit = 3, - kFSAllowConcurrentAsyncIOMask = 0x0008, - kFSPleaseCacheBit = 4, - kFSPleaseCacheMask = 0x0010, - kFSNoCacheBit = 5, - kFSNoCacheMask = 0x0020, - kFSRdVerifyBit = 6, - kFSRdVerifyMask = 0x0040, - kFSForceReadBit = 6, - kFSForceReadMask = 0x0040, - kFSNewLineBit = 7, - kFSNewLineMask = 0x0080, - kFSNewLineCharMask = 0xFF00 -}; - - -enum { - - fsSBPartialName = 0x01, - fsSBFullName = 0x02, - fsSBFlAttrib = 0x04, - fsSBFlFndrInfo = 0x08, - fsSBFlLgLen = 0x20, - fsSBFlPyLen = 0x40, - fsSBFlRLgLen = 0x80, - fsSBFlRPyLen = 0x0100, - fsSBFlCrDat = 0x0200, - fsSBFlMdDat = 0x0400, - fsSBFlBkDat = 0x0800, - fsSBFlXFndrInfo = 0x1000, - fsSBFlParID = 0x2000, - fsSBNegate = 0x4000, - fsSBDrUsrWds = 0x08, - fsSBDrNmFls = 0x10, - fsSBDrCrDat = 0x0200, - fsSBDrMdDat = 0x0400, - fsSBDrBkDat = 0x0800, - fsSBDrFndrInfo = 0x1000, - fsSBDrParID = 0x2000, - fsSBNodeID = 0x8000, - fsSBAttributeModDate = 0x00010000, - fsSBAccessDate = 0x00020000, - fsSBPermissions = 0x00040000, - fsSBSkipPackageContents = 0x00080000, - fsSBSkipHiddenItems = 0x00100000, - fsSBUserID = 0x00200000, - fsSBGroupID = 0x00400000 -}; - -enum { - - fsSBPartialNameBit = 0, - fsSBFullNameBit = 1, - fsSBFlAttribBit = 2, - fsSBFlFndrInfoBit = 3, - fsSBFlLgLenBit = 5, - fsSBFlPyLenBit = 6, - fsSBFlRLgLenBit = 7, - fsSBFlRPyLenBit = 8, - fsSBFlCrDatBit = 9, - fsSBFlMdDatBit = 10, - fsSBFlBkDatBit = 11, - fsSBFlXFndrInfoBit = 12, - fsSBFlParIDBit = 13, - fsSBNegateBit = 14, - fsSBDrUsrWdsBit = 3, - fsSBDrNmFlsBit = 4, - fsSBDrCrDatBit = 9, - fsSBDrMdDatBit = 10, - fsSBDrBkDatBit = 11, - fsSBDrFndrInfoBit = 12, - fsSBDrParIDBit = 13, - fsSBNodeIDBit = 15, - fsSBAttributeModDateBit = 16, - fsSBAccessDateBit = 17, - fsSBPermissionsBit = 18, - fsSBSkipPackageContentsBit = 19, - fsSBSkipHiddenItemsBit = 20, - fsSBUserIDBit = 21, - fsSBGroupIDBit = 22 -}; - -enum { - - bLimitFCBs = 31, - bLocalWList = 30, - bNoMiniFndr = 29, - bNoVNEdit = 28, - bNoLclSync = 27, - bTrshOffLine = 26, - bNoSwitchTo = 25, - bNoDeskItems = 20, - bNoBootBlks = 19, - bAccessCntl = 18, - bNoSysDir = 17, - bHasExtFSVol = 16, - bHasOpenDeny = 15, - bHasCopyFile = 14, - bHasMoveRename = 13, - bHasDesktopMgr = 12, - bHasShortName = 11, - bHasFolderLock = 10, - bHasPersonalAccessPrivileges = 9, - bHasUserGroupList = 8, - bHasCatSearch = 7, - bHasFileIDs = 6, - bHasBTreeMgr = 5, - bHasBlankAccessPrivileges = 4, - bSupportsAsyncRequests = 3, - bSupportsTrashVolumeCache = 2 -}; - -enum { - - bHasDirectIO = 1 -}; - -enum { - - bIsEjectable = 0, - bSupportsHFSPlusAPIs = 1, - bSupportsFSCatalogSearch = 2, - bSupportsFSExchangeObjects = 3, - bSupports2TBFiles = 4, - bSupportsLongNames = 5, - bSupportsMultiScriptNames = 6, - bSupportsNamedForks = 7, - bSupportsSubtreeIterators = 8, - bL2PCanMapFileBlocks = 9, - bParentModDateChanges = 10, - bAncestorModDateChanges = 11, - bSupportsSymbolicLinks = 13, - bIsAutoMounted = 14, - bAllowCDiDataHandler = 17, - bSupportsExclusiveLocks = 18, - bSupportsJournaling = 19, - bNoVolumeSizes = 20, - bIsOnInternalBus = 21, - bIsCaseSensitive = 22, - bIsCasePreserving = 23, - bDoNotDisplay = 24, - bIsRemovable = 25, - bNoRootTimes = 26, - bIsOnExternalBus = 27, - bSupportsExtendedFileSecurity = 28 -}; - - - - - - -enum { - - kWidePosOffsetBit = 8, - kUseWidePositioning = (1 << kWidePosOffsetBit), - kMaximumBlocksIn4GB = 0x007FFFFF -}; - -enum { - - fsUnixPriv = 1 -}; - -enum { - - kNoUserAuthentication = 1, - kPassword = 2, - kEncryptPassword = 3, - kTwoWayEncryptPassword = 6 -}; - - - -enum { - knoUser = 0, - kadministratorUser = 1 -}; - -enum { - knoGroup = 0 -}; - - -typedef SInt16 FSVolumeRefNum; - -typedef int FSIORefNum; - - - - -enum { - kFSInvalidVolumeRefNum = 0 -}; - -struct FSRef { - UInt8 hidden[80]; -}; -typedef struct FSRef FSRef; -typedef FSRef * FSRefPtr; -typedef struct __FSFileSecurity* FSFileSecurityRef; - -struct CatPositionRec { - SInt32 initialize; - SInt16 priv[6]; -}; -typedef struct CatPositionRec CatPositionRec; - -struct FSSpec { - UInt8 hidden[70]; -}; -typedef struct FSSpec FSSpec; -typedef FSSpec * FSSpecPtr; -typedef FSSpecPtr * FSSpecHandle; - -typedef FSSpecPtr FSSpecArrayPtr; - - - - -typedef const FSSpec * ConstFSSpecPtr; -typedef union ParamBlockRec ParamBlockRec; - -typedef void * ParmBlkPtr; - - - - -typedef void ( * IOCompletionProcPtr)(ParmBlkPtr paramBlock); -typedef IOCompletionProcPtr IOCompletionUPP; -struct FSPermissionInfo { - UInt32 userID; - UInt32 groupID; - UInt8 reserved1; - UInt8 userAccess; - UInt16 mode; - FSFileSecurityRef fileSec; -}; -typedef struct FSPermissionInfo FSPermissionInfo; - - -typedef UInt32 FSCatalogInfoBitmap; -enum { - kFSCatInfoNone = 0x00000000, - kFSCatInfoTextEncoding = 0x00000001, - kFSCatInfoNodeFlags = 0x00000002, - kFSCatInfoVolume = 0x00000004, - kFSCatInfoParentDirID = 0x00000008, - kFSCatInfoNodeID = 0x00000010, - kFSCatInfoCreateDate = 0x00000020, - kFSCatInfoContentMod = 0x00000040, - kFSCatInfoAttrMod = 0x00000080, - kFSCatInfoAccessDate = 0x00000100, - kFSCatInfoBackupDate = 0x00000200, - kFSCatInfoPermissions = 0x00000400, - kFSCatInfoFinderInfo = 0x00000800, - kFSCatInfoFinderXInfo = 0x00001000, - kFSCatInfoValence = 0x00002000, - kFSCatInfoDataSizes = 0x00004000, - kFSCatInfoRsrcSizes = 0x00008000, - kFSCatInfoSharingFlags = 0x00010000, - kFSCatInfoUserPrivs = 0x00020000, - kFSCatInfoUserAccess = 0x00080000, - kFSCatInfoSetOwnership = 0x00100000, - kFSCatInfoFSFileSecurityRef = 0x00400000, - kFSCatInfoAllDates = 0x000003E0, - kFSCatInfoGettableInfo = 0x0003FFFF, - kFSCatInfoSettableInfo = 0x00001FE3, - kFSCatInfoReserved = (int)0xFFFC0000 -}; - - -enum { - kFSNodeLockedBit = 0, - kFSNodeLockedMask = 0x0001, - kFSNodeResOpenBit = 2, - kFSNodeResOpenMask = 0x0004, - kFSNodeDataOpenBit = 3, - kFSNodeDataOpenMask = 0x0008, - kFSNodeIsDirectoryBit = 4, - kFSNodeIsDirectoryMask = 0x0010, - kFSNodeCopyProtectBit = 6, - kFSNodeCopyProtectMask = 0x0040, - kFSNodeForkOpenBit = 7, - kFSNodeForkOpenMask = 0x0080, - kFSNodeHardLinkBit = 8, - kFSNodeHardLinkMask = 0x00000100 -}; - - -enum { - kFSNodeInSharedBit = 2, - kFSNodeInSharedMask = 0x0004, - kFSNodeIsMountedBit = 3, - kFSNodeIsMountedMask = 0x0008, - kFSNodeIsSharePointBit = 5, - kFSNodeIsSharePointMask = 0x0020 -}; -struct FSCatalogInfo { - - - - - - UInt16 nodeFlags; - - - - - FSVolumeRefNum volume; - - - - - - UInt32 parentDirID; - - - - - UInt32 nodeID; - - - - - - UInt8 sharingFlags; - UInt8 userPrivileges; - UInt8 reserved1; - - - - - UInt8 reserved2; - - - - - UTCDateTime createDate; - - - - - - UTCDateTime contentModDate; - - - - - - UTCDateTime attributeModDate; - - - - - - UTCDateTime accessDate; - - - - - - UTCDateTime backupDate; - - - - - - FSPermissionInfo permissions; - - - - - - UInt8 finderInfo[16]; - - - - - - UInt8 extFinderInfo[16]; - - - - - - - UInt64 dataLogicalSize; - - - - - - UInt64 dataPhysicalSize; - - - - - - UInt64 rsrcLogicalSize; - - - - - - UInt64 rsrcPhysicalSize; - - - - - - UInt32 valence; - - - - - - TextEncoding textEncodingHint; -}; -typedef struct FSCatalogInfo FSCatalogInfo; -typedef FSCatalogInfo * FSCatalogInfoPtr; -struct FSRefParam { - QElemPtr qLink; - SInt16 qType; - SInt16 ioTrap; - Ptr ioCmdAddr; - IOCompletionUPP ioCompletion; - volatile OSErr ioResult; - ConstStringPtr ioNamePtr; - FSVolumeRefNum ioVRefNum; - - SInt16 reserved1; - UInt8 reserved2; - UInt8 reserved3; - - const FSRef * ref; - FSCatalogInfoBitmap whichInfo; - FSCatalogInfo * catInfo; - UniCharCount nameLength; - const UniChar * name; - UInt32 ioDirID; - FSSpecPtr spec; - FSRef * parentRef; - FSRef * newRef; - TextEncoding textEncodingHint; - HFSUniStr255 * outName; -}; -typedef struct FSRefParam FSRefParam; -typedef FSRefParam * FSRefParamPtr; - -struct FSRefForkIOParam { - QElemPtr qLink; - SInt16 qType; - SInt16 ioTrap; - Ptr ioCmdAddr; - IOCompletionUPP ioCompletion; - volatile OSErr ioResult; - const FSRef * parentRef; - UniCharCount nameLength; - const UniChar * name; - FSCatalogInfoBitmap whichInfo; - const FSCatalogInfo * catInfo; - UniCharCount forkNameLength; - const UniChar * forkName; - SInt8 permissions; - UInt8 reserved1; - FSIORefNum forkRefNum; - FSRef * newRef; -}; -typedef struct FSRefForkIOParam FSRefForkIOParam; -typedef FSRefForkIOParam * FSRefForkIOParamPtr; -typedef struct OpaqueFSIterator* FSIterator; -enum { - kFSIterateFlat = 0, - kFSIterateSubtree = 1, - kFSIterateDelete = 2, - kFSIterateReserved = (int)0xFFFFFFFC -}; - -typedef OptionBits FSIteratorFlags; -struct FSSearchParams { - Duration searchTime; - OptionBits searchBits; - UniCharCount searchNameLength; - const UniChar * searchName; - FSCatalogInfo * searchInfo1; - FSCatalogInfo * searchInfo2; -}; -typedef struct FSSearchParams FSSearchParams; -typedef FSSearchParams * FSSearchParamsPtr; -struct FSCatalogBulkParam { - QElemPtr qLink; - SInt16 qType; - SInt16 ioTrap; - Ptr ioCmdAddr; - IOCompletionUPP ioCompletion; - volatile OSErr ioResult; - Boolean containerChanged; - UInt8 reserved; - - FSIteratorFlags iteratorFlags; - FSIterator iterator; - const FSRef * container; - ItemCount maximumItems; - ItemCount actualItems; - FSCatalogInfoBitmap whichInfo; - FSCatalogInfo * catalogInfo; - FSRef * refs; - FSSpecPtr specs; - HFSUniStr255 * names; - const FSSearchParams * searchParams; -}; -typedef struct FSCatalogBulkParam FSCatalogBulkParam; -typedef FSCatalogBulkParam * FSCatalogBulkParamPtr; -typedef UInt16 FSAllocationFlags; -enum { - kFSAllocDefaultFlags = 0x0000, - kFSAllocAllOrNothingMask = 0x0001, - kFSAllocContiguousMask = 0x0002, - kFSAllocNoRoundUpMask = 0x0004, - kFSAllocReservedMask = 0xFFF8 -}; - -struct FSForkIOParam { - QElemPtr qLink; - SInt16 qType; - SInt16 ioTrap; - Ptr ioCmdAddr; - IOCompletionUPP ioCompletion; - volatile OSErr ioResult; - void * reserved1; - SInt16 reserved2; - FSIORefNum forkRefNum; - UInt8 reserved3; - SInt8 permissions; - const FSRef * ref; - - - Ptr buffer; - UInt32 requestCount; - UInt32 actualCount; - UInt16 positionMode; - SInt64 positionOffset; - - FSAllocationFlags allocationFlags; - UInt64 allocationAmount; - - UniCharCount forkNameLength; - const UniChar * forkName; - - CatPositionRec forkIterator; - HFSUniStr255 * outForkName; -}; -typedef struct FSForkIOParam FSForkIOParam; -typedef FSForkIOParam * FSForkIOParamPtr; -typedef UInt8 FSForkInfoFlags; -struct FSForkInfo { - FSForkInfoFlags flags; - SInt8 permissions; - FSVolumeRefNum volume; - UInt32 reserved2; - UInt32 nodeID; - UInt32 forkID; - UInt64 currentPosition; - UInt64 logicalEOF; - UInt64 physicalEOF; - UInt64 process; -}; -typedef struct FSForkInfo FSForkInfo; -typedef FSForkInfo * FSForkInfoPtr; -struct FSForkCBInfoParam { - QElemPtr qLink; - SInt16 qType; - SInt16 ioTrap; - Ptr ioCmdAddr; - IOCompletionUPP ioCompletion; - volatile OSErr ioResult; - FSIORefNum desiredRefNum; - FSVolumeRefNum volumeRefNum; - FSIORefNum iterator; - FSVolumeRefNum actualRefNum; - - FSRef * ref; - FSForkInfo * forkInfo; - HFSUniStr255 * forkName; -}; -typedef struct FSForkCBInfoParam FSForkCBInfoParam; -typedef FSForkCBInfoParam * FSForkCBInfoParamPtr; - -struct FSRangeLockParam { - QElemPtr qLink; - SInt16 qType; - SInt16 ioTrap; - Ptr ioCmdAddr; - IOCompletionUPP ioCompletion; - volatile OSErr ioResult; - FSIORefNum forkRefNum; - UInt64 requestCount; - UInt16 positionMode; - SInt64 positionOffset; - UInt64 rangeStart; - -}; -typedef struct FSRangeLockParam FSRangeLockParam; -typedef FSRangeLockParam * FSRangeLockParamPtr; -typedef UInt32 FSVolumeInfoBitmap; -enum { - kFSVolInfoNone = 0x0000, - kFSVolInfoCreateDate = 0x0001, - kFSVolInfoModDate = 0x0002, - kFSVolInfoBackupDate = 0x0004, - kFSVolInfoCheckedDate = 0x0008, - kFSVolInfoFileCount = 0x0010, - kFSVolInfoDirCount = 0x0020, - kFSVolInfoSizes = 0x0040, - kFSVolInfoBlocks = 0x0080, - kFSVolInfoNextAlloc = 0x0100, - kFSVolInfoRsrcClump = 0x0200, - kFSVolInfoDataClump = 0x0400, - kFSVolInfoNextID = 0x0800, - kFSVolInfoFinderInfo = 0x1000, - kFSVolInfoFlags = 0x2000, - kFSVolInfoFSInfo = 0x4000, - kFSVolInfoDriveInfo = 0x8000, - kFSVolInfoGettableInfo = 0xFFFF, - kFSVolInfoSettableInfo = 0x3004 -}; - - -enum { - kFSVolFlagDefaultVolumeBit = 5, - kFSVolFlagDefaultVolumeMask = 0x0020, - kFSVolFlagFilesOpenBit = 6, - kFSVolFlagFilesOpenMask = 0x0040, - kFSVolFlagHardwareLockedBit = 7, - kFSVolFlagHardwareLockedMask = 0x0080, - kFSVolFlagJournalingActiveBit = 14, - kFSVolFlagJournalingActiveMask = 0x4000, - kFSVolFlagSoftwareLockedBit = 15, - kFSVolFlagSoftwareLockedMask = 0x8000 -}; - - -struct FSVolumeInfo { - - UTCDateTime createDate; - UTCDateTime modifyDate; - UTCDateTime backupDate; - UTCDateTime checkedDate; - - - UInt32 fileCount; - UInt32 folderCount; - - - UInt64 totalBytes; - UInt64 freeBytes; - - - UInt32 blockSize; - UInt32 totalBlocks; - UInt32 freeBlocks; - UInt32 nextAllocation; - UInt32 rsrcClumpSize; - UInt32 dataClumpSize; - UInt32 nextCatalogID; - UInt8 finderInfo[32]; - - - UInt16 flags; - UInt16 filesystemID; - UInt16 signature; - UInt16 driveNumber; - FSIORefNum driverRefNum; -}; -typedef struct FSVolumeInfo FSVolumeInfo; -typedef FSVolumeInfo * FSVolumeInfoPtr; -struct FSVolumeInfoParam { - QElemPtr qLink; - SInt16 qType; - SInt16 ioTrap; - Ptr ioCmdAddr; - IOCompletionUPP ioCompletion; - volatile OSErr ioResult; - StringPtr ioNamePtr; - FSVolumeRefNum ioVRefNum; - - UInt32 volumeIndex; - FSVolumeInfoBitmap whichInfo; - FSVolumeInfo * volumeInfo; - HFSUniStr255 * volumeName; - FSRef * ref; -}; -typedef struct FSVolumeInfoParam FSVolumeInfoParam; -typedef FSVolumeInfoParam * FSVolumeInfoParamPtr; -struct GetVolParmsInfoBuffer { - SInt16 vMVersion; - SInt32 vMAttrib; - Handle vMLocalHand; - SInt32 vMServerAdr; - - SInt32 vMVolumeGrade; - SInt16 vMForeignPrivID; - - SInt32 vMExtendedAttributes; - - void * vMDeviceID; - - UniCharCount vMMaxNameLength; - -}; -typedef struct GetVolParmsInfoBuffer GetVolParmsInfoBuffer; - - - - - - -typedef OSType VolumeType; -enum { - - AppleShareMediaType = 'afpm' -}; - - - - -struct VolMountInfoHeader { - SInt16 length; - VolumeType media; -}; -typedef struct VolMountInfoHeader VolMountInfoHeader; -typedef VolMountInfoHeader * VolMountInfoPtr; - - - - -struct VolumeMountInfoHeader { - SInt16 length; - VolumeType media; - SInt16 flags; -}; -typedef struct VolumeMountInfoHeader VolumeMountInfoHeader; -typedef VolumeMountInfoHeader * VolumeMountInfoHeaderPtr; - -enum { - volMountNoLoginMsgFlagBit = 0, - volMountNoLoginMsgFlagMask = 0x0001, - volMountExtendedFlagsBit = 7, - volMountExtendedFlagsMask = 0x0080, - volMountInteractBit = 15, - volMountInteractMask = 0x8000, - volMountChangedBit = 14, - volMountChangedMask = 0x4000, - volMountFSReservedMask = 0x00FF, - volMountSysReservedMask = 0xFF00 -}; - - - -struct AFPVolMountInfo { - SInt16 length; - VolumeType media; - SInt16 flags; - SInt8 nbpInterval; - SInt8 nbpCount; - SInt16 uamType; - SInt16 zoneNameOffset; - SInt16 serverNameOffset; - SInt16 volNameOffset; - SInt16 userNameOffset; - SInt16 userPasswordOffset; - SInt16 volPasswordOffset; - char AFPData[144]; -}; -typedef struct AFPVolMountInfo AFPVolMountInfo; -typedef AFPVolMountInfo * AFPVolMountInfoPtr; - - - -struct AFPXVolMountInfo { - SInt16 length; - VolumeType media; - SInt16 flags; - SInt8 nbpInterval; - SInt8 nbpCount; - SInt16 uamType; - SInt16 zoneNameOffset; - SInt16 serverNameOffset; - SInt16 volNameOffset; - SInt16 userNameOffset; - SInt16 userPasswordOffset; - SInt16 volPasswordOffset; - SInt16 extendedFlags; - SInt16 uamNameOffset; - SInt16 alternateAddressOffset; - char AFPData[176]; -}; -typedef struct AFPXVolMountInfo AFPXVolMountInfo; -typedef AFPXVolMountInfo * AFPXVolMountInfoPtr; -enum { - kAFPExtendedFlagsAlternateAddressMask = 1 -}; - - -enum { - - kAFPTagTypeIP = 0x01, - kAFPTagTypeIPPort = 0x02, - kAFPTagTypeDDP = 0x03, - kAFPTagTypeDNS = 0x04 -}; - - -enum { - - kAFPTagLengthIP = 0x06, - kAFPTagLengthIPPort = 0x08, - kAFPTagLengthDDP = 0x06 -}; - -struct AFPTagData { - UInt8 fLength; - UInt8 fType; - UInt8 fData[1]; -}; -typedef struct AFPTagData AFPTagData; -struct AFPAlternateAddress { - - UInt8 fVersion; - UInt8 fAddressCount; - UInt8 fAddressList[1]; -}; -typedef struct AFPAlternateAddress AFPAlternateAddress; -enum { - kLargeIconSize = 256, - kLarge4BitIconSize = 512, - kLarge8BitIconSize = 1024, - kSmallIconSize = 64, - kSmall4BitIconSize = 128, - kSmall8BitIconSize = 256 -}; -extern IOCompletionUPP -NewIOCompletionUPP(IOCompletionProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeIOCompletionUPP(IOCompletionUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeIOCompletionUPP( - ParmBlkPtr paramBlock, - IOCompletionUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline IOCompletionUPP NewIOCompletionUPP(IOCompletionProcPtr userRoutine) { return userRoutine; } - inline void DisposeIOCompletionUPP(IOCompletionUPP) { } - inline void InvokeIOCompletionUPP(ParmBlkPtr paramBlock, IOCompletionUPP userUPP) { (*userUPP)(paramBlock); } -extern OSErr FSMakeFSRefUnicode(const FSRef *parentRef, UniCharCount nameLength, const UniChar *name, TextEncoding textEncodingHint, FSRef *newRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBMakeFSRefUnicodeSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBMakeFSRefUnicodeAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSCompareFSRefs(const FSRef *ref1, const FSRef *ref2) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBCompareFSRefsSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBCompareFSRefsAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSCreateFileUnicode(const FSRef *parentRef, UniCharCount nameLength, const UniChar *name, FSCatalogInfoBitmap whichInfo, const FSCatalogInfo *catalogInfo, FSRef *newRef, FSSpecPtr newSpec) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBCreateFileUnicodeSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBCreateFileUnicodeAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSCreateDirectoryUnicode(const FSRef *parentRef, UniCharCount nameLength, const UniChar *name, FSCatalogInfoBitmap whichInfo, const FSCatalogInfo *catalogInfo, FSRef *newRef, FSSpecPtr newSpec, UInt32 *newDirID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBCreateDirectoryUnicodeSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBCreateDirectoryUnicodeAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSDeleteObject(const FSRef * ref) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBDeleteObjectSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBDeleteObjectAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSUnlinkObject(const FSRef * ref) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSErr PBUnlinkObjectSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern void PBUnlinkObjectAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSErr FSMoveObject(const FSRef *ref, const FSRef *destDirectory, FSRef *newRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBMoveObjectSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBMoveObjectAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSExchangeObjects(const FSRef *ref, const FSRef *destRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBExchangeObjectsSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBExchangeObjectsAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -enum { - - - - - - kFSReplaceObjectDefaultOptions = 0, - - - - - - - kFSReplaceObjectReplaceMetadata = 0x01, - - - - - - - - kFSReplaceObjectSaveOriginalAsABackup = 0x02, - - - - - kFSReplaceObjectReplacePermissionInfo = 0x04, - - - - - kFSReplaceObjectPreservePermissionInfo = 0x08, - kFSReplaceObjectDoNotCheckObjectWriteAccess = 0x10 -}; -extern OSStatus FSReplaceObject(const FSRef *originalObject, const FSRef *replacementObject, CFStringRef newName, CFStringRef temporaryName, const FSRef *temporaryDirectory, OptionBits flags, FSRef *resultObject) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use NSFileManager's -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: instead. WARNING: FSReplaceObject does not work correctly in sandboxed apps."))); - extern OSStatus FSPathReplaceObject(const char *originalObjectPath, const char *replacementObjectPath, CFStringRef newName, CFStringRef temporaryName, const char *temporaryDirectoryPath, OptionBits flags) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use NSFileManager's -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: instead. WARNING: FSPathReplaceObject does not work correctly in sandboxed apps."))); -extern OSStatus FSGetTemporaryDirectoryForReplaceObject(const FSRef *originalObject, FSRef *temporaryDirectory, OptionBits flags) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus FSPathGetTemporaryDirectoryForReplaceObject(const char *originalObjectPath, char *temporaryDirectoryPath, UInt32 maxPathSize, OptionBits flags) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSErr FSRenameUnicode(const FSRef *ref, UniCharCount nameLength, const UniChar *name, TextEncoding textEncodingHint, FSRef *newRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBRenameUnicodeSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBRenameUnicodeAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSGetCatalogInfo(const FSRef *ref, FSCatalogInfoBitmap whichInfo, FSCatalogInfo *catalogInfo, HFSUniStr255 *outName, FSSpecPtr fsSpec, FSRef *parentRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBGetCatalogInfoSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBGetCatalogInfoAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSSetCatalogInfo(const FSRef *ref, FSCatalogInfoBitmap whichInfo, const FSCatalogInfo *catalogInfo) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBSetCatalogInfoSync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBSetCatalogInfoAsync(FSRefParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSOpenIterator(const FSRef *container, FSIteratorFlags iteratorFlags, FSIterator *iterator) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBOpenIteratorSync(FSCatalogBulkParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBOpenIteratorAsync(FSCatalogBulkParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSCloseIterator(FSIterator iterator) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBCloseIteratorSync(FSCatalogBulkParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBCloseIteratorAsync(FSCatalogBulkParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSGetCatalogInfoBulk(FSIterator iterator, ItemCount maximumObjects, ItemCount *actualObjects, Boolean *containerChanged, FSCatalogInfoBitmap whichInfo, FSCatalogInfo *catalogInfos, FSRef *refs, FSSpecPtr specs, HFSUniStr255 *names) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBGetCatalogInfoBulkSync(FSCatalogBulkParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBGetCatalogInfoBulkAsync(FSCatalogBulkParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSCatalogSearch(FSIterator iterator, const FSSearchParams *searchCriteria, ItemCount maximumObjects, ItemCount *actualObjects, Boolean *containerChanged, FSCatalogInfoBitmap whichInfo, FSCatalogInfo *catalogInfos, FSRef *refs, FSSpecPtr specs, HFSUniStr255 *names) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBCatalogSearchSync(FSCatalogBulkParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBCatalogSearchAsync(FSCatalogBulkParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus FSCreateFileAndOpenForkUnicode(const FSRef *parentRef, UniCharCount nameLength, const UniChar *name, FSCatalogInfoBitmap whichInfo, const FSCatalogInfo *catalogInfo, UniCharCount forkNameLength, const UniChar *forkName, SInt8 permissions, FSIORefNum *forkRefNum, FSRef *newRef) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus PBCreateFileAndOpenForkUnicodeSync(FSRefForkIOParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern void PBCreateFileAndOpenForkUnicodeAsync(FSRefForkIOParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSErr FSCreateFork(const FSRef *ref, UniCharCount forkNameLength, const UniChar *forkName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBCreateForkSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBCreateForkAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSDeleteFork(const FSRef *ref, UniCharCount forkNameLength, const UniChar *forkName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBDeleteForkSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBDeleteForkAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSIterateForks(const FSRef *ref, CatPositionRec *forkIterator, HFSUniStr255 *forkName, SInt64 *forkSize, UInt64 *forkPhysicalSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBIterateForksSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBIterateForksAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSOpenFork(const FSRef *ref, UniCharCount forkNameLength, const UniChar *forkName, SInt8 permissions, FSIORefNum *forkRefNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBOpenForkSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBOpenForkAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSReadFork(FSIORefNum forkRefNum, UInt16 positionMode, SInt64 positionOffset, ByteCount requestCount, void *buffer, ByteCount *actualCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBReadForkSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBReadForkAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSWriteFork(FSIORefNum forkRefNum, UInt16 positionMode, SInt64 positionOffset, ByteCount requestCount, const void *buffer, ByteCount *actualCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBWriteForkSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBWriteForkAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSGetForkPosition(FSIORefNum forkRefNum, SInt64 *position) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBGetForkPositionSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBGetForkPositionAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSSetForkPosition(FSIORefNum forkRefNum, UInt16 positionMode, SInt64 positionOffset) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBSetForkPositionSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBSetForkPositionAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSGetForkSize(FSIORefNum forkRefNum, SInt64 *forkSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBGetForkSizeSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBGetForkSizeAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSSetForkSize(FSIORefNum forkRefNum, UInt16 positionMode, SInt64 positionOffset) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBSetForkSizeSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBSetForkSizeAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSAllocateFork(FSIORefNum forkRefNum, FSAllocationFlags flags, UInt16 positionMode, SInt64 positionOffset, UInt64 requestCount, UInt64 *actualCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBAllocateForkSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBAllocateForkAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSFlushFork(FSIORefNum forkRefNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBFlushForkSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBFlushForkAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSCloseFork(FSIORefNum forkRefNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBCloseForkSync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBCloseForkAsync(FSForkIOParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSGetForkCBInfo(FSIORefNum desiredRefNum, FSVolumeRefNum volume, short *iterator, FSIORefNum *actualRefNum, FSForkInfo *forkInfo, FSRef *ref, HFSUniStr255 *outForkName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBGetForkCBInfoSync(FSForkCBInfoParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBGetForkCBInfoAsync(FSForkCBInfoParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus FSLockRange(FSIORefNum forkRefNum, UInt16 positionMode, SInt64 positionOffset, UInt64 requestCount, UInt64 *rangeStart) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus PBXLockRangeSync(FSRangeLockParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus PBXLockRangeAsync(FSRangeLockParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSUnlockRange(FSIORefNum forkRefNum, UInt16 positionMode, SInt64 positionOffset, UInt64 requestCount, UInt64 *rangeStart) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus PBXUnlockRangeSync(FSRangeLockParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus PBXUnlockRangeAsync(FSRangeLockParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSErr FSGetVolumeInfo(FSVolumeRefNum volume, ItemCount volumeIndex, FSVolumeRefNum *actualVolume, FSVolumeInfoBitmap whichInfo, FSVolumeInfo *info, HFSUniStr255 *volumeName, FSRef *rootDirectory) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBGetVolumeInfoSync(FSVolumeInfoParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBGetVolumeInfoAsync(FSVolumeInfoParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSSetVolumeInfo(FSVolumeRefNum volume, FSVolumeInfoBitmap whichInfo, const FSVolumeInfo *info) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr PBSetVolumeInfoSync(FSVolumeInfoParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void PBSetVolumeInfoAsync(FSVolumeInfoParam * paramBlock) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSGetDataForkName(HFSUniStr255 * dataForkName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr FSGetResourceForkName(HFSUniStr255 * resourceForkName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus FSRefMakePath(const FSRef *ref, UInt8 *path, UInt32 pathBufferSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus FSPathMakeRef(const UInt8 *path, FSRef *ref, Boolean *isDirectory) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -enum { - kFSPathMakeRefDefaultOptions = 0, - kFSPathMakeRefDoNotFollowLeafSymlink = 0x01 -}; -extern OSStatus FSPathMakeRefWithOptions(const UInt8 *path, OptionBits options, FSRef *ref, Boolean *isDirectory) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern Boolean FSIsFSRefValid(const FSRef * ref) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -typedef UInt32 FNMessage; -enum { - kFNDirectoryModifiedMessage = 1 -}; -extern OSStatus FNNotify(const FSRef *ref, FNMessage message, OptionBits flags) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus FNNotifyByPath(const UInt8 *path, FNMessage message, OptionBits flags) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus FNNotifyAll(FNMessage message, OptionBits flags) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -typedef struct OpaqueFNSubscriptionRef* FNSubscriptionRef; - - - - - -enum { - - - - - - - - kFNNoImplicitAllSubscription = (1 << 0), - - - - - - - - kFNNotifyInBackground = (1 << 1) -}; -typedef void ( * FNSubscriptionProcPtr)(FNMessage message, OptionBits flags, void *refcon, FNSubscriptionRef subscription); -typedef FNSubscriptionProcPtr FNSubscriptionUPP; -extern FNSubscriptionUPP -NewFNSubscriptionUPP(FNSubscriptionProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern void -DisposeFNSubscriptionUPP(FNSubscriptionUPP userUPP) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern void -InvokeFNSubscriptionUPP( - FNMessage message, - OptionBits flags, - void * refcon, - FNSubscriptionRef subscription, - FNSubscriptionUPP userUPP) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); - - - - inline FNSubscriptionUPP NewFNSubscriptionUPP(FNSubscriptionProcPtr userRoutine) { return userRoutine; } - inline void DisposeFNSubscriptionUPP(FNSubscriptionUPP) { } - inline void InvokeFNSubscriptionUPP(FNMessage message, OptionBits flags, void * refcon, FNSubscriptionRef subscription, FNSubscriptionUPP userUPP) { (*userUPP)(message, flags, refcon, subscription); } -extern OSStatus FNSubscribe(const FSRef *directoryRef, FNSubscriptionUPP callback, void *refcon, OptionBits flags, FNSubscriptionRef *subscription) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern OSStatus FNSubscribeByPath(const UInt8 *directoryPath, FNSubscriptionUPP callback, void *refcon, OptionBits flags, FNSubscriptionRef *subscription) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern OSStatus FNUnsubscribe(FNSubscriptionRef subscription) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern OSStatus FNGetDirectoryForSubscription(FNSubscriptionRef subscription, FSRef *ref) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); - - - - -enum { - kAsyncMountInProgress = 1, - kAsyncMountComplete = 2, - kAsyncUnmountInProgress = 3, - kAsyncUnmountComplete = 4, - kAsyncEjectInProgress = 5, - kAsyncEjectComplete = 6 -}; - - -typedef UInt32 FSMountStatus; -typedef UInt32 FSEjectStatus; -typedef UInt32 FSUnmountStatus; -typedef struct OpaqueFSVolumeOperation* FSVolumeOperation; -typedef void ( * FSVolumeMountProcPtr)(FSVolumeOperation volumeOp, void *clientData, OSStatus err, FSVolumeRefNum mountedVolumeRefNum); -typedef void ( * FSVolumeUnmountProcPtr)(FSVolumeOperation volumeOp, void *clientData, OSStatus err, FSVolumeRefNum volumeRefNum, pid_t dissenter); -typedef void ( * FSVolumeEjectProcPtr)(FSVolumeOperation volumeOp, void *clientData, OSStatus err, FSVolumeRefNum volumeRefNum, pid_t dissenter); -typedef FSVolumeMountProcPtr FSVolumeMountUPP; -typedef FSVolumeUnmountProcPtr FSVolumeUnmountUPP; -typedef FSVolumeEjectProcPtr FSVolumeEjectUPP; -extern FSVolumeMountUPP -NewFSVolumeMountUPP(FSVolumeMountProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern FSVolumeUnmountUPP -NewFSVolumeUnmountUPP(FSVolumeUnmountProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern FSVolumeEjectUPP -NewFSVolumeEjectUPP(FSVolumeEjectProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -DisposeFSVolumeMountUPP(FSVolumeMountUPP userUPP) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -DisposeFSVolumeUnmountUPP(FSVolumeUnmountUPP userUPP) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -DisposeFSVolumeEjectUPP(FSVolumeEjectUPP userUPP) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -InvokeFSVolumeMountUPP( - FSVolumeOperation volumeOp, - void * clientData, - OSStatus err, - FSVolumeRefNum mountedVolumeRefNum, - FSVolumeMountUPP userUPP) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -InvokeFSVolumeUnmountUPP( - FSVolumeOperation volumeOp, - void * clientData, - OSStatus err, - FSVolumeRefNum volumeRefNum, - pid_t dissenter, - FSVolumeUnmountUPP userUPP) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -InvokeFSVolumeEjectUPP( - FSVolumeOperation volumeOp, - void * clientData, - OSStatus err, - FSVolumeRefNum volumeRefNum, - pid_t dissenter, - FSVolumeEjectUPP userUPP) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - - - - inline FSVolumeMountUPP NewFSVolumeMountUPP(FSVolumeMountProcPtr userRoutine) { return userRoutine; } - inline FSVolumeUnmountUPP NewFSVolumeUnmountUPP(FSVolumeUnmountProcPtr userRoutine) { return userRoutine; } - inline FSVolumeEjectUPP NewFSVolumeEjectUPP(FSVolumeEjectProcPtr userRoutine) { return userRoutine; } - inline void DisposeFSVolumeMountUPP(FSVolumeMountUPP) { } - inline void DisposeFSVolumeUnmountUPP(FSVolumeUnmountUPP) { } - inline void DisposeFSVolumeEjectUPP(FSVolumeEjectUPP) { } - inline void InvokeFSVolumeMountUPP(FSVolumeOperation volumeOp, void * clientData, OSStatus err, FSVolumeRefNum mountedVolumeRefNum, FSVolumeMountUPP userUPP) { (*userUPP)(volumeOp, clientData, err, mountedVolumeRefNum); } - inline void InvokeFSVolumeUnmountUPP(FSVolumeOperation volumeOp, void * clientData, OSStatus err, FSVolumeRefNum volumeRefNum, pid_t dissenter, FSVolumeUnmountUPP userUPP) { (*userUPP)(volumeOp, clientData, err, volumeRefNum, dissenter); } - inline void InvokeFSVolumeEjectUPP(FSVolumeOperation volumeOp, void * clientData, OSStatus err, FSVolumeRefNum volumeRefNum, pid_t dissenter, FSVolumeEjectUPP userUPP) { (*userUPP)(volumeOp, clientData, err, volumeRefNum, dissenter); } -enum { - - - - - - kFSMountServerMarkDoNotDisplay = (1 << 0), - - - - - - kFSMountServerMountOnMountDir = (1 << 2), - - - - - - kFSMountServerSuppressConnectionUI = (1 << 6) -}; -enum { - - - - - - - kFSMountServerMountWithoutNotification = (1 << 1) -}; - - - - - - -enum { - kFSEjectVolumeForceEject = (1 << 0) -}; - - - - - - -enum { - kFSUnmountVolumeForceUnmount = (1 << 0) -}; -extern OSStatus FSCreateVolumeOperation(FSVolumeOperation * volumeOp) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSDisposeVolumeOperation(FSVolumeOperation volumeOp) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSMountLocalVolumeSync(CFStringRef diskID, CFURLRef mountDir, FSVolumeRefNum *mountedVolumeRefNum, OptionBits flags) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSMountLocalVolumeAsync(CFStringRef diskID, CFURLRef mountDir, FSVolumeOperation volumeOp, void *clientData, OptionBits flags, FSVolumeMountUPP callback, CFRunLoopRef runloop, CFStringRef runloopMode) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSMountServerVolumeSync(CFURLRef url, CFURLRef mountDir, CFStringRef user, CFStringRef password, FSVolumeRefNum *mountedVolumeRefNum, OptionBits flags) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSMountServerVolumeAsync(CFURLRef url, CFURLRef mountDir, CFStringRef user, CFStringRef password, FSVolumeOperation volumeOp, void *clientData, OptionBits flags, FSVolumeMountUPP callback, CFRunLoopRef runloop, CFStringRef runloopMode) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSGetAsyncMountStatus(FSVolumeOperation volumeOp, FSMountStatus *status, OSStatus *volumeOpStatus, FSVolumeRefNum *mountedVolumeRefNum, void **clientData) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSUnmountVolumeSync(FSVolumeRefNum vRefNum, OptionBits flags, pid_t *dissenter) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSUnmountVolumeAsync(FSVolumeRefNum vRefNum, OptionBits flags, FSVolumeOperation volumeOp, void *clientData, FSVolumeUnmountUPP callback, CFRunLoopRef runloop, CFStringRef runloopMode) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSGetAsyncUnmountStatus(FSVolumeOperation volumeOp, FSUnmountStatus *status, OSStatus *volumeOpStatus, FSVolumeRefNum *volumeRefNum, pid_t *dissenter, void **clientData) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSCancelVolumeOperation(FSVolumeOperation volumeOp) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSEjectVolumeSync(FSVolumeRefNum vRefNum, OptionBits flags, pid_t *dissenter) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSEjectVolumeAsync(FSVolumeRefNum vRefNum, OptionBits flags, FSVolumeOperation volumeOp, void *clientData, FSVolumeEjectUPP callback, CFRunLoopRef runloop, CFStringRef runloopMode) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSGetAsyncEjectStatus(FSVolumeOperation volumeOp, FSEjectStatus *status, OSStatus *volumeOpStatus, FSVolumeRefNum *volumeRefNum, pid_t *dissenter, void **clientData) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSCopyDiskIDForVolume(FSVolumeRefNum vRefNum, CFStringRef *diskID) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus FSCopyURLForVolume(FSVolumeRefNum vRefNum, CFURLRef *url) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern OSStatus FSGetVolumeForDiskID(CFStringRef diskID, FSVolumeRefNum *vRefNum) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSCopyDADiskForVolume(FSVolumeRefNum vRefNum, DADiskRef *disk) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSGetVolumeForDADisk(DADiskRef disk, FSVolumeRefNum *vRefNum) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); - - - - -typedef struct __FSFileOperation* FSFileOperationRef; -typedef UInt32 FSFileOperationStage; -struct FSFileOperationClientContext { - - - - - - - CFIndex version; - - - - - - void * info; - CFAllocatorRetainCallBack retain; - - - - - - CFAllocatorReleaseCallBack release; - - - - - - - - CFAllocatorCopyDescriptionCallBack copyDescription; -}; -typedef struct FSFileOperationClientContext FSFileOperationClientContext; -typedef void ( * FSFileOperationStatusProcPtr)(FSFileOperationRef fileOp, const FSRef *currentItem, FSFileOperationStage stage, OSStatus error, CFDictionaryRef statusDictionary, void *info); -typedef void ( * FSPathFileOperationStatusProcPtr)(FSFileOperationRef fileOp, const char *currentItem, FSFileOperationStage stage, OSStatus error, CFDictionaryRef statusDictionary, void *info); -enum { - - - - - - kFSFileOperationDefaultOptions = 0, - - - - - - kFSFileOperationOverwrite = 0x01, - - - - - - kFSFileOperationSkipSourcePermissionErrors = 0x02, - - - - - - kFSFileOperationDoNotMoveAcrossVolumes = 0x04, - - - - - - - kFSFileOperationSkipPreflight = 0x08 -}; -enum { - - - - - kFSOperationStageUndefined = 0, - - - - - - kFSOperationStagePreflighting = 1, - - - - - kFSOperationStageRunning = 2, - - - - - kFSOperationStageComplete = 3 -}; -extern const CFStringRef kFSOperationTotalBytesKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const CFStringRef kFSOperationBytesCompleteKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const CFStringRef kFSOperationBytesRemainingKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const CFStringRef kFSOperationTotalObjectsKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const CFStringRef kFSOperationObjectsCompleteKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const CFStringRef kFSOperationObjectsRemainingKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const CFStringRef kFSOperationTotalUserVisibleObjectsKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const CFStringRef kFSOperationUserVisibleObjectsCompleteKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const CFStringRef kFSOperationUserVisibleObjectsRemainingKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const CFStringRef kFSOperationThroughputKey __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSCopyObjectSync(const FSRef *source, const FSRef *destDir, CFStringRef destName, FSRef *target, OptionBits options) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSMoveObjectSync(const FSRef *source, const FSRef *destDir, CFStringRef destName, FSRef *target, OptionBits options) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSMoveObjectToTrashSync(const FSRef *source, FSRef *target, OptionBits options) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus FSPathCopyObjectSync(const char *sourcePath, const char *destDirPath, CFStringRef destName, char **targetPath, OptionBits options) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSPathMoveObjectSync(const char *sourcePath, const char *destDirPath, CFStringRef destName, char **targetPath, OptionBits options) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSPathMoveObjectToTrashSync(const char *sourcePath, char **targetPath, OptionBits options) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern CFTypeID FSFileOperationGetTypeID(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern FSFileOperationRef FSFileOperationCreate(CFAllocatorRef alloc) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileOperationScheduleWithRunLoop(FSFileOperationRef fileOp, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileOperationUnscheduleFromRunLoop(FSFileOperationRef fileOp, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSCopyObjectAsync(FSFileOperationRef fileOp, const FSRef *source, const FSRef *destDir, CFStringRef destName, OptionBits flags, FSFileOperationStatusProcPtr callback, CFTimeInterval statusChangeInterval, FSFileOperationClientContext *clientContext) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSMoveObjectAsync(FSFileOperationRef fileOp, const FSRef *source, const FSRef *destDir, CFStringRef destName, OptionBits flags, FSFileOperationStatusProcPtr callback, CFTimeInterval statusChangeInterval, FSFileOperationClientContext *clientContext) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSMoveObjectToTrashAsync(FSFileOperationRef fileOp, const FSRef *source, OptionBits flags, FSFileOperationStatusProcPtr callback, CFTimeInterval statusChangeInterval, FSFileOperationClientContext *clientContext) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus FSPathCopyObjectAsync(FSFileOperationRef fileOp, const char *sourcePath, const char *destDirPath, CFStringRef destName, OptionBits flags, FSPathFileOperationStatusProcPtr callback, CFTimeInterval statusChangeInterval, FSFileOperationClientContext *clientContext) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSPathMoveObjectAsync(FSFileOperationRef fileOp, const char *sourcePath, const char *destDirPath, CFStringRef destName, OptionBits flags, FSPathFileOperationStatusProcPtr callback, CFTimeInterval statusChangeInterval, FSFileOperationClientContext *clientContext) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSPathMoveObjectToTrashAsync(FSFileOperationRef fileOp, const char *sourcePath, OptionBits flags, FSPathFileOperationStatusProcPtr callback, CFTimeInterval statusChangeInterval, FSFileOperationClientContext *clientContext) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus FSFileOperationCancel(FSFileOperationRef fileOp) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileOperationCopyStatus(FSFileOperationRef fileOp, FSRef *currentItem, FSFileOperationStage *stage, OSStatus *error, CFDictionaryRef *statusDictionary, void **info) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSPathFileOperationCopyStatus(FSFileOperationRef fileOp, char **currentItem, FSFileOperationStage *stage, OSStatus *error, CFDictionaryRef *statusDictionary, void **info) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern CFStringRef FSCreateStringFromHFSUniStr(CFAllocatorRef alloc, const HFSUniStr255 *uniStr) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSGetHFSUniStrFromString(CFStringRef theString, HFSUniStr255 *uniStr) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern CFTypeID FSFileSecurityGetTypeID(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern FSFileSecurityRef FSFileSecurityCreate(CFAllocatorRef alloc) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern FSFileSecurityRef FSFileSecurityCreateWithFSPermissionInfo(CFAllocatorRef alloc, const FSPermissionInfo *permissions) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern FSFileSecurityRef FSFileSecurityRefCreateCopy(CFAllocatorRef alloc, FSFileSecurityRef fileSec) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecurityGetOwnerUUID(FSFileSecurityRef fileSec, CFUUIDBytes *owner) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecuritySetOwnerUUID(FSFileSecurityRef fileSec, const CFUUIDBytes *owner) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecurityGetGroupUUID(FSFileSecurityRef fileSec, CFUUIDBytes *group) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecuritySetGroupUUID(FSFileSecurityRef fileSec, const CFUUIDBytes *group) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecurityCopyAccessControlList(FSFileSecurityRef fileSec, acl_t *accessControlList) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecuritySetAccessControlList(FSFileSecurityRef fileSec, acl_t accessControlList) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecurityGetOwner(FSFileSecurityRef fileSec, UInt32 *owner) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecuritySetOwner(FSFileSecurityRef fileSec, UInt32 owner) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecurityGetGroup(FSFileSecurityRef fileSec, UInt32 *group) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecuritySetGroup(FSFileSecurityRef fileSec, UInt32 group) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecurityGetMode(FSFileSecurityRef fileSec, UInt16 *mode) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSStatus FSFileSecuritySetMode(FSFileSecurityRef fileSec, UInt16 mode) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); - - - -enum { - - pleaseCacheBit = 4, - pleaseCacheMask = 0x0010, - noCacheBit = 5, - noCacheMask = 0x0020, - rdVerifyBit = 6, - rdVerifyMask = 0x0040, - rdVerify = 64, - forceReadBit = 6, - forceReadMask = 0x0040, - newLineBit = 7, - newLineMask = 0x0080, - newLineCharMask = 0xFF00 -}; - - - -enum { - kOwnerID2Name = 1, - kGroupID2Name = 2, - kOwnerName2ID = 3, - kGroupName2ID = 4, - kReturnNextUser = 1, - kReturnNextGroup = 2, - kReturnNextUG = 3 -}; - - -enum { - kVCBFlagsIdleFlushBit = 3, - kVCBFlagsIdleFlushMask = 0x0008, - kVCBFlagsHFSPlusAPIsBit = 4, - kVCBFlagsHFSPlusAPIsMask = 0x0010, - kVCBFlagsHardwareGoneBit = 5, - kVCBFlagsHardwareGoneMask = 0x0020, - kVCBFlagsVolumeDirtyBit = 15, - kVCBFlagsVolumeDirtyMask = 0x8000 -}; - - -enum { - kioVAtrbDefaultVolumeBit = 5, - kioVAtrbDefaultVolumeMask = 0x0020, - kioVAtrbFilesOpenBit = 6, - kioVAtrbFilesOpenMask = 0x0040, - kioVAtrbHardwareLockedBit = 7, - kioVAtrbHardwareLockedMask = 0x0080, - kioVAtrbSoftwareLockedBit = 15, - kioVAtrbSoftwareLockedMask = 0x8000 -}; - - -enum { - - kioFlAttribLockedBit = 0, - kioFlAttribLockedMask = 0x01, - kioFlAttribResOpenBit = 2, - kioFlAttribResOpenMask = 0x04, - kioFlAttribDataOpenBit = 3, - kioFlAttribDataOpenMask = 0x08, - kioFlAttribDirBit = 4, - kioFlAttribDirMask = 0x10, - ioDirFlg = 4, - ioDirMask = 0x10, - kioFlAttribCopyProtBit = 6, - kioFlAttribCopyProtMask = 0x40, - kioFlAttribFileOpenBit = 7, - kioFlAttribFileOpenMask = 0x80, - kioFlAttribInSharedBit = 2, - kioFlAttribInSharedMask = 0x04, - kioFlAttribMountedBit = 3, - kioFlAttribMountedMask = 0x08, - kioFlAttribSharePointBit = 5, - kioFlAttribSharePointMask = 0x20 -}; - - - - - -enum { - kioFCBWriteBit = 8, - kioFCBWriteMask = 0x0100, - kioFCBResourceBit = 9, - kioFCBResourceMask = 0x0200, - kioFCBWriteLockedBit = 10, - kioFCBWriteLockedMask = 0x0400, - kioFCBLargeFileBit = 11, - kioFCBLargeFileMask = 0x0800, - kioFCBSharedWriteBit = 12, - kioFCBSharedWriteMask = 0x1000, - kioFCBFileLockedBit = 13, - kioFCBFileLockedMask = 0x2000, - kioFCBOwnClumpBit = 14, - kioFCBOwnClumpMask = 0x4000, - kioFCBModifiedBit = 15, - kioFCBModifiedMask = 0x8000 -}; - - - - -enum { - kForkInfoFlagsWriteBit = (kioFCBWriteBit - 8), - kForkInfoFlagsWriteMask = (1 << kForkInfoFlagsWriteBit), - kForkInfoFlagsResourceBit = (kioFCBResourceBit - 8), - kForkInfoFlagsResourceMask = (1 << kForkInfoFlagsResourceBit), - kForkInfoFlagsWriteLockedBit = (kioFCBWriteLockedBit - 8), - kForkInfoFlagsWriteLockedMask = (1 << kForkInfoFlagsWriteLockedBit), - kForkInfoFlagsLargeFileBit = (kioFCBLargeFileBit - 8), - kForkInfoFlagsLargeFileMask = (1 << kForkInfoFlagsLargeFileBit), - kForkInfoFlagsSharedWriteBit = (kioFCBSharedWriteBit - 8), - kForkInfoFlagsSharedWriteMask = (1 << kForkInfoFlagsSharedWriteBit), - kForkInfoFlagsFileLockedBit = (kioFCBFileLockedBit - 8), - kForkInfoFlagsFileLockedMask = (1 << kForkInfoFlagsFileLockedBit), - kForkInfoFlagsOwnClumpBit = (kioFCBOwnClumpBit - 8), - kForkInfoFlagsOwnClumpMask = (1 << kForkInfoFlagsOwnClumpBit), - kForkInfoFlagsModifiedBit = (kioFCBModifiedBit - 8), - kForkInfoFlagsModifiedMask = (1 << kForkInfoFlagsModifiedBit) -}; - - - -enum { - kioACUserNoSeeFolderBit = 0, - kioACUserNoSeeFolderMask = 0x01, - kioACUserNoSeeFilesBit = 1, - kioACUserNoSeeFilesMask = 0x02, - kioACUserNoMakeChangesBit = 2, - kioACUserNoMakeChangesMask = 0x04, - kioACUserNotOwnerBit = 7, - kioACUserNotOwnerMask = 0x80 -}; - - -enum { - kioACAccessOwnerBit = 31, - kioACAccessOwnerMask = (int)0x80000000, - kioACAccessBlankAccessBit = 28, - kioACAccessBlankAccessMask = 0x10000000, - kioACAccessUserWriteBit = 26, - kioACAccessUserWriteMask = 0x04000000, - kioACAccessUserReadBit = 25, - kioACAccessUserReadMask = 0x02000000, - kioACAccessUserSearchBit = 24, - kioACAccessUserSearchMask = 0x01000000, - kioACAccessEveryoneWriteBit = 18, - kioACAccessEveryoneWriteMask = 0x00040000, - kioACAccessEveryoneReadBit = 17, - kioACAccessEveryoneReadMask = 0x00020000, - kioACAccessEveryoneSearchBit = 16, - kioACAccessEveryoneSearchMask = 0x00010000, - kioACAccessGroupWriteBit = 10, - kioACAccessGroupWriteMask = 0x00000400, - kioACAccessGroupReadBit = 9, - kioACAccessGroupReadMask = 0x00000200, - kioACAccessGroupSearchBit = 8, - kioACAccessGroupSearchMask = 0x00000100, - kioACAccessOwnerWriteBit = 2, - kioACAccessOwnerWriteMask = 0x00000004, - kioACAccessOwnerReadBit = 1, - kioACAccessOwnerReadMask = 0x00000002, - kioACAccessOwnerSearchBit = 0, - kioACAccessOwnerSearchMask = 0x00000001, - kfullPrivileges = 0x00070007, - kownerPrivileges = 0x00000007 -}; -extern OSStatus FSGetVolumeParms(FSVolumeRefNum volume, GetVolParmsInfoBuffer *buffer, ByteCount bufferSize) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus FSGetVolumeMountInfoSize(FSVolumeRefNum volume, ByteCount *size) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus FSGetVolumeMountInfo(FSVolumeRefNum volume, BytePtr buffer, ByteCount bufferSize, ByteCount *actualSize) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus FSVolumeMount(BytePtr buffer, FSVolumeRefNum *mountedVolume) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus FSFlushVolume(FSVolumeRefNum vRefNum) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus PBFlushVolumeSync(FSRefParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus PBFlushVolumeAsync(FSRefParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus PBFSCopyFileSync(FSRefParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus PBFSCopyFileAsync(FSRefParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus FSResolveNodeID(FSVolumeRefNum volume, UInt32 nodeID, FSRefPtr newRef) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus PBFSResolveNodeIDSync(FSRefParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus PBFSResolveNodeIDAsync(FSRefParamPtr paramBlock) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -#pragma pack(pop) - - -} - - - -extern "C" { - - -typedef SInt16 ResID; -typedef SInt16 ResAttributes; -typedef SInt16 ResFileAttributes; -typedef SInt16 ResourceCount; -typedef SInt16 ResourceIndex; -typedef FSIORefNum ResFileRefNum; - -enum { - resSysRefBit = 7, - resSysHeapBit = 6, - resPurgeableBit = 5, - resLockedBit = 4, - resProtectedBit = 3, - resPreloadBit = 2, - resChangedBit = 1 -}; - - -enum { - resSysHeap = 64, - resPurgeable = 32, - resLocked = 16, - resProtected = 8, - resPreload = 4, - resChanged = 2 -}; - - -enum { - mapReadOnlyBit = 7, - mapCompactBit = 6, - mapChangedBit = 5 -}; - - -enum { - mapReadOnly = 128, - mapCompact = 64, - mapChanged = 32 -}; - - -enum { - kResFileNotOpened = -1, - kSystemResFile = 0 -}; - - -typedef void ( * ResErrProcPtr)(OSErr thErr); -typedef ResErrProcPtr ResErrUPP; -extern ResErrUPP -NewResErrUPP(ResErrProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeResErrUPP(ResErrUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeResErrUPP( - OSErr thErr, - ResErrUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline ResErrUPP NewResErrUPP(ResErrProcPtr userRoutine) { return userRoutine; } - inline void DisposeResErrUPP(ResErrUPP) { } - inline void InvokeResErrUPP(OSErr thErr, ResErrUPP userUPP) { (*userUPP)(thErr); } -typedef OSErr ( * ResourceEndianFilterPtr)(Handle theResource, Boolean currentlyNativeEndian); -extern void -CloseResFile(ResFileRefNum refNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -ResError(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResFileRefNum -CurResFile(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResFileRefNum -HomeResFile(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -UseResFile(ResFileRefNum refNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResourceCount -CountTypes(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResourceCount -Count1Types(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -GetIndType( - ResType * theType, - ResourceIndex itemIndex) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -Get1IndType( - ResType * theType, - ResourceIndex itemIndex) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetResLoad(Boolean load) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResourceCount -CountResources(ResType theType) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResourceCount -Count1Resources(ResType theType) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -GetIndResource( - ResType theType, - ResourceIndex itemIndex) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -Get1IndResource( - ResType theType, - ResourceIndex itemIndex) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -GetResource( - ResType theType, - ResID theID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -Get1Resource( - ResType theType, - ResID theID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -GetNamedResource( - ResType theType, - ConstStr255Param name) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -Get1NamedResource( - ResType theType, - ConstStr255Param name) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -LoadResource(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -ReleaseResource(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DetachResource(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResID -UniqueID(ResType theType) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResID -Unique1ID(ResType theType) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResAttributes -GetResAttrs(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -GetResInfo( - Handle theResource, - ResID * theID, - ResType * theType, - Str255 name) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetResInfo( - Handle theResource, - ResID theID, - ConstStr255Param name) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -AddResource( - Handle theData, - ResType theType, - ResID theID, - ConstStr255Param name) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -GetResourceSizeOnDisk(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -GetMaxResourceSize(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetResAttrs( - Handle theResource, - ResAttributes attrs) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -ChangedResource(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -RemoveResource(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -UpdateResFile(ResFileRefNum refNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -WriteResource(Handle theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetResPurge(Boolean install) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResFileAttributes -GetResFileAttrs(ResFileRefNum refNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetResFileAttrs( - ResFileRefNum refNum, - ResFileAttributes attrs) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -ReadPartialResource( - Handle theResource, - long offset, - void * buffer, - long count) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -WritePartialResource( - Handle theResource, - long offset, - const void * buffer, - long count) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetResourceSize( - Handle theResource, - long newSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -GetNextFOND(Handle fondHandle) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -typedef SInt16 RsrcChainLocation; -enum { - kRsrcChainBelowSystemMap = 0, - kRsrcChainBelowApplicationMap = 1, - kRsrcChainAboveApplicationMap = 2, - kRsrcChainAboveAllMaps = 4 -}; -extern OSErr -InsertResourceFile( - ResFileRefNum refNum, - RsrcChainLocation where) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -DetachResourceFile(ResFileRefNum refNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetTopResourceFile(ResFileRefNum * refNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetNextResourceFile( - ResFileRefNum curRefNum, - ResFileRefNum * nextRefNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResFileRefNum -FSOpenResFile( - const FSRef * ref, - SInt8 permission) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -FSCreateResFile( - const FSRef * parentRef, - UniCharCount nameLength, - const UniChar * name, - FSCatalogInfoBitmap whichInfo, - const FSCatalogInfo * catalogInfo, - FSRef * newRef, - FSSpecPtr newSpec) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Boolean -FSResourceFileAlreadyOpen( - const FSRef * resourceFileRef, - Boolean * inChain, - ResFileRefNum * refNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSOpenOrphanResFile( - const FSRef * ref, - SignedByte permission, - ResFileRefNum * refNum) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSErr -FSCreateResourceFile( - const FSRef * parentRef, - UniCharCount nameLength, - const UniChar * name, - FSCatalogInfoBitmap whichInfo, - const FSCatalogInfo * catalogInfo, - UniCharCount forkNameLength, - const UniChar * forkName, - FSRef * newRef, - FSSpecPtr newSpec) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSCreateResourceFork( - const FSRef * ref, - UniCharCount forkNameLength, - const UniChar * forkName, - UInt32 flags) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSErr -FSOpenResourceFile( - const FSRef * ref, - UniCharCount forkNameLength, - const UniChar * forkName, - SInt8 permissions, - ResFileRefNum * refNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -} -extern "C" { - - -#pragma pack(push, 2) - -enum { - kAppleManufacturer = 'appl', - kComponentResourceType = 'thng', - kComponentAliasResourceType = 'thga' -}; - -enum { - kAnyComponentType = 0, - kAnyComponentSubType = 0, - kAnyComponentManufacturer = 0, - kAnyComponentFlagsMask = 0 -}; - -enum { - cmpThreadSafe = 1UL << 28, - cmpIsMissing = 1UL << 29, - cmpWantsRegisterMessage = 1UL << 31 -}; - -enum { - kComponentOpenSelect = -1, - kComponentCloseSelect = -2, - kComponentCanDoSelect = -3, - kComponentVersionSelect = -4, - kComponentRegisterSelect = -5, - kComponentTargetSelect = -6, - kComponentUnregisterSelect = -7, - kComponentGetMPWorkFunctionSelect = -8, - kComponentExecuteWiredActionSelect = -9, - kComponentGetPublicResourceSelect = -10 -}; - - -enum { - componentDoAutoVersion = (1 << 0), - componentWantsUnregister = (1 << 1), - componentAutoVersionIncludeFlags = (1 << 2), - componentHasMultiplePlatforms = (1 << 3), - componentLoadResident = (1 << 4) -}; - - - - -enum { - defaultComponentIdentical = 0, - defaultComponentAnyFlags = 1, - defaultComponentAnyManufacturer = 2, - defaultComponentAnySubType = 4, - defaultComponentAnyFlagsAnyManufacturer = (defaultComponentAnyFlags + defaultComponentAnyManufacturer), - defaultComponentAnyFlagsAnyManufacturerAnySubType = (defaultComponentAnyFlags + defaultComponentAnyManufacturer + defaultComponentAnySubType) -}; - - -enum { - registerComponentGlobal = 1, - registerComponentNoDuplicates = 2, - registerComponentAfterExisting = 4, - registerComponentAliasesOnly = 8 -}; - - -struct ComponentDescription { - OSType componentType; - OSType componentSubType; - OSType componentManufacturer; - UInt32 componentFlags; - UInt32 componentFlagsMask; -}; -typedef struct ComponentDescription ComponentDescription; - -struct ResourceSpec { - OSType resType; - SInt16 resID; -}; -typedef struct ResourceSpec ResourceSpec; -struct ComponentResource { - ComponentDescription cd; - ResourceSpec component; - ResourceSpec componentName; - ResourceSpec componentInfo; - ResourceSpec componentIcon; -}; -typedef struct ComponentResource ComponentResource; -typedef ComponentResource * ComponentResourcePtr; -typedef ComponentResourcePtr * ComponentResourceHandle; -struct ComponentPlatformInfo { - SInt32 componentFlags; - ResourceSpec component; - SInt16 platformType; -}; -typedef struct ComponentPlatformInfo ComponentPlatformInfo; -struct ComponentResourceExtension { - SInt32 componentVersion; - SInt32 componentRegisterFlags; - SInt16 componentIconFamily; -}; -typedef struct ComponentResourceExtension ComponentResourceExtension; -struct ComponentPlatformInfoArray { - SInt32 count; - ComponentPlatformInfo platformArray[1]; -}; -typedef struct ComponentPlatformInfoArray ComponentPlatformInfoArray; -struct ExtComponentResource { - ComponentDescription cd; - ResourceSpec component; - ResourceSpec componentName; - ResourceSpec componentInfo; - ResourceSpec componentIcon; - SInt32 componentVersion; - SInt32 componentRegisterFlags; - SInt16 componentIconFamily; - SInt32 count; - ComponentPlatformInfo platformArray[1]; -}; -typedef struct ExtComponentResource ExtComponentResource; -typedef ExtComponentResource * ExtComponentResourcePtr; -typedef ExtComponentResourcePtr * ExtComponentResourceHandle; -struct ComponentAliasResource { - ComponentResource cr; - ComponentDescription aliasCD; -}; -typedef struct ComponentAliasResource ComponentAliasResource; - -struct ComponentParameters { - UInt8 flags; - UInt8 paramSize; - SInt16 what; - - - UInt32 padding; - - - long params[1]; -}; -typedef struct ComponentParameters ComponentParameters; -struct ComponentRecord { - long data[1]; -}; -typedef struct ComponentRecord ComponentRecord; -typedef ComponentRecord * Component; -struct ComponentInstanceRecord { - long data[1]; -}; -typedef struct ComponentInstanceRecord ComponentInstanceRecord; -typedef ComponentInstanceRecord * ComponentInstance; -struct RegisteredComponentRecord { - long data[1]; -}; -typedef struct RegisteredComponentRecord RegisteredComponentRecord; -typedef RegisteredComponentRecord * RegisteredComponentRecordPtr; -struct RegisteredComponentInstanceRecord { - long data[1]; -}; -typedef struct RegisteredComponentInstanceRecord RegisteredComponentInstanceRecord; -typedef RegisteredComponentInstanceRecord * RegisteredComponentInstanceRecordPtr; -typedef SInt32 ComponentResult; -enum { - platform68k = 1, - platformPowerPC = 2, - platformInterpreted = 3, - platformWin32 = 4, - platformPowerPCNativeEntryPoint = 5, - platformIA32NativeEntryPoint = 6, - platformPowerPC64NativeEntryPoint = 7, - platformX86_64NativeEntryPoint = 8 -}; - -enum { - platformIRIXmips = 1000, - platformSunOSsparc = 1100, - platformSunOSintel = 1101, - platformLinuxppc = 1200, - platformLinuxintel = 1201, - platformAIXppc = 1300, - platformNeXTIntel = 1400, - platformNeXTppc = 1401, - platformNeXTsparc = 1402, - platformNeXT68k = 1403, - platformMacOSx86 = 1500 -}; - -enum { - mpWorkFlagDoWork = (1 << 0), - mpWorkFlagDoCompletion = (1 << 1), - mpWorkFlagCopyWorkBlock = (1 << 2), - mpWorkFlagDontBlock = (1 << 3), - mpWorkFlagGetProcessorCount = (1 << 4), - mpWorkFlagGetIsRunning = (1 << 6) -}; - -enum { - cmpAliasNoFlags = 0, - cmpAliasOnlyThisFile = 1 -}; - -typedef UInt32 CSComponentsThreadMode; -enum { - kCSAcceptAllComponentsMode = 0, - kCSAcceptThreadSafeComponentsOnlyMode = 1 -}; -extern void -CSSetComponentsThreadMode(CSComponentsThreadMode mode) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern CSComponentsThreadMode -CSGetComponentsThreadMode(void) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); - - -struct ComponentMPWorkFunctionHeaderRecord { - UInt32 headerSize; - UInt32 recordSize; - UInt32 workFlags; - UInt16 processorCount; - UInt8 unused; - UInt8 isRunning; -}; -typedef struct ComponentMPWorkFunctionHeaderRecord ComponentMPWorkFunctionHeaderRecord; -typedef ComponentMPWorkFunctionHeaderRecord * ComponentMPWorkFunctionHeaderRecordPtr; -typedef ComponentResult ( * ComponentMPWorkFunctionProcPtr)(void *globalRefCon, ComponentMPWorkFunctionHeaderRecordPtr header); -typedef ComponentResult ( * ComponentRoutineProcPtr)(ComponentParameters *cp, Handle componentStorage); -typedef OSErr ( * GetMissingComponentResourceProcPtr)(Component c, OSType resType, SInt16 resID, void *refCon, Handle *resource); -typedef ComponentMPWorkFunctionProcPtr ComponentMPWorkFunctionUPP; -typedef ComponentRoutineProcPtr ComponentRoutineUPP; -typedef GetMissingComponentResourceProcPtr GetMissingComponentResourceUPP; - - - - - -typedef UniversalProcPtr ComponentFunctionUPP; -extern ComponentFunctionUPP -NewComponentFunctionUPP( - ProcPtr userRoutine, - ProcInfoType procInfo) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeComponentFunctionUPP(ComponentFunctionUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Component -RegisterComponent( - ComponentDescription * cd, - ComponentRoutineUPP componentEntryPoint, - SInt16 global, - Handle componentName, - Handle componentInfo, - Handle componentIcon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Component -RegisterComponentResource( - ComponentResourceHandle cr, - SInt16 global) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -UnregisterComponent(Component aComponent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Component -FindNextComponent( - Component aComponent, - ComponentDescription * looking) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -CountComponents(ComponentDescription * looking) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetComponentInfo( - Component aComponent, - ComponentDescription * cd, - Handle componentName, - Handle componentInfo, - Handle componentIcon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -GetComponentListModSeed(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -GetComponentTypeModSeed(OSType componentType) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -OpenAComponent( - Component aComponent, - ComponentInstance * ci) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentInstance -OpenComponent(Component aComponent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -CloseComponent(ComponentInstance aComponentInstance) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetComponentInstanceError(ComponentInstance aComponentInstance) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Component -ResolveComponentAlias(Component aComponent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetComponentPublicResource( - Component aComponent, - OSType resourceType, - SInt16 resourceID, - Handle * theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetComponentPublicResourceList( - OSType resourceType, - SInt16 resourceID, - SInt32 flags, - ComponentDescription * cd, - GetMissingComponentResourceUPP missingProc, - void * refCon, - void * atomContainerPtr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetComponentPublicIndString( - Component aComponent, - Str255 theString, - SInt16 strListID, - SInt16 index) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetComponentInstanceError( - ComponentInstance aComponentInstance, - OSErr theError) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -GetComponentRefcon(Component aComponent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetComponentRefcon( - Component aComponent, - long theRefcon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ResFileRefNum -OpenComponentResFile(Component aComponent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -OpenAComponentResFile( - Component aComponent, - ResFileRefNum * resRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -CloseComponentResFile(ResFileRefNum refnum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetComponentResource( - Component aComponent, - OSType resType, - SInt16 resID, - Handle * theResource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetComponentIndString( - Component aComponent, - Str255 theString, - SInt16 strListID, - SInt16 index) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Handle -GetComponentInstanceStorage(ComponentInstance aComponentInstance) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SetComponentInstanceStorage( - ComponentInstance aComponentInstance, - Handle theStorage) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -CountComponentInstances(Component aComponent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentFunction( - ComponentParameters * params, - ComponentFunctionUPP func) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentFunctionWithStorage( - Handle storage, - ComponentParameters * params, - ComponentFunctionUPP func) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentFunctionWithStorageProcInfo( - Handle storage, - ComponentParameters * params, - ProcPtr func, - ProcInfoType funcProcInfo) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -DelegateComponentCall( - ComponentParameters * originalParams, - ComponentInstance ci) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -SetDefaultComponent( - Component aComponent, - SInt16 flags) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentInstance -OpenDefaultComponent( - OSType componentType, - OSType componentSubType) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -OpenADefaultComponent( - OSType componentType, - OSType componentSubType, - ComponentInstance * ci) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Component -CaptureComponent( - Component capturedComponent, - Component capturingComponent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -UncaptureComponent(Component aComponent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -RegisterComponentResourceFile( - SInt16 resRefNum, - SInt16 global) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -RegisterComponentFileRef( - const FSRef * ref, - SInt16 global) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -RegisterComponentFileRefEntries( - const FSRef * ref, - SInt16 global, - const ComponentDescription * toRegister, - UInt32 registerCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentOpen( - ComponentInstance ci, - ComponentInstance self) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentClose( - ComponentInstance ci, - ComponentInstance self) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentCanDo( - ComponentInstance ci, - SInt16 ftnNumber) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentVersion(ComponentInstance ci) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentRegister(ComponentInstance ci) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentTarget( - ComponentInstance ci, - ComponentInstance target) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentUnregister(ComponentInstance ci) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentGetMPWorkFunction( - ComponentInstance ci, - ComponentMPWorkFunctionUPP * workFunction, - void ** refCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentGetPublicResource( - ComponentInstance ci, - OSType resourceType, - SInt16 resourceID, - Handle * resource) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -CallComponentDispatch(ComponentParameters * cp) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentMPWorkFunctionUPP -NewComponentMPWorkFunctionUPP(ComponentMPWorkFunctionProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentRoutineUPP -NewComponentRoutineUPP(ComponentRoutineProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern GetMissingComponentResourceUPP -NewGetMissingComponentResourceUPP(GetMissingComponentResourceProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeComponentMPWorkFunctionUPP(ComponentMPWorkFunctionUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeComponentRoutineUPP(ComponentRoutineUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeGetMissingComponentResourceUPP(GetMissingComponentResourceUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -InvokeComponentMPWorkFunctionUPP( - void * globalRefCon, - ComponentMPWorkFunctionHeaderRecordPtr header, - ComponentMPWorkFunctionUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ComponentResult -InvokeComponentRoutineUPP( - ComponentParameters * cp, - Handle componentStorage, - ComponentRoutineUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -InvokeGetMissingComponentResourceUPP( - Component c, - OSType resType, - SInt16 resID, - void * refCon, - Handle * resource, - GetMissingComponentResourceUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline ComponentMPWorkFunctionUPP NewComponentMPWorkFunctionUPP(ComponentMPWorkFunctionProcPtr userRoutine) { return userRoutine; } - inline ComponentRoutineUPP NewComponentRoutineUPP(ComponentRoutineProcPtr userRoutine) { return userRoutine; } - inline GetMissingComponentResourceUPP NewGetMissingComponentResourceUPP(GetMissingComponentResourceProcPtr userRoutine) { return userRoutine; } - inline void DisposeComponentMPWorkFunctionUPP(ComponentMPWorkFunctionUPP) { } - inline void DisposeComponentRoutineUPP(ComponentRoutineUPP) { } - inline void DisposeGetMissingComponentResourceUPP(GetMissingComponentResourceUPP) { } - inline ComponentResult InvokeComponentMPWorkFunctionUPP(void * globalRefCon, ComponentMPWorkFunctionHeaderRecordPtr header, ComponentMPWorkFunctionUPP userUPP) { return (*userUPP)(globalRefCon, header); } - inline ComponentResult InvokeComponentRoutineUPP(ComponentParameters * cp, Handle componentStorage, ComponentRoutineUPP userUPP) { return (*userUPP)(cp, componentStorage); } - inline OSErr InvokeGetMissingComponentResourceUPP(Component c, OSType resType, SInt16 resID, void * refCon, Handle * resource, GetMissingComponentResourceUPP userUPP) { return (*userUPP)(c, resType, resID, refCon, resource); } -enum { - uppComponentFunctionImplementedProcInfo = 0x000002F0, - uppGetComponentVersionProcInfo = 0x000000F0, - uppComponentSetTargetProcInfo = 0x000003F0, - uppCallComponentOpenProcInfo = 0x000003F0, - uppCallComponentCloseProcInfo = 0x000003F0, - uppCallComponentCanDoProcInfo = 0x000002F0, - uppCallComponentVersionProcInfo = 0x000000F0, - uppCallComponentRegisterProcInfo = 0x000000F0, - uppCallComponentTargetProcInfo = 0x000003F0, - uppCallComponentUnregisterProcInfo = 0x000000F0, - uppCallComponentGetMPWorkFunctionProcInfo = 0x00000FF0, - uppCallComponentGetPublicResourceProcInfo = 0x00003BF0 -}; - - - - - - - -#pragma pack(pop) - - -} -extern "C" { - - -#pragma options align=power -enum { - MPLibrary_MajorVersion = 2, - MPLibrary_MinorVersion = 3, - MPLibrary_Release = 1, - MPLibrary_DevelopmentRevision = 1 -}; - - - -typedef struct OpaqueMPProcessID* MPProcessID; -typedef struct OpaqueMPTaskID* MPTaskID; -typedef struct OpaqueMPQueueID* MPQueueID; -typedef struct OpaqueMPSemaphoreID* MPSemaphoreID; -typedef struct OpaqueMPCriticalRegionID* MPCriticalRegionID; -typedef struct OpaqueMPTimerID* MPTimerID; -typedef struct OpaqueMPEventID* MPEventID; -typedef struct OpaqueMPAddressSpaceID* MPAddressSpaceID; -typedef struct OpaqueMPNotificationID* MPNotificationID; -typedef struct OpaqueMPCoherenceID* MPCoherenceID; -typedef struct OpaqueMPCpuID* MPCpuID; -typedef struct OpaqueMPAreaID* MPAreaID; -typedef struct OpaqueMPConsoleID* MPConsoleID; -typedef struct OpaqueMPOpaqueID* MPOpaqueID; -enum { - - kOpaqueAnyID = 0, - kOpaqueProcessID = 1, - kOpaqueTaskID = 2, - kOpaqueTimerID = 3, - kOpaqueQueueID = 4, - kOpaqueSemaphoreID = 5, - kOpaqueCriticalRegionID = 6, - kOpaqueCpuID = 7, - kOpaqueAddressSpaceID = 8, - kOpaqueEventID = 9, - kOpaqueCoherenceID = 10, - kOpaqueAreaID = 11, - kOpaqueNotificationID = 12, - kOpaqueConsoleID = 13 -}; - -typedef UInt32 MPOpaqueIDClass; - -enum { - kMPNoID = 0 -}; - - -typedef OptionBits MPTaskOptions; -typedef ItemCount TaskStorageIndex; -typedef LogicalAddress TaskStorageValue; -typedef ItemCount MPSemaphoreCount; -typedef UInt32 MPTaskWeight; -typedef UInt32 MPEventFlags; -typedef UInt32 MPExceptionKind; -typedef UInt32 MPTaskStateKind; -typedef UInt32 MPPageSizeClass; - -enum { - kDurationImmediate = 0, - kDurationForever = 0x7FFFFFFF, - kDurationMillisecond = 1, - kDurationMicrosecond = -1 -}; -extern ItemCount -MPProcessors(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern ItemCount -MPProcessorsScheduled(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -enum { - - kMPCreateTaskSuspendedMask = 1L << 0, - kMPCreateTaskTakesAllExceptionsMask = 1L << 1, - kMPCreateTaskNotDebuggableMask = 1L << 2, - kMPCreateTaskValidOptionsMask = kMPCreateTaskSuspendedMask | kMPCreateTaskTakesAllExceptionsMask | kMPCreateTaskNotDebuggableMask -}; - - - - - - - -typedef OSStatus ( * TaskProc)(void * parameter); -extern OSStatus -MPCreateTask( - TaskProc entryPoint, - void * parameter, - ByteCount stackSize, - MPQueueID notifyQueue, - void * terminationParameter1, - void * terminationParameter2, - MPTaskOptions options, - MPTaskID * task) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPTerminateTask( - MPTaskID task, - OSStatus terminationStatus) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPSetTaskWeight( - MPTaskID task, - MPTaskWeight weight) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern Boolean -MPTaskIsPreemptive(MPTaskID taskID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -MPExit(OSStatus status) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -MPYield(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern MPTaskID -MPCurrentTaskID(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPSetTaskType( - MPTaskID task, - OSType taskType) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern OSStatus -MPAllocateTaskStorageIndex(TaskStorageIndex * taskIndex) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPDeallocateTaskStorageIndex(TaskStorageIndex taskIndex) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPSetTaskStorageValue( - TaskStorageIndex taskIndex, - TaskStorageValue value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern TaskStorageValue -MPGetTaskStorageValue(TaskStorageIndex taskIndex) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPCreateQueue(MPQueueID * queue) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPDeleteQueue(MPQueueID queue) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPNotifyQueue( - MPQueueID queue, - void * param1, - void * param2, - void * param3) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPWaitOnQueue( - MPQueueID queue, - void ** param1, - void ** param2, - void ** param3, - Duration timeout) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPSetQueueReserve( - MPQueueID queue, - ItemCount count) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPCreateSemaphore( - MPSemaphoreCount maximumValue, - MPSemaphoreCount initialValue, - MPSemaphoreID * semaphore) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPDeleteSemaphore(MPSemaphoreID semaphore) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPSignalSemaphore(MPSemaphoreID semaphore) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPWaitOnSemaphore( - MPSemaphoreID semaphore, - Duration timeout) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPCreateCriticalRegion(MPCriticalRegionID * criticalRegion) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPDeleteCriticalRegion(MPCriticalRegionID criticalRegion) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPEnterCriticalRegion( - MPCriticalRegionID criticalRegion, - Duration timeout) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPExitCriticalRegion(MPCriticalRegionID criticalRegion) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPCreateEvent(MPEventID * event) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPDeleteEvent(MPEventID event) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPSetEvent( - MPEventID event, - MPEventFlags flags) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPWaitForEvent( - MPEventID event, - MPEventFlags * flags, - Duration timeout) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPCreateNotification(MPNotificationID * notificationID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPDeleteNotification(MPNotificationID notificationID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPModifyNotification( - MPNotificationID notificationID, - MPOpaqueID anID, - void * notifyParam1, - void * notifyParam2, - void * notifyParam3) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPModifyNotificationParameters( - MPNotificationID notificationID, - MPOpaqueIDClass kind, - void * notifyParam1, - void * notifyParam2, - void * notifyParam3) __attribute__((availability(macosx,introduced=10.1,deprecated=10.7))); -extern OSStatus -MPCauseNotification(MPNotificationID notificationID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -enum { - - kMPPreserveTimerIDMask = 1L << 0, - kMPTimeIsDeltaMask = 1L << 1, - kMPTimeIsDurationMask = 1L << 2 -}; -extern OSStatus -MPDelayUntil(AbsoluteTime * expirationTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPCreateTimer(MPTimerID * timerID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPDeleteTimer(MPTimerID timerID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPSetTimerNotify( - MPTimerID timerID, - MPOpaqueID anID, - void * notifyParam1, - void * notifyParam2, - void * notifyParam3) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPArmTimer( - MPTimerID timerID, - AbsoluteTime * expirationTime, - OptionBits options) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPCancelTimer( - MPTimerID timerID, - AbsoluteTime * timeRemaining) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -enum { - - kMPMaxAllocSize = 1024L * 1024 * 1024 -}; - -enum { - - kMPAllocateDefaultAligned = 0, - kMPAllocate8ByteAligned = 3, - kMPAllocate16ByteAligned = 4, - kMPAllocate32ByteAligned = 5, - kMPAllocate1024ByteAligned = 10, - kMPAllocate4096ByteAligned = 12, - kMPAllocateMaxAlignment = 16, - kMPAllocateAltiVecAligned = kMPAllocate16ByteAligned, - kMPAllocateVMXAligned = kMPAllocateAltiVecAligned, - kMPAllocateVMPageAligned = 254, - kMPAllocateInterlockAligned = 255 -}; - - - -enum { - - kMPAllocateClearMask = 0x0001, - kMPAllocateGloballyMask = 0x0002, - kMPAllocateResidentMask = 0x0004, - kMPAllocateNoGrowthMask = 0x0010, - kMPAllocateNoCreateMask = 0x0020 -}; -extern LogicalAddress -MPAllocateAligned( - ByteCount size, - UInt8 alignment, - OptionBits options) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern LogicalAddress -MPAllocate(ByteCount size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -MPFree(LogicalAddress object) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern ByteCount -MPGetAllocatedBlockSize(LogicalAddress object) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -MPBlockCopy( - LogicalAddress source, - LogicalAddress destination, - ByteCount size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -MPBlockClear( - LogicalAddress address, - ByteCount size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -enum { - - kMPTaskStateRegisters = 0, - kMPTaskStateFPU = 1, - kMPTaskStateVectors = 2, - kMPTaskStateMachine = 3, - kMPTaskState32BitMemoryException = 4, - kMPTaskStateTaskInfo = 5 -}; - - - -enum { - - kMPTaskPropagate = 0, - kMPTaskResumeStep = 1, - kMPTaskResumeBranch = 2, - kMPTaskResumeMask = 0x0000, - kMPTaskPropagateMask = 1 << kMPTaskPropagate, - kMPTaskResumeStepMask = 1 << kMPTaskResumeStep, - kMPTaskResumeBranchMask = 1 << kMPTaskResumeBranch -}; - - - -enum { - - kMPTaskBlocked = 0, - kMPTaskReady = 1, - kMPTaskRunning = 2 -}; - -enum { - - kMPTaskInfoVersion = 3 -}; - - -struct MPTaskInfoVersion2 { - PBVersion version; - - OSType name; - - OSType queueName; - UInt16 runState; - UInt16 lastCPU; - UInt32 weight; - - MPProcessID processID; - - AbsoluteTime cpuTime; - AbsoluteTime schedTime; - AbsoluteTime creationTime; - - ItemCount codePageFaults; - ItemCount dataPageFaults; - ItemCount preemptions; - - MPCpuID cpuID; -}; -typedef struct MPTaskInfoVersion2 MPTaskInfoVersion2; -struct MPTaskInfo { - PBVersion version; - - OSType name; - - OSType queueName; - UInt16 runState; - UInt16 lastCPU; - UInt32 weight; - - MPProcessID processID; - - AbsoluteTime cpuTime; - AbsoluteTime schedTime; - AbsoluteTime creationTime; - - ItemCount codePageFaults; - ItemCount dataPageFaults; - ItemCount preemptions; - - MPCpuID cpuID; - MPOpaqueID blockedObject; - MPAddressSpaceID spaceID; - - LogicalAddress stackBase; - LogicalAddress stackLimit; - LogicalAddress stackCurr; -}; -typedef struct MPTaskInfo MPTaskInfo; -extern OSStatus -MPSetExceptionHandler( - MPTaskID task, - MPQueueID exceptionQ) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPDisposeTaskException( - MPTaskID task, - OptionBits action) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPExtractTaskState( - MPTaskID task, - MPTaskStateKind kind, - void * info) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPSetTaskState( - MPTaskID task, - MPTaskStateKind kind, - void * info) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPThrowException( - MPTaskID task, - MPExceptionKind kind) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - -typedef UInt32 MPDebuggerLevel; -enum { - kMPLowLevelDebugger = 0x00000000, - kMPMidLevelDebugger = 0x10000000, - kMPHighLevelDebugger = 0x20000000 -}; -extern OSStatus -MPRegisterDebugger( - MPQueueID queue, - MPDebuggerLevel level) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -MPUnregisterDebugger(MPQueueID queue) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -typedef void * ( * MPRemoteProcedure)(void * parameter); - -typedef UInt8 MPRemoteContext; -enum { - kMPAnyRemoteContext = 0, - kMPOwningProcessRemoteContext = 1, - kMPInterruptRemoteContext = 2, - kMPAsyncInterruptRemoteContext = 3 -}; -extern void * -MPRemoteCall( - MPRemoteProcedure remoteProc, - void * parameter, - MPRemoteContext context) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void * -MPRemoteCallCFM( - MPRemoteProcedure remoteProc, - void * parameter, - MPRemoteContext context) __attribute__((availability(macosx,introduced=10.4,deprecated=10.7))); -extern Boolean -_MPIsFullyInitialized(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - -typedef Boolean ( * MPIsFullyInitializedProc)(void); -extern void -_MPLibraryVersion( - const char ** versionCString, - UInt32 * major, - UInt32 * minor, - UInt32 * release, - UInt32 * revision) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern Boolean -_MPLibraryIsCompatible( - const char * versionCString, - UInt32 major, - UInt32 minor, - UInt32 release, - UInt32 revision) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -#pragma options align=reset - - -} -extern "C" { - - -#pragma pack(push, 2) -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - -typedef UInt32 FSAliasInfoBitmap; -enum { - kFSAliasInfoNone = 0x00000000, - kFSAliasInfoVolumeCreateDate = 0x00000001, - kFSAliasInfoTargetCreateDate = 0x00000002, - kFSAliasInfoFinderInfo = 0x00000004, - kFSAliasInfoIsDirectory = 0x00000008, - kFSAliasInfoIDs = 0x00000010, - kFSAliasInfoFSInfo = 0x00000020, - kFSAliasInfoVolumeFlags = 0x00000040 -}; - -enum { - rAliasType = 'alis' -}; - -enum { - - kARMMountVol = 0x00000001, - kARMNoUI = 0x00000002, - kARMMultVols = 0x00000008, - kARMSearch = 0x00000100, - kARMSearchMore = 0x00000200, - kARMSearchRelFirst = 0x00000400, - kARMTryFileIDFirst = 0x00000800 -}; - -enum { - - asiZoneName = -3, - asiServerName = -2, - asiVolumeName = -1, - asiAliasName = 0, - asiParentName = 1 -}; - - -enum { - kResolveAliasFileNoUI = 0x00000001, - kResolveAliasTryFileIDFirst = 0x00000002 -}; -struct AliasRecord { - UInt8 hidden[6]; -}; -typedef struct AliasRecord AliasRecord; -typedef AliasRecord * AliasPtr; -typedef AliasPtr * AliasHandle; - -struct FSAliasInfo { - UTCDateTime volumeCreateDate; - UTCDateTime targetCreateDate; - OSType fileType; - OSType fileCreator; - UInt32 parentDirID; - UInt32 nodeID; - UInt16 filesystemID; - UInt16 signature; - Boolean volumeIsBootVolume; - Boolean volumeIsAutomounted; - Boolean volumeIsEjectable; - Boolean volumeHasPersistentFileIDs; - Boolean isDirectory; -}; -typedef struct FSAliasInfo FSAliasInfo; -typedef FSAliasInfo * FSAliasInfoPtr; - -typedef short AliasInfoType; -typedef Boolean ( * FSAliasFilterProcPtr)(const FSRef *ref, Boolean *quitFlag, Ptr myDataPtr); -extern OSErr -FSNewAlias( - const FSRef * fromFile, - const FSRef * target, - AliasHandle * inAlias) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSNewAliasMinimal( - const FSRef * target, - AliasHandle * inAlias) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSIsAliasFile( - const FSRef * fileRef, - Boolean * aliasFileFlag, - Boolean * folderFlag) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSResolveAliasWithMountFlags( - const FSRef * fromFile, - AliasHandle inAlias, - FSRef * target, - Boolean * wasChanged, - unsigned long mountFlags) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSResolveAlias( - const FSRef * fromFile, - AliasHandle alias, - FSRef * target, - Boolean * wasChanged) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSResolveAliasFileWithMountFlags( - FSRef * theRef, - Boolean resolveAliasChains, - Boolean * targetIsFolder, - Boolean * wasAliased, - unsigned long mountFlags) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSResolveAliasFile( - FSRef * theRef, - Boolean resolveAliasChains, - Boolean * targetIsFolder, - Boolean * wasAliased) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSFollowFinderAlias( - FSRef * fromFile, - AliasHandle alias, - Boolean logon, - FSRef * target, - Boolean * wasChanged) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSUpdateAlias( - const FSRef * fromFile, - const FSRef * target, - AliasHandle alias, - Boolean * wasChanged) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSNewAliasUnicode( - const FSRef * fromFile, - const FSRef * targetParentRef, - UniCharCount targetNameLength, - const UniChar * targetName, - AliasHandle * inAlias, - Boolean * isDirectory) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSErr -FSNewAliasMinimalUnicode( - const FSRef * targetParentRef, - UniCharCount targetNameLength, - const UniChar * targetName, - AliasHandle * inAlias, - Boolean * isDirectory) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern OSStatus -FSNewAliasFromPath( - const char * fromFilePath, - const char * targetPath, - OptionBits flags, - AliasHandle * inAlias, - Boolean * isDirectory) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus -FSMatchAliasBulk( - const FSRef * fromFile, - unsigned long rulesMask, - AliasHandle inAlias, - short * aliasCount, - FSRef * aliasList, - Boolean * needsUpdate, - FSAliasFilterProcPtr aliasFilter, - void * yourDataPtr) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSStatus -FSCopyAliasInfo( - AliasHandle inAlias, - HFSUniStr255 * targetName, - HFSUniStr255 * volumeName, - CFStringRef * pathString, - FSAliasInfoBitmap * whichInfo, - FSAliasInfo * info) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern Size -GetAliasSize(AliasHandle alias) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSType -GetAliasUserType(AliasHandle alias) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern void -SetAliasUserType( - AliasHandle alias, - OSType userType) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern Size -GetAliasSizeFromPtr(const AliasRecord * alias) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSType -GetAliasUserTypeFromPtr(const AliasRecord * alias) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern void -SetAliasUserTypeWithPtr( - AliasPtr alias, - OSType userType) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - - - - - - - - -typedef struct OpaqueLocaleRef* LocaleRef; -typedef UInt32 LocalePartMask; -enum { - - kLocaleLanguageMask = 1L << 0, - kLocaleLanguageVariantMask = 1L << 1, - kLocaleScriptMask = 1L << 2, - kLocaleScriptVariantMask = 1L << 3, - kLocaleRegionMask = 1L << 4, - kLocaleRegionVariantMask = 1L << 5, - kLocaleAllPartsMask = 0x0000003F -}; - -typedef FourCharCode LocaleOperationClass; - -typedef FourCharCode LocaleOperationVariant; -struct LocaleAndVariant { - LocaleRef locale; - LocaleOperationVariant opVariant; -}; -typedef struct LocaleAndVariant LocaleAndVariant; - -typedef UInt32 LocaleNameMask; -enum { - - kLocaleNameMask = 1L << 0, - kLocaleOperationVariantNameMask = 1L << 1, - kLocaleAndVariantNameMask = 0x00000003 -}; -extern OSStatus -LocaleRefFromLangOrRegionCode( - LangCode lang, - RegionCode region, - LocaleRef * locale) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -LocaleRefFromLocaleString( - const char localeString[], - LocaleRef * locale) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -LocaleRefGetPartString( - LocaleRef locale, - LocalePartMask partMask, - ByteCount maxStringLen, - char partString[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -LocaleStringToLangAndRegionCodes( - const char localeString[], - LangCode * lang, - RegionCode * region) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -LocaleOperationCountLocales( - LocaleOperationClass opClass, - ItemCount * localeCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -LocaleOperationGetLocales( - LocaleOperationClass opClass, - ItemCount maxLocaleCount, - ItemCount * actualLocaleCount, - LocaleAndVariant localeVariantList[]) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -LocaleGetName( - LocaleRef locale, - LocaleOperationVariant opVariant, - LocaleNameMask nameMask, - LocaleRef displayLocale, - UniCharCount maxNameLen, - UniCharCount * actualNameLen, - UniChar displayName[]) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -LocaleCountNames( - LocaleRef locale, - LocaleOperationVariant opVariant, - LocaleNameMask nameMask, - ItemCount * nameCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -LocaleGetIndName( - LocaleRef locale, - LocaleOperationVariant opVariant, - LocaleNameMask nameMask, - ItemCount nameIndex, - UniCharCount maxNameLen, - UniCharCount * actualNameLen, - UniChar displayName[], - LocaleRef * displayLocale) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -LocaleOperationGetName( - LocaleOperationClass opClass, - LocaleRef displayLocale, - UniCharCount maxNameLen, - UniCharCount * actualNameLen, - UniChar displayName[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -LocaleOperationCountNames( - LocaleOperationClass opClass, - ItemCount * nameCount) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -LocaleOperationGetIndName( - LocaleOperationClass opClass, - ItemCount nameIndex, - UniCharCount maxNameLen, - UniCharCount * actualNameLen, - UniChar displayName[], - LocaleRef * displayLocale) __attribute__((availability(macosx,introduced=10.0))); - - - -#pragma pack(pop) - - -} - - - -extern "C" { -enum { - kBlessedBusErrorBait = 0x68F168F1 -}; -extern void -DebugAssert( - OSType componentSignature, - UInt32 options, - const char * assertionString, - const char * exceptionLabelString, - const char * errorString, - const char * fileName, - long lineNumber, - void * value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - - -enum { - k68kInterruptLevelMask = 0x00000007, - kInVBLTaskMask = 0x00000010, - kInDeferredTaskMask = 0x00000020, - kInSecondaryIntHandlerMask = 0x00000040, - kInNestedInterruptMask = 0x00000080 -}; -extern UInt32 -TaskLevel(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - - -enum { - kComponentDebugOption = 0 -}; - -enum { - kGetDebugOption = 1, - kSetDebugOption = 2 -}; -typedef void ( * DebugComponentCallbackProcPtr)(SInt32 optionSelectorNum, UInt32 command, Boolean *optionSetting); -typedef DebugComponentCallbackProcPtr DebugComponentCallbackUPP; -extern OSStatus -NewDebugComponent( - OSType componentSignature, - ConstStr255Param componentName, - DebugComponentCallbackUPP componentCallback) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -NewDebugOption( - OSType componentSignature, - SInt32 optionSelectorNum, - ConstStr255Param optionName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -DisposeDebugComponent(OSType componentSignature) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -GetDebugComponentInfo( - UInt32 itemIndex, - OSType * componentSignature, - Str255 componentName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -GetDebugOptionInfo( - UInt32 itemIndex, - OSType componentSignature, - SInt32 * optionSelectorNum, - Str255 optionName, - Boolean * optionSetting) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -SetDebugOptionValue( - OSType componentSignature, - SInt32 optionSelectorNum, - Boolean newOptionSetting) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -typedef void ( * DebugAssertOutputHandlerProcPtr)(OSType componentSignature, UInt32 options, const char *assertionString, const char *exceptionLabelString, const char *errorString, const char *fileName, long lineNumber, void *value, ConstStr255Param outputMsg); -typedef DebugAssertOutputHandlerProcPtr DebugAssertOutputHandlerUPP; -extern void -InstallDebugAssertOutputHandler(DebugAssertOutputHandlerUPP handler) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern const char * -GetMacOSStatusErrorString(OSStatus err) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern const char * -GetMacOSStatusCommentString(OSStatus err) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern DebugComponentCallbackUPP -NewDebugComponentCallbackUPP(DebugComponentCallbackProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern DebugAssertOutputHandlerUPP -NewDebugAssertOutputHandlerUPP(DebugAssertOutputHandlerProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeDebugComponentCallbackUPP(DebugComponentCallbackUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeDebugAssertOutputHandlerUPP(DebugAssertOutputHandlerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeDebugComponentCallbackUPP( - SInt32 optionSelectorNum, - UInt32 command, - Boolean * optionSetting, - DebugComponentCallbackUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeDebugAssertOutputHandlerUPP( - OSType componentSignature, - UInt32 options, - const char * assertionString, - const char * exceptionLabelString, - const char * errorString, - const char * fileName, - long lineNumber, - void * value, - ConstStr255Param outputMsg, - DebugAssertOutputHandlerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline DebugComponentCallbackUPP NewDebugComponentCallbackUPP(DebugComponentCallbackProcPtr userRoutine) { return userRoutine; } - inline DebugAssertOutputHandlerUPP NewDebugAssertOutputHandlerUPP(DebugAssertOutputHandlerProcPtr userRoutine) { return userRoutine; } - inline void DisposeDebugComponentCallbackUPP(DebugComponentCallbackUPP) { } - inline void DisposeDebugAssertOutputHandlerUPP(DebugAssertOutputHandlerUPP) { } - inline void InvokeDebugComponentCallbackUPP(SInt32 optionSelectorNum, UInt32 command, Boolean * optionSetting, DebugComponentCallbackUPP userUPP) { (*userUPP)(optionSelectorNum, command, optionSetting); } - inline void InvokeDebugAssertOutputHandlerUPP(OSType componentSignature, UInt32 options, const char * assertionString, const char * exceptionLabelString, const char * errorString, const char * fileName, long lineNumber, void * value, ConstStr255Param outputMsg, DebugAssertOutputHandlerUPP userUPP) { (*userUPP)(componentSignature, options, assertionString, exceptionLabelString, errorString, fileName, lineNumber, value, outputMsg); } -} - - - -extern "C" { -extern short -PLstrcmp( - ConstStr255Param str1, - ConstStr255Param str2) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern short -PLstrncmp( - ConstStr255Param str1, - ConstStr255Param str2, - short num) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern StringPtr -PLstrcpy( - StringPtr dest, - ConstStr255Param source) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern StringPtr -PLstrncpy( - StringPtr dest, - ConstStr255Param source, - short num) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern StringPtr -PLstrcat( - StringPtr str, - ConstStr255Param append) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern StringPtr -PLstrncat( - StringPtr str1, - ConstStr255Param append, - short num) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern Ptr -PLstrchr( - ConstStr255Param str1, - short ch1) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern Ptr -PLstrrchr( - ConstStr255Param str1, - short ch1) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern Ptr -PLstrpbrk( - ConstStr255Param str1, - ConstStr255Param charSet) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern short -PLstrspn( - ConstStr255Param str1, - ConstStr255Param charSet) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern Ptr -PLstrstr( - ConstStr255Param str1, - ConstStr255Param searchStr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern short -PLstrlen(ConstStr255Param str) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern short -PLpos( - ConstStr255Param str1, - ConstStr255Param searchStr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); - - - - - -} - - - -extern "C" { -extern Boolean -CompareAndSwap( - UInt32 oldValue, - UInt32 newValue, - UInt32 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Boolean -TestAndClear( - UInt32 bit, - UInt8 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Boolean -TestAndSet( - UInt32 bit, - UInt8 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt8 -IncrementAtomic8(SInt8 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt8 -DecrementAtomic8(SInt8 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt8 -AddAtomic8( - SInt32 amount, - SInt8 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt8 -BitAndAtomic8( - UInt32 mask, - UInt8 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt8 -BitOrAtomic8( - UInt32 mask, - UInt8 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt8 -BitXorAtomic8( - UInt32 mask, - UInt8 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt16 -IncrementAtomic16(SInt16 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt16 -DecrementAtomic16(SInt16 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt16 -AddAtomic16( - SInt32 amount, - SInt16 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt16 -BitAndAtomic16( - UInt32 mask, - UInt16 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt16 -BitOrAtomic16( - UInt32 mask, - UInt16 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt16 -BitXorAtomic16( - UInt32 mask, - UInt16 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -IncrementAtomic(SInt32 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -DecrementAtomic(SInt32 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt32 -AddAtomic( - SInt32 amount, - SInt32 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt32 -BitAndAtomic( - UInt32 mask, - UInt32 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt32 -BitOrAtomic( - UInt32 mask, - UInt32 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt32 -BitXorAtomic( - UInt32 mask, - UInt32 * address) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - -} - - - -typedef long long __m64 __attribute__((__vector_size__(8))); - -typedef int __v2si __attribute__((__vector_size__(8))); -typedef short __v4hi __attribute__((__vector_size__(8))); -typedef char __v8qi __attribute__((__vector_size__(8))); - - - - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_empty(void) -{ - __builtin_ia32_emms(); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cvtsi32_si64(int __i) -{ - return (__m64)__builtin_ia32_vec_init_v2si(__i, 0); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cvtsi64_si32(__m64 __m) -{ - return __builtin_ia32_vec_ext_v2si((__v2si)__m, 0); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cvtsi64_m64(long long __i) -{ - return (__m64)__i; -} - -static __inline__ long long __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cvtm64_si64(__m64 __m) -{ - return (long long)__m; -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_packs_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_packsswb((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_packs_pi32(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_packssdw((__v2si)__m1, (__v2si)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_packs_pu16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_packuswb((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_unpackhi_pi8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_punpckhbw((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_unpackhi_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_punpckhwd((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_unpackhi_pi32(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_punpckhdq((__v2si)__m1, (__v2si)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_unpacklo_pi8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_punpcklbw((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_unpacklo_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_punpcklwd((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_unpacklo_pi32(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_punpckldq((__v2si)__m1, (__v2si)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_add_pi8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_paddb((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_add_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_paddw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_add_pi32(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_paddd((__v2si)__m1, (__v2si)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_adds_pi8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_paddsb((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_adds_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_paddsw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_adds_pu8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_paddusb((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_adds_pu16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_paddusw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_sub_pi8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_psubb((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_sub_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_psubw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_sub_pi32(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_psubd((__v2si)__m1, (__v2si)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_subs_pi8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_psubsb((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_subs_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_psubsw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_subs_pu8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_psubusb((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_subs_pu16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_psubusw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_madd_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_pmaddwd((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_mulhi_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_pmulhw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_mullo_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_pmullw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_sll_pi16(__m64 __m, __m64 __count) -{ - return (__m64)__builtin_ia32_psllw((__v4hi)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_slli_pi16(__m64 __m, int __count) -{ - return (__m64)__builtin_ia32_psllwi((__v4hi)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_sll_pi32(__m64 __m, __m64 __count) -{ - return (__m64)__builtin_ia32_pslld((__v2si)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_slli_pi32(__m64 __m, int __count) -{ - return (__m64)__builtin_ia32_pslldi((__v2si)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_sll_si64(__m64 __m, __m64 __count) -{ - return (__m64)__builtin_ia32_psllq(__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_slli_si64(__m64 __m, int __count) -{ - return (__m64)__builtin_ia32_psllqi(__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_sra_pi16(__m64 __m, __m64 __count) -{ - return (__m64)__builtin_ia32_psraw((__v4hi)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_srai_pi16(__m64 __m, int __count) -{ - return (__m64)__builtin_ia32_psrawi((__v4hi)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_sra_pi32(__m64 __m, __m64 __count) -{ - return (__m64)__builtin_ia32_psrad((__v2si)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_srai_pi32(__m64 __m, int __count) -{ - return (__m64)__builtin_ia32_psradi((__v2si)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_srl_pi16(__m64 __m, __m64 __count) -{ - return (__m64)__builtin_ia32_psrlw((__v4hi)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_srli_pi16(__m64 __m, int __count) -{ - return (__m64)__builtin_ia32_psrlwi((__v4hi)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_srl_pi32(__m64 __m, __m64 __count) -{ - return (__m64)__builtin_ia32_psrld((__v2si)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_srli_pi32(__m64 __m, int __count) -{ - return (__m64)__builtin_ia32_psrldi((__v2si)__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_srl_si64(__m64 __m, __m64 __count) -{ - return (__m64)__builtin_ia32_psrlq(__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_srli_si64(__m64 __m, int __count) -{ - return (__m64)__builtin_ia32_psrlqi(__m, __count); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_and_si64(__m64 __m1, __m64 __m2) -{ - return __builtin_ia32_pand(__m1, __m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_andnot_si64(__m64 __m1, __m64 __m2) -{ - return __builtin_ia32_pandn(__m1, __m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_or_si64(__m64 __m1, __m64 __m2) -{ - return __builtin_ia32_por(__m1, __m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_xor_si64(__m64 __m1, __m64 __m2) -{ - return __builtin_ia32_pxor(__m1, __m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cmpeq_pi8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_pcmpeqb((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cmpeq_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_pcmpeqw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cmpeq_pi32(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_pcmpeqd((__v2si)__m1, (__v2si)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cmpgt_pi8(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_pcmpgtb((__v8qi)__m1, (__v8qi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cmpgt_pi16(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_pcmpgtw((__v4hi)__m1, (__v4hi)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_cmpgt_pi32(__m64 __m1, __m64 __m2) -{ - return (__m64)__builtin_ia32_pcmpgtd((__v2si)__m1, (__v2si)__m2); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_setzero_si64(void) -{ - return (__m64){ 0LL }; -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_set_pi32(int __i1, int __i0) -{ - return (__m64)__builtin_ia32_vec_init_v2si(__i0, __i1); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_set_pi16(short __s3, short __s2, short __s1, short __s0) -{ - return (__m64)__builtin_ia32_vec_init_v4hi(__s0, __s1, __s2, __s3); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_set_pi8(char __b7, char __b6, char __b5, char __b4, char __b3, char __b2, - char __b1, char __b0) -{ - return (__m64)__builtin_ia32_vec_init_v8qi(__b0, __b1, __b2, __b3, - __b4, __b5, __b6, __b7); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_set1_pi32(int __i) -{ - return _mm_set_pi32(__i, __i); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_set1_pi16(short __w) -{ - return _mm_set_pi16(__w, __w, __w, __w); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_set1_pi8(char __b) -{ - return _mm_set_pi8(__b, __b, __b, __b, __b, __b, __b, __b); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_setr_pi32(int __i0, int __i1) -{ - return _mm_set_pi32(__i1, __i0); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_setr_pi16(short __w0, short __w1, short __w2, short __w3) -{ - return _mm_set_pi16(__w3, __w2, __w1, __w0); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("mmx"))) -_mm_setr_pi8(char __b0, char __b1, char __b2, char __b3, char __b4, char __b5, - char __b6, char __b7) -{ - return _mm_set_pi8(__b7, __b6, __b5, __b4, __b3, __b2, __b1, __b0); -} - -typedef int __v4si __attribute__((__vector_size__(16))); -typedef float __v4sf __attribute__((__vector_size__(16))); -typedef float __m128 __attribute__((__vector_size__(16))); - - - - - -extern "C" int posix_memalign(void **__memptr, size_t __alignment, size_t __size); - - - - -static __inline__ void *__attribute__((__always_inline__, __nodebug__, - __malloc__)) -_mm_malloc(size_t __size, size_t __align) -{ - if (__align == 1) { - return malloc(__size); - } - - if (!(__align & (__align - 1)) && __align < sizeof(void *)) - __align = sizeof(void *); - - void *__mallocedMemory; - - - - - - if (posix_memalign(&__mallocedMemory, __align, __size)) - return 0; - - - return __mallocedMemory; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__)) -_mm_free(void *__p) -{ - free(__p); -} - - - - - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_add_ss(__m128 __a, __m128 __b) -{ - __a[0] += __b[0]; - return __a; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_add_ps(__m128 __a, __m128 __b) -{ - return __a + __b; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_sub_ss(__m128 __a, __m128 __b) -{ - __a[0] -= __b[0]; - return __a; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_sub_ps(__m128 __a, __m128 __b) -{ - return __a - __b; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_mul_ss(__m128 __a, __m128 __b) -{ - __a[0] *= __b[0]; - return __a; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_mul_ps(__m128 __a, __m128 __b) -{ - return __a * __b; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_div_ss(__m128 __a, __m128 __b) -{ - __a[0] /= __b[0]; - return __a; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_div_ps(__m128 __a, __m128 __b) -{ - return __a / __b; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_sqrt_ss(__m128 __a) -{ - __m128 __c = __builtin_ia32_sqrtss(__a); - return (__m128) { __c[0], __a[1], __a[2], __a[3] }; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_sqrt_ps(__m128 __a) -{ - return __builtin_ia32_sqrtps(__a); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_rcp_ss(__m128 __a) -{ - __m128 __c = __builtin_ia32_rcpss(__a); - return (__m128) { __c[0], __a[1], __a[2], __a[3] }; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_rcp_ps(__m128 __a) -{ - return __builtin_ia32_rcpps(__a); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_rsqrt_ss(__m128 __a) -{ - __m128 __c = __builtin_ia32_rsqrtss(__a); - return (__m128) { __c[0], __a[1], __a[2], __a[3] }; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_rsqrt_ps(__m128 __a) -{ - return __builtin_ia32_rsqrtps(__a); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_min_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_minss(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_min_ps(__m128 __a, __m128 __b) -{ - return __builtin_ia32_minps(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_max_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_maxss(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_max_ps(__m128 __a, __m128 __b) -{ - return __builtin_ia32_maxps(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_and_ps(__m128 __a, __m128 __b) -{ - return (__m128)((__v4si)__a & (__v4si)__b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_andnot_ps(__m128 __a, __m128 __b) -{ - return (__m128)(~(__v4si)__a & (__v4si)__b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_or_ps(__m128 __a, __m128 __b) -{ - return (__m128)((__v4si)__a | (__v4si)__b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_xor_ps(__m128 __a, __m128 __b) -{ - return (__m128)((__v4si)__a ^ (__v4si)__b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpeq_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpeqss(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpeq_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpeqps(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmplt_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpltss(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmplt_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpltps(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmple_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpless(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmple_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpleps(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpgt_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_shufflevector(__a, - __builtin_ia32_cmpltss(__b, __a), - 4, 1, 2, 3); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpgt_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpltps(__b, __a); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpge_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_shufflevector(__a, - __builtin_ia32_cmpless(__b, __a), - 4, 1, 2, 3); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpge_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpleps(__b, __a); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpneq_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpneqss(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpneq_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpneqps(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpnlt_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpnltss(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpnlt_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpnltps(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpnle_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpnless(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpnle_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpnleps(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpngt_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_shufflevector(__a, - __builtin_ia32_cmpnltss(__b, __a), - 4, 1, 2, 3); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpngt_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpnltps(__b, __a); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpnge_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_shufflevector(__a, - __builtin_ia32_cmpnless(__b, __a), - 4, 1, 2, 3); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpnge_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpnleps(__b, __a); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpord_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpordss(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpord_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpordps(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpunord_ss(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpunordss(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cmpunord_ps(__m128 __a, __m128 __b) -{ - return (__m128)__builtin_ia32_cmpunordps(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_comieq_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_comieq(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_comilt_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_comilt(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_comile_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_comile(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_comigt_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_comigt(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_comige_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_comige(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_comineq_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_comineq(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_ucomieq_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_ucomieq(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_ucomilt_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_ucomilt(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_ucomile_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_ucomile(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_ucomigt_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_ucomigt(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_ucomige_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_ucomige(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_ucomineq_ss(__m128 __a, __m128 __b) -{ - return __builtin_ia32_ucomineq(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtss_si32(__m128 __a) -{ - return __builtin_ia32_cvtss2si(__a); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvt_ss2si(__m128 __a) -{ - return _mm_cvtss_si32(__a); -} - - - -static __inline__ long long __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtss_si64(__m128 __a) -{ - return __builtin_ia32_cvtss2si64(__a); -} - - - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtps_pi32(__m128 __a) -{ - return (__m64)__builtin_ia32_cvtps2pi(__a); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvt_ps2pi(__m128 __a) -{ - return _mm_cvtps_pi32(__a); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvttss_si32(__m128 __a) -{ - return __a[0]; -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtt_ss2si(__m128 __a) -{ - return _mm_cvttss_si32(__a); -} - -static __inline__ long long __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvttss_si64(__m128 __a) -{ - return __a[0]; -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvttps_pi32(__m128 __a) -{ - return (__m64)__builtin_ia32_cvttps2pi(__a); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtt_ps2pi(__m128 __a) -{ - return _mm_cvttps_pi32(__a); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtsi32_ss(__m128 __a, int __b) -{ - __a[0] = __b; - return __a; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvt_si2ss(__m128 __a, int __b) -{ - return _mm_cvtsi32_ss(__a, __b); -} - - - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtsi64_ss(__m128 __a, long long __b) -{ - __a[0] = __b; - return __a; -} - - - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtpi32_ps(__m128 __a, __m64 __b) -{ - return __builtin_ia32_cvtpi2ps(__a, (__v2si)__b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvt_pi2ps(__m128 __a, __m64 __b) -{ - return _mm_cvtpi32_ps(__a, __b); -} - -static __inline__ float __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtss_f32(__m128 __a) -{ - return __a[0]; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_loadh_pi(__m128 __a, const __m64 *__p) -{ - typedef float __mm_loadh_pi_v2f32 __attribute__((__vector_size__(8))); - struct __mm_loadh_pi_struct { - __mm_loadh_pi_v2f32 __u; - } __attribute__((__packed__, __may_alias__)); - __mm_loadh_pi_v2f32 __b = ((struct __mm_loadh_pi_struct*)__p)->__u; - __m128 __bb = __builtin_shufflevector(__b, __b, 0, 1, 0, 1); - return __builtin_shufflevector(__a, __bb, 0, 1, 4, 5); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_loadl_pi(__m128 __a, const __m64 *__p) -{ - typedef float __mm_loadl_pi_v2f32 __attribute__((__vector_size__(8))); - struct __mm_loadl_pi_struct { - __mm_loadl_pi_v2f32 __u; - } __attribute__((__packed__, __may_alias__)); - __mm_loadl_pi_v2f32 __b = ((struct __mm_loadl_pi_struct*)__p)->__u; - __m128 __bb = __builtin_shufflevector(__b, __b, 0, 1, 0, 1); - return __builtin_shufflevector(__a, __bb, 4, 5, 2, 3); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_load_ss(const float *__p) -{ - struct __mm_load_ss_struct { - float __u; - } __attribute__((__packed__, __may_alias__)); - float __u = ((struct __mm_load_ss_struct*)__p)->__u; - return (__m128){ __u, 0, 0, 0 }; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_load1_ps(const float *__p) -{ - struct __mm_load1_ps_struct { - float __u; - } __attribute__((__packed__, __may_alias__)); - float __u = ((struct __mm_load1_ps_struct*)__p)->__u; - return (__m128){ __u, __u, __u, __u }; -} - - - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_load_ps(const float *__p) -{ - return *(__m128*)__p; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_loadu_ps(const float *__p) -{ - struct __loadu_ps { - __m128 __v; - } __attribute__((__packed__, __may_alias__)); - return ((struct __loadu_ps*)__p)->__v; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_loadr_ps(const float *__p) -{ - __m128 __a = _mm_load_ps(__p); - return __builtin_shufflevector(__a, __a, 3, 2, 1, 0); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_undefined_ps() -{ - return (__m128)__builtin_ia32_undef128(); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_set_ss(float __w) -{ - return (__m128){ __w, 0, 0, 0 }; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_set1_ps(float __w) -{ - return (__m128){ __w, __w, __w, __w }; -} - - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_set_ps1(float __w) -{ - return _mm_set1_ps(__w); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_set_ps(float __z, float __y, float __x, float __w) -{ - return (__m128){ __w, __x, __y, __z }; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_setr_ps(float __z, float __y, float __x, float __w) -{ - return (__m128){ __z, __y, __x, __w }; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_setzero_ps(void) -{ - return (__m128){ 0, 0, 0, 0 }; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_storeh_pi(__m64 *__p, __m128 __a) -{ - __builtin_ia32_storehps((__v2si *)__p, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_storel_pi(__m64 *__p, __m128 __a) -{ - __builtin_ia32_storelps((__v2si *)__p, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_store_ss(float *__p, __m128 __a) -{ - struct __mm_store_ss_struct { - float __u; - } __attribute__((__packed__, __may_alias__)); - ((struct __mm_store_ss_struct*)__p)->__u = __a[0]; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_storeu_ps(float *__p, __m128 __a) -{ - __builtin_ia32_storeups(__p, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_store1_ps(float *__p, __m128 __a) -{ - __a = __builtin_shufflevector(__a, __a, 0, 0, 0, 0); - _mm_storeu_ps(__p, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_store_ps1(float *__p, __m128 __a) -{ - return _mm_store1_ps(__p, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_store_ps(float *__p, __m128 __a) -{ - *(__m128 *)__p = __a; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_storer_ps(float *__p, __m128 __a) -{ - __a = __builtin_shufflevector(__a, __a, 3, 2, 1, 0); - _mm_store_ps(__p, __a); -} -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_stream_pi(__m64 *__p, __m64 __a) -{ - __builtin_ia32_movntq(__p, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_stream_ps(float *__p, __m128 __a) -{ - __builtin_ia32_movntps(__p, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_sfence(void) -{ - __builtin_ia32_sfence(); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_extract_pi16(__m64 __a, int __n) -{ - __v4hi __b = (__v4hi)__a; - return (unsigned short)__b[__n & 3]; -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_insert_pi16(__m64 __a, int __d, int __n) -{ - __v4hi __b = (__v4hi)__a; - __b[__n & 3] = __d; - return (__m64)__b; -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_max_pi16(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_pmaxsw((__v4hi)__a, (__v4hi)__b); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_max_pu8(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_pmaxub((__v8qi)__a, (__v8qi)__b); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_min_pi16(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_pminsw((__v4hi)__a, (__v4hi)__b); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_min_pu8(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_pminub((__v8qi)__a, (__v8qi)__b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_movemask_pi8(__m64 __a) -{ - return __builtin_ia32_pmovmskb((__v8qi)__a); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_mulhi_pu16(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_pmulhuw((__v4hi)__a, (__v4hi)__b); -} - - - - - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_maskmove_si64(__m64 __d, __m64 __n, char *__p) -{ - __builtin_ia32_maskmovq((__v8qi)__d, (__v8qi)__n, __p); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_avg_pu8(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_pavgb((__v8qi)__a, (__v8qi)__b); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_avg_pu16(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_pavgw((__v4hi)__a, (__v4hi)__b); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_sad_pu8(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_psadbw((__v8qi)__a, (__v8qi)__b); -} - -static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_getcsr(void) -{ - return __builtin_ia32_stmxcsr(); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_setcsr(unsigned int __i) -{ - __builtin_ia32_ldmxcsr(__i); -} -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_unpackhi_ps(__m128 __a, __m128 __b) -{ - return __builtin_shufflevector(__a, __b, 2, 6, 3, 7); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_unpacklo_ps(__m128 __a, __m128 __b) -{ - return __builtin_shufflevector(__a, __b, 0, 4, 1, 5); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_move_ss(__m128 __a, __m128 __b) -{ - return __builtin_shufflevector(__a, __b, 4, 1, 2, 3); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_movehl_ps(__m128 __a, __m128 __b) -{ - return __builtin_shufflevector(__a, __b, 6, 7, 2, 3); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_movelh_ps(__m128 __a, __m128 __b) -{ - return __builtin_shufflevector(__a, __b, 0, 1, 4, 5); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtpi16_ps(__m64 __a) -{ - __m64 __b, __c; - __m128 __r; - - __b = _mm_setzero_si64(); - __b = _mm_cmpgt_pi16(__b, __a); - __c = _mm_unpackhi_pi16(__a, __b); - __r = _mm_setzero_ps(); - __r = _mm_cvtpi32_ps(__r, __c); - __r = _mm_movelh_ps(__r, __r); - __c = _mm_unpacklo_pi16(__a, __b); - __r = _mm_cvtpi32_ps(__r, __c); - - return __r; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtpu16_ps(__m64 __a) -{ - __m64 __b, __c; - __m128 __r; - - __b = _mm_setzero_si64(); - __c = _mm_unpackhi_pi16(__a, __b); - __r = _mm_setzero_ps(); - __r = _mm_cvtpi32_ps(__r, __c); - __r = _mm_movelh_ps(__r, __r); - __c = _mm_unpacklo_pi16(__a, __b); - __r = _mm_cvtpi32_ps(__r, __c); - - return __r; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtpi8_ps(__m64 __a) -{ - __m64 __b; - - __b = _mm_setzero_si64(); - __b = _mm_cmpgt_pi8(__b, __a); - __b = _mm_unpacklo_pi8(__a, __b); - - return _mm_cvtpi16_ps(__b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtpu8_ps(__m64 __a) -{ - __m64 __b; - - __b = _mm_setzero_si64(); - __b = _mm_unpacklo_pi8(__a, __b); - - return _mm_cvtpi16_ps(__b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtpi32x2_ps(__m64 __a, __m64 __b) -{ - __m128 __c; - - __c = _mm_setzero_ps(); - __c = _mm_cvtpi32_ps(__c, __b); - __c = _mm_movelh_ps(__c, __c); - - return _mm_cvtpi32_ps(__c, __a); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtps_pi16(__m128 __a) -{ - __m64 __b, __c; - - __b = _mm_cvtps_pi32(__a); - __a = _mm_movehl_ps(__a, __a); - __c = _mm_cvtps_pi32(__a); - - return _mm_packs_pi32(__b, __c); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_cvtps_pi8(__m128 __a) -{ - __m64 __b, __c; - - __b = _mm_cvtps_pi16(__a); - __c = _mm_setzero_si64(); - - return _mm_packs_pi16(__b, __c); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse"))) -_mm_movemask_ps(__m128 __a) -{ - return __builtin_ia32_movmskps(__a); -} - -typedef double __m128d __attribute__((__vector_size__(16))); -typedef long long __m128i __attribute__((__vector_size__(16))); - - -typedef double __v2df __attribute__ ((__vector_size__ (16))); -typedef long long __v2di __attribute__ ((__vector_size__ (16))); -typedef short __v8hi __attribute__((__vector_size__(16))); -typedef char __v16qi __attribute__((__vector_size__(16))); - - - -typedef signed char __v16qs __attribute__((__vector_size__(16))); - - -typedef float __v8sf __attribute__ ((__vector_size__ (32))); -typedef float __m256 __attribute__ ((__vector_size__ (32))); -static inline __m128 __attribute__((__always_inline__, __nodebug__, __target__("f16c"))) -_mm_cvtph_ps(__m128i __a) -{ - return (__m128)__builtin_ia32_vcvtph2ps((__v8hi)__a); -} - -static inline __m256 __attribute__((__always_inline__, __nodebug__, __target__("f16c"))) -_mm256_cvtph_ps(__m128i __a) -{ - return (__m256)__builtin_ia32_vcvtph2ps256((__v8hi)__a); -} - - - - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_add_sd(__m128d __a, __m128d __b) -{ - __a[0] += __b[0]; - return __a; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_add_pd(__m128d __a, __m128d __b) -{ - return __a + __b; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sub_sd(__m128d __a, __m128d __b) -{ - __a[0] -= __b[0]; - return __a; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sub_pd(__m128d __a, __m128d __b) -{ - return __a - __b; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_mul_sd(__m128d __a, __m128d __b) -{ - __a[0] *= __b[0]; - return __a; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_mul_pd(__m128d __a, __m128d __b) -{ - return __a * __b; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_div_sd(__m128d __a, __m128d __b) -{ - __a[0] /= __b[0]; - return __a; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_div_pd(__m128d __a, __m128d __b) -{ - return __a / __b; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sqrt_sd(__m128d __a, __m128d __b) -{ - __m128d __c = __builtin_ia32_sqrtsd(__b); - return (__m128d) { __c[0], __a[1] }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sqrt_pd(__m128d __a) -{ - return __builtin_ia32_sqrtpd(__a); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_min_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_minsd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_min_pd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_minpd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_max_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_maxsd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_max_pd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_maxpd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_and_pd(__m128d __a, __m128d __b) -{ - return (__m128d)((__v4si)__a & (__v4si)__b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_andnot_pd(__m128d __a, __m128d __b) -{ - return (__m128d)(~(__v4si)__a & (__v4si)__b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_or_pd(__m128d __a, __m128d __b) -{ - return (__m128d)((__v4si)__a | (__v4si)__b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_xor_pd(__m128d __a, __m128d __b) -{ - return (__m128d)((__v4si)__a ^ (__v4si)__b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpeq_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpeqpd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmplt_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpltpd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmple_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmplepd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpgt_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpltpd(__b, __a); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpge_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmplepd(__b, __a); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpord_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpordpd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpunord_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpunordpd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpneq_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpneqpd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpnlt_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpnltpd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpnle_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpnlepd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpngt_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpnltpd(__b, __a); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpnge_pd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpnlepd(__b, __a); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpeq_sd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpeqsd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmplt_sd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpltsd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmple_sd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmplesd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpgt_sd(__m128d __a, __m128d __b) -{ - __m128d __c = __builtin_ia32_cmpltsd(__b, __a); - return (__m128d) { __c[0], __a[1] }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpge_sd(__m128d __a, __m128d __b) -{ - __m128d __c = __builtin_ia32_cmplesd(__b, __a); - return (__m128d) { __c[0], __a[1] }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpord_sd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpordsd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpunord_sd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpunordsd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpneq_sd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpneqsd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpnlt_sd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpnltsd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpnle_sd(__m128d __a, __m128d __b) -{ - return (__m128d)__builtin_ia32_cmpnlesd(__a, __b); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpngt_sd(__m128d __a, __m128d __b) -{ - __m128d __c = __builtin_ia32_cmpnltsd(__b, __a); - return (__m128d) { __c[0], __a[1] }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpnge_sd(__m128d __a, __m128d __b) -{ - __m128d __c = __builtin_ia32_cmpnlesd(__b, __a); - return (__m128d) { __c[0], __a[1] }; -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_comieq_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_comisdeq(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_comilt_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_comisdlt(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_comile_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_comisdle(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_comigt_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_comisdgt(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_comige_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_comisdge(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_comineq_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_comisdneq(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_ucomieq_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_ucomisdeq(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_ucomilt_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_ucomisdlt(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_ucomile_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_ucomisdle(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_ucomigt_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_ucomisdgt(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_ucomige_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_ucomisdge(__a, __b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_ucomineq_sd(__m128d __a, __m128d __b) -{ - return __builtin_ia32_ucomisdneq(__a, __b); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtpd_ps(__m128d __a) -{ - return __builtin_ia32_cvtpd2ps(__a); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtps_pd(__m128 __a) -{ - return __builtin_ia32_cvtps2pd(__a); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtepi32_pd(__m128i __a) -{ - return __builtin_ia32_cvtdq2pd((__v4si)__a); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtpd_epi32(__m128d __a) -{ - return __builtin_ia32_cvtpd2dq(__a); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsd_si32(__m128d __a) -{ - return __builtin_ia32_cvtsd2si(__a); -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsd_ss(__m128 __a, __m128d __b) -{ - __a[0] = __b[0]; - return __a; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsi32_sd(__m128d __a, int __b) -{ - __a[0] = __b; - return __a; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtss_sd(__m128d __a, __m128 __b) -{ - __a[0] = __b[0]; - return __a; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvttpd_epi32(__m128d __a) -{ - return (__m128i)__builtin_ia32_cvttpd2dq(__a); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvttsd_si32(__m128d __a) -{ - return __a[0]; -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtpd_pi32(__m128d __a) -{ - return (__m64)__builtin_ia32_cvtpd2pi(__a); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvttpd_pi32(__m128d __a) -{ - return (__m64)__builtin_ia32_cvttpd2pi(__a); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtpi32_pd(__m64 __a) -{ - return __builtin_ia32_cvtpi2pd((__v2si)__a); -} - -static __inline__ double __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsd_f64(__m128d __a) -{ - return __a[0]; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_load_pd(double const *__dp) -{ - return *(__m128d*)__dp; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_load1_pd(double const *__dp) -{ - struct __mm_load1_pd_struct { - double __u; - } __attribute__((__packed__, __may_alias__)); - double __u = ((struct __mm_load1_pd_struct*)__dp)->__u; - return (__m128d){ __u, __u }; -} - - - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_loadr_pd(double const *__dp) -{ - __m128d __u = *(__m128d*)__dp; - return __builtin_shufflevector(__u, __u, 1, 0); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_loadu_pd(double const *__dp) -{ - struct __loadu_pd { - __m128d __v; - } __attribute__((__packed__, __may_alias__)); - return ((struct __loadu_pd*)__dp)->__v; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_load_sd(double const *__dp) -{ - struct __mm_load_sd_struct { - double __u; - } __attribute__((__packed__, __may_alias__)); - double __u = ((struct __mm_load_sd_struct*)__dp)->__u; - return (__m128d){ __u, 0 }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_loadh_pd(__m128d __a, double const *__dp) -{ - struct __mm_loadh_pd_struct { - double __u; - } __attribute__((__packed__, __may_alias__)); - double __u = ((struct __mm_loadh_pd_struct*)__dp)->__u; - return (__m128d){ __a[0], __u }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_loadl_pd(__m128d __a, double const *__dp) -{ - struct __mm_loadl_pd_struct { - double __u; - } __attribute__((__packed__, __may_alias__)); - double __u = ((struct __mm_loadl_pd_struct*)__dp)->__u; - return (__m128d){ __u, __a[1] }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_undefined_pd() -{ - return (__m128d)__builtin_ia32_undef128(); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set_sd(double __w) -{ - return (__m128d){ __w, 0 }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set1_pd(double __w) -{ - return (__m128d){ __w, __w }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set_pd(double __w, double __x) -{ - return (__m128d){ __x, __w }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_setr_pd(double __w, double __x) -{ - return (__m128d){ __w, __x }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_setzero_pd(void) -{ - return (__m128d){ 0, 0 }; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_move_sd(__m128d __a, __m128d __b) -{ - return (__m128d){ __b[0], __a[1] }; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_store_sd(double *__dp, __m128d __a) -{ - struct __mm_store_sd_struct { - double __u; - } __attribute__((__packed__, __may_alias__)); - ((struct __mm_store_sd_struct*)__dp)->__u = __a[0]; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_store1_pd(double *__dp, __m128d __a) -{ - struct __mm_store1_pd_struct { - double __u[2]; - } __attribute__((__packed__, __may_alias__)); - ((struct __mm_store1_pd_struct*)__dp)->__u[0] = __a[0]; - ((struct __mm_store1_pd_struct*)__dp)->__u[1] = __a[0]; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_store_pd(double *__dp, __m128d __a) -{ - *(__m128d *)__dp = __a; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_storeu_pd(double *__dp, __m128d __a) -{ - __builtin_ia32_storeupd(__dp, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_storer_pd(double *__dp, __m128d __a) -{ - __a = __builtin_shufflevector(__a, __a, 1, 0); - *(__m128d *)__dp = __a; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_storeh_pd(double *__dp, __m128d __a) -{ - struct __mm_storeh_pd_struct { - double __u; - } __attribute__((__packed__, __may_alias__)); - ((struct __mm_storeh_pd_struct*)__dp)->__u = __a[1]; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_storel_pd(double *__dp, __m128d __a) -{ - struct __mm_storeh_pd_struct { - double __u; - } __attribute__((__packed__, __may_alias__)); - ((struct __mm_storeh_pd_struct*)__dp)->__u = __a[0]; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_add_epi8(__m128i __a, __m128i __b) -{ - return (__m128i)((__v16qi)__a + (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_add_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)((__v8hi)__a + (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_add_epi32(__m128i __a, __m128i __b) -{ - return (__m128i)((__v4si)__a + (__v4si)__b); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_add_si64(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_paddq(__a, __b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_add_epi64(__m128i __a, __m128i __b) -{ - return __a + __b; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_adds_epi8(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_paddsb128((__v16qi)__a, (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_adds_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_paddsw128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_adds_epu8(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_paddusb128((__v16qi)__a, (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_adds_epu16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_paddusw128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_avg_epu8(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_pavgb128((__v16qi)__a, (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_avg_epu16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_pavgw128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_madd_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_pmaddwd128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_max_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_pmaxsw128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_max_epu8(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_pmaxub128((__v16qi)__a, (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_min_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_pminsw128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_min_epu8(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_pminub128((__v16qi)__a, (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_mulhi_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_pmulhw128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_mulhi_epu16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_pmulhuw128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_mullo_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)((__v8hi)__a * (__v8hi)__b); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_mul_su32(__m64 __a, __m64 __b) -{ - return __builtin_ia32_pmuludq((__v2si)__a, (__v2si)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_mul_epu32(__m128i __a, __m128i __b) -{ - return __builtin_ia32_pmuludq128((__v4si)__a, (__v4si)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sad_epu8(__m128i __a, __m128i __b) -{ - return __builtin_ia32_psadbw128((__v16qi)__a, (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sub_epi8(__m128i __a, __m128i __b) -{ - return (__m128i)((__v16qi)__a - (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sub_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)((__v8hi)__a - (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sub_epi32(__m128i __a, __m128i __b) -{ - return (__m128i)((__v4si)__a - (__v4si)__b); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sub_si64(__m64 __a, __m64 __b) -{ - return (__m64)__builtin_ia32_psubq(__a, __b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sub_epi64(__m128i __a, __m128i __b) -{ - return __a - __b; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_subs_epi8(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_psubsb128((__v16qi)__a, (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_subs_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_psubsw128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_subs_epu8(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_psubusb128((__v16qi)__a, (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_subs_epu16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_psubusw128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_and_si128(__m128i __a, __m128i __b) -{ - return __a & __b; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_andnot_si128(__m128i __a, __m128i __b) -{ - return ~__a & __b; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_or_si128(__m128i __a, __m128i __b) -{ - return __a | __b; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_xor_si128(__m128i __a, __m128i __b) -{ - return __a ^ __b; -} -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_slli_epi16(__m128i __a, int __count) -{ - return (__m128i)__builtin_ia32_psllwi128((__v8hi)__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sll_epi16(__m128i __a, __m128i __count) -{ - return (__m128i)__builtin_ia32_psllw128((__v8hi)__a, (__v8hi)__count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_slli_epi32(__m128i __a, int __count) -{ - return (__m128i)__builtin_ia32_pslldi128((__v4si)__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sll_epi32(__m128i __a, __m128i __count) -{ - return (__m128i)__builtin_ia32_pslld128((__v4si)__a, (__v4si)__count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_slli_epi64(__m128i __a, int __count) -{ - return __builtin_ia32_psllqi128(__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sll_epi64(__m128i __a, __m128i __count) -{ - return __builtin_ia32_psllq128(__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_srai_epi16(__m128i __a, int __count) -{ - return (__m128i)__builtin_ia32_psrawi128((__v8hi)__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sra_epi16(__m128i __a, __m128i __count) -{ - return (__m128i)__builtin_ia32_psraw128((__v8hi)__a, (__v8hi)__count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_srai_epi32(__m128i __a, int __count) -{ - return (__m128i)__builtin_ia32_psradi128((__v4si)__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_sra_epi32(__m128i __a, __m128i __count) -{ - return (__m128i)__builtin_ia32_psrad128((__v4si)__a, (__v4si)__count); -} -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_srli_epi16(__m128i __a, int __count) -{ - return (__m128i)__builtin_ia32_psrlwi128((__v8hi)__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_srl_epi16(__m128i __a, __m128i __count) -{ - return (__m128i)__builtin_ia32_psrlw128((__v8hi)__a, (__v8hi)__count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_srli_epi32(__m128i __a, int __count) -{ - return (__m128i)__builtin_ia32_psrldi128((__v4si)__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_srl_epi32(__m128i __a, __m128i __count) -{ - return (__m128i)__builtin_ia32_psrld128((__v4si)__a, (__v4si)__count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_srli_epi64(__m128i __a, int __count) -{ - return __builtin_ia32_psrlqi128(__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_srl_epi64(__m128i __a, __m128i __count) -{ - return __builtin_ia32_psrlq128(__a, __count); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpeq_epi8(__m128i __a, __m128i __b) -{ - return (__m128i)((__v16qi)__a == (__v16qi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpeq_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)((__v8hi)__a == (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpeq_epi32(__m128i __a, __m128i __b) -{ - return (__m128i)((__v4si)__a == (__v4si)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpgt_epi8(__m128i __a, __m128i __b) -{ - - - return (__m128i)((__v16qs)__a > (__v16qs)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpgt_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)((__v8hi)__a > (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmpgt_epi32(__m128i __a, __m128i __b) -{ - return (__m128i)((__v4si)__a > (__v4si)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmplt_epi8(__m128i __a, __m128i __b) -{ - return _mm_cmpgt_epi8(__b, __a); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmplt_epi16(__m128i __a, __m128i __b) -{ - return _mm_cmpgt_epi16(__b, __a); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cmplt_epi32(__m128i __a, __m128i __b) -{ - return _mm_cmpgt_epi32(__b, __a); -} - - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsi64_sd(__m128d __a, long long __b) -{ - __a[0] = __b; - return __a; -} - -static __inline__ long long __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsd_si64(__m128d __a) -{ - return __builtin_ia32_cvtsd2si64(__a); -} - -static __inline__ long long __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvttsd_si64(__m128d __a) -{ - return __a[0]; -} - - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtepi32_ps(__m128i __a) -{ - return __builtin_ia32_cvtdq2ps((__v4si)__a); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtps_epi32(__m128 __a) -{ - return (__m128i)__builtin_ia32_cvtps2dq(__a); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvttps_epi32(__m128 __a) -{ - return (__m128i)__builtin_ia32_cvttps2dq(__a); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsi32_si128(int __a) -{ - return (__m128i)(__v4si){ __a, 0, 0, 0 }; -} - - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsi64_si128(long long __a) -{ - return (__m128i){ __a, 0 }; -} - - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsi128_si32(__m128i __a) -{ - __v4si __b = (__v4si)__a; - return __b[0]; -} - - -static __inline__ long long __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_cvtsi128_si64(__m128i __a) -{ - return __a[0]; -} - - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_load_si128(__m128i const *__p) -{ - return *__p; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_loadu_si128(__m128i const *__p) -{ - struct __loadu_si128 { - __m128i __v; - } __attribute__((__packed__, __may_alias__)); - return ((struct __loadu_si128*)__p)->__v; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_loadl_epi64(__m128i const *__p) -{ - struct __mm_loadl_epi64_struct { - long long __u; - } __attribute__((__packed__, __may_alias__)); - return (__m128i) { ((struct __mm_loadl_epi64_struct*)__p)->__u, 0}; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_undefined_si128() -{ - return (__m128i)__builtin_ia32_undef128(); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set_epi64x(long long __q1, long long __q0) -{ - return (__m128i){ __q0, __q1 }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set_epi64(__m64 __q1, __m64 __q0) -{ - return (__m128i){ (long long)__q0, (long long)__q1 }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set_epi32(int __i3, int __i2, int __i1, int __i0) -{ - return (__m128i)(__v4si){ __i0, __i1, __i2, __i3}; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set_epi16(short __w7, short __w6, short __w5, short __w4, short __w3, short __w2, short __w1, short __w0) -{ - return (__m128i)(__v8hi){ __w0, __w1, __w2, __w3, __w4, __w5, __w6, __w7 }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set_epi8(char __b15, char __b14, char __b13, char __b12, char __b11, char __b10, char __b9, char __b8, char __b7, char __b6, char __b5, char __b4, char __b3, char __b2, char __b1, char __b0) -{ - return (__m128i)(__v16qi){ __b0, __b1, __b2, __b3, __b4, __b5, __b6, __b7, __b8, __b9, __b10, __b11, __b12, __b13, __b14, __b15 }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set1_epi64x(long long __q) -{ - return (__m128i){ __q, __q }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set1_epi64(__m64 __q) -{ - return (__m128i){ (long long)__q, (long long)__q }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set1_epi32(int __i) -{ - return (__m128i)(__v4si){ __i, __i, __i, __i }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set1_epi16(short __w) -{ - return (__m128i)(__v8hi){ __w, __w, __w, __w, __w, __w, __w, __w }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_set1_epi8(char __b) -{ - return (__m128i)(__v16qi){ __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_setr_epi64(__m64 __q0, __m64 __q1) -{ - return (__m128i){ (long long)__q0, (long long)__q1 }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_setr_epi32(int __i0, int __i1, int __i2, int __i3) -{ - return (__m128i)(__v4si){ __i0, __i1, __i2, __i3}; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_setr_epi16(short __w0, short __w1, short __w2, short __w3, short __w4, short __w5, short __w6, short __w7) -{ - return (__m128i)(__v8hi){ __w0, __w1, __w2, __w3, __w4, __w5, __w6, __w7 }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_setr_epi8(char __b0, char __b1, char __b2, char __b3, char __b4, char __b5, char __b6, char __b7, char __b8, char __b9, char __b10, char __b11, char __b12, char __b13, char __b14, char __b15) -{ - return (__m128i)(__v16qi){ __b0, __b1, __b2, __b3, __b4, __b5, __b6, __b7, __b8, __b9, __b10, __b11, __b12, __b13, __b14, __b15 }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_setzero_si128(void) -{ - return (__m128i){ 0LL, 0LL }; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_store_si128(__m128i *__p, __m128i __b) -{ - *__p = __b; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_storeu_si128(__m128i *__p, __m128i __b) -{ - __builtin_ia32_storedqu((char *)__p, (__v16qi)__b); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_maskmoveu_si128(__m128i __d, __m128i __n, char *__p) -{ - __builtin_ia32_maskmovdqu((__v16qi)__d, (__v16qi)__n, __p); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_storel_epi64(__m128i *__p, __m128i __a) -{ - struct __mm_storel_epi64_struct { - long long __u; - } __attribute__((__packed__, __may_alias__)); - ((struct __mm_storel_epi64_struct*)__p)->__u = __a[0]; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_stream_pd(double *__p, __m128d __a) -{ - __builtin_ia32_movntpd(__p, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_stream_si128(__m128i *__p, __m128i __a) -{ - __builtin_ia32_movntdq(__p, __a); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_stream_si32(int *__p, int __a) -{ - __builtin_ia32_movnti(__p, __a); -} - - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_stream_si64(long long *__p, long long __a) -{ - __builtin_ia32_movnti64(__p, __a); -} - - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_clflush(void const *__p) -{ - __builtin_ia32_clflush(__p); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_lfence(void) -{ - __builtin_ia32_lfence(); -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_mfence(void) -{ - __builtin_ia32_mfence(); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_packs_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_packsswb128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_packs_epi32(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_packssdw128((__v4si)__a, (__v4si)__b); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_packus_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_ia32_packuswb128((__v8hi)__a, (__v8hi)__b); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_extract_epi16(__m128i __a, int __imm) -{ - __v8hi __b = (__v8hi)__a; - return (unsigned short)__b[__imm & 7]; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_insert_epi16(__m128i __a, int __b, int __imm) -{ - __v8hi __c = (__v8hi)__a; - __c[__imm & 7] = __b; - return (__m128i)__c; -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_movemask_epi8(__m128i __a) -{ - return __builtin_ia32_pmovmskb128((__v16qi)__a); -} -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpackhi_epi8(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_shufflevector((__v16qi)__a, (__v16qi)__b, 8, 16+8, 9, 16+9, 10, 16+10, 11, 16+11, 12, 16+12, 13, 16+13, 14, 16+14, 15, 16+15); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpackhi_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_shufflevector((__v8hi)__a, (__v8hi)__b, 4, 8+4, 5, 8+5, 6, 8+6, 7, 8+7); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpackhi_epi32(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_shufflevector((__v4si)__a, (__v4si)__b, 2, 4+2, 3, 4+3); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpackhi_epi64(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_shufflevector(__a, __b, 1, 2+1); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpacklo_epi8(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_shufflevector((__v16qi)__a, (__v16qi)__b, 0, 16+0, 1, 16+1, 2, 16+2, 3, 16+3, 4, 16+4, 5, 16+5, 6, 16+6, 7, 16+7); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpacklo_epi16(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_shufflevector((__v8hi)__a, (__v8hi)__b, 0, 8+0, 1, 8+1, 2, 8+2, 3, 8+3); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpacklo_epi32(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_shufflevector((__v4si)__a, (__v4si)__b, 0, 4+0, 1, 4+1); -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpacklo_epi64(__m128i __a, __m128i __b) -{ - return (__m128i)__builtin_shufflevector(__a, __b, 0, 2+0); -} - -static __inline__ __m64 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_movepi64_pi64(__m128i __a) -{ - return (__m64)__a[0]; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_movpi64_epi64(__m64 __a) -{ - return (__m128i){ (long long)__a, 0 }; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_move_epi64(__m128i __a) -{ - return __builtin_shufflevector(__a, (__m128i){ 0 }, 0, 2); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpackhi_pd(__m128d __a, __m128d __b) -{ - return __builtin_shufflevector(__a, __b, 1, 2+1); -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_unpacklo_pd(__m128d __a, __m128d __b) -{ - return __builtin_shufflevector(__a, __b, 0, 2+0); -} - -static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_movemask_pd(__m128d __a) -{ - return __builtin_ia32_movmskpd(__a); -} - - - - - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_castpd_ps(__m128d __a) -{ - return (__m128)__a; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_castpd_si128(__m128d __a) -{ - return (__m128i)__a; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_castps_pd(__m128 __a) -{ - return (__m128d)__a; -} - -static __inline__ __m128i __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_castps_si128(__m128 __a) -{ - return (__m128i)__a; -} - -static __inline__ __m128 __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_castsi128_ps(__m128i __a) -{ - return (__m128)__a; -} - -static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_castsi128_pd(__m128i __a) -{ - return (__m128d)__a; -} - -static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("sse2"))) -_mm_pause(void) -{ - __asm__ volatile ("pause"); -} -extern "C" { - - -#pragma options align=power - - -typedef struct OpaqueAreaID* AreaID; -struct MachineInformationPowerPC { - UnsignedWide CTR; - UnsignedWide LR; - UnsignedWide PC; - unsigned long CRRegister; - unsigned long XER; - unsigned long MSR; - unsigned long MQ; - unsigned long ExceptKind; - unsigned long DSISR; - UnsignedWide DAR; - UnsignedWide Reserved; -}; -typedef struct MachineInformationPowerPC MachineInformationPowerPC; -struct RegisterInformationPowerPC { - UnsignedWide R0; - UnsignedWide R1; - UnsignedWide R2; - UnsignedWide R3; - UnsignedWide R4; - UnsignedWide R5; - UnsignedWide R6; - UnsignedWide R7; - UnsignedWide R8; - UnsignedWide R9; - UnsignedWide R10; - UnsignedWide R11; - UnsignedWide R12; - UnsignedWide R13; - UnsignedWide R14; - UnsignedWide R15; - UnsignedWide R16; - UnsignedWide R17; - UnsignedWide R18; - UnsignedWide R19; - UnsignedWide R20; - UnsignedWide R21; - UnsignedWide R22; - UnsignedWide R23; - UnsignedWide R24; - UnsignedWide R25; - UnsignedWide R26; - UnsignedWide R27; - UnsignedWide R28; - UnsignedWide R29; - UnsignedWide R30; - UnsignedWide R31; -}; -typedef struct RegisterInformationPowerPC RegisterInformationPowerPC; -struct FPUInformationPowerPC { - UnsignedWide Registers[32]; - unsigned long FPSCR; - unsigned long Reserved; -}; -typedef struct FPUInformationPowerPC FPUInformationPowerPC; -union Vector128 { - - - - unsigned long l[4]; - unsigned short s[8]; - unsigned char c[16]; -}; -typedef union Vector128 Vector128; -struct VectorInformationPowerPC { - Vector128 Registers[32]; - Vector128 VSCR; - UInt32 VRsave; -}; -typedef struct VectorInformationPowerPC VectorInformationPowerPC; - -enum { - kWriteReference = 0, - kReadReference = 1, - kFetchReference = 2, - writeReference = kWriteReference, - readReference = kReadReference, - fetchReference = kFetchReference -}; - - -typedef unsigned long MemoryReferenceKind; -struct MemoryExceptionInformation { - AreaID theArea; - LogicalAddress theAddress; - OSStatus theError; - MemoryReferenceKind theReference; -}; -typedef struct MemoryExceptionInformation MemoryExceptionInformation; -enum { - kUnknownException = 0, - kIllegalInstructionException = 1, - kTrapException = 2, - kAccessException = 3, - kUnmappedMemoryException = 4, - kExcludedMemoryException = 5, - kReadOnlyMemoryException = 6, - kUnresolvablePageFaultException = 7, - kPrivilegeViolationException = 8, - kTraceException = 9, - kInstructionBreakpointException = 10, - kDataBreakpointException = 11, - kIntegerException = 12, - kFloatingPointException = 13, - kStackOverflowException = 14, - kTaskTerminationException = 15, - kTaskCreationException = 16, - kDataAlignmentException = 17 -}; -typedef unsigned long ExceptionKind; -union ExceptionInfo { - MemoryExceptionInformation * memoryInfo; -}; -typedef union ExceptionInfo ExceptionInfo; -struct ExceptionInformationPowerPC { - ExceptionKind theKind; - MachineInformationPowerPC * machineState; - RegisterInformationPowerPC * registerImage; - FPUInformationPowerPC * FPUImage; - ExceptionInfo info; - VectorInformationPowerPC * vectorImage; -}; -typedef struct ExceptionInformationPowerPC ExceptionInformationPowerPC; -union Vector128Intel { - __m128 s; - __m128i si; - __m128d sd; - unsigned char c[16]; -}; -typedef union Vector128Intel Vector128Intel; -struct MachineInformationIntel64 { - unsigned long CS; - unsigned long FS; - unsigned long GS; - unsigned long RFLAGS; - unsigned long RIP; - unsigned long ExceptTrap; - unsigned long ExceptErr; - unsigned long ExceptAddr; -}; -typedef struct MachineInformationIntel64 MachineInformationIntel64; -struct RegisterInformationIntel64 { - unsigned long RAX; - unsigned long RBX; - unsigned long RCX; - unsigned long RDX; - unsigned long RDI; - unsigned long RSI; - unsigned long RBP; - unsigned long RSP; - unsigned long R8; - unsigned long R9; - unsigned long R10; - unsigned long R11; - unsigned long R12; - unsigned long R13; - unsigned long R14; - unsigned long R15; -}; -typedef struct RegisterInformationIntel64 RegisterInformationIntel64; - -typedef unsigned char FPRegIntel[10]; -struct FPUInformationIntel64 { - FPRegIntel Registers[8]; - unsigned short Control; - unsigned short Status; - unsigned short Tag; - unsigned short Opcode; - unsigned int IP; - unsigned int DP; - unsigned int DS; -}; -typedef struct FPUInformationIntel64 FPUInformationIntel64; -struct VectorInformationIntel64 { - Vector128Intel Registers[16]; -}; -typedef struct VectorInformationIntel64 VectorInformationIntel64; - -typedef MachineInformationIntel64 MachineInformation; -typedef RegisterInformationIntel64 RegisterInformation; -typedef FPUInformationIntel64 FPUInformation; -typedef VectorInformationIntel64 VectorInformation; - - - -struct ExceptionInformation { - ExceptionKind theKind; - MachineInformation * machineState; - RegisterInformation * registerImage; - FPUInformation * FPUImage; - ExceptionInfo info; - VectorInformation * vectorImage; -}; -typedef struct ExceptionInformation ExceptionInformation; -typedef OSStatus ( * ExceptionHandlerProcPtr)(ExceptionInformation * theException); -typedef ExceptionHandlerProcPtr ExceptionHandlerUPP; -extern ExceptionHandlerUPP -NewExceptionHandlerUPP(ExceptionHandlerProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeExceptionHandlerUPP(ExceptionHandlerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -InvokeExceptionHandlerUPP( - ExceptionInformation * theException, - ExceptionHandlerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline ExceptionHandlerUPP NewExceptionHandlerUPP(ExceptionHandlerProcPtr userRoutine) { return userRoutine; } - inline void DisposeExceptionHandlerUPP(ExceptionHandlerUPP) { } - inline OSStatus InvokeExceptionHandlerUPP(ExceptionInformation * theException, ExceptionHandlerUPP userUPP) { return (*userUPP)(theException); } -typedef ExceptionHandlerUPP ExceptionHandlerTPP; -typedef ExceptionHandlerTPP ExceptionHandler; -extern ExceptionHandlerTPP InstallExceptionHandler(ExceptionHandlerTPP theHandler) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - -#pragma options align=reset - - -} -extern "C" { - - -#pragma options align=power - - -enum { - durationMicrosecond = -1L, - durationMillisecond = 1, - durationSecond = 1000, - durationMinute = 60000, - durationHour = 3600000, - durationDay = 86400000, - durationNoWait = 0, - durationForever = 0x7FFFFFFF -}; - - -typedef UnsignedWide Nanoseconds; -extern AbsoluteTime -UpTime(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Nanoseconds -AbsoluteToNanoseconds(AbsoluteTime absoluteTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Duration -AbsoluteToDuration(AbsoluteTime absoluteTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern AbsoluteTime -NanosecondsToAbsolute(Nanoseconds nanoseconds) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern AbsoluteTime -DurationToAbsolute(Duration duration) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern AbsoluteTime -AddAbsoluteToAbsolute( - AbsoluteTime absoluteTime1, - AbsoluteTime absoluteTime2) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern AbsoluteTime -SubAbsoluteFromAbsolute( - AbsoluteTime leftAbsoluteTime, - AbsoluteTime rightAbsoluteTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern AbsoluteTime -AddNanosecondsToAbsolute( - Nanoseconds nanoseconds, - AbsoluteTime absoluteTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern AbsoluteTime -AddDurationToAbsolute( - Duration duration, - AbsoluteTime absoluteTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern AbsoluteTime -SubNanosecondsFromAbsolute( - Nanoseconds nanoseconds, - AbsoluteTime absoluteTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern AbsoluteTime -SubDurationFromAbsolute( - Duration duration, - AbsoluteTime absoluteTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Nanoseconds -AbsoluteDeltaToNanoseconds( - AbsoluteTime leftAbsoluteTime, - AbsoluteTime rightAbsoluteTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Duration -AbsoluteDeltaToDuration( - AbsoluteTime leftAbsoluteTime, - AbsoluteTime rightAbsoluteTime) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Nanoseconds -DurationToNanoseconds(Duration theDuration) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Duration -NanosecondsToDuration(Nanoseconds theNanoseconds) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - - -#pragma options align=reset - - -} - - - - - - - -extern "C" { - - -#pragma pack(push, 2) -struct NumFormatString { - UInt8 fLength; - UInt8 fVersion; - char data[254]; -}; -typedef struct NumFormatString NumFormatString; -typedef NumFormatString NumFormatStringRec; -typedef short FormatStatus; -enum { - fVNumber = 0 -}; - -typedef SInt8 FormatClass; -enum { - fPositive = 0, - fNegative = 1, - fZero = 2 -}; - -typedef SInt8 FormatResultType; -enum { - fFormatOK = 0, - fBestGuess = 1, - fOutOfSynch = 2, - fSpuriousChars = 3, - fMissingDelimiter = 4, - fExtraDecimal = 5, - fMissingLiteral = 6, - fExtraExp = 7, - fFormatOverflow = 8, - fFormStrIsNAN = 9, - fBadPartsTable = 10, - fExtraPercent = 11, - fExtraSeparator = 12, - fEmptyFormatString = 13 -}; - -struct FVector { - short start; - short length; -}; -typedef struct FVector FVector; - -typedef FVector TripleInt[3]; -extern void -numtostring( - long theNum, - char * theString) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -#pragma pack(pop) - - -} - - - - - - - -extern "C" { -enum { - - systemCurLang = -2, - systemDefLang = -3, - currentCurLang = -4, - currentDefLang = -5, - scriptCurLang = -6, - scriptDefLang = -7 -}; - - -enum { - iuSystemCurLang = systemCurLang, - iuSystemDefLang = systemDefLang, - iuCurrentCurLang = currentCurLang, - iuCurrentDefLang = currentDefLang, - iuScriptCurLang = scriptCurLang, - iuScriptDefLang = scriptDefLang -}; -} - - - -extern "C" { - - -#pragma pack(push, 2) -extern long -Munger( - Handle h, - long offset, - const void * ptr1, - long len1, - const void * ptr2, - long len2) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -extern Boolean -BitTst( - const void * bytePtr, - long bitNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -BitSet( - void * bytePtr, - long bitNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -BitClr( - void * bytePtr, - long bitNum) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -BitAnd( - long value1, - long value2) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -BitOr( - long value1, - long value2) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -BitXor( - long value1, - long value2) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -BitNot(long value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long -BitShift( - long value, - short count) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -typedef UInt16 UCKeyOutput; -typedef UInt16 UCKeyCharSeq; -enum { - kUCKeyOutputStateIndexMask = 0x4000, - kUCKeyOutputSequenceIndexMask = 0x8000, - kUCKeyOutputTestForIndexMask = 0xC000, - kUCKeyOutputGetIndexMask = 0x3FFF -}; -struct UCKeyStateRecord { - UCKeyCharSeq stateZeroCharData; - UInt16 stateZeroNextState; - UInt16 stateEntryCount; - UInt16 stateEntryFormat; - - - UInt32 stateEntryData[1]; -}; -typedef struct UCKeyStateRecord UCKeyStateRecord; - - - - -enum { - kUCKeyStateEntryTerminalFormat = 0x0001, - kUCKeyStateEntryRangeFormat = 0x0002 -}; - - - - - - -struct UCKeyStateEntryTerminal { - UInt16 curState; - UCKeyCharSeq charData; -}; -typedef struct UCKeyStateEntryTerminal UCKeyStateEntryTerminal; - - - - - - - -struct UCKeyStateEntryRange { - UInt16 curStateStart; - UInt8 curStateRange; - UInt8 deltaMultiplier; - UCKeyCharSeq charData; - UInt16 nextState; -}; -typedef struct UCKeyStateEntryRange UCKeyStateEntryRange; -struct UCKeyboardTypeHeader { - UInt32 keyboardTypeFirst; - UInt32 keyboardTypeLast; - UInt32 keyModifiersToTableNumOffset; - UInt32 keyToCharTableIndexOffset; - UInt32 keyStateRecordsIndexOffset; - UInt32 keyStateTerminatorsOffset; - UInt32 keySequenceDataIndexOffset; -}; -typedef struct UCKeyboardTypeHeader UCKeyboardTypeHeader; -struct UCKeyboardLayout { - - UInt16 keyLayoutHeaderFormat; - UInt16 keyLayoutDataVersion; - UInt32 keyLayoutFeatureInfoOffset; - UInt32 keyboardTypeCount; - UCKeyboardTypeHeader keyboardTypeList[1]; -}; -typedef struct UCKeyboardLayout UCKeyboardLayout; - -struct UCKeyLayoutFeatureInfo { - UInt16 keyLayoutFeatureInfoFormat; - UInt16 reserved; - UInt32 maxOutputStringLength; -}; -typedef struct UCKeyLayoutFeatureInfo UCKeyLayoutFeatureInfo; - -struct UCKeyModifiersToTableNum { - UInt16 keyModifiersToTableNumFormat; - UInt16 defaultTableNum; - UInt32 modifiersCount; - UInt8 tableNum[1]; - - -}; -typedef struct UCKeyModifiersToTableNum UCKeyModifiersToTableNum; - -struct UCKeyToCharTableIndex { - UInt16 keyToCharTableIndexFormat; - UInt16 keyToCharTableSize; - UInt32 keyToCharTableCount; - UInt32 keyToCharTableOffsets[1]; - - - - - - -}; -typedef struct UCKeyToCharTableIndex UCKeyToCharTableIndex; - -struct UCKeyStateRecordsIndex { - UInt16 keyStateRecordsIndexFormat; - UInt16 keyStateRecordCount; - UInt32 keyStateRecordOffsets[1]; - - - - -}; -typedef struct UCKeyStateRecordsIndex UCKeyStateRecordsIndex; - -struct UCKeyStateTerminators { - UInt16 keyStateTerminatorsFormat; - UInt16 keyStateTerminatorCount; - UCKeyCharSeq keyStateTerminators[1]; - - - -}; -typedef struct UCKeyStateTerminators UCKeyStateTerminators; - -struct UCKeySequenceDataIndex { - UInt16 keySequenceDataIndexFormat; - UInt16 charSequenceCount; - UInt16 charSequenceOffsets[1]; - - - - - -}; -typedef struct UCKeySequenceDataIndex UCKeySequenceDataIndex; - - - -enum { - kUCKeyLayoutHeaderFormat = 0x1002, - kUCKeyLayoutFeatureInfoFormat = 0x2001, - kUCKeyModifiersToTableNumFormat = 0x3001, - kUCKeyToCharTableIndexFormat = 0x4001, - kUCKeyStateRecordsIndexFormat = 0x5001, - kUCKeyStateTerminatorsFormat = 0x6001, - kUCKeySequenceDataIndexFormat = 0x7001 -}; -enum { - kUCKeyActionDown = 0, - kUCKeyActionUp = 1, - kUCKeyActionAutoKey = 2, - kUCKeyActionDisplay = 3 -}; - - - - - - - -enum { - kUCKeyTranslateNoDeadKeysBit = 0 -}; - -enum { - kUCKeyTranslateNoDeadKeysMask = 1L << kUCKeyTranslateNoDeadKeysBit -}; -enum { - kUnicodeCollationClass = 'ucol' -}; - -typedef struct OpaqueCollatorRef* CollatorRef; -typedef UInt32 UCCollateOptions; -enum { - - kUCCollateComposeInsensitiveMask = 1L << 1, - kUCCollateWidthInsensitiveMask = 1L << 2, - kUCCollateCaseInsensitiveMask = 1L << 3, - kUCCollateDiacritInsensitiveMask = 1L << 4, - kUCCollatePunctuationSignificantMask = 1L << 15, - kUCCollateDigitsOverrideMask = 1L << 16, - kUCCollateDigitsAsNumberMask = 1L << 17 -}; - -enum { - kUCCollateStandardOptions = kUCCollateComposeInsensitiveMask | kUCCollateWidthInsensitiveMask -}; - - - - - -enum { - kUCCollateTypeHFSExtended = 1 -}; - - -enum { - kUCCollateTypeSourceMask = 0x000000FF, - kUCCollateTypeShiftBits = 24 -}; - -enum { - kUCCollateTypeMask = (UInt32)kUCCollateTypeSourceMask << kUCCollateTypeShiftBits -}; - - -typedef UInt32 UCCollationValue; -typedef struct OpaqueUCTypeSelectRef* UCTypeSelectRef; - - - - -typedef SInt32 UCTypeSelectCompareResult; - - - - -typedef UInt16 UCTSWalkDirection; -enum { - kUCTSDirectionNext = 0, - kUCTSDirectionPrevious = 1 -}; -typedef UInt16 UCTypeSelectOptions; -enum { - kUCTSOptionsNoneMask = 0, - kUCTSOptionsReleaseStringMask = 1, - kUCTSOptionsDataIsOrderedMask = 2 -}; - - - - - - -typedef Boolean ( * IndexToUCStringProcPtr)(UInt32 index, void *listDataPtr, void *refcon, CFStringRef *outString, UCTypeSelectOptions *tsOptions); - -typedef IndexToUCStringProcPtr IndexToUCStringUPP; -extern IndexToUCStringUPP -NewIndexToUCStringUPP(IndexToUCStringProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.4))); -extern void -DisposeIndexToUCStringUPP(IndexToUCStringUPP userUPP) __attribute__((availability(macosx,introduced=10.4))); -extern Boolean -InvokeIndexToUCStringUPP( - UInt32 index, - void * listDataPtr, - void * refcon, - CFStringRef * outString, - UCTypeSelectOptions * tsOptions, - IndexToUCStringUPP userUPP) __attribute__((availability(macosx,introduced=10.4))); - - - - inline IndexToUCStringUPP NewIndexToUCStringUPP(IndexToUCStringProcPtr userRoutine) { return userRoutine; } - inline void DisposeIndexToUCStringUPP(IndexToUCStringUPP) { } - inline Boolean InvokeIndexToUCStringUPP(UInt32 index, void * listDataPtr, void * refcon, CFStringRef * outString, UCTypeSelectOptions * tsOptions, IndexToUCStringUPP userUPP) { return (*userUPP)(index, listDataPtr, refcon, outString, tsOptions); } -enum { - kUCTypeSelectMaxListSize = (UInt32)0xFFFFFFFF -}; -enum { - kUnicodeTextBreakClass = 'ubrk' -}; - -typedef struct OpaqueTextBreakLocatorRef* TextBreakLocatorRef; - - - - - - - -typedef UInt32 UCTextBreakType; -enum { - - - - - - - kUCTextBreakCharMask = 1L << 0, - kUCTextBreakClusterMask = 1L << 2, - - - - - - - kUCTextBreakWordMask = 1L << 4, - kUCTextBreakLineMask = 1L << 6, - - - - - - - kUCTextBreakParagraphMask = 1L << 8 -}; - -typedef UInt32 UCTextBreakOptions; -enum { - kUCTextBreakLeadingEdgeMask = 1L << 0, - kUCTextBreakGoBackwardsMask = 1L << 1, - kUCTextBreakIterateMask = 1L << 2 -}; -extern OSStatus -UCKeyTranslate( - const UCKeyboardLayout * keyLayoutPtr, - UInt16 virtualKeyCode, - UInt16 keyAction, - UInt32 modifierKeyState, - UInt32 keyboardType, - OptionBits keyTranslateOptions, - UInt32 * deadKeyState, - UniCharCount maxStringLength, - UniCharCount * actualStringLength, - UniChar unicodeString[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UCCreateCollator( - LocaleRef locale, - LocaleOperationVariant opVariant, - UCCollateOptions options, - CollatorRef * collatorRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UCGetCollationKey( - CollatorRef collatorRef, - const UniChar * textPtr, - UniCharCount textLength, - ItemCount maxKeySize, - ItemCount * actualKeySize, - UCCollationValue collationKey[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UCCompareCollationKeys( - const UCCollationValue * key1Ptr, - ItemCount key1Length, - const UCCollationValue * key2Ptr, - ItemCount key2Length, - Boolean * equivalent, - SInt32 * order) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UCCompareText( - CollatorRef collatorRef, - const UniChar * text1Ptr, - UniCharCount text1Length, - const UniChar * text2Ptr, - UniCharCount text2Length, - Boolean * equivalent, - SInt32 * order) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UCDisposeCollator(CollatorRef * collatorRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UCCompareTextDefault( - UCCollateOptions options, - const UniChar * text1Ptr, - UniCharCount text1Length, - const UniChar * text2Ptr, - UniCharCount text2Length, - Boolean * equivalent, - SInt32 * order) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UCCompareTextNoLocale( - UCCollateOptions options, - const UniChar * text1Ptr, - UniCharCount text1Length, - const UniChar * text2Ptr, - UniCharCount text2Length, - Boolean * equivalent, - SInt32 * order) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -UCCreateTextBreakLocator( - LocaleRef locale, - LocaleOperationVariant opVariant, - UCTextBreakType breakTypes, - TextBreakLocatorRef * breakRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -UCFindTextBreak( - TextBreakLocatorRef breakRef, - UCTextBreakType breakType, - UCTextBreakOptions options, - const UniChar * textPtr, - UniCharCount textLength, - UniCharArrayOffset startOffset, - UniCharArrayOffset * breakOffset) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -UCDisposeTextBreakLocator(TextBreakLocatorRef * breakRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -UCTypeSelectCreateSelector( - LocaleRef locale, - LocaleOperationVariant opVariant, - UCCollateOptions options, - UCTypeSelectRef * newSelector) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -UCTypeSelectFlushSelectorData(UCTypeSelectRef ref) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -UCTypeSelectReleaseSelector(UCTypeSelectRef * ref) __attribute__((availability(macosx,introduced=10.4))); -extern Boolean -UCTypeSelectWouldResetBuffer( - UCTypeSelectRef inRef, - CFStringRef inText, - double inEventTime) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -UCTypeSelectAddKeyToSelector( - UCTypeSelectRef inRef, - CFStringRef inText, - double inEventTime, - Boolean * updateFlag) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -UCTypeSelectCompare( - UCTypeSelectRef ref, - CFStringRef inText, - UCTypeSelectCompareResult * result) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -UCTypeSelectFindItem( - UCTypeSelectRef ref, - UInt32 listSize, - void * listDataPtr, - void * refcon, - IndexToUCStringUPP userUPP, - UInt32 * closestItem) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -UCTypeSelectWalkList( - UCTypeSelectRef ref, - CFStringRef currSelect, - UCTSWalkDirection direction, - UInt32 listSize, - void * listDataPtr, - void * refcon, - IndexToUCStringUPP userUPP, - UInt32 * closestItem) __attribute__((availability(macosx,introduced=10.4))); - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -extern const double_t pi __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern double compound(double rate, double periods) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern double annuity(double rate, double periods) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern double_t randomx(double_t * x) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -typedef short relop; -enum { - GREATERTHAN = 0, - LESSTHAN = 1, - EQUALTO = 2, - UNORDERED = 3 -}; -extern relop relation(double_t x, double_t y) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -struct decimal { - char sgn; - char unused; - short exp; - struct { - unsigned char length; - unsigned char text[36]; - unsigned char unused; - } sig; -}; -typedef struct decimal decimal; - -struct decform { - char style; - char unused; - short digits; -}; -typedef struct decform decform; -extern void num2dec(const decform *f, double_t x, decimal *d) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern double_t dec2num(const decimal * d) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void dec2str(const decform *f, const decimal *d, char *s) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void str2dec(const char *s, short *ix, decimal *d, short *vp) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern float dec2f(const decimal * d) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern short dec2s(const decimal * d) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern long dec2l(const decimal * d) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern relop relationl(long double x, long double y); -extern void num2decl(const decform *f, long double x, decimal *d); -extern long double dec2numl(const decimal * d); -extern double x80tod(const extended80 * x80) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void dtox80(const double *x, extended80 *x80) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void x80told(const extended80 *x80, long double *x); -extern void ldtox80(const long double *x, extended80 *x80); -#pragma pack(pop) - - -} - - -extern "C" { -typedef struct { - unsigned short __control; - unsigned short __status; - unsigned int __mxcsr; - char __reserved[8]; -} fenv_t; - -typedef unsigned short fexcept_t; -extern const fenv_t _FE_DFL_ENV; -extern const fenv_t _FE_DFL_DISABLE_SSE_DENORMS_ENV; -extern int feclearexcept(int ); -extern int fegetexceptflag(fexcept_t * , int ); -extern int feraiseexcept(int ); -extern int fesetexceptflag(const fexcept_t * , int ); -extern int fetestexcept(int ); -extern int fegetround(void); -extern int fesetround(int ); -extern int fegetenv(fenv_t * ); -extern int feholdexcept(fenv_t * ); -extern int fesetenv(const fenv_t * ); -extern int feupdateenv(const fenv_t * ); - - -} - -extern "C" { - - -#pragma pack(push, 2) - -typedef OSType TECPluginSignature; -typedef UInt32 TECPluginVersion; - -enum { - kTECSignature = 'encv', - kTECUnicodePluginSignature = 'puni', - kTECJapanesePluginSignature = 'pjpn', - kTECChinesePluginSignature = 'pzho', - kTECKoreanPluginSignature = 'pkor' -}; - - - -typedef struct OpaqueTECObjectRef* TECObjectRef; -typedef struct OpaqueTECSnifferObjectRef* TECSnifferObjectRef; -typedef OSType TECPluginSig; -struct TECConversionInfo { - TextEncoding sourceEncoding; - TextEncoding destinationEncoding; - UInt16 reserved1; - UInt16 reserved2; -}; -typedef struct TECConversionInfo TECConversionInfo; -typedef UInt32 TECInternetNameUsageMask; -enum { - - - - - - - kTECInternetNameDefaultUsageMask = 0, - - - - - - kTECInternetNameStrictUsageMask = 1, - kTECInternetNameTolerantUsageMask = 2 -}; - - -enum { - kTEC_MIBEnumDontCare = -1 -}; - - -enum { - kTECDisableFallbacksBit = 16, - kTECDisableLooseMappingsBit = 17 -}; - -enum { - kTECDisableFallbacksMask = 1L << kTECDisableFallbacksBit, - kTECDisableLooseMappingsMask = 1L << kTECDisableLooseMappingsBit -}; -extern OSStatus -TECCountAvailableTextEncodings(ItemCount * numberEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetAvailableTextEncodings( - TextEncoding availableEncodings[], - ItemCount maxAvailableEncodings, - ItemCount * actualAvailableEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCountDirectTextEncodingConversions(ItemCount * numberOfEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetDirectTextEncodingConversions( - TECConversionInfo availableConversions[], - ItemCount maxAvailableConversions, - ItemCount * actualAvailableConversions) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCountDestinationTextEncodings( - TextEncoding inputEncoding, - ItemCount * numberOfEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetDestinationTextEncodings( - TextEncoding inputEncoding, - TextEncoding destinationEncodings[], - ItemCount maxDestinationEncodings, - ItemCount * actualDestinationEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetTextEncodingInternetName( - TextEncoding textEncoding, - Str255 encodingName) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetTextEncodingFromInternetName( - TextEncoding * textEncoding, - ConstStr255Param encodingName) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCreateConverter( - TECObjectRef * newEncodingConverter, - TextEncoding inputEncoding, - TextEncoding outputEncoding) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCreateConverterFromPath( - TECObjectRef * newEncodingConverter, - const TextEncoding inPath[], - ItemCount inEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECDisposeConverter(TECObjectRef newEncodingConverter) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECClearConverterContextInfo(TECObjectRef encodingConverter) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECConvertText( - TECObjectRef encodingConverter, - ConstTextPtr inputBuffer, - ByteCount inputBufferLength, - ByteCount * actualInputLength, - TextPtr outputBuffer, - ByteCount outputBufferLength, - ByteCount * actualOutputLength) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECFlushText( - TECObjectRef encodingConverter, - TextPtr outputBuffer, - ByteCount outputBufferLength, - ByteCount * actualOutputLength) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCountSubTextEncodings( - TextEncoding inputEncoding, - ItemCount * numberOfEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetSubTextEncodings( - TextEncoding inputEncoding, - TextEncoding subEncodings[], - ItemCount maxSubEncodings, - ItemCount * actualSubEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetEncodingList( - TECObjectRef encodingConverter, - ItemCount * numEncodings, - Handle * encodingList) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCreateOneToManyConverter( - TECObjectRef * newEncodingConverter, - TextEncoding inputEncoding, - ItemCount numOutputEncodings, - const TextEncoding outputEncodings[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECConvertTextToMultipleEncodings( - TECObjectRef encodingConverter, - ConstTextPtr inputBuffer, - ByteCount inputBufferLength, - ByteCount * actualInputLength, - TextPtr outputBuffer, - ByteCount outputBufferLength, - ByteCount * actualOutputLength, - TextEncodingRun outEncodingsBuffer[], - ItemCount maxOutEncodingRuns, - ItemCount * actualOutEncodingRuns) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECFlushMultipleEncodings( - TECObjectRef encodingConverter, - TextPtr outputBuffer, - ByteCount outputBufferLength, - ByteCount * actualOutputLength, - TextEncodingRun outEncodingsBuffer[], - ItemCount maxOutEncodingRuns, - ItemCount * actualOutEncodingRuns) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCountWebTextEncodings( - RegionCode locale, - ItemCount * numberEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetWebTextEncodings( - RegionCode locale, - TextEncoding availableEncodings[], - ItemCount maxAvailableEncodings, - ItemCount * actualAvailableEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCountMailTextEncodings( - RegionCode locale, - ItemCount * numberEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetMailTextEncodings( - RegionCode locale, - TextEncoding availableEncodings[], - ItemCount maxAvailableEncodings, - ItemCount * actualAvailableEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCountAvailableSniffers(ItemCount * numberOfEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECGetAvailableSniffers( - TextEncoding availableSniffers[], - ItemCount maxAvailableSniffers, - ItemCount * actualAvailableSniffers) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECCreateSniffer( - TECSnifferObjectRef * encodingSniffer, - const TextEncoding testEncodings[], - ItemCount numTextEncodings) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECSniffTextEncoding( - TECSnifferObjectRef encodingSniffer, - ConstTextPtr inputBuffer, - ByteCount inputBufferLength, - TextEncoding testEncodings[], - ItemCount numTextEncodings, - ItemCount numErrsArray[], - ItemCount maxErrs, - ItemCount numFeaturesArray[], - ItemCount maxFeatures) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECDisposeSniffer(TECSnifferObjectRef encodingSniffer) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECClearSnifferContextInfo(TECSnifferObjectRef encodingSniffer) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TECSetBasicOptions( - TECObjectRef encodingConverter, - OptionBits controlFlags) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TECCopyTextEncodingInternetNameAndMIB( - TextEncoding textEncoding, - TECInternetNameUsageMask usage, - CFStringRef * encodingNamePtr, - SInt32 * mibEnumPtr) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TECGetTextEncodingFromInternetNameOrMIB( - TextEncoding * textEncodingPtr, - TECInternetNameUsageMask usage, - CFStringRef encodingName, - SInt32 mibEnum) __attribute__((availability(macosx,introduced=10.3))); - - - - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - - -typedef struct OpaqueTextToUnicodeInfo* TextToUnicodeInfo; -typedef struct OpaqueUnicodeToTextInfo* UnicodeToTextInfo; -typedef struct OpaqueUnicodeToTextRunInfo* UnicodeToTextRunInfo; -typedef const TextToUnicodeInfo ConstTextToUnicodeInfo; -typedef const UnicodeToTextInfo ConstUnicodeToTextInfo; - -typedef SInt32 UnicodeMapVersion; -enum { - kUnicodeUseLatestMapping = -1, - kUnicodeUseHFSPlusMapping = 4 -}; - - -struct UnicodeMapping { - TextEncoding unicodeEncoding; - TextEncoding otherEncoding; - UnicodeMapVersion mappingVersion; -}; -typedef struct UnicodeMapping UnicodeMapping; -typedef UnicodeMapping * UnicodeMappingPtr; -typedef const UnicodeMapping * ConstUnicodeMappingPtr; - -enum { - kUnicodeUseFallbacksBit = 0, - kUnicodeKeepInfoBit = 1, - kUnicodeDirectionalityBits = 2, - kUnicodeVerticalFormBit = 4, - kUnicodeLooseMappingsBit = 5, - kUnicodeStringUnterminatedBit = 6, - kUnicodeTextRunBit = 7, - kUnicodeKeepSameEncodingBit = 8, - kUnicodeForceASCIIRangeBit = 9, - kUnicodeNoHalfwidthCharsBit = 10, - kUnicodeTextRunHeuristicsBit = 11, - kUnicodeMapLineFeedToReturnBit = 12, - - - - - - kUnicodeUseExternalEncodingFormBit = 13 -}; - -enum { - kUnicodeUseFallbacksMask = 1L << kUnicodeUseFallbacksBit, - kUnicodeKeepInfoMask = 1L << kUnicodeKeepInfoBit, - kUnicodeDirectionalityMask = 3L << kUnicodeDirectionalityBits, - kUnicodeVerticalFormMask = 1L << kUnicodeVerticalFormBit, - kUnicodeLooseMappingsMask = 1L << kUnicodeLooseMappingsBit, - kUnicodeStringUnterminatedMask = 1L << kUnicodeStringUnterminatedBit, - kUnicodeTextRunMask = 1L << kUnicodeTextRunBit, - kUnicodeKeepSameEncodingMask = 1L << kUnicodeKeepSameEncodingBit, - kUnicodeForceASCIIRangeMask = 1L << kUnicodeForceASCIIRangeBit, - kUnicodeNoHalfwidthCharsMask = 1L << kUnicodeNoHalfwidthCharsBit, - kUnicodeTextRunHeuristicsMask = 1L << kUnicodeTextRunHeuristicsBit, - kUnicodeMapLineFeedToReturnMask = 1L << kUnicodeMapLineFeedToReturnBit, - - - - - - kUnicodeUseExternalEncodingFormMask = 1L << kUnicodeUseExternalEncodingFormBit -}; - - -enum { - kUnicodeDefaultDirection = 0, - kUnicodeLeftToRight = 1, - kUnicodeRightToLeft = 2 -}; - - -enum { - kUnicodeDefaultDirectionMask = kUnicodeDefaultDirection << kUnicodeDirectionalityBits, - kUnicodeLeftToRightMask = kUnicodeLeftToRight << kUnicodeDirectionalityBits, - kUnicodeRightToLeftMask = kUnicodeRightToLeft << kUnicodeDirectionalityBits -}; -enum { - kUnicodeMatchUnicodeBaseBit = 0, - kUnicodeMatchUnicodeVariantBit = 1, - kUnicodeMatchUnicodeFormatBit = 2, - kUnicodeMatchOtherBaseBit = 3, - kUnicodeMatchOtherVariantBit = 4, - kUnicodeMatchOtherFormatBit = 5 -}; - -enum { - kUnicodeMatchUnicodeBaseMask = 1L << kUnicodeMatchUnicodeBaseBit, - kUnicodeMatchUnicodeVariantMask = 1L << kUnicodeMatchUnicodeVariantBit, - kUnicodeMatchUnicodeFormatMask = 1L << kUnicodeMatchUnicodeFormatBit, - kUnicodeMatchOtherBaseMask = 1L << kUnicodeMatchOtherBaseBit, - kUnicodeMatchOtherVariantMask = 1L << kUnicodeMatchOtherVariantBit, - kUnicodeMatchOtherFormatMask = 1L << kUnicodeMatchOtherFormatBit -}; - - -enum { - kUnicodeFallbackSequencingBits = 0 -}; - -enum { - kUnicodeFallbackSequencingMask = 3L << kUnicodeFallbackSequencingBits, - kUnicodeFallbackInterruptSafeMask = 1L << 2 -}; - - -enum { - kUnicodeFallbackDefaultOnly = 0, - kUnicodeFallbackCustomOnly = 1, - kUnicodeFallbackDefaultFirst = 2, - kUnicodeFallbackCustomFirst = 3 -}; - - - -typedef OSStatus ( * UnicodeToTextFallbackProcPtr)(UniChar *iSrcUniStr, ByteCount iSrcUniStrLen, ByteCount *oSrcConvLen, TextPtr oDestStr, ByteCount iDestStrLen, ByteCount *oDestConvLen, LogicalAddress iInfoPtr, ConstUnicodeMappingPtr iUnicodeMappingPtr); -typedef UnicodeToTextFallbackProcPtr UnicodeToTextFallbackUPP; -extern UnicodeToTextFallbackUPP -NewUnicodeToTextFallbackUPP(UnicodeToTextFallbackProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeUnicodeToTextFallbackUPP(UnicodeToTextFallbackUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -InvokeUnicodeToTextFallbackUPP( - UniChar * iSrcUniStr, - ByteCount iSrcUniStrLen, - ByteCount * oSrcConvLen, - TextPtr oDestStr, - ByteCount iDestStrLen, - ByteCount * oDestConvLen, - LogicalAddress iInfoPtr, - ConstUnicodeMappingPtr iUnicodeMappingPtr, - UnicodeToTextFallbackUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); - - - - inline UnicodeToTextFallbackUPP NewUnicodeToTextFallbackUPP(UnicodeToTextFallbackProcPtr userRoutine) { return userRoutine; } - inline void DisposeUnicodeToTextFallbackUPP(UnicodeToTextFallbackUPP) { } - inline OSStatus InvokeUnicodeToTextFallbackUPP(UniChar * iSrcUniStr, ByteCount iSrcUniStrLen, ByteCount * oSrcConvLen, TextPtr oDestStr, ByteCount iDestStrLen, ByteCount * oDestConvLen, LogicalAddress iInfoPtr, ConstUnicodeMappingPtr iUnicodeMappingPtr, UnicodeToTextFallbackUPP userUPP) { return (*userUPP)(iSrcUniStr, iSrcUniStrLen, oSrcConvLen, oDestStr, iDestStrLen, oDestConvLen, iInfoPtr, iUnicodeMappingPtr); } -extern OSStatus -CreateTextToUnicodeInfo( - ConstUnicodeMappingPtr iUnicodeMapping, - TextToUnicodeInfo * oTextToUnicodeInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -CreateTextToUnicodeInfoByEncoding( - TextEncoding iEncoding, - TextToUnicodeInfo * oTextToUnicodeInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -CreateUnicodeToTextInfo( - ConstUnicodeMappingPtr iUnicodeMapping, - UnicodeToTextInfo * oUnicodeToTextInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -CreateUnicodeToTextInfoByEncoding( - TextEncoding iEncoding, - UnicodeToTextInfo * oUnicodeToTextInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -CreateUnicodeToTextRunInfo( - ItemCount iNumberOfMappings, - const UnicodeMapping iUnicodeMappings[], - UnicodeToTextRunInfo * oUnicodeToTextInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -CreateUnicodeToTextRunInfoByEncoding( - ItemCount iNumberOfEncodings, - const TextEncoding iEncodings[], - UnicodeToTextRunInfo * oUnicodeToTextInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -CreateUnicodeToTextRunInfoByScriptCode( - ItemCount iNumberOfScriptCodes, - const ScriptCode iScripts[], - UnicodeToTextRunInfo * oUnicodeToTextInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ChangeTextToUnicodeInfo( - TextToUnicodeInfo ioTextToUnicodeInfo, - ConstUnicodeMappingPtr iUnicodeMapping) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ChangeUnicodeToTextInfo( - UnicodeToTextInfo ioUnicodeToTextInfo, - ConstUnicodeMappingPtr iUnicodeMapping) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -DisposeTextToUnicodeInfo(TextToUnicodeInfo * ioTextToUnicodeInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -DisposeUnicodeToTextInfo(UnicodeToTextInfo * ioUnicodeToTextInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -DisposeUnicodeToTextRunInfo(UnicodeToTextRunInfo * ioUnicodeToTextRunInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ConvertFromTextToUnicode( - TextToUnicodeInfo iTextToUnicodeInfo, - ByteCount iSourceLen, - ConstLogicalAddress iSourceStr, - OptionBits iControlFlags, - ItemCount iOffsetCount, - const ByteOffset iOffsetArray[], - ItemCount * oOffsetCount, - ByteOffset oOffsetArray[], - ByteCount iOutputBufLen, - ByteCount * oSourceRead, - ByteCount * oUnicodeLen, - UniChar oUnicodeStr[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ConvertFromUnicodeToText( - UnicodeToTextInfo iUnicodeToTextInfo, - ByteCount iUnicodeLen, - const UniChar iUnicodeStr[], - OptionBits iControlFlags, - ItemCount iOffsetCount, - const ByteOffset iOffsetArray[], - ItemCount * oOffsetCount, - ByteOffset oOffsetArray[], - ByteCount iOutputBufLen, - ByteCount * oInputRead, - ByteCount * oOutputLen, - LogicalAddress oOutputStr) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ConvertFromUnicodeToTextRun( - UnicodeToTextRunInfo iUnicodeToTextInfo, - ByteCount iUnicodeLen, - const UniChar iUnicodeStr[], - OptionBits iControlFlags, - ItemCount iOffsetCount, - const ByteOffset iOffsetArray[], - ItemCount * oOffsetCount, - ByteOffset oOffsetArray[], - ByteCount iOutputBufLen, - ByteCount * oInputRead, - ByteCount * oOutputLen, - LogicalAddress oOutputStr, - ItemCount iEncodingRunBufLen, - ItemCount * oEncodingRunOutLen, - TextEncodingRun oEncodingRuns[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ConvertFromUnicodeToScriptCodeRun( - UnicodeToTextRunInfo iUnicodeToTextInfo, - ByteCount iUnicodeLen, - const UniChar iUnicodeStr[], - OptionBits iControlFlags, - ItemCount iOffsetCount, - const ByteOffset iOffsetArray[], - ItemCount * oOffsetCount, - ByteOffset oOffsetArray[], - ByteCount iOutputBufLen, - ByteCount * oInputRead, - ByteCount * oOutputLen, - LogicalAddress oOutputStr, - ItemCount iScriptRunBufLen, - ItemCount * oScriptRunOutLen, - ScriptCodeRun oScriptCodeRuns[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TruncateForTextToUnicode( - ConstTextToUnicodeInfo iTextToUnicodeInfo, - ByteCount iSourceLen, - ConstLogicalAddress iSourceStr, - ByteCount iMaxLen, - ByteCount * oTruncatedLen) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -TruncateForUnicodeToText( - ConstUnicodeToTextInfo iUnicodeToTextInfo, - ByteCount iSourceLen, - const UniChar iSourceStr[], - OptionBits iControlFlags, - ByteCount iMaxLen, - ByteCount * oTruncatedLen) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ConvertFromPStringToUnicode( - TextToUnicodeInfo iTextToUnicodeInfo, - ConstStr255Param iPascalStr, - ByteCount iOutputBufLen, - ByteCount * oUnicodeLen, - UniChar oUnicodeStr[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ConvertFromUnicodeToPString( - UnicodeToTextInfo iUnicodeToTextInfo, - ByteCount iUnicodeLen, - const UniChar iUnicodeStr[], - Str255 oPascalStr) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -CountUnicodeMappings( - OptionBits iFilter, - ConstUnicodeMappingPtr iFindMapping, - ItemCount * oActualCount) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -QueryUnicodeMappings( - OptionBits iFilter, - ConstUnicodeMappingPtr iFindMapping, - ItemCount iMaxCount, - ItemCount * oActualCount, - UnicodeMapping oReturnedMappings[]) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -SetFallbackUnicodeToText( - UnicodeToTextInfo iUnicodeToTextInfo, - UnicodeToTextFallbackUPP iFallback, - OptionBits iControlFlags, - LogicalAddress iInfoPtr) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -SetFallbackUnicodeToTextRun( - UnicodeToTextRunInfo iUnicodeToTextRunInfo, - UnicodeToTextFallbackUPP iFallback, - OptionBits iControlFlags, - LogicalAddress iInfoPtr) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ResetTextToUnicodeInfo(TextToUnicodeInfo ioTextToUnicodeInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ResetUnicodeToTextInfo(UnicodeToTextInfo ioUnicodeToTextInfo) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ResetUnicodeToTextRunInfo(UnicodeToTextRunInfo ioUnicodeToTextRunInfo) __attribute__((availability(macosx,introduced=10.0))); - - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -typedef UInt16 ThreadState; -enum { - kReadyThreadState = 0, - kStoppedThreadState = 1, - kRunningThreadState = 2 -}; - - - - -typedef void * ThreadTaskRef; - -typedef UInt32 ThreadStyle; -enum { - kCooperativeThread = 1L << 0, - kPreemptiveThread = 1L << 1 -}; - - -typedef unsigned long ThreadID; -enum { - kNoThreadID = 0, - kCurrentThreadID = 1, - kApplicationThreadID = 2 -}; - - -typedef UInt32 ThreadOptions; -enum { - kNewSuspend = (1 << 0), - kUsePremadeThread = (1 << 1), - kCreateIfNeeded = (1 << 2), - kFPUNotNeeded = (1 << 3), - kExactMatchThread = (1 << 4) -}; - - -struct SchedulerInfoRec { - UInt32 InfoRecSize; - ThreadID CurrentThreadID; - ThreadID SuggestedThreadID; - ThreadID InterruptedCoopThreadID; -}; -typedef struct SchedulerInfoRec SchedulerInfoRec; -typedef SchedulerInfoRec * SchedulerInfoRecPtr; - - - - - - -typedef void * voidPtr; - -typedef voidPtr ( * ThreadEntryProcPtr)(void * threadParam); - -typedef ThreadID ( * ThreadSchedulerProcPtr)(SchedulerInfoRecPtr schedulerInfo); - -typedef void ( * ThreadSwitchProcPtr)(ThreadID threadBeingSwitched, void *switchProcParam); - -typedef void ( * ThreadTerminationProcPtr)(ThreadID threadTerminated, void *terminationProcParam); - -typedef void ( * DebuggerNewThreadProcPtr)(ThreadID threadCreated); - -typedef void ( * DebuggerDisposeThreadProcPtr)(ThreadID threadDeleted); - -typedef ThreadID ( * DebuggerThreadSchedulerProcPtr)(SchedulerInfoRecPtr schedulerInfo); -typedef ThreadEntryProcPtr ThreadEntryUPP; -typedef ThreadSchedulerProcPtr ThreadSchedulerUPP; -typedef ThreadSwitchProcPtr ThreadSwitchUPP; -typedef ThreadTerminationProcPtr ThreadTerminationUPP; -typedef DebuggerNewThreadProcPtr DebuggerNewThreadUPP; -typedef DebuggerDisposeThreadProcPtr DebuggerDisposeThreadUPP; -typedef DebuggerThreadSchedulerProcPtr DebuggerThreadSchedulerUPP; -extern ThreadEntryUPP -NewThreadEntryUPP(ThreadEntryProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern ThreadSchedulerUPP -NewThreadSchedulerUPP(ThreadSchedulerProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern ThreadSwitchUPP -NewThreadSwitchUPP(ThreadSwitchProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern ThreadTerminationUPP -NewThreadTerminationUPP(ThreadTerminationProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern DebuggerNewThreadUPP -NewDebuggerNewThreadUPP(DebuggerNewThreadProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern DebuggerDisposeThreadUPP -NewDebuggerDisposeThreadUPP(DebuggerDisposeThreadProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern DebuggerThreadSchedulerUPP -NewDebuggerThreadSchedulerUPP(DebuggerThreadSchedulerProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -DisposeThreadEntryUPP(ThreadEntryUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -DisposeThreadSchedulerUPP(ThreadSchedulerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -DisposeThreadSwitchUPP(ThreadSwitchUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -DisposeThreadTerminationUPP(ThreadTerminationUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -DisposeDebuggerNewThreadUPP(DebuggerNewThreadUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -DisposeDebuggerDisposeThreadUPP(DebuggerDisposeThreadUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -DisposeDebuggerThreadSchedulerUPP(DebuggerThreadSchedulerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern voidPtr -InvokeThreadEntryUPP( - void * threadParam, - ThreadEntryUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern ThreadID -InvokeThreadSchedulerUPP( - SchedulerInfoRecPtr schedulerInfo, - ThreadSchedulerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -InvokeThreadSwitchUPP( - ThreadID threadBeingSwitched, - void * switchProcParam, - ThreadSwitchUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -InvokeThreadTerminationUPP( - ThreadID threadTerminated, - void * terminationProcParam, - ThreadTerminationUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -InvokeDebuggerNewThreadUPP( - ThreadID threadCreated, - DebuggerNewThreadUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -InvokeDebuggerDisposeThreadUPP( - ThreadID threadDeleted, - DebuggerDisposeThreadUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern ThreadID -InvokeDebuggerThreadSchedulerUPP( - SchedulerInfoRecPtr schedulerInfo, - DebuggerThreadSchedulerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - inline ThreadEntryUPP NewThreadEntryUPP(ThreadEntryProcPtr userRoutine) { return userRoutine; } - inline ThreadSchedulerUPP NewThreadSchedulerUPP(ThreadSchedulerProcPtr userRoutine) { return userRoutine; } - inline ThreadSwitchUPP NewThreadSwitchUPP(ThreadSwitchProcPtr userRoutine) { return userRoutine; } - inline ThreadTerminationUPP NewThreadTerminationUPP(ThreadTerminationProcPtr userRoutine) { return userRoutine; } - inline DebuggerNewThreadUPP NewDebuggerNewThreadUPP(DebuggerNewThreadProcPtr userRoutine) { return userRoutine; } - inline DebuggerDisposeThreadUPP NewDebuggerDisposeThreadUPP(DebuggerDisposeThreadProcPtr userRoutine) { return userRoutine; } - inline DebuggerThreadSchedulerUPP NewDebuggerThreadSchedulerUPP(DebuggerThreadSchedulerProcPtr userRoutine) { return userRoutine; } - inline void DisposeThreadEntryUPP(ThreadEntryUPP) { } - inline void DisposeThreadSchedulerUPP(ThreadSchedulerUPP) { } - inline void DisposeThreadSwitchUPP(ThreadSwitchUPP) { } - inline void DisposeThreadTerminationUPP(ThreadTerminationUPP) { } - inline void DisposeDebuggerNewThreadUPP(DebuggerNewThreadUPP) { } - inline void DisposeDebuggerDisposeThreadUPP(DebuggerDisposeThreadUPP) { } - inline void DisposeDebuggerThreadSchedulerUPP(DebuggerThreadSchedulerUPP) { } - inline voidPtr InvokeThreadEntryUPP(void * threadParam, ThreadEntryUPP userUPP) { return (*userUPP)(threadParam); } - inline ThreadID InvokeThreadSchedulerUPP(SchedulerInfoRecPtr schedulerInfo, ThreadSchedulerUPP userUPP) { return (*userUPP)(schedulerInfo); } - inline void InvokeThreadSwitchUPP(ThreadID threadBeingSwitched, void * switchProcParam, ThreadSwitchUPP userUPP) { (*userUPP)(threadBeingSwitched, switchProcParam); } - inline void InvokeThreadTerminationUPP(ThreadID threadTerminated, void * terminationProcParam, ThreadTerminationUPP userUPP) { (*userUPP)(threadTerminated, terminationProcParam); } - inline void InvokeDebuggerNewThreadUPP(ThreadID threadCreated, DebuggerNewThreadUPP userUPP) { (*userUPP)(threadCreated); } - inline void InvokeDebuggerDisposeThreadUPP(ThreadID threadDeleted, DebuggerDisposeThreadUPP userUPP) { (*userUPP)(threadDeleted); } - inline ThreadID InvokeDebuggerThreadSchedulerUPP(SchedulerInfoRecPtr schedulerInfo, DebuggerThreadSchedulerUPP userUPP) { return (*userUPP)(schedulerInfo); } -typedef ThreadEntryUPP ThreadEntryTPP; -typedef ThreadSchedulerUPP ThreadSchedulerTPP; -typedef ThreadSwitchUPP ThreadSwitchTPP; -typedef ThreadTerminationUPP ThreadTerminationTPP; -typedef DebuggerNewThreadUPP DebuggerNewThreadTPP; -typedef DebuggerDisposeThreadUPP DebuggerDisposeThreadTPP; -typedef DebuggerThreadSchedulerUPP DebuggerThreadSchedulerTPP; -extern OSErr -NewThread( - ThreadStyle threadStyle, - ThreadEntryTPP threadEntry, - void * threadParam, - Size stackSize, - ThreadOptions options, - void ** threadResult, - ThreadID * threadMade) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -SetThreadScheduler(ThreadSchedulerTPP threadScheduler) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -SetThreadSwitcher( - ThreadID thread, - ThreadSwitchTPP threadSwitcher, - void * switchProcParam, - Boolean inOrOut) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -SetThreadTerminator( - ThreadID thread, - ThreadTerminationTPP threadTerminator, - void * terminationProcParam) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -SetDebuggerNotificationProcs( - DebuggerNewThreadTPP notifyNewThread, - DebuggerDisposeThreadTPP notifyDisposeThread, - DebuggerThreadSchedulerTPP notifyThreadScheduler) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -CreateThreadPool( - ThreadStyle threadStyle, - SInt16 numToCreate, - Size stackSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -GetDefaultThreadStackSize( - ThreadStyle threadStyle, - Size * stackSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -ThreadCurrentStackSpace( - ThreadID thread, - ByteCount * freeStack) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -DisposeThread( - ThreadID threadToDump, - void * threadResult, - Boolean recycleThread) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -YieldToThread(ThreadID suggestedThread) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -YieldToAnyThread(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -GetCurrentThread(ThreadID * currentThreadID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -GetThreadState( - ThreadID threadToGet, - ThreadState * threadState) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -SetThreadState( - ThreadID threadToSet, - ThreadState newState, - ThreadID suggestedThread) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -SetThreadStateEndCritical( - ThreadID threadToSet, - ThreadState newState, - ThreadID suggestedThread) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -ThreadBeginCritical(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -ThreadEndCritical(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -GetThreadCurrentTaskRef(ThreadTaskRef * threadTRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -GetThreadStateGivenTaskRef( - ThreadTaskRef threadTRef, - ThreadID threadToGet, - ThreadState * threadState) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSErr -SetThreadReadyGivenTaskRef( - ThreadTaskRef threadTRef, - ThreadID threadToSet) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -enum { - kOnSystemDisk = -32768L, - kOnAppropriateDisk = -32767, - - - kSystemDomain = -32766, - kLocalDomain = -32765, - kNetworkDomain = -32764, - kUserDomain = -32763, - kClassicDomain = -32762, - kFolderManagerLastDomain = -32760 -}; - - - - - -enum { - kLastDomainConstant = -32760 -}; - -enum { - kCreateFolder = true, - kDontCreateFolder = false -}; -extern OSErr -FindFolder( - FSVolumeRefNum vRefNum, - OSType folderType, - Boolean createFolder, - FSVolumeRefNum * foundVRefNum, - SInt32 * foundDirID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -ReleaseFolder( - FSVolumeRefNum vRefNum, - OSType folderType) __attribute__((availability(macosx,introduced=10.0,deprecated=10.3))); -extern OSErr -FSFindFolder( - FSVolumeRefNum vRefNum, - OSType folderType, - Boolean createFolder, - FSRef * foundRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -enum { - kDesktopFolderType = 'desk', - kTrashFolderType = 'trsh', - kWhereToEmptyTrashFolderType = 'empt', - kFontsFolderType = 'font', - kPreferencesFolderType = 'pref', - kSystemPreferencesFolderType = 'sprf', - kTemporaryFolderType = 'temp', - kChewableItemsFolderType = 'flnt', - kTemporaryItemsInCacheDataFolderType = 'vtmp', - kApplicationsFolderType = 'apps', - kVolumeRootFolderType = 'root', - kDomainTopLevelFolderType = 'dtop', - kDomainLibraryFolderType = 'dlib', - kUsersFolderType = 'usrs', - kCurrentUserFolderType = 'cusr', - kSharedUserDataFolderType = 'sdat' -}; - - - - - -enum { - kDocumentsFolderType = 'docs', - kPictureDocumentsFolderType = 'pdoc', - kMovieDocumentsFolderType = 'mdoc', - kMusicDocumentsFolderType = 0xB5646F63 , - kInternetSitesFolderType = 'site', - kPublicFolderType = 'pubb' -}; - - -enum { - kDropBoxFolderType = 'drop' -}; - -enum { - kSharedLibrariesFolderType = 0xC46C6962 , - kVoicesFolderType = 'fvoc', - kUtilitiesFolderType = 0x757469C4 , - kThemesFolderType = 'thme', - kFavoritesFolderType = 'favs', - kInternetSearchSitesFolderType = 'issf', - kInstallerLogsFolderType = 'ilgf', - kScriptsFolderType = 0x736372C4 , - kFolderActionsFolderType = 'fasf', - kSpeakableItemsFolderType = 'spki', - kKeychainFolderType = 'kchn' -}; - - - -enum { - kColorSyncFolderType = 'sync', - kColorSyncCMMFolderType = 'ccmm', - kColorSyncScriptingFolderType = 'cscr', - kPrintersFolderType = 'impr', - kSpeechFolderType = 'spch', - kCarbonLibraryFolderType = 'carb', - kDocumentationFolderType = 'info', - kISSDownloadsFolderType = 'issd', - kUserSpecificTmpFolderType = 'utmp', - kCachedDataFolderType = 'cach', - kFrameworksFolderType = 'fram', - kPrivateFrameworksFolderType = 'pfrm', - kClassicDesktopFolderType = 'sdsk', - kSystemSoundsFolderType = 'ssnd', - kComponentsFolderType = 'cmpd', - kQuickTimeComponentsFolderType = 'wcmp', - kCoreServicesFolderType = 'csrv', - kAudioSupportFolderType = 'adio', - kAudioPresetsFolderType = 'apst', - kAudioSoundsFolderType = 'asnd', - kAudioSoundBanksFolderType = 'bank', - kAudioAlertSoundsFolderType = 'alrt', - kAudioPlugInsFolderType = 'aplg', - kAudioComponentsFolderType = 'acmp', - kKernelExtensionsFolderType = 'kext', - kDirectoryServicesFolderType = 'dsrv', - kDirectoryServicesPlugInsFolderType = 'dplg', - kInstallerReceiptsFolderType = 'rcpt', - kFileSystemSupportFolderType = 'fsys', - kAppleShareSupportFolderType = 'shar', - kAppleShareAuthenticationFolderType = 'auth', - kMIDIDriversFolderType = 'midi', - kKeyboardLayoutsFolderType = 'klay', - kIndexFilesFolderType = 'indx', - kFindByContentIndexesFolderType = 'fbcx', - kManagedItemsFolderType = 'mang', - kBootTimeStartupItemsFolderType = 'empz', - kAutomatorWorkflowsFolderType = 'flow', - kAutosaveInformationFolderType = 'asav', - kSpotlightSavedSearchesFolderType = 'spot', - - kSpotlightImportersFolderType = 'simp', - kSpotlightMetadataCacheFolderType = 'scch', - kInputManagersFolderType = 'inpt', - kInputMethodsFolderType = 'inpf', - kLibraryAssistantsFolderType = 'astl', - kAudioDigidesignFolderType = 'adig', - kAudioVSTFolderType = 'avst', - kColorPickersFolderType = 'cpkr', - kCompositionsFolderType = 'cmps', - kFontCollectionsFolderType = 'fncl', - kiMovieFolderType = 'imov', - kiMoviePlugInsFolderType = 'impi', - kiMovieSoundEffectsFolderType = 'imse', - kDownloadsFolderType = 'down' -}; - -enum { - kColorSyncProfilesFolderType = 'prof', - kApplicationSupportFolderType = 'asup', - kTextEncodingsFolderType = 0xC4746578 , - kPrinterDescriptionFolderType = 'ppdf', - kPrinterDriverFolderType = 0xC4707264 , - kScriptingAdditionsFolderType = 0xC4736372 -}; - -enum { - kClassicPreferencesFolderType = 'cprf' -}; - -enum { - kQuickLookFolderType = 'qlck' -}; - -enum { - kServicesFolderType = 'svcs' -}; - -enum { - - kSystemFolderType = 'macs', - kSystemDesktopFolderType = 'sdsk', - kSystemTrashFolderType = 'strs', - kPrintMonitorDocsFolderType = 'prnt', - kALMModulesFolderType = 'walk', - kALMPreferencesFolderType = 'trip', - kALMLocationsFolderType = 'fall', - kAppleExtrasFolderType = 0x616578C4 , - kContextualMenuItemsFolderType = 'cmnu', - kMacOSReadMesFolderType = 0x6D6F72C4 , - kStartupFolderType = 'strt', - kShutdownFolderType = 'shdf', - kAppleMenuFolderType = 'amnu', - kControlPanelFolderType = 'ctrl', - kSystemControlPanelFolderType = 'sctl', - kExtensionFolderType = 'extn', - kExtensionDisabledFolderType = 'extD', - kControlPanelDisabledFolderType = 'ctrD', - kSystemExtensionDisabledFolderType = 'macD', - kStartupItemsDisabledFolderType = 'strD', - kShutdownItemsDisabledFolderType = 'shdD', - kAssistantsFolderType = 0x617374C4 , - kStationeryFolderType = 'odst', - kOpenDocFolderType = 'odod', - kOpenDocShellPlugInsFolderType = 'odsp', - kEditorsFolderType = 'oded', - kOpenDocEditorsFolderType = 0xC46F6466 , - kOpenDocLibrariesFolderType = 'odlb', - kGenEditorsFolderType = 0xC4656469 , - kHelpFolderType = 0xC4686C70 , - kInternetPlugInFolderType = 0xC46E6574 , - kModemScriptsFolderType = 0xC46D6F64 , - kControlStripModulesFolderType = 'sdev', - kInternetFolderType = 0x696E74C4 , - kAppearanceFolderType = 'appr', - kSoundSetsFolderType = 'snds', - kDesktopPicturesFolderType = 0x647470C4 , - kFindSupportFolderType = 'fnds', - kRecentApplicationsFolderType = 'rapp', - kRecentDocumentsFolderType = 'rdoc', - kRecentServersFolderType = 'rsvr', - kLauncherItemsFolderType = 'laun', - kQuickTimeExtensionsFolderType = 'qtex', - kDisplayExtensionsFolderType = 'dspl', - kMultiprocessingFolderType = 'mpxf', - kPrintingPlugInsFolderType = 'pplg', - kAppleshareAutomountServerAliasesFolderType = 0x737276C4 , - kVolumeSettingsFolderType = 'vsfd', - kPreMacOS91ApplicationsFolderType = 0x8C707073 , - kPreMacOS91InstallerLogsFolderType = 0x946C6766 , - kPreMacOS91AssistantsFolderType = 0x8C7374C4 , - kPreMacOS91UtilitiesFolderType = 0x9F7469C4 , - kPreMacOS91AppleExtrasFolderType = 0x8C6578C4 , - kPreMacOS91MacOSReadMesFolderType = 0xB56F72C4 , - kPreMacOS91InternetFolderType = 0x946E74C4 , - kPreMacOS91AutomountedServersFolderType = 0xA77276C4 , - kPreMacOS91StationeryFolderType = 0xBF647374 , - kLocalesFolderType = 0xC46C6F63 , - kFindByContentPluginsFolderType = 'fbcp', - kFindByContentFolderType = 'fbcf' -}; - - -enum { - kMagicTemporaryItemsFolderType = 'mtmp', - kTemporaryItemsInUserDomainFolderType = 'temq', - kCurrentUserRemoteFolderLocation = 'rusf', - kCurrentUserRemoteFolderType = 'rusr' -}; - - - - - -enum { - kDeveloperDocsFolderType = 'ddoc', - kDeveloperHelpFolderType = 'devh', - kDeveloperFolderType = 'devf', - kDeveloperApplicationsFolderType = 'dapp' -}; - - -enum { - kCreateFolderAtBoot = 0x00000002, - kCreateFolderAtBootBit = 1, - kFolderCreatedInvisible = 0x00000004, - kFolderCreatedInvisibleBit = 2, - kFolderCreatedNameLocked = 0x00000008, - kFolderCreatedNameLockedBit = 3, - kFolderCreatedAdminPrivs = 0x00000010, - kFolderCreatedAdminPrivsBit = 4 -}; - -enum { - kFolderInUserFolder = 0x00000020, - kFolderInUserFolderBit = 5, - kFolderTrackedByAlias = 0x00000040, - kFolderTrackedByAliasBit = 6, - kFolderInRemoteUserFolderIfAvailable = 0x00000080, - kFolderInRemoteUserFolderIfAvailableBit = 7, - kFolderNeverMatchedInIdentifyFolder = 0x00000100, - kFolderNeverMatchedInIdentifyFolderBit = 8, - kFolderMustStayOnSameVolume = 0x00000200, - kFolderMustStayOnSameVolumeBit = 9, - kFolderManagerFolderInMacOS9FolderIfMacOSXIsInstalledMask = 0x00000400, - kFolderManagerFolderInMacOS9FolderIfMacOSXIsInstalledBit = 10, - kFolderInLocalOrRemoteUserFolder = kFolderInUserFolder | kFolderInRemoteUserFolderIfAvailable, - kFolderManagerNotCreatedOnRemoteVolumesBit = 11, - kFolderManagerNotCreatedOnRemoteVolumesMask = (1 << kFolderManagerNotCreatedOnRemoteVolumesBit), - kFolderManagerNewlyCreatedFolderIsLocalizedBit = 12, - kFolderManagerNewlyCreatedFolderShouldHaveDotLocalizedCreatedWithinMask = (1 << kFolderManagerNewlyCreatedFolderIsLocalizedBit) -}; - -typedef UInt32 FolderDescFlags; - -enum { - kRelativeFolder = 'relf', - kRedirectedRelativeFolder = 'rrel', - kSpecialFolder = 'spcf' -}; - -typedef OSType FolderClass; - -enum { - kBlessedFolder = 'blsf', - kRootFolder = 'rotf' -}; - -enum { - kCurrentUserFolderLocation = 'cusf' -}; - - -enum { - kDictionariesFolderType = 'dict', - kLogsFolderType = 'logs', - kPreferencePanesFolderType = 'ppan' -}; - - -enum { - kWidgetsFolderType = 'wdgt', - kScreenSaversFolderType = 'scrn' -}; - -typedef OSType FolderType; -typedef OSType FolderLocation; - -struct FolderDesc { - Size descSize; - FolderType foldType; - FolderDescFlags flags; - FolderClass foldClass; - FolderType foldLocation; - OSType badgeSignature; - OSType badgeType; - UInt32 reserved; - StrFileName name; -}; -typedef struct FolderDesc FolderDesc; -typedef FolderDesc * FolderDescPtr; - -typedef UInt32 RoutingFlags; -struct FolderRouting { - Size descSize; - OSType fileType; - FolderType routeFromFolder; - FolderType routeToFolder; - RoutingFlags flags; -}; -typedef struct FolderRouting FolderRouting; -typedef FolderRouting * FolderRoutingPtr; -extern OSErr -AddFolderDescriptor( - FolderType foldType, - FolderDescFlags flags, - FolderClass foldClass, - FolderLocation foldLocation, - OSType badgeSignature, - OSType badgeType, - ConstStrFileNameParam name, - Boolean replaceFlag) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetFolderTypes( - UInt32 requestedTypeCount, - UInt32 * totalTypeCount, - FolderType * theTypes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -RemoveFolderDescriptor(FolderType foldType) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -GetFolderNameUnicode( - FSVolumeRefNum vRefNum, - OSType foldType, - FSVolumeRefNum * foundVRefNum, - HFSUniStr255 * name) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern OSErr -InvalidateFolderDescriptorCache( - FSVolumeRefNum vRefNum, - SInt32 dirID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -IdentifyFolder( - FSVolumeRefNum vRefNum, - SInt32 dirID, - FolderType * foldType) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -FSDetermineIfRefIsEnclosedByFolder( - FSVolumeRefNum domainOrVRefNum, - OSType folderType, - const FSRef * inRef, - Boolean * outResult) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -extern OSErr -DetermineIfPathIsEnclosedByFolder( - FSVolumeRefNum domainOrVRefNum, - OSType folderType, - const UInt8 * utf8Path, - Boolean pathIsRealPath, - Boolean * outResult) __attribute__((availability(macosx,introduced=10.4,deprecated=10.8))); -typedef OSStatus ( * FolderManagerNotificationProcPtr)(OSType message, void *arg, void *userRefCon); -typedef FolderManagerNotificationProcPtr FolderManagerNotificationUPP; -extern FolderManagerNotificationUPP -NewFolderManagerNotificationUPP(FolderManagerNotificationProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeFolderManagerNotificationUPP(FolderManagerNotificationUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -InvokeFolderManagerNotificationUPP( - OSType message, - void * arg, - void * userRefCon, - FolderManagerNotificationUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline FolderManagerNotificationUPP NewFolderManagerNotificationUPP(FolderManagerNotificationProcPtr userRoutine) { return userRoutine; } - inline void DisposeFolderManagerNotificationUPP(FolderManagerNotificationUPP) { } - inline OSStatus InvokeFolderManagerNotificationUPP(OSType message, void * arg, void * userRefCon, FolderManagerNotificationUPP userUPP) { return (*userUPP)(message, arg, userRefCon); } -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -extern void -Microseconds(UnsignedWide * microTickCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -enum { - - kTMTaskActive = (1L << 15) -}; - -typedef struct TMTask TMTask; -typedef TMTask * TMTaskPtr; -typedef void ( * TimerProcPtr)(TMTaskPtr tmTaskPtr); -typedef TimerProcPtr TimerUPP; -struct TMTask { - QElemPtr qLink; - short qType; - TimerUPP tmAddr; - long tmCount; - long tmWakeUp; - long tmReserved; -}; -extern void -InsTime(QElemPtr tmTaskPtr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern void -InsXTime(QElemPtr tmTaskPtr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern void -PrimeTime( - QElemPtr tmTaskPtr, - long count) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern void -RmvTime(QElemPtr tmTaskPtr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern OSErr -InstallTimeTask(QElemPtr tmTaskPtr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern OSErr -InstallXTimeTask(QElemPtr tmTaskPtr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern OSErr -PrimeTimeTask( - QElemPtr tmTaskPtr, - long count) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern OSErr -RemoveTimeTask(QElemPtr tmTaskPtr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern TimerUPP -NewTimerUPP(TimerProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeTimerUPP(TimerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeTimerUPP( - TMTaskPtr tmTaskPtr, - TimerUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline TimerUPP NewTimerUPP(TimerProcPtr userRoutine) { return userRoutine; } - inline void DisposeTimerUPP(TimerUPP) { } - inline void InvokeTimerUPP(TMTaskPtr tmTaskPtr, TimerUPP userUPP) { (*userUPP)(tmTaskPtr); } -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma options align=power -extern OSStatus -MPGetNextCpuID( - MPCoherenceID owningCoherenceID, - MPCpuID * cpuID) __attribute__((availability(macosx,introduced=10.4,deprecated=10.7))); -extern OSStatus -MPGetNextTaskID( - MPProcessID owningProcessID, - MPTaskID * taskID) __attribute__((availability(macosx,introduced=10.4,deprecated=10.7))); -enum { - - kMPQueueInfoVersion = 1L | (kOpaqueQueueID << 16), - kMPSemaphoreInfoVersion = 1L | (kOpaqueSemaphoreID << 16), - kMPEventInfoVersion = 1L | (kOpaqueEventID << 16), - kMPCriticalRegionInfoVersion = 1L | (kOpaqueCriticalRegionID << 16), - kMPNotificationInfoVersion = 1L | (kOpaqueNotificationID << 16), - kMPAddressSpaceInfoVersion = 1L | (kOpaqueAddressSpaceID << 16) -}; - - -struct MPQueueInfo { - PBVersion version; - - MPProcessID processID; - OSType queueName; - - ItemCount nWaiting; - MPTaskID waitingTaskID; - - ItemCount nMessages; - ItemCount nReserved; - - void * p1; - void * p2; - void * p3; -}; -typedef struct MPQueueInfo MPQueueInfo; -struct MPSemaphoreInfo { - PBVersion version; - - MPProcessID processID; - OSType semaphoreName; - - ItemCount nWaiting; - MPTaskID waitingTaskID; - - ItemCount maximum; - ItemCount count; -}; -typedef struct MPSemaphoreInfo MPSemaphoreInfo; -struct MPEventInfo { - PBVersion version; - - MPProcessID processID; - OSType eventName; - - ItemCount nWaiting; - MPTaskID waitingTaskID; - - MPEventFlags events; -}; -typedef struct MPEventInfo MPEventInfo; -struct MPCriticalRegionInfo { - PBVersion version; - - MPProcessID processID; - OSType regionName; - - ItemCount nWaiting; - MPTaskID waitingTaskID; - - MPTaskID owningTask; - ItemCount count; -}; -typedef struct MPCriticalRegionInfo MPCriticalRegionInfo; -struct MPNotificationInfo { - PBVersion version; - - MPProcessID processID; - OSType notificationName; - - MPQueueID queueID; - void * p1; - void * p2; - void * p3; - - MPEventID eventID; - MPEventFlags events; - - MPSemaphoreID semaphoreID; -}; -typedef struct MPNotificationInfo MPNotificationInfo; -struct MPAddressSpaceInfo { - PBVersion version; - - MPProcessID processID; - MPCoherenceID groupID; - ItemCount nTasks; - UInt32 vsid[16]; -}; -typedef struct MPAddressSpaceInfo MPAddressSpaceInfo; -#pragma options align=reset - - -} -extern "C" { - - -#pragma pack(push, 2) -extern SInt16 LMGetBootDrive(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void LMSetBootDrive(SInt16 value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt16 LMGetApFontID(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern void LMSetApFontID(SInt16 value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern SInt16 LMGetSysMap(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void LMSetSysMap(SInt16 value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt8 LMGetResLoad(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void LMSetResLoad(UInt8 value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SInt16 LMGetResErr(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void LMSetResErr(SInt16 value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern UInt8 LMGetTmpResLoad(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void LMSetTmpResLoad(UInt8 value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern Ptr LMGetIntlSpec(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void LMSetIntlSpec(Ptr value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void LMSetSysFontFam(SInt16 value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern SInt16 LMGetSysFontSize(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.4))); -extern void LMSetSysFontSize(SInt16 value) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - - - - - - - - -typedef UInt16 AVLVisitStage; -enum { - - - - - kAVLPreOrder = 0, - - - - - - kAVLInOrder = 1, - - - - - kAVLPostOrder = 2 -}; -typedef UInt16 AVLOrder; -enum { - - - - - kLeftToRight = 0, - - - - - kRightToLeft = 1 -}; -typedef UInt16 AVLNodeType; -enum { - kAVLIsTree = 0, - kAVLIsLeftBranch = 1, - kAVLIsRightBranch = 2, - kAVLIsLeaf = 3, - kAVLNullNode = 4 -}; - -enum { - errItemAlreadyInTree = -960, - errNotValidTree = -961, - errItemNotFoundInTree = -962, - errCanNotInsertWhileWalkProcInProgress = -963, - errTreeIsLocked = -964 -}; -struct AVLTreeStruct { - OSType signature; - unsigned long privateStuff[8]; -}; -typedef struct AVLTreeStruct AVLTreeStruct; -typedef AVLTreeStruct * AVLTreePtr; -typedef SInt32 ( * AVLCompareItemsProcPtr)(AVLTreePtr tree, const void *i1, const void *i2, AVLNodeType nd_typ); -typedef ByteCount ( * AVLItemSizeProcPtr)(AVLTreePtr tree, const void *itemPtr); -typedef void ( * AVLDisposeItemProcPtr)(AVLTreePtr tree, const void *dataP); -typedef OSErr ( * AVLWalkProcPtr)(AVLTreePtr tree, const void *dataPtr, AVLVisitStage visitStage, AVLNodeType node, UInt32 level, SInt32 balance, void *refCon); -typedef AVLCompareItemsProcPtr AVLCompareItemsUPP; -typedef AVLItemSizeProcPtr AVLItemSizeUPP; -typedef AVLDisposeItemProcPtr AVLDisposeItemUPP; -typedef AVLWalkProcPtr AVLWalkUPP; -extern AVLCompareItemsUPP -NewAVLCompareItemsUPP(AVLCompareItemsProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern AVLItemSizeUPP -NewAVLItemSizeUPP(AVLItemSizeProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern AVLDisposeItemUPP -NewAVLDisposeItemUPP(AVLDisposeItemProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern AVLWalkUPP -NewAVLWalkUPP(AVLWalkProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern void -DisposeAVLCompareItemsUPP(AVLCompareItemsUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern void -DisposeAVLItemSizeUPP(AVLItemSizeUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern void -DisposeAVLDisposeItemUPP(AVLDisposeItemUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern void -DisposeAVLWalkUPP(AVLWalkUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern SInt32 -InvokeAVLCompareItemsUPP( - AVLTreePtr tree, - const void * i1, - const void * i2, - AVLNodeType nd_typ, - AVLCompareItemsUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern ByteCount -InvokeAVLItemSizeUPP( - AVLTreePtr tree, - const void * itemPtr, - AVLItemSizeUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern void -InvokeAVLDisposeItemUPP( - AVLTreePtr tree, - const void * dataP, - AVLDisposeItemUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern OSErr -InvokeAVLWalkUPP( - AVLTreePtr tree, - const void * dataPtr, - AVLVisitStage visitStage, - AVLNodeType node, - UInt32 level, - SInt32 balance, - void * refCon, - AVLWalkUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); - - - - inline AVLCompareItemsUPP NewAVLCompareItemsUPP(AVLCompareItemsProcPtr userRoutine) { return userRoutine; } - inline AVLItemSizeUPP NewAVLItemSizeUPP(AVLItemSizeProcPtr userRoutine) { return userRoutine; } - inline AVLDisposeItemUPP NewAVLDisposeItemUPP(AVLDisposeItemProcPtr userRoutine) { return userRoutine; } - inline AVLWalkUPP NewAVLWalkUPP(AVLWalkProcPtr userRoutine) { return userRoutine; } - inline void DisposeAVLCompareItemsUPP(AVLCompareItemsUPP) { } - inline void DisposeAVLItemSizeUPP(AVLItemSizeUPP) { } - inline void DisposeAVLDisposeItemUPP(AVLDisposeItemUPP) { } - inline void DisposeAVLWalkUPP(AVLWalkUPP) { } - inline SInt32 InvokeAVLCompareItemsUPP(AVLTreePtr tree, const void * i1, const void * i2, AVLNodeType nd_typ, AVLCompareItemsUPP userUPP) { return (*userUPP)(tree, i1, i2, nd_typ); } - inline ByteCount InvokeAVLItemSizeUPP(AVLTreePtr tree, const void * itemPtr, AVLItemSizeUPP userUPP) { return (*userUPP)(tree, itemPtr); } - inline void InvokeAVLDisposeItemUPP(AVLTreePtr tree, const void * dataP, AVLDisposeItemUPP userUPP) { (*userUPP)(tree, dataP); } - inline OSErr InvokeAVLWalkUPP(AVLTreePtr tree, const void * dataPtr, AVLVisitStage visitStage, AVLNodeType node, UInt32 level, SInt32 balance, void * refCon, AVLWalkUPP userUPP) { return (*userUPP)(tree, dataPtr, visitStage, node, level, balance, refCon); } -#pragma pack(pop) - - -} - - - -#pragma pack(push, 2) -struct PEFContainerHeader { - OSType tag1; - OSType tag2; - OSType architecture; - UInt32 formatVersion; - UInt32 dateTimeStamp; - UInt32 oldDefVersion; - UInt32 oldImpVersion; - UInt32 currentVersion; - UInt16 sectionCount; - UInt16 instSectionCount; - UInt32 reservedA; -}; -typedef struct PEFContainerHeader PEFContainerHeader; -enum { - kPEFTag1 = 'Joy!', - kPEFTag2 = 'peff', - kPEFVersion = 0x00000001 -}; - - -enum { - kPEFFirstSectionHeaderOffset = sizeof(PEFContainerHeader) -}; -struct PEFSectionHeader { - SInt32 nameOffset; - UInt32 defaultAddress; - UInt32 totalLength; - UInt32 unpackedLength; - UInt32 containerLength; - UInt32 containerOffset; - UInt8 sectionKind; - UInt8 shareKind; - UInt8 alignment; - UInt8 reservedA; -}; -typedef struct PEFSectionHeader PEFSectionHeader; -enum { - - - kPEFCodeSection = 0, - kPEFUnpackedDataSection = 1, - kPEFPackedDataSection = 2, - kPEFConstantSection = 3, - kPEFExecDataSection = 6, - - kPEFLoaderSection = 4, - kPEFDebugSection = 5, - kPEFExceptionSection = 7, - kPEFTracebackSection = 8 -}; - - -enum { - - kPEFProcessShare = 1, - kPEFGlobalShare = 4, - kPEFProtectedShare = 5 -}; -enum { - - kPEFPkDataZero = 0, - kPEFPkDataBlock = 1, - kPEFPkDataRepeat = 2, - kPEFPkDataRepeatBlock = 3, - kPEFPkDataRepeatZero = 4 -}; - - -enum { - kPEFPkDataOpcodeShift = 5, - kPEFPkDataCount5Mask = 0x1F, - kPEFPkDataMaxCount5 = 31, - kPEFPkDataVCountShift = 7, - kPEFPkDataVCountMask = 0x7F, - kPEFPkDataVCountEndMask = 0x80 -}; -struct PEFLoaderInfoHeader { - SInt32 mainSection; - UInt32 mainOffset; - SInt32 initSection; - UInt32 initOffset; - SInt32 termSection; - UInt32 termOffset; - UInt32 importedLibraryCount; - UInt32 totalImportedSymbolCount; - UInt32 relocSectionCount; - UInt32 relocInstrOffset; - UInt32 loaderStringsOffset; - UInt32 exportHashOffset; - UInt32 exportHashTablePower; - UInt32 exportedSymbolCount; -}; -typedef struct PEFLoaderInfoHeader PEFLoaderInfoHeader; - - - - - - - -struct PEFImportedLibrary { - UInt32 nameOffset; - UInt32 oldImpVersion; - UInt32 currentVersion; - UInt32 importedSymbolCount; - UInt32 firstImportedSymbol; - UInt8 options; - UInt8 reservedA; - UInt16 reservedB; -}; -typedef struct PEFImportedLibrary PEFImportedLibrary; -enum { - - kPEFWeakImportLibMask = 0x40, - kPEFInitLibBeforeMask = 0x80 -}; -struct PEFImportedSymbol { - UInt32 classAndName; -}; -typedef struct PEFImportedSymbol PEFImportedSymbol; -enum { - kPEFImpSymClassShift = 24, - kPEFImpSymNameOffsetMask = 0x00FFFFFF, - kPEFImpSymMaxNameOffset = 0x00FFFFFF -}; - - - - - - - -enum { - - kPEFCodeSymbol = 0x00, - kPEFDataSymbol = 0x01, - kPEFTVectorSymbol = 0x02, - kPEFTOCSymbol = 0x03, - kPEFGlueSymbol = 0x04, - kPEFUndefinedSymbol = 0x0F, - kPEFWeakImportSymMask = 0x80 -}; -struct PEFExportedSymbolHashSlot { - UInt32 countAndStart; -}; -typedef struct PEFExportedSymbolHashSlot PEFExportedSymbolHashSlot; -enum { - kPEFHashSlotSymCountShift = 18, - kPEFHashSlotFirstKeyMask = 0x0003FFFF, - kPEFHashSlotMaxSymbolCount = 0x00003FFF, - kPEFHashSlotMaxKeyIndex = 0x0003FFFF -}; -struct PEFSplitHashWord { - UInt16 nameLength; - UInt16 hashValue; -}; -typedef struct PEFSplitHashWord PEFSplitHashWord; -struct PEFExportedSymbolKey { - union { - UInt32 fullHashWord; - PEFSplitHashWord splitHashWord; - } u; -}; -typedef struct PEFExportedSymbolKey PEFExportedSymbolKey; -enum { - kPEFHashLengthShift = 16, - kPEFHashValueMask = 0x0000FFFF, - kPEFHashMaxLength = 0x0000FFFF -}; -struct PEFExportedSymbol { - UInt32 classAndName; - UInt32 symbolValue; - SInt16 sectionIndex; -}; -typedef struct PEFExportedSymbol PEFExportedSymbol; -enum { - kPEFExpSymClassShift = 24, - kPEFExpSymNameOffsetMask = 0x00FFFFFF, - kPEFExpSymMaxNameOffset = 0x00FFFFFF -}; - - - - - - - -enum { - - kPEFAbsoluteExport = -2, - kPEFReexportedImport = -3 -}; -typedef UInt16 PEFRelocChunk; -struct PEFLoaderRelocationHeader { - UInt16 sectionIndex; - UInt16 reservedA; - UInt32 relocCount; - UInt32 firstRelocOffset; -}; -typedef struct PEFLoaderRelocationHeader PEFLoaderRelocationHeader; -enum { - kPEFRelocBasicOpcodeRange = 128 -}; -enum { - kPEFRelocBySectDWithSkip = 0x00, - kPEFRelocBySectC = 0x20, - kPEFRelocBySectD = 0x21, - kPEFRelocTVector12 = 0x22, - kPEFRelocTVector8 = 0x23, - kPEFRelocVTable8 = 0x24, - kPEFRelocImportRun = 0x25, - kPEFRelocSmByImport = 0x30, - kPEFRelocSmSetSectC = 0x31, - kPEFRelocSmSetSectD = 0x32, - kPEFRelocSmBySection = 0x33, - kPEFRelocIncrPosition = 0x40, - kPEFRelocSmRepeat = 0x48, - kPEFRelocSetPosition = 0x50, - kPEFRelocLgByImport = 0x52, - kPEFRelocLgRepeat = 0x58, - kPEFRelocLgSetOrBySection = 0x5A, - kPEFRelocUndefinedOpcode = 0xFF -}; -enum { - kPEFRelocLgBySectionSubopcode = 0x00, - kPEFRelocLgSetSectCSubopcode = 0x01, - kPEFRelocLgSetSectDSubopcode = 0x02 -}; -enum { - kPEFRelocWithSkipMaxSkipCount = 255, - kPEFRelocWithSkipMaxRelocCount = 63 -}; -enum { - kPEFRelocRunMaxRunLength = 512 -}; -enum { - kPEFRelocSmIndexMaxIndex = 511 -}; -enum { - kPEFRelocIncrPositionMaxOffset = 4096 -}; -enum { - kPEFRelocSmRepeatMaxChunkCount = 16, - kPEFRelocSmRepeatMaxRepeatCount = 256 -}; -enum { - kPEFRelocSetPosMaxOffset = 0x03FFFFFF -}; -enum { - kPEFRelocLgByImportMaxIndex = 0x03FFFFFF -}; -enum { - kPEFRelocLgRepeatMaxChunkCount = 16, - kPEFRelocLgRepeatMaxRepeatCount = 0x003FFFFF -}; -enum { - kPEFRelocLgSetOrBySectionMaxIndex = 0x003FFFFF -}; -struct XLibContainerHeader { - - - - OSType tag1; - OSType tag2; - UInt32 currentFormat; - UInt32 containerStringsOffset; - UInt32 exportHashOffset; - UInt32 exportKeyOffset; - UInt32 exportSymbolOffset; - UInt32 exportNamesOffset; - UInt32 exportHashTablePower; - UInt32 exportedSymbolCount; - - - - UInt32 fragNameOffset; - UInt32 fragNameLength; - UInt32 dylibPathOffset; - UInt32 dylibPathLength; - OSType cpuFamily; - OSType cpuModel; - UInt32 dateTimeStamp; - UInt32 currentVersion; - UInt32 oldDefVersion; - UInt32 oldImpVersion; - -}; -typedef struct XLibContainerHeader XLibContainerHeader; -enum { - kXLibTag1 = (int)0xF04D6163 , - kVLibTag2 = 'VLib', - kBLibTag2 = 'BLib', - kXLibVersion = 0x00000001 -}; - - - -typedef PEFExportedSymbolHashSlot XLibExportedSymbolHashSlot; -typedef PEFExportedSymbolKey XLibExportedSymbolKey; -struct XLibExportedSymbol { - UInt32 classAndName; - UInt32 bpOffset; -}; -typedef struct XLibExportedSymbol XLibExportedSymbol; -#pragma pack(pop) - - - -extern "C" { - - - - - -enum { - kHFSSigWord = 0x4244, - kHFSPlusSigWord = 0x482B, - kHFSXSigWord = 0x4858, - - kHFSPlusVersion = 0x0004, - kHFSXVersion = 0x0005, - - kHFSPlusMountVersion = 0x31302E30, - kHFSJMountVersion = 0x4846534a, - kFSKMountVersion = 0x46534b21 -}; -enum { - kHardLinkFileType = 0x686C6E6B, - kHFSPlusCreator = 0x6866732B -}; - - - - - -enum { - kSymLinkFileType = 0x736C6E6B, - kSymLinkCreator = 0x72686170 -}; - - -enum { - kHFSMaxVolumeNameChars = 27, - kHFSMaxFileNameChars = 31, - kHFSPlusMaxFileNameChars = 255 -}; - - - - - -struct HFSExtentKey { - u_int8_t keyLength; - u_int8_t forkType; - u_int32_t fileID; - u_int16_t startBlock; -} __attribute__((aligned(2), packed)); -typedef struct HFSExtentKey HFSExtentKey; - - -struct HFSPlusExtentKey { - u_int16_t keyLength; - u_int8_t forkType; - u_int8_t pad; - u_int32_t fileID; - u_int32_t startBlock; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusExtentKey HFSPlusExtentKey; - - -enum { - kHFSExtentDensity = 3, - kHFSPlusExtentDensity = 8 -}; - - -struct HFSExtentDescriptor { - u_int16_t startBlock; - u_int16_t blockCount; -} __attribute__((aligned(2), packed)); -typedef struct HFSExtentDescriptor HFSExtentDescriptor; - - -struct HFSPlusExtentDescriptor { - u_int32_t startBlock; - u_int32_t blockCount; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusExtentDescriptor HFSPlusExtentDescriptor; - - -typedef HFSExtentDescriptor HFSExtentRecord[3]; - - -typedef HFSPlusExtentDescriptor HFSPlusExtentRecord[8]; - - - -struct FndrFileInfo { - u_int32_t fdType; - u_int32_t fdCreator; - u_int16_t fdFlags; - struct { - int16_t v; - int16_t h; - } fdLocation; - int16_t opaque; -} __attribute__((aligned(2), packed)); -typedef struct FndrFileInfo FndrFileInfo; - -struct FndrDirInfo { - struct { - int16_t top; - int16_t left; - int16_t bottom; - int16_t right; - } frRect; - unsigned short frFlags; - struct { - u_int16_t v; - u_int16_t h; - } frLocation; - int16_t opaque; -} __attribute__((aligned(2), packed)); -typedef struct FndrDirInfo FndrDirInfo; - -struct FndrOpaqueInfo { - int8_t opaque[16]; -} __attribute__((aligned(2), packed)); -typedef struct FndrOpaqueInfo FndrOpaqueInfo; - -struct FndrExtendedDirInfo { - u_int32_t document_id; - u_int32_t date_added; - u_int16_t extended_flags; - u_int16_t reserved3; - u_int32_t write_gen_counter; -} __attribute__((aligned(2), packed)); - -struct FndrExtendedFileInfo { - u_int32_t document_id; - u_int32_t date_added; - u_int16_t extended_flags; - u_int16_t reserved2; - u_int32_t write_gen_counter; -} __attribute__((aligned(2), packed)); - - -struct HFSPlusForkData { - u_int64_t logicalSize; - u_int32_t clumpSize; - u_int32_t totalBlocks; - HFSPlusExtentRecord extents; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusForkData HFSPlusForkData; - - - - - - - -struct HFSPlusBSDInfo { - u_int32_t ownerID; - u_int32_t groupID; - u_int8_t adminFlags; - u_int8_t ownerFlags; - u_int16_t fileMode; - union { - u_int32_t iNodeNum; - u_int32_t linkCount; - u_int32_t rawDevice; - } special; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusBSDInfo HFSPlusBSDInfo; -enum { - kHFSRootParentID = 1, - kHFSRootFolderID = 2, - kHFSExtentsFileID = 3, - kHFSCatalogFileID = 4, - kHFSBadBlockFileID = 5, - kHFSAllocationFileID = 6, - kHFSStartupFileID = 7, - kHFSAttributesFileID = 8, - kHFSAttributeDataFileID = 13, - - kHFSRepairCatalogFileID = 14, - kHFSBogusExtentFileID = 15, - kHFSFirstUserCatalogNodeID = 16 -}; - - -struct HFSCatalogKey { - u_int8_t keyLength; - u_int8_t reserved; - u_int32_t parentID; - u_int8_t nodeName[kHFSMaxFileNameChars + 1]; -} __attribute__((aligned(2), packed)); -typedef struct HFSCatalogKey HFSCatalogKey; - - -struct HFSPlusCatalogKey { - u_int16_t keyLength; - u_int32_t parentID; - HFSUniStr255 nodeName; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusCatalogKey HFSPlusCatalogKey; - - -enum { - - kHFSFolderRecord = 0x0100, - kHFSFileRecord = 0x0200, - kHFSFolderThreadRecord = 0x0300, - kHFSFileThreadRecord = 0x0400, - - - kHFSPlusFolderRecord = 1, - kHFSPlusFileRecord = 2, - kHFSPlusFolderThreadRecord = 3, - kHFSPlusFileThreadRecord = 4 -}; - - - -enum { - kHFSFileLockedBit = 0x0000, - kHFSFileLockedMask = 0x0001, - - kHFSThreadExistsBit = 0x0001, - kHFSThreadExistsMask = 0x0002, - - kHFSHasAttributesBit = 0x0002, - kHFSHasAttributesMask = 0x0004, - - kHFSHasSecurityBit = 0x0003, - kHFSHasSecurityMask = 0x0008, - - kHFSHasFolderCountBit = 0x0004, - kHFSHasFolderCountMask = 0x0010, - - kHFSHasLinkChainBit = 0x0005, - kHFSHasLinkChainMask = 0x0020, - - kHFSHasChildLinkBit = 0x0006, - kHFSHasChildLinkMask = 0x0040, - - kHFSHasDateAddedBit = 0x0007, - kHFSHasDateAddedMask = 0x0080, - - kHFSFastDevPinnedBit = 0x0008, - kHFSFastDevPinnedMask = 0x0100, - - kHFSDoNotFastDevPinBit = 0x0009, - kHFSDoNotFastDevPinMask = 0x0200, - - kHFSFastDevCandidateBit = 0x000a, - kHFSFastDevCandidateMask = 0x0400, - - kHFSAutoCandidateBit = 0x000b, - kHFSAutoCandidateMask = 0x0800 - - - -}; - - - -struct HFSCatalogFolder { - int16_t recordType; - u_int16_t flags; - u_int16_t valence; - u_int32_t folderID; - u_int32_t createDate; - u_int32_t modifyDate; - u_int32_t backupDate; - FndrDirInfo userInfo; - FndrOpaqueInfo finderInfo; - u_int32_t reserved[4]; -} __attribute__((aligned(2), packed)); -typedef struct HFSCatalogFolder HFSCatalogFolder; - - -struct HFSPlusCatalogFolder { - int16_t recordType; - u_int16_t flags; - u_int32_t valence; - u_int32_t folderID; - u_int32_t createDate; - u_int32_t contentModDate; - u_int32_t attributeModDate; - u_int32_t accessDate; - u_int32_t backupDate; - HFSPlusBSDInfo bsdInfo; - FndrDirInfo userInfo; - FndrOpaqueInfo finderInfo; - u_int32_t textEncoding; - u_int32_t folderCount; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusCatalogFolder HFSPlusCatalogFolder; - - -struct HFSCatalogFile { - int16_t recordType; - u_int8_t flags; - int8_t fileType; - FndrFileInfo userInfo; - u_int32_t fileID; - u_int16_t dataStartBlock; - int32_t dataLogicalSize; - int32_t dataPhysicalSize; - u_int16_t rsrcStartBlock; - int32_t rsrcLogicalSize; - int32_t rsrcPhysicalSize; - u_int32_t createDate; - u_int32_t modifyDate; - u_int32_t backupDate; - FndrOpaqueInfo finderInfo; - u_int16_t clumpSize; - HFSExtentRecord dataExtents; - HFSExtentRecord rsrcExtents; - u_int32_t reserved; -} __attribute__((aligned(2), packed)); -typedef struct HFSCatalogFile HFSCatalogFile; - - -struct HFSPlusCatalogFile { - int16_t recordType; - u_int16_t flags; - u_int32_t reserved1; - u_int32_t fileID; - u_int32_t createDate; - u_int32_t contentModDate; - u_int32_t attributeModDate; - u_int32_t accessDate; - u_int32_t backupDate; - HFSPlusBSDInfo bsdInfo; - FndrFileInfo userInfo; - FndrOpaqueInfo finderInfo; - u_int32_t textEncoding; - u_int32_t reserved2; - - - HFSPlusForkData dataFork; - HFSPlusForkData resourceFork; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusCatalogFile HFSPlusCatalogFile; - - -struct HFSCatalogThread { - int16_t recordType; - int32_t reserved[2]; - u_int32_t parentID; - u_int8_t nodeName[kHFSMaxFileNameChars + 1]; -} __attribute__((aligned(2), packed)); -typedef struct HFSCatalogThread HFSCatalogThread; - - -struct HFSPlusCatalogThread { - int16_t recordType; - int16_t reserved; - u_int32_t parentID; - HFSUniStr255 nodeName; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusCatalogThread HFSPlusCatalogThread; - - - - - - -enum { - kHFSPlusAttrInlineData = 0x10, - kHFSPlusAttrForkData = 0x20, - kHFSPlusAttrExtents = 0x30 -}; -struct HFSPlusAttrForkData { - u_int32_t recordType; - u_int32_t reserved; - HFSPlusForkData theFork; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusAttrForkData HFSPlusAttrForkData; - - - - - - -struct HFSPlusAttrExtents { - u_int32_t recordType; - u_int32_t reserved; - HFSPlusExtentRecord extents; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusAttrExtents HFSPlusAttrExtents; - - - - - - - -struct HFSPlusAttrData { - u_int32_t recordType; - u_int32_t reserved[2]; - u_int32_t attrSize; - u_int8_t attrData[2]; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusAttrData HFSPlusAttrData; - - - -struct HFSPlusAttrInlineData { - u_int32_t recordType; - u_int32_t reserved; - u_int32_t logicalSize; - u_int8_t userData[2]; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusAttrInlineData HFSPlusAttrInlineData; - - - -union HFSPlusAttrRecord { - u_int32_t recordType; - HFSPlusAttrInlineData inlineData; - HFSPlusAttrData attrData; - HFSPlusAttrForkData forkData; - HFSPlusAttrExtents overflowExtents; -}; -typedef union HFSPlusAttrRecord HFSPlusAttrRecord; - - -enum { kHFSMaxAttrNameLen = 127 }; -struct HFSPlusAttrKey { - u_int16_t keyLength; - u_int16_t pad; - u_int32_t fileID; - u_int32_t startBlock; - u_int16_t attrNameLen; - u_int16_t attrName[kHFSMaxAttrNameLen]; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusAttrKey HFSPlusAttrKey; -enum { - kHFSPlusExtentKeyMaximumLength = sizeof(HFSPlusExtentKey) - sizeof(u_int16_t), - kHFSExtentKeyMaximumLength = sizeof(HFSExtentKey) - sizeof(u_int8_t), - kHFSPlusCatalogKeyMaximumLength = sizeof(HFSPlusCatalogKey) - sizeof(u_int16_t), - kHFSPlusCatalogKeyMinimumLength = kHFSPlusCatalogKeyMaximumLength - sizeof(HFSUniStr255) + sizeof(u_int16_t), - kHFSCatalogKeyMaximumLength = sizeof(HFSCatalogKey) - sizeof(u_int8_t), - kHFSCatalogKeyMinimumLength = kHFSCatalogKeyMaximumLength - (kHFSMaxFileNameChars + 1) + sizeof(u_int8_t), - kHFSPlusCatalogMinNodeSize = 4096, - kHFSPlusExtentMinNodeSize = 512, - kHFSPlusAttrMinNodeSize = 4096 -}; - - -enum { - - kHFSVolumeHardwareLockBit = 7, - kHFSVolumeUnmountedBit = 8, - kHFSVolumeSparedBlocksBit = 9, - kHFSVolumeNoCacheRequiredBit = 10, - kHFSBootVolumeInconsistentBit = 11, - kHFSCatalogNodeIDsReusedBit = 12, - kHFSVolumeJournaledBit = 13, - kHFSVolumeInconsistentBit = 14, - kHFSVolumeSoftwareLockBit = 15, - - - - - kHFSUnusedNodeFixBit = 31, - kHFSContentProtectionBit = 30, - - - kHFSVolumeHardwareLockMask = 0x00000080, - kHFSVolumeUnmountedMask = 0x00000100, - kHFSVolumeSparedBlocksMask = 0x00000200, - kHFSVolumeNoCacheRequiredMask = 0x00000400, - kHFSBootVolumeInconsistentMask = 0x00000800, - kHFSCatalogNodeIDsReusedMask = 0x00001000, - kHFSVolumeJournaledMask = 0x00002000, - kHFSVolumeInconsistentMask = 0x00004000, - kHFSVolumeSoftwareLockMask = 0x00008000, - - - - kHFSContentProtectionMask = 0x40000000, - kHFSUnusedNodeFixMask = 0x80000000, - - kHFSMDBAttributesMask = 0x8380 -}; - -enum { - kHFSUnusedNodesFixDate = 0xc5ef2480 -}; - - - -struct HFSMasterDirectoryBlock { - u_int16_t drSigWord; - u_int32_t drCrDate; - u_int32_t drLsMod; - u_int16_t drAtrb; - u_int16_t drNmFls; - u_int16_t drVBMSt; - u_int16_t drAllocPtr; - u_int16_t drNmAlBlks; - u_int32_t drAlBlkSiz; - u_int32_t drClpSiz; - u_int16_t drAlBlSt; - u_int32_t drNxtCNID; - u_int16_t drFreeBks; - u_int8_t drVN[kHFSMaxVolumeNameChars + 1]; - u_int32_t drVolBkUp; - u_int16_t drVSeqNum; - u_int32_t drWrCnt; - u_int32_t drXTClpSiz; - u_int32_t drCTClpSiz; - u_int16_t drNmRtDirs; - u_int32_t drFilCnt; - u_int32_t drDirCnt; - u_int32_t drFndrInfo[8]; - u_int16_t drEmbedSigWord; - HFSExtentDescriptor drEmbedExtent; - u_int32_t drXTFlSize; - HFSExtentRecord drXTExtRec; - u_int32_t drCTFlSize; - HFSExtentRecord drCTExtRec; -} __attribute__((aligned(2), packed)); -typedef struct HFSMasterDirectoryBlock HFSMasterDirectoryBlock; -struct HFSPlusVolumeHeader { - u_int16_t signature; - u_int16_t version; - u_int32_t attributes; - u_int32_t lastMountedVersion; - u_int32_t journalInfoBlock; - - u_int32_t createDate; - u_int32_t modifyDate; - u_int32_t backupDate; - u_int32_t checkedDate; - - u_int32_t fileCount; - u_int32_t folderCount; - - u_int32_t blockSize; - u_int32_t totalBlocks; - u_int32_t freeBlocks; - - u_int32_t nextAllocation; - u_int32_t rsrcClumpSize; - u_int32_t dataClumpSize; - u_int32_t nextCatalogID; - - u_int32_t writeCount; - u_int64_t encodingsBitmap; - - u_int8_t finderInfo[32]; - - HFSPlusForkData allocationFile; - HFSPlusForkData extentsFile; - HFSPlusForkData catalogFile; - HFSPlusForkData attributesFile; - HFSPlusForkData startupFile; -} __attribute__((aligned(2), packed)); -typedef struct HFSPlusVolumeHeader HFSPlusVolumeHeader; - - - - -enum BTreeKeyLimits{ - kMaxKeyLength = 520 -}; - -union BTreeKey{ - u_int8_t length8; - u_int16_t length16; - u_int8_t rawData [kMaxKeyLength+2]; -}; -typedef union BTreeKey BTreeKey; - - -struct BTNodeDescriptor { - u_int32_t fLink; - u_int32_t bLink; - int8_t kind; - u_int8_t height; - u_int16_t numRecords; - u_int16_t reserved; -} __attribute__((aligned(2), packed)); -typedef struct BTNodeDescriptor BTNodeDescriptor; - - -enum { - kBTLeafNode = -1, - kBTIndexNode = 0, - kBTHeaderNode = 1, - kBTMapNode = 2 -}; - - -struct BTHeaderRec { - u_int16_t treeDepth; - u_int32_t rootNode; - u_int32_t leafRecords; - u_int32_t firstLeafNode; - u_int32_t lastLeafNode; - u_int16_t nodeSize; - u_int16_t maxKeyLength; - u_int32_t totalNodes; - u_int32_t freeNodes; - u_int16_t reserved1; - u_int32_t clumpSize; - u_int8_t btreeType; - u_int8_t keyCompareType; - u_int32_t attributes; - u_int32_t reserved3[16]; -} __attribute__((aligned(2), packed)); -typedef struct BTHeaderRec BTHeaderRec; - - -enum { - kBTBadCloseMask = 0x00000001, - kBTBigKeysMask = 0x00000002, - kBTVariableIndexKeysMask = 0x00000004 -}; - - - -enum { - kHFSCaseFolding = 0xCF, - kHFSBinaryCompare = 0xBC -}; - - -typedef __darwin_uuid_string_t uuid_string_t; - - - - - - -extern "C" { - - -void uuid_clear(uuid_t uu); - -int uuid_compare(const uuid_t uu1, const uuid_t uu2); - -void uuid_copy(uuid_t dst, const uuid_t src); - -void uuid_generate(uuid_t out); -void uuid_generate_random(uuid_t out); -void uuid_generate_time(uuid_t out); - -int uuid_is_null(const uuid_t uu); - -int uuid_parse(const uuid_string_t in, uuid_t uu); - -void uuid_unparse(const uuid_t uu, uuid_string_t out); -void uuid_unparse_lower(const uuid_t uu, uuid_string_t out); -void uuid_unparse_upper(const uuid_t uu, uuid_string_t out); - - -} -struct JournalInfoBlock { - u_int32_t flags; - u_int32_t device_signature[8]; - u_int64_t offset; - u_int64_t size; - uuid_string_t ext_jnl_uuid; - char machine_serial_num[48]; - char reserved[((32*sizeof(u_int32_t)) - sizeof(uuid_string_t) - 48)]; -} __attribute__((aligned(2), packed)); -typedef struct JournalInfoBlock JournalInfoBlock; - -enum { - kJIJournalInFSMask = 0x00000001, - kJIJournalOnOtherDeviceMask = 0x00000002, - kJIJournalNeedInitMask = 0x00000004 -}; -} - - - - - - - - -typedef UInt32 HFSCatalogNodeID; - - - -#pragma pack(push, 2) - -enum { - AIFFID = 'AIFF', - AIFCID = 'AIFC', - FormatVersionID = 'FVER', - CommonID = 'COMM', - FORMID = 'FORM', - SoundDataID = 'SSND', - MarkerID = 'MARK', - InstrumentID = 'INST', - MIDIDataID = 'MIDI', - AudioRecordingID = 'AESD', - ApplicationSpecificID = 'APPL', - CommentID = 'COMT', - NameID = 'NAME', - AuthorID = 'AUTH', - CopyrightID = '(c) ', - AnnotationID = 'ANNO' -}; - -enum { - NoLooping = 0, - ForwardLooping = 1, - ForwardBackwardLooping = 2 -}; - - -enum { - - AIFCVersion1 = (uint32_t)0xA2805140 -}; - - - - - - - -enum { - - NoneType = 'NONE', - ACE2Type = 'ACE2', - ACE8Type = 'ACE8', - MACE3Type = 'MAC3', - MACE6Type = 'MAC6' -}; -typedef SInt16 MarkerIdType; -struct ChunkHeader { - UInt32 ckID; - SInt32 ckSize; -}; -typedef struct ChunkHeader ChunkHeader; -struct ContainerChunk { - UInt32 ckID; - SInt32 ckSize; - UInt32 formType; -}; -typedef struct ContainerChunk ContainerChunk; -struct FormatVersionChunk { - UInt32 ckID; - SInt32 ckSize; - UInt32 timestamp; -}; -typedef struct FormatVersionChunk FormatVersionChunk; -typedef FormatVersionChunk * FormatVersionChunkPtr; -struct CommonChunk { - UInt32 ckID; - SInt32 ckSize; - SInt16 numChannels; - UInt32 numSampleFrames; - SInt16 sampleSize; - extended80 sampleRate; -}; -typedef struct CommonChunk CommonChunk; -typedef CommonChunk * CommonChunkPtr; -struct ExtCommonChunk { - UInt32 ckID; - SInt32 ckSize; - SInt16 numChannels; - UInt32 numSampleFrames; - SInt16 sampleSize; - extended80 sampleRate; - UInt32 compressionType; - char compressionName[1]; -}; -typedef struct ExtCommonChunk ExtCommonChunk; -typedef ExtCommonChunk * ExtCommonChunkPtr; -struct SoundDataChunk { - UInt32 ckID; - SInt32 ckSize; - UInt32 offset; - UInt32 blockSize; -}; -typedef struct SoundDataChunk SoundDataChunk; -typedef SoundDataChunk * SoundDataChunkPtr; -struct Marker { - MarkerIdType id; - UInt32 position; - Str255 markerName; -}; -typedef struct Marker Marker; -struct MarkerChunk { - UInt32 ckID; - SInt32 ckSize; - UInt16 numMarkers; - Marker Markers[1]; -}; -typedef struct MarkerChunk MarkerChunk; -typedef MarkerChunk * MarkerChunkPtr; -struct AIFFLoop { - SInt16 playMode; - MarkerIdType beginLoop; - MarkerIdType endLoop; -}; -typedef struct AIFFLoop AIFFLoop; -struct InstrumentChunk { - UInt32 ckID; - SInt32 ckSize; - UInt8 baseFrequency; - UInt8 detune; - UInt8 lowFrequency; - UInt8 highFrequency; - UInt8 lowVelocity; - UInt8 highVelocity; - SInt16 gain; - AIFFLoop sustainLoop; - AIFFLoop releaseLoop; -}; -typedef struct InstrumentChunk InstrumentChunk; -typedef InstrumentChunk * InstrumentChunkPtr; -struct MIDIDataChunk { - UInt32 ckID; - SInt32 ckSize; - UInt8 MIDIdata[1]; -}; -typedef struct MIDIDataChunk MIDIDataChunk; -typedef MIDIDataChunk * MIDIDataChunkPtr; -struct AudioRecordingChunk { - UInt32 ckID; - SInt32 ckSize; - UInt8 AESChannelStatus[24]; -}; -typedef struct AudioRecordingChunk AudioRecordingChunk; -typedef AudioRecordingChunk * AudioRecordingChunkPtr; -struct ApplicationSpecificChunk { - UInt32 ckID; - SInt32 ckSize; - OSType applicationSignature; - UInt8 data[1]; -}; -typedef struct ApplicationSpecificChunk ApplicationSpecificChunk; -typedef ApplicationSpecificChunk * ApplicationSpecificChunkPtr; -struct Comment { - UInt32 timeStamp; - MarkerIdType marker; - UInt16 count; - char text[1]; -}; -typedef struct Comment Comment; -struct CommentsChunk { - UInt32 ckID; - SInt32 ckSize; - UInt16 numComments; - Comment comments[1]; -}; -typedef struct CommentsChunk CommentsChunk; -typedef CommentsChunk * CommentsChunkPtr; -struct TextChunk { - UInt32 ckID; - SInt32 ckSize; - char text[1]; -}; -typedef struct TextChunk TextChunk; -typedef TextChunk * TextChunkPtr; - -#pragma pack(pop) - - - -#pragma pack(push, 2) -enum { - kTECAvailableEncodingsResType = 'cven', - kTECAvailableSniffersResType = 'cvsf', - kTECSubTextEncodingsResType = 'cvsb', - kTECConversionInfoResType = 'cvif', - kTECMailEncodingsResType = 'cvml', - kTECWebEncodingsResType = 'cvwb', - kTECInternetNamesResType = 'cvmm' -}; - -enum { - kTECPluginType = 'ecpg', - kTECPluginCreator = 'encv', - kTECPluginOneToOne = 'otoo', - kTECPluginOneToMany = 'otom', - kTECPluginManyToOne = 'mtoo', - kTECPluginSniffObj = 'snif' -}; - -enum { - verUnspecified = 32767, - kTECResourceID = 128 -}; -struct TextEncodingRec { - UInt32 base; - UInt32 variant; - UInt32 format; -}; -typedef struct TextEncodingRec TextEncodingRec; - -struct TECEncodingsListRec { - UInt32 count; - TextEncodingRec encodings; -}; -typedef struct TECEncodingsListRec TECEncodingsListRec; -typedef TECEncodingsListRec * TECEncodingsListPtr; -typedef TECEncodingsListPtr * TECEncodingsListHandle; - -struct TECSubTextEncodingRec { - UInt32 offset; - TextEncodingRec searchEncoding; - UInt32 count; - TextEncodingRec subEncodings; -}; -typedef struct TECSubTextEncodingRec TECSubTextEncodingRec; -struct TECSubTextEncodingsRec { - UInt32 count; - TECSubTextEncodingRec subTextEncodingRec; -}; -typedef struct TECSubTextEncodingsRec TECSubTextEncodingsRec; -typedef TECSubTextEncodingsRec * TECSubTextEncodingsPtr; -typedef TECSubTextEncodingsPtr * TECSubTextEncodingsHandle; - -struct TECEncodingPairRec { - TextEncodingRec source; - TextEncodingRec dest; -}; -typedef struct TECEncodingPairRec TECEncodingPairRec; -struct TECEncodingPairs { - TECEncodingPairRec encodingPair; - UInt32 flags; - UInt32 speed; -}; -typedef struct TECEncodingPairs TECEncodingPairs; -struct TECEncodingPairsRec { - UInt32 count; - TECEncodingPairs encodingPairs; -}; -typedef struct TECEncodingPairsRec TECEncodingPairsRec; -typedef TECEncodingPairsRec * TECEncodingPairsPtr; -typedef TECEncodingPairsPtr * TECEncodingPairsHandle; - -struct TECLocaleListToEncodingListRec { - UInt32 offset; - UInt32 count; - RegionCode locales; - -}; -typedef struct TECLocaleListToEncodingListRec TECLocaleListToEncodingListRec; -typedef TECLocaleListToEncodingListRec * TECLocaleListToEncodingListPtr; -struct TECLocaleToEncodingsListRec { - UInt32 count; - TECLocaleListToEncodingListRec localeListToEncodingList; -}; -typedef struct TECLocaleToEncodingsListRec TECLocaleToEncodingsListRec; -typedef TECLocaleToEncodingsListRec * TECLocaleToEncodingsListPtr; -typedef TECLocaleToEncodingsListPtr * TECLocaleToEncodingsListHandle; - -struct TECInternetNameRec { - UInt32 offset; - TextEncodingRec searchEncoding; - UInt8 encodingNameLength; - UInt8 encodingName[1]; -}; -typedef struct TECInternetNameRec TECInternetNameRec; -struct TECInternetNamesRec { - UInt32 count; - TECInternetNameRec InternetNames; -}; -typedef struct TECInternetNamesRec TECInternetNamesRec; -typedef TECInternetNamesRec * TECInternetNamesPtr; -typedef TECInternetNamesPtr * TECInternetNamesHandle; - -struct TECBufferContextRec { - ConstTextPtr textInputBuffer; - ConstTextPtr textInputBufferEnd; - TextPtr textOutputBuffer; - TextPtr textOutputBufferEnd; - - ConstTextEncodingRunPtr encodingInputBuffer; - ConstTextEncodingRunPtr encodingInputBufferEnd; - TextEncodingRunPtr encodingOutputBuffer; - TextEncodingRunPtr encodingOutputBufferEnd; -}; -typedef struct TECBufferContextRec TECBufferContextRec; -struct TECPluginStateRec { - - UInt8 state1; - UInt8 state2; - UInt8 state3; - UInt8 state4; - - UInt32 longState1; - UInt32 longState2; - UInt32 longState3; - UInt32 longState4; -}; -typedef struct TECPluginStateRec TECPluginStateRec; -struct TECConverterContextRec { - - - Ptr pluginRec; - TextEncoding sourceEncoding; - TextEncoding destEncoding; - UInt32 reserved1; - UInt32 reserved2; - TECBufferContextRec bufferContext; - - URefCon contextRefCon; - ProcPtr conversionProc; - ProcPtr flushProc; - ProcPtr clearContextInfoProc; - UInt32 options1; - UInt32 options2; - TECPluginStateRec pluginState; -}; -typedef struct TECConverterContextRec TECConverterContextRec; -struct TECSnifferContextRec { - - Ptr pluginRec; - TextEncoding encoding; - ItemCount maxErrors; - ItemCount maxFeatures; - ConstTextPtr textInputBuffer; - ConstTextPtr textInputBufferEnd; - ItemCount numFeatures; - ItemCount numErrors; - - URefCon contextRefCon; - ProcPtr sniffProc; - ProcPtr clearContextInfoProc; - TECPluginStateRec pluginState; -}; -typedef struct TECSnifferContextRec TECSnifferContextRec; - - - - - - -typedef OSStatus ( * TECPluginNewEncodingConverterPtr)(TECObjectRef *newEncodingConverter, TECConverterContextRec *plugContext, TextEncoding inputEncoding, TextEncoding outputEncoding); -typedef OSStatus ( * TECPluginClearContextInfoPtr)(TECObjectRef encodingConverter, TECConverterContextRec *plugContext); -typedef OSStatus ( * TECPluginConvertTextEncodingPtr)(TECObjectRef encodingConverter, TECConverterContextRec *plugContext); -typedef OSStatus ( * TECPluginFlushConversionPtr)(TECObjectRef encodingConverter, TECConverterContextRec *plugContext); -typedef OSStatus ( * TECPluginDisposeEncodingConverterPtr)(TECObjectRef newEncodingConverter, TECConverterContextRec *plugContext); -typedef OSStatus ( * TECPluginNewEncodingSnifferPtr)(TECSnifferObjectRef *encodingSniffer, TECSnifferContextRec *snifContext, TextEncoding inputEncoding); -typedef OSStatus ( * TECPluginClearSnifferContextInfoPtr)(TECSnifferObjectRef encodingSniffer, TECSnifferContextRec *snifContext); -typedef OSStatus ( * TECPluginSniffTextEncodingPtr)(TECSnifferObjectRef encodingSniffer, TECSnifferContextRec *snifContext); -typedef OSStatus ( * TECPluginDisposeEncodingSnifferPtr)(TECSnifferObjectRef encodingSniffer, TECSnifferContextRec *snifContext); -typedef OSStatus ( * TECPluginGetCountAvailableTextEncodingsPtr)(TextEncoding *availableEncodings, ItemCount maxAvailableEncodings, ItemCount *actualAvailableEncodings); -typedef OSStatus ( * TECPluginGetCountAvailableTextEncodingPairsPtr)(TECConversionInfo *availableEncodings, ItemCount maxAvailableEncodings, ItemCount *actualAvailableEncodings); -typedef OSStatus ( * TECPluginGetCountDestinationTextEncodingsPtr)(TextEncoding inputEncoding, TextEncoding *destinationEncodings, ItemCount maxDestinationEncodings, ItemCount *actualDestinationEncodings); -typedef OSStatus ( * TECPluginGetCountSubTextEncodingsPtr)(TextEncoding inputEncoding, TextEncoding subEncodings[], ItemCount maxSubEncodings, ItemCount *actualSubEncodings); -typedef OSStatus ( * TECPluginGetCountAvailableSniffersPtr)(TextEncoding *availableEncodings, ItemCount maxAvailableEncodings, ItemCount *actualAvailableEncodings); -typedef OSStatus ( * TECPluginGetTextEncodingInternetNamePtr)(TextEncoding textEncoding, Str255 encodingName); -typedef OSStatus ( * TECPluginGetTextEncodingFromInternetNamePtr)(TextEncoding *textEncoding, ConstStr255Param encodingName); -typedef OSStatus ( * TECPluginGetCountWebEncodingsPtr)(TextEncoding *availableEncodings, ItemCount maxAvailableEncodings, ItemCount *actualAvailableEncodings); -typedef OSStatus ( * TECPluginGetCountMailEncodingsPtr)(TextEncoding *availableEncodings, ItemCount maxAvailableEncodings, ItemCount *actualAvailableEncodings); - - - - - - -enum { - kTECPluginDispatchTableVersion1 = 0x00010000, - kTECPluginDispatchTableVersion1_1 = 0x00010001, - kTECPluginDispatchTableVersion1_2 = 0x00010002, - kTECPluginDispatchTableCurrentVersion = kTECPluginDispatchTableVersion1_2 -}; - -struct TECPluginDispatchTable { - - TECPluginVersion version; - TECPluginVersion compatibleVersion; - TECPluginSignature PluginID; - - TECPluginNewEncodingConverterPtr PluginNewEncodingConverter; - TECPluginClearContextInfoPtr PluginClearContextInfo; - TECPluginConvertTextEncodingPtr PluginConvertTextEncoding; - TECPluginFlushConversionPtr PluginFlushConversion; - TECPluginDisposeEncodingConverterPtr PluginDisposeEncodingConverter; - - TECPluginNewEncodingSnifferPtr PluginNewEncodingSniffer; - TECPluginClearSnifferContextInfoPtr PluginClearSnifferContextInfo; - TECPluginSniffTextEncodingPtr PluginSniffTextEncoding; - TECPluginDisposeEncodingSnifferPtr PluginDisposeEncodingSniffer; - - TECPluginGetCountAvailableTextEncodingsPtr PluginGetCountAvailableTextEncodings; - TECPluginGetCountAvailableTextEncodingPairsPtr PluginGetCountAvailableTextEncodingPairs; - TECPluginGetCountDestinationTextEncodingsPtr PluginGetCountDestinationTextEncodings; - TECPluginGetCountSubTextEncodingsPtr PluginGetCountSubTextEncodings; - TECPluginGetCountAvailableSniffersPtr PluginGetCountAvailableSniffers; - TECPluginGetCountWebEncodingsPtr PluginGetCountWebTextEncodings; - TECPluginGetCountMailEncodingsPtr PluginGetCountMailTextEncodings; - - TECPluginGetTextEncodingInternetNamePtr PluginGetTextEncodingInternetName; - TECPluginGetTextEncodingFromInternetNamePtr PluginGetTextEncodingFromInternetName; - -}; -typedef struct TECPluginDispatchTable TECPluginDispatchTable; -typedef TECPluginDispatchTable * ( * TECPluginGetPluginDispatchTablePtr)(void); - - - - - - -#pragma pack(pop) - - - - -extern "C" { - - -#pragma pack(push, 2) - - -enum { - typeBoolean = 'bool', - typeChar = 'TEXT' -}; - - - - - -enum { - typeStyledUnicodeText = 'sutx', - typeEncodedString = 'encs', - typeUnicodeText = 'utxt', - typeCString = 'cstr', - typePString = 'pstr' -}; - - - - -enum { - typeUTF16ExternalRepresentation = 'ut16', - typeUTF8Text = 'utf8' -}; - - -enum { - typeSInt16 = 'shor', - typeUInt16 = 'ushr', - typeSInt32 = 'long', - typeUInt32 = 'magn', - typeSInt64 = 'comp', - typeUInt64 = 'ucom', - typeIEEE32BitFloatingPoint = 'sing', - typeIEEE64BitFloatingPoint = 'doub', - type128BitFloatingPoint = 'ldbl', - typeDecimalStruct = 'decm' -}; -enum { - typeAEList = 'list', - typeAERecord = 'reco', - typeAppleEvent = 'aevt', - typeEventRecord = 'evrc', - typeTrue = 'true', - typeFalse = 'fals', - typeAlias = 'alis', - typeEnumerated = 'enum', - typeType = 'type', - typeAppParameters = 'appa', - typeProperty = 'prop', - typeFSRef = 'fsrf', - typeFileURL = 'furl', - typeBookmarkData = 'bmrk', - typeKeyword = 'keyw', - typeSectionH = 'sect', - typeWildCard = '****', - typeApplSignature = 'sign', - typeQDRectangle = 'qdrt', - typeFixed = 'fixd', - typeProcessSerialNumber = 'psn ', - typeApplicationURL = 'aprl', - typeNull = 'null' -}; -enum { - typeCFAttributedStringRef = 'cfas', - typeCFMutableAttributedStringRef = 'cfaa', - typeCFStringRef = 'cfst', - typeCFMutableStringRef = 'cfms', - typeCFArrayRef = 'cfar', - typeCFMutableArrayRef = 'cfma', - typeCFDictionaryRef = 'cfdc', - typeCFMutableDictionaryRef = 'cfmd', - typeCFNumberRef = 'cfnb', - typeCFBooleanRef = 'cftf', - typeCFTypeRef = 'cfty' -}; - - -enum { - typeKernelProcessID = 'kpid', - typeMachPort = 'port' -}; - - -enum { - typeAuditToken = 'tokn', -}; - - -enum { - typeApplicationBundleID = 'bund' -}; - - -enum { - keyTransactionIDAttr = 'tran', - keyReturnIDAttr = 'rtid', - keyEventClassAttr = 'evcl', - keyEventIDAttr = 'evid', - keyAddressAttr = 'addr', - keyOptionalKeywordAttr = 'optk', - keyTimeoutAttr = 'timo', - keyInteractLevelAttr = 'inte', - keyEventSourceAttr = 'esrc', - keyMissedKeywordAttr = 'miss', - keyOriginalAddressAttr = 'from', - keyAcceptTimeoutAttr = 'actm', - keyReplyRequestedAttr = 'repq', - - keySenderEUIDAttr = 'seid', - keySenderEGIDAttr = 'sgid', - keySenderUIDAttr = 'uids', - keySenderGIDAttr = 'gids', - keySenderPIDAttr = 'spid', - keySenderAuditTokenAttr = 'tokn', - - - keySenderApplescriptEntitlementsAttr = 'entl', - keySenderApplicationIdentifierEntitlementAttr = 'aiea', - keySenderApplicationSandboxed = 'sssb', - keyActualSenderAuditToken = 'acat', - -}; - - -enum { - kAEDebugPOSTHeader = (1 << 0), - kAEDebugReplyHeader = (1 << 1), - kAEDebugXMLRequest = (1 << 2), - kAEDebugXMLResponse = (1 << 3), - kAEDebugXMLDebugAll = (int)0xFFFFFFFF -}; - - - - - -enum { - kSOAP1999Schema = 'ss99', - kSOAP2001Schema = 'ss01' -}; - -enum { - - keyUserNameAttr = 'unam', - keyUserPasswordAttr = 'pass', - keyDisableAuthenticationAttr = 'auth', - - - keyXMLDebuggingAttr = 'xdbg', - - kAERPCClass = 'rpc ', - kAEXMLRPCScheme = 'RPC2', - kAESOAPScheme = 'SOAP', - kAESharedScriptHandler = 'wscp', - - keyRPCMethodName = 'meth', - keyRPCMethodParam = 'parm', - keyRPCMethodParamOrder = '/ord', - - keyAEPOSTHeaderData = 'phed', - keyAEReplyHeaderData = 'rhed', - keyAEXMLRequestData = 'xreq', - keyAEXMLReplyData = 'xrep', - - keyAdditionalHTTPHeaders = 'ahed', - keySOAPAction = 'sact', - keySOAPMethodNameSpace = 'mspc', - keySOAPMethodNameSpaceURI = 'mspu', - keySOAPSchemaVersion = 'ssch' -}; -enum { - keySOAPStructureMetaData = '/smd', - keySOAPSMDNamespace = 'ssns', - keySOAPSMDNamespaceURI = 'ssnu', - keySOAPSMDType = 'sstp' -}; - - - - - - -enum { - - kAEUseHTTPProxyAttr = 'xupr', - - kAEHTTPProxyPortAttr = 'xhtp', - kAEHTTPProxyHostAttr = 'xhth' -}; - - - - - - -enum { - kAESocks4Protocol = 4, - kAESocks5Protocol = 5 -}; - -enum { - kAEUseSocksAttr = 'xscs', - - kAESocksProxyAttr = 'xsok', - - kAESocksHostAttr = 'xshs', - kAESocksPortAttr = 'xshp', - kAESocksUserAttr = 'xshu', - - kAESocksPasswordAttr = 'xshw' -}; - - - -enum { - kAEDescListFactorNone = 0, - kAEDescListFactorType = 4, - kAEDescListFactorTypeAndSize = 8 -}; - - -enum { - - kAutoGenerateReturnID = -1, - - kAnyTransactionID = 0 -}; - - -typedef ResType DescType; -typedef FourCharCode AEKeyword; - -typedef struct OpaqueAEDataStorageType* AEDataStorageType; - - - - -typedef AEDataStorageType * AEDataStorage; -struct AEDesc { - DescType descriptorType; - AEDataStorage dataHandle; -}; -typedef struct AEDesc AEDesc; -typedef AEDesc * AEDescPtr; -struct AEKeyDesc { - AEKeyword descKey; - AEDesc descContent; -}; -typedef struct AEKeyDesc AEKeyDesc; - - -typedef AEDesc AEDescList; - -typedef AEDescList AERecord; - -typedef AEDesc AEAddressDesc; - -typedef AERecord AppleEvent; -typedef AppleEvent * AppleEventPtr; -typedef SInt16 AEReturnID; -typedef SInt32 AETransactionID; -typedef FourCharCode AEEventClass; -typedef FourCharCode AEEventID; -typedef SInt8 AEArrayType; -enum { - kAEDataArray = 0, - kAEPackedArray = 1, - kAEDescArray = 3, - kAEKeyDescArray = 4 -}; - - -enum { - kAEHandleArray = 2 -}; - -union AEArrayData { - SInt16 kAEDataArray[1]; - char kAEPackedArray[1]; - Handle kAEHandleArray[1]; - AEDesc kAEDescArray[1]; - AEKeyDesc kAEKeyDescArray[1]; -}; -typedef union AEArrayData AEArrayData; -typedef AEArrayData * AEArrayDataPointer; - - - - -typedef SInt16 AESendPriority; -enum { - kAENormalPriority = 0x00000000, - kAEHighPriority = 0x00000001 -}; - - -typedef SInt32 AESendMode; -enum { - kAENoReply = 0x00000001, - kAEQueueReply = 0x00000002, - kAEWaitReply = 0x00000003, - kAEDontReconnect = 0x00000080, - kAEWantReceipt = 0x00000200, - kAENeverInteract = 0x00000010, - kAECanInteract = 0x00000020, - kAEAlwaysInteract = 0x00000030, - kAECanSwitchLayer = 0x00000040, - kAEDontRecord = 0x00001000, - kAEDontExecute = 0x00002000, - kAEProcessNonReplyEvents = 0x00008000, - kAEDoNotAutomaticallyAddAnnotationsToEvent = 0x00010000 -}; - - - -enum { - kAEDefaultTimeout = -1, - kNoTimeOut = -2 -}; - - - - - -typedef OSErr ( * AECoerceDescProcPtr)(const AEDesc *fromDesc, DescType toType, SRefCon handlerRefcon, AEDesc *toDesc); -typedef OSErr ( * AECoercePtrProcPtr)(DescType typeCode, const void *dataPtr, Size dataSize, DescType toType, SRefCon handlerRefcon, AEDesc *result); -typedef AECoerceDescProcPtr AECoerceDescUPP; -typedef AECoercePtrProcPtr AECoercePtrUPP; -extern AECoerceDescUPP -NewAECoerceDescUPP(AECoerceDescProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern AECoercePtrUPP -NewAECoercePtrUPP(AECoercePtrProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeAECoerceDescUPP(AECoerceDescUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeAECoercePtrUPP(AECoercePtrUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeAECoerceDescUPP( - const AEDesc * fromDesc, - DescType toType, - SRefCon handlerRefcon, - AEDesc * toDesc, - AECoerceDescUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeAECoercePtrUPP( - DescType typeCode, - const void * dataPtr, - Size dataSize, - DescType toType, - SRefCon handlerRefcon, - AEDesc * result, - AECoercePtrUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); - - - - inline AECoerceDescUPP NewAECoerceDescUPP(AECoerceDescProcPtr userRoutine) { return userRoutine; } - inline AECoercePtrUPP NewAECoercePtrUPP(AECoercePtrProcPtr userRoutine) { return userRoutine; } - inline void DisposeAECoerceDescUPP(AECoerceDescUPP) { } - inline void DisposeAECoercePtrUPP(AECoercePtrUPP) { } - inline OSErr InvokeAECoerceDescUPP(const AEDesc * fromDesc, DescType toType, SRefCon handlerRefcon, AEDesc * toDesc, AECoerceDescUPP userUPP) { return (*userUPP)(fromDesc, toType, handlerRefcon, toDesc); } - inline OSErr InvokeAECoercePtrUPP(DescType typeCode, const void * dataPtr, Size dataSize, DescType toType, SRefCon handlerRefcon, AEDesc * result, AECoercePtrUPP userUPP) { return (*userUPP)(typeCode, dataPtr, dataSize, toType, handlerRefcon, result); } -typedef AECoerceDescUPP AECoercionHandlerUPP; -extern OSErr -AEInstallCoercionHandler( - DescType fromType, - DescType toType, - AECoercionHandlerUPP handler, - SRefCon handlerRefcon, - Boolean fromTypeIsDesc, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AERemoveCoercionHandler( - DescType fromType, - DescType toType, - AECoercionHandlerUPP handler, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetCoercionHandler( - DescType fromType, - DescType toType, - AECoercionHandlerUPP * handler, - SRefCon * handlerRefcon, - Boolean * fromTypeIsDesc, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AECoercePtr( - DescType typeCode, - const void * dataPtr, - Size dataSize, - DescType toType, - AEDesc * result) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AECoerceDesc( - const AEDesc * theAEDesc, - DescType toType, - AEDesc * result) __attribute__((availability(macosx,introduced=10.0))); -extern void -AEInitializeDesc(AEDesc * desc) __attribute__((availability(macosx,introduced=10.0))); - - - - - inline void AEInitializeDescInline(AEDesc* d) { d->descriptorType = typeNull; d->dataHandle = __null; } -extern OSErr -AECreateDesc( - DescType typeCode, - const void * dataPtr, - Size dataSize, - AEDesc * result) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEDisposeDesc(AEDesc * theAEDesc) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEDuplicateDesc( - const AEDesc * theAEDesc, - AEDesc * result) __attribute__((availability(macosx,introduced=10.0))); - - - -typedef void ( * AEDisposeExternalProcPtr)(const void *dataPtr, Size dataLength, SRefCon refcon); -typedef AEDisposeExternalProcPtr AEDisposeExternalUPP; -extern OSStatus -AECreateDescFromExternalPtr( - OSType descriptorType, - const void * dataPtr, - Size dataLength, - AEDisposeExternalUPP disposeCallback, - SRefCon disposeRefcon, - AEDesc * theDesc) __attribute__((availability(macosx,introduced=10.2))); - extern OSStatus - AECompareDesc( const AEDesc * desc1, const AEDesc* desc2, Boolean* resultP ) __attribute__((availability(macosx,introduced=10.8))); -extern OSErr -AECreateList( - const void * factoringPtr, - Size factoredSize, - Boolean isRecord, - AEDescList * resultList) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AECountItems( - const AEDescList * theAEDescList, - long * theCount) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEPutPtr( - AEDescList * theAEDescList, - long index, - DescType typeCode, - const void * dataPtr, - Size dataSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEPutDesc( - AEDescList * theAEDescList, - long index, - const AEDesc * theAEDesc) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetNthPtr( - const AEDescList * theAEDescList, - long index, - DescType desiredType, - AEKeyword * theAEKeyword, - DescType * typeCode, - void * dataPtr, - Size maximumSize, - Size * actualSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetNthDesc( - const AEDescList * theAEDescList, - long index, - DescType desiredType, - AEKeyword * theAEKeyword, - AEDesc * result) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AESizeOfNthItem( - const AEDescList * theAEDescList, - long index, - DescType * typeCode, - Size * dataSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetArray( - const AEDescList * theAEDescList, - AEArrayType arrayType, - AEArrayDataPointer arrayPtr, - Size maximumSize, - DescType * itemType, - Size * itemSize, - long * itemCount) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEPutArray( - AEDescList * theAEDescList, - AEArrayType arrayType, - const AEArrayData * arrayPtr, - DescType itemType, - Size itemSize, - long itemCount) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEDeleteItem( - AEDescList * theAEDescList, - long index) __attribute__((availability(macosx,introduced=10.0))); -extern Boolean -AECheckIsRecord(const AEDesc * theDesc) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AECreateAppleEvent( - AEEventClass theAEEventClass, - AEEventID theAEEventID, - const AEAddressDesc * target, - AEReturnID returnID, - AETransactionID transactionID, - AppleEvent * result) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEPutParamPtr( - AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - DescType typeCode, - const void * dataPtr, - Size dataSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEPutParamDesc( - AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - const AEDesc * theAEDesc) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetParamPtr( - const AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - DescType desiredType, - DescType * actualType, - void * dataPtr, - Size maximumSize, - Size * actualSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetParamDesc( - const AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - DescType desiredType, - AEDesc * result) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AESizeOfParam( - const AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - DescType * typeCode, - Size * dataSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEDeleteParam( - AppleEvent * theAppleEvent, - AEKeyword theAEKeyword) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetAttributePtr( - const AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - DescType desiredType, - DescType * typeCode, - void * dataPtr, - Size maximumSize, - Size * actualSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetAttributeDesc( - const AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - DescType desiredType, - AEDesc * result) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AESizeOfAttribute( - const AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - DescType * typeCode, - Size * dataSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEPutAttributePtr( - AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - DescType typeCode, - const void * dataPtr, - Size dataSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEPutAttributeDesc( - AppleEvent * theAppleEvent, - AEKeyword theAEKeyword, - const AEDesc * theAEDesc) __attribute__((availability(macosx,introduced=10.0))); -extern Size -AESizeOfFlattenedDesc(const AEDesc * theAEDesc) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEFlattenDesc( - const AEDesc * theAEDesc, - Ptr buffer, - Size bufferSize, - Size * actualSize) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEUnflattenDesc( - const void * buffer, - AEDesc * result) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetDescData( - const AEDesc * theAEDesc, - void * dataPtr, - Size maximumSize) __attribute__((availability(macosx,introduced=10.0))); -extern Size -AEGetDescDataSize(const AEDesc * theAEDesc) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEReplaceDescData( - DescType typeCode, - const void * dataPtr, - Size dataSize, - AEDesc * theAEDesc) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEGetDescDataRange( - const AEDesc * dataDesc, - void * buffer, - Size offset, - Size length) __attribute__((availability(macosx,introduced=10.2))); - - - - - -typedef OSErr ( * AEEventHandlerProcPtr)(const AppleEvent *theAppleEvent, AppleEvent *reply, SRefCon handlerRefcon); -typedef AEEventHandlerProcPtr AEEventHandlerUPP; -extern AEDisposeExternalUPP -NewAEDisposeExternalUPP(AEDisposeExternalProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.2))); -extern AEEventHandlerUPP -NewAEEventHandlerUPP(AEEventHandlerProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeAEDisposeExternalUPP(AEDisposeExternalUPP userUPP) __attribute__((availability(macosx,introduced=10.2))); -extern void -DisposeAEEventHandlerUPP(AEEventHandlerUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern void -InvokeAEDisposeExternalUPP( - const void * dataPtr, - Size dataLength, - SRefCon refcon, - AEDisposeExternalUPP userUPP) __attribute__((availability(macosx,introduced=10.2))); -extern OSErr -InvokeAEEventHandlerUPP( - const AppleEvent * theAppleEvent, - AppleEvent * reply, - SRefCon handlerRefcon, - AEEventHandlerUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); - - - - inline AEDisposeExternalUPP NewAEDisposeExternalUPP(AEDisposeExternalProcPtr userRoutine) { return userRoutine; } - inline AEEventHandlerUPP NewAEEventHandlerUPP(AEEventHandlerProcPtr userRoutine) { return userRoutine; } - inline void DisposeAEDisposeExternalUPP(AEDisposeExternalUPP) { } - inline void DisposeAEEventHandlerUPP(AEEventHandlerUPP) { } - inline void InvokeAEDisposeExternalUPP(const void * dataPtr, Size dataLength, SRefCon refcon, AEDisposeExternalUPP userUPP) { (*userUPP)(dataPtr, dataLength, refcon); } - inline OSErr InvokeAEEventHandlerUPP(const AppleEvent * theAppleEvent, AppleEvent * reply, SRefCon handlerRefcon, AEEventHandlerUPP userUPP) { return (*userUPP)(theAppleEvent, reply, handlerRefcon); } -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - -enum { - - keyDirectObject = '----', - keyErrorNumber = 'errn', - keyErrorString = 'errs', - keyProcessSerialNumber = 'psn ', - keyPreDispatch = 'phac', - keySelectProc = 'selh', - - keyAERecorderCount = 'recr', - - keyAEVersion = 'vers' -}; - - -enum { - kCoreEventClass = 'aevt' -}; - - -enum { - kAEOpenApplication = 'oapp', - kAEOpenDocuments = 'odoc', - kAEPrintDocuments = 'pdoc', - kAEOpenContents = 'ocon', - kAEQuitApplication = 'quit', - kAEAnswer = 'ansr', - kAEApplicationDied = 'obit', - kAEShowPreferences = 'pref' -}; - - -enum { - kAEStartRecording = 'reca', - kAEStopRecording = 'recc', - kAENotifyStartRecording = 'rec1', - kAENotifyStopRecording = 'rec0', - kAENotifyRecording = 'recr' -}; -typedef SInt8 AEEventSource; -enum { - kAEUnknownSource = 0, - kAEDirectCall = 1, - kAESameProcess = 2, - kAELocalProcess = 3, - kAERemoteProcess = 4 -}; - - - - enum { - errAETargetAddressNotPermitted = -1742, - errAEEventNotPermitted = -1743, - }; -extern OSErr -AEInstallEventHandler( - AEEventClass theAEEventClass, - AEEventID theAEEventID, - AEEventHandlerUPP handler, - SRefCon handlerRefcon, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AERemoveEventHandler( - AEEventClass theAEEventClass, - AEEventID theAEEventID, - AEEventHandlerUPP handler, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetEventHandler( - AEEventClass theAEEventClass, - AEEventID theAEEventID, - AEEventHandlerUPP * handler, - SRefCon * handlerRefcon, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEInstallSpecialHandler( - AEKeyword functionClass, - AEEventHandlerUPP handler, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AERemoveSpecialHandler( - AEKeyword functionClass, - AEEventHandlerUPP handler, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetSpecialHandler( - AEKeyword functionClass, - AEEventHandlerUPP * handler, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEManagerInfo( - AEKeyword keyWord, - long * result) __attribute__((availability(macosx,introduced=10.0))); -extern const CFStringRef kAERemoteProcessURLKey __attribute__((availability(macosx,introduced=10.3))); -extern const CFStringRef kAERemoteProcessNameKey __attribute__((availability(macosx,introduced=10.3))); -extern const CFStringRef kAERemoteProcessUserIDKey __attribute__((availability(macosx,introduced=10.3))); -extern const CFStringRef kAERemoteProcessProcessIDKey __attribute__((availability(macosx,introduced=10.3))); -struct AERemoteProcessResolverContext { - - - - - CFIndex version; - - - - - void * info; - - - - - CFAllocatorRetainCallBack retain; - - - - - CFAllocatorReleaseCallBack release; - - - - - CFAllocatorCopyDescriptionCallBack copyDescription; -}; -typedef struct AERemoteProcessResolverContext AERemoteProcessResolverContext; -typedef struct AERemoteProcessResolver* AERemoteProcessResolverRef; -extern AERemoteProcessResolverRef -AECreateRemoteProcessResolver( - CFAllocatorRef allocator, - CFURLRef url) __attribute__((availability(macosx,introduced=10.3))); -extern void -AEDisposeRemoteProcessResolver(AERemoteProcessResolverRef ref) __attribute__((availability(macosx,introduced=10.3))); -extern CFArrayRef -AERemoteProcessResolverGetProcesses( - AERemoteProcessResolverRef ref, - CFStreamError * outError) __attribute__((availability(macosx,introduced=10.3))); -typedef void ( * AERemoteProcessResolverCallback)(AERemoteProcessResolverRef ref, void *info); -extern void -AERemoteProcessResolverScheduleWithRunLoop( - AERemoteProcessResolverRef ref, - CFRunLoopRef runLoop, - CFStringRef runLoopMode, - AERemoteProcessResolverCallback callback, - const AERemoteProcessResolverContext * ctx) __attribute__((availability(macosx,introduced=10.3))); - - - - - - -#pragma pack(pop) - - -} - - - -extern "C" { -extern OSErr -CreateOffsetDescriptor( - long theOffset, - AEDesc * theDescriptor) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -CreateCompDescriptor( - DescType comparisonOperator, - AEDesc * operand1, - AEDesc * operand2, - Boolean disposeInputs, - AEDesc * theDescriptor) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -CreateLogicalDescriptor( - AEDescList * theLogicalTerms, - DescType theLogicOperator, - Boolean disposeInputs, - AEDesc * theDescriptor) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -CreateObjSpecifier( - DescType desiredClass, - AEDesc * theContainer, - DescType keyForm, - AEDesc * keyData, - Boolean disposeInputs, - AEDesc * objSpecifier) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -CreateRangeDescriptor( - AEDesc * rangeStart, - AEDesc * rangeStop, - Boolean disposeInputs, - AEDesc * theDescriptor) __attribute__((availability(macosx,introduced=10.0))); - - - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - -enum { - - kAEAND = 'AND ', - kAEOR = 'OR ', - kAENOT = 'NOT ', - - kAEFirst = 'firs', - kAELast = 'last', - kAEMiddle = 'midd', - kAEAny = 'any ', - kAEAll = 'all ', - - kAENext = 'next', - kAEPrevious = 'prev', - - keyAECompOperator = 'relo', - keyAELogicalTerms = 'term', - keyAELogicalOperator = 'logc', - keyAEObject1 = 'obj1', - keyAEObject2 = 'obj2', - - keyAEDesiredClass = 'want', - keyAEContainer = 'from', - keyAEKeyForm = 'form', - keyAEKeyData = 'seld' -}; - -enum { - - keyAERangeStart = 'star', - keyAERangeStop = 'stop', - - keyDisposeTokenProc = 'xtok', - keyAECompareProc = 'cmpr', - keyAECountProc = 'cont', - keyAEMarkTokenProc = 'mkid', - keyAEMarkProc = 'mark', - keyAEAdjustMarksProc = 'adjm', - keyAEGetErrDescProc = 'indc' -}; - - -enum { - - formAbsolutePosition = 'indx', - formRelativePosition = 'rele', - formTest = 'test', - formRange = 'rang', - formPropertyID = 'prop', - formName = 'name', - formUniqueID = 'ID ', - - typeObjectSpecifier = 'obj ', - typeObjectBeingExamined = 'exmn', - typeCurrentContainer = 'ccnt', - typeToken = 'toke', - typeRelativeDescriptor = 'rel ', - typeAbsoluteOrdinal = 'abso', - typeIndexDescriptor = 'inde', - typeRangeDescriptor = 'rang', - typeLogicalDescriptor = 'logi', - typeCompDescriptor = 'cmpd', - typeOSLTokenList = 'ostl' -}; - - -enum { - kAEIDoMinimum = 0x0000, - kAEIDoWhose = 0x0001, - kAEIDoMarking = 0x0004, - kAEPassSubDescs = 0x0008, - kAEResolveNestedLists = 0x0010, - kAEHandleSimpleRanges = 0x0020, - kAEUseRelativeIterators = 0x0040 -}; - - -enum { - typeWhoseDescriptor = 'whos', - formWhose = 'whos', - typeWhoseRange = 'wrng', - keyAEWhoseRangeStart = 'wstr', - keyAEWhoseRangeStop = 'wstp', - keyAEIndex = 'kidx', - keyAETest = 'ktst' -}; - - - - - - - -struct ccntTokenRecord { - DescType tokenClass; - AEDesc token; -}; -typedef struct ccntTokenRecord ccntTokenRecord; -typedef ccntTokenRecord * ccntTokenRecPtr; -typedef ccntTokenRecPtr * ccntTokenRecHandle; - - - - - - -typedef OSErr ( * OSLAccessorProcPtr)(DescType desiredClass, const AEDesc *container, DescType containerClass, DescType form, const AEDesc *selectionData, AEDesc *value, SRefCon accessorRefcon); -typedef OSErr ( * OSLCompareProcPtr)(DescType oper, const AEDesc *obj1, const AEDesc *obj2, Boolean *result); -typedef OSErr ( * OSLCountProcPtr)(DescType desiredType, DescType containerClass, const AEDesc *container, long *result); -typedef OSErr ( * OSLDisposeTokenProcPtr)(AEDesc * unneededToken); -typedef OSErr ( * OSLGetMarkTokenProcPtr)(const AEDesc *dContainerToken, DescType containerClass, AEDesc *result); -typedef OSErr ( * OSLGetErrDescProcPtr)(AEDesc ** appDescPtr); -typedef OSErr ( * OSLMarkProcPtr)(const AEDesc *dToken, const AEDesc *markToken, long index); -typedef OSErr ( * OSLAdjustMarksProcPtr)(long newStart, long newStop, const AEDesc *markToken); -typedef OSLAccessorProcPtr OSLAccessorUPP; -typedef OSLCompareProcPtr OSLCompareUPP; -typedef OSLCountProcPtr OSLCountUPP; -typedef OSLDisposeTokenProcPtr OSLDisposeTokenUPP; -typedef OSLGetMarkTokenProcPtr OSLGetMarkTokenUPP; -typedef OSLGetErrDescProcPtr OSLGetErrDescUPP; -typedef OSLMarkProcPtr OSLMarkUPP; -typedef OSLAdjustMarksProcPtr OSLAdjustMarksUPP; -extern OSLAccessorUPP -NewOSLAccessorUPP(OSLAccessorProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern OSLCompareUPP -NewOSLCompareUPP(OSLCompareProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern OSLCountUPP -NewOSLCountUPP(OSLCountProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern OSLDisposeTokenUPP -NewOSLDisposeTokenUPP(OSLDisposeTokenProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern OSLGetMarkTokenUPP -NewOSLGetMarkTokenUPP(OSLGetMarkTokenProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern OSLGetErrDescUPP -NewOSLGetErrDescUPP(OSLGetErrDescProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern OSLMarkUPP -NewOSLMarkUPP(OSLMarkProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern OSLAdjustMarksUPP -NewOSLAdjustMarksUPP(OSLAdjustMarksProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeOSLAccessorUPP(OSLAccessorUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeOSLCompareUPP(OSLCompareUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeOSLCountUPP(OSLCountUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeOSLDisposeTokenUPP(OSLDisposeTokenUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeOSLGetMarkTokenUPP(OSLGetMarkTokenUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeOSLGetErrDescUPP(OSLGetErrDescUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeOSLMarkUPP(OSLMarkUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern void -DisposeOSLAdjustMarksUPP(OSLAdjustMarksUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeOSLAccessorUPP( - DescType desiredClass, - const AEDesc * container, - DescType containerClass, - DescType form, - const AEDesc * selectionData, - AEDesc * value, - SRefCon accessorRefcon, - OSLAccessorUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeOSLCompareUPP( - DescType oper, - const AEDesc * obj1, - const AEDesc * obj2, - Boolean * result, - OSLCompareUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeOSLCountUPP( - DescType desiredType, - DescType containerClass, - const AEDesc * container, - long * result, - OSLCountUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeOSLDisposeTokenUPP( - AEDesc * unneededToken, - OSLDisposeTokenUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeOSLGetMarkTokenUPP( - const AEDesc * dContainerToken, - DescType containerClass, - AEDesc * result, - OSLGetMarkTokenUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeOSLGetErrDescUPP( - AEDesc ** appDescPtr, - OSLGetErrDescUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeOSLMarkUPP( - const AEDesc * dToken, - const AEDesc * markToken, - long index, - OSLMarkUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -InvokeOSLAdjustMarksUPP( - long newStart, - long newStop, - const AEDesc * markToken, - OSLAdjustMarksUPP userUPP) __attribute__((availability(macosx,introduced=10.0))); - - - - inline OSLAccessorUPP NewOSLAccessorUPP(OSLAccessorProcPtr userRoutine) { return userRoutine; } - inline OSLCompareUPP NewOSLCompareUPP(OSLCompareProcPtr userRoutine) { return userRoutine; } - inline OSLCountUPP NewOSLCountUPP(OSLCountProcPtr userRoutine) { return userRoutine; } - inline OSLDisposeTokenUPP NewOSLDisposeTokenUPP(OSLDisposeTokenProcPtr userRoutine) { return userRoutine; } - inline OSLGetMarkTokenUPP NewOSLGetMarkTokenUPP(OSLGetMarkTokenProcPtr userRoutine) { return userRoutine; } - inline OSLGetErrDescUPP NewOSLGetErrDescUPP(OSLGetErrDescProcPtr userRoutine) { return userRoutine; } - inline OSLMarkUPP NewOSLMarkUPP(OSLMarkProcPtr userRoutine) { return userRoutine; } - inline OSLAdjustMarksUPP NewOSLAdjustMarksUPP(OSLAdjustMarksProcPtr userRoutine) { return userRoutine; } - inline void DisposeOSLAccessorUPP(OSLAccessorUPP) { } - inline void DisposeOSLCompareUPP(OSLCompareUPP) { } - inline void DisposeOSLCountUPP(OSLCountUPP) { } - inline void DisposeOSLDisposeTokenUPP(OSLDisposeTokenUPP) { } - inline void DisposeOSLGetMarkTokenUPP(OSLGetMarkTokenUPP) { } - inline void DisposeOSLGetErrDescUPP(OSLGetErrDescUPP) { } - inline void DisposeOSLMarkUPP(OSLMarkUPP) { } - inline void DisposeOSLAdjustMarksUPP(OSLAdjustMarksUPP) { } - inline OSErr InvokeOSLAccessorUPP(DescType desiredClass, const AEDesc * container, DescType containerClass, DescType form, const AEDesc * selectionData, AEDesc * value, SRefCon accessorRefcon, OSLAccessorUPP userUPP) { return (*userUPP)(desiredClass, container, containerClass, form, selectionData, value, accessorRefcon); } - inline OSErr InvokeOSLCompareUPP(DescType oper, const AEDesc * obj1, const AEDesc * obj2, Boolean * result, OSLCompareUPP userUPP) { return (*userUPP)(oper, obj1, obj2, result); } - inline OSErr InvokeOSLCountUPP(DescType desiredType, DescType containerClass, const AEDesc * container, long * result, OSLCountUPP userUPP) { return (*userUPP)(desiredType, containerClass, container, result); } - inline OSErr InvokeOSLDisposeTokenUPP(AEDesc * unneededToken, OSLDisposeTokenUPP userUPP) { return (*userUPP)(unneededToken); } - inline OSErr InvokeOSLGetMarkTokenUPP(const AEDesc * dContainerToken, DescType containerClass, AEDesc * result, OSLGetMarkTokenUPP userUPP) { return (*userUPP)(dContainerToken, containerClass, result); } - inline OSErr InvokeOSLGetErrDescUPP(AEDesc ** appDescPtr, OSLGetErrDescUPP userUPP) { return (*userUPP)(appDescPtr); } - inline OSErr InvokeOSLMarkUPP(const AEDesc * dToken, const AEDesc * markToken, long index, OSLMarkUPP userUPP) { return (*userUPP)(dToken, markToken, index); } - inline OSErr InvokeOSLAdjustMarksUPP(long newStart, long newStop, const AEDesc * markToken, OSLAdjustMarksUPP userUPP) { return (*userUPP)(newStart, newStop, markToken); } -extern OSErr -AEObjectInit(void) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AESetObjectCallbacks( - OSLCompareUPP myCompareProc, - OSLCountUPP myCountProc, - OSLDisposeTokenUPP myDisposeTokenProc, - OSLGetMarkTokenUPP myGetMarkTokenProc, - OSLMarkUPP myMarkProc, - OSLAdjustMarksUPP myAdjustMarksProc, - OSLGetErrDescUPP myGetErrDescProcPtr) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEResolve( - const AEDesc * objectSpecifier, - short callbackFlags, - AEDesc * theToken) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEInstallObjectAccessor( - DescType desiredClass, - DescType containerType, - OSLAccessorUPP theAccessor, - SRefCon accessorRefcon, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AERemoveObjectAccessor( - DescType desiredClass, - DescType containerType, - OSLAccessorUPP theAccessor, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEGetObjectAccessor( - DescType desiredClass, - DescType containerType, - OSLAccessorUPP * accessor, - SRefCon * accessorRefcon, - Boolean isSysHandler) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AEDisposeToken(AEDesc * theToken) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AECallObjectAccessor( - DescType desiredClass, - const AEDesc * containerToken, - DescType containerClass, - DescType keyForm, - const AEDesc * keyData, - AEDesc * token) __attribute__((availability(macosx,introduced=10.0))); - - - -#pragma pack(pop) - - -} - - - -#pragma pack(push, 2) - -enum { - cAEList = 'list', - cApplication = 'capp', - cArc = 'carc', - cBoolean = 'bool', - cCell = 'ccel', - cChar = 'cha ', - cColorTable = 'clrt', - cColumn = 'ccol', - cDocument = 'docu', - cDrawingArea = 'cdrw', - cEnumeration = 'enum', - cFile = 'file', - cFixed = 'fixd', - cFixedPoint = 'fpnt', - cFixedRectangle = 'frct', - cGraphicLine = 'glin', - cGraphicObject = 'cgob', - cGraphicShape = 'cgsh', - cGraphicText = 'cgtx', - cGroupedGraphic = 'cpic' -}; - -enum { - cInsertionLoc = 'insl', - cInsertionPoint = 'cins', - cIntlText = 'itxt', - cIntlWritingCode = 'intl', - cItem = 'citm', - cLine = 'clin', - cLongDateTime = 'ldt ', - cLongFixed = 'lfxd', - cLongFixedPoint = 'lfpt', - cLongFixedRectangle = 'lfrc', - cLongInteger = 'long', - cLongPoint = 'lpnt', - cLongRectangle = 'lrct', - cMachineLoc = 'mLoc', - cMenu = 'cmnu', - cMenuItem = 'cmen', - cObject = 'cobj', - cObjectSpecifier = 'obj ', - cOpenableObject = 'coob', - cOval = 'covl' -}; - -enum { - cParagraph = 'cpar', - cPICT = 'PICT', - cPixel = 'cpxl', - cPixelMap = 'cpix', - cPolygon = 'cpgn', - cProperty = 'prop', - cQDPoint = 'QDpt', - cQDRectangle = 'qdrt', - cRectangle = 'crec', - cRGBColor = 'cRGB', - cRotation = 'trot', - cRoundedRectangle = 'crrc', - cRow = 'crow', - cSelection = 'csel', - cShortInteger = 'shor', - cTable = 'ctbl', - cText = 'ctxt', - cTextFlow = 'cflo', - cTextStyles = 'tsty', - cType = 'type' -}; - -enum { - cVersion = 'vers', - cWindow = 'cwin', - cWord = 'cwor', - enumArrows = 'arro', - enumJustification = 'just', - enumKeyForm = 'kfrm', - enumPosition = 'posi', - enumProtection = 'prtn', - enumQuality = 'qual', - enumSaveOptions = 'savo', - enumStyle = 'styl', - enumTransferMode = 'tran', - kAEAbout = 'abou', - kAEAfter = 'afte', - kAEAliasSelection = 'sali', - kAEAllCaps = 'alcp', - kAEArrowAtEnd = 'aren', - kAEArrowAtStart = 'arst', - kAEArrowBothEnds = 'arbo' -}; - -enum { - kAEAsk = 'ask ', - kAEBefore = 'befo', - kAEBeginning = 'bgng', - kAEBeginsWith = 'bgwt', - kAEBeginTransaction = 'begi', - kAEBold = 'bold', - kAECaseSensEquals = 'cseq', - kAECentered = 'cent', - kAEChangeView = 'view', - kAEClone = 'clon', - kAEClose = 'clos', - kAECondensed = 'cond', - kAEContains = 'cont', - kAECopy = 'copy', - kAECoreSuite = 'core', - kAECountElements = 'cnte', - kAECreateElement = 'crel', - kAECreatePublisher = 'cpub', - kAECut = 'cut ', - kAEDelete = 'delo' -}; - -enum { - kAEDoObjectsExist = 'doex', - kAEDoScript = 'dosc', - kAEDrag = 'drag', - kAEDuplicateSelection = 'sdup', - kAEEditGraphic = 'edit', - kAEEmptyTrash = 'empt', - kAEEnd = 'end ', - kAEEndsWith = 'ends', - kAEEndTransaction = 'endt', - kAEEquals = '= ', - kAEExpanded = 'pexp', - kAEFast = 'fast', - kAEFinderEvents = 'FNDR', - kAEFormulaProtect = 'fpro', - kAEFullyJustified = 'full', - kAEGetClassInfo = 'qobj', - kAEGetData = 'getd', - kAEGetDataSize = 'dsiz', - kAEGetEventInfo = 'gtei', - kAEGetInfoSelection = 'sinf' -}; - -enum { - kAEGetPrivilegeSelection = 'sprv', - kAEGetSuiteInfo = 'gtsi', - kAEGreaterThan = '> ', - kAEGreaterThanEquals = '>= ', - kAEGrow = 'grow', - kAEHidden = 'hidn', - kAEHiQuality = 'hiqu', - kAEImageGraphic = 'imgr', - kAEIsUniform = 'isun', - kAEItalic = 'ital', - kAELeftJustified = 'left', - kAELessThan = '< ', - kAELessThanEquals = '<= ', - kAELowercase = 'lowc', - kAEMakeObjectsVisible = 'mvis', - kAEMiscStandards = 'misc', - kAEModifiable = 'modf', - kAEMove = 'move', - kAENo = 'no ', - kAENoArrow = 'arno' -}; - -enum { - kAENonmodifiable = 'nmod', - kAEOpen = 'odoc', - kAEOpenSelection = 'sope', - kAEOutline = 'outl', - kAEPageSetup = 'pgsu', - kAEPaste = 'past', - kAEPlain = 'plan', - kAEPrint = 'pdoc', - kAEPrintSelection = 'spri', - kAEPrintWindow = 'pwin', - kAEPutAwaySelection = 'sput', - kAEQDAddOver = 'addo', - kAEQDAddPin = 'addp', - kAEQDAdMax = 'admx', - kAEQDAdMin = 'admn', - kAEQDBic = 'bic ', - kAEQDBlend = 'blnd', - kAEQDCopy = 'cpy ', - kAEQDNotBic = 'nbic', - kAEQDNotCopy = 'ncpy' -}; - -enum { - kAEQDNotOr = 'ntor', - kAEQDNotXor = 'nxor', - kAEQDOr = 'or ', - kAEQDSubOver = 'subo', - kAEQDSubPin = 'subp', - kAEQDSupplementalSuite = 'qdsp', - kAEQDXor = 'xor ', - kAEQuickdrawSuite = 'qdrw', - kAEQuitAll = 'quia', - kAERedo = 'redo', - kAERegular = 'regl', - kAEReopenApplication = 'rapp', - kAEReplace = 'rplc', - kAERequiredSuite = 'reqd', - kAERestart = 'rest', - kAERevealSelection = 'srev', - kAERevert = 'rvrt', - kAERightJustified = 'rght', - kAESave = 'save', - kAESelect = 'slct', - kAESetData = 'setd' -}; - -enum { - kAESetPosition = 'posn', - kAEShadow = 'shad', - kAEShowClipboard = 'shcl', - kAEShutDown = 'shut', - kAESleep = 'slep', - kAESmallCaps = 'smcp', - kAESpecialClassProperties = 'c@#!', - kAEStrikethrough = 'strk', - kAESubscript = 'sbsc', - kAESuperscript = 'spsc', - kAETableSuite = 'tbls', - kAETextSuite = 'TEXT', - kAETransactionTerminated = 'ttrm', - kAEUnderline = 'undl', - kAEUndo = 'undo', - kAEWholeWordEquals = 'wweq', - kAEYes = 'yes ', - kAEZoom = 'zoom' -}; - - -enum { - kAELogOut = 'logo', - kAEReallyLogOut = 'rlgo', - kAEShowRestartDialog = 'rrst', - kAEShowShutdownDialog = 'rsdn' -}; - - -enum { - kAEMouseClass = 'mous', - kAEDown = 'down', - kAEUp = 'up ', - kAEMoved = 'move', - kAEStoppedMoving = 'stop', - kAEWindowClass = 'wind', - kAEUpdate = 'updt', - kAEActivate = 'actv', - kAEDeactivate = 'dact', - kAECommandClass = 'cmnd', - kAEKeyClass = 'keyc', - kAERawKey = 'rkey', - kAEVirtualKey = 'keyc', - kAENavigationKey = 'nave', - kAEAutoDown = 'auto', - kAEApplicationClass = 'appl', - kAESuspend = 'susp', - kAEResume = 'rsme', - kAEDiskEvent = 'disk', - kAENullEvent = 'null', - kAEWakeUpEvent = 'wake', - kAEScrapEvent = 'scrp', - kAEHighLevel = 'high' -}; - -enum { - keyAEAngle = 'kang', - keyAEArcAngle = 'parc' -}; - -enum { - keyAEBaseAddr = 'badd', - keyAEBestType = 'pbst', - keyAEBgndColor = 'kbcl', - keyAEBgndPattern = 'kbpt', - keyAEBounds = 'pbnd', - keyAECellList = 'kclt', - keyAEClassID = 'clID', - keyAEColor = 'colr', - keyAEColorTable = 'cltb', - keyAECurveHeight = 'kchd', - keyAECurveWidth = 'kcwd', - keyAEDashStyle = 'pdst', - keyAEData = 'data', - keyAEDefaultType = 'deft', - keyAEDefinitionRect = 'pdrt', - keyAEDescType = 'dstp', - keyAEDestination = 'dest', - keyAEDoAntiAlias = 'anta', - keyAEDoDithered = 'gdit', - keyAEDoRotate = 'kdrt' -}; - -enum { - keyAEDoScale = 'ksca', - keyAEDoTranslate = 'ktra', - keyAEEditionFileLoc = 'eloc', - keyAEElements = 'elms', - keyAEEndPoint = 'pend', - keyAEEventClass = 'evcl', - keyAEEventID = 'evti', - keyAEFile = 'kfil', - keyAEFileType = 'fltp', - keyAEFillColor = 'flcl', - keyAEFillPattern = 'flpt', - keyAEFlipHorizontal = 'kfho', - keyAEFlipVertical = 'kfvt', - keyAEFont = 'font', - keyAEFormula = 'pfor', - keyAEGraphicObjects = 'gobs', - keyAEID = 'ID ', - keyAEImageQuality = 'gqua', - keyAEInsertHere = 'insh', - keyAEKeyForms = 'keyf' -}; - -enum { - keyAEKeyword = 'kywd', - keyAELevel = 'levl', - keyAELineArrow = 'arro', - keyAEName = 'pnam', - keyAENewElementLoc = 'pnel', - keyAEObject = 'kobj', - keyAEObjectClass = 'kocl', - keyAEOffStyles = 'ofst', - keyAEOnStyles = 'onst', - keyAEParameters = 'prms', - keyAEParamFlags = 'pmfg', - keyAEPenColor = 'ppcl', - keyAEPenPattern = 'pppa', - keyAEPenWidth = 'ppwd', - keyAEPixelDepth = 'pdpt', - keyAEPixMapMinus = 'kpmm', - keyAEPMTable = 'kpmt', - keyAEPointList = 'ptlt', - keyAEPointSize = 'ptsz', - keyAEPosition = 'kpos' -}; - -enum { - keyAEPropData = 'prdt', - keyAEProperties = 'qpro', - keyAEProperty = 'kprp', - keyAEPropFlags = 'prfg', - keyAEPropID = 'prop', - keyAEProtection = 'ppro', - keyAERenderAs = 'kren', - keyAERequestedType = 'rtyp', - keyAEResult = '----', - keyAEResultInfo = 'rsin', - keyAERotation = 'prot', - keyAERotPoint = 'krtp', - keyAERowList = 'krls', - keyAESaveOptions = 'savo', - keyAEScale = 'pscl', - keyAEScriptTag = 'psct', - keyAESearchText = 'stxt', - keyAEShowWhere = 'show', - keyAEStartAngle = 'pang', - keyAEStartPoint = 'pstp', - keyAEStyles = 'ksty' -}; - -enum { - keyAESuiteID = 'suit', - keyAEText = 'ktxt', - keyAETextColor = 'ptxc', - keyAETextFont = 'ptxf', - keyAETextPointSize = 'ptps', - keyAETextStyles = 'txst', - keyAETextLineHeight = 'ktlh', - keyAETextLineAscent = 'ktas', - keyAETheText = 'thtx', - keyAETransferMode = 'pptm', - keyAETranslation = 'ptrs', - keyAETryAsStructGraf = 'toog', - keyAEUniformStyles = 'ustl', - keyAEUpdateOn = 'pupd', - keyAEUserTerm = 'utrm', - keyAEWindow = 'wndw', - keyAEWritingCode = 'wrcd' -}; - -enum { - keyMiscellaneous = 'fmsc', - keySelection = 'fsel', - keyWindow = 'kwnd', - - keyWhen = 'when', - keyWhere = 'wher', - keyModifiers = 'mods', - keyKey = 'key ', - keyKeyCode = 'code', - keyKeyboard = 'keyb', - keyDriveNumber = 'drv#', - keyErrorCode = 'err#', - keyHighLevelClass = 'hcls', - keyHighLevelID = 'hid ' -}; - -enum { - pArcAngle = 'parc', - pBackgroundColor = 'pbcl', - pBackgroundPattern = 'pbpt', - pBestType = 'pbst', - pBounds = 'pbnd', - pClass = 'pcls', - pClipboard = 'pcli', - pColor = 'colr', - pColorTable = 'cltb', - pContents = 'pcnt', - pCornerCurveHeight = 'pchd', - pCornerCurveWidth = 'pcwd', - pDashStyle = 'pdst', - pDefaultType = 'deft', - pDefinitionRect = 'pdrt', - pEnabled = 'enbl', - pEndPoint = 'pend', - pFillColor = 'flcl', - pFillPattern = 'flpt', - pFont = 'font' -}; - -enum { - pFormula = 'pfor', - pGraphicObjects = 'gobs', - pHasCloseBox = 'hclb', - pHasTitleBar = 'ptit', - pID = 'ID ', - pIndex = 'pidx', - pInsertionLoc = 'pins', - pIsFloating = 'isfl', - pIsFrontProcess = 'pisf', - pIsModal = 'pmod', - pIsModified = 'imod', - pIsResizable = 'prsz', - pIsStationeryPad = 'pspd', - pIsZoomable = 'iszm', - pIsZoomed = 'pzum', - pItemNumber = 'itmn', - pJustification = 'pjst', - pLineArrow = 'arro', - pMenuID = 'mnid', - pName = 'pnam' -}; - -enum { - pNewElementLoc = 'pnel', - pPenColor = 'ppcl', - pPenPattern = 'pppa', - pPenWidth = 'ppwd', - pPixelDepth = 'pdpt', - pPointList = 'ptlt', - pPointSize = 'ptsz', - pProtection = 'ppro', - pRotation = 'prot', - pScale = 'pscl', - pScript = 'scpt', - pScriptTag = 'psct', - pSelected = 'selc', - pSelection = 'sele', - pStartAngle = 'pang', - pStartPoint = 'pstp', - pTextColor = 'ptxc', - pTextFont = 'ptxf', - pTextItemDelimiters = 'txdl', - pTextPointSize = 'ptps' -}; - -enum { - pTextStyles = 'txst', - pTransferMode = 'pptm', - pTranslation = 'ptrs', - pUniformStyles = 'ustl', - pUpdateOn = 'pupd', - pUserSelection = 'pusl', - pVersion = 'vers', - pVisible = 'pvis' -}; - -enum { - typeAEText = 'tTXT', - typeArc = 'carc', - typeBest = 'best', - typeCell = 'ccel', - typeClassInfo = 'gcli', - typeColorTable = 'clrt', - typeColumn = 'ccol', - typeDashStyle = 'tdas', - typeData = 'tdta', - typeDrawingArea = 'cdrw', - typeElemInfo = 'elin', - typeEnumeration = 'enum', - typeEPS = 'EPS ', - typeEventInfo = 'evin' -}; - -enum { - typeFinderWindow = 'fwin', - typeFixedPoint = 'fpnt', - typeFixedRectangle = 'frct', - typeGraphicLine = 'glin', - typeGraphicText = 'cgtx', - typeGroupedGraphic = 'cpic', - typeInsertionLoc = 'insl', - typeIntlText = 'itxt', - typeIntlWritingCode = 'intl', - typeLongDateTime = 'ldt ', - typeCFAbsoluteTime = 'cfat', - typeISO8601DateTime = 'isot', - typeLongFixed = 'lfxd', - typeLongFixedPoint = 'lfpt', - typeLongFixedRectangle = 'lfrc', - typeLongPoint = 'lpnt', - typeLongRectangle = 'lrct', - typeMachineLoc = 'mLoc', - typeOval = 'covl', - typeParamInfo = 'pmin', - typePict = 'PICT' -}; - -enum { - typePixelMap = 'cpix', - typePixMapMinus = 'tpmm', - typePolygon = 'cpgn', - typePropInfo = 'pinf', - typePtr = 'ptr ', - typeQDPoint = 'QDpt', - typeQDRegion = 'Qrgn', - typeRectangle = 'crec', - typeRGB16 = 'tr16', - typeRGB96 = 'tr96', - typeRGBColor = 'cRGB', - typeRotation = 'trot', - typeRoundedRectangle = 'crrc', - typeRow = 'crow', - typeScrapStyles = 'styl', - typeScript = 'scpt', - typeStyledText = 'STXT', - typeSuiteInfo = 'suin', - typeTable = 'ctbl', - typeTextStyles = 'tsty' -}; - -enum { - typeTIFF = 'TIFF', - typeJPEG = 'JPEG', - typeGIF = 'GIFf', - typeVersion = 'vers' -}; - -enum { - kAEMenuClass = 'menu', - kAEMenuSelect = 'mhit', - kAEMouseDown = 'mdwn', - kAEMouseDownInBack = 'mdbk', - kAEKeyDown = 'kdwn', - kAEResized = 'rsiz', - kAEPromise = 'prom' -}; - -enum { - keyMenuID = 'mid ', - keyMenuItem = 'mitm', - keyCloseAllWindows = 'caw ', - keyOriginalBounds = 'obnd', - keyNewBounds = 'nbnd', - keyLocalWhere = 'lwhr' -}; - -enum { - typeHIMenu = 'mobj', - typeHIWindow = 'wobj' -}; - -enum { - kAEQuitPreserveState = 'stat', - - kAEQuitReason = 'why?' -}; - -enum { - kBySmallIcon = 0, - kByIconView = 1, - kByNameView = 2, - kByDateView = 3, - kBySizeView = 4, - kByKindView = 5, - kByCommentView = 6, - kByLabelView = 7, - kByVersionView = 8 -}; - -enum { - kAEInfo = 11, - kAEMain = 0, - kAESharing = 13 -}; - -enum { - kAEZoomIn = 7, - kAEZoomOut = 8 -}; - -enum { - kTextServiceClass = 'tsvc', - kUpdateActiveInputArea = 'updt', - kShowHideInputWindow = 'shiw', - kPos2Offset = 'p2st', - kOffset2Pos = 'st2p', - kUnicodeNotFromInputMethod = 'unim', - kGetSelectedText = 'gtxt', - keyAETSMDocumentRefcon = 'refc', - keyAEServerInstance = 'srvi', - keyAETheData = 'kdat', - keyAEFixLength = 'fixl', - keyAEUpdateRange = 'udng', - keyAECurrentPoint = 'cpos', - keyAEBufferSize = 'buff', - keyAEMoveView = 'mvvw', - keyAENextBody = 'nxbd', - keyAETSMScriptTag = 'sclg', - keyAETSMTextFont = 'ktxf', - keyAETSMTextFMFont = 'ktxm', - keyAETSMTextPointSize = 'ktps', - keyAETSMEventRecord = 'tevt', - keyAETSMEventRef = 'tevr', - keyAETextServiceEncoding = 'tsen', - keyAETextServiceMacEncoding = 'tmen', - keyAETSMGlyphInfoArray = 'tgia', - typeTextRange = 'txrn', - typeComponentInstance = 'cmpi', - typeOffsetArray = 'ofay', - typeTextRangeArray = 'tray', - typeLowLevelEventRecord = 'evtr', - typeGlyphInfoArray = 'glia', - typeEventRef = 'evrf', - typeText = typeChar -}; - - - -enum { - kTSMOutsideOfBody = 1, - kTSMInsideOfBody = 2, - kTSMInsideOfActiveInputArea = 3 -}; - -enum { - kNextBody = 1, - kPreviousBody = 2 -}; - -struct TextRange { - SInt32 fStart; - SInt32 fEnd; - SInt16 fHiliteStyle; -}; -typedef struct TextRange TextRange; -typedef TextRange * TextRangePtr; -typedef TextRangePtr * TextRangeHandle; -struct TextRangeArray { - SInt16 fNumOfRanges; - TextRange fRange[1]; -}; -typedef struct TextRangeArray TextRangeArray; -typedef TextRangeArray * TextRangeArrayPtr; -typedef TextRangeArrayPtr * TextRangeArrayHandle; -struct OffsetArray { - SInt16 fNumOfOffsets; - SInt32 fOffset[1]; -}; -typedef struct OffsetArray OffsetArray; -typedef OffsetArray * OffsetArrayPtr; -typedef OffsetArrayPtr * OffsetArrayHandle; -struct WritingCode { - ScriptCode theScriptCode; - LangCode theLangCode; -}; -typedef struct WritingCode WritingCode; -struct IntlText { - ScriptCode theScriptCode; - LangCode theLangCode; - char theText[1]; -}; -typedef struct IntlText IntlText; - - -enum { - kTSMHiliteCaretPosition = 1, - kTSMHiliteRawText = 2, - kTSMHiliteSelectedRawText = 3, - kTSMHiliteConvertedText = 4, - kTSMHiliteSelectedConvertedText = 5, - kTSMHiliteBlockFillText = 6, - kTSMHiliteOutlineText = 7, - kTSMHiliteSelectedText = 8, - kTSMHiliteNoHilite = 9 -}; -enum { - keyAEHiliteRange = 'hrng', - keyAEPinRange = 'pnrg', - keyAEClauseOffsets = 'clau', - keyAEOffset = 'ofst', - keyAEPoint = 'gpos', - keyAELeftSide = 'klef', - keyAERegionClass = 'rgnc', - keyAEDragging = 'bool' -}; -enum { - - typeMeters = 'metr', - typeInches = 'inch', - typeFeet = 'feet', - typeYards = 'yard', - typeMiles = 'mile', - typeKilometers = 'kmtr', - typeCentimeters = 'cmtr', - typeSquareMeters = 'sqrm', - typeSquareFeet = 'sqft', - typeSquareYards = 'sqyd', - typeSquareMiles = 'sqmi', - typeSquareKilometers = 'sqkm', - typeLiters = 'litr', - typeQuarts = 'qrts', - typeGallons = 'galn', - typeCubicMeters = 'cmet', - typeCubicFeet = 'cfet', - typeCubicInches = 'cuin', - typeCubicCentimeter = 'ccmt', - typeCubicYards = 'cyrd', - typeKilograms = 'kgrm', - typeGrams = 'gram', - typeOunces = 'ozs ', - typePounds = 'lbs ', - typeDegreesC = 'degc', - typeDegreesF = 'degf', - typeDegreesK = 'degk' -}; - -enum { - - kFAServerApp = 'ssrv', - kDoFolderActionEvent = 'fola', - kFolderActionCode = 'actn', - kFolderOpenedEvent = 'fopn', - kFolderClosedEvent = 'fclo', - kFolderWindowMovedEvent = 'fsiz', - kFolderItemsAddedEvent = 'fget', - kFolderItemsRemovedEvent = 'flos', - kItemList = 'flst', - kNewSizeParameter = 'fnsz', - kFASuiteCode = 'faco', - kFAAttachCommand = 'atfa', - kFARemoveCommand = 'rmfa', - kFAEditCommand = 'edfa', - kFAFileParam = 'faal', - kFAIndexParam = 'indx' -}; - - -enum { - - kAEInternetSuite = 'gurl', - kAEISWebStarSuite = 0x575757BD -}; - -enum { - - kAEISGetURL = 'gurl', - KAEISHandleCGI = 'sdoc' -}; - -enum { - - cURL = 'url ', - cInternetAddress = 'IPAD', - cHTML = 'html', - cFTPItem = 'ftp ' -}; - -enum { - - kAEISHTTPSearchArgs = 'kfor', - kAEISPostArgs = 'post', - kAEISMethod = 'meth', - kAEISClientAddress = 'addr', - kAEISUserName = 'user', - kAEISPassword = 'pass', - kAEISFromUser = 'frmu', - kAEISServerName = 'svnm', - kAEISServerPort = 'svpt', - kAEISScriptName = 'scnm', - kAEISContentType = 'ctyp', - kAEISReferrer = 'refr', - kAEISUserAgent = 'Agnt', - kAEISAction = 'Kact', - kAEISActionPath = 'Kapt', - kAEISClientIP = 'Kcip', - kAEISFullRequest = 'Kfrq' -}; - -enum { - - pScheme = 'pusc', - pHost = 'HOST', - pPath = 'FTPc', - pUserName = 'RAun', - pUserPassword = 'RApw', - pDNSForm = 'pDNS', - pURL = 'pURL', - pTextEncoding = 'ptxe', - pFTPKind = 'kind' -}; - -enum { - - eScheme = 'esch', - eurlHTTP = 'http', - eurlHTTPS = 'htps', - eurlFTP = 'ftp ', - eurlMail = 'mail', - eurlFile = 'file', - eurlGopher = 'gphr', - eurlTelnet = 'tlnt', - eurlNews = 'news', - eurlSNews = 'snws', - eurlNNTP = 'nntp', - eurlMessage = 'mess', - eurlMailbox = 'mbox', - eurlMulti = 'mult', - eurlLaunch = 'laun', - eurlAFP = 'afp ', - eurlAT = 'at ', - eurlEPPC = 'eppc', - eurlRTSP = 'rtsp', - eurlIMAP = 'imap', - eurlNFS = 'unfs', - eurlPOP = 'upop', - eurlLDAP = 'uldp', - eurlUnknown = 'url?' -}; - -enum { - - kConnSuite = 'macc', - cDevSpec = 'cdev', - cAddressSpec = 'cadr', - cADBAddress = 'cadb', - cAppleTalkAddress = 'cat ', - cBusAddress = 'cbus', - cEthernetAddress = 'cen ', - cFireWireAddress = 'cfw ', - cIPAddress = 'cip ', - cLocalTalkAddress = 'clt ', - cSCSIAddress = 'cscs', - cTokenRingAddress = 'ctok', - cUSBAddress = 'cusb', - - pDeviceType = 'pdvt', - pDeviceAddress = 'pdva', - pConduit = 'pcon', - pProtocol = 'pprt', - pATMachine = 'patm', - pATZone = 'patz', - pATType = 'patt', - pDottedDecimal = 'pipd', - pDNS = 'pdns', - pPort = 'ppor', - pNetwork = 'pnet', - pNode = 'pnod', - pSocket = 'psoc', - pSCSIBus = 'pscb', - pSCSILUN = 'pslu', - - eDeviceType = 'edvt', - eAddressSpec = 'eads', - eConduit = 'econ', - eProtocol = 'epro', - eADB = 'eadb', - eAnalogAudio = 'epau', - eAppleTalk = 'epat', - eAudioLineIn = 'ecai', - eAudioLineOut = 'ecal', - eAudioOut = 'ecao', - eBus = 'ebus', - eCDROM = 'ecd ', - eCommSlot = 'eccm', - eDigitalAudio = 'epda', - eDisplay = 'edds', - eDVD = 'edvd', - eEthernet = 'ecen', - eFireWire = 'ecfw', - eFloppy = 'efd ', - eHD = 'ehd ', - eInfrared = 'ecir', - eIP = 'epip', - eIrDA = 'epir', - eIRTalk = 'epit', - eKeyboard = 'ekbd', - eLCD = 'edlc', - eLocalTalk = 'eclt', - eMacIP = 'epmi', - eMacVideo = 'epmv', - eMicrophone = 'ecmi', - eModemPort = 'ecmp', - eModemPrinterPort = 'empp', - eModem = 'edmm', - eMonitorOut = 'ecmn', - eMouse = 'emou', - eNuBusCard = 'ednb', - eNuBus = 'enub', - ePCcard = 'ecpc', - ePCIbus = 'ecpi', - ePCIcard = 'edpi', - ePDSslot = 'ecpd', - ePDScard = 'epds', - ePointingDevice = 'edpd', - ePostScript = 'epps', - ePPP = 'eppp', - ePrinterPort = 'ecpp', - ePrinter = 'edpr', - eSvideo = 'epsv', - eSCSI = 'ecsc', - eSerial = 'epsr', - eSpeakers = 'edsp', - eStorageDevice = 'edst', - eSVGA = 'epsg', - eTokenRing = 'etok', - eTrackball = 'etrk', - eTrackpad = 'edtp', - eUSB = 'ecus', - eVideoIn = 'ecvi', - eVideoMonitor = 'edvm', - eVideoOut = 'ecvo' -}; - -enum { - - cKeystroke = 'kprs', - pKeystrokeKey = 'kMsg', - pModifiers = 'kMod', - pKeyKind = 'kknd', - eModifiers = 'eMds', - eOptionDown = 'Kopt', - eCommandDown = 'Kcmd', - eControlDown = 'Kctl', - eShiftDown = 'Ksft', - eCapsLockDown = 'Kclk', - eKeyKind = 'ekst', - - eEscapeKey = 0x6B733500, - eDeleteKey = 0x6B733300, - eTabKey = 0x6B733000, - eReturnKey = 0x6B732400, - eClearKey = 0x6B734700, - eEnterKey = 0x6B734C00, - eUpArrowKey = 0x6B737E00, - eDownArrowKey = 0x6B737D00, - eLeftArrowKey = 0x6B737B00, - eRightArrowKey = 0x6B737C00, - eHelpKey = 0x6B737200, - eHomeKey = 0x6B737300, - ePageUpKey = 0x6B737400, - ePageDownKey = 0x6B737900, - eForwardDelKey = 0x6B737500, - eEndKey = 0x6B737700, - eF1Key = 0x6B737A00, - eF2Key = 0x6B737800, - eF3Key = 0x6B736300, - eF4Key = 0x6B737600, - eF5Key = 0x6B736000, - eF6Key = 0x6B736100, - eF7Key = 0x6B736200, - eF8Key = 0x6B736400, - eF9Key = 0x6B736500, - eF10Key = 0x6B736D00, - eF11Key = 0x6B736700, - eF12Key = 0x6B736F00, - eF13Key = 0x6B736900, - eF14Key = 0x6B736B00, - eF15Key = 0x6B737100 -}; - -enum { - keyAELaunchedAsLogInItem = 'lgit', - keyAELaunchedAsServiceItem = 'svit' -}; - - -#pragma pack(pop) - - - -#pragma pack(push, 2) - -enum { - kAEUserTerminology = 'aeut', - kAETerminologyExtension = 'aete', - kAEScriptingSizeResource = 'scsz', - kAEOSAXSizeResource = 'osiz' -}; - -enum { - kAEUTHasReturningParam = 31, - kAEUTOptional = 15, - kAEUTlistOfItems = 14, - kAEUTEnumerated = 13, - kAEUTReadWrite = 12, - kAEUTChangesState = 12, - kAEUTTightBindingFunction = 12, - - kAEUTEnumsAreTypes = 11, - kAEUTEnumListIsExclusive = 10, - kAEUTReplyIsReference = 9, - kAEUTDirectParamIsReference = 9, - kAEUTParamIsReference = 9, - kAEUTPropertyIsReference = 9, - kAEUTNotDirectParamIsTarget = 8, - kAEUTParamIsTarget = 8, - kAEUTApostrophe = 3, - kAEUTFeminine = 2, - kAEUTMasculine = 1, - kAEUTPlural = 0 -}; - -struct TScriptingSizeResource { - SInt16 scriptingSizeFlags; - UInt32 minStackSize; - UInt32 preferredStackSize; - UInt32 maxStackSize; - UInt32 minHeapSize; - UInt32 preferredHeapSize; - UInt32 maxHeapSize; -}; -typedef struct TScriptingSizeResource TScriptingSizeResource; -enum { - kLaunchToGetTerminology = (1 << 15), - kDontFindAppBySignature = (1 << 14), - kAlwaysSendSubject = (1 << 13) -}; - - -enum { - kReadExtensionTermsMask = (1 << 15) -}; - -enum { - - - kOSIZDontOpenResourceFile = 15, - kOSIZdontAcceptRemoteEvents = 14, - kOSIZOpenWithReadPermission = 13, - kOSIZCodeInSharedLibraries = 11 -}; - - -#pragma pack(pop) - - - -extern "C" { - - -#pragma pack(push, 2) -typedef UInt32 AEBuildErrorCode; -enum { - aeBuildSyntaxNoErr = 0, - aeBuildSyntaxBadToken = 1, - aeBuildSyntaxBadEOF = 2, - aeBuildSyntaxNoEOF = 3, - aeBuildSyntaxBadNegative = 4, - aeBuildSyntaxMissingQuote = 5, - aeBuildSyntaxBadHex = 6, - aeBuildSyntaxOddHex = 7, - aeBuildSyntaxNoCloseHex = 8, - aeBuildSyntaxUncoercedHex = 9, - aeBuildSyntaxNoCloseString = 10, - aeBuildSyntaxBadDesc = 11, - aeBuildSyntaxBadData = 12, - aeBuildSyntaxNoCloseParen = 13, - aeBuildSyntaxNoCloseBracket = 14, - aeBuildSyntaxNoCloseBrace = 15, - aeBuildSyntaxNoKey = 16, - aeBuildSyntaxNoColon = 17, - aeBuildSyntaxCoercedList = 18, - aeBuildSyntaxUncoercedDoubleAt = 19 -}; - - - -struct AEBuildError { - AEBuildErrorCode fError; - UInt32 fErrorPos; -}; -typedef struct AEBuildError AEBuildError; -extern OSStatus -AEBuildDesc( - AEDesc * dst, - AEBuildError * error, - const char * src, - ...) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -vAEBuildDesc( - AEDesc * dst, - AEBuildError * error, - const char * src, - va_list args) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEBuildParameters( - AppleEvent * event, - AEBuildError * error, - const char * format, - ...) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -vAEBuildParameters( - AppleEvent * event, - AEBuildError * error, - const char * format, - va_list args) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEBuildAppleEvent( - AEEventClass theClass, - AEEventID theID, - DescType addressType, - const void * addressData, - Size addressLength, - SInt16 returnID, - SInt32 transactionID, - AppleEvent * result, - AEBuildError * error, - const char * paramsFmt, - ...) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -vAEBuildAppleEvent( - AEEventClass theClass, - AEEventID theID, - DescType addressType, - const void * addressData, - Size addressLength, - SInt16 returnID, - SInt32 transactionID, - AppleEvent * resultEvt, - AEBuildError * error, - const char * paramsFmt, - va_list args) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEPrintDescToHandle( - const AEDesc * desc, - Handle * result) __attribute__((availability(macosx,introduced=10.0))); -typedef struct OpaqueAEStreamRef* AEStreamRef; -extern AEStreamRef -AEStreamOpen(void) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamClose( - AEStreamRef ref, - AEDesc * desc) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamOpenDesc( - AEStreamRef ref, - DescType newType) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamWriteData( - AEStreamRef ref, - const void * data, - Size length) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamCloseDesc(AEStreamRef ref) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamWriteDesc( - AEStreamRef ref, - DescType newType, - const void * data, - Size length) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamWriteAEDesc( - AEStreamRef ref, - const AEDesc * desc) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamOpenList(AEStreamRef ref) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamCloseList(AEStreamRef ref) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamOpenRecord( - AEStreamRef ref, - DescType newType) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamSetRecordType( - AEStreamRef ref, - DescType newType) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamCloseRecord(AEStreamRef ref) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamWriteKeyDesc( - AEStreamRef ref, - AEKeyword key, - DescType newType, - const void * data, - Size length) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamOpenKeyDesc( - AEStreamRef ref, - AEKeyword key, - DescType newType) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamWriteKey( - AEStreamRef ref, - AEKeyword key) __attribute__((availability(macosx,introduced=10.0))); -extern AEStreamRef -AEStreamCreateEvent( - AEEventClass clazz, - AEEventID id, - DescType targetType, - const void * targetData, - Size targetLength, - SInt16 returnID, - SInt32 transactionID) __attribute__((availability(macosx,introduced=10.0))); -extern AEStreamRef -AEStreamOpenEvent(AppleEvent * event) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEStreamOptionalParam( - AEStreamRef ref, - AEKeyword key) __attribute__((availability(macosx,introduced=10.0))); - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - - -} -extern "C" { -enum { - keyReplyPortAttr = 'repp' -}; - - -enum { - typeReplyPortAttr = keyReplyPortAttr -}; -extern mach_port_t -AEGetRegisteredMachPort(void) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEDecodeMessage( - mach_msg_header_t * header, - AppleEvent * event, - AppleEvent * reply) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AEProcessMessage(mach_msg_header_t * header) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -AESendMessage( - const AppleEvent * event, - AppleEvent * reply, - AESendMode sendMode, - long timeOutInTicks) __attribute__((availability(macosx,introduced=10.0))); - - - - - -} - - - - - - - - - - -extern "C" { -extern const CFStringRef kCFErrorDomainCFNetwork __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFErrorDomainWinSock __attribute__((availability(macosx,introduced=10_5))); -typedef int CFNetworkErrors; enum { - - kCFHostErrorHostNotFound = 1, - kCFHostErrorUnknown = 2, - - kCFSOCKSErrorUnknownClientVersion = 100, - kCFSOCKSErrorUnsupportedServerVersion = 101, - - kCFSOCKS4ErrorRequestFailed = 110, - kCFSOCKS4ErrorIdentdFailed = 111, - kCFSOCKS4ErrorIdConflict = 112, - kCFSOCKS4ErrorUnknownStatusCode = 113, - - kCFSOCKS5ErrorBadState = 120, - kCFSOCKS5ErrorBadResponseAddr = 121, - kCFSOCKS5ErrorBadCredentials = 122, - kCFSOCKS5ErrorUnsupportedNegotiationMethod = 123, - kCFSOCKS5ErrorNoAcceptableMethod = 124, - - kCFFTPErrorUnexpectedStatusCode = 200, - - kCFErrorHTTPAuthenticationTypeUnsupported = 300, - kCFErrorHTTPBadCredentials = 301, - kCFErrorHTTPConnectionLost = 302, - kCFErrorHTTPParseFailure = 303, - kCFErrorHTTPRedirectionLoopDetected = 304, - kCFErrorHTTPBadURL = 305, - kCFErrorHTTPProxyConnectionFailure = 306, - kCFErrorHTTPBadProxyCredentials = 307, - kCFErrorPACFileError = 308, - kCFErrorPACFileAuth = 309, - kCFErrorHTTPSProxyConnectionFailure = 310, - kCFStreamErrorHTTPSProxyFailureUnexpectedResponseToCONNECTMethod = 311, - - - kCFURLErrorBackgroundSessionInUseByAnotherProcess = -996, - kCFURLErrorBackgroundSessionWasDisconnected = -997, - kCFURLErrorUnknown = -998, - kCFURLErrorCancelled = -999, - kCFURLErrorBadURL = -1000, - kCFURLErrorTimedOut = -1001, - kCFURLErrorUnsupportedURL = -1002, - kCFURLErrorCannotFindHost = -1003, - kCFURLErrorCannotConnectToHost = -1004, - kCFURLErrorNetworkConnectionLost = -1005, - kCFURLErrorDNSLookupFailed = -1006, - kCFURLErrorHTTPTooManyRedirects = -1007, - kCFURLErrorResourceUnavailable = -1008, - kCFURLErrorNotConnectedToInternet = -1009, - kCFURLErrorRedirectToNonExistentLocation = -1010, - kCFURLErrorBadServerResponse = -1011, - kCFURLErrorUserCancelledAuthentication = -1012, - kCFURLErrorUserAuthenticationRequired = -1013, - kCFURLErrorZeroByteResource = -1014, - kCFURLErrorCannotDecodeRawData = -1015, - kCFURLErrorCannotDecodeContentData = -1016, - kCFURLErrorCannotParseResponse = -1017, - kCFURLErrorInternationalRoamingOff = -1018, - kCFURLErrorCallIsActive = -1019, - kCFURLErrorDataNotAllowed = -1020, - kCFURLErrorRequestBodyStreamExhausted = -1021, - kCFURLErrorAppTransportSecurityRequiresSecureConnection = -1022, - kCFURLErrorFileDoesNotExist = -1100, - kCFURLErrorFileIsDirectory = -1101, - kCFURLErrorNoPermissionsToReadFile = -1102, - kCFURLErrorDataLengthExceedsMaximum = -1103, - - kCFURLErrorSecureConnectionFailed = -1200, - kCFURLErrorServerCertificateHasBadDate = -1201, - kCFURLErrorServerCertificateUntrusted = -1202, - kCFURLErrorServerCertificateHasUnknownRoot = -1203, - kCFURLErrorServerCertificateNotYetValid = -1204, - kCFURLErrorClientCertificateRejected = -1205, - kCFURLErrorClientCertificateRequired = -1206, - kCFURLErrorCannotLoadFromNetwork = -2000, - - kCFURLErrorCannotCreateFile = -3000, - kCFURLErrorCannotOpenFile = -3001, - kCFURLErrorCannotCloseFile = -3002, - kCFURLErrorCannotWriteToFile = -3003, - kCFURLErrorCannotRemoveFile = -3004, - kCFURLErrorCannotMoveFile = -3005, - kCFURLErrorDownloadDecodingFailedMidStream = -3006, - kCFURLErrorDownloadDecodingFailedToComplete = -3007, - - - kCFHTTPCookieCannotParseCookieFile = -4000, - - - kCFNetServiceErrorUnknown = -72000L, - kCFNetServiceErrorCollision = -72001L, - kCFNetServiceErrorNotFound = -72002L, - kCFNetServiceErrorInProgress = -72003L, - kCFNetServiceErrorBadArgument = -72004L, - kCFNetServiceErrorCancel = -72005L, - kCFNetServiceErrorInvalid = -72006L, - kCFNetServiceErrorTimeout = -72007L, - kCFNetServiceErrorDNSServiceFailure = -73000L -}; -extern const CFStringRef kCFURLErrorFailingURLErrorKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFURLErrorFailingURLStringErrorKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFGetAddrInfoFailureKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFSOCKSStatusCodeKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFSOCKSVersionKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFSOCKSNegotiationMethodKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFDNSServiceFailureKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFFTPStatusCodeKey __attribute__((availability(macosx,introduced=10_5))); - - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - - - - - - - - -typedef struct __CFHost* CFHostRef; -extern const SInt32 kCFStreamErrorDomainNetDB __attribute__((availability(macosx,introduced=10_3))); -extern const SInt32 kCFStreamErrorDomainSystemConfiguration __attribute__((availability(macosx,introduced=10_3))); -typedef int CFHostInfoType; enum { - - - - - - kCFHostAddresses = 0, - - - - - kCFHostNames = 1, - - - - - - kCFHostReachability = 2 -}; -struct CFHostClientContext { - - - - - - - CFIndex version; - - - - - - void * _Nullable info; - CFAllocatorRetainCallBack _Nullable retain; - - - - - - CFAllocatorReleaseCallBack _Nullable release; - - - - - - - - CFAllocatorCopyDescriptionCallBack copyDescription; -}; -typedef struct CFHostClientContext CFHostClientContext; -typedef void ( * CFHostClientCallBack)(CFHostRef theHost, CFHostInfoType typeInfo, const CFStreamError * _Nullable error, void * _Nullable info); -extern CFTypeID -CFHostGetTypeID(void) __attribute__((availability(macosx,introduced=10_3))); -extern CFHostRef -CFHostCreateWithName(CFAllocatorRef _Nullable allocator, CFStringRef hostname) __attribute__((availability(macosx,introduced=10_3))); -extern CFHostRef -CFHostCreateWithAddress(CFAllocatorRef _Nullable allocator, CFDataRef addr) __attribute__((availability(macosx,introduced=10_3))); -extern CFHostRef -CFHostCreateCopy(CFAllocatorRef _Nullable alloc, CFHostRef host) __attribute__((availability(macosx,introduced=10_3))); -extern Boolean -CFHostStartInfoResolution(CFHostRef theHost, CFHostInfoType info, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_3))); -extern _Nullable CFArrayRef -CFHostGetAddressing(CFHostRef theHost, Boolean * _Nullable hasBeenResolved) __attribute__((availability(macosx,introduced=10_3))); -extern _Nullable CFArrayRef -CFHostGetNames(CFHostRef theHost, Boolean * _Nullable hasBeenResolved) __attribute__((availability(macosx,introduced=10_3))); -extern _Nullable CFDataRef -CFHostGetReachability(CFHostRef theHost, Boolean * _Nullable hasBeenResolved) __attribute__((availability(macosx,introduced=10_3))); -extern void -CFHostCancelInfoResolution(CFHostRef theHost, CFHostInfoType info) __attribute__((availability(macosx,introduced=10_3))); -extern Boolean -CFHostSetClient(CFHostRef theHost, CFHostClientCallBack _Nullable clientCB, CFHostClientContext * _Nullable clientContext) __attribute__((availability(macosx,introduced=10_3))); -extern void -CFHostScheduleWithRunLoop(CFHostRef theHost, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10_3))); -extern void -CFHostUnscheduleFromRunLoop(CFHostRef theHost, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10_3))); - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -typedef struct __CFNetService* CFNetServiceRef; -typedef struct __CFNetServiceMonitor* CFNetServiceMonitorRef; -typedef struct __CFNetServiceBrowser* CFNetServiceBrowserRef; -extern const SInt32 kCFStreamErrorDomainMach __attribute__((availability(macosx,introduced=10_2))); -extern const SInt32 kCFStreamErrorDomainNetServices __attribute__((availability(macosx,introduced=10_2))); -typedef int CFNetServicesError; enum { - - - - - kCFNetServicesErrorUnknown = -72000L, - - - - - - - kCFNetServicesErrorCollision = -72001L, - - - - - kCFNetServicesErrorNotFound = -72002L, - - - - - - kCFNetServicesErrorInProgress = -72003L, - - - - - kCFNetServicesErrorBadArgument = -72004L, - - - - - kCFNetServicesErrorCancel = -72005L, - - - - - - kCFNetServicesErrorInvalid = -72006L, - - - - - - kCFNetServicesErrorTimeout = -72007L -}; -typedef int CFNetServiceMonitorType; enum { - - - - - kCFNetServiceMonitorTXT = 1 -}; -typedef CFOptionFlags CFNetServiceRegisterFlags; enum { - - - - - kCFNetServiceFlagNoAutoRename = 1 -}; -typedef CFOptionFlags CFNetServiceBrowserFlags; enum { - - - - - kCFNetServiceFlagMoreComing = 1, - - - - - kCFNetServiceFlagIsDomain = 2, - - - - - kCFNetServiceFlagIsDefault = 4, - - - - - kCFNetServiceFlagIsRegistrationDomain __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))) = 4, - - - - - kCFNetServiceFlagRemove = 8 -}; -struct CFNetServiceClientContext { - - - - - - - CFIndex version; - - - - - - void * _Nullable info; - CFAllocatorRetainCallBack _Nullable retain; - - - - - - CFAllocatorReleaseCallBack _Nullable release; - - - - - - - - CFAllocatorCopyDescriptionCallBack _Nullable copyDescription; -}; -typedef struct CFNetServiceClientContext CFNetServiceClientContext; -typedef void ( * CFNetServiceClientCallBack)(CFNetServiceRef theService, CFStreamError * _Nullable error, void * _Nullable info); -typedef void ( * CFNetServiceMonitorClientCallBack)(CFNetServiceMonitorRef theMonitor, CFNetServiceRef theService, CFNetServiceMonitorType typeInfo, CFDataRef rdata, CFStreamError * _Nullable error, void * _Nullable info); -typedef void ( * CFNetServiceBrowserClientCallBack)(CFNetServiceBrowserRef browser, CFOptionFlags flags, CFTypeRef domainOrService, CFStreamError * _Nullable error, void * _Nullable info); -extern CFTypeID -CFNetServiceGetTypeID(void) __attribute__((availability(macosx,introduced=10_2))); -extern CFTypeID -CFNetServiceMonitorGetTypeID(void) __attribute__((availability(macosx,introduced=10_4))); -extern CFTypeID -CFNetServiceBrowserGetTypeID(void) __attribute__((availability(macosx,introduced=10_2))); -extern CFNetServiceRef -CFNetServiceCreate(CFAllocatorRef _Nullable alloc, CFStringRef domain, CFStringRef serviceType, CFStringRef name, SInt32 port) __attribute__((availability(macosx,introduced=10_2))); -extern CFNetServiceRef -CFNetServiceCreateCopy(CFAllocatorRef _Nullable alloc, CFNetServiceRef service) __attribute__((availability(macosx,introduced=10_3))); -extern CFStringRef -CFNetServiceGetDomain(CFNetServiceRef theService) __attribute__((availability(macosx,introduced=10_2))); -extern CFStringRef -CFNetServiceGetType(CFNetServiceRef theService) __attribute__((availability(macosx,introduced=10_2))); -extern CFStringRef -CFNetServiceGetName(CFNetServiceRef theService) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFNetServiceRegisterWithOptions(CFNetServiceRef theService, CFOptionFlags options, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_4))); -extern Boolean -CFNetServiceResolveWithTimeout(CFNetServiceRef theService, CFTimeInterval timeout, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_4))); -extern void -CFNetServiceCancel(CFNetServiceRef theService) __attribute__((availability(macosx,introduced=10_2))); -extern _Nullable CFStringRef -CFNetServiceGetTargetHost(CFNetServiceRef theService) __attribute__((availability(macosx,introduced=10_4))); -extern SInt32 -CFNetServiceGetPortNumber(CFNetServiceRef theService) __attribute__((availability(macosx,introduced=10_5))); -extern _Nullable CFArrayRef -CFNetServiceGetAddressing(CFNetServiceRef theService) __attribute__((availability(macosx,introduced=10_2))); -extern _Nullable CFDataRef -CFNetServiceGetTXTData(CFNetServiceRef theService) __attribute__((availability(macosx,introduced=10_4))); -extern Boolean -CFNetServiceSetTXTData(CFNetServiceRef theService, CFDataRef txtRecord) __attribute__((availability(macosx,introduced=10_4))); -extern _Nullable CFDictionaryRef -CFNetServiceCreateDictionaryWithTXTData(CFAllocatorRef _Nullable alloc, CFDataRef txtRecord) __attribute__((availability(macosx,introduced=10_4))); -extern _Nullable CFDataRef -CFNetServiceCreateTXTDataWithDictionary(CFAllocatorRef _Nullable alloc, CFDictionaryRef keyValuePairs) __attribute__((availability(macosx,introduced=10_4))); -extern Boolean -CFNetServiceSetClient(CFNetServiceRef theService, CFNetServiceClientCallBack _Nullable clientCB, CFNetServiceClientContext * _Nullable clientContext) __attribute__((availability(macosx,introduced=10_2))); -extern void -CFNetServiceScheduleWithRunLoop(CFNetServiceRef theService, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10_2))); -extern void -CFNetServiceUnscheduleFromRunLoop(CFNetServiceRef theService, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10_2))); -extern CFNetServiceMonitorRef -CFNetServiceMonitorCreate( - CFAllocatorRef _Nullable alloc, - CFNetServiceRef theService, - CFNetServiceMonitorClientCallBack clientCB, - CFNetServiceClientContext * clientContext) __attribute__((availability(macosx,introduced=10_4))); -extern void -CFNetServiceMonitorInvalidate(CFNetServiceMonitorRef monitor) __attribute__((availability(macosx,introduced=10_4))); -extern Boolean -CFNetServiceMonitorStart(CFNetServiceMonitorRef monitor, CFNetServiceMonitorType recordType, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_4))); -extern void -CFNetServiceMonitorStop(CFNetServiceMonitorRef monitor, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_4))); -extern void -CFNetServiceMonitorScheduleWithRunLoop(CFNetServiceMonitorRef monitor, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10_4))); -extern void -CFNetServiceMonitorUnscheduleFromRunLoop(CFNetServiceMonitorRef monitor, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10_4))); -extern CFNetServiceBrowserRef -CFNetServiceBrowserCreate(CFAllocatorRef _Nullable alloc, CFNetServiceBrowserClientCallBack clientCB, CFNetServiceClientContext *clientContext) __attribute__((availability(macosx,introduced=10_2))); -extern void -CFNetServiceBrowserInvalidate(CFNetServiceBrowserRef browser) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFNetServiceBrowserSearchForDomains(CFNetServiceBrowserRef browser, Boolean registrationDomains, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFNetServiceBrowserSearchForServices(CFNetServiceBrowserRef browser, CFStringRef domain, CFStringRef serviceType, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_2))); -extern void -CFNetServiceBrowserStopSearch(CFNetServiceBrowserRef browser, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_2))); -extern void -CFNetServiceBrowserScheduleWithRunLoop(CFNetServiceBrowserRef browser, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10_2))); -extern void -CFNetServiceBrowserUnscheduleFromRunLoop(CFNetServiceBrowserRef browser, CFRunLoopRef runLoop, CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFNetServiceRegister(CFNetServiceRef theService, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); -extern Boolean -CFNetServiceResolve(CFNetServiceRef theService, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); -extern _Nullable CFStringRef -CFNetServiceGetProtocolSpecificInformation(CFNetServiceRef theService) __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); -extern void -CFNetServiceSetProtocolSpecificInformation(CFNetServiceRef theService, CFStringRef _Nullable theInfo) __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); - - - - - -#pragma pack(pop) - - -} - - - - - - - - -extern "C" { -extern const CFStringRef kCFStreamPropertySSLContext __attribute__((availability(macosx,introduced=10_9))); -extern const CFStringRef kCFStreamPropertySSLPeerTrust __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFStreamSSLValidatesCertificateChain __attribute__((availability(macosx,introduced=10_4))); -extern const CFStringRef kCFStreamPropertySSLSettings __attribute__((availability(macosx,introduced=10_4))); -extern const CFStringRef kCFStreamSSLLevel __attribute__((availability(macosx,introduced=10_4))); -extern const CFStringRef kCFStreamSSLPeerName __attribute__((availability(macosx,introduced=10_4))); -extern const CFStringRef kCFStreamSSLCertificates __attribute__((availability(macosx,introduced=10_4))); -extern const CFStringRef kCFStreamSSLIsServer __attribute__((availability(macosx,introduced=10_4))); -extern const CFStringRef kCFStreamNetworkServiceType __attribute__((availability(macosx,introduced=10_7))); - - -extern const CFStringRef kCFStreamNetworkServiceTypeVideo __attribute__((availability(macosx,introduced=10_7))); -extern const CFStringRef kCFStreamNetworkServiceTypeVoice __attribute__((availability(macosx,introduced=10_7))); -extern const CFStringRef kCFStreamNetworkServiceTypeBackground __attribute__((availability(macosx,introduced=10_7))); - - -extern const CFStringRef kCFStreamNetworkServiceTypeVoIP __attribute__((availability(macosx,introduced=10_7,deprecated=10_11,message="" "use PushKit for VoIP control purposes"))); -extern const CFStringRef kCFStreamPropertyNoCellular __attribute__((availability(macosx,introduced=10_8))); -extern const CFStringRef kCFStreamPropertyConnectionIsCellular __attribute__((availability(macosx,introduced=10_8))); -extern const CFIndex kCFStreamErrorDomainWinSock __attribute__((availability(macosx,introduced=10_5))); -extern const int kCFStreamErrorDomainSOCKS __attribute__((availability(macosx,introduced=10_0))); - - - -static __inline__ __attribute__((always_inline)) -SInt32 CFSocketStreamSOCKSGetErrorSubdomain(const CFStreamError* error) { - return ((error->error >> 16) & 0x0000FFFF); -} - -static __inline__ __attribute__((always_inline)) -SInt32 CFSocketStreamSOCKSGetError(const CFStreamError* error) { - return (error->error & 0x0000FFFF); -} - -enum { - kCFStreamErrorSOCKSSubDomainNone = 0, - kCFStreamErrorSOCKSSubDomainVersionCode = 1, - kCFStreamErrorSOCKS4SubDomainResponse = 2, - kCFStreamErrorSOCKS5SubDomainUserPass = 3, - kCFStreamErrorSOCKS5SubDomainMethod = 4, - kCFStreamErrorSOCKS5SubDomainResponse = 5 -}; - - - -enum { - kCFStreamErrorSOCKS5BadResponseAddr = 1, - kCFStreamErrorSOCKS5BadState = 2, - kCFStreamErrorSOCKSUnknownClientVersion = 3 -}; - - -enum { - kCFStreamErrorSOCKS4RequestFailed = 91, - kCFStreamErrorSOCKS4IdentdFailed = 92, - kCFStreamErrorSOCKS4IdConflict = 93 -}; - - -enum { - kSOCKS5NoAcceptableMethod = 0xFF -}; -extern const CFStringRef kCFStreamPropertySOCKSProxy __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamPropertySOCKSProxyHost __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamPropertySOCKSProxyPort __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamPropertySOCKSVersion __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamSocketSOCKSVersion4 __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamSocketSOCKSVersion5 __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamPropertySOCKSUser __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamPropertySOCKSPassword __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamPropertyProxyLocalBypass __attribute__((availability(macosx,introduced=10_4))); -extern const int kCFStreamErrorDomainSSL __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamPropertySocketSecurityLevel __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamSocketSecurityLevelNone __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamSocketSecurityLevelSSLv2 __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamSocketSecurityLevelSSLv3 __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamSocketSecurityLevelTLSv1 __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamSocketSecurityLevelNegotiatedSSL __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamPropertyShouldCloseNativeSocket __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFStreamPropertySocketRemoteHost __attribute__((availability(macosx,introduced=10_3))); -extern const CFStringRef kCFStreamPropertySocketRemoteNetService __attribute__((availability(macosx,introduced=10_3))); -extern const CFStringRef kCFStreamPropertySocketExtendedBackgroundIdleMode __attribute__((availability(macosx,introduced=10_11))); -extern void -CFStreamCreatePairWithSocketToCFHost( - CFAllocatorRef _Nullable alloc, - CFHostRef host, - SInt32 port, - CFReadStreamRef _Nullable * _Nullable readStream, - CFWriteStreamRef _Nullable * _Nullable writeStream) __attribute__((availability(macosx,introduced=10_3))); -extern void -CFStreamCreatePairWithSocketToNetService( - CFAllocatorRef _Nullable alloc, - CFNetServiceRef service, - CFReadStreamRef _Nullable * _Nullable readStream, - CFWriteStreamRef _Nullable * _Nullable writeStream) __attribute__((availability(macosx,introduced=10_3))); -extern const CFStringRef kCFStreamPropertySSLPeerCertificates __attribute__((availability(macosx,introduced=10_4,deprecated=10_6,message="" ))); -extern const CFStringRef kCFStreamSSLAllowsExpiredCertificates __attribute__((availability(macosx,introduced=10_4,deprecated=10_6,message="" ))); -extern const CFStringRef kCFStreamSSLAllowsExpiredRoots __attribute__((availability(macosx,introduced=10_4,deprecated=10_6,message="" ))); -extern const CFStringRef kCFStreamSSLAllowsAnyRoot __attribute__((availability(macosx,introduced=10_4,deprecated=10_6,message="" ))); - - - - - - - -} - - - -extern "C" { -extern const SInt32 kCFStreamErrorDomainFTP __attribute__((availability(macosx,introduced=10_3))); -extern const CFStringRef kCFStreamPropertyFTPUserName __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFStreamPropertyFTPPassword __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFStreamPropertyFTPUsePassiveMode __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFStreamPropertyFTPResourceSize __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFStreamPropertyFTPFetchResourceInfo __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFStreamPropertyFTPFileTransferOffset __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFStreamPropertyFTPAttemptPersistentConnection __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFStreamPropertyFTPProxy __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFStreamPropertyFTPProxyHost __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFStreamPropertyFTPProxyPort __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); - - - - - -extern const CFStringRef kCFStreamPropertyFTPProxyUser __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); - - - - - -extern const CFStringRef kCFStreamPropertyFTPProxyPassword __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFFTPResourceMode __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFFTPResourceName __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFFTPResourceOwner __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFFTPResourceGroup __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFFTPResourceLink __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFFTPResourceSize __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFFTPResourceType __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern const CFStringRef kCFFTPResourceModDate __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern CFReadStreamRef -CFReadStreamCreateWithFTPURL(CFAllocatorRef _Nullable alloc, CFURLRef ftpURL) __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern CFIndex -CFFTPCreateParsedResourceListing(CFAllocatorRef _Nullable alloc, const UInt8 *buffer, CFIndex bufferLength, CFDictionaryRef _Nullable * _Nullable parsed) __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); -extern CFWriteStreamRef -CFWriteStreamCreateWithFTPURL(CFAllocatorRef _Nullable alloc, CFURLRef ftpURL) __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSessionAPI for ftp requests"))); - - - -} - - - - - - - -extern "C" { -extern const CFStringRef kCFHTTPVersion1_0 __attribute__((availability(macosx,introduced=10_1))); -extern const CFStringRef kCFHTTPVersion1_1 __attribute__((availability(macosx,introduced=10_1))); -extern const CFStringRef kCFHTTPVersion2_0 __attribute__((availability(macosx,introduced=10_10))); -extern const CFStringRef kCFHTTPAuthenticationSchemeBasic __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFHTTPAuthenticationSchemeDigest __attribute__((availability(macosx,introduced=10_2))); -extern const CFStringRef kCFHTTPAuthenticationSchemeNTLM __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFHTTPAuthenticationSchemeKerberos __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFHTTPAuthenticationSchemeNegotiate __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFHTTPAuthenticationSchemeNegotiate2 __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFHTTPAuthenticationSchemeXMobileMeAuthToken __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFHTTPAuthenticationSchemeOAuth1 __attribute__((availability(macosx,introduced=10_9))); -typedef struct __CFHTTPMessage* CFHTTPMessageRef; -extern CFTypeID -CFHTTPMessageGetTypeID(void) __attribute__((availability(macosx,introduced=10_1))); -extern CFHTTPMessageRef -CFHTTPMessageCreateRequest(CFAllocatorRef _Nullable alloc, CFStringRef requestMethod, CFURLRef url, CFStringRef httpVersion) __attribute__((availability(macosx,introduced=10_1))); -extern CFHTTPMessageRef -CFHTTPMessageCreateResponse( - CFAllocatorRef _Nullable alloc, - CFIndex statusCode, - CFStringRef _Nullable statusDescription, - CFStringRef httpVersion) __attribute__((availability(macosx,introduced=10_1))); -extern CFHTTPMessageRef -CFHTTPMessageCreateEmpty(CFAllocatorRef _Nullable alloc, Boolean isRequest) __attribute__((availability(macosx,introduced=10_1))); -extern CFHTTPMessageRef -CFHTTPMessageCreateCopy(CFAllocatorRef _Nullable alloc, CFHTTPMessageRef message) __attribute__((availability(macosx,introduced=10_1))); -extern Boolean -CFHTTPMessageIsRequest(CFHTTPMessageRef message) __attribute__((availability(macosx,introduced=10_1))); -extern CFStringRef -CFHTTPMessageCopyVersion(CFHTTPMessageRef message) __attribute__((availability(macosx,introduced=10_1))); -extern _Nullable CFDataRef -CFHTTPMessageCopyBody(CFHTTPMessageRef message) __attribute__((availability(macosx,introduced=10_1))); -extern void -CFHTTPMessageSetBody(CFHTTPMessageRef message, CFDataRef bodyData) __attribute__((availability(macosx,introduced=10_1))); -extern _Nullable CFStringRef -CFHTTPMessageCopyHeaderFieldValue(CFHTTPMessageRef message, CFStringRef headerField) __attribute__((availability(macosx,introduced=10_1))); -extern _Nullable CFDictionaryRef -CFHTTPMessageCopyAllHeaderFields(CFHTTPMessageRef message) __attribute__((availability(macosx,introduced=10_1))); -extern void -CFHTTPMessageSetHeaderFieldValue(CFHTTPMessageRef message, CFStringRef headerField, CFStringRef _Nullable value) __attribute__((availability(macosx,introduced=10_1))); -extern Boolean -CFHTTPMessageAppendBytes(CFHTTPMessageRef message, const UInt8 *newBytes, CFIndex numBytes) __attribute__((availability(macosx,introduced=10_1))); -extern Boolean -CFHTTPMessageIsHeaderComplete(CFHTTPMessageRef message) __attribute__((availability(macosx,introduced=10_1))); -extern _Nullable CFDataRef -CFHTTPMessageCopySerializedMessage(CFHTTPMessageRef message) __attribute__((availability(macosx,introduced=10_1))); -extern _Nullable CFURLRef -CFHTTPMessageCopyRequestURL(CFHTTPMessageRef request) __attribute__((availability(macosx,introduced=10_1))); -extern _Nullable CFStringRef -CFHTTPMessageCopyRequestMethod(CFHTTPMessageRef request) __attribute__((availability(macosx,introduced=10_1))); -extern Boolean -CFHTTPMessageAddAuthentication( - CFHTTPMessageRef request, - CFHTTPMessageRef _Nullable authenticationFailureResponse, - CFStringRef username, - CFStringRef password, - CFStringRef _Nullable authenticationScheme, - Boolean forProxy) __attribute__((availability(macosx,introduced=10_1))); -extern CFIndex -CFHTTPMessageGetResponseStatusCode(CFHTTPMessageRef response) __attribute__((availability(macosx,introduced=10_1))); -extern _Nullable CFStringRef -CFHTTPMessageCopyResponseStatusLine(CFHTTPMessageRef response) __attribute__((availability(macosx,introduced=10_1))); - - - - -} - - - -extern "C" { -extern const SInt32 kCFStreamErrorDomainHTTP __attribute__((availability(macosx,introduced=10_1))); - - - - - - - -typedef int CFStreamErrorHTTP; enum { - - - - - kCFStreamErrorHTTPParseFailure = -1, - - - - - kCFStreamErrorHTTPRedirectionLoop = -2, - - - - - kCFStreamErrorHTTPBadURL = -3 -}; -extern const CFStringRef kCFStreamPropertyHTTPResponseHeader __attribute__((availability(macosx,introduced=10_1,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPFinalURL __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPFinalRequest __attribute__((availability(macosx,introduced=10_5,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPProxy __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPProxyHost __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPProxyPort __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPSProxyHost __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPSProxyPort __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPShouldAutoredirect __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPAttemptPersistentConnection __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern const CFStringRef kCFStreamPropertyHTTPRequestBytesWrittenCount __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern CFReadStreamRef -CFReadStreamCreateForHTTPRequest(CFAllocatorRef _Nullable alloc, CFHTTPMessageRef request) __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern CFReadStreamRef -CFReadStreamCreateForStreamedHTTPRequest(CFAllocatorRef _Nullable alloc, CFHTTPMessageRef requestHeaders, CFReadStreamRef requestBody) __attribute__((availability(macosx,introduced=10_2,deprecated=10_11,message="" "Use NSURLSession API for http requests"))); -extern void -CFHTTPReadStreamSetRedirectsAutomatically(CFReadStreamRef httpStream, Boolean shouldAutoRedirect) __attribute__((availability(macosx,introduced=10_1,deprecated=10_3,message="" ))); -} - - - -extern "C" { -typedef struct _CFHTTPAuthentication* CFHTTPAuthenticationRef; -typedef int CFStreamErrorHTTPAuthentication; enum { - - - - - - kCFStreamErrorHTTPAuthenticationTypeUnsupported = -1000, - - - - - - kCFStreamErrorHTTPAuthenticationBadUserName = -1001, - - - - - - kCFStreamErrorHTTPAuthenticationBadPassword = -1002 -}; -extern const CFStringRef kCFHTTPAuthenticationUsername __attribute__((availability(macosx,introduced=10_4))); -extern const CFStringRef kCFHTTPAuthenticationPassword __attribute__((availability(macosx,introduced=10_4))); -extern const CFStringRef kCFHTTPAuthenticationAccountDomain __attribute__((availability(macosx,introduced=10_4))); -extern CFTypeID -CFHTTPAuthenticationGetTypeID(void) __attribute__((availability(macosx,introduced=10_2))); -extern CFHTTPAuthenticationRef -CFHTTPAuthenticationCreateFromResponse(CFAllocatorRef _Nullable alloc, CFHTTPMessageRef response) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFHTTPAuthenticationIsValid(CFHTTPAuthenticationRef auth, CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFHTTPAuthenticationAppliesToRequest(CFHTTPAuthenticationRef auth, CFHTTPMessageRef request) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFHTTPAuthenticationRequiresOrderedRequests(CFHTTPAuthenticationRef auth) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFHTTPMessageApplyCredentials( - CFHTTPMessageRef request, - CFHTTPAuthenticationRef auth, - CFStringRef _Nullable username, - CFStringRef _Nullable password, - CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFHTTPMessageApplyCredentialDictionary( - CFHTTPMessageRef request, - CFHTTPAuthenticationRef auth, - CFDictionaryRef dict, - CFStreamError * _Nullable error) __attribute__((availability(macosx,introduced=10_4))); -extern CFStringRef -CFHTTPAuthenticationCopyRealm(CFHTTPAuthenticationRef auth) __attribute__((availability(macosx,introduced=10_2))); -extern CFArrayRef -CFHTTPAuthenticationCopyDomains(CFHTTPAuthenticationRef auth) __attribute__((availability(macosx,introduced=10_2))); -extern CFStringRef -CFHTTPAuthenticationCopyMethod(CFHTTPAuthenticationRef auth) __attribute__((availability(macosx,introduced=10_2))); -extern Boolean -CFHTTPAuthenticationRequiresUserNameAndPassword(CFHTTPAuthenticationRef auth) __attribute__((availability(macosx,introduced=10_3))); -extern Boolean -CFHTTPAuthenticationRequiresAccountDomain(CFHTTPAuthenticationRef auth) __attribute__((availability(macosx,introduced=10_4))); - - - - -} - - - -extern "C" { -typedef struct __CFNetDiagnostic* CFNetDiagnosticRef; - - - - - - - -typedef int CFNetDiagnosticStatusValues; enum { - - - - - kCFNetDiagnosticNoErr = 0, - - - - - kCFNetDiagnosticErr = -66560L, - - - - - kCFNetDiagnosticConnectionUp = -66559L, - kCFNetDiagnosticConnectionIndeterminate = -66558L, - - - - - kCFNetDiagnosticConnectionDown = -66557L -}; -typedef CFIndex CFNetDiagnosticStatus; -extern CFNetDiagnosticRef -CFNetDiagnosticCreateWithStreams(CFAllocatorRef _Nullable alloc, CFReadStreamRef _Nullable readStream, CFWriteStreamRef _Nullable writeStream) __attribute__((availability(macosx,introduced=10_4))); -extern CFNetDiagnosticRef -CFNetDiagnosticCreateWithURL(CFAllocatorRef alloc, CFURLRef url) __attribute__((availability(macosx,introduced=10_4))); -extern void -CFNetDiagnosticSetName(CFNetDiagnosticRef details, CFStringRef name) __attribute__((availability(macosx,introduced=10_4))); -extern CFNetDiagnosticStatus -CFNetDiagnosticDiagnoseProblemInteractively(CFNetDiagnosticRef details) __attribute__((availability(macosx,introduced=10_4))); -extern CFNetDiagnosticStatus -CFNetDiagnosticCopyNetworkStatusPassively(CFNetDiagnosticRef details, CFStringRef _Nullable * _Nullable description) __attribute__((availability(macosx,introduced=10_4))); - - - - -} - - - - - - - -extern "C" { -extern _Nullable CFDictionaryRef -CFNetworkCopySystemProxySettings(void) __attribute__((availability(macosx,introduced=10_6))); -extern CFArrayRef -CFNetworkCopyProxiesForURL(CFURLRef url, CFDictionaryRef proxySettings) __attribute__((availability(macosx,introduced=10_5))); -typedef void ( * CFProxyAutoConfigurationResultCallback)(void *client, CFArrayRef proxyList, CFErrorRef _Nullable error); -extern _Nullable CFArrayRef -CFNetworkCopyProxiesForAutoConfigurationScript(CFStringRef proxyAutoConfigurationScript, CFURLRef targetURL, CFErrorRef * _Nullable error) __attribute__((availability(macosx,introduced=10_5))); -extern CFRunLoopSourceRef -CFNetworkExecuteProxyAutoConfigurationScript( - CFStringRef proxyAutoConfigurationScript, - CFURLRef targetURL, - CFProxyAutoConfigurationResultCallback cb, - CFStreamClientContext * clientContext) __attribute__((availability(macosx,introduced=10_5))); -extern CFRunLoopSourceRef -CFNetworkExecuteProxyAutoConfigurationURL( - CFURLRef proxyAutoConfigURL, - CFURLRef targetURL, - CFProxyAutoConfigurationResultCallback cb, - CFStreamClientContext * clientContext) __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFProxyTypeKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFProxyHostNameKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFProxyPortNumberKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFProxyAutoConfigurationURLKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFProxyAutoConfigurationJavaScriptKey __attribute__((availability(macosx,introduced=10_7))); -extern const CFStringRef kCFProxyUsernameKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFProxyPasswordKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFProxyTypeNone __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern const CFStringRef kCFProxyTypeHTTP __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern const CFStringRef kCFProxyTypeHTTPS __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern const CFStringRef kCFProxyTypeSOCKS __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern const CFStringRef kCFProxyTypeFTP __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern const CFStringRef kCFProxyTypeAutoConfigurationURL __attribute__((availability(macosx,introduced=10_5))); - - - - - -extern const CFStringRef kCFProxyTypeAutoConfigurationJavaScript __attribute__((availability(macosx,introduced=10_7))); - - - - - -extern const CFStringRef kCFProxyAutoConfigurationHTTPResponseKey __attribute__((availability(macosx,introduced=10_5))); -extern const CFStringRef kCFNetworkProxiesExceptionsList __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesExcludeSimpleHostnames __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesFTPEnable __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesFTPPassive __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesFTPPort __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesFTPProxy __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesGopherEnable __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesGopherPort __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesGopherProxy __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesHTTPEnable __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesHTTPPort __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesHTTPProxy __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesHTTPSEnable __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesHTTPSPort __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesHTTPSProxy __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesRTSPEnable __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesRTSPPort __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesRTSPProxy __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesSOCKSEnable __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesSOCKSPort __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesSOCKSProxy __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesProxyAutoConfigEnable __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesProxyAutoConfigURLString __attribute__((availability(macosx,introduced=10_6))); -extern const CFStringRef kCFNetworkProxiesProxyAutoConfigJavaScript __attribute__((availability(macosx,introduced=10_7))); -extern const CFStringRef kCFNetworkProxiesProxyAutoDiscoveryEnable __attribute__((availability(macosx,introduced=10_6))); - - - -} - - - -extern "C" { - - - - - - -typedef const struct __attribute__((objc_bridge(id))) __DCSDictionary* DCSDictionaryRef; -extern CFRange DCSGetTermRangeInString( DCSDictionaryRef _Nullable dictionary, CFStringRef textString, CFIndex offset ) - __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef _Nullable DCSCopyTextDefinition( DCSDictionaryRef _Nullable dictionary, CFStringRef textString, CFRange range ) - __attribute__((availability(macosx,introduced=10.5))); - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -extern const CFStringRef kCSIdentityErrorDomain __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -enum { - - - - - kCSIdentityUnknownAuthorityErr = -1, - - - - - kCSIdentityAuthorityNotAccessibleErr = -2, - - - - - kCSIdentityPermissionErr = -3, - - - - - kCSIdentityDeletedErr = -4, - - - - - kCSIdentityInvalidFullNameErr = -5, - - - - - kCSIdentityDuplicateFullNameErr = -6, - - - - - - kCSIdentityInvalidPosixNameErr = -7, - - - - - kCSIdentityDuplicatePosixNameErr = -8, -}; - -#pragma pack(pop) - - -} - - - - - - - -extern "C" { -typedef struct __CSIdentityAuthority* CSIdentityAuthorityRef; -extern CFTypeID -CSIdentityAuthorityGetTypeID(void) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityAuthorityRef -CSGetDefaultIdentityAuthority(void) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityAuthorityRef -CSGetLocalIdentityAuthority(void) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityAuthorityRef -CSGetManagedIdentityAuthority(void) __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef -CSIdentityAuthorityCopyLocalizedName(CSIdentityAuthorityRef authority) __attribute__((availability(macosx,introduced=10.5))); - - - - - -} -extern "C" { - - -#pragma pack(push, 2) -typedef struct __CSIdentity* CSIdentityRef; -typedef struct __CSIdentityQuery* CSIdentityQueryRef; -extern const CFStringRef kCSIdentityGeneratePosixName __attribute__((availability(macosx,introduced=10.5))); -enum { - - - - - kCSIdentityClassUser = 1, - - - - - kCSIdentityClassGroup = 2 -}; - -typedef CFIndex CSIdentityClass; - - - - - - - -enum { - - - - - kCSIdentityFlagNone = 0, - kCSIdentityFlagHidden = 1 -}; - -typedef CFOptionFlags CSIdentityFlags; -extern CFTypeID -CSIdentityGetTypeID(void) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityRef -CSIdentityCreate( - CFAllocatorRef allocator, - CSIdentityClass identityClass, - CFStringRef fullName, - CFStringRef posixName, - CSIdentityFlags flags, - CSIdentityAuthorityRef authority) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityRef -CSIdentityCreateCopy( - CFAllocatorRef allocator, - CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityClass -CSIdentityGetClass(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityAuthorityRef -CSIdentityGetAuthority(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CFUUIDRef -CSIdentityGetUUID(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef -CSIdentityGetFullName(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern id_t -CSIdentityGetPosixID(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef -CSIdentityGetPosixName(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef -CSIdentityGetEmailAddress(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CFURLRef -CSIdentityGetImageURL(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CFDataRef -CSIdentityGetImageData(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef -CSIdentityGetImageDataType(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CFArrayRef -CSIdentityGetAliases(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -CSIdentityIsMemberOfGroup( - CSIdentityRef identity, - CSIdentityRef group) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -CSIdentityIsHidden(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern CFDataRef -CSIdentityCreatePersistentReference( - CFAllocatorRef allocator, - CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -CSIdentityIsEnabled(CSIdentityRef user) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -CSIdentityAuthenticateUsingPassword( - CSIdentityRef user, - CFStringRef password) __attribute__((availability(macosx,introduced=10.5))); -extern SecCertificateRef -CSIdentityGetCertificate(CSIdentityRef user) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityQueryRef -CSIdentityCreateGroupMembershipQuery( - CFAllocatorRef allocator, - CSIdentityRef group) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentitySetFullName( - CSIdentityRef identity, - CFStringRef fullName) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentitySetEmailAddress( - CSIdentityRef identity, - CFStringRef emailAddress) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentitySetImageURL( - CSIdentityRef identity, - CFURLRef url) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentitySetImageData( - CSIdentityRef identity, - CFDataRef imageData, - CFStringRef imageDataType) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentityAddAlias( - CSIdentityRef identity, - CFStringRef alias) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentityRemoveAlias( - CSIdentityRef identity, - CFStringRef alias) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentityAddMember( - CSIdentityRef group, - CSIdentityRef member) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentityRemoveMember( - CSIdentityRef group, - CSIdentityRef member) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentitySetIsEnabled( - CSIdentityRef user, - Boolean isEnabled) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentitySetPassword( - CSIdentityRef user, - CFStringRef password) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentitySetCertificate( - CSIdentityRef user, - SecCertificateRef certificate) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentityDelete(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -CSIdentityCommit( - CSIdentityRef identity, - AuthorizationRef authorization, - CFErrorRef * error) __attribute__((availability(macosx,introduced=10.5))); -enum { - - - - - kCSIdentityCommitCompleted = 1 -}; - - -typedef void ( * CSIdentityStatusUpdatedCallback)(CSIdentityRef identity, CFIndex status, CFErrorRef error, void *info); -struct CSIdentityClientContext { - - - - - - CFIndex version; - - - - - - void * info; - CFAllocatorRetainCallBack retain; - - - - - - CFAllocatorReleaseCallBack release; - - - - - - - CFAllocatorCopyDescriptionCallBack copyDescription; - - - - - - CSIdentityStatusUpdatedCallback statusUpdated; -}; -typedef struct CSIdentityClientContext CSIdentityClientContext; -extern Boolean -CSIdentityCommitAsynchronously( - CSIdentityRef identity, - const CSIdentityClientContext * clientContext, - CFRunLoopRef runLoop, - CFStringRef runLoopMode, - AuthorizationRef authorization) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -CSIdentityIsCommitting(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentityRemoveClient(CSIdentityRef identity) __attribute__((availability(macosx,introduced=10.5))); - - - - -#pragma pack(pop) - - -} -extern "C" { - - -#pragma pack(push, 2) -extern CFTypeID -CSIdentityQueryGetTypeID(void) __attribute__((availability(macosx,introduced=10.5))); -enum { - - - - - - kCSIdentityQueryGenerateUpdateEvents = 0x0001, - - - - - - kCSIdentityQueryIncludeHiddenIdentities = 0x0002 -}; - -typedef CFOptionFlags CSIdentityQueryFlags; -enum { - - - - - kCSIdentityQueryStringEquals = 1, - - - - - kCSIdentityQueryStringBeginsWith = 2 -}; - -typedef CFIndex CSIdentityQueryStringComparisonMethod; -extern CSIdentityQueryRef -CSIdentityQueryCreate( - CFAllocatorRef allocator, - CSIdentityClass identityClass, - CSIdentityAuthorityRef authority) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityQueryRef -CSIdentityQueryCreateForName( - CFAllocatorRef allocator, - CFStringRef name, - CSIdentityQueryStringComparisonMethod comparisonMethod, - CSIdentityClass identityClass, - CSIdentityAuthorityRef authority) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityQueryRef -CSIdentityQueryCreateForUUID( - CFAllocatorRef allocator, - CFUUIDRef uuid, - CSIdentityAuthorityRef authority) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityQueryRef -CSIdentityQueryCreateForPosixID( - CFAllocatorRef allocator, - id_t posixID, - CSIdentityClass identityClass, - CSIdentityAuthorityRef authority) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityQueryRef -CSIdentityQueryCreateForPersistentReference( - CFAllocatorRef allocator, - CFDataRef referenceData) __attribute__((availability(macosx,introduced=10.5))); -extern CSIdentityQueryRef -CSIdentityQueryCreateForCurrentUser(CFAllocatorRef allocator) __attribute__((availability(macosx,introduced=10.5))); -extern CFArrayRef -CSIdentityQueryCopyResults(CSIdentityQueryRef query) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -CSIdentityQueryExecute( - CSIdentityQueryRef query, - CSIdentityQueryFlags flags, - CFErrorRef * error) __attribute__((availability(macosx,introduced=10.5))); -enum { - - - - - - - kCSIdentityQueryEventSearchPhaseFinished = 1, - - - - - kCSIdentityQueryEventResultsAdded = 2, - - - - - - kCSIdentityQueryEventResultsChanged = 3, - - - - - kCSIdentityQueryEventResultsRemoved = 4, - - - - - - kCSIdentityQueryEventErrorOccurred = 5 -}; - -typedef CFIndex CSIdentityQueryEvent; -typedef void ( * CSIdentityQueryReceiveEventCallback)(CSIdentityQueryRef query, CSIdentityQueryEvent event, CFArrayRef identities, CFErrorRef error, void *info); - - - - - - - -struct CSIdentityQueryClientContext { - CFIndex version; - void * info; - CFAllocatorRetainCallBack retainInfo; - CFAllocatorReleaseCallBack releaseInfo; - CFAllocatorCopyDescriptionCallBack copyInfoDescription; - CSIdentityQueryReceiveEventCallback receiveEvent; -}; -typedef struct CSIdentityQueryClientContext CSIdentityQueryClientContext; -extern Boolean -CSIdentityQueryExecuteAsynchronously( - CSIdentityQueryRef query, - CSIdentityQueryFlags flags, - const CSIdentityQueryClientContext * clientContext, - CFRunLoopRef runLoop, - CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10.5))); -extern void -CSIdentityQueryStop(CSIdentityQueryRef query) __attribute__((availability(macosx,introduced=10.5))); - - - - -#pragma pack(pop) - - -} - - - -#pragma pack(push, 2) - - - -enum { - kIconServices16PixelDataARGB = 'ic04', - kIconServices32PixelDataARGB = 'ic05', - kIconServices48PixelDataARGB = 'ic06', - kIconServices128PixelDataARGB = 'ic07' -}; - - - -enum { - kIconServices256PixelDataARGB = 'ic08', - kIconServices512PixelDataARGB = 'ic09', - kIconServices1024PixelDataARGB = 'ic10', - kThumbnail32BitData = 'it32', - kThumbnail8BitMask = 't8mk' -}; - -enum { - kHuge1BitMask = 'ich#', - kHuge4BitData = 'ich4', - kHuge8BitData = 'ich8', - kHuge32BitData = 'ih32', - kHuge8BitMask = 'h8mk' -}; - - - -enum { - kLarge1BitMask = 'ICN#', - kLarge4BitData = 'icl4', - kLarge8BitData = 'icl8', - kLarge32BitData = 'il32', - kLarge8BitMask = 'l8mk', - kSmall1BitMask = 'ics#', - kSmall4BitData = 'ics4', - kSmall8BitData = 'ics8', - kSmall32BitData = 'is32', - kSmall8BitMask = 's8mk', - kMini1BitMask = 'icm#', - kMini4BitData = 'icm4', - kMini8BitData = 'icm8' -}; - - -enum { - large1BitMask = kLarge1BitMask, - large4BitData = kLarge4BitData, - large8BitData = kLarge8BitData, - small1BitMask = kSmall1BitMask, - small4BitData = kSmall4BitData, - small8BitData = kSmall8BitData, - mini1BitMask = kMini1BitMask, - mini4BitData = kMini4BitData, - mini8BitData = kMini8BitData -}; -enum { - kIconFamilyType = 'icns' -}; - - -struct IconFamilyElement { - OSType elementType; - SInt32 elementSize; - unsigned char elementData[1]; -}; -typedef struct IconFamilyElement IconFamilyElement; -struct IconFamilyResource { - OSType resourceType; - SInt32 resourceSize; - IconFamilyElement elements[1]; - -}; -typedef struct IconFamilyResource IconFamilyResource; -typedef IconFamilyResource* IconFamilyPtr; -typedef IconFamilyPtr* IconFamilyHandle; - - - -enum { - kTileIconVariant = 'tile', - kRolloverIconVariant = 'over', - kDropIconVariant = 'drop', - kOpenIconVariant = 'open', - kOpenDropIconVariant = 'odrp' -}; - - -#pragma pack(pop) - - - -extern "C" { - - -#pragma pack(push, 2) - -enum { - - kSleepRequest = 1, - kSleepDemand = 2, - kSleepWakeUp = 3, - kSleepRevoke = 4, - kSleepUnlock = 4, - kSleepDeny = 5, - kSleepNow = 6, - kDozeDemand = 7, - kDozeWakeUp = 8, - kDozeRequest = 9, - kEnterStandby = 10, - kEnterRun = 11, - kSuspendRequest = 12, - kSuspendDemand = 13, - kSuspendRevoke = 14, - kSuspendWakeUp = 15, - kGetPowerLevel = 16, - kSetPowerLevel = 17, - kDeviceInitiatedWake = 18, - kWakeToDoze = 19, - kDozeToFullWakeUp = 20, - kGetPowerInfo = 21, - kGetWakeOnNetInfo = 22, - kSuspendWakeToDoze = 23, - kEnterIdle = 24, - kStillIdle = 25, - kExitIdle = 26 -}; - -enum { - - noCalls = 1, - noRequest = 2, - slpQType = 16, - sleepQType = 16 -}; - - - - - - - -enum { - OverallAct = 0, - UsrActivity = 1, - NetActivity = 2, - HDActivity = 3, - IdleActivity = 4 -}; - -typedef struct SleepQRec SleepQRec; -typedef SleepQRec * SleepQRecPtr; -typedef long ( * SleepQProcPtr)(long message, SleepQRecPtr qRecPtr); -typedef SleepQProcPtr SleepQUPP; -extern SleepQUPP -NewSleepQUPP(SleepQProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern void -DisposeSleepQUPP(SleepQUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern long -InvokeSleepQUPP( - long message, - SleepQRecPtr qRecPtr, - SleepQUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); - - - - inline SleepQUPP NewSleepQUPP(SleepQProcPtr userRoutine) { return userRoutine; } - inline void DisposeSleepQUPP(SleepQUPP) { } - inline long InvokeSleepQUPP(long message, SleepQRecPtr qRecPtr, SleepQUPP userUPP) { return (*userUPP)(message, qRecPtr); } - - - - - - -struct SleepQRec { - SleepQRecPtr sleepQLink; - short sleepQType; - SleepQUPP sleepQProc; - short sleepQFlags; -}; -extern long -GetCPUSpeed(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SleepQInstall(SleepQRecPtr qRecPtr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -SleepQRemove(SleepQRecPtr qRecPtr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern short -MaximumProcessorSpeed(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern short -MinimumProcessorSpeed(void) __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -extern short -CurrentProcessorSpeed(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern short -BatteryCount(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -UpdateSystemActivity(UInt8 activity) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - -typedef SecKeychainRef KCRef; -typedef SecKeychainItemRef KCItemRef; -typedef SecKeychainSearchRef KCSearchRef; -typedef SecKeychainAttribute KCAttribute; -typedef SecKeychainAttributeList KCAttributeList; -typedef SecKeychainAttrType KCAttrType; -typedef SecKeychainStatus KCStatus; -typedef UInt16 KCEvent; -enum { - kIdleKCEvent = 0, - kLockKCEvent = 1, - kUnlockKCEvent = 2, - kAddKCEvent = 3, - kDeleteKCEvent = 4, - kUpdateKCEvent = 5, - kPasswordChangedKCEvent = 6, - kSystemKCEvent = 8, - kDefaultChangedKCEvent = 9, - kDataAccessKCEvent = 10, - kKeychainListChangedKCEvent = 11 -}; - -typedef UInt16 KCEventMask; -enum { - kIdleKCEventMask = 1 << kIdleKCEvent, - kLockKCEventMask = 1 << kLockKCEvent, - kUnlockKCEventMask = 1 << kUnlockKCEvent, - kAddKCEventMask = 1 << kAddKCEvent, - kDeleteKCEventMask = 1 << kDeleteKCEvent, - kUpdateKCEventMask = 1 << kUpdateKCEvent, - kPasswordChangedKCEventMask = 1 << kPasswordChangedKCEvent, - kSystemEventKCEventMask = 1 << kSystemKCEvent, - kDefaultChangedKCEventMask = 1 << kDefaultChangedKCEvent, - kDataAccessKCEventMask = 1 << kDataAccessKCEvent, - kEveryKCEventMask = 0xFFFF -}; - -typedef UInt8 AFPServerSignature[16]; -typedef UInt8 KCPublicKeyHash[20]; -struct KCCallbackInfo { - UInt32 version; - KCItemRef item; - SInt32 processID[2]; - SInt32 event[4]; - KCRef keychain; -}; -typedef struct KCCallbackInfo KCCallbackInfo; -enum { - kUnlockStateKCStatus = 1, - kRdPermKCStatus = 2, - kWrPermKCStatus = 4 -}; - - -enum { - kCertificateKCItemClass = 'cert', - kAppleSharePasswordKCItemClass = 'ashp', - kInternetPasswordKCItemClass = 'inet', - kGenericPasswordKCItemClass = 'genp' -}; - - -typedef FourCharCode KCItemClass; -enum { - - kClassKCItemAttr = 'clas', - kCreationDateKCItemAttr = 'cdat', - kModDateKCItemAttr = 'mdat', - kDescriptionKCItemAttr = 'desc', - kCommentKCItemAttr = 'icmt', - kCreatorKCItemAttr = 'crtr', - kTypeKCItemAttr = 'type', - kScriptCodeKCItemAttr = 'scrp', - kLabelKCItemAttr = 'labl', - kInvisibleKCItemAttr = 'invi', - kNegativeKCItemAttr = 'nega', - kCustomIconKCItemAttr = 'cusi', - kAccountKCItemAttr = 'acct', - - kServiceKCItemAttr = 'svce', - kGenericKCItemAttr = 'gena', - - kSecurityDomainKCItemAttr = 'sdmn', - kServerKCItemAttr = 'srvr', - kAuthTypeKCItemAttr = 'atyp', - kPortKCItemAttr = 'port', - kPathKCItemAttr = 'path', - - kVolumeKCItemAttr = 'vlme', - kAddressKCItemAttr = 'addr', - kSignatureKCItemAttr = 'ssig', - - kProtocolKCItemAttr = 'ptcl', - - kSubjectKCItemAttr = 'subj', - kCommonNameKCItemAttr = 'cn ', - kIssuerKCItemAttr = 'issu', - kSerialNumberKCItemAttr = 'snbr', - kEMailKCItemAttr = 'mail', - kPublicKeyHashKCItemAttr = 'hpky', - kIssuerURLKCItemAttr = 'iurl', - - kEncryptKCItemAttr = 'encr', - kDecryptKCItemAttr = 'decr', - kSignKCItemAttr = 'sign', - kVerifyKCItemAttr = 'veri', - kWrapKCItemAttr = 'wrap', - kUnwrapKCItemAttr = 'unwr', - kStartDateKCItemAttr = 'sdat', - kEndDateKCItemAttr = 'edat' -}; - -typedef FourCharCode KCItemAttr; -enum { - kKCAuthTypeNTLM = 'ntlm', - kKCAuthTypeMSN = 'msna', - kKCAuthTypeDPA = 'dpaa', - kKCAuthTypeRPA = 'rpaa', - kKCAuthTypeHTTPDigest = 'httd', - kKCAuthTypeDefault = 'dflt' -}; - -typedef FourCharCode KCAuthType; -enum { - kKCProtocolTypeFTP = 'ftp ', - kKCProtocolTypeFTPAccount = 'ftpa', - kKCProtocolTypeHTTP = 'http', - kKCProtocolTypeIRC = 'irc ', - kKCProtocolTypeNNTP = 'nntp', - kKCProtocolTypePOP3 = 'pop3', - kKCProtocolTypeSMTP = 'smtp', - kKCProtocolTypeSOCKS = 'sox ', - kKCProtocolTypeIMAP = 'imap', - kKCProtocolTypeLDAP = 'ldap', - kKCProtocolTypeAppleTalk = 'atlk', - kKCProtocolTypeAFP = 'afp ', - kKCProtocolTypeTelnet = 'teln' -}; - -typedef FourCharCode KCProtocolType; -typedef UInt32 KCCertAddOptions; -enum { - kSecOptionReserved = 0x000000FF, - kCertUsageShift = 8, - kCertUsageSigningAdd = 1 << (kCertUsageShift + 0), - kCertUsageSigningAskAndAdd = 1 << (kCertUsageShift + 1), - kCertUsageVerifyAdd = 1 << (kCertUsageShift + 2), - kCertUsageVerifyAskAndAdd = 1 << (kCertUsageShift + 3), - kCertUsageEncryptAdd = 1 << (kCertUsageShift + 4), - kCertUsageEncryptAskAndAdd = 1 << (kCertUsageShift + 5), - kCertUsageDecryptAdd = 1 << (kCertUsageShift + 6), - kCertUsageDecryptAskAndAdd = 1 << (kCertUsageShift + 7), - kCertUsageKeyExchAdd = 1 << (kCertUsageShift + 8), - kCertUsageKeyExchAskAndAdd = 1 << (kCertUsageShift + 9), - kCertUsageRootAdd = 1 << (kCertUsageShift + 10), - kCertUsageRootAskAndAdd = 1 << (kCertUsageShift + 11), - kCertUsageSSLAdd = 1 << (kCertUsageShift + 12), - kCertUsageSSLAskAndAdd = 1 << (kCertUsageShift + 13), - kCertUsageAllAdd = 0x7FFFFF00 -}; - -typedef UInt16 KCVerifyStopOn; -enum { - kPolicyKCStopOn = 0, - kNoneKCStopOn = 1, - kFirstPassKCStopOn = 2, - kFirstFailKCStopOn = 3 -}; - -typedef UInt32 KCCertSearchOptions; -enum { - kCertSearchShift = 0, - kCertSearchSigningIgnored = 0, - kCertSearchSigningAllowed = 1 << (kCertSearchShift + 0), - kCertSearchSigningDisallowed = 1 << (kCertSearchShift + 1), - kCertSearchSigningMask = ((kCertSearchSigningAllowed) | (kCertSearchSigningDisallowed)), - kCertSearchVerifyIgnored = 0, - kCertSearchVerifyAllowed = 1 << (kCertSearchShift + 2), - kCertSearchVerifyDisallowed = 1 << (kCertSearchShift + 3), - kCertSearchVerifyMask = ((kCertSearchVerifyAllowed) | (kCertSearchVerifyDisallowed)), - kCertSearchEncryptIgnored = 0, - kCertSearchEncryptAllowed = 1 << (kCertSearchShift + 4), - kCertSearchEncryptDisallowed = 1 << (kCertSearchShift + 5), - kCertSearchEncryptMask = ((kCertSearchEncryptAllowed) | (kCertSearchEncryptDisallowed)), - kCertSearchDecryptIgnored = 0, - kCertSearchDecryptAllowed = 1 << (kCertSearchShift + 6), - kCertSearchDecryptDisallowed = 1 << (kCertSearchShift + 7), - kCertSearchDecryptMask = ((kCertSearchDecryptAllowed) | (kCertSearchDecryptDisallowed)), - kCertSearchWrapIgnored = 0, - kCertSearchWrapAllowed = 1 << (kCertSearchShift + 8), - kCertSearchWrapDisallowed = 1 << (kCertSearchShift + 9), - kCertSearchWrapMask = ((kCertSearchWrapAllowed) | (kCertSearchWrapDisallowed)), - kCertSearchUnwrapIgnored = 0, - kCertSearchUnwrapAllowed = 1 << (kCertSearchShift + 10), - kCertSearchUnwrapDisallowed = 1 << (kCertSearchShift + 11), - kCertSearchUnwrapMask = ((kCertSearchUnwrapAllowed) | (kCertSearchUnwrapDisallowed)), - kCertSearchPrivKeyRequired = 1 << (kCertSearchShift + 12), - kCertSearchAny = 0 -}; - - -enum { - kAnyPort = 0 -}; - -enum { - kAnyProtocol = 0, - kAnyAuthType = 0 -}; -extern OSStatus -KCGetKeychainManagerVersion(UInt32 * returnVers) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - inline Boolean KeychainManagerAvailable() { return true; } -extern OSStatus -KCSetInteractionAllowed(Boolean state) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern Boolean -KCIsInteractionAllowed(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCMakeKCRefFromFSRef( - FSRef * keychainFSRef, - KCRef * keychain) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCMakeKCRefFromAlias( - AliasHandle keychainAlias, - KCRef * keychain) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCMakeAliasFromKCRef( - KCRef keychain, - AliasHandle * keychainAlias) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCReleaseKeychain(KCRef * keychain) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCGetDefaultKeychain(KCRef * keychain) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCSetDefaultKeychain(KCRef keychain) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCGetStatus( - KCRef keychain, - UInt32 * keychainStatus) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCGetKeychain( - KCItemRef item, - KCRef * keychain) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCGetKeychainName( - KCRef keychain, - StringPtr keychainName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern UInt16 -KCCountKeychains(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCGetIndKeychain( - UInt16 index, - KCRef * keychain) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - -typedef OSStatus ( * KCCallbackProcPtr)(KCEvent keychainEvent, KCCallbackInfo *info, void *userContext); -typedef KCCallbackProcPtr KCCallbackUPP; -extern KCCallbackUPP -NewKCCallbackUPP(KCCallbackProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern void -DisposeKCCallbackUPP(KCCallbackUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -InvokeKCCallbackUPP( - KCEvent keychainEvent, - KCCallbackInfo * info, - void * userContext, - KCCallbackUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - inline KCCallbackUPP NewKCCallbackUPP(KCCallbackProcPtr userRoutine) { return userRoutine; } - inline void DisposeKCCallbackUPP(KCCallbackUPP) { } - inline OSStatus InvokeKCCallbackUPP(KCEvent keychainEvent, KCCallbackInfo * info, void * userContext, KCCallbackUPP userUPP) { return (*userUPP)(keychainEvent, info, userContext); } -extern OSStatus -KCFindAppleSharePassword( - AFPServerSignature * serverSignature, - ConstStringPtr serverAddress, - ConstStringPtr serverName, - ConstStringPtr volumeName, - ConstStringPtr accountName, - UInt32 maxLength, - void * passwordData, - UInt32 * actualLength, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCFindInternetPassword( - ConstStringPtr serverName, - ConstStringPtr securityDomain, - ConstStringPtr accountName, - UInt16 port, - OSType protocol, - OSType authType, - UInt32 maxLength, - void * passwordData, - UInt32 * actualLength, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCFindInternetPasswordWithPath( - ConstStringPtr serverName, - ConstStringPtr securityDomain, - ConstStringPtr accountName, - ConstStringPtr path, - UInt16 port, - OSType protocol, - OSType authType, - UInt32 maxLength, - void * passwordData, - UInt32 * actualLength, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCFindGenericPassword( - ConstStringPtr serviceName, - ConstStringPtr accountName, - UInt32 maxLength, - void * passwordData, - UInt32 * actualLength, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCAddCallback( - KCCallbackUPP callbackProc, - KCEventMask eventMask, - void * userContext) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCRemoveCallback(KCCallbackUPP callbackProc) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCNewItem( - KCItemClass itemClass, - OSType itemCreator, - UInt32 length, - const void * data, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCSetAttribute( - KCItemRef item, - KCAttribute * attr) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCGetAttribute( - KCItemRef item, - KCAttribute * attr, - UInt32 * actualLength) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCSetData( - KCItemRef item, - UInt32 length, - const void * data) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCUpdateItem(KCItemRef item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCReleaseItem(KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCCopyItem( - KCItemRef item, - KCRef destKeychain, - KCItemRef * copy) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCFindFirstItem( - KCRef keychain, - const KCAttributeList * attrList, - KCSearchRef * search, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCFindNextItem( - KCSearchRef search, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCReleaseSearch(KCSearchRef * search) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCDeleteItem(KCItemRef item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCGetData( - KCItemRef item, - UInt32 maxLength, - void * data, - UInt32 * actualLength) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -KCLock(KCRef keychain) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -kcgetkeychainname( - KCRef keychain, - char * keychainName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -kcfindapplesharepassword( - AFPServerSignature * serverSignature, - const char * serverAddress, - const char * serverName, - const char * volumeName, - const char * accountName, - UInt32 maxLength, - void * passwordData, - UInt32 * actualLength, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -kcfindinternetpassword( - const char * serverName, - const char * securityDomain, - const char * accountName, - UInt16 port, - OSType protocol, - OSType authType, - UInt32 maxLength, - void * passwordData, - UInt32 * actualLength, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -kcfindinternetpasswordwithpath( - const char * serverName, - const char * securityDomain, - const char * accountName, - const char * path, - UInt16 port, - OSType protocol, - OSType authType, - UInt32 maxLength, - void * passwordData, - UInt32 * actualLength, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern OSStatus -kcfindgenericpassword( - const char * serviceName, - const char * accountName, - UInt32 maxLength, - void * passwordData, - UInt32 * actualLength, - KCItemRef * item) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - - - - - -enum { - errWSInternalError = -65793L, - errWSTransportError = -65794L, - errWSParseError = -65795L, - errWSTimeoutError = -65796L -}; -enum WSTypeID { - - - - - eWSUnknownType = 0, - - - - - eWSNullType = 1, - - - - - eWSBooleanType = 2, - - - - - eWSIntegerType = 3, - - - - - eWSDoubleType = 4, - - - - - eWSStringType = 5, - - - - - eWSDateType = 6, - - - - - eWSDataType = 7, - - - - - eWSArrayType = 8, - - - - - eWSDictionaryType = 9 -}; -typedef enum WSTypeID WSTypeID; - -typedef void * ( * WSClientContextRetainCallBackProcPtr)(void * info); -typedef void ( * WSClientContextReleaseCallBackProcPtr)(void * info); -typedef CFStringRef ( * WSClientContextCopyDescriptionCallBackProcPtr)(void * info); -struct WSClientContext { - - - - - CFIndex version; - - - - - void * info; - - - - - WSClientContextRetainCallBackProcPtr retain; - - - - - WSClientContextReleaseCallBackProcPtr release; - - - - - WSClientContextCopyDescriptionCallBackProcPtr copyDescription; -}; -typedef struct WSClientContext WSClientContext; -extern CFStringRef kWSXMLRPCProtocol __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSSOAP1999Protocol __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSSOAP2001Protocol __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern WSTypeID -WSGetWSTypeIDFromCFType(CFTypeRef ref) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFTypeID -WSGetCFTypeIDFromWSTypeID(WSTypeID typeID) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - - - - - - - -#pragma pack(pop) - - -} -extern "C" { -extern CFStringRef kWSMethodInvocationResult __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - - - -extern CFStringRef kWSFaultString __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSFaultCode __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSFaultExtra __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSNetworkStreamFaultString __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSStreamErrorMessage __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSStreamErrorDomain __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSStreamErrorError __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSHTTPMessage __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSHTTPResponseMessage __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - - - - - -extern CFStringRef kWSHTTPExtraHeaders __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSHTTPVersion __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSHTTPProxy __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSHTTPFollowsRedirects __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSDebugOutgoingHeaders __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSDebugOutgoingBody __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSDebugIncomingHeaders __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSDebugIncomingBody __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - - - - - -extern CFStringRef kWSSOAPBodyEncodingStyle __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSSOAPMethodNamespaceURI __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSSOAPStyleDoc __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSSOAPStyleRPC __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - - - - - - - -extern CFStringRef kWSSOAPMessageHeaders __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - - - - - -extern CFStringRef kWSRecordParameterOrder __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSRecordNamespaceURI __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFStringRef kWSRecordType __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - - - - - -extern CFStringRef kWSMethodInvocationResultParameterName __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - - - - - - -extern CFStringRef kWSMethodInvocationTimeoutValue __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); - -} -extern "C" { -typedef struct OpaqueWSMethodInvocationRef* WSMethodInvocationRef; -extern CFTypeID -WSMethodInvocationGetTypeID(void) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern WSMethodInvocationRef -WSMethodInvocationCreate( - CFURLRef url, - CFStringRef methodName, - CFStringRef protocol) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern WSMethodInvocationRef -WSMethodInvocationCreateFromSerialization(CFDataRef contract) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFDataRef -WSMethodInvocationCopySerialization(WSMethodInvocationRef invocation) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -WSMethodInvocationSetParameters( - WSMethodInvocationRef invocation, - CFDictionaryRef parameters, - CFArrayRef parameterOrder) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFDictionaryRef -WSMethodInvocationCopyParameters( - WSMethodInvocationRef invocation, - CFArrayRef * parameterOrder) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -WSMethodInvocationSetProperty( - WSMethodInvocationRef invocation, - CFStringRef propertyName, - CFTypeRef propertyValue) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern CFTypeRef -WSMethodInvocationCopyProperty( - WSMethodInvocationRef invocation, - CFStringRef propertyName) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern __attribute__((cf_returns_retained)) CFDictionaryRef -WSMethodInvocationInvoke(WSMethodInvocationRef invocation) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -typedef void ( * WSMethodInvocationCallBackProcPtr)(WSMethodInvocationRef invocation, void *info, CFDictionaryRef outRef); -extern void -WSMethodInvocationSetCallBack( - WSMethodInvocationRef invocation, - WSMethodInvocationCallBackProcPtr clientCB, - WSClientContext * context) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -WSMethodInvocationScheduleWithRunLoop( - WSMethodInvocationRef invocation, - CFRunLoopRef runLoop, - CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern void -WSMethodInvocationUnscheduleFromRunLoop( - WSMethodInvocationRef invocation, - CFRunLoopRef runLoop, - CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -extern Boolean -WSMethodResultIsFault(CFDictionaryRef methodResult) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -typedef CFStringRef ( * WSMethodInvocationSerializationProcPtr)(WSMethodInvocationRef invocation, CFTypeRef obj, void *info); -extern void -WSMethodInvocationAddSerializationOverride( - WSMethodInvocationRef invocation, - CFTypeID objType, - WSMethodInvocationSerializationProcPtr serializationProc, - WSClientContext * context) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -typedef CFTypeRef ( * WSMethodInvocationDeserializationProcPtr)(WSMethodInvocationRef invocation, CFXMLTreeRef msgRoot, CFXMLTreeRef deserializeRoot, void *info); -extern void -WSMethodInvocationAddDeserializationOverride( - WSMethodInvocationRef invocation, - CFStringRef typeNamespace, - CFStringRef typeName, - WSMethodInvocationDeserializationProcPtr deserializationProc, - WSClientContext * context) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8))); -} - - - -extern "C" { -typedef struct OpaqueWSProtocolHandlerRef* WSProtocolHandlerRef; -extern CFTypeID -WSProtocolHandlerGetTypeID(void) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern WSProtocolHandlerRef -WSProtocolHandlerCreate( - CFAllocatorRef allocator, - CFStringRef protocol) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern CFDictionaryRef -WSProtocolHandlerCopyRequestDictionary( - WSProtocolHandlerRef ref, - CFDataRef data) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern CFDictionaryRef -WSProtocolHandlerCopyReplyDictionary( - WSProtocolHandlerRef ref, - CFStringRef methodName, - CFDataRef data) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern CFDataRef -WSProtocolHandlerCopyReplyDocument( - WSProtocolHandlerRef ref, - CFDictionaryRef methodContext, - CFTypeRef resultValue) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern CFDataRef -WSProtocolHandlerCopyFaultDocument( - WSProtocolHandlerRef ref, - CFDictionaryRef methodContext, - CFDictionaryRef faultDict) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern CFDataRef -WSProtocolHandlerCopyRequestDocument( - WSProtocolHandlerRef ref, - CFStringRef methodName, - CFDictionaryRef methodParams, - CFArrayRef methodParamOrder, - CFDictionaryRef methodExtras) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern CFTypeRef -WSProtocolHandlerCopyProperty( - WSProtocolHandlerRef ref, - CFStringRef propertyName) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern void -WSProtocolHandlerSetProperty( - WSProtocolHandlerRef ref, - CFStringRef propertyName, - CFTypeRef propertyValue) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -typedef CFStringRef ( * WSProtocolHandlerSerializationProcPtr)(WSProtocolHandlerRef protocol, CFTypeRef obj, void *info); -extern void -WSProtocolHandlerSetSerializationOverride( - WSProtocolHandlerRef protocol, - CFTypeID objType, - WSProtocolHandlerSerializationProcPtr serializationProc, - WSClientContext * context) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -typedef CFTypeRef ( * WSProtocolHandlerDeserializationProcPtr)(WSProtocolHandlerRef protocol, CFXMLTreeRef msgRoot, CFXMLTreeRef deserializeRoot, void *info); -extern void -WSProtocolHandlerSetDeserializationOverride( - WSProtocolHandlerRef protocol, - CFStringRef typeNamespace, - CFStringRef typeName, - WSProtocolHandlerDeserializationProcPtr deserializationProc, - WSClientContext * context) __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -} -extern "C" { - - - - -enum { - kGenericDocumentIconResource = -4000, - kGenericStationeryIconResource = -3985, - kGenericEditionFileIconResource = -3989, - kGenericApplicationIconResource = -3996, - kGenericDeskAccessoryIconResource = -3991, - kGenericFolderIconResource = -3999, - kPrivateFolderIconResource = -3994, - kFloppyIconResource = -3998, - kTrashIconResource = -3993, - kGenericRAMDiskIconResource = -3988, - kGenericCDROMIconResource = -3987 -}; - - - -enum { - kDesktopIconResource = -3992, - kOpenFolderIconResource = -3997, - kGenericHardDiskIconResource = -3995, - kGenericFileServerIconResource = -3972, - kGenericSuitcaseIconResource = -3970, - kGenericMoverObjectIconResource = -3969 -}; - - - -enum { - kGenericPreferencesIconResource = -3971, - kGenericQueryDocumentIconResource = -16506, - kGenericExtensionIconResource = -16415, - kSystemFolderIconResource = -3983, - kHelpIconResource = -20271, - kAppleMenuFolderIconResource = -3982 -}; - - -enum { - genericDocumentIconResource = kGenericDocumentIconResource, - genericStationeryIconResource = kGenericStationeryIconResource, - genericEditionFileIconResource = kGenericEditionFileIconResource, - genericApplicationIconResource = kGenericApplicationIconResource, - genericDeskAccessoryIconResource = kGenericDeskAccessoryIconResource, - genericFolderIconResource = kGenericFolderIconResource, - privateFolderIconResource = kPrivateFolderIconResource, - floppyIconResource = kFloppyIconResource, - trashIconResource = kTrashIconResource, - genericRAMDiskIconResource = kGenericRAMDiskIconResource, - genericCDROMIconResource = kGenericCDROMIconResource, - desktopIconResource = kDesktopIconResource, - openFolderIconResource = kOpenFolderIconResource, - genericHardDiskIconResource = kGenericHardDiskIconResource, - genericFileServerIconResource = kGenericFileServerIconResource, - genericSuitcaseIconResource = kGenericSuitcaseIconResource, - genericMoverObjectIconResource = kGenericMoverObjectIconResource, - genericPreferencesIconResource = kGenericPreferencesIconResource, - genericQueryDocumentIconResource = kGenericQueryDocumentIconResource, - genericExtensionIconResource = kGenericExtensionIconResource, - systemFolderIconResource = kSystemFolderIconResource, - appleMenuFolderIconResource = kAppleMenuFolderIconResource -}; - - -enum { - kStartupFolderIconResource = -3981, - kOwnedFolderIconResource = -3980, - kDropFolderIconResource = -3979, - kSharedFolderIconResource = -3978, - kMountedFolderIconResource = -3977, - kControlPanelFolderIconResource = -3976, - kPrintMonitorFolderIconResource = -3975, - kPreferencesFolderIconResource = -3974, - kExtensionsFolderIconResource = -3973, - kFontsFolderIconResource = -3968, - kFullTrashIconResource = -3984 -}; - - -enum { - startupFolderIconResource = kStartupFolderIconResource, - ownedFolderIconResource = kOwnedFolderIconResource, - dropFolderIconResource = kDropFolderIconResource, - sharedFolderIconResource = kSharedFolderIconResource, - mountedFolderIconResource = kMountedFolderIconResource, - controlPanelFolderIconResource = kControlPanelFolderIconResource, - printMonitorFolderIconResource = kPrintMonitorFolderIconResource, - preferencesFolderIconResource = kPreferencesFolderIconResource, - extensionsFolderIconResource = kExtensionsFolderIconResource, - fontsFolderIconResource = kFontsFolderIconResource, - fullTrashIconResource = kFullTrashIconResource -}; - - -typedef struct OpaqueIconRef* IconRef; -enum { - kSystemIconsCreator = 'macs' -}; -enum { - kClipboardIcon = 'CLIP', - kClippingUnknownTypeIcon = 'clpu', - kClippingPictureTypeIcon = 'clpp', - kClippingTextTypeIcon = 'clpt', - kClippingSoundTypeIcon = 'clps', - kDesktopIcon = 'desk', - kFinderIcon = 'FNDR', - kComputerIcon = 'root', - kFontSuitcaseIcon = 'FFIL', - kFullTrashIcon = 'ftrh', - kGenericApplicationIcon = 'APPL', - kGenericCDROMIcon = 'cddr', - kGenericControlPanelIcon = 'APPC', - kGenericControlStripModuleIcon = 'sdev', - kGenericComponentIcon = 'thng', - kGenericDeskAccessoryIcon = 'APPD', - kGenericDocumentIcon = 'docu', - kGenericEditionFileIcon = 'edtf', - kGenericExtensionIcon = 'INIT', - kGenericFileServerIcon = 'srvr', - kGenericFontIcon = 'ffil', - kGenericFontScalerIcon = 'sclr', - kGenericFloppyIcon = 'flpy', - kGenericHardDiskIcon = 'hdsk', - kGenericIDiskIcon = 'idsk', - kGenericRemovableMediaIcon = 'rmov', - kGenericMoverObjectIcon = 'movr', - kGenericPCCardIcon = 'pcmc', - kGenericPreferencesIcon = 'pref', - kGenericQueryDocumentIcon = 'qery', - kGenericRAMDiskIcon = 'ramd', - kGenericSharedLibaryIcon = 'shlb', - kGenericStationeryIcon = 'sdoc', - kGenericSuitcaseIcon = 'suit', - kGenericURLIcon = 'gurl', - kGenericWORMIcon = 'worm', - kInternationalResourcesIcon = 'ifil', - kKeyboardLayoutIcon = 'kfil', - kSoundFileIcon = 'sfil', - kSystemSuitcaseIcon = 'zsys', - kTrashIcon = 'trsh', - kTrueTypeFontIcon = 'tfil', - kTrueTypeFlatFontIcon = 'sfnt', - kTrueTypeMultiFlatFontIcon = 'ttcf', - kUserIDiskIcon = 'udsk', - kUnknownFSObjectIcon = 'unfs', - kInternationResourcesIcon = kInternationalResourcesIcon -}; - - -enum { - kInternetLocationHTTPIcon = 'ilht', - kInternetLocationFTPIcon = 'ilft', - kInternetLocationAppleShareIcon = 'ilaf', - kInternetLocationAppleTalkZoneIcon = 'ilat', - kInternetLocationFileIcon = 'ilfi', - kInternetLocationMailIcon = 'ilma', - kInternetLocationNewsIcon = 'ilnw', - kInternetLocationNSLNeighborhoodIcon = 'ilns', - kInternetLocationGenericIcon = 'ilge' -}; - - -enum { - kGenericFolderIcon = 'fldr', - kDropFolderIcon = 'dbox', - kMountedFolderIcon = 'mntd', - kOpenFolderIcon = 'ofld', - kOwnedFolderIcon = 'ownd', - kPrivateFolderIcon = 'prvf', - kSharedFolderIcon = 'shfl' -}; - - -enum { - kSharingPrivsNotApplicableIcon = 'shna', - kSharingPrivsReadOnlyIcon = 'shro', - kSharingPrivsReadWriteIcon = 'shrw', - kSharingPrivsUnknownIcon = 'shuk', - kSharingPrivsWritableIcon = 'writ' -}; - - - -enum { - kUserFolderIcon = 'ufld', - kWorkgroupFolderIcon = 'wfld', - kGuestUserIcon = 'gusr', - kUserIcon = 'user', - kOwnerIcon = 'susr', - kGroupIcon = 'grup' -}; - - -enum { - kAppearanceFolderIcon = 'appr', - kAppleExtrasFolderIcon = 0x616578C4 , - kAppleMenuFolderIcon = 'amnu', - kApplicationsFolderIcon = 'apps', - kApplicationSupportFolderIcon = 'asup', - kAssistantsFolderIcon = 0x617374C4 , - kColorSyncFolderIcon = 'prof', - kContextualMenuItemsFolderIcon = 'cmnu', - kControlPanelDisabledFolderIcon = 'ctrD', - kControlPanelFolderIcon = 'ctrl', - kControlStripModulesFolderIcon = 0x736476C4 , - kDocumentsFolderIcon = 'docs', - kExtensionsDisabledFolderIcon = 'extD', - kExtensionsFolderIcon = 'extn', - kFavoritesFolderIcon = 'favs', - kFontsFolderIcon = 'font', - kHelpFolderIcon = (int)0xC4686C70 , - kInternetFolderIcon = 0x696E74C4 , - kInternetPlugInFolderIcon = (int)0xC46E6574 , - kInternetSearchSitesFolderIcon = 'issf', - kLocalesFolderIcon = (int)0xC46C6F63 , - kMacOSReadMeFolderIcon = 0x6D6F72C4 , - kPublicFolderIcon = 'pubf', - kPreferencesFolderIcon = 0x707266C4 , - kPrinterDescriptionFolderIcon = 'ppdf', - kPrinterDriverFolderIcon = (int)0xC4707264 , - kPrintMonitorFolderIcon = 'prnt', - kRecentApplicationsFolderIcon = 'rapp', - kRecentDocumentsFolderIcon = 'rdoc', - kRecentServersFolderIcon = 'rsrv', - kScriptingAdditionsFolderIcon = (int)0xC4736372 , - kSharedLibrariesFolderIcon = (int)0xC46C6962 , - kScriptsFolderIcon = 0x736372C4 , - kShutdownItemsDisabledFolderIcon = 'shdD', - kShutdownItemsFolderIcon = 'shdf', - kSpeakableItemsFolder = 'spki', - kStartupItemsDisabledFolderIcon = 'strD', - kStartupItemsFolderIcon = 'strt', - kSystemExtensionDisabledFolderIcon = 'macD', - kSystemFolderIcon = 'macs', - kTextEncodingsFolderIcon = (int)0xC4746578 , - kUsersFolderIcon = 0x757372C4 , - kUtilitiesFolderIcon = 0x757469C4 , - kVoicesFolderIcon = 'fvoc' -}; - - -enum { - kAppleScriptBadgeIcon = 'scrp', - kLockedBadgeIcon = 'lbdg', - kMountedBadgeIcon = 'mbdg', - kSharedBadgeIcon = 'sbdg', - kAliasBadgeIcon = 'abdg', - kAlertCautionBadgeIcon = 'cbdg' -}; - - -enum { - kAlertNoteIcon = 'note', - kAlertCautionIcon = 'caut', - kAlertStopIcon = 'stop' -}; - - -enum { - kAppleTalkIcon = 'atlk', - kAppleTalkZoneIcon = 'atzn', - kAFPServerIcon = 'afps', - kFTPServerIcon = 'ftps', - kHTTPServerIcon = 'htps', - kGenericNetworkIcon = 'gnet', - kIPFileServerIcon = 'isrv' -}; - - -enum { - kToolbarCustomizeIcon = 'tcus', - kToolbarDeleteIcon = 'tdel', - kToolbarFavoritesIcon = 'tfav', - kToolbarHomeIcon = 'thom', - kToolbarAdvancedIcon = 'tbav', - kToolbarInfoIcon = 'tbin', - kToolbarLabelsIcon = 'tblb', - kToolbarApplicationsFolderIcon = 'tAps', - kToolbarDocumentsFolderIcon = 'tDoc', - kToolbarMovieFolderIcon = 'tMov', - kToolbarMusicFolderIcon = 'tMus', - kToolbarPicturesFolderIcon = 'tPic', - kToolbarPublicFolderIcon = 'tPub', - kToolbarDesktopFolderIcon = 'tDsk', - kToolbarDownloadsFolderIcon = 'tDwn', - kToolbarLibraryFolderIcon = 'tLib', - kToolbarUtilitiesFolderIcon = 'tUtl', - kToolbarSitesFolderIcon = 'tSts' -}; - - -enum { - kAppleLogoIcon = 'capl', - kAppleMenuIcon = 'sapl', - kBackwardArrowIcon = 'baro', - kFavoriteItemsIcon = 'favr', - kForwardArrowIcon = 'faro', - kGridIcon = 'grid', - kHelpIcon = 'help', - kKeepArrangedIcon = 'arng', - kLockedIcon = 'lock', - kNoFilesIcon = 'nfil', - kNoFolderIcon = 'nfld', - kNoWriteIcon = 'nwrt', - kProtectedApplicationFolderIcon = 'papp', - kProtectedSystemFolderIcon = 'psys', - kRecentItemsIcon = 'rcnt', - kShortcutIcon = 'shrt', - kSortAscendingIcon = 'asnd', - kSortDescendingIcon = 'dsnd', - kUnlockedIcon = 'ulck', - kConnectToIcon = 'cnct', - kGenericWindowIcon = 'gwin', - kQuestionMarkIcon = 'ques', - kDeleteAliasIcon = 'dali', - kEjectMediaIcon = 'ejec', - kBurningIcon = 'burn', - kRightContainerArrowIcon = 'rcar' -}; - - - -typedef UInt32 IconServicesUsageFlags; -enum { - kIconServicesNormalUsageFlag = 0x00000000, - kIconServicesNoBadgeFlag = 0x00000001, - kIconServicesUpdateIfNeededFlag = 0x00000002 -}; -enum { - kIconServicesCatalogInfoMask = (kFSCatInfoNodeID | kFSCatInfoParentDirID | kFSCatInfoVolume | kFSCatInfoNodeFlags | kFSCatInfoFinderInfo | kFSCatInfoFinderXInfo | kFSCatInfoUserAccess | kFSCatInfoPermissions | kFSCatInfoContentMod) -}; -extern OSErr -GetIconRefOwners( - IconRef theIconRef, - UInt16 * owners) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -AcquireIconRef(IconRef theIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -ReleaseIconRef(IconRef theIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -GetIconRef( - SInt16 vRefNum, - OSType creator, - OSType iconType, - IconRef * theIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -GetIconRefFromFolder( - SInt16 vRefNum, - SInt32 parentFolderID, - SInt32 folderID, - SInt8 attributes, - SInt8 accessPrivileges, - IconRef * theIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -GetIconRefFromFileInfo( - const FSRef * inRef, - UniCharCount inFileNameLength, - const UniChar * inFileName, - FSCatalogInfoBitmap inWhichInfo, - const FSCatalogInfo * inCatalogInfo, - IconServicesUsageFlags inUsageFlags, - IconRef * outIconRef, - SInt16 * outLabel) __attribute__((availability(macosx,introduced=10.1))); -extern OSErr -GetIconRefFromTypeInfo( - OSType inCreator, - OSType inType, - CFStringRef inExtension, - CFStringRef inMIMEType, - IconServicesUsageFlags inUsageFlags, - IconRef * outIconRef) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -GetIconRefFromIconFamilyPtr( - const IconFamilyResource * inIconFamilyPtr, - Size inSize, - IconRef * outIconRef) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -GetIconRefFromComponent( - Component inComponent, - IconRef * outIconRef) __attribute__((availability(macosx,introduced=10.5))); -extern OSErr -RegisterIconRefFromIconFamily( - OSType creator, - OSType iconType, - IconFamilyHandle iconFamily, - IconRef * theIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -RegisterIconRefFromFSRef( - OSType creator, - OSType iconType, - const FSRef * iconFile, - IconRef * theIconRef) __attribute__((availability(macosx,introduced=10.1))); -extern OSErr -UnregisterIconRef( - OSType creator, - OSType iconType) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -UpdateIconRef(IconRef theIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -OverrideIconRef( - IconRef oldIconRef, - IconRef newIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -RemoveIconRefOverride(IconRef theIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -CompositeIconRef( - IconRef backgroundIconRef, - IconRef foregroundIconRef, - IconRef * compositeIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -IsIconRefComposite( - IconRef compositeIconRef, - IconRef * backgroundIconRef, - IconRef * foregroundIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern Boolean -IsValidIconRef(IconRef theIconRef) __attribute__((availability(macosx,introduced=10.0))); -extern Boolean -IsDataAvailableInIconRef( - OSType inIconKind, - IconRef inIconRef) __attribute__((availability(macosx,introduced=10.3))); -extern OSErr -SetCustomIconsEnabled( - SInt16 vRefNum, - Boolean enableCustomIcons) __attribute__((availability(macosx,introduced=10.0))); -extern OSErr -GetCustomIconsEnabled( - SInt16 vRefNum, - Boolean * customIconsEnabled) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -ReadIconFromFSRef( - const FSRef * ref, - IconFamilyHandle * iconFamily) __attribute__((availability(macosx,introduced=10.1))); - - - - -} - - - - -extern "C" { - - -#pragma pack(push, 2) -enum { - kLSAppInTrashErr = -10660, - kLSExecutableIncorrectFormat = -10661, - kLSAttributeNotFoundErr = -10662, - kLSAttributeNotSettableErr = -10663, - kLSIncompatibleApplicationVersionErr = -10664, - kLSNoRosettaEnvironmentErr = -10665, - kLSUnknownErr = -10810, - kLSNotAnApplicationErr = -10811, - kLSNotInitializedErr = -10812, - kLSDataUnavailableErr = -10813, - kLSApplicationNotFoundErr = -10814, - kLSUnknownTypeErr = -10815, - kLSDataTooOldErr = -10816, - kLSDataErr = -10817, - kLSLaunchInProgressErr = -10818, - kLSNotRegisteredErr = -10819, - kLSAppDoesNotClaimTypeErr = -10820, - kLSAppDoesNotSupportSchemeWarning = -10821, - kLSServerCommunicationErr = -10822, - kLSCannotSetInfoErr = -10823, - kLSNoRegistrationInfoErr = -10824, - kLSIncompatibleSystemVersionErr = -10825, - kLSNoLaunchPermissionErr = -10826, - kLSNoExecutableErr = -10827, - kLSNoClassicEnvironmentErr = -10828, - kLSMultipleSessionsNotSupportedErr = -10829, -}; - -typedef OptionBits LSRolesMask; enum { - kLSRolesNone = 0x00000001, - kLSRolesViewer = 0x00000002, - kLSRolesEditor = 0x00000004, - kLSRolesShell = 0x00000008, - kLSRolesAll = (UInt32)0xFFFFFFFF -}; - -enum { - kLSUnknownType = 0, - kLSUnknownCreator = 0 -}; - -typedef OptionBits LSAcceptanceFlags; enum { - kLSAcceptDefault = 0x00000001, - kLSAcceptAllowLoginUI = 0x00000002 -}; -extern _Nullable CFURLRef -LSCopyDefaultApplicationURLForURL( - CFURLRef inURL, - LSRolesMask inRoleMask, - _Nullable CFErrorRef *_Nullable outError) __attribute__((availability(macosx,introduced=10.10))); -extern _Nullable CFURLRef -LSCopyDefaultApplicationURLForContentType( - CFStringRef inContentType, - LSRolesMask inRoleMask, - _Nullable CFErrorRef *_Nullable outError) __attribute__((availability(macosx,introduced=10.10))); -extern _Nullable CFArrayRef -LSCopyApplicationURLsForBundleIdentifier( - CFStringRef inBundleIdentifier, - _Nullable CFErrorRef *_Nullable outError) __attribute__((availability(macosx,introduced=10.10))); -extern _Nullable CFArrayRef -LSCopyApplicationURLsForURL( - CFURLRef inURL, - LSRolesMask inRoleMask) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -LSCanURLAcceptURL( - CFURLRef inItemURL, - CFURLRef inTargetURL, - LSRolesMask inRoleMask, - LSAcceptanceFlags inFlags, - Boolean * outAcceptsItem) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -LSRegisterURL( - CFURLRef inURL, - Boolean inUpdate) __attribute__((availability(macosx,introduced=10.3))); -extern _Nullable CFStringRef -LSCopyDefaultRoleHandlerForContentType( - CFStringRef inContentType, - LSRolesMask inRole) __attribute__((availability(macosx,introduced=10.4))); -extern _Nullable CFArrayRef -LSCopyAllRoleHandlersForContentType( - CFStringRef inContentType, - LSRolesMask inRole) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -LSSetDefaultRoleHandlerForContentType( - CFStringRef inContentType, - LSRolesMask inRole, - CFStringRef inHandlerBundleID) __attribute__((availability(macosx,introduced=10.4))); -extern _Nullable CFStringRef -LSCopyDefaultHandlerForURLScheme(CFStringRef inURLScheme) __attribute__((availability(macosx,introduced=10.4))); -extern _Nullable CFArrayRef -LSCopyAllHandlersForURLScheme(CFStringRef inURLScheme) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -LSSetDefaultHandlerForURLScheme( - CFStringRef inURLScheme, - CFStringRef inHandlerBundleID) __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -#pragma pack(pop) - - -} - - - - - -extern "C" { - - -#pragma pack(push, 2) - - - -typedef OptionBits LSRequestedInfo; enum { - kLSRequestExtension __attribute__((availability(macosx,deprecated=10.11,message="Use CFURLCopyPathExtension(), -[NSURL pathExtension], or -[NSString pathExtension] instead."))) = 0x00000001, - kLSRequestTypeCreator __attribute__((availability(macosx,deprecated=10.11,message="Creator codes are deprecated on OS X."))) = 0x00000002, - kLSRequestBasicFlagsOnly __attribute__((availability(macosx,deprecated=10.11,message="Use CFURLCopyResourcePropertiesForKeys or -[NSURL resourceValuesForKeys:error:] instead."))) = 0x00000004, - kLSRequestAppTypeFlags __attribute__((availability(macosx,deprecated=10.11,message="Use CFURLCopyResourcePropertiesForKeys or -[NSURL resourceValuesForKeys:error:] instead."))) = 0x00000008, - kLSRequestAllFlags __attribute__((availability(macosx,deprecated=10.11,message="Use CFURLCopyResourcePropertiesForKeys or -[NSURL resourceValuesForKeys:error:] instead."))) = 0x00000010, - kLSRequestIconAndKind __attribute__((availability(macosx,deprecated=10.11,message="Use CFURLCopyResourcePropertiesForKeys or -[NSURL resourceValuesForKeys:error:] instead."))) = 0x00000020, - kLSRequestExtensionFlagsOnly __attribute__((availability(macosx,deprecated=10.11,message="Use CFURLCopyResourcePropertiesForKeys or -[NSURL resourceValuesForKeys:error:] instead."))) = 0x00000040, - kLSRequestAllInfo __attribute__((availability(macosx,deprecated=10.11,message="Use CFURLCopyResourcePropertiesForKeys or -[NSURL resourceValuesForKeys:error:] instead."))) = (UInt32)0xFFFFFFFF -}; - - - -typedef OptionBits LSItemInfoFlags; enum { - kLSItemInfoIsPlainFile __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLIsRegularFileKey or NSURLIsRegularFileKey instead."))) = 0x00000001, - kLSItemInfoIsPackage __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLIsPackageKey or NSURLIsPackageKey instead."))) = 0x00000002, - kLSItemInfoIsApplication __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLIsApplicationKey or NSURLIsApplicationKey instead."))) = 0x00000004, - kLSItemInfoIsContainer __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLIsDirectoryKey or NSURLIsDirectoryKey instead."))) = 0x00000008, - kLSItemInfoIsAliasFile __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLIsAliasFileKey or NSURLIsAliasFileKey instead."))) = 0x00000010, - kLSItemInfoIsSymlink __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLIsSymbolicLinkKey or NSURLIsSymbolicLinkKey."))) = 0x00000020, - kLSItemInfoIsInvisible __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLIsHiddenKey or NSURLIsHiddenKey instead."))) = 0x00000040, - kLSItemInfoIsNativeApp __attribute__((availability(macosx,deprecated=10.11,message="The Classic environment is no longer supported."))) = 0x00000080, - kLSItemInfoIsClassicApp __attribute__((availability(macosx,deprecated=10.11,message="The Classic environment is no longer supported."))) = 0x00000100, - kLSItemInfoAppPrefersNative __attribute__((availability(macosx,deprecated=10.11,message="The Classic environment is no longer supported."))) = 0x00000200, - kLSItemInfoAppPrefersClassic __attribute__((availability(macosx,deprecated=10.11,message="The Classic environment is no longer supported."))) = 0x00000400, - kLSItemInfoAppIsScriptable __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLApplicationIsScriptableKey or NSURLApplicationIsScriptableKey instead."))) = 0x00000800, - kLSItemInfoIsVolume __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLIsVolumeKey or NSURLIsVolumeKey instead."))) = 0x00001000, - kLSItemInfoExtensionIsHidden __attribute__((availability(macosx,deprecated=10.11,message="Use the URL resource property kCFURLHasHiddenExtensionKey or NSURLHasHiddenExtensionKey instead."))) = 0x00100000 -}; -typedef struct LSItemInfoRecord { - LSItemInfoFlags flags; - OSType filetype; - OSType creator; - CFStringRef extension; -} LSItemInfoRecord __attribute__((availability(macosx,deprecated=10.11,message="Use CFURLCopyResourcePropertiesForKeys or -[NSURL resourceValuesForKeys:error:] instead."))); -extern OSStatus -LSCopyItemInfoForURL( - CFURLRef inURL, - LSRequestedInfo inWhichInfo, - LSItemInfoRecord * outItemInfo) __attribute__((availability(macosx,introduced=10.0,deprecated=10.11,message="Use URL resource properties instead."))); -extern OSStatus -LSCopyItemInfoForRef( - const FSRef * inItemRef, - LSRequestedInfo inWhichInfo, - LSItemInfoRecord * outItemInfo) __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use URL resource properties instead."))); -extern OSStatus -LSGetExtensionInfo( - UniCharCount inNameLen, - const UniChar inNameBuffer[], - UniCharCount * outExtStartIndex) __attribute__((availability(macosx,introduced=10.1,deprecated=10.11,message="Use CFURLCopyPathExtension(), -[NSURL pathExtension], or -[NSString pathExtension] instead."))); -extern OSStatus -LSCopyDisplayNameForRef( - const FSRef * inRef, - CFStringRef * outDisplayName) __attribute__((availability(macosx,introduced=10.1,deprecated=10.10,message="Use the URL resource property kCFURLLocalizedNameKey or NSURLLocalizedNameKey instead."))); -extern OSStatus -LSCopyDisplayNameForURL( - CFURLRef inURL, - CFStringRef * outDisplayName) __attribute__((availability(macosx,introduced=10.1,deprecated=10.11,message="Use the URL resource property kCFURLLocalizedNameKey or NSURLLocalizedNameKey instead."))); -extern OSStatus -LSSetExtensionHiddenForRef( - const FSRef * inRef, - Boolean inHide) __attribute__((availability(macosx,introduced=10.1,deprecated=10.10,message="Use the URL resource property kCFURLHasHiddenExtensionKey or NSURLHasHiddenExtensionKey instead."))); -extern OSStatus -LSSetExtensionHiddenForURL( - CFURLRef inURL, - Boolean inHide) __attribute__((availability(macosx,introduced=10.1,deprecated=10.11,message="Use the URL resource property kCFURLHasHiddenExtensionKey or NSURLHasHiddenExtensionKey instead."))); -extern OSStatus -LSCopyKindStringForRef( - const FSRef * inFSRef, - CFStringRef * outKindString) __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use the URL resource property kCFURLLocalizedTypeDescriptionKey or NSURLLocalizedTypeDescriptionKey instead."))); -extern OSStatus -LSCopyKindStringForURL( - CFURLRef inURL, - CFStringRef * outKindString) __attribute__((availability(macosx,introduced=10.0,deprecated=10.11,message="Use the URL resource property kCFURLLocalizedTypeDescriptionKey or NSURLLocalizedTypeDescriptionKey instead."))); -extern OSStatus -LSCopyKindStringForTypeInfo( - OSType inType, - OSType inCreator, - CFStringRef inExtension, - CFStringRef * outKindString) __attribute__((availability(macosx,introduced=10.2,deprecated=10.10,message="Use UTTypeCopyDescription instead."))); -extern OSStatus -LSCopyKindStringForMIMEType( - CFStringRef inMIMEType, - CFStringRef * outKindString) __attribute__((availability(macosx,introduced=10.2,deprecated=10.10,message="Use UTTypeCopyDescription instead."))); -extern OSStatus -LSGetApplicationForItem( - const FSRef * inItemRef, - LSRolesMask inRoleMask, - FSRef * outAppRef, - CFURLRef * outAppURL) __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use LSCopyDefaultApplicationURLForURL instead."))); -extern OSStatus -LSGetApplicationForInfo( - OSType inType, - OSType inCreator, - CFStringRef inExtension, - LSRolesMask inRoleMask, - FSRef * outAppRef, - CFURLRef * outAppURL) __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use LSCopyDefaultApplicationURLForContentType instead."))); -extern OSStatus -LSCopyApplicationForMIMEType( - CFStringRef inMIMEType, - LSRolesMask inRoleMask, - CFURLRef * outAppURL) __attribute__((availability(macosx,introduced=10.2,deprecated=10.10,message="Use LSCopyDefaultApplicationURLForContentType instead."))); -extern OSStatus -LSGetApplicationForURL( - CFURLRef inURL, - LSRolesMask inRoleMask, - FSRef * outAppRef, - CFURLRef * outAppURL) __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use LSCopyDefaultApplicationURLForURL instead."))); -extern OSStatus -LSFindApplicationForInfo( - OSType inCreator, - CFStringRef inBundleID, - CFStringRef inName, - FSRef * outAppRef, - CFURLRef * outAppURL) __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use LSCopyApplicationURLsForBundleIdentifier instead."))); -extern OSStatus -LSCanRefAcceptItem( - const FSRef * inItemFSRef, - const FSRef * inTargetRef, - LSRolesMask inRoleMask, - LSAcceptanceFlags inFlags, - Boolean * outAcceptsItem) __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use LSCanURLAcceptURL instead."))); -extern OSStatus -LSRegisterFSRef( - const FSRef * inRef, - Boolean inUpdate) __attribute__((availability(macosx,introduced=10.3,deprecated=10.10,message="Use LSRegisterURL instead."))); -extern const CFStringRef kLSItemContentType __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use the URL resource property kCFURLTypeIdentifierKey or NSURLTypeIdentifierKey instead."))); -extern const CFStringRef kLSItemFileType __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use the URL resource property kCFURLTypeIdentifierKey or NSURLTypeIdentifierKey to get the file's UTI instead."))); -extern const CFStringRef kLSItemFileCreator __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use the URL resource property kCFURLTypeIdentifierKey or NSURLTypeIdentifierKey to get the file's UTI instead."))); -extern const CFStringRef kLSItemExtension __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use CFURLCopyPathExtension or -[NSURL pathExtension] instead."))); -extern const CFStringRef kLSItemDisplayName __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use the URL resource property kCFURLLocalizedNameKey or NSURLLocalizedNameKey instead."))); -extern const CFStringRef kLSItemDisplayKind __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use the URL resource property kCFURLLocalizedTypeDescriptionKey or NSURLLocalizedTypeDescriptionKey instead."))); -extern const CFStringRef kLSItemRoleHandlerDisplayName __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Instead, resolve the desired role handler for the file, then use the URL resource property kCFURLLocalizedNameKey or NSURLLocalizedNameKey on the role handler's URL."))); -extern const CFStringRef kLSItemIsInvisible __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use the URL resource property kCFURLIsHiddenKey or NSURLIsHiddenKey instead."))); -extern const CFStringRef kLSItemExtensionIsHidden __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use the URL resource property kCFURLHasHiddenExtensionKey or NSURLHasHiddenExtensionKey instead."))); -extern const CFStringRef kLSItemQuarantineProperties __attribute__((availability(macosx,introduced=10.5,deprecated=10.10,message="Use the URL resource property kCFURLQuarantinePropertiesKey or NSURLQuarantinePropertiesKey instead."))); -extern OSStatus -LSCopyItemAttribute( - const FSRef * inItem, - LSRolesMask inRoles, - CFStringRef inAttributeName, - CFTypeRef * outValue) __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use CFURLCopyResourcePropertyForKey or -[NSURL getResourceValue:forKey:error:] instead."))); -extern OSStatus -LSCopyItemAttributes( - const FSRef * inItem, - LSRolesMask inRoles, - CFArrayRef inAttributeNames, - CFDictionaryRef * outValues) __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use CFURLCopyResourcePropertiesForKeys or -[NSURL resourceValuesForKeys:error:] instead."))); -extern OSStatus -LSSetItemAttribute( - const FSRef * inItem, - LSRolesMask inRoles, - CFStringRef inAttributeName, - CFTypeRef inValue) __attribute__((availability(macosx,introduced=10.5,deprecated=10.10,message="Use CFURLSetResourcePropertyForKey or -[NSURL setResourceValue:forKey:error:] instead."))); -typedef OptionBits LSHandlerOptions; enum { - kLSHandlerOptionsDefault __attribute__((availability(macosx,introduced=10.4,deprecated=10.11,message="Creator codes are deprecated on OS X."))) = 0, - kLSHandlerOptionsIgnoreCreator __attribute__((availability(macosx,introduced=10.4,deprecated=10.11,message="Creator codes are deprecated on OS X."))) = 1 -}; -extern LSHandlerOptions -LSGetHandlerOptionsForContentType(CFStringRef inContentType) __attribute__((availability(macosx,introduced=10.4,deprecated=10.11,message="Creator codes are deprecated on OS X."))); -extern OSStatus -LSSetHandlerOptionsForContentType( - CFStringRef inContentType, - LSHandlerOptions inOptions) __attribute__((availability(macosx,introduced=10.4,deprecated=10.11,message="Creator codes are deprecated on OS X."))); - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -typedef OptionBits LSLaunchFlags; enum { - kLSLaunchDefaults = 0x00000001, - kLSLaunchAndPrint = 0x00000002, - kLSLaunchReserved2 = 0x00000004, - kLSLaunchReserved3 = 0x00000008, - kLSLaunchReserved4 = 0x00000010, - kLSLaunchReserved5 = 0x00000020, - kLSLaunchAndDisplayErrors = 0x00000040, - kLSLaunchInhibitBGOnly = 0x00000080, - kLSLaunchDontAddToRecents = 0x00000100, - kLSLaunchDontSwitch = 0x00000200, - kLSLaunchNoParams = 0x00000800, - kLSLaunchAsync = 0x00010000, - kLSLaunchNewInstance = 0x00080000, - kLSLaunchAndHide = 0x00100000, - kLSLaunchAndHideOthers = 0x00200000, - kLSLaunchHasUntrustedContents = 0x00400000, -}; - - -typedef struct LSLaunchURLSpec { - _Nullable CFURLRef appURL; - _Nullable CFArrayRef itemURLs; - const AEDesc * _Nullable passThruParams; - LSLaunchFlags launchFlags; - void * _Nullable asyncRefCon; -} LSLaunchURLSpec __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -LSOpenCFURLRef( - CFURLRef inURL, - _Nullable CFURLRef *_Nullable outLaunchedURL) __attribute__((availability(macosx,introduced=10.0))); -extern OSStatus -LSOpenFromURLSpec( - const LSLaunchURLSpec * inLaunchSpec, - _Nullable CFURLRef *_Nullable outLaunchedURL) __attribute__((availability(macosx,introduced=10.0))); - - - - - - - - -#pragma pack(pop) - - -} - - - - - -extern "C" { - - -#pragma pack(push, 2) - - - -enum { - kLSLaunchStartClassic __attribute__((availability(macosx,introduced=10.0,deprecated=10.11,message="The Classic environment is no longer supported."))) = 0x00020000, - kLSLaunchInClassic __attribute__((availability(macosx,introduced=10.0,deprecated=10.11,message="The Classic environment is no longer supported."))) = 0x00040000, -}; - - - - -typedef struct LSLaunchFSRefSpec { - const FSRef * appRef; - ItemCount numDocs; - const FSRef * itemRefs; - const AEDesc * passThruParams; - - LSLaunchFlags launchFlags; - void * asyncRefCon; -} LSLaunchFSRefSpec __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use LSLaunchURLSpec instead."))); -extern OSStatus -LSOpenFSRef( - const FSRef * inRef, - FSRef * outLaunchedRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use LSOpenCFURLRef or -[NSWorkspace openURL:] instead."))); -extern OSStatus -LSOpenFromRefSpec( - const LSLaunchFSRefSpec * inLaunchSpec, - FSRef * outLaunchedRef) __attribute__((availability(macosx,introduced=10.0,deprecated=10.10,message="Use LSOpenFromURLSpec or NSWorkspace instead."))); -typedef struct LSApplicationParameters { - CFIndex version; - LSLaunchFlags flags; - const FSRef * application; - void * asyncLaunchRefCon; - CFDictionaryRef environment; - - CFArrayRef argv; - - AppleEvent * initialEvent; -} LSApplicationParameters __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use NSWorkspace instead."))); -extern OSStatus -LSOpenApplication( - const LSApplicationParameters * appParams, - ProcessSerialNumber * outPSN) __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use -[NSWorkspace launchApplicationAtURL:options:configuration:error:] instead."))); -extern OSStatus -LSOpenItemsWithRole( - const FSRef * inItems, - CFIndex inItemCount, - LSRolesMask inRole, - const AEKeyDesc * inAEParam, - const LSApplicationParameters * inAppParams, - ProcessSerialNumber * outPSNs, - CFIndex inMaxPSNCount) __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use NSWorkspace instead."))); -extern OSStatus -LSOpenURLsWithRole( - CFArrayRef inURLs, - LSRolesMask inRole, - const AEKeyDesc * inAEParam, - const LSApplicationParameters * inAppParams, - ProcessSerialNumber * outPSNs, - CFIndex inMaxPSNCount) __attribute__((availability(macosx,introduced=10.4,deprecated=10.10,message="Use NSWorkspace instead."))); - - - - -#pragma pack(pop) - - -} - - - -extern const CFStringRef kLSQuarantineAgentNameKey __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineAgentBundleIdentifierKey __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineTimeStampKey __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineTypeKey __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineTypeWebDownload __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineTypeOtherDownload __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineTypeEmailAttachment __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineTypeInstantMessageAttachment __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineTypeCalendarEventAttachment __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineTypeOtherAttachment __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineOriginURLKey __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kLSQuarantineDataURLKey __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" { -extern const CFStringRef kUTTypeItem __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeContent __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeCompositeContent __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeMessage __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeContact __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeArchive __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeDiskImage __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeData __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeDirectory __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeResolvable __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeSymLink __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeExecutable __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kUTTypeMountPoint __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeAliasFile __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeAliasRecord __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeURLBookmarkData __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeURL __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeFileURL __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeText __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypePlainText __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeUTF8PlainText __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeUTF16ExternalPlainText __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeUTF16PlainText __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeDelimitedText __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeCommaSeparatedText __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeTabSeparatedText __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeUTF8TabSeparatedText __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeRTF __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeHTML __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeXML __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeSourceCode __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeAssemblyLanguageSource __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeCSource __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeObjectiveCSource __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeSwiftSource __attribute__((availability(macosx,introduced=10.11))); -extern const CFStringRef kUTTypeCPlusPlusSource __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeObjectiveCPlusPlusSource __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeCHeader __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeCPlusPlusHeader __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeJavaSource __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeScript __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeAppleScript __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeOSAScript __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeOSAScriptBundle __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeJavaScript __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeShellScript __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypePerlScript __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypePythonScript __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeRubyScript __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypePHPScript __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeJSON __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypePropertyList __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeXMLPropertyList __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeBinaryPropertyList __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypePDF __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeRTFD __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeFlatRTFD __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeTXNTextAndMultimediaData __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeWebArchive __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeImage __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeJPEG __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeJPEG2000 __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeTIFF __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypePICT __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeGIF __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypePNG __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeQuickTimeImage __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeAppleICNS __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeBMP __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeICO __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeRawImage __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeScalableVectorGraphics __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeAudiovisualContent __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeMovie __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeVideo __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeAudio __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeQuickTimeMovie __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeMPEG __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeMPEG2Video __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeMPEG2TransportStream __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeMP3 __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeMPEG4 __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeMPEG4Audio __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeAppleProtectedMPEG4Audio __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeAppleProtectedMPEG4Video __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeAVIMovie __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeAudioInterchangeFileFormat __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeWaveformAudio __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeMIDIAudio __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypePlaylist __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeM3UPlaylist __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeFolder __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeVolume __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypePackage __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeBundle __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypePluginBundle __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeSpotlightImporter __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeQuickLookGenerator __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeXPCService __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeFramework __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeApplication __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeApplicationBundle __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeApplicationFile __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeUnixExecutable __attribute__((availability(macosx,introduced=10.10))); - - -extern const CFStringRef kUTTypeWindowsExecutable __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeJavaClass __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeJavaArchive __attribute__((availability(macosx,introduced=10.10))); - - -extern const CFStringRef kUTTypeSystemPreferencesPane __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeGNUZipArchive __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeBzip2Archive __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeZipArchive __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeSpreadsheet __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypePresentation __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeDatabase __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeVCard __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeToDoItem __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeCalendarEvent __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeEmailMessage __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeInternetLocation __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeInkText __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kUTTypeFont __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeBookmark __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTType3DContent __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypePKCS12 __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeX509Certificate __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeElectronicPublication __attribute__((availability(macosx,introduced=10.10))); -extern const CFStringRef kUTTypeLog __attribute__((availability(macosx,introduced=10.10))); -} - - - -extern "C" { -extern const CFStringRef kUTExportedTypeDeclarationsKey __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTImportedTypeDeclarationsKey __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTypeIdentifierKey __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTypeTagSpecificationKey __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTypeConformsToKey __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTypeDescriptionKey __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTypeIconFileKey __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTypeReferenceURLKey __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTypeVersionKey __attribute__((availability(macosx,introduced=10.3))); -extern const CFStringRef kUTTagClassFilenameExtension __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTagClassMIMEType __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTagClassNSPboardType __attribute__((availability(macosx,introduced=10.3))); - - - -extern const CFStringRef kUTTagClassOSType __attribute__((availability(macosx,introduced=10.3))); -extern _Nullable CFStringRef -UTTypeCreatePreferredIdentifierForTag( - CFStringRef inTagClass, - CFStringRef inTag, - _Nullable CFStringRef inConformingToUTI) __attribute__((availability(macosx,introduced=10.3))); -extern _Nullable CFArrayRef -UTTypeCreateAllIdentifiersForTag( - CFStringRef inTagClass, - CFStringRef inTag, - _Nullable CFStringRef inConformingToUTI) __attribute__((availability(macosx,introduced=10.3))); -extern _Nullable CFStringRef -UTTypeCopyPreferredTagWithClass( - CFStringRef inUTI, - CFStringRef inTagClass) __attribute__((availability(macosx,introduced=10.3))); -extern _Nullable CFArrayRef -UTTypeCopyAllTagsWithClass( - CFStringRef inUTI, - CFStringRef inTagClass) __attribute__((availability(macosx,introduced=10.10))); -extern Boolean -UTTypeEqual( - CFStringRef inUTI1, - CFStringRef inUTI2) __attribute__((availability(macosx,introduced=10.3))); -extern Boolean -UTTypeConformsTo( - CFStringRef inUTI, - CFStringRef inConformsToUTI) __attribute__((availability(macosx,introduced=10.3))); -extern _Nullable CFStringRef -UTTypeCopyDescription(CFStringRef inUTI) __attribute__((availability(macosx,introduced=10.3))); -extern Boolean -UTTypeIsDeclared(CFStringRef inUTI) __attribute__((availability(macosx,introduced=10.10))); -extern Boolean -UTTypeIsDynamic(CFStringRef inUTI) __attribute__((availability(macosx,introduced=10.10))); -extern _Nullable CFDictionaryRef -UTTypeCopyDeclaration(CFStringRef inUTI) __attribute__((availability(macosx,introduced=10.3))); -extern _Nullable CFURLRef -UTTypeCopyDeclaringBundleURL(CFStringRef inUTI) __attribute__((availability(macosx,introduced=10.3))); -extern CFStringRef -UTCreateStringForOSType(OSType inOSType) __attribute__((availability(macosx,introduced=10.3))); -extern OSType -UTGetOSTypeFromString(CFStringRef inString) __attribute__((availability(macosx,introduced=10.3))); -} - - - -extern "C" { - - - - - - -typedef struct __attribute__((objc_bridge(id))) __MDItem * MDItemRef; - - - - - -extern CFTypeID MDItemGetTypeID(void) __attribute__((availability(macosx,introduced=10.4))); -extern MDItemRef MDItemCreate(CFAllocatorRef allocator, CFStringRef path) __attribute__((availability(macosx,introduced=10.4))); -extern MDItemRef MDItemCreateWithURL(CFAllocatorRef allocator, CFURLRef url) __attribute__((availability(macosx,introduced=10.6))); -extern CFArrayRef MDItemsCreateWithURLs(CFAllocatorRef allocator, CFArrayRef urls) __attribute__((availability(macosx,introduced=10.7))); -extern CFTypeRef MDItemCopyAttribute(MDItemRef item, CFStringRef name) __attribute__((availability(macosx,introduced=10.4))); -extern CFDictionaryRef MDItemCopyAttributes(MDItemRef item, CFArrayRef names) __attribute__((availability(macosx,introduced=10.4))); -extern CFDictionaryRef MDItemCopyAttributeList(MDItemRef item, ... ) __attribute__((availability(macosx,introduced=10.4))); -extern CFArrayRef MDItemCopyAttributeNames(MDItemRef item) __attribute__((availability(macosx,introduced=10.4))); -extern CFArrayRef MDItemsCopyAttributes(CFArrayRef items, CFArrayRef names) __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemAttributeChangeDate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemContentType __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemContentTypeTree __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemKeywords __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemTitle __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAuthors __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemEditors __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemParticipants __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kMDItemProjects __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemDownloadedDate __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemWhereFroms __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemComment __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemCopyright __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemLastUsedDate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemContentCreationDate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemContentModificationDate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemDateAdded __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemDurationSeconds __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemContactKeywords __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemVersion __attribute__((availability(macosx,introduced=10.4))); - -extern const CFStringRef kMDItemPixelHeight __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemPixelWidth __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemPixelCount __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kMDItemColorSpace __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemBitsPerSample __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFlashOnOff __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFocalLength __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAcquisitionMake __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAcquisitionModel __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemISOSpeed __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemOrientation __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemLayerNames __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemWhiteBalance __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAperture __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemProfileName __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemResolutionWidthDPI __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemResolutionHeightDPI __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemExposureMode __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemExposureTimeSeconds __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemEXIFVersion __attribute__((availability(macosx,introduced=10.4))); - -extern const CFStringRef kMDItemCameraOwner __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemFocalLength35mm __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemLensModel __attribute__((availability(macosx,introduced=10.7))); - -extern const CFStringRef kMDItemEXIFGPSVersion __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemAltitude __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemLatitude __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemLongitude __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemSpeed __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemTimestamp __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemGPSTrack __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemImageDirection __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemNamedLocation __attribute__((availability(macosx,introduced=10.6))); - -extern const CFStringRef kMDItemGPSStatus __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSMeasureMode __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSDOP __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSMapDatum __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSDestLatitude __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSDestLongitude __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSDestBearing __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSDestDistance __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSProcessingMethod __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSAreaInformation __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSDateStamp __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemGPSDifferental __attribute__((availability(macosx,introduced=10.7))); - -extern const CFStringRef kMDItemCodecs __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemMediaTypes __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemStreamable __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemTotalBitRate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemVideoBitRate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAudioBitRate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemDeliveryType __attribute__((availability(macosx,introduced=10.4))); - -extern const CFStringRef kMDItemAlbum __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemHasAlphaChannel __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemRedEyeOnOff __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemMeteringMode __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemMaxAperture __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFNumber __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemExposureProgram __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemExposureTimeString __attribute__((availability(macosx,introduced=10.4))); - - -extern const CFStringRef kMDItemHeadline __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemInstructions __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemCity __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemStateOrProvince __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemCountry __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSName __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemDisplayName __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemPath __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSSize __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSCreationDate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSContentChangeDate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSOwnerUserID __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSOwnerGroupID __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSExists __attribute__((availability(macosx,introduced=10.4,deprecated=10.4))); -extern const CFStringRef kMDItemFSIsReadable __attribute__((availability(macosx,introduced=10.4,deprecated=10.4))); -extern const CFStringRef kMDItemFSIsWriteable __attribute__((availability(macosx,introduced=10.4,deprecated=10.4))); -extern const CFStringRef kMDItemFSHasCustomIcon __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSIsExtensionHidden __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSIsStationery __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSInvisible __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSLabel __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFSNodeCount __attribute__((availability(macosx,introduced=10.4))); - -extern const CFStringRef kMDItemHTMLContent __attribute__((availability(macosx,introduced=10.11))); -extern const CFStringRef kMDItemTextContent __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAudioSampleRate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAudioChannelCount __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemTempo __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemKeySignature __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemTimeSignature __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAudioEncodingApplication __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemComposer __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemLyricist __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAudioTrackNumber __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemRecordingDate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemMusicalGenre __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemIsGeneralMIDISequence __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemRecordingYear __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemOrganizations __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemLanguages __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemRights __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemPublishers __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemContributors __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemCoverage __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemSubject __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemTheme __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemDescription __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemIdentifier __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAudiences __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemNumberOfPages __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemPageWidth __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemPageHeight __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemSecurityMethod __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemCreator __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemEncodingApplications __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemDueDate __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemStarRating __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemPhoneNumbers __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemEmailAddresses __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemInstantMessageAddresses __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemKind __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemRecipients __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFinderComment __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemFonts __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAppleLoopsRootKey __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAppleLoopsKeyFilterType __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAppleLoopsLoopMode __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemAppleLoopDescriptors __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemMusicalInstrumentCategory __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDItemMusicalInstrumentName __attribute__((availability(macosx,introduced=10.4))); - -extern const CFStringRef kMDItemCFBundleIdentifier __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemSupportFileType __attribute__((availability(macosx,introduced=10.5,deprecated=10.5))); -extern const CFStringRef kMDItemInformation __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemDirector __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemProducer __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemGenre __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemPerformers __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemOriginalFormat __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemOriginalSource __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemAuthorEmailAddresses __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemRecipientEmailAddresses __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kMDItemAuthorAddresses __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kMDItemRecipientAddresses __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kMDItemURL __attribute__((availability(macosx,introduced=10.5))); - -extern const CFStringRef kMDItemLabelIcon __attribute__((availability(macosx,introduced=10.7,deprecated=10.7))); -extern const CFStringRef kMDItemLabelID __attribute__((availability(macosx,introduced=10.7,deprecated=10.7))); -extern const CFStringRef kMDItemLabelKind __attribute__((availability(macosx,introduced=10.7,deprecated=10.7))); -extern const CFStringRef kMDItemLabelUUID __attribute__((availability(macosx,introduced=10.7,deprecated=10.7))); - -extern const CFStringRef kMDItemIsLikelyJunk __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemExecutableArchitectures __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemExecutablePlatform __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kMDItemApplicationCategories __attribute__((availability(macosx,introduced=10.7))); - -extern const CFStringRef kMDItemIsApplicationManaged __attribute__((availability(macosx,introduced=10.7))); - -} - - - - - -extern "C" { - -extern CFDictionaryRef __MDItemCopyAttributesEllipsis1(MDItemRef item, ...) __attribute__((availability(macosx,introduced=10.4))); -} -extern "C" { - - - - - - -typedef struct __attribute__((objc_bridge(id))) __MDQuery * MDQueryRef; - -typedef enum { - kMDQuerySynchronous = 1, - kMDQueryWantsUpdates = 4, - kMDQueryAllowFSTranslation = 8 -} MDQueryOptionFlags; -extern CFTypeID MDQueryGetTypeID(void) __attribute__((availability(macosx,introduced=10.4))); -extern MDQueryRef MDQueryCreate(CFAllocatorRef allocator, CFStringRef queryString, CFArrayRef valueListAttrs, CFArrayRef sortingAttrs) __attribute__((availability(macosx,introduced=10.4))); -extern MDQueryRef MDQueryCreateSubset(CFAllocatorRef allocator, MDQueryRef query, CFStringRef queryString, CFArrayRef valueListAttrs, CFArrayRef sortingAttrs) __attribute__((availability(macosx,introduced=10.4))); -extern MDQueryRef MDQueryCreateForItems(CFAllocatorRef allocator, - CFStringRef queryString, - CFArrayRef valueListAttrs, - CFArrayRef sortingAttrs, - CFArrayRef items) __attribute__((availability(macosx,introduced=10.7))); -extern CFStringRef MDQueryCopyQueryString(MDQueryRef query) __attribute__((availability(macosx,introduced=10.4))); -extern CFArrayRef MDQueryCopyValueListAttributes(MDQueryRef query) __attribute__((availability(macosx,introduced=10.4))); -extern CFArrayRef MDQueryCopySortingAttributes(MDQueryRef query) __attribute__((availability(macosx,introduced=10.4))); -typedef struct { - size_t first_max_num; - size_t first_max_ms; - size_t progress_max_num; - size_t progress_max_ms; - size_t update_max_num; - size_t update_max_ms; -} MDQueryBatchingParams; -extern MDQueryBatchingParams MDQueryGetBatchingParameters(MDQueryRef query) __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern void MDQuerySetBatchingParameters(MDQueryRef query, MDQueryBatchingParams params) __attribute__((availability(macosx,introduced=10.4))); -typedef const void *(*MDQueryCreateResultFunction)(MDQueryRef query, MDItemRef item, void *context); -extern void MDQuerySetCreateResultFunction(MDQueryRef query, MDQueryCreateResultFunction func, void *context, const CFArrayCallBacks *cb) __attribute__((availability(macosx,introduced=10.4))); -typedef const void *(*MDQueryCreateValueFunction)(MDQueryRef query, CFStringRef attrName, CFTypeRef attrValue, void *context); -extern void MDQuerySetCreateValueFunction(MDQueryRef query, MDQueryCreateValueFunction func, void *context, const CFArrayCallBacks *cb) __attribute__((availability(macosx,introduced=10.4))); -extern void MDQuerySetDispatchQueue(MDQueryRef query, dispatch_queue_t queue) __attribute__((availability(macosx,introduced=10.6))); -extern Boolean MDQueryExecute(MDQueryRef query, CFOptionFlags optionFlags) __attribute__((availability(macosx,introduced=10.4))); -extern void MDQueryStop(MDQueryRef query) __attribute__((availability(macosx,introduced=10.4))); -extern void MDQueryDisableUpdates(MDQueryRef query) __attribute__((availability(macosx,introduced=10.4))); -extern void MDQueryEnableUpdates(MDQueryRef query) __attribute__((availability(macosx,introduced=10.4))); -extern Boolean MDQueryIsGatheringComplete(MDQueryRef query) __attribute__((availability(macosx,introduced=10.4))); -extern CFIndex MDQueryGetResultCount(MDQueryRef query) __attribute__((availability(macosx,introduced=10.4))); -extern const void *MDQueryGetResultAtIndex(MDQueryRef query, CFIndex idx) __attribute__((availability(macosx,introduced=10.4))); -extern CFIndex MDQueryGetIndexOfResult(MDQueryRef query, const void *result) __attribute__((availability(macosx,introduced=10.4))); -extern void *MDQueryGetAttributeValueOfResultAtIndex(MDQueryRef query, CFStringRef name, CFIndex idx) __attribute__((availability(macosx,introduced=10.4))); -extern CFArrayRef MDQueryCopyValuesOfAttribute(MDQueryRef query, CFStringRef name) __attribute__((availability(macosx,introduced=10.4))); -extern CFIndex MDQueryGetCountOfResultsWithAttributeValue(MDQueryRef query, CFStringRef name, CFTypeRef value) __attribute__((availability(macosx,introduced=10.4))); -extern Boolean MDQuerySetSortOrder(MDQueryRef query, CFArrayRef sortingAttrs) __attribute__((availability(macosx,introduced=10.7))); - - - - - -typedef enum { - kMDQueryReverseSortOrderFlag = (1<<0), -} MDQuerySortOptionFlags; -extern Boolean MDQuerySetSortOptionFlagsForAttribute(MDQueryRef query, CFStringRef fieldName, uint32_t flags) __attribute__((availability(macosx,introduced=10.7))); -extern uint32_t MDQueryGetSortOptionFlagsForAttribute(MDQueryRef query, CFStringRef fieldName) __attribute__((availability(macosx,introduced=10.7))); -typedef CFComparisonResult (*MDQuerySortComparatorFunction)(const CFTypeRef attrs1[], const CFTypeRef attrs2[], void *context); -extern void MDQuerySetSortComparator(MDQueryRef query, MDQuerySortComparatorFunction comparator, void *context) __attribute__((availability(macosx,introduced=10.4))); -extern void MDQuerySetSortComparatorBlock(MDQueryRef query, CFComparisonResult (*comparator)(const CFTypeRef attrs1[], const CFTypeRef attrs2[])) __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kMDQueryProgressNotification __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDQueryDidFinishNotification __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDQueryDidUpdateNotification __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDQueryUpdateAddedItems __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDQueryUpdateChangedItems __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDQueryUpdateRemovedItems __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDQueryResultContentRelevance __attribute__((availability(macosx,introduced=10.4))); -extern void MDQuerySetSearchScope(MDQueryRef query, CFArrayRef scopeDirectories, OptionBits scopeOptions) __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern const CFStringRef kMDQueryScopeHome __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern const CFStringRef kMDQueryScopeComputer __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern const CFStringRef kMDQueryScopeNetwork __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern const CFStringRef kMDQueryScopeAllIndexed __attribute__((availability(macosx,introduced=10.6))); - - - - - - - -extern const CFStringRef kMDQueryScopeComputerIndexed __attribute__((availability(macosx,introduced=10.6))); - - - - - - -extern const CFStringRef kMDQueryScopeNetworkIndexed __attribute__((availability(macosx,introduced=10.6))); -extern void MDQuerySetMaxCount(MDQueryRef query, CFIndex size) __attribute__((availability(macosx,introduced=10.5))); - -} - - - - - -extern "C" { - - - - - -typedef struct __MDLabel * MDLabelRef; - -extern CFTypeID MDLabelGetTypeID(void) -__attribute__((availability(macosx,introduced=10.7))); -extern CFArrayRef MDItemCopyLabels(MDItemRef item) -__attribute__((availability(macosx,introduced=10.7))); -extern Boolean MDItemSetLabel(MDItemRef item, MDLabelRef label) -__attribute__((availability(macosx,introduced=10.7))); -extern Boolean MDItemRemoveLabel(MDItemRef item, MDLabelRef label) -__attribute__((availability(macosx,introduced=10.7))); - - - - - -typedef enum { - kMDLabelUserDomain, - kMDLabelLocalDomain, -} MDLabelDomain; -extern MDLabelRef MDLabelCreate(CFAllocatorRef allocator, - CFStringRef displayName, - CFStringRef kind, - MDLabelDomain domain) -__attribute__((availability(macosx,introduced=10.7))); -extern CFTypeRef MDLabelCopyAttribute(MDLabelRef label, - CFStringRef name) -__attribute__((availability(macosx,introduced=10.7))); - - - - - - - -extern CFStringRef MDLabelCopyAttributeName(MDLabelRef label) -__attribute__((availability(macosx,introduced=10.7))); - - - - - - - -extern Boolean MDLabelDelete(MDLabelRef label) -__attribute__((availability(macosx,introduced=10.7))); -extern Boolean MDLabelSetAttributes(MDLabelRef label, - CFDictionaryRef attrs) -__attribute__((availability(macosx,introduced=10.7))); - - - - - - -extern CFArrayRef MDCopyLabelKinds(void) -__attribute__((availability(macosx,introduced=10.7))); - - - - - - - -extern CFArrayRef MDCopyLabelsMatchingExpression(CFStringRef simpleQueryString) -__attribute__((availability(macosx,introduced=10.7))); - - - - - - - -extern CFArrayRef MDCopyLabelsWithKind(CFStringRef kind) -__attribute__((availability(macosx,introduced=10.7))); - - - - - - - -extern MDLabelRef MDCopyLabelWithUUID(CFUUIDRef labelUUID) -__attribute__((availability(macosx,introduced=10.7))); -extern CFStringRef kMDLabelBundleURL -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelContentChangeDate -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelDisplayName -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelIconData -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelIconUUID -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelIsMutuallyExclusiveSetMember -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelKind -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelSetsFinderColor -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelUUID -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelVisibility -__attribute__((availability(macosx,introduced=10.7))); -extern CFStringRef kMDLabelKindIsMutuallyExclusiveSetKey -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDLabelKindVisibilityKey -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDPrivateVisibility -__attribute__((availability(macosx,introduced=10.7))); - -extern CFStringRef kMDPublicVisibility -__attribute__((availability(macosx,introduced=10.7))); - - - - - -extern const CFStringRef kMDLabelAddedNotification -__attribute__((availability(macosx,introduced=10.7))); - - - - - -extern const CFStringRef kMDLabelChangedNotification -__attribute__((availability(macosx,introduced=10.7))); - - - - - -extern const CFStringRef kMDLabelRemovedNotification -__attribute__((availability(macosx,introduced=10.7))); - -} - -extern "C" { -extern CFDictionaryRef MDSchemaCopyAttributesForContentType(CFStringRef contentTypeUTI) __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern CFDictionaryRef MDSchemaCopyMetaAttributesForAttribute(CFStringRef name) __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern CFArrayRef MDSchemaCopyAllAttributes(void) __attribute__((availability(macosx,introduced=10.4))); -extern CFStringRef MDSchemaCopyDisplayNameForAttribute(CFStringRef name) __attribute__((availability(macosx,introduced=10.4))); -extern CFStringRef MDSchemaCopyDisplayDescriptionForAttribute(CFStringRef name) __attribute__((availability(macosx,introduced=10.4))); - - -extern const CFStringRef kMDAttributeDisplayValues __attribute__((availability(macosx,introduced=10.4))); - - - -extern const CFStringRef kMDAttributeAllValues __attribute__((availability(macosx,introduced=10.4))); - - - -extern const CFStringRef kMDAttributeReadOnlyValues __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kMDExporterAvaliable __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern const CFStringRef kMDAttributeName __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDAttributeType __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kMDAttributeMultiValued __attribute__((availability(macosx,introduced=10.4))); - -} -extern "C" { -} - - - - - - - -extern "C" { -typedef CFTypeRef SKDocumentRef; -extern CFTypeID -SKDocumentGetTypeID(void) __attribute__((availability(macosx,introduced=10.3))); -extern SKDocumentRef -SKDocumentCreateWithURL(CFURLRef inURL) __attribute__((availability(macosx,introduced=10.3))); -extern CFURLRef -SKDocumentCopyURL(SKDocumentRef inDocument) __attribute__((availability(macosx,introduced=10.3))); -extern SKDocumentRef -SKDocumentCreate( - CFStringRef inScheme, - SKDocumentRef inParent, - CFStringRef inName) __attribute__((availability(macosx,introduced=10.3))); -extern CFStringRef -SKDocumentGetSchemeName(SKDocumentRef inDocument) __attribute__((availability(macosx,introduced=10.3))); -extern CFStringRef -SKDocumentGetName(SKDocumentRef inDocument) __attribute__((availability(macosx,introduced=10.3))); -extern SKDocumentRef -SKDocumentGetParent(SKDocumentRef inDocument) __attribute__((availability(macosx,introduced=10.3))); - - - - -} - - - -extern const CFStringRef kSKMinTermLength __attribute__((availability(macosx,introduced=10.3))); -extern const CFStringRef kSKSubstitutions __attribute__((availability(macosx,introduced=10.3))); -extern const CFStringRef kSKStopWords __attribute__((availability(macosx,introduced=10.3))); -extern const CFStringRef kSKProximityIndexing __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kSKMaximumTerms __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kSKTermChars __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kSKStartTermChars __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kSKEndTermChars __attribute__((availability(macosx,introduced=10.4))); -extern const CFStringRef kSKLanguageTypes __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); - - - -extern "C" { -typedef struct __SKIndex* SKIndexRef; -extern CFTypeID -SKIndexGetTypeID(void) __attribute__((availability(macosx,introduced=10.3))); -typedef struct __SKIndexDocumentIterator* SKIndexDocumentIteratorRef; -extern CFTypeID -SKIndexDocumentIteratorGetTypeID(void) __attribute__((availability(macosx,introduced=10.3))); -enum SKIndexType { - - - - - kSKIndexUnknown = 0, - - - - - kSKIndexInverted = 1, - - - - - kSKIndexVector = 2, - - - - - - kSKIndexInvertedVector = 3 -}; -typedef enum SKIndexType SKIndexType; -enum SKDocumentIndexState { - - - - - kSKDocumentStateNotIndexed = 0, - - - - - kSKDocumentStateIndexed = 1, - - - - - - kSKDocumentStateAddPending = 2, - - - - - - kSKDocumentStateDeletePending = 3 -}; -typedef enum SKDocumentIndexState SKDocumentIndexState; -extern SKIndexRef -SKIndexCreateWithURL( - CFURLRef inURL, - CFStringRef inIndexName, - SKIndexType inIndexType, - CFDictionaryRef inAnalysisProperties) __attribute__((availability(macosx,introduced=10.3))); -extern SKIndexRef -SKIndexOpenWithURL( - CFURLRef inURL, - CFStringRef inIndexName, - Boolean inWriteAccess) __attribute__((availability(macosx,introduced=10.3))); -extern SKIndexRef -SKIndexCreateWithMutableData( - CFMutableDataRef inData, - CFStringRef inIndexName, - SKIndexType inIndexType, - CFDictionaryRef inAnalysisProperties) __attribute__((availability(macosx,introduced=10.3))); -extern SKIndexRef -SKIndexOpenWithData( - CFDataRef inData, - CFStringRef inIndexName) __attribute__((availability(macosx,introduced=10.3))); -extern SKIndexRef -SKIndexOpenWithMutableData( - CFMutableDataRef inData, - CFStringRef inIndexName) __attribute__((availability(macosx,introduced=10.3))); -extern Boolean -SKIndexFlush(SKIndexRef inIndex) __attribute__((availability(macosx,introduced=10.3))); -extern void -SKIndexSetMaximumBytesBeforeFlush( - SKIndexRef inIndex, - CFIndex inBytesForUpdate) __attribute__((availability(macosx,introduced=10.3))); -extern CFIndex -SKIndexGetMaximumBytesBeforeFlush(SKIndexRef inIndex) __attribute__((availability(macosx,introduced=10.3))); -extern Boolean -SKIndexCompact(SKIndexRef inIndex) __attribute__((availability(macosx,introduced=10.3))); -extern SKIndexType -SKIndexGetIndexType(SKIndexRef inIndex) __attribute__((availability(macosx,introduced=10.3))); -extern CFDictionaryRef -SKIndexGetAnalysisProperties(SKIndexRef inIndex) __attribute__((availability(macosx,introduced=10.3))); -extern CFIndex -SKIndexGetDocumentCount(SKIndexRef inIndex) __attribute__((availability(macosx,introduced=10.3))); -extern void -SKIndexClose(SKIndexRef inIndex) __attribute__((availability(macosx,introduced=10.4))); - - - - - -typedef CFIndex SKDocumentID; -extern Boolean -SKIndexAddDocumentWithText( - SKIndexRef inIndex, - SKDocumentRef inDocument, - CFStringRef inDocumentText, - Boolean inCanReplace) __attribute__((availability(macosx,introduced=10.3))); -extern Boolean -SKIndexAddDocument( - SKIndexRef inIndex, - SKDocumentRef inDocument, - CFStringRef inMIMETypeHint, - Boolean inCanReplace) __attribute__((availability(macosx,introduced=10.3))); -extern Boolean -SKIndexRemoveDocument( - SKIndexRef inIndex, - SKDocumentRef inDocument) __attribute__((availability(macosx,introduced=10.3))); -extern CFDictionaryRef -SKIndexCopyDocumentProperties( - SKIndexRef inIndex, - SKDocumentRef inDocument) __attribute__((availability(macosx,introduced=10.3))); -extern void -SKIndexSetDocumentProperties( - SKIndexRef inIndex, - SKDocumentRef inDocument, - CFDictionaryRef inProperties) __attribute__((availability(macosx,introduced=10.3))); -extern SKDocumentIndexState -SKIndexGetDocumentState( - SKIndexRef inIndex, - SKDocumentRef inDocument) __attribute__((availability(macosx,introduced=10.3))); -extern SKDocumentID -SKIndexGetDocumentID( - SKIndexRef inIndex, - SKDocumentRef inDocument) __attribute__((availability(macosx,introduced=10.3))); -extern SKDocumentRef -SKIndexCopyDocumentForDocumentID( - SKIndexRef inIndex, - SKDocumentID inDocumentID) __attribute__((availability(macosx,introduced=10.3))); -extern Boolean -SKIndexRenameDocument( - SKIndexRef inIndex, - SKDocumentRef inDocument, - CFStringRef inNewName) __attribute__((availability(macosx,introduced=10.3))); -extern Boolean -SKIndexMoveDocument( - SKIndexRef inIndex, - SKDocumentRef inDocument, - SKDocumentRef inNewParent) __attribute__((availability(macosx,introduced=10.3))); -extern SKIndexDocumentIteratorRef -SKIndexDocumentIteratorCreate( - SKIndexRef inIndex, - SKDocumentRef inParentDocument) __attribute__((availability(macosx,introduced=10.3))); -extern SKDocumentRef -SKIndexDocumentIteratorCopyNext(SKIndexDocumentIteratorRef inIterator) __attribute__((availability(macosx,introduced=10.3))); -extern SKDocumentID -SKIndexGetMaximumDocumentID(SKIndexRef inIndex) __attribute__((availability(macosx,introduced=10.3))); -extern CFIndex -SKIndexGetDocumentTermCount( - SKIndexRef inIndex, - SKDocumentID inDocumentID) __attribute__((availability(macosx,introduced=10.3))); -extern CFArrayRef -SKIndexCopyTermIDArrayForDocumentID( - SKIndexRef inIndex, - SKDocumentID inDocumentID) __attribute__((availability(macosx,introduced=10.3))); -extern CFIndex -SKIndexGetDocumentTermFrequency( - SKIndexRef inIndex, - SKDocumentID inDocumentID, - CFIndex inTermID) __attribute__((availability(macosx,introduced=10.3))); -extern CFIndex -SKIndexGetMaximumTermID(SKIndexRef inIndex) __attribute__((availability(macosx,introduced=10.3))); -extern CFIndex -SKIndexGetTermDocumentCount( - SKIndexRef inIndex, - CFIndex inTermID) __attribute__((availability(macosx,introduced=10.3))); -extern CFArrayRef -SKIndexCopyDocumentIDArrayForTermID( - SKIndexRef inIndex, - CFIndex inTermID) __attribute__((availability(macosx,introduced=10.3))); -extern CFStringRef -SKIndexCopyTermStringForTermID( - SKIndexRef inIndex, - CFIndex inTermID) __attribute__((availability(macosx,introduced=10.3))); -extern CFIndex -SKIndexGetTermIDForTermString( - SKIndexRef inIndex, - CFStringRef inTermString) __attribute__((availability(macosx,introduced=10.3))); -extern void -SKLoadDefaultExtractorPlugIns(void) __attribute__((availability(macosx,introduced=10.3))); -} - - - -extern "C" { -typedef struct __SKSearch* SKSearchRef; -extern CFTypeID -SKSearchGetTypeID(void) __attribute__((availability(macosx,introduced=10.4))); -typedef UInt32 SKSearchOptions; -enum { - kSKSearchOptionDefault = 0, - kSKSearchOptionNoRelevanceScores = 1L << 0, - kSKSearchOptionSpaceMeansOR = 1L << 1, - kSKSearchOptionFindSimilar = 1L << 2 -}; -extern SKSearchRef -SKSearchCreate( - SKIndexRef inIndex, - CFStringRef inQuery, - SKSearchOptions inSearchOptions) __attribute__((availability(macosx,introduced=10.4))); -extern void -SKSearchCancel(SKSearchRef inSearch) __attribute__((availability(macosx,introduced=10.4))); -extern Boolean -SKSearchFindMatches( - SKSearchRef inSearch, - CFIndex inMaximumCount, - SKDocumentID * outDocumentIDsArray, - float * outScoresArray, - CFTimeInterval maximumTime, - CFIndex * outFoundCount) __attribute__((availability(macosx,introduced=10.4))); -extern void -SKIndexCopyInfoForDocumentIDs( - SKIndexRef inIndex, - CFIndex inCount, - SKDocumentID * inDocumentIDsArray, - CFStringRef * outNamesArray, - SKDocumentID * outParentIDsArray) __attribute__((availability(macosx,introduced=10.4))); -extern void -SKIndexCopyDocumentRefsForDocumentIDs( - SKIndexRef inIndex, - CFIndex inCount, - SKDocumentID * inDocumentIDsArray, - SKDocumentRef * outDocumentRefsArray) __attribute__((availability(macosx,introduced=10.4))); -extern void -SKIndexCopyDocumentURLsForDocumentIDs( - SKIndexRef inIndex, - CFIndex inCount, - SKDocumentID * inDocumentIDsArray, - CFURLRef * outDocumentURLsArray) __attribute__((availability(macosx,introduced=10.4))); -typedef struct __SKSearchGroup* SKSearchGroupRef; -extern CFTypeID -SKSearchGroupGetTypeID(void) __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); -typedef struct __SKSearchResults* SKSearchResultsRef; -extern CFTypeID -SKSearchResultsGetTypeID(void) __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); -enum SKSearchType { - - - - - kSKSearchRanked = 0, - - - - - - kSKSearchBooleanRanked = 1, - - - - - kSKSearchRequiredRanked = 2, - - - - - kSKSearchPrefixRanked = 3 -}; -typedef enum SKSearchType SKSearchType; -typedef Boolean ( * SKSearchResultsFilterCallBack)(SKIndexRef inIndex, SKDocumentRef inDocument, void *inContext); -extern SKSearchGroupRef -SKSearchGroupCreate(CFArrayRef inArrayOfInIndexes) __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); -extern CFArrayRef -SKSearchGroupCopyIndexes(SKSearchGroupRef inSearchGroup) __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); -extern SKSearchResultsRef -SKSearchResultsCreateWithQuery( - SKSearchGroupRef inSearchGroup, - CFStringRef inQuery, - SKSearchType inSearchType, - CFIndex inMaxFoundDocuments, - void * inContext, - SKSearchResultsFilterCallBack inFilterCallBack) __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); -extern SKSearchResultsRef -SKSearchResultsCreateWithDocuments( - SKSearchGroupRef inSearchGroup, - CFArrayRef inExampleDocuments, - CFIndex inMaxFoundDocuments, - void * inContext, - SKSearchResultsFilterCallBack inFilterCallBack) __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); -extern CFIndex -SKSearchResultsGetCount(SKSearchResultsRef inSearchResults) __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); -extern CFIndex -SKSearchResultsGetInfoInRange( - SKSearchResultsRef inSearchResults, - CFRange inRange, - SKDocumentRef * outDocumentsArray, - SKIndexRef * outIndexesArray, - float * outScoresArray) __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); -extern CFArrayRef -SKSearchResultsCopyMatchingTerms( - SKSearchResultsRef inSearchResults, - CFIndex inItem) __attribute__((availability(macosx,introduced=10.3,deprecated=10.4))); -} - - - -extern "C" { -typedef struct __SKSummary* SKSummaryRef; -extern CFTypeID -SKSummaryGetTypeID(void) __attribute__((availability(macosx,introduced=10.4))); -extern SKSummaryRef -SKSummaryCreateWithString(CFStringRef inString) __attribute__((availability(macosx,introduced=10.4))); -extern CFIndex -SKSummaryGetSentenceCount(SKSummaryRef summary) __attribute__((availability(macosx,introduced=10.4))); -extern CFIndex -SKSummaryGetParagraphCount(SKSummaryRef summary) __attribute__((availability(macosx,introduced=10.4))); -extern CFStringRef -SKSummaryCopySentenceAtIndex( - SKSummaryRef summary, - CFIndex i) __attribute__((availability(macosx,introduced=10.4))); -extern CFStringRef -SKSummaryCopyParagraphAtIndex( - SKSummaryRef summary, - CFIndex i) __attribute__((availability(macosx,introduced=10.4))); -extern CFStringRef -SKSummaryCopySentenceSummaryString( - SKSummaryRef summary, - CFIndex numSentences) __attribute__((availability(macosx,introduced=10.4))); -extern CFStringRef -SKSummaryCopyParagraphSummaryString( - SKSummaryRef summary, - CFIndex numParagraphs) __attribute__((availability(macosx,introduced=10.4))); -extern CFIndex -SKSummaryGetSentenceSummaryInfo( - SKSummaryRef summary, - CFIndex numSentencesInSummary, - CFIndex * outRankOrderOfSentences, - CFIndex * outSentenceIndexOfSentences, - CFIndex * outParagraphIndexOfSentences) __attribute__((availability(macosx,introduced=10.4))); -extern CFIndex -SKSummaryGetParagraphSummaryInfo( - SKSummaryRef summary, - CFIndex numParagraphsInSummary, - CFIndex * outRankOrderOfParagraphs, - CFIndex * outParagraphIndexOfParagraphs) __attribute__((availability(macosx,introduced=10.4))); - - - - -} - - - -extern "C" { - - - - -#pragma pack(push, 2) -typedef UInt32 FSEventStreamCreateFlags; -enum { - - - - - kFSEventStreamCreateFlagNone = 0x00000000, - - - - - - - - kFSEventStreamCreateFlagUseCFTypes = 0x00000001, - kFSEventStreamCreateFlagNoDefer = 0x00000002, - kFSEventStreamCreateFlagWatchRoot = 0x00000004, - kFSEventStreamCreateFlagIgnoreSelf __attribute__((availability(macosx,introduced=10.6))) = 0x00000008, - - - - - - - - kFSEventStreamCreateFlagFileEvents __attribute__((availability(macosx,introduced=10.7))) = 0x00000010, - kFSEventStreamCreateFlagMarkSelf __attribute__((availability(macosx,introduced=10.9))) = 0x00000020 -}; -typedef UInt32 FSEventStreamEventFlags; -enum { - - - - - - kFSEventStreamEventFlagNone = 0x00000000, - kFSEventStreamEventFlagMustScanSubDirs = 0x00000001, - kFSEventStreamEventFlagUserDropped = 0x00000002, - kFSEventStreamEventFlagKernelDropped = 0x00000004, - - - - - - - - kFSEventStreamEventFlagEventIdsWrapped = 0x00000008, - kFSEventStreamEventFlagHistoryDone = 0x00000010, - kFSEventStreamEventFlagRootChanged = 0x00000020, - kFSEventStreamEventFlagMount = 0x00000040, - kFSEventStreamEventFlagUnmount = 0x00000080, - - - - - - kFSEventStreamEventFlagItemCreated __attribute__((availability(macosx,introduced=10.7))) = 0x00000100, - - - - - - kFSEventStreamEventFlagItemRemoved __attribute__((availability(macosx,introduced=10.7))) = 0x00000200, - - - - - - kFSEventStreamEventFlagItemInodeMetaMod __attribute__((availability(macosx,introduced=10.7))) = 0x00000400, - - - - - - kFSEventStreamEventFlagItemRenamed __attribute__((availability(macosx,introduced=10.7))) = 0x00000800, - - - - - - kFSEventStreamEventFlagItemModified __attribute__((availability(macosx,introduced=10.7))) = 0x00001000, - - - - - - kFSEventStreamEventFlagItemFinderInfoMod __attribute__((availability(macosx,introduced=10.7))) = 0x00002000, - - - - - - kFSEventStreamEventFlagItemChangeOwner __attribute__((availability(macosx,introduced=10.7))) = 0x00004000, - - - - - - kFSEventStreamEventFlagItemXattrMod __attribute__((availability(macosx,introduced=10.7))) = 0x00008000, - - - - - - kFSEventStreamEventFlagItemIsFile __attribute__((availability(macosx,introduced=10.7))) = 0x00010000, - - - - - - kFSEventStreamEventFlagItemIsDir __attribute__((availability(macosx,introduced=10.7))) = 0x00020000, - - - - - - kFSEventStreamEventFlagItemIsSymlink __attribute__((availability(macosx,introduced=10.7))) = 0x00040000, - - - - - - kFSEventStreamEventFlagOwnEvent __attribute__((availability(macosx,introduced=10.9))) = 0x00080000, - - - - - - kFSEventStreamEventFlagItemIsHardlink __attribute__((availability(macosx,introduced=10.10))) = 0x00100000, - - - - - kFSEventStreamEventFlagItemIsLastHardlink __attribute__((availability(macosx,introduced=10.10))) = 0x00200000, - -}; -typedef UInt64 FSEventStreamEventId; - -enum { - kFSEventStreamEventIdSinceNow = 0xFFFFFFFFFFFFFFFFULL -}; -typedef struct __FSEventStream* FSEventStreamRef; - - - - - - - -typedef const struct __FSEventStream* ConstFSEventStreamRef; -struct FSEventStreamContext { - - - - - CFIndex version; - void * _Nullable info; - - - - - CFAllocatorRetainCallBack _Nullable retain; - - - - - - CFAllocatorReleaseCallBack _Nullable release; - - - - - - - CFAllocatorCopyDescriptionCallBack _Nullable copyDescription; -}; -typedef struct FSEventStreamContext FSEventStreamContext; -typedef void ( * FSEventStreamCallback)(ConstFSEventStreamRef streamRef, void * _Nullable clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]); -extern FSEventStreamRef _Nullable -FSEventStreamCreate( - CFAllocatorRef _Nullable allocator, - FSEventStreamCallback callback, - FSEventStreamContext * _Nullable context, - CFArrayRef pathsToWatch, - FSEventStreamEventId sinceWhen, - CFTimeInterval latency, - FSEventStreamCreateFlags flags) __attribute__((availability(macosx,introduced=10.5))); -extern FSEventStreamRef _Nullable -FSEventStreamCreateRelativeToDevice( - CFAllocatorRef _Nullable allocator, - FSEventStreamCallback callback, - FSEventStreamContext * _Nullable context, - dev_t deviceToWatch, - CFArrayRef pathsToWatchRelativeToDevice, - FSEventStreamEventId sinceWhen, - CFTimeInterval latency, - FSEventStreamCreateFlags flags) __attribute__((availability(macosx,introduced=10.5))); -extern FSEventStreamEventId -FSEventStreamGetLatestEventId(ConstFSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern dev_t -FSEventStreamGetDeviceBeingWatched(ConstFSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern __attribute__((cf_returns_retained)) CFArrayRef -FSEventStreamCopyPathsBeingWatched(ConstFSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern FSEventStreamEventId -FSEventsGetCurrentEventId(void) __attribute__((availability(macosx,introduced=10.5))); -extern __attribute__((cf_returns_retained)) CFUUIDRef _Nullable -FSEventsCopyUUIDForDevice(dev_t dev) __attribute__((availability(macosx,introduced=10.5))); -extern FSEventStreamEventId -FSEventsGetLastEventIdForDeviceBeforeTime( - dev_t dev, - CFAbsoluteTime time) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -FSEventsPurgeEventsForDeviceUpToEventId( - dev_t dev, - FSEventStreamEventId eventId) __attribute__((availability(macosx,introduced=10.5))); -extern void -FSEventStreamRetain(FSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern void -FSEventStreamRelease(FSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern void -FSEventStreamScheduleWithRunLoop( - FSEventStreamRef streamRef, - CFRunLoopRef runLoop, - CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10.5))); -extern void -FSEventStreamUnscheduleFromRunLoop( - FSEventStreamRef streamRef, - CFRunLoopRef runLoop, - CFStringRef runLoopMode) __attribute__((availability(macosx,introduced=10.5))); -extern void -FSEventStreamSetDispatchQueue( - FSEventStreamRef streamRef, - dispatch_queue_t _Nullable q) __attribute__((availability(macosx,introduced=10.6))); -extern void -FSEventStreamInvalidate(FSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -FSEventStreamStart(FSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern FSEventStreamEventId -FSEventStreamFlushAsync(FSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern void -FSEventStreamFlushSync(FSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern void -FSEventStreamStop(FSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern void -FSEventStreamShow(ConstFSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern __attribute__((cf_returns_retained)) CFStringRef -FSEventStreamCopyDescription(ConstFSEventStreamRef streamRef) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -FSEventStreamSetExclusionPaths(FSEventStreamRef streamRef, CFArrayRef pathsToExclude) __attribute__((availability(macosx,introduced=10.9))); - - - - - - -#pragma pack(pop) - - - - -} - - - -extern "C" { -typedef struct OpaqueLSSharedFileListRef* LSSharedFileListRef; -typedef struct OpaqueLSSharedFileListItemRef* LSSharedFileListItemRef; -extern CFStringRef kLSSharedFileListFavoriteVolumes __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef kLSSharedFileListFavoriteItems __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef kLSSharedFileListRecentApplicationItems __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef kLSSharedFileListRecentDocumentItems __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef kLSSharedFileListRecentServerItems __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef kLSSharedFileListSessionLoginItems __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="Use a LaunchAgent, XPCService or the ServiceManagement APIs instead."))); -extern CFStringRef kLSSharedFileListGlobalLoginItems __attribute__((availability(macosx,introduced=10.5,deprecated=10.9,message="Use a LaunchAgent instead."))); -extern CFStringRef kLSSharedFileListRecentItemsMaxAmount __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef kLSSharedFileListVolumesComputerVisible __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef kLSSharedFileListVolumesIDiskVisible __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="iDisk is no longer available."))); -extern CFStringRef kLSSharedFileListVolumesNetworkVisible __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern LSSharedFileListItemRef kLSSharedFileListItemBeforeFirst __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern LSSharedFileListItemRef kLSSharedFileListItemLast __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef kLSSharedFileListItemHidden __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef kLSSharedFileListLoginItemHidden __attribute__((availability(macosx,introduced=10.6,deprecated=10.11))); - - -typedef UInt32 LSSharedFileListResolutionFlags; -enum { - kLSSharedFileListNoUserInteraction = 1 << 0, - kLSSharedFileListDoNotMountVolumes = 1 << 1 -}; -typedef void ( * LSSharedFileListChangedProcPtr)(LSSharedFileListRef inList, void *context); -extern CFTypeID -LSSharedFileListGetTypeID(void) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFTypeID -LSSharedFileListItemGetTypeID(void) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern LSSharedFileListRef -LSSharedFileListCreate( - CFAllocatorRef inAllocator, - CFStringRef inListType, - CFTypeRef listOptions) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern OSStatus -LSSharedFileListSetAuthorization( - LSSharedFileListRef inList, - AuthorizationRef inAuthorization) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern void -LSSharedFileListAddObserver( - LSSharedFileListRef inList, - CFRunLoopRef inRunloop, - CFStringRef inRunloopMode, - LSSharedFileListChangedProcPtr callback, - void * context) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern void -LSSharedFileListRemoveObserver( - LSSharedFileListRef inList, - CFRunLoopRef inRunloop, - CFStringRef inRunloopMode, - LSSharedFileListChangedProcPtr callback, - void * context) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern UInt32 -LSSharedFileListGetSeedValue(LSSharedFileListRef inList) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFTypeRef -LSSharedFileListCopyProperty( - LSSharedFileListRef inList, - CFStringRef inPropertyName) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern OSStatus -LSSharedFileListSetProperty( - LSSharedFileListRef inList, - CFStringRef inPropertyName, - CFTypeRef inPropertyData) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFArrayRef -LSSharedFileListCopySnapshot( - LSSharedFileListRef inList, - UInt32 * outSnapshotSeed) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern LSSharedFileListItemRef -LSSharedFileListInsertItemURL( - LSSharedFileListRef inList, - LSSharedFileListItemRef insertAfterThisItem, - CFStringRef inDisplayName, - IconRef inIconRef, - CFURLRef inURL, - CFDictionaryRef inPropertiesToSet, - CFArrayRef inPropertiesToClear) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern LSSharedFileListItemRef -LSSharedFileListInsertItemFSRef( - LSSharedFileListRef inList, - LSSharedFileListItemRef insertAfterThisItem, - CFStringRef inDisplayName, - IconRef inIconRef, - const FSRef * inFSRef, - CFDictionaryRef inPropertiesToSet, - CFArrayRef inPropertiesToClear) __attribute__((availability(macosx,introduced=10.5,deprecated=10.10,message="Use LSSharedFileListInsertItemURL instead."))); -extern OSStatus -LSSharedFileListItemMove( - LSSharedFileListRef inList, - LSSharedFileListItemRef inItem, - LSSharedFileListItemRef inMoveAfterItem) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern OSStatus -LSSharedFileListItemRemove( - LSSharedFileListRef inList, - LSSharedFileListItemRef inItem) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern OSStatus -LSSharedFileListRemoveAllItems(LSSharedFileListRef inList) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern UInt32 -LSSharedFileListItemGetID(LSSharedFileListItemRef inItem) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern IconRef -LSSharedFileListItemCopyIconRef(LSSharedFileListItemRef inItem) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern CFStringRef -LSSharedFileListItemCopyDisplayName(LSSharedFileListItemRef inItem) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern OSStatus -LSSharedFileListItemResolve( - LSSharedFileListItemRef inItem, - LSSharedFileListResolutionFlags inFlags, - CFURLRef * outURL, - FSRef * outRef) __attribute__((availability(macosx,introduced=10.5,deprecated=10.10,message="Use LSSharedFileListItemCopyResolvedURL instead."))); -extern CFURLRef -LSSharedFileListItemCopyResolvedURL( - LSSharedFileListItemRef inItem, - LSSharedFileListResolutionFlags inFlags, - CFErrorRef * outError) __attribute__((availability(macosx,introduced=10.10,deprecated=10.11))); -extern CFTypeRef -LSSharedFileListItemCopyProperty( - LSSharedFileListItemRef inItem, - CFStringRef inPropertyName) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); -extern OSStatus -LSSharedFileListItemSetProperty( - LSSharedFileListItemRef inItem, - CFStringRef inPropertyName, - CFTypeRef inPropertyData) __attribute__((availability(macosx,introduced=10.5,deprecated=10.11,message="This functionality is no longer supported on OS X."))); - - - - -} - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - - - - -extern "C" NSString * const NSURLErrorDomain; - - - - - -extern "C" NSString * const NSURLErrorFailingURLErrorKey __attribute__((availability(macosx,introduced=10_6))); - - - - - - -extern "C" NSString * const NSURLErrorFailingURLStringErrorKey __attribute__((availability(macosx,introduced=10_6))); - - - - - - -extern "C" NSString * const NSErrorFailingURLStringKey __attribute__((availability(macosx,introduced=10_0,deprecated=10_6,message="" ))); - - - - - -extern "C" NSString * const NSURLErrorFailingURLPeerTrustErrorKey __attribute__((availability(macosx,introduced=10_6))); - - - - - - -extern "C" NSString * const NSURLErrorBackgroundTaskCancelledReasonKey __attribute__((availability(macosx,introduced=10_10))); - - - - - - -enum -{ - NSURLErrorCancelledReasonUserForceQuitApplication = 0, - NSURLErrorCancelledReasonBackgroundUpdatesDisabled = 1, - NSURLErrorCancelledReasonInsufficientSystemResources __attribute__((availability(macosx,introduced=10_10))) = 2, - -} __attribute__((availability(macosx,introduced=10_10))); - - - - - -enum -{ - NSURLErrorUnknown = -1, - NSURLErrorCancelled = -999, - NSURLErrorBadURL = -1000, - NSURLErrorTimedOut = -1001, - NSURLErrorUnsupportedURL = -1002, - NSURLErrorCannotFindHost = -1003, - NSURLErrorCannotConnectToHost = -1004, - NSURLErrorNetworkConnectionLost = -1005, - NSURLErrorDNSLookupFailed = -1006, - NSURLErrorHTTPTooManyRedirects = -1007, - NSURLErrorResourceUnavailable = -1008, - NSURLErrorNotConnectedToInternet = -1009, - NSURLErrorRedirectToNonExistentLocation = -1010, - NSURLErrorBadServerResponse = -1011, - NSURLErrorUserCancelledAuthentication = -1012, - NSURLErrorUserAuthenticationRequired = -1013, - NSURLErrorZeroByteResource = -1014, - NSURLErrorCannotDecodeRawData = -1015, - NSURLErrorCannotDecodeContentData = -1016, - NSURLErrorCannotParseResponse = -1017, - NSURLErrorAppTransportSecurityRequiresSecureConnection __attribute__((availability(macosx,introduced=10_11))) = -1022, - NSURLErrorFileDoesNotExist = -1100, - NSURLErrorFileIsDirectory = -1101, - NSURLErrorNoPermissionsToReadFile = -1102, - NSURLErrorDataLengthExceedsMaximum __attribute__((availability(macosx,introduced=10_5))) = -1103, - - - NSURLErrorSecureConnectionFailed = -1200, - NSURLErrorServerCertificateHasBadDate = -1201, - NSURLErrorServerCertificateUntrusted = -1202, - NSURLErrorServerCertificateHasUnknownRoot = -1203, - NSURLErrorServerCertificateNotYetValid = -1204, - NSURLErrorClientCertificateRejected = -1205, - NSURLErrorClientCertificateRequired = -1206, - NSURLErrorCannotLoadFromNetwork = -2000, - - - NSURLErrorCannotCreateFile = -3000, - NSURLErrorCannotOpenFile = -3001, - NSURLErrorCannotCloseFile = -3002, - NSURLErrorCannotWriteToFile = -3003, - NSURLErrorCannotRemoveFile = -3004, - NSURLErrorCannotMoveFile = -3005, - NSURLErrorDownloadDecodingFailedMidStream = -3006, - NSURLErrorDownloadDecodingFailedToComplete =-3007, - - NSURLErrorInternationalRoamingOff __attribute__((availability(macosx,introduced=10_7))) = -1018, - NSURLErrorCallIsActive __attribute__((availability(macosx,introduced=10_7))) = -1019, - NSURLErrorDataNotAllowed __attribute__((availability(macosx,introduced=10_7))) = -1020, - NSURLErrorRequestBodyStreamExhausted __attribute__((availability(macosx,introduced=10_7))) = -1021, - - NSURLErrorBackgroundSessionRequiresSharedContainer __attribute__((availability(macosx,introduced=10_10))) = -995, - NSURLErrorBackgroundSessionInUseByAnotherProcess __attribute__((availability(macosx,introduced=10_10))) = -996, - NSURLErrorBackgroundSessionWasDisconnected __attribute__((availability(macosx,introduced=10_10)))= -997, -}; - -// @class NSCachedURLResponse; -#ifndef _REWRITER_typedef_NSCachedURLResponse -#define _REWRITER_typedef_NSCachedURLResponse -typedef struct objc_object NSCachedURLResponse; -typedef struct {} _objc_exc_NSCachedURLResponse; -#endif - -// @class NSError; -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -// @class NSMutableURLRequest; -#ifndef _REWRITER_typedef_NSMutableURLRequest -#define _REWRITER_typedef_NSMutableURLRequest -typedef struct objc_object NSMutableURLRequest; -typedef struct {} _objc_exc_NSMutableURLRequest; -#endif - -// @class NSURLAuthenticationChallenge; -#ifndef _REWRITER_typedef_NSURLAuthenticationChallenge -#define _REWRITER_typedef_NSURLAuthenticationChallenge -typedef struct objc_object NSURLAuthenticationChallenge; -typedef struct {} _objc_exc_NSURLAuthenticationChallenge; -#endif - -// @class NSURLConnection; -#ifndef _REWRITER_typedef_NSURLConnection -#define _REWRITER_typedef_NSURLConnection -typedef struct objc_object NSURLConnection; -typedef struct {} _objc_exc_NSURLConnection; -#endif - -// @class NSURLProtocol; -#ifndef _REWRITER_typedef_NSURLProtocol -#define _REWRITER_typedef_NSURLProtocol -typedef struct objc_object NSURLProtocol; -typedef struct {} _objc_exc_NSURLProtocol; -#endif - -// @class NSURLProtocolInternal; -#ifndef _REWRITER_typedef_NSURLProtocolInternal -#define _REWRITER_typedef_NSURLProtocolInternal -typedef struct objc_object NSURLProtocolInternal; -typedef struct {} _objc_exc_NSURLProtocolInternal; -#endif - -// @class NSURLRequest; -#ifndef _REWRITER_typedef_NSURLRequest -#define _REWRITER_typedef_NSURLRequest -typedef struct objc_object NSURLRequest; -typedef struct {} _objc_exc_NSURLRequest; -#endif - -// @class NSURLResponse; -#ifndef _REWRITER_typedef_NSURLResponse -#define _REWRITER_typedef_NSURLResponse -typedef struct objc_object NSURLResponse; -typedef struct {} _objc_exc_NSURLResponse; -#endif - -// @class NSURLSessionTask; -#ifndef _REWRITER_typedef_NSURLSessionTask -#define _REWRITER_typedef_NSURLSessionTask -typedef struct objc_object NSURLSessionTask; -typedef struct {} _objc_exc_NSURLSessionTask; -#endif - -// @protocol NSURLProtocolClient <NSObject> -// - (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse; -// - (void)URLProtocol:(NSURLProtocol *)protocol cachedResponseIsValid:(NSCachedURLResponse *)cachedResponse; -// - (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy; -// - (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data; - - - - - - - -// - (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol; -// - (void)URLProtocol:(NSURLProtocol *)protocol didFailWithError:(NSError *)error; -// - (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; - - - - - - - -// - (void)URLProtocol:(NSURLProtocol *)protocol didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; - -/* @end */ - - -#ifndef _REWRITER_typedef_NSURLProtocol -#define _REWRITER_typedef_NSURLProtocol -typedef struct objc_object NSURLProtocol; -typedef struct {} _objc_exc_NSURLProtocol; -#endif - -struct NSURLProtocol_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLProtocolInternal *_internal; -}; - -// - (instancetype)initWithRequest:(NSURLRequest *)request cachedResponse:(nullable NSCachedURLResponse *)cachedResponse client:(nullable id <NSURLProtocolClient>)client __attribute__((objc_designated_initializer)); - - - - - - -// @property (nullable, readonly, retain) id <NSURLProtocolClient> client; - - - - - - -// @property (readonly, copy) NSURLRequest *request; - - - - - - -// @property (nullable, readonly, copy) NSCachedURLResponse *cachedResponse; -// + (BOOL)canInitWithRequest:(NSURLRequest *)request; -// + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request; -// + (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b; - - - - - - - -// - (void)startLoading; -// - (void)stopLoading; -// + (nullable id)propertyForKey:(NSString *)key inRequest:(NSURLRequest *)request; -// + (void)setProperty:(id)value forKey:(NSString *)key inRequest:(NSMutableURLRequest *)request; -// + (void)removePropertyForKey:(NSString *)key inRequest:(NSMutableURLRequest *)request; -// + (BOOL)registerClass:(Class)protocolClass; -// + (void)unregisterClass:(Class)protocolClass; - -/* @end */ - - - -// @interface NSURLProtocol (NSURLSessionTaskAdditions) -// + (BOOL)canInitWithTask:(NSURLSessionTask *)task __attribute__((availability(macosx,introduced=10_10))); -// - (instancetype)initWithTask:(NSURLSessionTask *)task cachedResponse:(nullable NSCachedURLResponse *)cachedResponse client:(nullable id <NSURLProtocolClient>)client __attribute__((availability(macosx,introduced=10_10))); -// @property (nullable, readonly, copy) NSURLSessionTask *task __attribute__((availability(macosx,introduced=10_10))); -/* @end */ - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -// @class NSInputStream; -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSURL; -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -// @class NSURLRequestInternal; -#ifndef _REWRITER_typedef_NSURLRequestInternal -#define _REWRITER_typedef_NSURLRequestInternal -typedef struct objc_object NSURLRequestInternal; -typedef struct {} _objc_exc_NSURLRequestInternal; -#endif - -typedef NSUInteger NSURLRequestCachePolicy; enum -{ - NSURLRequestUseProtocolCachePolicy = 0, - - NSURLRequestReloadIgnoringLocalCacheData = 1, - NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, - NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData, - - NSURLRequestReturnCacheDataElseLoad = 2, - NSURLRequestReturnCacheDataDontLoad = 3, - - NSURLRequestReloadRevalidatingCacheData = 5, -}; -typedef NSUInteger NSURLRequestNetworkServiceType; enum -{ - NSURLNetworkServiceTypeDefault = 0, - NSURLNetworkServiceTypeVoIP = 1, - NSURLNetworkServiceTypeVideo = 2, - NSURLNetworkServiceTypeBackground = 3, - NSURLNetworkServiceTypeVoice = 4 -}; - -#ifndef _REWRITER_typedef_NSURLRequest -#define _REWRITER_typedef_NSURLRequest -typedef struct objc_object NSURLRequest; -typedef struct {} _objc_exc_NSURLRequest; -#endif - -struct NSURLRequest_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLRequestInternal *_internal; -}; - -// + (instancetype)requestWithURL:(NSURL *)URL; - - - - - - -// + (BOOL)supportsSecureCoding; -// + (instancetype)requestWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval; -// - (instancetype)initWithURL:(NSURL *)URL; -// - (instancetype)initWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval __attribute__((objc_designated_initializer)); - - - - - - -// @property (nullable, readonly, copy) NSURL *URL; - - - - - - -// @property (readonly) NSURLRequestCachePolicy cachePolicy; -// @property (readonly) NSTimeInterval timeoutInterval; -// @property (nullable, readonly, copy) NSURL *mainDocumentURL; -// @property (readonly) NSURLRequestNetworkServiceType networkServiceType __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly) BOOL allowsCellularAccess __attribute__((availability(macosx,introduced=10_8))); - -/* @end */ - - -#ifndef _REWRITER_typedef_NSMutableURLRequest -#define _REWRITER_typedef_NSMutableURLRequest -typedef struct objc_object NSMutableURLRequest; -typedef struct {} _objc_exc_NSMutableURLRequest; -#endif - -struct NSMutableURLRequest_IMPL { - struct NSURLRequest_IMPL NSURLRequest_IVARS; -}; - - - - - - - -// @property (nullable, copy) NSURL *URL; - - - - - - -// @property NSURLRequestCachePolicy cachePolicy; -// @property NSTimeInterval timeoutInterval; -// @property (nullable, copy) NSURL *mainDocumentURL; -// @property NSURLRequestNetworkServiceType networkServiceType __attribute__((availability(macosx,introduced=10_7))); -// @property BOOL allowsCellularAccess __attribute__((availability(macosx,introduced=10_8))); - -/* @end */ - -// @interface NSURLRequest (NSHTTPURLRequest) - - - - - - -// @property (nullable, readonly, copy) NSString *HTTPMethod; -// @property (nullable, readonly, copy) NSDictionary<NSString *, NSString *> *allHTTPHeaderFields; -// - (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; -// @property (nullable, readonly, copy) NSData *HTTPBody; -// @property (nullable, readonly, retain) NSInputStream *HTTPBodyStream; -// @property (readonly) BOOL HTTPShouldHandleCookies; -// @property (readonly) BOOL HTTPShouldUsePipelining __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - -// @interface NSMutableURLRequest (NSMutableHTTPURLRequest) - - - - - - -// @property (copy) NSString *HTTPMethod; -// @property (nullable, copy) NSDictionary<NSString *, NSString *> *allHTTPHeaderFields; -// - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString *)field; -// - (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field; -// @property (nullable, copy) NSData *HTTPBody; -// @property (nullable, retain) NSInputStream *HTTPBodyStream; -// @property BOOL HTTPShouldHandleCookies; -// @property BOOL HTTPShouldUsePipelining __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSURL; -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -// @class NSURLRequest; -#ifndef _REWRITER_typedef_NSURLRequest -#define _REWRITER_typedef_NSURLRequest -typedef struct objc_object NSURLRequest; -typedef struct {} _objc_exc_NSURLRequest; -#endif - -// @class NSURLResponseInternal; -#ifndef _REWRITER_typedef_NSURLResponseInternal -#define _REWRITER_typedef_NSURLResponseInternal -typedef struct objc_object NSURLResponseInternal; -typedef struct {} _objc_exc_NSURLResponseInternal; -#endif - - -#ifndef _REWRITER_typedef_NSURLResponse -#define _REWRITER_typedef_NSURLResponse -typedef struct objc_object NSURLResponse; -typedef struct {} _objc_exc_NSURLResponse; -#endif - -struct NSURLResponse_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLResponseInternal *_internal; -}; - -// - (instancetype)initWithURL:(NSURL *)URL MIMEType:(nullable NSString *)MIMEType expectedContentLength:(NSInteger)length textEncodingName:(nullable NSString *)name __attribute__((objc_designated_initializer)); - - - - - - -// @property (nullable, readonly, copy) NSURL *URL; -// @property (nullable, readonly, copy) NSString *MIMEType; -// @property (readonly) long long expectedContentLength; -// @property (nullable, readonly, copy) NSString *textEncodingName; -// @property (nullable, readonly, copy) NSString *suggestedFilename; - -/* @end */ - - - - -// @class NSHTTPURLResponseInternal; -#ifndef _REWRITER_typedef_NSHTTPURLResponseInternal -#define _REWRITER_typedef_NSHTTPURLResponseInternal -typedef struct objc_object NSHTTPURLResponseInternal; -typedef struct {} _objc_exc_NSHTTPURLResponseInternal; -#endif - - -#ifndef _REWRITER_typedef_NSHTTPURLResponse -#define _REWRITER_typedef_NSHTTPURLResponse -typedef struct objc_object NSHTTPURLResponse; -typedef struct {} _objc_exc_NSHTTPURLResponse; -#endif - -struct NSHTTPURLResponse_IMPL { - struct NSURLResponse_IMPL NSURLResponse_IVARS; - NSHTTPURLResponseInternal *_httpInternal; -}; - -// - (nullable instancetype)initWithURL:(NSURL *)url statusCode:(NSInteger)statusCode HTTPVersion:(nullable NSString *)HTTPVersion headerFields:(nullable NSDictionary<NSString *, NSString *> *)headerFields __attribute__((availability(macosx,introduced=10_7))); - - - - - - -// @property (readonly) NSInteger statusCode; -// @property (readonly, copy) NSDictionary *allHeaderFields; -// + (NSString *)localizedStringForStatusCode:(NSInteger)statusCode; - -/* @end */ - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - - - - -extern "C" NSString * const NSGlobalDomain; -extern "C" NSString * const NSArgumentDomain; -extern "C" NSString * const NSRegistrationDomain; - - -#ifndef _REWRITER_typedef_NSUserDefaults -#define _REWRITER_typedef_NSUserDefaults -typedef struct objc_object NSUserDefaults; -typedef struct {} _objc_exc_NSUserDefaults; -#endif - -struct NSUserDefaults_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSInteger _unused; - void *_reserved[4]; -}; - - -// + (NSUserDefaults *)standardUserDefaults; -// + (void)resetStandardUserDefaults; - -// - (instancetype)init; -// - (nullable instancetype)initWithSuiteName:(nullable NSString *)suitename __attribute__((availability(macosx,introduced=10_9))) __attribute__((objc_designated_initializer)); -// - (nullable id)initWithUser:(NSString *)username __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))); - -// - (nullable id)objectForKey:(NSString *)defaultName; -// - (void)setObject:(nullable id)value forKey:(NSString *)defaultName; -// - (void)removeObjectForKey:(NSString *)defaultName; - -// - (nullable NSString *)stringForKey:(NSString *)defaultName; -// - (nullable NSArray *)arrayForKey:(NSString *)defaultName; -// - (nullable NSDictionary<NSString *, id> *)dictionaryForKey:(NSString *)defaultName; -// - (nullable NSData *)dataForKey:(NSString *)defaultName; -// - (nullable NSArray<NSString *> *)stringArrayForKey:(NSString *)defaultName; -// - (NSInteger)integerForKey:(NSString *)defaultName; -// - (float)floatForKey:(NSString *)defaultName; -// - (double)doubleForKey:(NSString *)defaultName; -// - (BOOL)boolForKey:(NSString *)defaultName; -// - (nullable NSURL *)URLForKey:(NSString *)defaultName __attribute__((availability(macosx,introduced=10_6))); - -// - (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName; -// - (void)setFloat:(float)value forKey:(NSString *)defaultName; -// - (void)setDouble:(double)value forKey:(NSString *)defaultName; -// - (void)setBool:(BOOL)value forKey:(NSString *)defaultName; -// - (void)setURL:(nullable NSURL *)url forKey:(NSString *)defaultName __attribute__((availability(macosx,introduced=10_6))); - -// - (void)registerDefaults:(NSDictionary<NSString *, id> *)registrationDictionary; - -// - (void)addSuiteNamed:(NSString *)suiteName; -// - (void)removeSuiteNamed:(NSString *)suiteName; - -// - (NSDictionary<NSString *, id> *)dictionaryRepresentation; - -// @property (readonly, copy) NSArray<NSString *> *volatileDomainNames; -// - (NSDictionary<NSString *, id> *)volatileDomainForName:(NSString *)domainName; -// - (void)setVolatileDomain:(NSDictionary<NSString *, id> *)domain forName:(NSString *)domainName; -// - (void)removeVolatileDomainForName:(NSString *)domainName; - -// - (NSArray *)persistentDomainNames __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))); -// - (nullable NSDictionary<NSString *, id> *)persistentDomainForName:(NSString *)domainName; -// - (void)setPersistentDomain:(NSDictionary<NSString *, id> *)domain forName:(NSString *)domainName; -// - (void)removePersistentDomainForName:(NSString *)domainName; - -// - (BOOL)synchronize; - -// - (BOOL)objectIsForcedForKey:(NSString *)key; -// - (BOOL)objectIsForcedForKey:(NSString *)key inDomain:(NSString *)domain; - - -/* @end */ - - -extern "C" NSString * const NSUserDefaultsDidChangeNotification; - - - - -extern "C" NSString * const NSWeekDayNameArray __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSShortWeekDayNameArray __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSMonthNameArray __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSShortMonthNameArray __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSTimeFormatString __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSDateFormatString __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSTimeDateFormatString __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSShortTimeDateFormatString __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSCurrencySymbol __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSDecimalSeparator __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSThousandsSeparator __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSDecimalDigits __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSAMPMDesignation __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSHourNameDesignations __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSYearMonthWeekDesignations __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSEarlierTimeDesignations __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSLaterTimeDesignations __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSThisDayDesignations __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSNextDayDesignations __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSNextNextDayDesignations __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSPriorDayDesignations __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSDateTimeOrdering __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSInternationalCurrencyString __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSShortDateFormatString __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSPositiveCurrencyFormatString __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); -extern "C" NSString * const NSNegativeCurrencyFormatString __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -extern "C" NSString * const NSNegateBooleanTransformerName __attribute__((availability(macosx,introduced=10_3))); -extern "C" NSString * const NSIsNilTransformerName __attribute__((availability(macosx,introduced=10_3))); -extern "C" NSString * const NSIsNotNilTransformerName __attribute__((availability(macosx,introduced=10_3))); -extern "C" NSString * const NSUnarchiveFromDataTransformerName __attribute__((availability(macosx,introduced=10_3))); -extern "C" NSString * const NSKeyedUnarchiveFromDataTransformerName __attribute__((availability(macosx,introduced=10_5))); - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_3))) - -#ifndef _REWRITER_typedef_NSValueTransformer -#define _REWRITER_typedef_NSValueTransformer -typedef struct objc_object NSValueTransformer; -typedef struct {} _objc_exc_NSValueTransformer; -#endif - -struct NSValueTransformer_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - - -// + (void)setValueTransformer:(nullable NSValueTransformer *)transformer forName:(NSString *)name; -// + (nullable NSValueTransformer *)valueTransformerForName:(NSString *)name; -// + (NSArray<NSString *> *)valueTransformerNames; - - -// + (Class)transformedValueClass; -// + (BOOL)allowsReverseTransformation; - -// - (nullable id)transformedValue:(nullable id)value; -// - (nullable id)reverseTransformedValue:(nullable id)value; - -/* @end */ - - - - - - - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - -// @protocol NSXMLParserDelegate; - - - -__attribute__((availability(macosx,introduced=10_9))) -typedef NSUInteger NSXMLParserExternalEntityResolvingPolicy; enum { - NSXMLParserResolveExternalEntitiesNever = 0, - NSXMLParserResolveExternalEntitiesNoNetwork, - NSXMLParserResolveExternalEntitiesSameOriginOnly, - NSXMLParserResolveExternalEntitiesAlways -}; - - -#ifndef _REWRITER_typedef_NSXMLParser -#define _REWRITER_typedef_NSXMLParser -typedef struct objc_object NSXMLParser; -typedef struct {} _objc_exc_NSXMLParser; -#endif - -struct NSXMLParser_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _reserved0; - id _delegate; - id _reserved1; - id _reserved2; - id _reserved3; -}; - -// - (nullable instancetype)initWithContentsOfURL:(NSURL *)url; -// - (instancetype)initWithData:(NSData *)data __attribute__((objc_designated_initializer)); -// - (instancetype)initWithStream:(NSInputStream *)stream __attribute__((availability(macosx,introduced=10_7))); - - -// @property (nullable, assign) id <NSXMLParserDelegate> delegate; - -// @property BOOL shouldProcessNamespaces; -// @property BOOL shouldReportNamespacePrefixes; - - -// @property NSXMLParserExternalEntityResolvingPolicy externalEntityResolvingPolicy __attribute__((availability(macosx,introduced=10_9))); - -// @property (nullable, copy) NSSet<NSURL *> *allowedExternalEntityURLs __attribute__((availability(macosx,introduced=10_9))); - -// - (BOOL)parse; -// - (void)abortParsing; - -// @property (nullable, readonly, copy) NSError *parserError; - - - -// @property BOOL shouldResolveExternalEntities; - -/* @end */ - - - -// @interface NSXMLParser (NSXMLParserLocatorAdditions) -// @property (nullable, readonly, copy) NSString *publicID; -// @property (nullable, readonly, copy) NSString *systemID; -// @property (readonly) NSInteger lineNumber; -// @property (readonly) NSInteger columnNumber; - -/* @end */ - -// @protocol NSXMLParserDelegate <NSObject> -/* @optional */ - - -// - (void)parserDidStartDocument:(NSXMLParser *)parser; - -// - (void)parserDidEndDocument:(NSXMLParser *)parser; - - - -// - (void)parser:(NSXMLParser *)parser foundNotationDeclarationWithName:(NSString *)name publicID:(nullable NSString *)publicID systemID:(nullable NSString *)systemID; - -// - (void)parser:(NSXMLParser *)parser foundUnparsedEntityDeclarationWithName:(NSString *)name publicID:(nullable NSString *)publicID systemID:(nullable NSString *)systemID notationName:(nullable NSString *)notationName; - -// - (void)parser:(NSXMLParser *)parser foundAttributeDeclarationWithName:(NSString *)attributeName forElement:(NSString *)elementName type:(nullable NSString *)type defaultValue:(nullable NSString *)defaultValue; - -// - (void)parser:(NSXMLParser *)parser foundElementDeclarationWithName:(NSString *)elementName model:(NSString *)model; - -// - (void)parser:(NSXMLParser *)parser foundInternalEntityDeclarationWithName:(NSString *)name value:(nullable NSString *)value; - -// - (void)parser:(NSXMLParser *)parser foundExternalEntityDeclarationWithName:(NSString *)name publicID:(nullable NSString *)publicID systemID:(nullable NSString *)systemID; - -// - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict; - - - - - - - -// - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName; - - -// - (void)parser:(NSXMLParser *)parser didStartMappingPrefix:(NSString *)prefix toURI:(NSString *)namespaceURI; - - - - -// - (void)parser:(NSXMLParser *)parser didEndMappingPrefix:(NSString *)prefix; - - -// - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string; - - -// - (void)parser:(NSXMLParser *)parser foundIgnorableWhitespace:(NSString *)whitespaceString; - - -// - (void)parser:(NSXMLParser *)parser foundProcessingInstructionWithTarget:(NSString *)target data:(nullable NSString *)data; - - -// - (void)parser:(NSXMLParser *)parser foundComment:(NSString *)comment; - - -// - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock; - - -// - (nullable NSData *)parser:(NSXMLParser *)parser resolveExternalEntityName:(NSString *)name systemID:(nullable NSString *)systemID; - - -// - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError; - - -// - (void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validationError; - -/* @end */ - - -extern "C" NSString * const NSXMLParserErrorDomain __attribute__((availability(macosx,introduced=10_3))); - - -typedef NSInteger NSXMLParserError; enum { - NSXMLParserInternalError = 1, - NSXMLParserOutOfMemoryError = 2, - NSXMLParserDocumentStartError = 3, - NSXMLParserEmptyDocumentError = 4, - NSXMLParserPrematureDocumentEndError = 5, - NSXMLParserInvalidHexCharacterRefError = 6, - NSXMLParserInvalidDecimalCharacterRefError = 7, - NSXMLParserInvalidCharacterRefError = 8, - NSXMLParserInvalidCharacterError = 9, - NSXMLParserCharacterRefAtEOFError = 10, - NSXMLParserCharacterRefInPrologError = 11, - NSXMLParserCharacterRefInEpilogError = 12, - NSXMLParserCharacterRefInDTDError = 13, - NSXMLParserEntityRefAtEOFError = 14, - NSXMLParserEntityRefInPrologError = 15, - NSXMLParserEntityRefInEpilogError = 16, - NSXMLParserEntityRefInDTDError = 17, - NSXMLParserParsedEntityRefAtEOFError = 18, - NSXMLParserParsedEntityRefInPrologError = 19, - NSXMLParserParsedEntityRefInEpilogError = 20, - NSXMLParserParsedEntityRefInInternalSubsetError = 21, - NSXMLParserEntityReferenceWithoutNameError = 22, - NSXMLParserEntityReferenceMissingSemiError = 23, - NSXMLParserParsedEntityRefNoNameError = 24, - NSXMLParserParsedEntityRefMissingSemiError = 25, - NSXMLParserUndeclaredEntityError = 26, - NSXMLParserUnparsedEntityError = 28, - NSXMLParserEntityIsExternalError = 29, - NSXMLParserEntityIsParameterError = 30, - NSXMLParserUnknownEncodingError = 31, - NSXMLParserEncodingNotSupportedError = 32, - NSXMLParserStringNotStartedError = 33, - NSXMLParserStringNotClosedError = 34, - NSXMLParserNamespaceDeclarationError = 35, - NSXMLParserEntityNotStartedError = 36, - NSXMLParserEntityNotFinishedError = 37, - NSXMLParserLessThanSymbolInAttributeError = 38, - NSXMLParserAttributeNotStartedError = 39, - NSXMLParserAttributeNotFinishedError = 40, - NSXMLParserAttributeHasNoValueError = 41, - NSXMLParserAttributeRedefinedError = 42, - NSXMLParserLiteralNotStartedError = 43, - NSXMLParserLiteralNotFinishedError = 44, - NSXMLParserCommentNotFinishedError = 45, - NSXMLParserProcessingInstructionNotStartedError = 46, - NSXMLParserProcessingInstructionNotFinishedError = 47, - NSXMLParserNotationNotStartedError = 48, - NSXMLParserNotationNotFinishedError = 49, - NSXMLParserAttributeListNotStartedError = 50, - NSXMLParserAttributeListNotFinishedError = 51, - NSXMLParserMixedContentDeclNotStartedError = 52, - NSXMLParserMixedContentDeclNotFinishedError = 53, - NSXMLParserElementContentDeclNotStartedError = 54, - NSXMLParserElementContentDeclNotFinishedError = 55, - NSXMLParserXMLDeclNotStartedError = 56, - NSXMLParserXMLDeclNotFinishedError = 57, - NSXMLParserConditionalSectionNotStartedError = 58, - NSXMLParserConditionalSectionNotFinishedError = 59, - NSXMLParserExternalSubsetNotFinishedError = 60, - NSXMLParserDOCTYPEDeclNotFinishedError = 61, - NSXMLParserMisplacedCDATAEndStringError = 62, - NSXMLParserCDATANotFinishedError = 63, - NSXMLParserMisplacedXMLDeclarationError = 64, - NSXMLParserSpaceRequiredError = 65, - NSXMLParserSeparatorRequiredError = 66, - NSXMLParserNMTOKENRequiredError = 67, - NSXMLParserNAMERequiredError = 68, - NSXMLParserPCDATARequiredError = 69, - NSXMLParserURIRequiredError = 70, - NSXMLParserPublicIdentifierRequiredError = 71, - NSXMLParserLTRequiredError = 72, - NSXMLParserGTRequiredError = 73, - NSXMLParserLTSlashRequiredError = 74, - NSXMLParserEqualExpectedError = 75, - NSXMLParserTagNameMismatchError = 76, - NSXMLParserUnfinishedTagError = 77, - NSXMLParserStandaloneValueError = 78, - NSXMLParserInvalidEncodingNameError = 79, - NSXMLParserCommentContainsDoubleHyphenError = 80, - NSXMLParserInvalidEncodingError = 81, - NSXMLParserExternalStandaloneEntityError = 82, - NSXMLParserInvalidConditionalSectionError = 83, - NSXMLParserEntityValueRequiredError = 84, - NSXMLParserNotWellBalancedError = 85, - NSXMLParserExtraContentError = 86, - NSXMLParserInvalidCharacterInEntityError = 87, - NSXMLParserParsedEntityRefInInternalError = 88, - NSXMLParserEntityRefLoopError = 89, - NSXMLParserEntityBoundaryError = 90, - NSXMLParserInvalidURIError = 91, - NSXMLParserURIFragmentError = 92, - NSXMLParserNoDTDError = 94, - NSXMLParserDelegateAbortedParseError = 512 -}; - - - - - - - - - - -enum { - - NSFileNoSuchFileError = 4, - NSFileLockingError = 255, - NSFileReadUnknownError = 256, - NSFileReadNoPermissionError = 257, - NSFileReadInvalidFileNameError = 258, - NSFileReadCorruptFileError = 259, - NSFileReadNoSuchFileError = 260, - NSFileReadInapplicableStringEncodingError = 261, - NSFileReadUnsupportedSchemeError = 262, - NSFileReadTooLargeError __attribute__((availability(macosx,introduced=10_5))) = 263, - NSFileReadUnknownStringEncodingError __attribute__((availability(macosx,introduced=10_5))) = 264, - NSFileWriteUnknownError = 512, - NSFileWriteNoPermissionError = 513, - NSFileWriteInvalidFileNameError = 514, - NSFileWriteFileExistsError __attribute__((availability(macosx,introduced=10_7))) = 516, - NSFileWriteInapplicableStringEncodingError = 517, - NSFileWriteUnsupportedSchemeError = 518, - NSFileWriteOutOfSpaceError = 640, - NSFileWriteVolumeReadOnlyError __attribute__((availability(macosx,introduced=10_6))) = 642, - - - NSFileManagerUnmountUnknownError __attribute__((availability(macosx,introduced=10_11))) = 768, - NSFileManagerUnmountBusyError __attribute__((availability(macosx,introduced=10_11))) = 769, - - - NSKeyValueValidationError = 1024, - NSFormattingError = 2048, - NSUserCancelledError = 3072, - NSFeatureUnsupportedError __attribute__((availability(macosx,introduced=10_8))) = 3328, - - - NSExecutableNotLoadableError __attribute__((availability(macosx,introduced=10_5))) = 3584, - NSExecutableArchitectureMismatchError __attribute__((availability(macosx,introduced=10_5))) = 3585, - NSExecutableRuntimeMismatchError __attribute__((availability(macosx,introduced=10_5))) = 3586, - NSExecutableLoadError __attribute__((availability(macosx,introduced=10_5))) = 3587, - NSExecutableLinkError __attribute__((availability(macosx,introduced=10_5))) = 3588, - - - NSFileErrorMinimum = 0, - NSFileErrorMaximum = 1023, - - NSValidationErrorMinimum = 1024, - NSValidationErrorMaximum = 2047, - - NSExecutableErrorMinimum __attribute__((availability(macosx,introduced=10_5))) = 3584, - NSExecutableErrorMaximum __attribute__((availability(macosx,introduced=10_5))) = 3839, - - NSFormattingErrorMinimum = 2048, - NSFormattingErrorMaximum = 2559, - - NSPropertyListReadCorruptError __attribute__((availability(macosx,introduced=10_6))) = 3840, - NSPropertyListReadUnknownVersionError __attribute__((availability(macosx,introduced=10_6))) = 3841, - NSPropertyListReadStreamError __attribute__((availability(macosx,introduced=10_6))) = 3842, - NSPropertyListWriteStreamError __attribute__((availability(macosx,introduced=10_6))) = 3851, - NSPropertyListWriteInvalidError __attribute__((availability(macosx,introduced=10_10))) = 3852, - - NSPropertyListErrorMinimum __attribute__((availability(macosx,introduced=10_6))) = 3840, - NSPropertyListErrorMaximum __attribute__((availability(macosx,introduced=10_6))) = 4095, - - NSXPCConnectionInterrupted __attribute__((availability(macosx,introduced=10_8))) = 4097, - NSXPCConnectionInvalid __attribute__((availability(macosx,introduced=10_8))) = 4099, - NSXPCConnectionReplyInvalid __attribute__((availability(macosx,introduced=10_8))) = 4101, - - NSXPCConnectionErrorMinimum __attribute__((availability(macosx,introduced=10_8))) = 4096, - NSXPCConnectionErrorMaximum __attribute__((availability(macosx,introduced=10_8))) = 4224, - - NSUbiquitousFileUnavailableError __attribute__((availability(macosx,introduced=10_9))) = 4353, - NSUbiquitousFileNotUploadedDueToQuotaError __attribute__((availability(macosx,introduced=10_9))) = 4354, - NSUbiquitousFileUbiquityServerNotAvailable __attribute__((availability(macosx,introduced=10_9))) = 4355, - - NSUbiquitousFileErrorMinimum __attribute__((availability(macosx,introduced=10_9))) = 4352, - NSUbiquitousFileErrorMaximum __attribute__((availability(macosx,introduced=10_9))) = 4607, - - NSUserActivityHandoffFailedError __attribute__((availability(macosx,introduced=10_10))) = 4608, - NSUserActivityConnectionUnavailableError __attribute__((availability(macosx,introduced=10_10))) = 4609, - NSUserActivityRemoteApplicationTimedOutError __attribute__((availability(macosx,introduced=10_10))) = 4610, - NSUserActivityHandoffUserInfoTooLargeError __attribute__((availability(macosx,introduced=10_10))) = 4611, - - NSUserActivityErrorMinimum __attribute__((availability(macosx,introduced=10_10))) = 4608, - NSUserActivityErrorMaximum __attribute__((availability(macosx,introduced=10_10))) = 4863, - - NSCoderReadCorruptError __attribute__((availability(macosx,introduced=10_11))) = 4864, - NSCoderValueNotFoundError __attribute__((availability(macosx,introduced=10_11))) = 4865, - NSCoderErrorMinimum __attribute__((availability(macosx,introduced=10_11))) = 4864, - NSCoderErrorMaximum __attribute__((availability(macosx,introduced=10_11))) = 4991, - - NSBundleErrorMinimum __attribute__((availability(macosx,introduced=10_11))) = 4992, - NSBundleErrorMaximum __attribute__((availability(macosx,introduced=10_11))) = 5119, - - NSBundleOnDemandResourceOutOfSpaceError __attribute__((availability(macosx,introduced=NA))) = 4992, - NSBundleOnDemandResourceExceededMaximumSizeError __attribute__((availability(macosx,introduced=NA))) = 4993, - NSBundleOnDemandResourceInvalidTagError __attribute__((availability(macosx,introduced=NA))) = 4994, -}; - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_0))) - -#ifndef _REWRITER_typedef_NSAttributedString -#define _REWRITER_typedef_NSAttributedString -typedef struct objc_object NSAttributedString; -typedef struct {} _objc_exc_NSAttributedString; -#endif - -struct NSAttributedString_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly, copy) NSString *string; -// - (NSDictionary<NSString *, id> *)attributesAtIndex:(NSUInteger)location effectiveRange:(nullable NSRangePointer)range; - -/* @end */ - - -// @interface NSAttributedString (NSExtendedAttributedString) - -// @property (readonly) NSUInteger length; -// - (nullable id)attribute:(NSString *)attrName atIndex:(NSUInteger)location effectiveRange:(nullable NSRangePointer)range; -// - (NSAttributedString *)attributedSubstringFromRange:(NSRange)range; - -// - (NSDictionary<NSString *, id> *)attributesAtIndex:(NSUInteger)location longestEffectiveRange:(nullable NSRangePointer)range inRange:(NSRange)rangeLimit; -// - (nullable id)attribute:(NSString *)attrName atIndex:(NSUInteger)location longestEffectiveRange:(nullable NSRangePointer)range inRange:(NSRange)rangeLimit; - -// - (BOOL)isEqualToAttributedString:(NSAttributedString *)other; - -// - (instancetype)initWithString:(NSString *)str; -// - (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSString *, id> *)attrs; -// - (instancetype)initWithAttributedString:(NSAttributedString *)attrStr; - -typedef NSUInteger NSAttributedStringEnumerationOptions; enum { - NSAttributedStringEnumerationReverse = (1UL << 1), - NSAttributedStringEnumerationLongestEffectiveRangeNotRequired = (1UL << 20) -}; - -// - (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(NSDictionary<NSString *, id> *attrs, NSRange range, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); -// - (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(id _Nullable value, NSRange range, BOOL *stop))block __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_0))) - -#ifndef _REWRITER_typedef_NSMutableAttributedString -#define _REWRITER_typedef_NSMutableAttributedString -typedef struct objc_object NSMutableAttributedString; -typedef struct {} _objc_exc_NSMutableAttributedString; -#endif - -struct NSMutableAttributedString_IMPL { - struct NSAttributedString_IMPL NSAttributedString_IVARS; -}; - - -// - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str; -// - (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range; - -/* @end */ - - -// @interface NSMutableAttributedString (NSExtendedMutableAttributedString) - -// @property (readonly, retain) NSMutableString *mutableString; - -// - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range; -// - (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range; -// - (void)removeAttribute:(NSString *)name range:(NSRange)range; - -// - (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString; -// - (void)insertAttributedString:(NSAttributedString *)attrString atIndex:(NSUInteger)loc; -// - (void)appendAttributedString:(NSAttributedString *)attrString; -// - (void)deleteCharactersInRange:(NSRange)range; -// - (void)setAttributedString:(NSAttributedString *)attrString; - -// - (void)beginEditing; -// - (void)endEditing; - -/* @end */ - - - - - - - - - -typedef NSUInteger NSByteCountFormatterUnits; enum { - - NSByteCountFormatterUseDefault = 0, - - NSByteCountFormatterUseBytes = 1UL << 0, - NSByteCountFormatterUseKB = 1UL << 1, - NSByteCountFormatterUseMB = 1UL << 2, - NSByteCountFormatterUseGB = 1UL << 3, - NSByteCountFormatterUseTB = 1UL << 4, - NSByteCountFormatterUsePB = 1UL << 5, - NSByteCountFormatterUseEB = 1UL << 6, - NSByteCountFormatterUseZB = 1UL << 7, - NSByteCountFormatterUseYBOrHigher = 0x0FFUL << 8, - - NSByteCountFormatterUseAll = 0x0FFFFUL -}; - -typedef NSInteger NSByteCountFormatterCountStyle; enum { - - NSByteCountFormatterCountStyleFile = 0, - - NSByteCountFormatterCountStyleMemory = 1, - - NSByteCountFormatterCountStyleDecimal = 2, - NSByteCountFormatterCountStyleBinary = 3 -}; - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSByteCountFormatter -#define _REWRITER_typedef_NSByteCountFormatter -typedef struct objc_object NSByteCountFormatter; -typedef struct {} _objc_exc_NSByteCountFormatter; -#endif - -struct NSByteCountFormatter_IMPL { - struct NSFormatter_IMPL NSFormatter_IVARS; - unsigned int _allowedUnits; - char _countStyle; - BOOL _allowsNonnumericFormatting; - BOOL _includesUnit; - BOOL _includesCount; - BOOL _includesActualByteCount; - BOOL _adaptive; - BOOL _zeroPadsFractionDigits; - int _formattingContext; - int _reserved[5]; -}; - - - - -// + (NSString *)stringFromByteCount:(long long)byteCount countStyle:(NSByteCountFormatterCountStyle)countStyle; - - - -// - (NSString *)stringFromByteCount:(long long)byteCount; - - - -// @property NSByteCountFormatterUnits allowedUnits; - - - -// @property NSByteCountFormatterCountStyle countStyle; - - - -// @property BOOL allowsNonnumericFormatting; - - - -// @property BOOL includesUnit; -// @property BOOL includesCount; - - - -// @property BOOL includesActualByteCount; - - - -// @property (getter=isAdaptive) BOOL adaptive; - - - -// @property BOOL zeroPadsFractionDigits; - - - -// @property NSFormattingContext formattingContext __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @protocol NSCacheDelegate; - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_6))) - -#ifndef _REWRITER_typedef_NSCache -#define _REWRITER_typedef_NSCache -typedef struct objc_object NSCache; -typedef struct {} _objc_exc_NSCache; -#endif - -struct NSCache_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _delegate; - void *_private[5]; - void *_reserved; -}; - - -// @property (copy) NSString *name; - -// @property (nullable, assign) id<NSCacheDelegate> delegate; - -// - (nullable ObjectType)objectForKey:(KeyType)key; -// - (void)setObject:(ObjectType)obj forKey:(KeyType)key; -// - (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g; -// - (void)removeObjectForKey:(KeyType)key; - -// - (void)removeAllObjects; - -// @property NSUInteger totalCostLimit; -// @property NSUInteger countLimit; -// @property BOOL evictsObjectsWithDiscardedContent; - -/* @end */ - - -// @protocol NSCacheDelegate <NSObject> -/* @optional */ -// - (void)cache:(NSCache *)cache willEvictObject:(id)obj; -/* @end */ - - - - - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_4))) - -#ifndef _REWRITER_typedef_NSPredicate -#define _REWRITER_typedef_NSPredicate -typedef struct objc_object NSPredicate; -typedef struct {} _objc_exc_NSPredicate; -#endif - - struct _predicateFlags { - unsigned int _evaluationBlocked : 1; - unsigned int _reservedPredicateFlags : 31; - } ; -struct NSPredicate_IMPL { - struct NSObject_IMPL NSObject_IVARS; - - struct _predicateFlags _predicateFlags; - uint32_t reserved; -}; - - - -// + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat argumentArray:(nullable NSArray *)arguments; -// + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...; -// + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat arguments:(va_list)argList; - -// + (nullable NSPredicate *)predicateFromMetadataQueryString:(NSString *)queryString __attribute__((availability(macosx,introduced=10_9))); - -// + (NSPredicate *)predicateWithValue:(BOOL)value; - -// + (NSPredicate*)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary<NSString *, id> * _Nullable bindings))block __attribute__((availability(macosx,introduced=10_6))); - -// @property (readonly, copy) NSString *predicateFormat; - -// - (instancetype)predicateWithSubstitutionVariables:(NSDictionary<NSString *, id> *)variables; - -// - (BOOL)evaluateWithObject:(nullable id)object; - -// - (BOOL)evaluateWithObject:(nullable id)object substitutionVariables:(nullable NSDictionary<NSString *, id> *)bindings __attribute__((availability(macosx,introduced=10_5))); - -// - (void)allowEvaluation __attribute__((availability(macosx,introduced=10_9))); - -/* @end */ - - -// @interface NSArray<ObjectType> (NSPredicateSupport) -// - (NSArray<ObjectType> *)filteredArrayUsingPredicate:(NSPredicate *)predicate; -/* @end */ - - -// @interface NSMutableArray<ObjectType> (NSPredicateSupport) -// - (void)filterUsingPredicate:(NSPredicate *)predicate; -/* @end */ - - - -// @interface NSSet<ObjectType> (NSPredicateSupport) -// - (NSSet<ObjectType> *)filteredSetUsingPredicate:(NSPredicate *)predicate __attribute__((availability(macosx,introduced=10_5))); -/* @end */ - - -// @interface NSMutableSet<ObjectType> (NSPredicateSupport) -// - (void)filterUsingPredicate:(NSPredicate *)predicate __attribute__((availability(macosx,introduced=10_5))); -/* @end */ - - -// @interface NSOrderedSet<ObjectType> (NSPredicateSupport) - -// - (NSOrderedSet<ObjectType> *)filteredOrderedSetUsingPredicate:(NSPredicate *)p __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - -// @interface NSMutableOrderedSet<ObjectType> (NSPredicateSupport) - -// - (void)filterUsingPredicate:(NSPredicate *)p __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - - - - -typedef NSUInteger NSComparisonPredicateOptions; enum { - NSCaseInsensitivePredicateOption = 0x01, - NSDiacriticInsensitivePredicateOption = 0x02, - NSNormalizedPredicateOption __attribute__((availability(macosx,introduced=10_6))) = 0x04, -}; - - -typedef NSUInteger NSComparisonPredicateModifier; enum { - NSDirectPredicateModifier = 0, - NSAllPredicateModifier, - NSAnyPredicateModifier -}; - - - -typedef NSUInteger NSPredicateOperatorType; enum { - NSLessThanPredicateOperatorType = 0, - NSLessThanOrEqualToPredicateOperatorType, - NSGreaterThanPredicateOperatorType, - NSGreaterThanOrEqualToPredicateOperatorType, - NSEqualToPredicateOperatorType, - NSNotEqualToPredicateOperatorType, - NSMatchesPredicateOperatorType, - NSLikePredicateOperatorType, - NSBeginsWithPredicateOperatorType, - NSEndsWithPredicateOperatorType, - NSInPredicateOperatorType, - NSCustomSelectorPredicateOperatorType, - NSContainsPredicateOperatorType __attribute__((availability(macosx,introduced=10_5))) = 99, - NSBetweenPredicateOperatorType __attribute__((availability(macosx,introduced=10_5))) -}; - -// @class NSPredicateOperator; -#ifndef _REWRITER_typedef_NSPredicateOperator -#define _REWRITER_typedef_NSPredicateOperator -typedef struct objc_object NSPredicateOperator; -typedef struct {} _objc_exc_NSPredicateOperator; -#endif - -// @class NSExpression; -#ifndef _REWRITER_typedef_NSExpression -#define _REWRITER_typedef_NSExpression -typedef struct objc_object NSExpression; -typedef struct {} _objc_exc_NSExpression; -#endif - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_4))) - -#ifndef _REWRITER_typedef_NSComparisonPredicate -#define _REWRITER_typedef_NSComparisonPredicate -typedef struct objc_object NSComparisonPredicate; -typedef struct {} _objc_exc_NSComparisonPredicate; -#endif - -struct NSComparisonPredicate_IMPL { - struct NSPredicate_IMPL NSPredicate_IVARS; - void *_reserved2; - NSPredicateOperator *_predicateOperator; - NSExpression *_lhs; - NSExpression *_rhs; -}; - - -// + (NSComparisonPredicate *)predicateWithLeftExpression:(NSExpression *)lhs rightExpression:(NSExpression *)rhs modifier:(NSComparisonPredicateModifier)modifier type:(NSPredicateOperatorType)type options:(NSComparisonPredicateOptions)options; -// + (NSComparisonPredicate *)predicateWithLeftExpression:(NSExpression *)lhs rightExpression:(NSExpression *)rhs customSelector:(SEL)selector; - -// - (instancetype)initWithLeftExpression:(NSExpression *)lhs rightExpression:(NSExpression *)rhs modifier:(NSComparisonPredicateModifier)modifier type:(NSPredicateOperatorType)type options:(NSComparisonPredicateOptions)options __attribute__((objc_designated_initializer)); -// - (instancetype)initWithLeftExpression:(NSExpression *)lhs rightExpression:(NSExpression *)rhs customSelector:(SEL)selector __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)coder __attribute__((objc_designated_initializer)); - -// @property (readonly) NSPredicateOperatorType predicateOperatorType; -// @property (readonly) NSComparisonPredicateModifier comparisonPredicateModifier; -// @property (readonly, retain) NSExpression *leftExpression; -// @property (readonly, retain) NSExpression *rightExpression; -// @property (nullable, readonly) SEL customSelector; -// @property (readonly) NSComparisonPredicateOptions options; - -/* @end */ - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - - - - - - -typedef NSUInteger NSCompoundPredicateType; enum { - NSNotPredicateType = 0, - NSAndPredicateType, - NSOrPredicateType, -}; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_4))) - -#ifndef _REWRITER_typedef_NSCompoundPredicate -#define _REWRITER_typedef_NSCompoundPredicate -typedef struct objc_object NSCompoundPredicate; -typedef struct {} _objc_exc_NSCompoundPredicate; -#endif - -struct NSCompoundPredicate_IMPL { - struct NSPredicate_IMPL NSPredicate_IVARS; - void *_reserved2; - NSUInteger _type; - NSArray *_subpredicates; -}; - - -// - (instancetype)initWithType:(NSCompoundPredicateType)type subpredicates:(NSArray<NSPredicate *> *)subpredicates __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)coder __attribute__((objc_designated_initializer)); - -// @property (readonly) NSCompoundPredicateType compoundPredicateType; -// @property (readonly, copy) NSArray *subpredicates; - - -// + (NSCompoundPredicate *)andPredicateWithSubpredicates:(NSArray<NSPredicate *> *)subpredicates __attribute__((swift_name("init(andPredicateWithSubpredicates:)"))); -// + (NSCompoundPredicate *)orPredicateWithSubpredicates:(NSArray<NSPredicate *> *)subpredicates __attribute__((swift_name("init(orPredicateWithSubpredicates:)"))); -// + (NSCompoundPredicate *)notPredicateWithSubpredicate:(NSPredicate *)predicate __attribute__((swift_name("init(notPredicateWithSubpredicate:)"))); - -/* @end */ - -__attribute__((availability(macosx,introduced=10_10))) -typedef NSInteger NSDateComponentsFormatterUnitsStyle; enum { - NSDateComponentsFormatterUnitsStylePositional = 0, - NSDateComponentsFormatterUnitsStyleAbbreviated, - NSDateComponentsFormatterUnitsStyleShort, - NSDateComponentsFormatterUnitsStyleFull, - NSDateComponentsFormatterUnitsStyleSpellOut -}; - -__attribute__((availability(macosx,introduced=10_10))) -typedef NSUInteger NSDateComponentsFormatterZeroFormattingBehavior; enum { - NSDateComponentsFormatterZeroFormattingBehaviorNone = (0), - NSDateComponentsFormatterZeroFormattingBehaviorDefault = (1 << 0), - - NSDateComponentsFormatterZeroFormattingBehaviorDropLeading = (1 << 1), - NSDateComponentsFormatterZeroFormattingBehaviorDropMiddle = (1 << 2), - NSDateComponentsFormatterZeroFormattingBehaviorDropTrailing = (1 << 3), - NSDateComponentsFormatterZeroFormattingBehaviorDropAll = (NSDateComponentsFormatterZeroFormattingBehaviorDropLeading | NSDateComponentsFormatterZeroFormattingBehaviorDropMiddle | NSDateComponentsFormatterZeroFormattingBehaviorDropTrailing), - - NSDateComponentsFormatterZeroFormattingBehaviorPad = (1 << 16), -}; - - - -__attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSDateComponentsFormatter -#define _REWRITER_typedef_NSDateComponentsFormatter -typedef struct objc_object NSDateComponentsFormatter; -typedef struct {} _objc_exc_NSDateComponentsFormatter; -#endif - -struct NSDateComponentsFormatter_IMPL { - struct NSFormatter_IMPL NSFormatter_IVARS; - pthread_mutex_t _lock; - void *_fmt; - void *_unused; - NSString *_fmtLocaleIdent; - NSCalendar *_calendar; - NSDate *_referenceDate; - NSNumberFormatter *_unitFormatter; - NSCalendarUnit _allowedUnits; - NSFormattingContext _formattingContext; - NSDateComponentsFormatterUnitsStyle _unitsStyle; - NSDateComponentsFormatterZeroFormattingBehavior _zeroFormattingBehavior; - NSInteger _maximumUnitCount; - BOOL _allowsFractionalUnits; - BOOL _collapsesLargestUnit; - BOOL _includesApproximationPhrase; - BOOL _includesTimeRemainingPhrase; - void *_reserved; -}; - - - - -// - (nullable NSString *)stringForObjectValue:(id)obj; - -// - (nullable NSString *)stringFromDateComponents:(NSDateComponents *)components; - - - - - - - -// - (nullable NSString *)stringFromDate:(NSDate *)startDate toDate:(NSDate *)endDate; - - - -// - (nullable NSString *)stringFromTimeInterval:(NSTimeInterval)ti; - - -// + (nullable NSString *)localizedStringFromDateComponents:(NSDateComponents *)components unitsStyle:(NSDateComponentsFormatterUnitsStyle) unitsStyle; - - - -// @property NSDateComponentsFormatterUnitsStyle unitsStyle; -// @property NSCalendarUnit allowedUnits; - - - - - -// @property NSDateComponentsFormatterZeroFormattingBehavior zeroFormattingBehavior; - - - -// @property (nullable, copy) NSCalendar *calendar; - - - -// @property BOOL allowsFractionalUnits; -// @property NSInteger maximumUnitCount; - - - -// @property BOOL collapsesLargestUnit; - - - -// @property BOOL includesApproximationPhrase; - - - -// @property BOOL includesTimeRemainingPhrase; - - - - -// @property NSFormattingContext formattingContext; - - - -// - (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string errorDescription:(out NSString * _Nullable * _Nullable)error; - -/* @end */ - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSMutableDictionary; -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -// @class NSPredicate; -#ifndef _REWRITER_typedef_NSPredicate -#define _REWRITER_typedef_NSPredicate -typedef struct objc_object NSPredicate; -typedef struct {} _objc_exc_NSPredicate; -#endif - - - - - - -typedef NSUInteger NSExpressionType; enum { - NSConstantValueExpressionType = 0, - NSEvaluatedObjectExpressionType, - NSVariableExpressionType, - NSKeyPathExpressionType, - NSFunctionExpressionType, - NSUnionSetExpressionType __attribute__((availability(macosx,introduced=10_5))), - NSIntersectSetExpressionType __attribute__((availability(macosx,introduced=10_5))), - NSMinusSetExpressionType __attribute__((availability(macosx,introduced=10_5))), - NSSubqueryExpressionType __attribute__((availability(macosx,introduced=10_5))) = 13, - NSAggregateExpressionType __attribute__((availability(macosx,introduced=10_5))) = 14, - NSAnyKeyExpressionType __attribute__((availability(macosx,introduced=10_9))) = 15, - NSBlockExpressionType = 19, - NSConditionalExpressionType __attribute__((availability(macosx,introduced=10_11))) = 20 - -}; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_4))) - -#ifndef _REWRITER_typedef_NSExpression -#define _REWRITER_typedef_NSExpression -typedef struct objc_object NSExpression; -typedef struct {} _objc_exc_NSExpression; -#endif - - struct _expressionFlags { - unsigned int _evaluationBlocked : 1; - unsigned int _reservedExpressionFlags : 31; - } ; -struct NSExpression_IMPL { - struct NSObject_IMPL NSObject_IVARS; - - struct _expressionFlags _expressionFlags; - uint32_t reserved; - NSExpressionType _expressionType; -}; - - -// + (NSExpression *)expressionWithFormat:(NSString *)expressionFormat argumentArray:(NSArray *)arguments __attribute__((availability(macosx,introduced=10_6))); -// + (NSExpression *)expressionWithFormat:(NSString *)expressionFormat, ... __attribute__((availability(macosx,introduced=10_6))); -// + (NSExpression *)expressionWithFormat:(NSString *)expressionFormat arguments:(va_list)argList __attribute__((availability(macosx,introduced=10_6))); - -// + (NSExpression *)expressionForConstantValue:(nullable id)obj; -// + (NSExpression *)expressionForEvaluatedObject; -// + (NSExpression *)expressionForVariable:(NSString *)string; -// + (NSExpression *)expressionForKeyPath:(NSString *)keyPath; -// + (NSExpression *)expressionForFunction:(NSString *)name arguments:(NSArray *)parameters; -// + (NSExpression *)expressionForAggregate:(NSArray *)subexpressions __attribute__((availability(macosx,introduced=10_5))); -// + (NSExpression *)expressionForUnionSet:(NSExpression *)left with:(NSExpression *)right __attribute__((availability(macosx,introduced=10_5))); -// + (NSExpression *)expressionForIntersectSet:(NSExpression *)left with:(NSExpression *)right __attribute__((availability(macosx,introduced=10_5))); -// + (NSExpression *)expressionForMinusSet:(NSExpression *)left with:(NSExpression *)right __attribute__((availability(macosx,introduced=10_5))); -// + (NSExpression *)expressionForSubquery:(NSExpression *)expression usingIteratorVariable:(NSString *)variable predicate:(id)predicate __attribute__((availability(macosx,introduced=10_5))); -// + (NSExpression *)expressionForFunction:(NSExpression *)target selectorName:(NSString *)name arguments:(nullable NSArray *)parameters __attribute__((availability(macosx,introduced=10_5))); -// + (NSExpression *)expressionForAnyKey __attribute__((availability(macosx,introduced=10_9))); -// + (NSExpression *)expressionForBlock:(id (^)(id _Nullable evaluatedObject, NSArray *expressions, NSMutableDictionary * _Nullable context))block arguments:(nullable NSArray<NSExpression *> *)arguments __attribute__((availability(macosx,introduced=10_6))); -// + (NSExpression *)expressionForConditional:(NSPredicate *)predicate trueExpression:(NSExpression *)trueExpression falseExpression:(NSExpression *)falseExpression __attribute__((availability(macosx,introduced=10_11))); - -// - (instancetype)initWithExpressionType:(NSExpressionType)type __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)coder __attribute__((objc_designated_initializer)); - - -// @property (readonly) NSExpressionType expressionType; -// @property (readonly, retain) id constantValue; -// @property (readonly, copy) NSString *keyPath; -// @property (readonly, copy) NSString *function; -// @property (readonly, copy) NSString *variable; -// @property (readonly, copy) NSExpression *operand; -// @property (nullable, readonly, copy) NSArray<NSExpression *> *arguments; - -// @property (readonly, retain) id collection __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly, copy) NSPredicate *predicate __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly, copy) NSExpression *leftExpression __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly, copy) NSExpression *rightExpression __attribute__((availability(macosx,introduced=10_5))); - - -// @property (readonly, copy) NSExpression *trueExpression __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly, copy) NSExpression *falseExpression __attribute__((availability(macosx,introduced=10_11))); - -// @property (readonly, copy) id (^expressionBlock)(id _Nullable, NSArray *, NSMutableDictionary * _Nullable) __attribute__((availability(macosx,introduced=10_6))); - - -// - (id)expressionValueWithObject:(nullable id)object context:(nullable NSMutableDictionary *)context; - -// - (void)allowEvaluation __attribute__((availability(macosx,introduced=10_9))); - -/* @end */ - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSExtensionContext -#define _REWRITER_typedef_NSExtensionContext -typedef struct objc_object NSExtensionContext; -typedef struct {} _objc_exc_NSExtensionContext; -#endif - -struct NSExtensionContext_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - -// @property(readonly, copy, atomic) NSArray *inputItems; - - -// - (void)completeRequestReturningItems:(nullable NSArray *)items completionHandler:(void(^ _Nullable)(BOOL expired))completionHandler; - - -// - (void)cancelRequestWithError:(NSError *)error; - - -// - (void)openURL:(NSURL *)URL completionHandler:(void (^ _Nullable)(BOOL success))completionHandler; - -/* @end */ - - - -extern "C" NSString * _Null_unspecified const NSExtensionItemsAndErrorsKey __attribute__((availability(macosx,introduced=10_10))); - - -extern "C" NSString * _Null_unspecified const NSExtensionHostWillEnterForegroundNotification __attribute__((availability(macosx,unavailable))); - - -extern "C" NSString * _Null_unspecified const NSExtensionHostDidEnterBackgroundNotification __attribute__((availability(macosx,unavailable))); - - -extern "C" NSString * _Null_unspecified const NSExtensionHostWillResignActiveNotification __attribute__((availability(macosx,unavailable))); - - -extern "C" NSString * _Null_unspecified const NSExtensionHostDidBecomeActiveNotification __attribute__((availability(macosx,unavailable))); - - - - - -typedef void (*NSItemProviderCompletionHandler)(_Nullable id /*<NSSecureCoding>*/ item, NSError * _Null_unspecified error); -typedef void (*NSItemProviderLoadHandler)(_Null_unspecified NSItemProviderCompletionHandler completionHandler, _Null_unspecified Class expectedValueClass, NSDictionary * _Null_unspecified options); - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSItemProvider -#define _REWRITER_typedef_NSItemProvider -typedef struct objc_object NSItemProvider; -typedef struct {} _objc_exc_NSItemProvider; -#endif - -struct NSItemProvider_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - -// - (instancetype)initWithItem:(nullable id <NSSecureCoding>)item typeIdentifier:(nullable NSString *)typeIdentifier __attribute__((objc_designated_initializer)); - - -// - (nullable instancetype)initWithContentsOfURL:(null_unspecified NSURL *)fileURL; - - -// - (void)registerItemForTypeIdentifier:(NSString *)typeIdentifier loadHandler:(NSItemProviderLoadHandler)loadHandler; - - -// @property(copy, readonly, atomic) NSArray *registeredTypeIdentifiers; - - -// - (BOOL)hasItemConformingToTypeIdentifier:(NSString *)typeIdentifier; - - -// - (void)loadItemForTypeIdentifier:(NSString *)typeIdentifier options:(nullable NSDictionary *)options completionHandler:(nullable NSItemProviderCompletionHandler)completionHandler; - -/* @end */ - - - -extern "C" NSString * _Null_unspecified const NSItemProviderPreferredImageSizeKey __attribute__((availability(macosx,introduced=10_10))); - -// @interface NSItemProvider(NSPreviewSupport) - - -// @property(nullable, copy, atomic) NSItemProviderLoadHandler previewImageHandler __attribute__((availability(macosx,introduced=10_10))); - - -// - (void)loadPreviewImageWithOptions:(null_unspecified NSDictionary *)options completionHandler:(null_unspecified NSItemProviderCompletionHandler)completionHandler __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - - - - - -extern "C" NSString * _Null_unspecified const NSExtensionJavaScriptPreprocessingResultsKey __attribute__((availability(macosx,introduced=10_10))); - - -extern "C" NSString * _Null_unspecified const NSExtensionJavaScriptFinalizeArgumentKey __attribute__((availability(macosx,unavailable))); - - - - - -extern "C" NSString * _Null_unspecified const NSItemProviderErrorDomain __attribute__((availability(macosx,introduced=10_10))); - - -typedef NSInteger NSItemProviderErrorCode; enum { - NSItemProviderUnknownError = -1, - NSItemProviderItemUnavailableError = -1000, - NSItemProviderUnexpectedValueClassError = -1100, - NSItemProviderUnavailableCoercionError __attribute__((availability(macosx,introduced=10_11))) = -1200 -} __attribute__((availability(macosx,introduced=10_10))); - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSExtensionItem -#define _REWRITER_typedef_NSExtensionItem -typedef struct objc_object NSExtensionItem; -typedef struct {} _objc_exc_NSExtensionItem; -#endif - -struct NSExtensionItem_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - -// @property(nullable, copy, atomic) NSAttributedString *attributedTitle; - - -// @property(nullable, copy, atomic) NSAttributedString *attributedContentText; - - -// @property(nullable, copy, atomic) NSArray *attachments; - - -// @property(nullable, copy, atomic) NSDictionary *userInfo; - -/* @end */ - - - -extern "C" NSString * _Null_unspecified const NSExtensionItemAttributedTitleKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * _Null_unspecified const NSExtensionItemAttributedContentTextKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * _Null_unspecified const NSExtensionItemAttachmentsKey __attribute__((availability(macosx,introduced=10_10))); -// @class NSExtensionContext; -#ifndef _REWRITER_typedef_NSExtensionContext -#define _REWRITER_typedef_NSExtensionContext -typedef struct objc_object NSExtensionContext; -typedef struct {} _objc_exc_NSExtensionContext; -#endif - - - -// @protocol NSExtensionRequestHandling <NSObject> - -/* @required */ - - -// - (void)beginRequestWithExtensionContext:(NSExtensionContext *)context; - -/* @end */ - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSOperationQueue -#define _REWRITER_typedef_NSOperationQueue -typedef struct objc_object NSOperationQueue; -typedef struct {} _objc_exc_NSOperationQueue; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - - -// @protocol NSFilePresenter; - - - -typedef NSUInteger NSFileCoordinatorReadingOptions; enum { - - - - NSFileCoordinatorReadingWithoutChanges = 1 << 0, - - - - NSFileCoordinatorReadingResolvesSymbolicLink = 1 << 1, - - - - NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly __attribute__((availability(macosx,introduced=10_10))) = 1 << 2, - - - - - - NSFileCoordinatorReadingForUploading __attribute__((availability(macosx,introduced=10_10))) = 1 << 3, - -}; - -typedef NSUInteger NSFileCoordinatorWritingOptions; enum { - NSFileCoordinatorWritingForDeleting = 1 << 0, - - - - - - NSFileCoordinatorWritingForMoving = 1 << 1, - - - - NSFileCoordinatorWritingForMerging = 1 << 2, - - - - - - - - NSFileCoordinatorWritingForReplacing = 1 << 3, - - - - NSFileCoordinatorWritingContentIndependentMetadataOnly __attribute__((availability(macosx,introduced=10_10))) = 1 << 4 - -}; - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSFileAccessIntent -#define _REWRITER_typedef_NSFileAccessIntent -typedef struct objc_object NSFileAccessIntent; -typedef struct {} _objc_exc_NSFileAccessIntent; -#endif - -struct NSFileAccessIntent_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURL *_url; - BOOL _isRead; - NSInteger _options; -}; - -// + (instancetype)readingIntentWithURL:(NSURL *)url options:(NSFileCoordinatorReadingOptions)options; -// + (instancetype)writingIntentWithURL:(NSURL *)url options:(NSFileCoordinatorWritingOptions)options; -// @property (readonly, copy) NSURL *URL; -/* @end */ - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSFileCoordinator -#define _REWRITER_typedef_NSFileCoordinator -typedef struct objc_object NSFileCoordinator; -typedef struct {} _objc_exc_NSFileCoordinator; -#endif - -struct NSFileCoordinator_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _accessArbiter; - id _fileReactor; - id _purposeID; - NSURL *_recentFilePresenterURL; - id _accessClaimIDOrIDs; - BOOL _isCancelled; - NSMutableDictionary *_movedItems; -}; - - - - - - - - -// + (void)addFilePresenter:(id<NSFilePresenter>)filePresenter; -// + (void)removeFilePresenter:(id<NSFilePresenter>)filePresenter; -// + (NSArray<id<NSFilePresenter>> *)filePresenters; -// - (instancetype)initWithFilePresenter:(nullable id<NSFilePresenter>)filePresenterOrNil __attribute__((objc_designated_initializer)); -// @property (copy) NSString *purposeIdentifier __attribute__((availability(macosx,introduced=10_7))); -// - (void)coordinateAccessWithIntents:(NSArray<NSFileAccessIntent *> *)intents queue:(NSOperationQueue *)queue byAccessor:(void (^)(NSError * _Nullable error))accessor __attribute__((availability(macosx,introduced=10_10))); -// - (void)coordinateReadingItemAtURL:(NSURL *)url options:(NSFileCoordinatorReadingOptions)options error:(NSError **)outError byAccessor:(void (^)(NSURL *newURL))reader; -// - (void)coordinateWritingItemAtURL:(NSURL *)url options:(NSFileCoordinatorWritingOptions)options error:(NSError **)outError byAccessor:(void (^)(NSURL *newURL))writer; -// - (void)coordinateReadingItemAtURL:(NSURL *)readingURL options:(NSFileCoordinatorReadingOptions)readingOptions writingItemAtURL:(NSURL *)writingURL options:(NSFileCoordinatorWritingOptions)writingOptions error:(NSError **)outError byAccessor:(void (^)(NSURL *newReadingURL, NSURL *newWritingURL))readerWriter; -// - (void)coordinateWritingItemAtURL:(NSURL *)url1 options:(NSFileCoordinatorWritingOptions)options1 writingItemAtURL:(NSURL *)url2 options:(NSFileCoordinatorWritingOptions)options2 error:(NSError **)outError byAccessor:(void (^)(NSURL *newURL1, NSURL *newURL2))writer; -// - (void)prepareForReadingItemsAtURLs:(NSArray<NSURL *> *)readingURLs options:(NSFileCoordinatorReadingOptions)readingOptions writingItemsAtURLs:(NSArray<NSURL *> *)writingURLs options:(NSFileCoordinatorWritingOptions)writingOptions error:(NSError **)outError byAccessor:(void (^)(void (^completionHandler)(void)))batchAccessor; -// - (void)itemAtURL:(NSURL *)oldURL willMoveToURL:(NSURL *)newURL __attribute__((availability(macosx,introduced=10_8))); -// - (void)itemAtURL:(NSURL *)oldURL didMoveToURL:(NSURL *)newURL; - - - - - - - -// - (void)cancel; - -/* @end */ - - - - - - - - - -// @class NSError; -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSFileVersion -#define _REWRITER_typedef_NSFileVersion -typedef struct objc_object NSFileVersion; -typedef struct {} _objc_exc_NSFileVersion; -#endif - -#ifndef _REWRITER_typedef_NSOperationQueue -#define _REWRITER_typedef_NSOperationQueue -typedef struct objc_object NSOperationQueue; -typedef struct {} _objc_exc_NSOperationQueue; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -// @protocol NSFilePresenter<NSObject> - -/* @required */ - - - - - -// @property (nullable, readonly, copy) NSURL *presentedItemURL; - - - - - -// @property (readonly, retain) NSOperationQueue *presentedItemOperationQueue; - -/* @optional */ - - - -// @property (nullable, readonly, copy) NSURL *primaryPresentedItemURL __attribute__((availability(macosx,introduced=10_8))); - - - - - -// - (void)relinquishPresentedItemToReader:(void (^)(void (^ _Nullable reacquirer)(void)))reader; - - - - - -// - (void)relinquishPresentedItemToWriter:(void (^)(void (^ _Nullable reacquirer)(void)))writer; - - - - - - - -// - (void)savePresentedItemChangesWithCompletionHandler:(void (^)(NSError * _Nullable errorOrNil))completionHandler; - - - - - - - -// - (void)accommodatePresentedItemDeletionWithCompletionHandler:(void (^)(NSError * _Nullable errorOrNil))completionHandler; -// - (void)presentedItemDidMoveToURL:(NSURL *)newURL; -// - (void)presentedItemDidChange; - - - - - -// - (void)presentedItemDidGainVersion:(NSFileVersion *)version; -// - (void)presentedItemDidLoseVersion:(NSFileVersion *)version; -// - (void)presentedItemDidResolveConflictVersion:(NSFileVersion *)version; -// - (void)accommodatePresentedSubitemDeletionAtURL:(NSURL *)url completionHandler:(void (^)(NSError * _Nullable errorOrNil))completionHandler; - - - - - -// - (void)presentedSubitemDidAppearAtURL:(NSURL *)url; - - - - - -// - (void)presentedSubitemAtURL:(NSURL *)oldURL didMoveToURL:(NSURL *)newURL; - - - - - -// - (void)presentedSubitemDidChangeAtURL:(NSURL *)url; - - - -// - (void)presentedSubitemAtURL:(NSURL *)url didGainVersion:(NSFileVersion *)version; -// - (void)presentedSubitemAtURL:(NSURL *)url didLoseVersion:(NSFileVersion *)version; -// - (void)presentedSubitemAtURL:(NSURL *)url didResolveConflictVersion:(NSFileVersion *)version; - -/* @end */ - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - - - - -typedef NSUInteger NSFileVersionAddingOptions; enum { - - - - NSFileVersionAddingByMoving = 1 << 0 - -}; - -typedef NSUInteger NSFileVersionReplacingOptions; enum { - - - - NSFileVersionReplacingByMoving = 1 << 0 - -}; - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSFileVersion -#define _REWRITER_typedef_NSFileVersion -typedef struct objc_object NSFileVersion; -typedef struct {} _objc_exc_NSFileVersion; -#endif - -struct NSFileVersion_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURL *_fileURL; - id _addition; - id _deadVersionIdentifier; - id _nonLocalVersion; - NSURL *_contentsURL; - BOOL _isBackup; - NSString *_localizedName; - NSString *_localizedComputerName; - NSDate *_modificationDate; - BOOL _isResolved; - BOOL _contentsURLIsAccessed; - id _reserved; - NSString *_name; -}; - - - - -// + (nullable NSFileVersion *)currentVersionOfItemAtURL:(NSURL *)url; - - - -// + (nullable NSArray<NSFileVersion *> *)otherVersionsOfItemAtURL:(NSURL *)url; - - - -// + (nullable NSArray<NSFileVersion *> *)unresolvedConflictVersionsOfItemAtURL:(NSURL *)url; - - - - - - - -// + (void)getNonlocalVersionsOfItemAtURL:(NSURL *)url completionHandler:(void (^)(NSArray<NSFileVersion *> * _Nullable nonlocalFileVersions, NSError * _Nullable error))completionHandler __attribute__((availability(macosx,introduced=10_10))); - - - -// + (nullable NSFileVersion *)versionOfItemAtURL:(NSURL *)url forPersistentIdentifier:(id)persistentIdentifier; - - - - - - - -// + (nullable NSFileVersion *)addVersionOfItemAtURL:(NSURL *)url withContentsOfURL:(NSURL *)contentsURL options:(NSFileVersionAddingOptions)options error:(NSError **)outError __attribute__((availability(macosx,introduced=10_7))); - - - -// + (NSURL *)temporaryDirectoryURLForNewVersionOfItemAtURL:(NSURL *)url __attribute__((availability(macosx,introduced=10_7))); - - - -// @property (readonly, copy) NSURL *URL; - - - -// @property (nullable, readonly, copy) NSString *localizedName; - - - -// @property (nullable, readonly, copy) NSString *localizedNameOfSavingComputer; - - - -// @property (nullable, readonly, copy) NSDate *modificationDate; - - - -// @property (readonly, retain) id<NSCoding> persistentIdentifier; - - - -// @property (readonly, getter=isConflict) BOOL conflict; - - - - - - - -// @property (getter=isResolved) BOOL resolved; -// @property (getter=isDiscardable) BOOL discardable __attribute__((availability(macosx,introduced=10_7))); - - - -// @property (readonly) BOOL hasLocalContents __attribute__((availability(macosx,introduced=10_10))); - - - -// @property (readonly) BOOL hasThumbnail __attribute__((availability(macosx,introduced=10_10))); - - - - - -// - (nullable NSURL *)replaceItemAtURL:(NSURL *)url options:(NSFileVersionReplacingOptions)options error:(NSError **)error; - - - - - - - -// - (BOOL)removeAndReturnError:(NSError **)outError; - - - - - -// + (BOOL)removeOtherVersionsOfItemAtURL:(NSURL *)url error:(NSError **)outError; - -/* @end */ - - - - - - - - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - - - - -typedef NSUInteger NSFileWrapperReadingOptions; enum { - - - - NSFileWrapperReadingImmediate = 1 << 0, - - - - NSFileWrapperReadingWithoutMapping = 1 << 1 - -} __attribute__((availability(macosx,introduced=10_6))); - -typedef NSUInteger NSFileWrapperWritingOptions; enum { - - - - NSFileWrapperWritingAtomic = 1 << 0, - - - - NSFileWrapperWritingWithNameUpdating = 1 << 1 - -} __attribute__((availability(macosx,introduced=10_6))); - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_0))) - -#ifndef _REWRITER_typedef_NSFileWrapper -#define _REWRITER_typedef_NSFileWrapper -typedef struct objc_object NSFileWrapper; -typedef struct {} _objc_exc_NSFileWrapper; -#endif - -struct NSFileWrapper_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSDictionary *_fileAttributes; - NSString *_preferredFileName; - NSString *_fileName; - id _contents; - id _icon; - id _moreVars; -}; - - - - - - -// - (nullable instancetype)initWithURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)outError __attribute__((objc_designated_initializer)) __attribute__((availability(macosx,introduced=10_6))); - - - -// - (instancetype)initDirectoryWithFileWrappers:(NSDictionary<NSString *, NSFileWrapper *> *)childrenByPreferredName __attribute__((objc_designated_initializer)); - - - -// - (instancetype)initRegularFileWithContents:(NSData *)contents __attribute__((objc_designated_initializer)); - - - -// - (instancetype)initSymbolicLinkWithDestinationURL:(NSURL *)url __attribute__((objc_designated_initializer)) __attribute__((availability(macosx,introduced=10_6))); - - - -// - (nullable instancetype)initWithSerializedRepresentation:(NSData *)serializeRepresentation __attribute__((objc_designated_initializer)); - -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); - - - - - -// @property (readonly, getter=isDirectory) BOOL directory; -// @property (readonly, getter=isRegularFile) BOOL regularFile; -// @property (readonly, getter=isSymbolicLink) BOOL symbolicLink; - - - - - -// @property (nullable, copy) NSString *preferredFilename; - - - -// @property (nullable, copy) NSString *filename; - - - -// @property (copy) NSDictionary<NSString *, id> *fileAttributes; -// - (BOOL)matchesContentsOfURL:(NSURL *)url __attribute__((availability(macosx,introduced=10_6))); - - - -// - (BOOL)readFromURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)outError __attribute__((availability(macosx,introduced=10_6))); - - - - - -// - (BOOL)writeToURL:(NSURL *)url options:(NSFileWrapperWritingOptions)options originalContentsURL:(nullable NSURL *)originalContentsURL error:(NSError **)outError __attribute__((availability(macosx,introduced=10_6))); - - - - - -// @property (nullable, readonly, copy) NSData *serializedRepresentation; - - - - - - - -// - (NSString *)addFileWrapper:(NSFileWrapper *)child; - - - -// - (NSString *)addRegularFileWithContents:(NSData *)data preferredFilename:(NSString *)fileName; - - - -// - (void)removeFileWrapper:(NSFileWrapper *)child; - - - -// @property (nullable, readonly, copy) NSDictionary<NSString *, NSFileWrapper *> *fileWrappers; - - - -// - (nullable NSString *)keyForFileWrapper:(NSFileWrapper *)child; - - - - - - - -// @property (nullable, readonly, copy) NSData *regularFileContents; - - - - - - - -// @property (nullable, readonly, copy) NSURL *symbolicLinkDestinationURL __attribute__((availability(macosx,introduced=10_6))); - -/* @end */ - - - - -// @interface NSFileWrapper(NSDeprecated) - - - - - -// - (nullable id)initWithPath:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use -initWithURL:options:error: instead."))); -// - (id)initSymbolicLinkWithDestination:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use -initSymbolicLinkWithDestinationURL: and -setPreferredFileName:, if necessary, instead."))); -// - (BOOL)needsToBeUpdatedFromPath:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use -matchesContentsOfURL: instead."))); -// - (BOOL)updateFromPath:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use -readFromURL:options:error: instead."))); -// - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)atomicFlag updateFilenames:(BOOL)updateFilenamesFlag __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use -writeToURL:options:originalContentsURL:error: instead."))); -// - (NSString *)addFileWithPath:(NSString *)path __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Instantiate a new NSFileWrapper with -initWithURL:options:error:, send it -setPreferredFileName: if necessary, then use -addFileWrapper: instead."))); -// - (NSString *)addSymbolicLinkWithDestination:(NSString *)path preferredFilename:(NSString *)filename __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Instantiate a new NSFileWrapper with -initWithSymbolicLinkDestinationURL:, send it -setPreferredFileName: if necessary, then use -addFileWrapper: instead."))); -// - (NSString *)symbolicLinkDestination __attribute__((availability(macosx,introduced=10_0,deprecated=10_10,message="" "Use -symbolicLinkDestinationURL instead."))); - -/* @end */ - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSOrthography -#define _REWRITER_typedef_NSOrthography -typedef struct objc_object NSOrthography; -typedef struct {} _objc_exc_NSOrthography; -#endif - -#ifndef _REWRITER_typedef_NSValue -#define _REWRITER_typedef_NSValue -typedef struct objc_object NSValue; -typedef struct {} _objc_exc_NSValue; -#endif - - - - - - - - -extern "C" NSString *const NSLinguisticTagSchemeTokenType __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagSchemeLexicalClass __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagSchemeNameType __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagSchemeNameTypeOrLexicalClass __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagSchemeLemma __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagSchemeLanguage __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagSchemeScript __attribute__((availability(macosx,introduced=10_7))); - - -extern "C" NSString *const NSLinguisticTagWord __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagPunctuation __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagWhitespace __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagOther __attribute__((availability(macosx,introduced=10_7))); - - -extern "C" NSString *const NSLinguisticTagNoun __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagVerb __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagAdjective __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagAdverb __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagPronoun __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagDeterminer __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagParticle __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagPreposition __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagNumber __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagConjunction __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagInterjection __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagClassifier __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagIdiom __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagOtherWord __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagSentenceTerminator __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagOpenQuote __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagCloseQuote __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagOpenParenthesis __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagCloseParenthesis __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagWordJoiner __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagDash __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagOtherPunctuation __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagParagraphBreak __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagOtherWhitespace __attribute__((availability(macosx,introduced=10_7))); - - -extern "C" NSString *const NSLinguisticTagPersonalName __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagPlaceName __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString *const NSLinguisticTagOrganizationName __attribute__((availability(macosx,introduced=10_7))); - - - - - -typedef NSUInteger NSLinguisticTaggerOptions; enum { - NSLinguisticTaggerOmitWords = 1 << 0, - NSLinguisticTaggerOmitPunctuation = 1 << 1, - NSLinguisticTaggerOmitWhitespace = 1 << 2, - NSLinguisticTaggerOmitOther = 1 << 3, - NSLinguisticTaggerJoinNames = 1 << 4 -}; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSLinguisticTagger -#define _REWRITER_typedef_NSLinguisticTagger -typedef struct objc_object NSLinguisticTagger; -typedef struct {} _objc_exc_NSLinguisticTagger; -#endif - -struct NSLinguisticTagger_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSArray *_schemes; - NSUInteger _options; - NSString *_string; - id _orthographyArray; - id _tokenArray; - id _reserved; -}; - - - - -// - (instancetype)initWithTagSchemes:(NSArray<NSString *> *)tagSchemes options:(NSUInteger)opts __attribute__((objc_designated_initializer)) __attribute__((availability(macosx,introduced=10_7))); - -// @property (readonly, copy) NSArray<NSString *> *tagSchemes __attribute__((availability(macosx,introduced=10_7))); -// @property (nullable, retain) NSString *string __attribute__((availability(macosx,introduced=10_7))); - - - -// + (NSArray<NSString *> *)availableTagSchemesForLanguage:(NSString *)language __attribute__((availability(macosx,introduced=10_7))); - - - -// - (void)setOrthography:(nullable NSOrthography *)orthography range:(NSRange)range __attribute__((availability(macosx,introduced=10_7))); -// - (nullable NSOrthography *)orthographyAtIndex:(NSUInteger)charIndex effectiveRange:(nullable NSRangePointer)effectiveRange __attribute__((availability(macosx,introduced=10_7))); - - - -// - (void)stringEditedInRange:(NSRange)newRange changeInLength:(NSInteger)delta __attribute__((availability(macosx,introduced=10_7))); - - - -// - (void)enumerateTagsInRange:(NSRange)range scheme:(NSString *)tagScheme options:(NSLinguisticTaggerOptions)opts usingBlock:(void (^)(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop))block __attribute__((availability(macosx,introduced=10_7))); - -// - (NSRange)sentenceRangeForRange:(NSRange)range __attribute__((availability(macosx,introduced=10_7))); -// - (nullable NSString *)tagAtIndex:(NSUInteger)charIndex scheme:(NSString *)tagScheme tokenRange:(nullable NSRangePointer)tokenRange sentenceRange:(nullable NSRangePointer)sentenceRange __attribute__((availability(macosx,introduced=10_7))); -// - (NSArray<NSString *> *)tagsInRange:(NSRange)range scheme:(NSString *)tagScheme options:(NSLinguisticTaggerOptions)opts tokenRanges:(NSArray<NSValue *> * _Nullable * _Nullable)tokenRanges __attribute__((availability(macosx,introduced=10_7))); -// - (nullable NSArray<NSString *> *)possibleTagsAtIndex:(NSUInteger)charIndex scheme:(NSString *)tagScheme tokenRange:(nullable NSRangePointer)tokenRange sentenceRange:(nullable NSRangePointer)sentenceRange scores:(NSArray<NSValue *> * _Nullable * _Nullable)scores __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - -// @interface NSString (NSLinguisticAnalysis) - - - -// - (NSArray<NSString *> *)linguisticTagsInRange:(NSRange)range scheme:(NSString *)tagScheme options:(NSLinguisticTaggerOptions)opts orthography:(nullable NSOrthography *)orthography tokenRanges:(NSArray<NSValue *> * _Nullable * _Nullable)tokenRanges __attribute__((availability(macosx,introduced=10_7))); -// - (void)enumerateLinguisticTagsInRange:(NSRange)range scheme:(NSString *)tagScheme options:(NSLinguisticTaggerOptions)opts orthography:(nullable NSOrthography *)orthography usingBlock:(void (^)(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop))block __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - - -extern "C" NSString * const NSMetadataItemFSNameKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataItemDisplayNameKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataItemURLKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataItemPathKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataItemFSSizeKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataItemFSCreationDateKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataItemFSContentChangeDateKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataItemContentTypeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemContentTypeTreeKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemIsUbiquitousKey __attribute__((availability(macosx,introduced=10_7))); - -extern "C" NSString * const NSMetadataUbiquitousItemHasUnresolvedConflictsKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataUbiquitousItemIsDownloadedKey __attribute__((availability(macosx,introduced=10_7,deprecated=10_9,message="" "Use NSMetadataUbiquitousItemDownloadingStatusKey instead"))); -extern "C" NSString * const NSMetadataUbiquitousItemDownloadingStatusKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataUbiquitousItemDownloadingStatusNotDownloaded __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataUbiquitousItemDownloadingStatusDownloaded __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataUbiquitousItemDownloadingStatusCurrent __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataUbiquitousItemIsDownloadingKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataUbiquitousItemIsUploadedKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataUbiquitousItemIsUploadingKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataUbiquitousItemPercentDownloadedKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataUbiquitousItemPercentUploadedKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataUbiquitousItemDownloadingErrorKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataUbiquitousItemUploadingErrorKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataUbiquitousItemDownloadRequestedKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSMetadataUbiquitousItemIsExternalDocumentKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSMetadataUbiquitousItemContainerDisplayNameKey __attribute__((availability(macosx,introduced=10_10))); -extern "C" NSString * const NSMetadataUbiquitousItemURLInLocalContainerKey __attribute__((availability(macosx,introduced=10_10))); - - - -extern "C" NSString * const NSMetadataItemAttributeChangeDateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemKeywordsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemTitleKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAuthorsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemEditorsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemParticipantsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemProjectsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemDownloadedDateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemWhereFromsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemCommentKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemCopyrightKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemLastUsedDateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemContentCreationDateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemContentModificationDateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemDateAddedKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemDurationSecondsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemContactKeywordsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemVersionKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemPixelHeightKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemPixelWidthKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemPixelCountKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemColorSpaceKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemBitsPerSampleKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemFlashOnOffKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemFocalLengthKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAcquisitionMakeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAcquisitionModelKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemISOSpeedKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemOrientationKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemLayerNamesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemWhiteBalanceKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemApertureKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemProfileNameKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemResolutionWidthDPIKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemResolutionHeightDPIKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemExposureModeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemExposureTimeSecondsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemEXIFVersionKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemCameraOwnerKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemFocalLength35mmKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemLensModelKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemEXIFGPSVersionKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAltitudeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemLatitudeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemLongitudeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemSpeedKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemTimestampKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSTrackKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemImageDirectionKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemNamedLocationKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemGPSStatusKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSMeasureModeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSDOPKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSMapDatumKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSDestLatitudeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSDestLongitudeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSDestBearingKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSDestDistanceKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSProcessingMethodKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSAreaInformationKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSDateStampKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGPSDifferentalKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemCodecsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemMediaTypesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemStreamableKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemTotalBitRateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemVideoBitRateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAudioBitRateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemDeliveryTypeKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemAlbumKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemHasAlphaChannelKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemRedEyeOnOffKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemMeteringModeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemMaxApertureKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemFNumberKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemExposureProgramKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemExposureTimeStringKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemHeadlineKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemInstructionsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemCityKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemStateOrProvinceKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemCountryKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemTextContentKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemAudioSampleRateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAudioChannelCountKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemTempoKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemKeySignatureKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemTimeSignatureKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAudioEncodingApplicationKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemComposerKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemLyricistKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAudioTrackNumberKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemRecordingDateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemMusicalGenreKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemIsGeneralMIDISequenceKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemRecordingYearKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemOrganizationsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemLanguagesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemRightsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemPublishersKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemContributorsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemCoverageKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemSubjectKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemThemeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemDescriptionKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemIdentifierKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAudiencesKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemNumberOfPagesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemPageWidthKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemPageHeightKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemSecurityMethodKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemCreatorKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemEncodingApplicationsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemDueDateKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemStarRatingKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemPhoneNumbersKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemEmailAddressesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemInstantMessageAddressesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemKindKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemRecipientsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemFinderCommentKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemFontsKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemAppleLoopsRootKeyKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAppleLoopsKeyFilterTypeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAppleLoopsLoopModeKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAppleLoopDescriptorsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemMusicalInstrumentCategoryKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemMusicalInstrumentNameKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemCFBundleIdentifierKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemInformationKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemDirectorKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemProducerKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemGenreKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemPerformersKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemOriginalFormatKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemOriginalSourceKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAuthorEmailAddressesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemRecipientEmailAddressesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemAuthorAddressesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemRecipientAddressesKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemIsLikelyJunkKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemExecutableArchitecturesKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemExecutablePlatformKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataItemApplicationCategoriesKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataItemIsApplicationManagedKey __attribute__((availability(macosx,introduced=10_9))); - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSPredicate -#define _REWRITER_typedef_NSPredicate -typedef struct objc_object NSPredicate; -typedef struct {} _objc_exc_NSPredicate; -#endif - -#ifndef _REWRITER_typedef_NSOperationQueue -#define _REWRITER_typedef_NSOperationQueue -typedef struct objc_object NSOperationQueue; -typedef struct {} _objc_exc_NSOperationQueue; -#endif - -#ifndef _REWRITER_typedef_NSSortDescriptor -#define _REWRITER_typedef_NSSortDescriptor -typedef struct objc_object NSSortDescriptor; -typedef struct {} _objc_exc_NSSortDescriptor; -#endif - -// @class NSMetadataItem; -#ifndef _REWRITER_typedef_NSMetadataItem -#define _REWRITER_typedef_NSMetadataItem -typedef struct objc_object NSMetadataItem; -typedef struct {} _objc_exc_NSMetadataItem; -#endif - -#ifndef _REWRITER_typedef_NSMetadataQueryAttributeValueTuple -#define _REWRITER_typedef_NSMetadataQueryAttributeValueTuple -typedef struct objc_object NSMetadataQueryAttributeValueTuple; -typedef struct {} _objc_exc_NSMetadataQueryAttributeValueTuple; -#endif - -#ifndef _REWRITER_typedef_NSMetadataQueryResultGroup -#define _REWRITER_typedef_NSMetadataQueryResultGroup -typedef struct objc_object NSMetadataQueryResultGroup; -typedef struct {} _objc_exc_NSMetadataQueryResultGroup; -#endif - -// @protocol NSMetadataQueryDelegate; - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_4))) - -#ifndef _REWRITER_typedef_NSMetadataQuery -#define _REWRITER_typedef_NSMetadataQuery -typedef struct objc_object NSMetadataQuery; -typedef struct {} _objc_exc_NSMetadataQuery; -#endif - -struct NSMetadataQuery_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSUInteger _flags; - NSTimeInterval _interval; - id _private[11]; - void *_reserved; -}; - - -// @property (nullable, assign) id<NSMetadataQueryDelegate> delegate; -// @property (nullable, copy) NSPredicate *predicate; -// @property (copy) NSArray<NSSortDescriptor *> *sortDescriptors; -// @property (copy) NSArray<NSString *> *valueListAttributes; -// @property (nullable, copy) NSArray<NSString *> *groupingAttributes; -// @property NSTimeInterval notificationBatchingInterval; - -// @property (copy) NSArray *searchScopes; - - - - - -// @property (nullable, copy) NSArray *searchItems __attribute__((availability(macosx,introduced=10_9))); - - - -// @property (nullable, retain) NSOperationQueue *operationQueue __attribute__((availability(macosx,introduced=10_9))); - - -// - (BOOL)startQuery; -// - (void)stopQuery; - -// @property (readonly, getter=isStarted) BOOL started; -// @property (readonly, getter=isGathering) BOOL gathering; -// @property (readonly, getter=isStopped) BOOL stopped; - -// - (void)disableUpdates; -// - (void)enableUpdates; - - - -// @property (readonly) NSUInteger resultCount; -// - (id)resultAtIndex:(NSUInteger)idx; - -// - (void)enumerateResultsUsingBlock:(void (^)(id result, NSUInteger idx, BOOL *stop))block __attribute__((availability(macosx,introduced=10_9))); -// - (void)enumerateResultsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id result, NSUInteger idx, BOOL *stop))block __attribute__((availability(macosx,introduced=10_9))); - -// @property (readonly, copy) NSArray *results; - -// - (NSUInteger)indexOfResult:(id)result; - -// @property (readonly, copy) NSDictionary<NSString *, NSArray<NSMetadataQueryAttributeValueTuple *> *> *valueLists; - -// @property (readonly, copy) NSArray<NSMetadataQueryResultGroup *> *groupedResults; - -// - (nullable id)valueOfAttribute:(NSString *)attrName forResultAtIndex:(NSUInteger)idx; - -/* @end */ - - -// @protocol NSMetadataQueryDelegate <NSObject> -/* @optional */ - -// - (id)metadataQuery:(NSMetadataQuery *)query replacementObjectForResultObject:(NSMetadataItem *)result; -// - (id)metadataQuery:(NSMetadataQuery *)query replacementValueForAttribute:(NSString *)attrName value:(id)attrValue; - -/* @end */ - - - -extern "C" NSString * const NSMetadataQueryDidStartGatheringNotification __attribute__((availability(macosx,introduced=10_4))); -extern "C" NSString * const NSMetadataQueryGatheringProgressNotification __attribute__((availability(macosx,introduced=10_4))); -extern "C" NSString * const NSMetadataQueryDidFinishGatheringNotification __attribute__((availability(macosx,introduced=10_4))); -extern "C" NSString * const NSMetadataQueryDidUpdateNotification __attribute__((availability(macosx,introduced=10_4))); - - -extern "C" NSString * const NSMetadataQueryUpdateAddedItemsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataQueryUpdateChangedItemsKey __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataQueryUpdateRemovedItemsKey __attribute__((availability(macosx,introduced=10_9))); - -extern "C" NSString * const NSMetadataQueryResultContentRelevanceAttribute __attribute__((availability(macosx,introduced=10_4))); - - -extern "C" NSString * const NSMetadataQueryUserHomeScope __attribute__((availability(macosx,introduced=10_4))); -extern "C" NSString * const NSMetadataQueryLocalComputerScope __attribute__((availability(macosx,introduced=10_4))); -extern "C" NSString * const NSMetadataQueryNetworkScope __attribute__((availability(macosx,introduced=10_4))); - -extern "C" NSString * const NSMetadataQueryIndexedLocalComputerScope __attribute__((availability(macosx,introduced=10_9))); -extern "C" NSString * const NSMetadataQueryIndexedNetworkScope __attribute__((availability(macosx,introduced=10_9))); - - -extern "C" NSString * const NSMetadataQueryUbiquitousDocumentsScope __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataQueryUbiquitousDataScope __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSMetadataQueryAccessibleUbiquitousExternalDocumentsScope __attribute__((availability(macosx,introduced=10_10))); - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_4))) - -#ifndef _REWRITER_typedef_NSMetadataItem -#define _REWRITER_typedef_NSMetadataItem -typedef struct objc_object NSMetadataItem; -typedef struct {} _objc_exc_NSMetadataItem; -#endif - -struct NSMetadataItem_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _item; - void *_reserved; -}; - - -// - (nullable instancetype)initWithURL:(NSURL *)url __attribute__((objc_designated_initializer)) __attribute__((availability(macosx,introduced=10_9))); - -// - (nullable id)valueForAttribute:(NSString *)key; -// - (nullable NSDictionary<NSString *, id> *)valuesForAttributes:(NSArray<NSString *> *)keys; - -// @property (readonly, copy) NSArray<NSString *> *attributes; - -/* @end */ - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_4))) - -#ifndef _REWRITER_typedef_NSMetadataQueryAttributeValueTuple -#define _REWRITER_typedef_NSMetadataQueryAttributeValueTuple -typedef struct objc_object NSMetadataQueryAttributeValueTuple; -typedef struct {} _objc_exc_NSMetadataQueryAttributeValueTuple; -#endif - -struct NSMetadataQueryAttributeValueTuple_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _attr; - id _value; - NSUInteger _count; - void *_reserved; -}; - - -// @property (readonly, copy) NSString *attribute; -// @property (nullable, readonly, retain) id value; -// @property (readonly) NSUInteger count; - -/* @end */ - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_4))) - -#ifndef _REWRITER_typedef_NSMetadataQueryResultGroup -#define _REWRITER_typedef_NSMetadataQueryResultGroup -typedef struct objc_object NSMetadataQueryResultGroup; -typedef struct {} _objc_exc_NSMetadataQueryResultGroup; -#endif - -struct NSMetadataQueryResultGroup_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _private[9]; - NSUInteger _private2[1]; - void *_reserved; -}; - - -// @property (readonly, copy) NSString *attribute; -// @property (readonly, retain) id value; - -// @property (nullable, readonly, copy) NSArray<NSMetadataQueryResultGroup *> *subgroups; - -// @property (readonly) NSUInteger resultCount; -// - (id)resultAtIndex:(NSUInteger)idx; - -// @property (readonly, copy) NSArray *results; - -/* @end */ - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - -#ifndef _REWRITER_typedef_NSOutputStream -#define _REWRITER_typedef_NSOutputStream -typedef struct objc_object NSOutputStream; -typedef struct {} _objc_exc_NSOutputStream; -#endif - -#ifndef _REWRITER_typedef_NSRunLoop -#define _REWRITER_typedef_NSRunLoop -typedef struct objc_object NSRunLoop; -typedef struct {} _objc_exc_NSRunLoop; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @protocol NSNetServiceDelegate, NSNetServiceBrowserDelegate; - - - - - -extern "C" NSString * const NSNetServicesErrorCode; -extern "C" NSString * const NSNetServicesErrorDomain; - -typedef NSInteger NSNetServicesError; enum { - - - - NSNetServicesUnknownError = -72000L, - - - - NSNetServicesCollisionError = -72001L, - - - - NSNetServicesNotFoundError = -72002L, - - - - NSNetServicesActivityInProgress = -72003L, - - - - NSNetServicesBadArgumentError = -72004L, - - - - NSNetServicesCancelledError = -72005L, - - - - NSNetServicesInvalidError = -72006L, - - - - NSNetServicesTimeoutError = -72007L, - -}; - - -typedef NSUInteger NSNetServiceOptions; enum { - - - - - NSNetServiceNoAutoRename = 1UL << 0, - NSNetServiceListenForConnections __attribute__((availability(macosx,introduced=10_9))) = 1UL << 1 -}; - - - - - - -#ifndef _REWRITER_typedef_NSNetService -#define _REWRITER_typedef_NSNetService -typedef struct objc_object NSNetService; -typedef struct {} _objc_exc_NSNetService; -#endif - -struct NSNetService_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _netService; - id _delegate; - id _reserved; -}; - - - - -// - (instancetype)initWithDomain:(NSString *)domain type:(NSString *)type name:(NSString *)name port:(int)port __attribute__((objc_designated_initializer)); - - - - - -// - (instancetype)initWithDomain:(NSString *)domain type:(NSString *)type name:(NSString *)name; - - - -// - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; -// - (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; - - - -// @property (nullable, assign) id <NSNetServiceDelegate> delegate; - - - -// @property BOOL includesPeerToPeer __attribute__((availability(macosx,introduced=10_10))); - - - -// @property (readonly, copy) NSString *name; - - - -// @property (readonly, copy) NSString *type; - - - -// @property (readonly, copy) NSString *domain; - - - -// @property (nullable, readonly, copy) NSString *hostName; - - - -// @property (nullable, readonly, copy) NSArray<NSData *> *addresses; - - - -// @property (readonly) NSInteger port __attribute__((availability(macosx,introduced=10_5))); - - - - - -// - (void)publish; - - - - - -// - (void)publishWithOptions:(NSNetServiceOptions)options __attribute__((availability(macosx,introduced=10_5))); - - - - -// - (void)resolve __attribute__((availability(macosx,introduced=10_2,deprecated=10_4,message="" ))); - - - -// - (void)stop; - - - -// + (NSDictionary<NSString *, NSData *> *)dictionaryFromTXTRecordData:(NSData *)txtData; - - - -// + (NSData *)dataFromTXTRecordDictionary:(NSDictionary<NSString *, NSData *> *)txtDictionary; - - - -// - (void)resolveWithTimeout:(NSTimeInterval)timeout; - - - -// - (BOOL)getInputStream:(out __attribute__((objc_ownership(strong))) NSInputStream * _Nullable * _Nullable)inputStream outputStream:(out __attribute__((objc_ownership(strong))) NSOutputStream * _Nullable * _Nullable)outputStream; - - - -// - (BOOL)setTXTRecordData:(nullable NSData *)recordData; - - - -// - (nullable NSData *)TXTRecordData; - - - -// - (void)startMonitoring; - - - -// - (void)stopMonitoring; - - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSNetServiceBrowser -#define _REWRITER_typedef_NSNetServiceBrowser -typedef struct objc_object NSNetServiceBrowser; -typedef struct {} _objc_exc_NSNetServiceBrowser; -#endif - -struct NSNetServiceBrowser_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _netServiceBrowser; - id _delegate; - void *_reserved; -}; - - -// - (instancetype)init; - - - -// @property (nullable, assign) id <NSNetServiceBrowserDelegate> delegate; - - - -// @property BOOL includesPeerToPeer __attribute__((availability(macosx,introduced=10_10))); - - - -// - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; -// - (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; - - - -// - (void)searchForBrowsableDomains; - - - -// - (void)searchForRegistrationDomains; - - - -// - (void)searchForServicesOfType:(NSString *)type inDomain:(NSString *)domainString; - - - -// - (void)stop; - -/* @end */ - - - - -// @protocol NSNetServiceDelegate <NSObject> -/* @optional */ - - - -// - (void)netServiceWillPublish:(NSNetService *)sender; - - - -// - (void)netServiceDidPublish:(NSNetService *)sender; - - - -// - (void)netService:(NSNetService *)sender didNotPublish:(NSDictionary<NSString *, NSNumber *> *)errorDict; - - - -// - (void)netServiceWillResolve:(NSNetService *)sender; - - - -// - (void)netServiceDidResolveAddress:(NSNetService *)sender; - - - -// - (void)netService:(NSNetService *)sender didNotResolve:(NSDictionary<NSString *, NSNumber *> *)errorDict; - - - -// - (void)netServiceDidStop:(NSNetService *)sender; - - - -// - (void)netService:(NSNetService *)sender didUpdateTXTRecordData:(NSData *)data; -// - (void)netService:(NSNetService *)sender didAcceptConnectionWithInputStream:(NSInputStream *)inputStream outputStream:(NSOutputStream *)outputStream __attribute__((availability(macosx,introduced=10_9))); - -/* @end */ - - - - -// @protocol NSNetServiceBrowserDelegate <NSObject> -/* @optional */ - - - -// - (void)netServiceBrowserWillSearch:(NSNetServiceBrowser *)browser; - - - -// - (void)netServiceBrowserDidStopSearch:(NSNetServiceBrowser *)browser; - - - -// - (void)netServiceBrowser:(NSNetServiceBrowser *)browser didNotSearch:(NSDictionary<NSString *, NSNumber *> *)errorDict; - - - -// - (void)netServiceBrowser:(NSNetServiceBrowser *)browser didFindDomain:(NSString *)domainString moreComing:(BOOL)moreComing; - - - -// - (void)netServiceBrowser:(NSNetServiceBrowser *)browser didFindService:(NSNetService *)service moreComing:(BOOL)moreComing; - - - -// - (void)netServiceBrowser:(NSNetServiceBrowser *)browser didRemoveDomain:(NSString *)domainString moreComing:(BOOL)moreComing; - - - -// - (void)netServiceBrowser:(NSNetServiceBrowser *)browser didRemoveService:(NSNetService *)service moreComing:(BOOL)moreComing; - -/* @end */ - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_7))) - -#ifndef _REWRITER_typedef_NSUbiquitousKeyValueStore -#define _REWRITER_typedef_NSUbiquitousKeyValueStore -typedef struct objc_object NSUbiquitousKeyValueStore; -typedef struct {} _objc_exc_NSUbiquitousKeyValueStore; -#endif - -struct NSUbiquitousKeyValueStore_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _private1; - id _private2; - id _private3; - void *_private4; - void *_reserved[3]; - int _daemonWakeToken; -}; - - -// + (NSUbiquitousKeyValueStore *)defaultStore; - -// - (nullable id)objectForKey:(NSString *)aKey; -// - (void)setObject:(nullable id)anObject forKey:(NSString *)aKey; -// - (void)removeObjectForKey:(NSString *)aKey; - -// - (nullable NSString *)stringForKey:(NSString *)aKey; -// - (nullable NSArray *)arrayForKey:(NSString *)aKey; -// - (nullable NSDictionary<NSString *, id> *)dictionaryForKey:(NSString *)aKey; -// - (nullable NSData *)dataForKey:(NSString *)aKey; -// - (long long)longLongForKey:(NSString *)aKey; -// - (double)doubleForKey:(NSString *)aKey; -// - (BOOL)boolForKey:(NSString *)aKey; - -// - (void)setString:(nullable NSString *)aString forKey:(NSString *)aKey; -// - (void)setData:(nullable NSData *)aData forKey:(NSString *)aKey; -// - (void)setArray:(nullable NSArray *)anArray forKey:(NSString *)aKey; -// - (void)setDictionary:(nullable NSDictionary<NSString *, id> *)aDictionary forKey:(NSString *)aKey; -// - (void)setLongLong:(long long)value forKey:(NSString *)aKey; -// - (void)setDouble:(double)value forKey:(NSString *)aKey; -// - (void)setBool:(BOOL)value forKey:(NSString *)aKey; - -// @property (readonly, copy) NSDictionary<NSString *, id> *dictionaryRepresentation; - -// - (BOOL)synchronize; - -/* @end */ - - -extern "C" NSString * const NSUbiquitousKeyValueStoreDidChangeExternallyNotification __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSUbiquitousKeyValueStoreChangeReasonKey __attribute__((availability(macosx,introduced=10_7))); -extern "C" NSString * const NSUbiquitousKeyValueStoreChangedKeysKey __attribute__((availability(macosx,introduced=10_7))); - -enum { - NSUbiquitousKeyValueStoreServerChange __attribute__((availability(macosx,introduced=10_7))), - NSUbiquitousKeyValueStoreInitialSyncChange __attribute__((availability(macosx,introduced=10_7))), - NSUbiquitousKeyValueStoreQuotaViolationChange __attribute__((availability(macosx,introduced=10_7))), - NSUbiquitousKeyValueStoreAccountChange __attribute__((availability(macosx,introduced=10_8))) -}; -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - -static const NSUInteger NSUndoCloseGroupingRunLoopOrdering = 350000; - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_0))) - -#ifndef _REWRITER_typedef_NSUndoManager -#define _REWRITER_typedef_NSUndoManager -typedef struct objc_object NSUndoManager; -typedef struct {} _objc_exc_NSUndoManager; -#endif - -struct NSUndoManager_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _undoStack; - id _redoStack; - NSArray *_runLoopModes; - uint64_t _NSUndoManagerPrivate1; - id _target; - id _proxy; - void *_NSUndoManagerPrivate2; - void *_NSUndoManagerPrivate3; -}; - - - - -// - (void)beginUndoGrouping; -// - (void)endUndoGrouping; - - -// @property (readonly) NSInteger groupingLevel; - - - - -// - (void)disableUndoRegistration; -// - (void)enableUndoRegistration; -// @property (readonly, getter=isUndoRegistrationEnabled) BOOL undoRegistrationEnabled; - - - -// @property BOOL groupsByEvent; - - - - - - -// @property NSUInteger levelsOfUndo; - - - - - - -// @property (copy) NSArray<NSString *> *runLoopModes; - - - -// - (void)undo; - - - -// - (void)redo; - - -// - (void)undoNestedGroup; - - - -// @property (readonly) BOOL canUndo; -// @property (readonly) BOOL canRedo; - - -// @property (readonly, getter=isUndoing) BOOL undoing; -// @property (readonly, getter=isRedoing) BOOL redoing; - - - - - -// - (void)removeAllActions; - -// - (void)removeAllActionsWithTarget:(id)target; - - - -// - (void)registerUndoWithTarget:(id)target selector:(SEL)selector object:(nullable id)anObject; - - - -// - (id)prepareWithInvocationTarget:(id)target; -// - (void)registerUndoWithTarget:(id)target handler:(void (^)(id target))undoHandler __attribute__((availability(macosx,introduced=10_11))) __attribute__((swift_private)); - -// - (void)setActionIsDiscardable:(BOOL)discardable __attribute__((availability(macosx,introduced=10_7))); - - - -extern "C" NSString * const NSUndoManagerGroupIsDiscardableKey __attribute__((availability(macosx,introduced=10_7))); - -// @property (readonly) BOOL undoActionIsDiscardable __attribute__((availability(macosx,introduced=10_7))); -// @property (readonly) BOOL redoActionIsDiscardable __attribute__((availability(macosx,introduced=10_7))); - - - - -// @property (readonly, copy) NSString *undoActionName; -// @property (readonly, copy) NSString *redoActionName; - - - -// - (void)setActionName:(NSString *)actionName; - - - - - -// @property (readonly, copy) NSString *undoMenuItemTitle; -// @property (readonly, copy) NSString *redoMenuItemTitle; - - - - - - -// - (NSString *)undoMenuTitleForUndoActionName:(NSString *)actionName; -// - (NSString *)redoMenuTitleForUndoActionName:(NSString *)actionName; - - - - -/* @end */ - - -extern "C" NSString * const NSUndoManagerCheckpointNotification __attribute__((availability(macosx,introduced=10_0))); - - - - -extern "C" NSString * const NSUndoManagerWillUndoChangeNotification __attribute__((availability(macosx,introduced=10_0))); -extern "C" NSString * const NSUndoManagerWillRedoChangeNotification __attribute__((availability(macosx,introduced=10_0))); - -extern "C" NSString * const NSUndoManagerDidUndoChangeNotification __attribute__((availability(macosx,introduced=10_0))); -extern "C" NSString * const NSUndoManagerDidRedoChangeNotification __attribute__((availability(macosx,introduced=10_0))); - -extern "C" NSString * const NSUndoManagerDidOpenUndoGroupNotification __attribute__((availability(macosx,introduced=10_0))); -extern "C" NSString * const NSUndoManagerWillCloseUndoGroupNotification __attribute__((availability(macosx,introduced=10_0))); - - -extern "C" NSString * const NSUndoManagerDidCloseUndoGroupNotification __attribute__((availability(macosx,introduced=10_7))); -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSURL; -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -// @class NSError; -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -// @class NSInputStream; -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -// @class NSOutputStream; -#ifndef _REWRITER_typedef_NSOutputStream -#define _REWRITER_typedef_NSOutputStream -typedef struct objc_object NSOutputStream; -typedef struct {} _objc_exc_NSOutputStream; -#endif - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -// @class NSOperationQueue; -#ifndef _REWRITER_typedef_NSOperationQueue -#define _REWRITER_typedef_NSOperationQueue -typedef struct objc_object NSOperationQueue; -typedef struct {} _objc_exc_NSOperationQueue; -#endif - - -// @class NSURLCache; -#ifndef _REWRITER_typedef_NSURLCache -#define _REWRITER_typedef_NSURLCache -typedef struct objc_object NSURLCache; -typedef struct {} _objc_exc_NSURLCache; -#endif - -// @class NSURLResponse; -#ifndef _REWRITER_typedef_NSURLResponse -#define _REWRITER_typedef_NSURLResponse -typedef struct objc_object NSURLResponse; -typedef struct {} _objc_exc_NSURLResponse; -#endif - -// @class NSHTTPURLResponse; -#ifndef _REWRITER_typedef_NSHTTPURLResponse -#define _REWRITER_typedef_NSHTTPURLResponse -typedef struct objc_object NSHTTPURLResponse; -typedef struct {} _objc_exc_NSHTTPURLResponse; -#endif - -// @class NSHTTPCookie; -#ifndef _REWRITER_typedef_NSHTTPCookie -#define _REWRITER_typedef_NSHTTPCookie -typedef struct objc_object NSHTTPCookie; -typedef struct {} _objc_exc_NSHTTPCookie; -#endif - -// @class NSCachedURLResponse; -#ifndef _REWRITER_typedef_NSCachedURLResponse -#define _REWRITER_typedef_NSCachedURLResponse -typedef struct objc_object NSCachedURLResponse; -typedef struct {} _objc_exc_NSCachedURLResponse; -#endif - -// @class NSURLAuthenticationChallenge; -#ifndef _REWRITER_typedef_NSURLAuthenticationChallenge -#define _REWRITER_typedef_NSURLAuthenticationChallenge -typedef struct objc_object NSURLAuthenticationChallenge; -typedef struct {} _objc_exc_NSURLAuthenticationChallenge; -#endif - -// @class NSURLProtectionSpace; -#ifndef _REWRITER_typedef_NSURLProtectionSpace -#define _REWRITER_typedef_NSURLProtectionSpace -typedef struct objc_object NSURLProtectionSpace; -typedef struct {} _objc_exc_NSURLProtectionSpace; -#endif - -// @class NSURLCredential; -#ifndef _REWRITER_typedef_NSURLCredential -#define _REWRITER_typedef_NSURLCredential -typedef struct objc_object NSURLCredential; -typedef struct {} _objc_exc_NSURLCredential; -#endif - -// @class NSURLCredentialStorage; -#ifndef _REWRITER_typedef_NSURLCredentialStorage -#define _REWRITER_typedef_NSURLCredentialStorage -typedef struct objc_object NSURLCredentialStorage; -typedef struct {} _objc_exc_NSURLCredentialStorage; -#endif - -// @class NSURLSessionDataTask; -#ifndef _REWRITER_typedef_NSURLSessionDataTask -#define _REWRITER_typedef_NSURLSessionDataTask -typedef struct objc_object NSURLSessionDataTask; -typedef struct {} _objc_exc_NSURLSessionDataTask; -#endif - -// @class NSURLSessionUploadTask; -#ifndef _REWRITER_typedef_NSURLSessionUploadTask -#define _REWRITER_typedef_NSURLSessionUploadTask -typedef struct objc_object NSURLSessionUploadTask; -typedef struct {} _objc_exc_NSURLSessionUploadTask; -#endif - -// @class NSURLSessionDownloadTask; -#ifndef _REWRITER_typedef_NSURLSessionDownloadTask -#define _REWRITER_typedef_NSURLSessionDownloadTask -typedef struct objc_object NSURLSessionDownloadTask; -typedef struct {} _objc_exc_NSURLSessionDownloadTask; -#endif - -// @class NSNetService; -#ifndef _REWRITER_typedef_NSNetService -#define _REWRITER_typedef_NSNetService -typedef struct objc_object NSNetService; -typedef struct {} _objc_exc_NSNetService; -#endif - -// @class NSURLSession; -#ifndef _REWRITER_typedef_NSURLSession -#define _REWRITER_typedef_NSURLSession -typedef struct objc_object NSURLSession; -typedef struct {} _objc_exc_NSURLSession; -#endif - -// @class NSURLSessionDataTask; -#ifndef _REWRITER_typedef_NSURLSessionDataTask -#define _REWRITER_typedef_NSURLSessionDataTask -typedef struct objc_object NSURLSessionDataTask; -typedef struct {} _objc_exc_NSURLSessionDataTask; -#endif - -// @class NSURLSessionUploadTask; -#ifndef _REWRITER_typedef_NSURLSessionUploadTask -#define _REWRITER_typedef_NSURLSessionUploadTask -typedef struct objc_object NSURLSessionUploadTask; -typedef struct {} _objc_exc_NSURLSessionUploadTask; -#endif - -// @class NSURLSessionDownloadTask; -#ifndef _REWRITER_typedef_NSURLSessionDownloadTask -#define _REWRITER_typedef_NSURLSessionDownloadTask -typedef struct objc_object NSURLSessionDownloadTask; -typedef struct {} _objc_exc_NSURLSessionDownloadTask; -#endif - -// @class NSURLSessionStreamTask; -#ifndef _REWRITER_typedef_NSURLSessionStreamTask -#define _REWRITER_typedef_NSURLSessionStreamTask -typedef struct objc_object NSURLSessionStreamTask; -typedef struct {} _objc_exc_NSURLSessionStreamTask; -#endif - -// @class NSURLSessionConfiguration; -#ifndef _REWRITER_typedef_NSURLSessionConfiguration -#define _REWRITER_typedef_NSURLSessionConfiguration -typedef struct objc_object NSURLSessionConfiguration; -typedef struct {} _objc_exc_NSURLSessionConfiguration; -#endif - -// @protocol NSURLSessionDelegate; -extern "C" const int64_t NSURLSessionTransferSizeUnknown __attribute__((availability(macosx,introduced=10_9))); - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_9))) - -#ifndef _REWRITER_typedef_NSURLSession -#define _REWRITER_typedef_NSURLSession -typedef struct objc_object NSURLSession; -typedef struct {} _objc_exc_NSURLSession; -#endif - -struct NSURLSession_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - - - - -// + (NSURLSession *)sharedSession; -// + (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration; -// + (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(nullable id <NSURLSessionDelegate>)delegate delegateQueue:(nullable NSOperationQueue *)queue; - -// @property (readonly, retain) NSOperationQueue *delegateQueue; -// @property (nullable, readonly, retain) id <NSURLSessionDelegate> delegate; -// @property (readonly, copy) NSURLSessionConfiguration *configuration; - - - - - -// @property (nullable, copy) NSString *sessionDescription; -// - (void)finishTasksAndInvalidate; - - - - - - -// - (void)invalidateAndCancel; - -// - (void)resetWithCompletionHandler:(void (^)(void))completionHandler; -// - (void)flushWithCompletionHandler:(void (^)(void))completionHandler; - -// - (void)getTasksWithCompletionHandler:(void (^)(NSArray<NSURLSessionDataTask *> *dataTasks, NSArray<NSURLSessionUploadTask *> *uploadTasks, NSArray<NSURLSessionDownloadTask *> *downloadTasks))completionHandler; - -// - (void)getAllTasksWithCompletionHandler:(void (^)(NSArray<__kindof NSURLSessionTask *> *tasks))completionHandler __attribute__((availability(macosx,introduced=10_11))); - - - - - - - -// - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request; - - -// - (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url; - - -// - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL; - - -// - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData; - - -// - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request; - - -// - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request; - - -// - (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url; - - -// - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData; - - - -// - (NSURLSessionStreamTask *)streamTaskWithHostName:(NSString *)hostname port:(NSInteger)port __attribute__((availability(macosx,introduced=10_11))); - - - - -// - (NSURLSessionStreamTask *)streamTaskWithNetService:(NSNetService *)service __attribute__((availability(macosx,introduced=10_11))); - -/* @end */ - -// @interface NSURLSession (NSURLSessionAsynchronousConvenience) -// - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler; -// - (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler; - - - - -// - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler; -// - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(nullable NSData *)bodyData completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler; - - - - - - - -// - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler; -// - (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler; -// - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler; - -/* @end */ - - -typedef NSInteger NSURLSessionTaskState; enum { - NSURLSessionTaskStateRunning = 0, - NSURLSessionTaskStateSuspended = 1, - NSURLSessionTaskStateCanceling = 2, - NSURLSessionTaskStateCompleted = 3, -} __attribute__((availability(macosx,introduced=10_9))); - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_9))) - -#ifndef _REWRITER_typedef_NSURLSessionTask -#define _REWRITER_typedef_NSURLSessionTask -typedef struct objc_object NSURLSessionTask; -typedef struct {} _objc_exc_NSURLSessionTask; -#endif - -struct NSURLSessionTask_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly) NSUInteger taskIdentifier; -// @property (nullable, readonly, copy) NSURLRequest *originalRequest; -// @property (nullable, readonly, copy) NSURLRequest *currentRequest; -// @property (nullable, readonly, copy) NSURLResponse *response; - - - - - - - -// @property (readonly) int64_t countOfBytesReceived; - - -// @property (readonly) int64_t countOfBytesSent; - - -// @property (readonly) int64_t countOfBytesExpectedToSend; - - -// @property (readonly) int64_t countOfBytesExpectedToReceive; - - - - - -// @property (nullable, copy) NSString *taskDescription; - - - - - - - -// - (void)cancel; - - - - -// @property (readonly) NSURLSessionTaskState state; - - - - - -// @property (nullable, readonly, copy) NSError *error; -// - (void)suspend; -// - (void)resume; -// @property float priority __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - -extern "C" const float NSURLSessionTaskPriorityDefault __attribute__((availability(macosx,introduced=10_10))); -extern "C" const float NSURLSessionTaskPriorityLow __attribute__((availability(macosx,introduced=10_10))); -extern "C" const float NSURLSessionTaskPriorityHigh __attribute__((availability(macosx,introduced=10_10))); - - - - - - - -#ifndef _REWRITER_typedef_NSURLSessionDataTask -#define _REWRITER_typedef_NSURLSessionDataTask -typedef struct objc_object NSURLSessionDataTask; -typedef struct {} _objc_exc_NSURLSessionDataTask; -#endif - -struct NSURLSessionDataTask_IMPL { - struct NSURLSessionTask_IMPL NSURLSessionTask_IVARS; -}; - -/* @end */ - - - - - - - - - -#ifndef _REWRITER_typedef_NSURLSessionUploadTask -#define _REWRITER_typedef_NSURLSessionUploadTask -typedef struct objc_object NSURLSessionUploadTask; -typedef struct {} _objc_exc_NSURLSessionUploadTask; -#endif - -struct NSURLSessionUploadTask_IMPL { - struct NSURLSessionDataTask_IMPL NSURLSessionDataTask_IVARS; -}; - -/* @end */ - - - - - - - -#ifndef _REWRITER_typedef_NSURLSessionDownloadTask -#define _REWRITER_typedef_NSURLSessionDownloadTask -typedef struct objc_object NSURLSessionDownloadTask; -typedef struct {} _objc_exc_NSURLSessionDownloadTask; -#endif - -struct NSURLSessionDownloadTask_IMPL { - struct NSURLSessionTask_IMPL NSURLSessionTask_IVARS; -}; - -// - (void)cancelByProducingResumeData:(void (^)(NSData * _Nullable resumeData))completionHandler; - -/* @end */ - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_11))) - -#ifndef _REWRITER_typedef_NSURLSessionStreamTask -#define _REWRITER_typedef_NSURLSessionStreamTask -typedef struct objc_object NSURLSessionStreamTask; -typedef struct {} _objc_exc_NSURLSessionStreamTask; -#endif - -struct NSURLSessionStreamTask_IMPL { - struct NSURLSessionTask_IMPL NSURLSessionTask_IVARS; -}; - - - - - - - -// - (void)readDataOfMinLength:(NSUInteger)minBytes maxLength:(NSUInteger)maxBytes timeout:(NSTimeInterval)timeout completionHandler:(void (^) (NSData * _Nullable data, BOOL atEOF, NSError * _Nullable error))completionHandler; - - - - - - -// - (void)writeData:(NSData *)data timeout:(NSTimeInterval)timeout completionHandler:(void (^) (NSError * _Nullable error))completionHandler; - - - - - - - -// - (void)captureStreams; - - - - - - - -// - (void)closeWrite; - - - - - -// - (void)closeRead; - - - - - - -// - (void)startSecureConnection; - - - - - -// - (void)stopSecureConnection; - -/* @end */ - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_9))) - -#ifndef _REWRITER_typedef_NSURLSessionConfiguration -#define _REWRITER_typedef_NSURLSessionConfiguration -typedef struct objc_object NSURLSessionConfiguration; -typedef struct {} _objc_exc_NSURLSessionConfiguration; -#endif - -struct NSURLSessionConfiguration_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// + (NSURLSessionConfiguration *)defaultSessionConfiguration; -// + (NSURLSessionConfiguration *)ephemeralSessionConfiguration; -// + (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier __attribute__((availability(macosx,introduced=10_10))); - - -// @property (nullable, readonly, copy) NSString *identifier; - - -// @property NSURLRequestCachePolicy requestCachePolicy; - - -// @property NSTimeInterval timeoutIntervalForRequest; - - -// @property NSTimeInterval timeoutIntervalForResource; - - -// @property NSURLRequestNetworkServiceType networkServiceType; - - -// @property BOOL allowsCellularAccess; - - -// @property (getter=isDiscretionary) BOOL discretionary __attribute__((availability(macosx,introduced=10_10))); - - - - - -// @property (nullable, copy) NSString *sharedContainerIdentifier __attribute__((availability(macosx,introduced=10_10))); - - - - - - -// @property BOOL sessionSendsLaunchEvents __attribute__((availability(macosx,introduced=NA))); - - -// @property (nullable, copy) NSDictionary *connectionProxyDictionary; - - -// @property SSLProtocol TLSMinimumSupportedProtocol; - - -// @property SSLProtocol TLSMaximumSupportedProtocol; - - -// @property BOOL HTTPShouldUsePipelining; - - -// @property BOOL HTTPShouldSetCookies; - - -// @property NSHTTPCookieAcceptPolicy HTTPCookieAcceptPolicy; - - - -// @property (nullable, copy) NSDictionary *HTTPAdditionalHeaders; - - -// @property NSInteger HTTPMaximumConnectionsPerHost; - - -// @property (nullable, retain) NSHTTPCookieStorage *HTTPCookieStorage; - - -// @property (nullable, retain) NSURLCredentialStorage *URLCredentialStorage; - - -// @property (nullable, retain) NSURLCache *URLCache; - - - - -// @property BOOL shouldUseExtendedBackgroundIdleMode __attribute__((availability(macosx,introduced=10_11))); -// @property (nullable, copy) NSArray<Class> *protocolClasses; - -/* @end */ - - - - - -typedef NSInteger NSURLSessionAuthChallengeDisposition; enum { - NSURLSessionAuthChallengeUseCredential = 0, - NSURLSessionAuthChallengePerformDefaultHandling = 1, - NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, - NSURLSessionAuthChallengeRejectProtectionSpace = 3, -} __attribute__((availability(macosx,introduced=10_9))); - - -typedef NSInteger NSURLSessionResponseDisposition; enum { - NSURLSessionResponseCancel = 0, - NSURLSessionResponseAllow = 1, - NSURLSessionResponseBecomeDownload = 2, - NSURLSessionResponseBecomeStream __attribute__((availability(macosx,introduced=10_11))) = 3, -} __attribute__((availability(macosx,introduced=10_9))); -// @protocol NSURLSessionDelegate <NSObject> -/* @optional */ - - - - - -// - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error; -#if 0 -- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge - completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler; -#endif - -// - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session __attribute__((availability(macosx,unavailable))); - -/* @end */ - - - - - -// @protocol NSURLSessionTaskDelegate <NSURLSessionDelegate> -/* @optional */ -#if 0 -- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task - willPerformHTTPRedirection:(NSHTTPURLResponse *)response - newRequest:(NSURLRequest *)request - completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler; -#endif - - - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task - didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge - completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler; -#endif - - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task - needNewBodyStream:(void (^)(NSInputStream * _Nullable bodyStream))completionHandler; -#endif - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task - didSendBodyData:(int64_t)bytesSent - totalBytesSent:(int64_t)totalBytesSent - totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend; -#endif - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task - didCompleteWithError:(nullable NSError *)error; -#endif - - -/* @end */ - - - - - - -// @protocol NSURLSessionDataDelegate <NSURLSessionTaskDelegate> -/* @optional */ -#if 0 -- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask - didReceiveResponse:(NSURLResponse *)response - completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler; -#endif - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask - didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask; -#endif - -#if 0 -- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask - didBecomeStreamTask:(NSURLSessionStreamTask *)streamTask; -#endif - - - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask - didReceiveData:(NSData *)data; -#endif - - - - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask - willCacheResponse:(NSCachedURLResponse *)proposedResponse - completionHandler:(void (^)(NSCachedURLResponse * _Nullable cachedResponse))completionHandler; -#endif - - -/* @end */ - - - - - - -// @protocol NSURLSessionDownloadDelegate <NSURLSessionTaskDelegate> - - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask - didFinishDownloadingToURL:(NSURL *)location; -#endif - - -/* @optional */ - -#if 0 -- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask - didWriteData:(int64_t)bytesWritten - totalBytesWritten:(int64_t)totalBytesWritten - totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite; -#endif - - - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask - didResumeAtOffset:(int64_t)fileOffset - expectedTotalBytes:(int64_t)expectedTotalBytes; -#endif - - -/* @end */ - - -// @protocol NSURLSessionStreamDelegate <NSURLSessionTaskDelegate> -/* @optional */ - - - - - - - -// - (void)URLSession:(NSURLSession *)session readClosedForStreamTask:(NSURLSessionStreamTask *)streamTask; - - - - - -// - (void)URLSession:(NSURLSession *)session writeClosedForStreamTask:(NSURLSessionStreamTask *)streamTask; -// - (void)URLSession:(NSURLSession *)session betterRouteDiscoveredForStreamTask:(NSURLSessionStreamTask *)streamTask; - - - - - - - -#if 0 -- (void)URLSession:(NSURLSession *)session streamTask:(NSURLSessionStreamTask *)streamTask - didBecomeInputStream:(NSInputStream *)inputStream - outputStream:(NSOutputStream *)outputStream; -#endif - - -/* @end */ - - - -extern "C" NSString * const NSURLSessionDownloadTaskResumeData __attribute__((availability(macosx,introduced=10_9))); - -// @interface NSURLSessionConfiguration (NSURLSessionDeprecated) -// + (NSURLSessionConfiguration *)backgroundSessionConfiguration:(NSString *)identifier __attribute__((availability(macosx,introduced=10_9,deprecated=10_10,message="" "Please use backgroundSessionConfigurationWithIdentifier: instead"))); -/* @end */ - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -#ifndef _REWRITER_typedef_NSInputStream -#define _REWRITER_typedef_NSInputStream -typedef struct objc_object NSInputStream; -typedef struct {} _objc_exc_NSInputStream; -#endif - -#ifndef _REWRITER_typedef_NSOutputStream -#define _REWRITER_typedef_NSOutputStream -typedef struct objc_object NSOutputStream; -typedef struct {} _objc_exc_NSOutputStream; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -// @protocol NSUserActivityDelegate; - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSUserActivity -#define _REWRITER_typedef_NSUserActivity -typedef struct objc_object NSUserActivity; -typedef struct {} _objc_exc_NSUserActivity; -#endif - -struct NSUserActivity_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - - -// - (instancetype)initWithActivityType:(NSString *)activityType; - - - -// - (instancetype)init; - - - -// @property (readonly, copy) NSString *activityType; - - - -// @property (nullable, copy) NSString *title; - - - -// @property (nullable, copy) NSDictionary *userInfo; - - - -// - (void)addUserInfoEntriesFromDictionary:(NSDictionary *)otherDictionary; - - -// @property (copy) NSSet<NSString *> *requiredUserInfoKeys __attribute__((availability(macosx,introduced=10_11))); - - - -// @property (assign) BOOL needsSave; - - - -// @property (nullable, copy) NSURL *webpageURL; - - -// @property (copy) NSDate *expirationDate __attribute__((availability(macosx,introduced=10_11))); - - -// @property (copy) NSSet<NSString *> *keywords __attribute__((availability(macosx,introduced=10_11))); - - - -// @property BOOL supportsContinuationStreams; - - - -// @property (nullable, weak) id<NSUserActivityDelegate> delegate; - - - -// - (void)becomeCurrent; - - -// - (void)resignCurrent __attribute__((availability(macosx,introduced=10_11))); - - - -// - (void)invalidate; - - - -// - (void)getContinuationStreamsWithCompletionHandler:(void (^)(NSInputStream * _Nullable inputStream, NSOutputStream * _Nullable outputStream, NSError * _Nullable error))completionHandler; - - -// @property (getter=isEligibleForHandoff) BOOL eligibleForHandoff __attribute__((availability(macosx,introduced=10_11))); - - -// @property (getter=isEligibleForSearch) BOOL eligibleForSearch __attribute__((availability(macosx,introduced=10_11))); - - -// @property (getter=isEligibleForPublicIndexing) BOOL eligibleForPublicIndexing __attribute__((availability(macosx,introduced=10_11))); - -/* @end */ - - - - -extern "C" NSString * const NSUserActivityTypeBrowsingWeb __attribute__((availability(macosx,introduced=10_10))); - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) -// @protocol NSUserActivityDelegate <NSObject> -/* @optional */ - - - -// - (void)userActivityWillSave:(NSUserActivity *)userActivity; - - - -// - (void)userActivityWasContinued:(NSUserActivity *)userActivity; - - - -// - (void)userActivity:(nullable NSUserActivity *)userActivity didReceiveInputStream:(NSInputStream *)inputStream outputStream:(NSOutputStream *)outputStream; - -/* @end */ - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSUUID -#define _REWRITER_typedef_NSUUID -typedef struct objc_object NSUUID; -typedef struct {} _objc_exc_NSUUID; -#endif - -struct NSUUID_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - - -// + (instancetype)UUID; - - -// - (instancetype)init __attribute__((objc_designated_initializer)); - - -// - (nullable instancetype)initWithUUIDString:(NSString *)string; - - -// - (instancetype)initWithUUIDBytes:(const uuid_t)bytes; - - -// - (void)getUUIDBytes:(uuid_t)uuid; - - -// @property (readonly, copy) NSString *UUIDString; - -/* @end */ - - - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSMutableData -#define _REWRITER_typedef_NSMutableData -typedef struct objc_object NSMutableData; -typedef struct {} _objc_exc_NSMutableData; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSMutableArray -#define _REWRITER_typedef_NSMutableArray -typedef struct objc_object NSMutableArray; -typedef struct {} _objc_exc_NSMutableArray; -#endif - - - - - - - -#ifndef _REWRITER_typedef_NSArchiver -#define _REWRITER_typedef_NSArchiver -typedef struct objc_object NSArchiver; -typedef struct {} _objc_exc_NSArchiver; -#endif - -struct NSArchiver_IMPL { - struct NSCoder_IMPL NSCoder_IVARS; - void *mdata; - void *pointerTable; - void *stringTable; - void *ids; - void *map; - void *replacementTable; - void *reserved; -}; - - -// - (instancetype)initForWritingWithMutableData:(NSMutableData *)mdata __attribute__((objc_designated_initializer)); - -// @property (readonly, retain) NSMutableData *archiverData; - -// - (void)encodeRootObject:(id)rootObject; -// - (void)encodeConditionalObject:(nullable id)object; - -// + (NSData *)archivedDataWithRootObject:(id)rootObject; - -// + (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path; - -// - (void)encodeClassName:(NSString *)trueName intoClassName:(NSString *)inArchiveName; -// - (nullable NSString *)classNameEncodedForTrueClassName:(NSString *)trueName; - -// - (void)replaceObject:(id)object withObject:(id)newObject; - -/* @end */ - - - - - -#ifndef _REWRITER_typedef_NSUnarchiver -#define _REWRITER_typedef_NSUnarchiver -typedef struct objc_object NSUnarchiver; -typedef struct {} _objc_exc_NSUnarchiver; -#endif - -struct NSUnarchiver_IMPL { - struct NSCoder_IMPL NSCoder_IVARS; - void *datax; - NSUInteger cursor; - NSZone *objectZone; - NSUInteger systemVersion; - signed char streamerVersion; - char swap; - char unused1; - char unused2; - void *pointerTable; - void *stringTable; - id classVersions; - NSInteger lastLabel; - void *map; - void *allUnarchivedObjects; - id reserved; -}; - - -// - (nullable instancetype)initForReadingWithData:(NSData *)data __attribute__((objc_designated_initializer)); - -// - (void)setObjectZone:(nullable NSZone *)zone ; -// - (nullable NSZone *)objectZone ; - -// @property (getter=isAtEnd, readonly) BOOL atEnd; - -// @property (readonly) unsigned int systemVersion; - -// + (nullable id)unarchiveObjectWithData:(NSData *)data; -// + (nullable id)unarchiveObjectWithFile:(NSString *)path; - -// + (void)decodeClassName:(NSString *)inArchiveName asClassName:(NSString *)trueName; - -// - (void)decodeClassName:(NSString *)inArchiveName asClassName:(NSString *)trueName; - -// + (NSString *)classNameDecodedForArchiveClassName:(NSString *)inArchiveName; -// - (NSString *)classNameDecodedForArchiveClassName:(NSString *)inArchiveName; - -// - (void)replaceObject:(id)object withObject:(id)newObject; - -/* @end */ - - - - -extern "C" NSString * const NSInconsistentArchiveException; - - - -// @interface NSObject (NSArchiverCallback) - -// @property (nullable, readonly) Class classForArchiver; -// - (nullable id)replacementObjectForArchiver:(NSArchiver *)archiver; - -/* @end */ - -typedef NSInteger NSBackgroundActivityResult; enum { - - NSBackgroundActivityResultFinished = 1, - - - NSBackgroundActivityResultDeferred = 2, -} __attribute__((availability(macosx,introduced=10_10))); - -typedef void (*NSBackgroundActivityCompletionHandler)(NSBackgroundActivityResult result); - - - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSBackgroundActivityScheduler -#define _REWRITER_typedef_NSBackgroundActivityScheduler -typedef struct objc_object NSBackgroundActivityScheduler; -typedef struct {} _objc_exc_NSBackgroundActivityScheduler; -#endif - -struct NSBackgroundActivityScheduler_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _private1; - id _private2; - id _private3; - int64_t _flags; -}; - - - - - - -// - (instancetype)initWithIdentifier:(NSString *)identifier __attribute__((objc_designated_initializer)); - - - -// @property (readonly, copy) NSString *identifier; - - - -// @property NSQualityOfService qualityOfService; - - - - -// @property BOOL repeats; - - - - -// @property NSTimeInterval interval; - - - - - - - -// @property NSTimeInterval tolerance; -// - (void)scheduleWithBlock:(void (^)(NSBackgroundActivityCompletionHandler completionHandler))block; - - - -// - (void)invalidate; - - - - - -// @property (readonly) BOOL shouldDefer; - -/* @end */ - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSTimeZone -#define _REWRITER_typedef_NSTimeZone -typedef struct objc_object NSTimeZone; -typedef struct {} _objc_exc_NSTimeZone; -#endif - -__attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" "Use NSCalendar and NSDateComponents and NSDateFormatter instead"))) -__attribute__((availability(swift, unavailable, message="Use NSCalendar and NSDateComponents and NSDateFormatter instead"))) - -#ifndef _REWRITER_typedef_NSCalendarDate -#define _REWRITER_typedef_NSCalendarDate -typedef struct objc_object NSCalendarDate; -typedef struct {} _objc_exc_NSCalendarDate; -#endif - -struct NSCalendarDate_IMPL { - struct NSDate_IMPL NSDate_IVARS; - NSUInteger refCount; - NSTimeInterval _timeIntervalSinceReferenceDate; - NSTimeZone *_timeZone; - NSString *_formatString; - void *_reserved; -}; - - - - - - - -// + (id)calendarDate __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// + (nullable id)dateWithString:(NSString *)description calendarFormat:(NSString *)format locale:(nullable id)locale __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// + (nullable id)dateWithString:(NSString *)description calendarFormat:(NSString *)format __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// + (id)dateWithYear:(NSInteger)year month:(NSUInteger)month day:(NSUInteger)day hour:(NSUInteger)hour minute:(NSUInteger)minute second:(NSUInteger)second timeZone:(nullable NSTimeZone *)aTimeZone __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSCalendarDate *)dateByAddingYears:(NSInteger)year months:(NSInteger)month days:(NSInteger)day hours:(NSInteger)hour minutes:(NSInteger)minute seconds:(NSInteger)second __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSInteger)dayOfCommonEra __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSInteger)dayOfMonth __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSInteger)dayOfWeek __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSInteger)dayOfYear __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSInteger)hourOfDay __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSInteger)minuteOfHour __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSInteger)monthOfYear __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSInteger)secondOfMinute __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSInteger)yearOfCommonEra __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSString *)calendarFormat __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSString *)descriptionWithCalendarFormat:(NSString *)format locale:(nullable id)locale __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSString *)descriptionWithCalendarFormat:(NSString *)format __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSString *)descriptionWithLocale:(nullable id)locale __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSTimeZone *)timeZone __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (nullable id)initWithString:(NSString *)description calendarFormat:(NSString *)format locale:(nullable id)locale __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (nullable id)initWithString:(NSString *)description calendarFormat:(NSString *)format __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (nullable id)initWithString:(NSString *)description __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (id)initWithYear:(NSInteger)year month:(NSUInteger)month day:(NSUInteger)day hour:(NSUInteger)hour minute:(NSUInteger)minute second:(NSUInteger)second timeZone:(nullable NSTimeZone *)aTimeZone __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (void)setCalendarFormat:(nullable NSString *)format __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (void)setTimeZone:(nullable NSTimeZone *)aTimeZone __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (void)years:(nullable NSInteger *)yp months:(nullable NSInteger *)mop days:(nullable NSInteger *)dp hours:(nullable NSInteger *)hp minutes:(nullable NSInteger *)mip seconds:(nullable NSInteger *)sp sinceDate:(NSCalendarDate *)date __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// + (instancetype)distantFuture __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// + (instancetype)distantPast __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -/* @end */ - - -// @interface NSDate (NSCalendarDateExtras) - - - - - -// + (nullable id)dateWithNaturalLanguageString:(NSString *)string locale:(nullable id)locale __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// + (nullable id)dateWithNaturalLanguageString:(NSString *)string __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// + (id)dateWithString:(NSString *)aString __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (NSCalendarDate *)dateWithCalendarFormat:(nullable NSString *)format timeZone:(nullable NSTimeZone *)aTimeZone __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (nullable NSString *)descriptionWithCalendarFormat:(nullable NSString *)format timeZone:(nullable NSTimeZone *)aTimeZone locale:(nullable id)locale __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -// - (nullable id)initWithString:(NSString *)description __attribute__((availability(macosx,introduced=10_4,deprecated=10_10,message="" ))); -/* @end */ - - - - - - - - -// @class NSMutableData; -#ifndef _REWRITER_typedef_NSMutableData -#define _REWRITER_typedef_NSMutableData -typedef struct objc_object NSMutableData; -typedef struct {} _objc_exc_NSMutableData; -#endif - -#ifndef _REWRITER_typedef_NSDistantObject -#define _REWRITER_typedef_NSDistantObject -typedef struct objc_object NSDistantObject; -typedef struct {} _objc_exc_NSDistantObject; -#endif - -#ifndef _REWRITER_typedef_NSException -#define _REWRITER_typedef_NSException -typedef struct objc_object NSException; -typedef struct {} _objc_exc_NSException; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - -// @class NSPort; -#ifndef _REWRITER_typedef_NSPort -#define _REWRITER_typedef_NSPort -typedef struct objc_object NSPort; -typedef struct {} _objc_exc_NSPort; -#endif - -#ifndef _REWRITER_typedef_NSRunLoop -#define _REWRITER_typedef_NSRunLoop -typedef struct objc_object NSRunLoop; -typedef struct {} _objc_exc_NSRunLoop; -#endif - -#ifndef _REWRITER_typedef_NSPortNameServer -#define _REWRITER_typedef_NSPortNameServer -typedef struct objc_object NSPortNameServer; -typedef struct {} _objc_exc_NSPortNameServer; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSDistantObjectRequest; -#ifndef _REWRITER_typedef_NSDistantObjectRequest -#define _REWRITER_typedef_NSDistantObjectRequest -typedef struct objc_object NSDistantObjectRequest; -typedef struct {} _objc_exc_NSDistantObjectRequest; -#endif - -// @protocol NSConnectionDelegate; - -__attribute__((objc_arc_weak_reference_unavailable)) - - -__attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))) - -#ifndef _REWRITER_typedef_NSConnection -#define _REWRITER_typedef_NSConnection -typedef struct objc_object NSConnection; -typedef struct {} _objc_exc_NSConnection; -#endif - - struct NSConnection__T_1 { - unsigned char authGen : 1; - unsigned char authCheck : 1; - unsigned char _reserved1 : 1; - unsigned char _reserved2 : 1; - unsigned char doRequest : 1; - unsigned char isQueueing : 1; - unsigned char isMulti : 1; - unsigned char invalidateRP : 1; - } ; -struct NSConnection_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id receivePort; - id sendPort; - id delegate; - int32_t busy; - int32_t localProxyCount; - int32_t waitCount; - id delayedRL; - id statistics; - unsigned char isDead; - unsigned char isValid; - unsigned char wantsInvalid; - struct NSConnection__T_1 NSConnection__GRBF_1; - id ___1; - id ___2; - id runLoops; - id requestModes; - id rootObject; - void *registerInfo; - id replMode; - id classInfoImported; - id releasedProxies; - id reserved; -}; - - -// @property (readonly, copy) NSDictionary<NSString *, NSNumber *> *statistics; - -// + (NSArray<NSConnection *> *)allConnections; - -// + (NSConnection *)defaultConnection __attribute__((availability(macosx,introduced=10_0,deprecated=10_6,message="" ))); - -// + (nullable instancetype)connectionWithRegisteredName:(NSString *)name host:(nullable NSString *)hostName; -// + (nullable instancetype)connectionWithRegisteredName:(NSString *)name host:(nullable NSString *)hostName usingNameServer:(NSPortNameServer *)server; -// + (nullable NSDistantObject *)rootProxyForConnectionWithRegisteredName:(NSString *)name host:(nullable NSString *)hostName; -// + (nullable NSDistantObject *)rootProxyForConnectionWithRegisteredName:(NSString *)name host:(nullable NSString *)hostName usingNameServer:(NSPortNameServer *)server; - -// + (nullable instancetype)serviceConnectionWithName:(NSString *)name rootObject:(id)root usingNameServer:(NSPortNameServer *)server __attribute__((availability(macosx,introduced=10_5))); -// + (nullable instancetype)serviceConnectionWithName:(NSString *)name rootObject:(id)root __attribute__((availability(macosx,introduced=10_5))); - -// @property NSTimeInterval requestTimeout; -// @property NSTimeInterval replyTimeout; -// @property (nullable, retain) id rootObject; -// @property (nullable, assign) id<NSConnectionDelegate> delegate; -// @property BOOL independentConversationQueueing; -// @property (readonly, getter=isValid) BOOL valid; - -// @property (readonly, retain) NSDistantObject *rootProxy; - -// - (void)invalidate; - -// - (void)addRequestMode:(NSString *)rmode; -// - (void)removeRequestMode:(NSString *)rmode; -// @property (readonly, copy) NSArray<NSString *> *requestModes; - -// - (BOOL)registerName:(nullable NSString *) name; -// - (BOOL)registerName:(nullable NSString *) name withNameServer:(NSPortNameServer *)server; - -// + (nullable instancetype)connectionWithReceivePort:(nullable NSPort *)receivePort sendPort:(nullable NSPort *)sendPort; - -// + (nullable id)currentConversation; - -// - (nullable instancetype)initWithReceivePort:(nullable NSPort *)receivePort sendPort:(nullable NSPort *)sendPort; - -// @property (readonly, retain) NSPort *sendPort; -// @property (readonly, retain) NSPort *receivePort; - -// - (void)enableMultipleThreads; -// @property (readonly) BOOL multipleThreadsEnabled; - -// - (void)addRunLoop:(NSRunLoop *)runloop; -// - (void)removeRunLoop:(NSRunLoop *)runloop; - -// - (void)runInNewThread; - -// @property (readonly, copy) NSArray *remoteObjects; -// @property (readonly, copy) NSArray *localObjects; - - -// - (void)dispatchWithComponents:(NSArray *)components __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - -extern "C" NSString * const NSConnectionReplyMode __attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))); - -extern "C" NSString * const NSConnectionDidDieNotification __attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))); - - -__attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))) -// @protocol NSConnectionDelegate <NSObject> -/* @optional */ - - - -// - (BOOL)makeNewConnection:(NSConnection *)conn sender:(NSConnection *)ancestor; - - - -// - (BOOL)connection:(NSConnection *)ancestor shouldMakeNewConnection:(NSConnection *)conn; - -// - (NSData *)authenticationDataForComponents:(NSArray *)components; -// - (BOOL)authenticateComponents:(NSArray *)components withData:(NSData *)signature; - -// - (id)createConversationForConnection:(NSConnection *)conn; - -// - (BOOL)connection:(NSConnection *)connection handleRequest:(NSDistantObjectRequest *)doreq; - -/* @end */ - - -extern "C" NSString * const NSFailedAuthenticationException __attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))); - -extern "C" NSString * const NSConnectionDidInitializeNotification __attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))); - -__attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))) - -#ifndef _REWRITER_typedef_NSDistantObjectRequest -#define _REWRITER_typedef_NSDistantObjectRequest -typedef struct objc_object NSDistantObjectRequest; -typedef struct {} _objc_exc_NSDistantObjectRequest; -#endif - -struct NSDistantObjectRequest_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// @property (readonly, retain) NSInvocation *invocation; -// @property (readonly, retain) NSConnection *connection; -// @property (readonly, retain) id conversation; -// - (void)replyWithException:(nullable NSException *)exception; - -/* @end */ - - - - - - - -// @class Protocol; -#ifndef _REWRITER_typedef_Protocol -#define _REWRITER_typedef_Protocol -typedef struct objc_object Protocol; -typedef struct {} _objc_exc_Protocol; -#endif - -#ifndef _REWRITER_typedef_NSConnection -#define _REWRITER_typedef_NSConnection -typedef struct objc_object NSConnection; -typedef struct {} _objc_exc_NSConnection; -#endif - -#ifndef _REWRITER_typedef_NSCoder -#define _REWRITER_typedef_NSCoder -typedef struct objc_object NSCoder; -typedef struct {} _objc_exc_NSCoder; -#endif - - - - -__attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))) - -#ifndef _REWRITER_typedef_NSDistantObject -#define _REWRITER_typedef_NSDistantObject -typedef struct objc_object NSDistantObject; -typedef struct {} _objc_exc_NSDistantObject; -#endif - -struct NSDistantObject_IMPL { - struct NSProxy_IMPL NSProxy_IVARS; - id _knownSelectors; - NSUInteger _wireCount; - NSUInteger _refCount; - id _proto; - uint16_t ___2; - uint8_t ___1; - uint8_t _wireType; - id _remoteClass; -}; - - - - -// + (nullable id)proxyWithTarget:(id)target connection:(NSConnection *)connection; -// - (nullable instancetype)initWithTarget:(id)target connection:(NSConnection *)connection; - -// + (id)proxyWithLocal:(id)target connection:(NSConnection *)connection; -// - (instancetype)initWithLocal:(id)target connection:(NSConnection *)connection; - -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); - -// - (void)setProtocolForProxy:(nullable Protocol *)proto; - -// @property (readonly, retain) NSConnection *connectionForProxy; - -/* @end */ - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - - - - -extern "C" NSString * const NSLocalNotificationCenterType; - - -typedef NSUInteger NSNotificationSuspensionBehavior; enum { - NSNotificationSuspensionBehaviorDrop = 1, - - NSNotificationSuspensionBehaviorCoalesce = 2, - - NSNotificationSuspensionBehaviorHold = 3, - - NSNotificationSuspensionBehaviorDeliverImmediately = 4 - - - -}; - -typedef NSUInteger NSDistributedNotificationOptions; enum { - NSDistributedNotificationDeliverImmediately = (1UL << 0), - NSDistributedNotificationPostToAllSessions = (1UL << 1) -}; -static const NSDistributedNotificationOptions NSNotificationDeliverImmediately = NSDistributedNotificationDeliverImmediately; -static const NSDistributedNotificationOptions NSNotificationPostToAllSessions = NSDistributedNotificationPostToAllSessions; - - -#ifndef _REWRITER_typedef_NSDistributedNotificationCenter -#define _REWRITER_typedef_NSDistributedNotificationCenter -typedef struct objc_object NSDistributedNotificationCenter; -typedef struct {} _objc_exc_NSDistributedNotificationCenter; -#endif - -struct NSDistributedNotificationCenter_IMPL { - struct NSNotificationCenter_IMPL NSNotificationCenter_IVARS; -}; - - -// + (NSDistributedNotificationCenter *)notificationCenterForType:(NSString *)notificationCenterType; - - -// + (NSDistributedNotificationCenter *)defaultCenter; - - -// - (void)addObserver:(id)observer selector:(SEL)selector name:(nullable NSString *)name object:(nullable NSString *)object suspensionBehavior:(NSNotificationSuspensionBehavior)suspensionBehavior; - - -// - (void)postNotificationName:(NSString *)name object:(nullable NSString *)object userInfo:(nullable NSDictionary *)userInfo deliverImmediately:(BOOL)deliverImmediately; - - - -// - (void)postNotificationName:(NSString *)name object:(nullable NSString *)object userInfo:(nullable NSDictionary *)userInfo options:(NSDistributedNotificationOptions)options; - - - - - -// @property BOOL suspended; - - -// - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable NSString *)anObject; - -// - (void)postNotificationName:(NSString *)aName object:(nullable NSString *)anObject; -// - (void)postNotificationName:(NSString *)aName object:(nullable NSString *)anObject userInfo:(nullable NSDictionary *)aUserInfo; -// - (void)removeObserver:(id)observer name:(nullable NSString *)aName object:(nullable NSString *)anObject; - -/* @end */ - - - - - - - - -// @class NSConnection; -#ifndef _REWRITER_typedef_NSConnection -#define _REWRITER_typedef_NSConnection -typedef struct objc_object NSConnection; -typedef struct {} _objc_exc_NSConnection; -#endif - -#ifndef _REWRITER_typedef_NSPort -#define _REWRITER_typedef_NSPort -typedef struct objc_object NSPort; -typedef struct {} _objc_exc_NSPort; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - - - - -__attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))) - -#ifndef _REWRITER_typedef_NSPortCoder -#define _REWRITER_typedef_NSPortCoder -typedef struct objc_object NSPortCoder; -typedef struct {} _objc_exc_NSPortCoder; -#endif - -struct NSPortCoder_IMPL { - struct NSCoder_IMPL NSCoder_IVARS; -}; - - -// - (BOOL)isBycopy; -// - (BOOL)isByref; -// - (void)encodePortObject:(NSPort *)aport; -// - (nullable NSPort *)decodePortObject; - - -// - (nullable NSConnection *)connection __attribute__((availability(macosx,introduced=10_0,deprecated=10_7,message="" ))); -// + (id) portCoderWithReceivePort:(nullable NSPort *)rcvPort sendPort:(nullable NSPort *)sndPort components:(nullable NSArray *)comps __attribute__((availability(macosx,introduced=10_0,deprecated=10_7,message="" ))); -// - (id)initWithReceivePort:(nullable NSPort *)rcvPort sendPort:(nullable NSPort *)sndPort components:(nullable NSArray *)comps __attribute__((availability(macosx,introduced=10_0,deprecated=10_7,message="" ))); -// - (void)dispatch __attribute__((availability(macosx,introduced=10_0,deprecated=10_7,message="" ))); - -/* @end */ - - -// @interface NSObject (NSDistributedObjects) - -// @property (readonly) Class classForPortCoder __attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))); - -// - (nullable id)replacementObjectForPortCoder:(NSPortCoder *)coder __attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))); - -/* @end */ - - - - - - - -// @class NSPort; -#ifndef _REWRITER_typedef_NSPort -#define _REWRITER_typedef_NSPort -typedef struct objc_object NSPort; -typedef struct {} _objc_exc_NSPort; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSMutableArray -#define _REWRITER_typedef_NSMutableArray -typedef struct objc_object NSMutableArray; -typedef struct {} _objc_exc_NSMutableArray; -#endif - - - - - -#ifndef _REWRITER_typedef_NSPortMessage -#define _REWRITER_typedef_NSPortMessage -typedef struct objc_object NSPortMessage; -typedef struct {} _objc_exc_NSPortMessage; -#endif - -struct NSPortMessage_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSPort *localPort; - NSPort *remotePort; - NSMutableArray *components; - uint32_t msgid; - void *reserved2; - void *reserved; -}; - - -// - (instancetype)initWithSendPort:(nullable NSPort *)sendPort receivePort:(nullable NSPort *)replyPort components:(nullable NSArray *)components __attribute__((objc_designated_initializer)); - -// @property (nullable, readonly, copy) NSArray *components; -// @property (nullable, readonly, retain) NSPort *receivePort; -// @property (nullable, readonly, retain) NSPort *sendPort; -// - (BOOL)sendBeforeDate:(NSDate *)date; - -// @property uint32_t msgid; - -/* @end */ - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSPort -#define _REWRITER_typedef_NSPort -typedef struct objc_object NSPort; -typedef struct {} _objc_exc_NSPort; -#endif - - - - -__attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))) - -#ifndef _REWRITER_typedef_NSPortNameServer -#define _REWRITER_typedef_NSPortNameServer -typedef struct objc_object NSPortNameServer; -typedef struct {} _objc_exc_NSPortNameServer; -#endif - -struct NSPortNameServer_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// + (NSPortNameServer *)systemDefaultPortNameServer; - -// - (nullable NSPort *)portForName:(NSString *)name; -// - (nullable NSPort *)portForName:(NSString *)name host:(nullable NSString *)host; - -// - (BOOL)registerPort:(NSPort *)port name:(NSString *)name; - -// - (BOOL)removePortForName:(NSString *)name; - -/* @end */ - - - - -__attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))) - -#ifndef _REWRITER_typedef_NSMachBootstrapServer -#define _REWRITER_typedef_NSMachBootstrapServer -typedef struct objc_object NSMachBootstrapServer; -typedef struct {} _objc_exc_NSMachBootstrapServer; -#endif - -struct NSMachBootstrapServer_IMPL { - struct NSPortNameServer_IMPL NSPortNameServer_IVARS; -}; - - - - -// + (id)sharedInstance; - -// - (nullable NSPort *)portForName:(NSString *)name; -// - (nullable NSPort *)portForName:(NSString *)name host:(nullable NSString *)host; - - - -// - (BOOL)registerPort:(NSPort *)port name:(NSString *)name; - - - - - - -// - (nullable NSPort *)servicePortWithName:(NSString *)name __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - - - -__attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))) - -#ifndef _REWRITER_typedef_NSMessagePortNameServer -#define _REWRITER_typedef_NSMessagePortNameServer -typedef struct objc_object NSMessagePortNameServer; -typedef struct {} _objc_exc_NSMessagePortNameServer; -#endif - -struct NSMessagePortNameServer_IMPL { - struct NSPortNameServer_IMPL NSPortNameServer_IVARS; -}; - - - - -// + (id)sharedInstance; - -// - (nullable NSPort *)portForName:(NSString *)name; -// - (nullable NSPort *)portForName:(NSString *)name host:(nullable NSString *)host; -/* @end */ - - - - -__attribute__((availability(swift, unavailable, message="Use NSXPCConnection instead"))) - -#ifndef _REWRITER_typedef_NSSocketPortNameServer -#define _REWRITER_typedef_NSSocketPortNameServer -typedef struct objc_object NSSocketPortNameServer; -typedef struct {} _objc_exc_NSSocketPortNameServer; -#endif - -struct NSSocketPortNameServer_IMPL { - struct NSPortNameServer_IMPL NSPortNameServer_IVARS; -}; - - - - -// + (id)sharedInstance; - -// - (nullable NSPort *)portForName:(NSString *)name; -// - (nullable NSPort *)portForName:(NSString *)name host:(nullable NSString *)host; - -// - (BOOL)registerPort:(NSPort *)port name:(NSString *)name; - -// - (BOOL)removePortForName:(NSString *)name; - - - -// - (nullable NSPort *)portForName:(NSString *)name host:(nullable NSString *)host nameServerPortNumber:(uint16_t)portNumber; -// - (BOOL)registerPort:(NSPort *)port name:(NSString *)name nameServerPortNumber:(uint16_t)portNumber; -// @property uint16_t defaultNameServerPortNumber; - -/* @end */ - - -#ifndef _REWRITER_typedef_NSProtocolChecker -#define _REWRITER_typedef_NSProtocolChecker -typedef struct objc_object NSProtocolChecker; -typedef struct {} _objc_exc_NSProtocolChecker; -#endif - -struct NSProtocolChecker_IMPL { - struct NSProxy_IMPL NSProxy_IVARS; -}; - - -// @property (readonly) Protocol *protocol; -// @property (nullable, readonly, retain) NSObject *target; - -/* @end */ - - -// @interface NSProtocolChecker (NSProtocolCheckerCreation) - -// + (instancetype)protocolCheckerWithTarget:(NSObject *)anObject protocol:(Protocol *)aProtocol; -// - (instancetype)initWithTarget:(NSObject *)anObject protocol:(Protocol *)aProtocol; - -/* @end */ - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -typedef NSInteger NSTaskTerminationReason; enum { - NSTaskTerminationReasonExit = 1, - NSTaskTerminationReasonUncaughtSignal = 2 -} __attribute__((availability(macosx,introduced=10_6))); - - -#ifndef _REWRITER_typedef_NSTask -#define _REWRITER_typedef_NSTask -typedef struct objc_object NSTask; -typedef struct {} _objc_exc_NSTask; -#endif - -struct NSTask_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - -// - (instancetype)init __attribute__((objc_designated_initializer)); - - -// @property (nullable, copy) NSString *launchPath; -// @property (nullable, copy) NSArray<NSString *> *arguments; -// @property (nullable, copy) NSDictionary<NSString *, NSString *> *environment; -// @property (copy) NSString *currentDirectoryPath; - - -// @property (nullable, retain) id standardInput; -// @property (nullable, retain) id standardOutput; -// @property (nullable, retain) id standardError; - - -// - (void)launch; - -// - (void)interrupt; -// - (void)terminate; - -// - (BOOL)suspend; -// - (BOOL)resume; - - -// @property (readonly) int processIdentifier; -// @property (readonly, getter=isRunning) BOOL running; - -// @property (readonly) int terminationStatus; -// @property (readonly) NSTaskTerminationReason terminationReason __attribute__((availability(macosx,introduced=10_6))); - - - - -// @property (nullable, copy) void (^terminationHandler)(NSTask *) __attribute__((availability(macosx,introduced=10_7))); - -// @property NSQualityOfService qualityOfService __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - -// @interface NSTask (NSTaskConveniences) - -// + (NSTask *)launchedTaskWithLaunchPath:(NSString *)path arguments:(NSArray<NSString *> *)arguments; - - -// - (void)waitUntilExit; - - -/* @end */ - - -extern "C" NSString * const NSTaskDidTerminateNotification; - - - - - - - - - -enum { - NSXMLNodeOptionsNone = 0, - - - NSXMLNodeIsCDATA = 1UL << 0, - NSXMLNodeExpandEmptyElement = 1UL << 1, - NSXMLNodeCompactEmptyElement = 1UL << 2, - NSXMLNodeUseSingleQuotes = 1UL << 3, - NSXMLNodeUseDoubleQuotes = 1UL << 4, - NSXMLNodeNeverEscapeContents = 1UL << 5, - - - NSXMLDocumentTidyHTML = 1UL << 9, - NSXMLDocumentTidyXML = 1UL << 10, - - - NSXMLDocumentValidate = 1UL << 13, - - - - NSXMLNodeLoadExternalEntitiesAlways = 1UL << 14, - NSXMLNodeLoadExternalEntitiesSameOriginOnly = 1UL << 15, - NSXMLNodeLoadExternalEntitiesNever = 1UL << 19, - - - NSXMLDocumentXInclude = 1UL << 16, - - - NSXMLNodePrettyPrint = 1UL << 17, - NSXMLDocumentIncludeContentTypeDeclaration = 1UL << 18, - - - NSXMLNodePreserveNamespaceOrder = 1UL << 20, - NSXMLNodePreserveAttributeOrder = 1UL << 21, - NSXMLNodePreserveEntities = 1UL << 22, - NSXMLNodePreservePrefixes = 1UL << 23, - NSXMLNodePreserveCDATA = 1UL << 24, - NSXMLNodePreserveWhitespace = 1UL << 25, - NSXMLNodePreserveDTD = 1UL << 26, - NSXMLNodePreserveCharacterReferences = 1UL << 27, - NSXMLNodePromoteSignificantWhitespace = 1UL << 28, - NSXMLNodePreserveEmptyElements = - (NSXMLNodeExpandEmptyElement | NSXMLNodeCompactEmptyElement), - NSXMLNodePreserveQuotes = - (NSXMLNodeUseSingleQuotes | NSXMLNodeUseDoubleQuotes), - NSXMLNodePreserveAll = ( - NSXMLNodePreserveNamespaceOrder | - NSXMLNodePreserveAttributeOrder | - NSXMLNodePreserveEntities | - NSXMLNodePreservePrefixes | - NSXMLNodePreserveCDATA | - NSXMLNodePreserveEmptyElements | - NSXMLNodePreserveQuotes | - NSXMLNodePreserveWhitespace | - NSXMLNodePreserveDTD | - NSXMLNodePreserveCharacterReferences | - 0xFFF00000) -}; - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -// @class NSXMLElement; -#ifndef _REWRITER_typedef_NSXMLElement -#define _REWRITER_typedef_NSXMLElement -typedef struct objc_object NSXMLElement; -typedef struct {} _objc_exc_NSXMLElement; -#endif - -#ifndef _REWRITER_typedef_NSXMLDocument -#define _REWRITER_typedef_NSXMLDocument -typedef struct objc_object NSXMLDocument; -typedef struct {} _objc_exc_NSXMLDocument; -#endif - - - - - - - -typedef NSUInteger NSXMLNodeKind; enum { - NSXMLInvalidKind = 0, - NSXMLDocumentKind, - NSXMLElementKind, - NSXMLAttributeKind, - NSXMLNamespaceKind, - NSXMLProcessingInstructionKind, - NSXMLCommentKind, - NSXMLTextKind, - NSXMLDTDKind __attribute__((swift_name("DTDKind"))), - NSXMLEntityDeclarationKind, - NSXMLAttributeDeclarationKind, - NSXMLElementDeclarationKind, - NSXMLNotationDeclarationKind -}; - -#ifndef _REWRITER_typedef_NSXMLNode -#define _REWRITER_typedef_NSXMLNode -typedef struct objc_object NSXMLNode; -typedef struct {} _objc_exc_NSXMLNode; -#endif - - struct NSXMLNode__T_1 { - NSXMLNodeKind _kind : 4; - uint32_t _index : 28; - } ; -struct NSXMLNode_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSXMLNode *_parent; - id _objectValue; - struct NSXMLNode__T_1 NSXMLNode__GRBF_1; - int32_t _private; -}; - - -// - (instancetype)init __attribute__((objc_designated_initializer)); - - - - - -// - (instancetype)initWithKind:(NSXMLNodeKind)kind; - - - - - -// - (instancetype)initWithKind:(NSXMLNodeKind)kind options:(NSUInteger)options __attribute__((objc_designated_initializer)); - - - - - -// + (id)document; - - - - - - -// + (id)documentWithRootElement:(NSXMLElement *)element; - - - - - -// + (id)elementWithName:(NSString *)name; - - - - - -// + (id)elementWithName:(NSString *)name URI:(NSString *)URI; - - - - - -// + (id)elementWithName:(NSString *)name stringValue:(NSString *)string; - - - - - -// + (id)elementWithName:(NSString *)name children:(nullable NSArray<NSXMLNode *> *)children attributes:(nullable NSArray<NSXMLNode *> *)attributes; - - - - - -// + (id)attributeWithName:(NSString *)name stringValue:(NSString *)stringValue; - - - - - -// + (id)attributeWithName:(NSString *)name URI:(NSString *)URI stringValue:(NSString *)stringValue; - - - - - -// + (id)namespaceWithName:(NSString *)name stringValue:(NSString *)stringValue; - - - - - -// + (id)processingInstructionWithName:(NSString *)name stringValue:(NSString *)stringValue; - - - - - -// + (id)commentWithStringValue:(NSString *)stringValue; - - - - - -// + (id)textWithStringValue:(NSString *)stringValue; - - - - - -// + (nullable id)DTDNodeWithXMLString:(NSString *)string; -// @property (readonly) NSXMLNodeKind kind; - - - - - -// @property (nullable, copy) NSString *name; - - - - - -// @property (nullable, retain) id objectValue; - - - - - -// @property (nullable, copy) NSString *stringValue; - - - - - -// - (void)setStringValue:(NSString *)string resolvingEntities:(BOOL)resolve; -// @property (readonly) NSUInteger index; - - - - - -// @property (readonly) NSUInteger level; - - - - - -// @property (nullable, readonly, retain) NSXMLDocument *rootDocument; - - - - - -// @property (nullable, readonly, copy) NSXMLNode *parent; - - - - - -// @property (readonly) NSUInteger childCount; - - - - - -// @property (nullable, readonly, copy) NSArray<NSXMLNode *> *children; - - - - - -// - (nullable NSXMLNode *)childAtIndex:(NSUInteger)index; - - - - - -// @property (nullable, readonly, copy) NSXMLNode *previousSibling; - - - - - -// @property (nullable, readonly, copy) NSXMLNode *nextSibling; - - - - - -// @property (nullable, readonly, copy) NSXMLNode *previousNode; - - - - - -// @property (nullable, readonly, copy) NSXMLNode *nextNode; - - - - - -// - (void)detach; - - - - - -// @property (nullable, readonly, copy) NSString *XPath; -// @property (nullable, readonly, copy) NSString *localName; - - - - - -// @property (nullable, readonly, copy) NSString *prefix; - - - - - -// @property (nullable, copy) NSString *URI; - - - - - -// + (NSString *)localNameForName:(NSString *)name; - - - - - -// + (nullable NSString *)prefixForName:(NSString *)name; - - - - - - -// + (nullable NSXMLNode *)predefinedNamespaceForPrefix:(NSString *)name; -// @property (readonly, copy) NSString *description; - - - - - -// @property (readonly, copy) NSString *XMLString; - - - - - -// - (NSString *)XMLStringWithOptions:(NSUInteger)options; - - - - - -// - (NSString *)canonicalXMLStringPreservingComments:(BOOL)comments; -// - (nullable NSArray<__kindof NSXMLNode *> *)nodesForXPath:(NSString *)xpath error:(NSError **)error; - - - - - - -// - (nullable NSArray *)objectsForXQuery:(NSString *)xquery constants:(nullable NSDictionary<NSString *, id> *)constants error:(NSError **)error; - -// - (nullable NSArray *)objectsForXQuery:(NSString *)xquery error:(NSError **)error; -/* @end */ - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -// @class NSXMLDTDNode; -#ifndef _REWRITER_typedef_NSXMLDTDNode -#define _REWRITER_typedef_NSXMLDTDNode -typedef struct objc_object NSXMLDTDNode; -typedef struct {} _objc_exc_NSXMLDTDNode; -#endif - - - - - - - - - -#ifndef _REWRITER_typedef_NSXMLDTD -#define _REWRITER_typedef_NSXMLDTD -typedef struct objc_object NSXMLDTD; -typedef struct {} _objc_exc_NSXMLDTD; -#endif - -struct NSXMLDTD_IMPL { - struct NSXMLNode_IMPL NSXMLNode_IVARS; - NSString *_name; - NSString *_publicID; - NSString *_systemID; - NSArray *_children; - BOOL _childrenHaveMutated; - uint8_t _padding3[3]; - NSMutableDictionary *_entities; - NSMutableDictionary *_elements; - NSMutableDictionary *_notations; - NSMutableDictionary *_attributes; - NSString *_original; - BOOL _modified; - uint8_t _padding2[3]; -}; - - - - - - -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (instancetype)initWithKind:(NSXMLNodeKind)kind options:(NSUInteger)options __attribute__((unavailable)); -// - (nullable instancetype)initWithContentsOfURL:(NSURL *)url options:(NSUInteger)mask error:(NSError **)error; -// - (nullable instancetype)initWithData:(NSData *)data options:(NSUInteger)mask error:(NSError **)error __attribute__((objc_designated_initializer)); - - - - - -// @property (nullable, copy) NSString *publicID; - - - - - -// @property (nullable, copy) NSString *systemID; -// - (void)insertChild:(NSXMLNode *)child atIndex:(NSUInteger)index; - - - - - -// - (void)insertChildren:(NSArray<NSXMLNode *> *)children atIndex:(NSUInteger)index; - - - - - -// - (void)removeChildAtIndex:(NSUInteger)index; - - - - - -// - (void)setChildren:(nullable NSArray<NSXMLNode *> *)children; - - - - - -// - (void)addChild:(NSXMLNode *)child; - - - - - -// - (void)replaceChildAtIndex:(NSUInteger)index withNode:(NSXMLNode *)node; -// - (nullable NSXMLDTDNode *)entityDeclarationForName:(NSString *)name; - - - - - -// - (nullable NSXMLDTDNode *)notationDeclarationForName:(NSString *)name; - - - - - -// - (nullable NSXMLDTDNode *)elementDeclarationForName:(NSString *)name; - - - - - -// - (nullable NSXMLDTDNode *)attributeDeclarationForName:(NSString *)name elementName:(NSString *)elementName; - - - - - - - -// + (nullable NSXMLDTDNode *)predefinedEntityDeclarationForName:(NSString *)name; -/* @end */ - -typedef NSUInteger NSXMLDTDNodeKind; enum { - NSXMLEntityGeneralKind = 1, - NSXMLEntityParsedKind, - NSXMLEntityUnparsedKind, - NSXMLEntityParameterKind, - NSXMLEntityPredefined, - - NSXMLAttributeCDATAKind, - NSXMLAttributeIDKind, - NSXMLAttributeIDRefKind, - NSXMLAttributeIDRefsKind, - NSXMLAttributeEntityKind, - NSXMLAttributeEntitiesKind, - NSXMLAttributeNMTokenKind, - NSXMLAttributeNMTokensKind, - NSXMLAttributeEnumerationKind, - NSXMLAttributeNotationKind, - - NSXMLElementDeclarationUndefinedKind, - NSXMLElementDeclarationEmptyKind, - NSXMLElementDeclarationAnyKind, - NSXMLElementDeclarationMixedKind, - NSXMLElementDeclarationElementKind -}; - -#ifndef _REWRITER_typedef_NSXMLDTDNode -#define _REWRITER_typedef_NSXMLDTDNode -typedef struct objc_object NSXMLDTDNode; -typedef struct {} _objc_exc_NSXMLDTDNode; -#endif - -struct NSXMLDTDNode_IMPL { - struct NSXMLNode_IMPL NSXMLNode_IVARS; - NSXMLDTDNodeKind _DTDKind; - NSString *_name; - NSString *_notationName; - NSString *_publicID; - NSString *_systemID; -}; - - - - - - -// - (nullable instancetype)initWithXMLString:(NSString *)string __attribute__((objc_designated_initializer)); - -// - (instancetype)initWithKind:(NSXMLNodeKind)kind options:(NSUInteger)options __attribute__((objc_designated_initializer)); - -// - (instancetype)init __attribute__((objc_designated_initializer)); - - - - - -// @property NSXMLDTDNodeKind DTDKind; - - - - - -// @property (readonly, getter=isExternal) BOOL external; - - - - - -// @property (nullable, copy) NSString *publicID; - - - - - -// @property (nullable, copy) NSString *systemID; - - - - - -// @property (nullable, copy) NSString *notationName; - -/* @end */ - - - - - - - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSXMLDTD -#define _REWRITER_typedef_NSXMLDTD -typedef struct objc_object NSXMLDTD; -typedef struct {} _objc_exc_NSXMLDTD; -#endif - -#ifndef _REWRITER_typedef_NSXMLDocument -#define _REWRITER_typedef_NSXMLDocument -typedef struct objc_object NSXMLDocument; -typedef struct {} _objc_exc_NSXMLDocument; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -typedef NSUInteger NSXMLDocumentContentKind; enum { - NSXMLDocumentXMLKind = 0, - NSXMLDocumentXHTMLKind, - NSXMLDocumentHTMLKind, - NSXMLDocumentTextKind -}; - - - - - - - -#ifndef _REWRITER_typedef_NSXMLDocument -#define _REWRITER_typedef_NSXMLDocument -typedef struct objc_object NSXMLDocument; -typedef struct {} _objc_exc_NSXMLDocument; -#endif - -struct NSXMLDocument_IMPL { - struct NSXMLNode_IMPL NSXMLNode_IVARS; - NSString *_encoding; - NSString *_version; - NSXMLDTD *_docType; - NSArray *_children; - BOOL _childrenHaveMutated; - BOOL _standalone; - int8_t padding[2]; - NSXMLElement *_rootElement; - NSString *_URI; - id _extraIvars; - NSUInteger _fidelityMask; - NSXMLDocumentContentKind _contentKind; -}; - - -// - (instancetype)init __attribute__((objc_designated_initializer)); - - - - - -// - (nullable instancetype)initWithXMLString:(NSString *)string options:(NSUInteger)mask error:(NSError **)error; - - - - - -// - (nullable instancetype)initWithContentsOfURL:(NSURL *)url options:(NSUInteger)mask error:(NSError **)error; - - - - - -// - (nullable instancetype)initWithData:(NSData *)data options:(NSUInteger)mask error:(NSError **)error __attribute__((objc_designated_initializer)); - - - - - -// - (instancetype)initWithRootElement:(nullable NSXMLElement *)element __attribute__((objc_designated_initializer)); - - - - - -// + (Class)replacementClassForClass:(Class)cls; - - - - - -// @property (nullable, copy) NSString *characterEncoding; - - - - - -// @property (nullable, copy) NSString *version; - - - - - -// @property (getter=isStandalone) BOOL standalone; - - - - - -// @property NSXMLDocumentContentKind documentContentKind; - - - - - -// @property (nullable, copy) NSString *MIMEType; - - - - - -// @property (nullable, copy) NSXMLDTD *DTD; - - - - - -// - (void)setRootElement:(NSXMLElement *)root; - - - - - -// - (nullable NSXMLElement *)rootElement; -// - (void)insertChild:(NSXMLNode *)child atIndex:(NSUInteger)index; - - - - - -// - (void)insertChildren:(NSArray<NSXMLNode *> *)children atIndex:(NSUInteger)index; - - - - - -// - (void)removeChildAtIndex:(NSUInteger)index; - - - - - -// - (void)setChildren:(nullable NSArray<NSXMLNode *> *)children; - - - - - -// - (void)addChild:(NSXMLNode *)child; - - - - - -// - (void)replaceChildAtIndex:(NSUInteger)index withNode:(NSXMLNode *)node; -// @property (readonly, copy) NSData *XMLData; - - - - - -// - (NSData *)XMLDataWithOptions:(NSUInteger)options; -// - (nullable id)objectByApplyingXSLT:(NSData *)xslt arguments:(nullable NSDictionary<NSString *, NSString *> *)arguments error:(NSError **)error; - - - - - -// - (nullable id)objectByApplyingXSLTString:(NSString *)xslt arguments:(nullable NSDictionary<NSString *, NSString *> *)arguments error:(NSError **)error; - - - - - -// - (nullable id)objectByApplyingXSLTAtURL:(NSURL *)xsltURL arguments:(nullable NSDictionary<NSString *, NSString *> *)argument error:(NSError **)error; - - - - - -// - (BOOL)validateAndReturnError:(NSError **)error; - -/* @end */ - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSMutableArray -#define _REWRITER_typedef_NSMutableArray -typedef struct objc_object NSMutableArray; -typedef struct {} _objc_exc_NSMutableArray; -#endif - -#ifndef _REWRITER_typedef_NSEnumerator -#define _REWRITER_typedef_NSEnumerator -typedef struct objc_object NSEnumerator; -typedef struct {} _objc_exc_NSEnumerator; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - -#ifndef _REWRITER_typedef_NSXMLElement -#define _REWRITER_typedef_NSXMLElement -typedef struct objc_object NSXMLElement; -typedef struct {} _objc_exc_NSXMLElement; -#endif - -struct NSXMLElement_IMPL { - struct NSXMLNode_IMPL NSXMLNode_IVARS; - NSString *_name; - id _attributes; - id _namespaces; - NSArray *_children; - BOOL _childrenHaveMutated; - BOOL _zeroOrOneAttributes; - BOOL _zeroOrOneNamespaces; - uint8_t _padding; - NSString *_URI; - NSInteger _prefixIndex; -}; - - - - - - -// - (instancetype)initWithName:(NSString *)name; - - - - - -// - (instancetype)initWithName:(NSString *)name URI:(nullable NSString *)URI __attribute__((objc_designated_initializer)); - - - - - -// - (instancetype)initWithName:(NSString *)name stringValue:(nullable NSString *)string; - - - - - -// - (nullable instancetype)initWithXMLString:(NSString *)string error:(NSError **)error __attribute__((objc_designated_initializer)); - -// - (instancetype)initWithKind:(NSXMLNodeKind)kind options:(NSUInteger)options; -// - (NSArray<NSXMLElement *> *)elementsForName:(NSString *)name; - - - - - -// - (NSArray<NSXMLElement *> *)elementsForLocalName:(NSString *)localName URI:(nullable NSString *)URI; -// - (void)addAttribute:(NSXMLNode *)attribute; - - - - - -// - (void)removeAttributeForName:(NSString *)name; - - - - - -// @property (nullable, copy) NSArray<NSXMLNode *> *attributes; - - - - - -// - (void)setAttributesWithDictionary:(NSDictionary<NSString *, NSString *> *)attributes; - - - - - -// - (nullable NSXMLNode *)attributeForName:(NSString *)name; - - - - - -// - (nullable NSXMLNode *)attributeForLocalName:(NSString *)localName URI:(nullable NSString *)URI; -// - (void)addNamespace:(NSXMLNode *)aNamespace; - - - - - -// - (void)removeNamespaceForPrefix:(NSString *)name; - - - - - -// @property (nullable, copy) NSArray<NSXMLNode *> *namespaces; - - - - - -// - (nullable NSXMLNode *)namespaceForPrefix:(NSString *)name; - - - - - -// - (nullable NSXMLNode *)resolveNamespaceForName:(NSString *)name; - - - - - -// - (nullable NSString *)resolvePrefixForNamespaceURI:(NSString *)namespaceURI; -// - (void)insertChild:(NSXMLNode *)child atIndex:(NSUInteger)index; - - - - - -// - (void)insertChildren:(NSArray<NSXMLNode *> *)children atIndex:(NSUInteger)index; - - - - - -// - (void)removeChildAtIndex:(NSUInteger)index; - - - - - -// - (void)setChildren:(nullable NSArray<NSXMLNode *> *)children; - - - - - -// - (void)addChild:(NSXMLNode *)child; - - - - - -// - (void)replaceChildAtIndex:(NSUInteger)index withNode:(NSXMLNode *)node; - - - - - -// - (void)normalizeAdjacentTextNodesPreservingCDATA:(BOOL)preserve; - -/* @end */ - - -// @interface NSXMLElement (NSDeprecated) - - - - - -// - (void)setAttributesAsDictionary:(NSDictionary *)attributes; -/* @end */ - - - -// @class NSError; -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -// @class NSURLAuthenticationChallenge; -#ifndef _REWRITER_typedef_NSURLAuthenticationChallenge -#define _REWRITER_typedef_NSURLAuthenticationChallenge -typedef struct objc_object NSURLAuthenticationChallenge; -typedef struct {} _objc_exc_NSURLAuthenticationChallenge; -#endif - -// @class NSURLDownloadInternal; -#ifndef _REWRITER_typedef_NSURLDownloadInternal -#define _REWRITER_typedef_NSURLDownloadInternal -typedef struct objc_object NSURLDownloadInternal; -typedef struct {} _objc_exc_NSURLDownloadInternal; -#endif - -// @class NSURLRequest; -#ifndef _REWRITER_typedef_NSURLRequest -#define _REWRITER_typedef_NSURLRequest -typedef struct objc_object NSURLRequest; -typedef struct {} _objc_exc_NSURLRequest; -#endif - -// @class NSURLResponse; -#ifndef _REWRITER_typedef_NSURLResponse -#define _REWRITER_typedef_NSURLResponse -typedef struct objc_object NSURLResponse; -typedef struct {} _objc_exc_NSURLResponse; -#endif - -// @class NSURLProtectionSpace; -#ifndef _REWRITER_typedef_NSURLProtectionSpace -#define _REWRITER_typedef_NSURLProtectionSpace -typedef struct objc_object NSURLProtectionSpace; -typedef struct {} _objc_exc_NSURLProtectionSpace; -#endif - -// @protocol NSURLDownloadDelegate; - -#ifndef _REWRITER_typedef_NSURLDownload -#define _REWRITER_typedef_NSURLDownload -typedef struct objc_object NSURLDownload; -typedef struct {} _objc_exc_NSURLDownload; -#endif - -struct NSURLDownload_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURLDownloadInternal *_internal; -}; - -// + (BOOL)canResumeDownloadDecodedWithEncodingMIMEType:(NSString *)MIMEType; -// - (instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id <NSURLDownloadDelegate>)delegate __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSession downloadTask (see NSURLSession.h)"))); -// - (instancetype)initWithResumeData:(NSData *)resumeData delegate:(nullable id <NSURLDownloadDelegate>)delegate path:(NSString *)path __attribute__((availability(macosx,introduced=10_3,deprecated=10_11,message="" "Use NSURLSession downloadTask (see NSURLSession.h)"))); - - - - - -// - (void)cancel; -// - (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite; - - - - - - -// @property (readonly, copy) NSURLRequest *request; -// @property (nullable, readonly, copy) NSData *resumeData; -// @property BOOL deletesFileUponFailure; - -/* @end */ - - - - - - -// @protocol NSURLDownloadDelegate <NSObject> - -/* @optional */ - - - - - - -// - (void)downloadDidBegin:(NSURLDownload *)download; -// - (nullable NSURLRequest *)download:(NSURLDownload *)download willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)redirectResponse; -// - (BOOL)download:(NSURLDownload *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace; -// - (void)download:(NSURLDownload *)download didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; - - - - - - - -// - (void)download:(NSURLDownload *)download didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; -// - (BOOL)downloadShouldUseCredentialStorage:(NSURLDownload *)download; -// - (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response; -// - (void)download:(NSURLDownload *)download willResumeWithResponse:(NSURLResponse *)response fromByte:(long long)startingByte; -// - (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length; -// - (BOOL)download:(NSURLDownload *)download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType; -// - (void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename; - - - - - - - -// - (void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path; -// - (void)downloadDidFinish:(NSURLDownload *)download; -// - (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error; - -/* @end */ - - - - - - - - - - - - - - - - - - - - -typedef struct CGAffineTransform CGAffineTransform; - - - - - - -struct CGAffineTransform { - CGFloat a, b, c, d; - CGFloat tx, ty; -}; - - - -extern "C" const CGAffineTransform CGAffineTransformIdentity - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGAffineTransform CGAffineTransformMake(CGFloat a, CGFloat b, - CGFloat c, CGFloat d, CGFloat tx, CGFloat ty) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGAffineTransform CGAffineTransformMakeTranslation(CGFloat tx, - CGFloat ty) __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGAffineTransform CGAffineTransformMakeScale(CGFloat sx, CGFloat sy) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGAffineTransform CGAffineTransformMakeRotation(CGFloat angle) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGAffineTransformIsIdentity(CGAffineTransform t) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGAffineTransform CGAffineTransformTranslate(CGAffineTransform t, - CGFloat tx, CGFloat ty) __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGAffineTransform CGAffineTransformScale(CGAffineTransform t, - CGFloat sx, CGFloat sy) __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGAffineTransform CGAffineTransformRotate(CGAffineTransform t, - CGFloat angle) __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGAffineTransform CGAffineTransformInvert(CGAffineTransform t) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGAffineTransform CGAffineTransformConcat(CGAffineTransform t1, - CGAffineTransform t2) __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGAffineTransformEqualToTransform(CGAffineTransform t1, - CGAffineTransform t2) __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CGPoint CGPointApplyAffineTransform(CGPoint point, - CGAffineTransform t) __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CGSize CGSizeApplyAffineTransform(CGSize size, CGAffineTransform t) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGRect CGRectApplyAffineTransform(CGRect rect, CGAffineTransform t) - __attribute__((availability(macosx,introduced=10.4))); - - - -static inline CGAffineTransform -__CGAffineTransformMake(CGFloat a, CGFloat b, CGFloat c, CGFloat d, - CGFloat tx, CGFloat ty) -{ - CGAffineTransform t; - t.a = a; t.b = b; t.c = c; t.d = d; t.tx = tx; t.ty = ty; - return t; -} - - -static inline CGPoint -__CGPointApplyAffineTransform(CGPoint point, CGAffineTransform t) -{ - CGPoint p; - p.x = (CGFloat)((double)t.a * point.x + (double)t.c * point.y + t.tx); - p.y = (CGFloat)((double)t.b * point.x + (double)t.d * point.y + t.ty); - return p; -} - - -static inline CGSize -__CGSizeApplyAffineTransform(CGSize size, CGAffineTransform t) -{ - CGSize s; - s.width = (CGFloat)((double)t.a * size.width + (double)t.c * size.height); - s.height = (CGFloat)((double)t.b * size.width + (double)t.d * size.height); - return s; -} - - - -typedef struct { - CGFloat m11, m12, m21, m22; - CGFloat tX, tY; -} NSAffineTransformStruct; - - -#ifndef _REWRITER_typedef_NSAffineTransform -#define _REWRITER_typedef_NSAffineTransform -typedef struct objc_object NSAffineTransform; -typedef struct {} _objc_exc_NSAffineTransform; -#endif - -struct NSAffineTransform_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSAffineTransformStruct _transformStruct; -}; - - - -// + (NSAffineTransform *)transform; - - -// - (instancetype)initWithTransform:(NSAffineTransform *)transform; -// - (instancetype)init __attribute__((objc_designated_initializer)); - - -// - (void)translateXBy:(CGFloat)deltaX yBy:(CGFloat)deltaY; - - -// - (void)rotateByDegrees:(CGFloat)angle; -// - (void)rotateByRadians:(CGFloat)angle; - - -// - (void)scaleBy:(CGFloat)scale; -// - (void)scaleXBy:(CGFloat)scaleX yBy:(CGFloat)scaleY; - - -// - (void)invert; - - -// - (void)appendTransform:(NSAffineTransform *)transform; -// - (void)prependTransform:(NSAffineTransform *)transform; - - -// - (NSPoint)transformPoint:(NSPoint)aPoint; -// - (NSSize)transformSize:(NSSize)aSize; - - -// @property NSAffineTransformStruct transformStruct; - -/* @end */ - - - - - - - - - - - -extern "C" { - - -#pragma pack(push, 2) -enum { - kAllTypographicFeaturesType = 0, - kLigaturesType = 1, - kCursiveConnectionType = 2, - kLetterCaseType = 3, - kVerticalSubstitutionType = 4, - kLinguisticRearrangementType = 5, - kNumberSpacingType = 6, - kSmartSwashType = 8, - kDiacriticsType = 9, - kVerticalPositionType = 10, - kFractionsType = 11, - kOverlappingCharactersType = 13, - kTypographicExtrasType = 14, - kMathematicalExtrasType = 15, - kOrnamentSetsType = 16, - kCharacterAlternativesType = 17, - kDesignComplexityType = 18, - kStyleOptionsType = 19, - kCharacterShapeType = 20, - kNumberCaseType = 21, - kTextSpacingType = 22, - kTransliterationType = 23, - kAnnotationType = 24, - kKanaSpacingType = 25, - kIdeographicSpacingType = 26, - kUnicodeDecompositionType = 27, - kRubyKanaType = 28, - kCJKSymbolAlternativesType = 29, - kIdeographicAlternativesType = 30, - kCJKVerticalRomanPlacementType = 31, - kItalicCJKRomanType = 32, - kCaseSensitiveLayoutType = 33, - kAlternateKanaType = 34, - kStylisticAlternativesType = 35, - kContextualAlternatesType = 36, - kLowerCaseType = 37, - kUpperCaseType = 38, - kLanguageTagType = 39, - kCJKRomanSpacingType = 103, - kLastFeatureType = -1 -}; - - - - - - -enum { - kAllTypeFeaturesOnSelector = 0, - kAllTypeFeaturesOffSelector = 1 -}; - - - - - - - -enum { - kRequiredLigaturesOnSelector = 0, - kRequiredLigaturesOffSelector = 1, - kCommonLigaturesOnSelector = 2, - kCommonLigaturesOffSelector = 3, - kRareLigaturesOnSelector = 4, - kRareLigaturesOffSelector = 5, - kLogosOnSelector = 6, - kLogosOffSelector = 7, - kRebusPicturesOnSelector = 8, - kRebusPicturesOffSelector = 9, - kDiphthongLigaturesOnSelector = 10, - kDiphthongLigaturesOffSelector = 11, - kSquaredLigaturesOnSelector = 12, - kSquaredLigaturesOffSelector = 13, - kAbbrevSquaredLigaturesOnSelector = 14, - kAbbrevSquaredLigaturesOffSelector = 15, - kSymbolLigaturesOnSelector = 16, - kSymbolLigaturesOffSelector = 17, - kContextualLigaturesOnSelector = 18, - kContextualLigaturesOffSelector = 19, - kHistoricalLigaturesOnSelector = 20, - kHistoricalLigaturesOffSelector = 21 -}; - - - - - - -enum { - kUnconnectedSelector = 0, - kPartiallyConnectedSelector = 1, - kCursiveSelector = 2 -}; - - - - - - -enum { - kUpperAndLowerCaseSelector = 0, - kAllCapsSelector = 1, - kAllLowerCaseSelector = 2, - kSmallCapsSelector = 3, - kInitialCapsSelector = 4, - kInitialCapsAndSmallCapsSelector = 5 -}; - - - - - - -enum { - kSubstituteVerticalFormsOnSelector = 0, - kSubstituteVerticalFormsOffSelector = 1 -}; - - - - - - -enum { - kLinguisticRearrangementOnSelector = 0, - kLinguisticRearrangementOffSelector = 1 -}; - - - - - - -enum { - kMonospacedNumbersSelector = 0, - kProportionalNumbersSelector = 1, - kThirdWidthNumbersSelector = 2, - kQuarterWidthNumbersSelector = 3 -}; - - - - - - -enum { - kWordInitialSwashesOnSelector = 0, - kWordInitialSwashesOffSelector = 1, - kWordFinalSwashesOnSelector = 2, - kWordFinalSwashesOffSelector = 3, - kLineInitialSwashesOnSelector = 4, - kLineInitialSwashesOffSelector = 5, - kLineFinalSwashesOnSelector = 6, - kLineFinalSwashesOffSelector = 7, - kNonFinalSwashesOnSelector = 8, - kNonFinalSwashesOffSelector = 9 -}; - - - - - - -enum { - kShowDiacriticsSelector = 0, - kHideDiacriticsSelector = 1, - kDecomposeDiacriticsSelector = 2 -}; - - - - - - -enum { - kNormalPositionSelector = 0, - kSuperiorsSelector = 1, - kInferiorsSelector = 2, - kOrdinalsSelector = 3, - kScientificInferiorsSelector = 4 -}; - - - - - - -enum { - kNoFractionsSelector = 0, - kVerticalFractionsSelector = 1, - kDiagonalFractionsSelector = 2 -}; - - - - - - -enum { - kPreventOverlapOnSelector = 0, - kPreventOverlapOffSelector = 1 -}; - - - - - - -enum { - kHyphensToEmDashOnSelector = 0, - kHyphensToEmDashOffSelector = 1, - kHyphenToEnDashOnSelector = 2, - kHyphenToEnDashOffSelector = 3, - kSlashedZeroOnSelector = 4, - kSlashedZeroOffSelector = 5, - kFormInterrobangOnSelector = 6, - kFormInterrobangOffSelector = 7, - kSmartQuotesOnSelector = 8, - kSmartQuotesOffSelector = 9, - kPeriodsToEllipsisOnSelector = 10, - kPeriodsToEllipsisOffSelector = 11 -}; - - - - - - -enum { - kHyphenToMinusOnSelector = 0, - kHyphenToMinusOffSelector = 1, - kAsteriskToMultiplyOnSelector = 2, - kAsteriskToMultiplyOffSelector = 3, - kSlashToDivideOnSelector = 4, - kSlashToDivideOffSelector = 5, - kInequalityLigaturesOnSelector = 6, - kInequalityLigaturesOffSelector = 7, - kExponentsOnSelector = 8, - kExponentsOffSelector = 9, - kMathematicalGreekOnSelector = 10, - kMathematicalGreekOffSelector = 11 -}; - - - - - - -enum { - kNoOrnamentsSelector = 0, - kDingbatsSelector = 1, - kPiCharactersSelector = 2, - kFleuronsSelector = 3, - kDecorativeBordersSelector = 4, - kInternationalSymbolsSelector = 5, - kMathSymbolsSelector = 6 -}; - - - - - - -enum { - kNoAlternatesSelector = 0 -}; - - - - - - -enum { - kDesignLevel1Selector = 0, - kDesignLevel2Selector = 1, - kDesignLevel3Selector = 2, - kDesignLevel4Selector = 3, - kDesignLevel5Selector = 4 -}; - - - - - - -enum { - kNoStyleOptionsSelector = 0, - kDisplayTextSelector = 1, - kEngravedTextSelector = 2, - kIlluminatedCapsSelector = 3, - kTitlingCapsSelector = 4, - kTallCapsSelector = 5 -}; - - - - - - -enum { - kTraditionalCharactersSelector = 0, - kSimplifiedCharactersSelector = 1, - kJIS1978CharactersSelector = 2, - kJIS1983CharactersSelector = 3, - kJIS1990CharactersSelector = 4, - kTraditionalAltOneSelector = 5, - kTraditionalAltTwoSelector = 6, - kTraditionalAltThreeSelector = 7, - kTraditionalAltFourSelector = 8, - kTraditionalAltFiveSelector = 9, - kExpertCharactersSelector = 10, - kJIS2004CharactersSelector = 11, - kHojoCharactersSelector = 12, - kNLCCharactersSelector = 13, - kTraditionalNamesCharactersSelector = 14 -}; - - - - - - -enum { - kLowerCaseNumbersSelector = 0, - kUpperCaseNumbersSelector = 1 -}; - - - - - - -enum { - kProportionalTextSelector = 0, - kMonospacedTextSelector = 1, - kHalfWidthTextSelector = 2, - kThirdWidthTextSelector = 3, - kQuarterWidthTextSelector = 4, - kAltProportionalTextSelector = 5, - kAltHalfWidthTextSelector = 6 -}; - - - - - - -enum { - kNoTransliterationSelector = 0, - kHanjaToHangulSelector = 1, - kHiraganaToKatakanaSelector = 2, - kKatakanaToHiraganaSelector = 3, - kKanaToRomanizationSelector = 4, - kRomanizationToHiraganaSelector = 5, - kRomanizationToKatakanaSelector = 6, - kHanjaToHangulAltOneSelector = 7, - kHanjaToHangulAltTwoSelector = 8, - kHanjaToHangulAltThreeSelector = 9 -}; - - - - - - -enum { - kNoAnnotationSelector = 0, - kBoxAnnotationSelector = 1, - kRoundedBoxAnnotationSelector = 2, - kCircleAnnotationSelector = 3, - kInvertedCircleAnnotationSelector = 4, - kParenthesisAnnotationSelector = 5, - kPeriodAnnotationSelector = 6, - kRomanNumeralAnnotationSelector = 7, - kDiamondAnnotationSelector = 8, - kInvertedBoxAnnotationSelector = 9, - kInvertedRoundedBoxAnnotationSelector = 10 -}; - - - - - - -enum { - kFullWidthKanaSelector = 0, - kProportionalKanaSelector = 1 -}; - - - - - - -enum { - kFullWidthIdeographsSelector = 0, - kProportionalIdeographsSelector = 1, - kHalfWidthIdeographsSelector = 2 -}; - - - - - - -enum { - kCanonicalCompositionOnSelector = 0, - kCanonicalCompositionOffSelector = 1, - kCompatibilityCompositionOnSelector = 2, - kCompatibilityCompositionOffSelector = 3, - kTranscodingCompositionOnSelector = 4, - kTranscodingCompositionOffSelector = 5 -}; - - - - - - -enum { - kNoRubyKanaSelector = 0, - kRubyKanaSelector = 1, - kRubyKanaOnSelector = 2, - kRubyKanaOffSelector = 3 -}; - - - - - - -enum { - kNoCJKSymbolAlternativesSelector = 0, - kCJKSymbolAltOneSelector = 1, - kCJKSymbolAltTwoSelector = 2, - kCJKSymbolAltThreeSelector = 3, - kCJKSymbolAltFourSelector = 4, - kCJKSymbolAltFiveSelector = 5 -}; - - - - - - -enum { - kNoIdeographicAlternativesSelector = 0, - kIdeographicAltOneSelector = 1, - kIdeographicAltTwoSelector = 2, - kIdeographicAltThreeSelector = 3, - kIdeographicAltFourSelector = 4, - kIdeographicAltFiveSelector = 5 -}; - - - - - - -enum { - kCJKVerticalRomanCenteredSelector = 0, - kCJKVerticalRomanHBaselineSelector = 1 -}; - - - - - - -enum { - kNoCJKItalicRomanSelector = 0, - kCJKItalicRomanSelector = 1, - kCJKItalicRomanOnSelector = 2, - kCJKItalicRomanOffSelector = 3 -}; - - - - - - -enum { - kCaseSensitiveLayoutOnSelector = 0, - kCaseSensitiveLayoutOffSelector = 1, - kCaseSensitiveSpacingOnSelector = 2, - kCaseSensitiveSpacingOffSelector = 3 -}; - - - - - - -enum { - kAlternateHorizKanaOnSelector = 0, - kAlternateHorizKanaOffSelector = 1, - kAlternateVertKanaOnSelector = 2, - kAlternateVertKanaOffSelector = 3 -}; - - - - - - -enum { - kNoStylisticAlternatesSelector = 0, - kStylisticAltOneOnSelector = 2, - kStylisticAltOneOffSelector = 3, - kStylisticAltTwoOnSelector = 4, - kStylisticAltTwoOffSelector = 5, - kStylisticAltThreeOnSelector = 6, - kStylisticAltThreeOffSelector = 7, - kStylisticAltFourOnSelector = 8, - kStylisticAltFourOffSelector = 9, - kStylisticAltFiveOnSelector = 10, - kStylisticAltFiveOffSelector = 11, - kStylisticAltSixOnSelector = 12, - kStylisticAltSixOffSelector = 13, - kStylisticAltSevenOnSelector = 14, - kStylisticAltSevenOffSelector = 15, - kStylisticAltEightOnSelector = 16, - kStylisticAltEightOffSelector = 17, - kStylisticAltNineOnSelector = 18, - kStylisticAltNineOffSelector = 19, - kStylisticAltTenOnSelector = 20, - kStylisticAltTenOffSelector = 21, - kStylisticAltElevenOnSelector = 22, - kStylisticAltElevenOffSelector = 23, - kStylisticAltTwelveOnSelector = 24, - kStylisticAltTwelveOffSelector = 25, - kStylisticAltThirteenOnSelector = 26, - kStylisticAltThirteenOffSelector = 27, - kStylisticAltFourteenOnSelector = 28, - kStylisticAltFourteenOffSelector = 29, - kStylisticAltFifteenOnSelector = 30, - kStylisticAltFifteenOffSelector = 31, - kStylisticAltSixteenOnSelector = 32, - kStylisticAltSixteenOffSelector = 33, - kStylisticAltSeventeenOnSelector = 34, - kStylisticAltSeventeenOffSelector = 35, - kStylisticAltEighteenOnSelector = 36, - kStylisticAltEighteenOffSelector = 37, - kStylisticAltNineteenOnSelector = 38, - kStylisticAltNineteenOffSelector = 39, - kStylisticAltTwentyOnSelector = 40, - kStylisticAltTwentyOffSelector = 41 -}; - - - - - - -enum { - kContextualAlternatesOnSelector = 0, - kContextualAlternatesOffSelector = 1, - kSwashAlternatesOnSelector = 2, - kSwashAlternatesOffSelector = 3, - kContextualSwashAlternatesOnSelector = 4, - kContextualSwashAlternatesOffSelector = 5 -}; - - - - - - -enum { - kDefaultLowerCaseSelector = 0, - kLowerCaseSmallCapsSelector = 1, - kLowerCasePetiteCapsSelector = 2 -}; - - - - - - -enum { - kDefaultUpperCaseSelector = 0, - kUpperCaseSmallCapsSelector = 1, - kUpperCasePetiteCapsSelector = 2 -}; - - - - - - -enum { - kHalfWidthCJKRomanSelector = 0, - kProportionalCJKRomanSelector = 1, - kDefaultCJKRomanSelector = 2, - kFullWidthCJKRomanSelector = 3 -}; - - - - - -enum { - kSFNTLookupSimpleArray = 0, - kSFNTLookupSegmentSingle = 2, - kSFNTLookupSegmentArray = 4, - kSFNTLookupSingleTable = 6, - kSFNTLookupTrimmedArray = 8 -}; - -typedef UInt16 SFNTLookupTableFormat; -typedef UInt16 SFNTLookupValue; -typedef UInt16 SFNTLookupOffset; -typedef UInt32 SFNTLookupKind; - - - - - - -struct SFNTLookupBinarySearchHeader { - UInt16 unitSize; - UInt16 nUnits; - UInt16 searchRange; - UInt16 entrySelector; - UInt16 rangeShift; -}; -typedef struct SFNTLookupBinarySearchHeader SFNTLookupBinarySearchHeader; - -struct SFNTLookupArrayHeader { - SFNTLookupValue lookupValues[1]; -}; -typedef struct SFNTLookupArrayHeader SFNTLookupArrayHeader; - -struct SFNTLookupTrimmedArrayHeader { - UInt16 firstGlyph; - UInt16 count; - SFNTLookupValue valueArray[1]; -}; -typedef struct SFNTLookupTrimmedArrayHeader SFNTLookupTrimmedArrayHeader; - - - - - - -struct SFNTLookupSegment { - UInt16 lastGlyph; - UInt16 firstGlyph; - UInt16 value[1]; -}; -typedef struct SFNTLookupSegment SFNTLookupSegment; -struct SFNTLookupSegmentHeader { - SFNTLookupBinarySearchHeader binSearch; - SFNTLookupSegment segments[1]; -}; -typedef struct SFNTLookupSegmentHeader SFNTLookupSegmentHeader; - -struct SFNTLookupSingle { - UInt16 glyph; - UInt16 value[1]; -}; -typedef struct SFNTLookupSingle SFNTLookupSingle; -struct SFNTLookupSingleHeader { - SFNTLookupBinarySearchHeader binSearch; - SFNTLookupSingle entries[1]; -}; -typedef struct SFNTLookupSingleHeader SFNTLookupSingleHeader; - -union SFNTLookupFormatSpecificHeader { - SFNTLookupArrayHeader theArray; - SFNTLookupSegmentHeader segment; - SFNTLookupSingleHeader single; - SFNTLookupTrimmedArrayHeader trimmedArray; -}; -typedef union SFNTLookupFormatSpecificHeader SFNTLookupFormatSpecificHeader; - -struct SFNTLookupTable { - SFNTLookupTableFormat format; - SFNTLookupFormatSpecificHeader fsHeader; -}; -typedef struct SFNTLookupTable SFNTLookupTable; -typedef SFNTLookupTable * SFNTLookupTablePtr; -typedef SFNTLookupTablePtr * SFNTLookupTableHandle; - - -enum { - kSTClassEndOfText = 0, - kSTClassOutOfBounds = 1, - kSTClassDeletedGlyph = 2, - kSTClassEndOfLine = 3, - kSTSetMark = 0x8000, - kSTNoAdvance = 0x4000, - kSTMarkEnd = 0x2000, - kSTLigActionMask = 0x3FFF, - kSTRearrVerbMask = 0x000F -}; - -typedef UInt8 STClass; -typedef UInt8 STEntryIndex; -struct STHeader { - UInt8 filler; - STClass nClasses; - UInt16 classTableOffset; - UInt16 stateArrayOffset; - UInt16 entryTableOffset; -}; -typedef struct STHeader STHeader; -struct STClassTable { - UInt16 firstGlyph; - UInt16 nGlyphs; - STClass classes[1]; -}; -typedef struct STClassTable STClassTable; -struct STEntryZero { - UInt16 newState; - UInt16 flags; -}; -typedef struct STEntryZero STEntryZero; -struct STEntryOne { - UInt16 newState; - UInt16 flags; - UInt16 offset1; -}; -typedef struct STEntryOne STEntryOne; -struct STEntryTwo { - UInt16 newState; - UInt16 flags; - UInt16 offset1; - UInt16 offset2; -}; -typedef struct STEntryTwo STEntryTwo; - - -enum { - kSTXHasLigAction = 0x2000 -}; - - -typedef UInt16 STXClass; -typedef UInt16 STXStateIndex; -typedef UInt16 STXEntryIndex; -struct STXHeader { - UInt32 nClasses; - UInt32 classTableOffset; - UInt32 stateArrayOffset; - UInt32 entryTableOffset; -}; -typedef struct STXHeader STXHeader; - -typedef SFNTLookupTable STXClassTable; -struct STXEntryZero { - STXStateIndex newState; - UInt16 flags; -}; -typedef struct STXEntryZero STXEntryZero; -struct STXEntryOne { - STXStateIndex newState; - UInt16 flags; - UInt16 index1; -}; -typedef struct STXEntryOne STXEntryOne; -struct STXEntryTwo { - STXStateIndex newState; - UInt16 flags; - UInt16 index1; - UInt16 index2; -}; -typedef struct STXEntryTwo STXEntryTwo; - - -enum { - kSTKCrossStreamReset = 0x2000 -}; - - - -enum { - kLCARTag = 0x6C636172, - kLCARCurrentVersion = 0x00010000, - kLCARLinearFormat = 0, - kLCARCtlPointFormat = 1 -}; - - -struct LcarCaretClassEntry { - UInt16 count; - UInt16 partials[1]; -}; -typedef struct LcarCaretClassEntry LcarCaretClassEntry; -struct LcarCaretTable { - Fixed version; - UInt16 format; - SFNTLookupTable lookup; -}; -typedef struct LcarCaretTable LcarCaretTable; -typedef LcarCaretTable * LcarCaretTablePtr; - - - -enum { - kJUSTTag = 0x6A757374, - kJUSTCurrentVersion = 0x00010000, - kJUSTStandardFormat = 0, - kJUSTnoGlyphcode = 0xFFFF, - kJUSTpcDecompositionAction = 0, - kJUSTpcUnconditionalAddAction = 1, - kJUSTpcConditionalAddAction = 2, - kJUSTpcGlyphStretchAction = 3, - kJUSTpcDuctilityAction = 4, - kJUSTpcGlyphRepeatAddAction = 5 -}; - - -enum { - kJUSTKashidaPriority = 0, - kJUSTSpacePriority = 1, - kJUSTLetterPriority = 2, - kJUSTNullPriority = 3, - kJUSTPriorityCount = 4 -}; - - -enum { - kJUSTOverridePriority = 0x8000, - kJUSTOverrideLimits = 0x4000, - kJUSTOverrideUnlimited = 0x2000, - kJUSTUnlimited = 0x1000, - kJUSTPriorityMask = 0x0003 -}; - - -typedef UInt16 JustPCActionType; -typedef UInt16 JustificationFlags; - -struct JustPCDecompositionAction { - Fixed lowerLimit; - Fixed upperLimit; - UInt16 order; - UInt16 count; - UInt16 glyphs[1]; -}; -typedef struct JustPCDecompositionAction JustPCDecompositionAction; - - -typedef UInt16 JustPCUnconditionalAddAction; - - - - - -struct JustPCConditionalAddAction { - Fixed substThreshold; - UInt16 addGlyph; - UInt16 substGlyph; -}; -typedef struct JustPCConditionalAddAction JustPCConditionalAddAction; - -struct JustPCDuctilityAction { - UInt32 ductilityAxis; - Fixed minimumLimit; - Fixed noStretchValue; - Fixed maximumLimit; -}; -typedef struct JustPCDuctilityAction JustPCDuctilityAction; - - - - - -struct JustPCGlyphRepeatAddAction { - UInt16 flags; - UInt16 glyph; -}; -typedef struct JustPCGlyphRepeatAddAction JustPCGlyphRepeatAddAction; - -struct JustPCActionSubrecord { - UInt16 theClass; - JustPCActionType theType; - UInt32 length; - UInt32 data; -}; -typedef struct JustPCActionSubrecord JustPCActionSubrecord; - -struct JustPCAction { - UInt32 actionCount; - JustPCActionSubrecord actions[1]; -}; -typedef struct JustPCAction JustPCAction; - - - - -struct JustWidthDeltaEntry { - UInt32 justClass; - Fixed beforeGrowLimit; - Fixed beforeShrinkLimit; - Fixed afterGrowLimit; - Fixed afterShrinkLimit; - JustificationFlags growFlags; - JustificationFlags shrinkFlags; -}; -typedef struct JustWidthDeltaEntry JustWidthDeltaEntry; -struct JustWidthDeltaGroup { - UInt32 count; - JustWidthDeltaEntry entries[1]; -}; -typedef struct JustWidthDeltaGroup JustWidthDeltaGroup; - -struct JustPostcompTable { - SFNTLookupTable lookupTable; - -}; -typedef struct JustPostcompTable JustPostcompTable; -struct JustDirectionTable { - UInt16 justClass; - UInt16 widthDeltaClusters; - UInt16 postcomp; - SFNTLookupTable lookup; -}; -typedef struct JustDirectionTable JustDirectionTable; -struct JustTable { - Fixed version; - UInt16 format; - UInt16 horizHeaderOffset; - UInt16 vertHeaderOffset; -}; -typedef struct JustTable JustTable; - - - -enum { - kOPBDTag = 0x6F706264, - kOPBDCurrentVersion = 0x00010000, - kOPBDDistanceFormat = 0, - kOPBDControlPointFormat = 1 -}; - - - -typedef UInt16 OpbdTableFormat; - - - - - -struct OpbdSideValues { - SInt16 leftSideShift; - SInt16 topSideShift; - SInt16 rightSideShift; - SInt16 bottomSideShift; -}; -typedef struct OpbdSideValues OpbdSideValues; -struct OpbdTable { - Fixed version; - OpbdTableFormat format; - SFNTLookupTable lookupTable; -}; -typedef struct OpbdTable OpbdTable; - - - -enum { - kMORTTag = 0x6D6F7274, - kMORTCurrentVersion = 0x00010000, - - kMORTCoverVertical = 0x8000, - kMORTCoverDescending = 0x4000, - kMORTCoverIgnoreVertical = 0x2000, - kMORTCoverTypeMask = 0x000F, - kMORTRearrangementType = 0, - kMORTContextualType = 1, - kMORTLigatureType = 2, - kMORTSwashType = 4, - kMORTInsertionType = 5, - kMORTLigLastAction = (int)0x80000000, - kMORTLigStoreLigature = 0x40000000, - kMORTLigFormOffsetMask = 0x3FFFFFFF, - kMORTLigFormOffsetShift = 2, - kMORTraNoAction = 0, - kMORTraxA = 1, - kMORTraDx = 2, - kMORTraDxA = 3, - kMORTraxAB = 4, - kMORTraxBA = 5, - kMORTraCDx = 6, - kMORTraDCx = 7, - kMORTraCDxA = 8, - kMORTraDCxA = 9, - kMORTraDxAB = 10, - kMORTraDxBA = 11, - kMORTraCDxAB = 12, - kMORTraCDxBA = 13, - kMORTraDCxAB = 14, - kMORTraDCxBA = 15, - - kMORTDoInsertionsBefore = 0x80, - kMORTIsSplitVowelPiece = 0x40, - kMORTInsertionsCountMask = 0x3F, - kMORTCurrInsertKashidaLike = 0x2000, - kMORTMarkInsertKashidaLike = 0x1000, - kMORTCurrInsertBefore = 0x0800, - kMORTMarkInsertBefore = 0x0400, - kMORTMarkJustTableCountMask = 0x3F80, - kMORTMarkJustTableCountShift = 7, - kMORTCurrJustTableCountMask = 0x007F, - kMORTCurrJustTableCountShift = 0, - kMORTCurrInsertCountMask = 0x03E0, - kMORTCurrInsertCountShift = 5, - kMORTMarkInsertCountMask = 0x001F, - kMORTMarkInsertCountShift = 0 -}; - - - -typedef UInt32 MortSubtableMaskFlags; -typedef UInt32 MortLigatureActionEntry; -struct MortRearrangementSubtable { - STHeader header; -}; -typedef struct MortRearrangementSubtable MortRearrangementSubtable; -struct MortContextualSubtable { - STHeader header; - UInt16 substitutionTableOffset; -}; -typedef struct MortContextualSubtable MortContextualSubtable; -struct MortLigatureSubtable { - STHeader header; - UInt16 ligatureActionTableOffset; - UInt16 componentTableOffset; - UInt16 ligatureTableOffset; -}; -typedef struct MortLigatureSubtable MortLigatureSubtable; -struct MortSwashSubtable { - SFNTLookupTable lookup; -}; -typedef struct MortSwashSubtable MortSwashSubtable; -struct MortInsertionSubtable { - STHeader header; -}; -typedef struct MortInsertionSubtable MortInsertionSubtable; -union MortSpecificSubtable { - MortRearrangementSubtable rearrangement; - MortContextualSubtable contextual; - MortLigatureSubtable ligature; - MortSwashSubtable swash; - MortInsertionSubtable insertion; -}; -typedef union MortSpecificSubtable MortSpecificSubtable; -struct MortSubtable { - UInt16 length; - UInt16 coverage; - MortSubtableMaskFlags flags; - MortSpecificSubtable u; -}; -typedef struct MortSubtable MortSubtable; -struct MortFeatureEntry { - UInt16 featureType; - UInt16 featureSelector; - MortSubtableMaskFlags enableFlags; - MortSubtableMaskFlags disableFlags; -}; -typedef struct MortFeatureEntry MortFeatureEntry; -struct MortChain { - MortSubtableMaskFlags defaultFlags; - UInt32 length; - UInt16 nFeatures; - UInt16 nSubtables; - MortFeatureEntry featureEntries[1]; - -}; -typedef struct MortChain MortChain; -struct MortTable { - Fixed version; - UInt32 nChains; - MortChain chains[1]; -}; -typedef struct MortTable MortTable; - - - -enum { - kMORXTag = 0x6D6F7278, - kMORXCurrentVersion = 0x00020000, - - kMORXCoverVertical = (int)0x80000000, - kMORXCoverDescending = 0x40000000, - kMORXCoverIgnoreVertical = 0x20000000, - kMORXCoverLogicalOrder = 0x10000000, - kMORXCoverTypeMask = 0x000000FF -}; - - -struct MorxRearrangementSubtable { - STXHeader header; -}; -typedef struct MorxRearrangementSubtable MorxRearrangementSubtable; -struct MorxContextualSubtable { - STXHeader header; - UInt32 substitutionTableOffset; -}; -typedef struct MorxContextualSubtable MorxContextualSubtable; -struct MorxLigatureSubtable { - STXHeader header; - UInt32 ligatureActionTableOffset; - UInt32 componentTableOffset; - UInt32 ligatureTableOffset; -}; -typedef struct MorxLigatureSubtable MorxLigatureSubtable; -struct MorxInsertionSubtable { - STXHeader header; - UInt32 insertionGlyphTableOffset; -}; -typedef struct MorxInsertionSubtable MorxInsertionSubtable; -union MorxSpecificSubtable { - MorxRearrangementSubtable rearrangement; - MorxContextualSubtable contextual; - MorxLigatureSubtable ligature; - MortSwashSubtable swash; - MorxInsertionSubtable insertion; -}; -typedef union MorxSpecificSubtable MorxSpecificSubtable; -struct MorxSubtable { - UInt32 length; - UInt32 coverage; - MortSubtableMaskFlags flags; - MorxSpecificSubtable u; -}; -typedef struct MorxSubtable MorxSubtable; -struct MorxChain { - MortSubtableMaskFlags defaultFlags; - UInt32 length; - UInt32 nFeatures; - UInt32 nSubtables; - MortFeatureEntry featureEntries[1]; - -}; -typedef struct MorxChain MorxChain; -struct MorxTable { - Fixed version; - UInt32 nChains; - MorxChain chains[1]; -}; -typedef struct MorxTable MorxTable; - - - -enum { - kPROPTag = 0x70726F70, - kPROPCurrentVersion = 0x00030000, - kPROPPairOffsetShift = 8, - kPROPPairOffsetSign = 7, - kPROPIsFloaterMask = 0x8000, - kPROPCanHangLTMask = 0x4000, - kPROPCanHangRBMask = 0x2000, - kPROPUseRLPairMask = 0x1000, - kPROPPairOffsetMask = 0x0F00, - kPROPRightConnectMask = 0x0080, - kPROPZeroReserved = 0x0060, - kPROPDirectionMask = 0x001F -}; - - -enum { - kPROPLDirectionClass = 0, - kPROPRDirectionClass = 1, - kPROPALDirectionClass = 2, - kPROPENDirectionClass = 3, - kPROPESDirectionClass = 4, - kPROPETDirectionClass = 5, - kPROPANDirectionClass = 6, - kPROPCSDirectionClass = 7, - kPROPPSDirectionClass = 8, - kPROPSDirectionClass = 9, - kPROPWSDirectionClass = 10, - kPROPONDirectionClass = 11, - kPROPSENDirectionClass = 12, - kPROPLREDirectionClass = 13, - kPROPLRODirectionClass = 14, - kPROPRLEDirectionClass = 15, - kPROPRLODirectionClass = 16, - kPROPPDFDirectionClass = 17, - kPROPNSMDirectionClass = 18, - kPROPBNDirectionClass = 19, - kPROPNumDirectionClasses = 20 -}; - - - -typedef UInt16 PropCharProperties; -struct PropTable { - Fixed version; - UInt16 format; - PropCharProperties defaultProps; - SFNTLookupTable lookup; -}; -typedef struct PropTable PropTable; -struct PropLookupSegment { - UInt16 lastGlyph; - UInt16 firstGlyph; - UInt16 value; -}; -typedef struct PropLookupSegment PropLookupSegment; -struct PropLookupSingle { - UInt16 glyph; - PropCharProperties props; -}; -typedef struct PropLookupSingle PropLookupSingle; - - - -enum { - kTRAKTag = 0x7472616B, - kTRAKCurrentVersion = 0x00010000, - kTRAKUniformFormat = 0 -}; - - - -typedef SInt16 TrakValue; -struct TrakTableEntry { - Fixed track; - UInt16 nameTableIndex; - UInt16 sizesOffset; -}; -typedef struct TrakTableEntry TrakTableEntry; -struct TrakTableData { - UInt16 nTracks; - UInt16 nSizes; - UInt32 sizeTableOffset; - TrakTableEntry trakTable[1]; -}; -typedef struct TrakTableData TrakTableData; -struct TrakTable { - Fixed version; - UInt16 format; - UInt16 horizOffset; - UInt16 vertOffset; -}; -typedef struct TrakTable TrakTable; - - - -enum { - kKERNTag = 0x6B65726E, - kKERNCurrentVersion = 0x00010000, - kKERNVertical = 0x8000, - kKERNResetCrossStream = 0x8000, - kKERNCrossStream = 0x4000, - kKERNVariation = 0x2000, - kKERNUnusedBits = 0x1F00, - kKERNFormatMask = 0x00FF -}; - -enum { - kKERNOrderedList = 0, - kKERNStateTable = 1, - kKERNSimpleArray = 2, - kKERNIndexArray = 3 -}; - - -enum { - kKERNLineStart = 0x00000001, - kKERNLineEndKerning = 0x00000002, - kKERNNoCrossKerning = 0x00000004, - kKERNNotesRequested = 0x00000008, - kKERNNoStakeNote = 1, - kKERNCrossStreamResetNote = 2, - kKERNNotApplied = 0x00000001 -}; - - - -typedef UInt8 KernTableFormat; -typedef UInt16 KernSubtableInfo; -typedef SInt16 KernKerningValue; -typedef UInt16 KernArrayOffset; - -struct KernVersion0Header { - UInt16 version; - UInt16 nTables; - UInt16 firstSubtable[1]; -}; -typedef struct KernVersion0Header KernVersion0Header; - -struct KernTableHeader { - Fixed version; - SInt32 nTables; - UInt16 firstSubtable[1]; -}; -typedef struct KernTableHeader KernTableHeader; -typedef KernTableHeader * KernTableHeaderPtr; -typedef KernTableHeaderPtr * KernTableHeaderHandle; -struct KernKerningPair { - UInt16 left; - UInt16 right; -}; -typedef struct KernKerningPair KernKerningPair; - -struct KernOrderedListEntry { - KernKerningPair pair; - KernKerningValue value; -}; -typedef struct KernOrderedListEntry KernOrderedListEntry; -typedef KernOrderedListEntry * KernOrderedListEntryPtr; - -struct KernOrderedListHeader { - UInt16 nPairs; - UInt16 searchRange; - UInt16 entrySelector; - UInt16 rangeShift; - UInt16 table[1]; -}; -typedef struct KernOrderedListHeader KernOrderedListHeader; - -struct KernStateHeader { - STHeader header; - UInt16 valueTable; - UInt8 firstTable[1]; -}; -typedef struct KernStateHeader KernStateHeader; -struct KernStateEntry { - UInt16 newState; - UInt16 flags; -}; -typedef struct KernStateEntry KernStateEntry; - - - - - - -struct KernOffsetTable { - UInt16 firstGlyph; - UInt16 nGlyphs; - KernArrayOffset offsetTable[1]; -}; -typedef struct KernOffsetTable KernOffsetTable; -typedef KernOffsetTable * KernOffsetTablePtr; -struct KernSimpleArrayHeader { - UInt16 rowWidth; - UInt16 leftOffsetTable; - UInt16 rightOffsetTable; - KernArrayOffset theArray; - UInt16 firstTable[1]; -}; -typedef struct KernSimpleArrayHeader KernSimpleArrayHeader; - -struct KernIndexArrayHeader { - UInt16 glyphCount; - UInt8 kernValueCount; - UInt8 leftClassCount; - UInt8 rightClassCount; - UInt8 flags; - SInt16 kernValue[1]; - UInt8 leftClass[1]; - UInt8 rightClass[1]; - UInt8 kernIndex[1]; -}; -typedef struct KernIndexArrayHeader KernIndexArrayHeader; - -union KernFormatSpecificHeader { - KernOrderedListHeader orderedList; - KernStateHeader stateTable; - KernSimpleArrayHeader simpleArray; - KernIndexArrayHeader indexArray; -}; -typedef union KernFormatSpecificHeader KernFormatSpecificHeader; - -struct KernVersion0SubtableHeader { - UInt16 version; - UInt16 length; - KernSubtableInfo stInfo; - KernFormatSpecificHeader fsHeader; -}; -typedef struct KernVersion0SubtableHeader KernVersion0SubtableHeader; - -struct KernSubtableHeader { - SInt32 length; - KernSubtableInfo stInfo; - SInt16 tupleIndex; - KernFormatSpecificHeader fsHeader; -}; -typedef struct KernSubtableHeader KernSubtableHeader; -typedef KernSubtableHeader * KernSubtableHeaderPtr; - - - -enum { - kKERXTag = 0x6B657278, - kKERXCurrentVersion = 0x00020000, - kKERXVertical = (int)0x80000000, - kKERXResetCrossStream = 0x8000, - kKERXCrossStream = 0x40000000, - kKERXVariation = 0x20000000, - kKERXDescending = 0x10000000, - kKERXUnusedBits = 0x0FFFFF00, - kKERXFormatMask = 0x000000FF -}; - -enum { - kKERXOrderedList = 0, - kKERXStateTable = 1, - kKERXSimpleArray = 2, - kKERXIndexArray = 3, - kKERXControlPoint = 4 -}; - - -enum { - kKERXLineStart = 0x00000001, - kKERXLineEndKerning = 0x00000002, - kKERXNoCrossKerning = 0x00000004, - kKERXNotesRequested = 0x00000008, - kKERXNoStakeNote = 1, - kKERXCrossStreamResetNote = 2, - kKERXNotApplied = 0x00000001 -}; - - -enum { - kKERXActionTypeMask = (3U << 30), - kKERXActionTypeControlPoints = (0U << 30), - kKERXActionTypeAnchorPoints = (1U << 30), - kKERXActionTypeCoordinates = (2U << 30), - kKERXUnusedFlags = 0x3F000000, - kKERXActionOffsetMask = 0x00FFFFFF, -}; - - -typedef UInt32 KerxSubtableCoverage; -typedef UInt32 KerxArrayOffset; - -struct KerxTableHeader { - Fixed version; - UInt32 nTables; - UInt32 firstSubtable[1]; -}; -typedef struct KerxTableHeader KerxTableHeader; -typedef KerxTableHeader * KerxTableHeaderPtr; -typedef KerxTableHeaderPtr * KerxTableHeaderHandle; -struct KerxKerningPair { - UInt16 left; - UInt16 right; -}; -typedef struct KerxKerningPair KerxKerningPair; - -struct KerxOrderedListEntry { - KerxKerningPair pair; - KernKerningValue value; -}; -typedef struct KerxOrderedListEntry KerxOrderedListEntry; -typedef KerxOrderedListEntry * KerxOrderedListEntryPtr; - -struct KerxOrderedListHeader { - UInt32 nPairs; - UInt32 searchRange; - UInt32 entrySelector; - UInt32 rangeShift; - UInt32 table[1]; -}; -typedef struct KerxOrderedListHeader KerxOrderedListHeader; - -struct KerxStateHeader { - STXHeader header; - UInt32 valueTable; - UInt8 firstTable[1]; -}; -typedef struct KerxStateHeader KerxStateHeader; -struct KerxStateEntry { - UInt16 newState; - UInt16 flags; - UInt16 valueIndex; -}; -typedef struct KerxStateEntry KerxStateEntry; - -struct KerxControlPointHeader { - STXHeader header; - UInt32 flags; - UInt8 firstTable[1]; -}; -typedef struct KerxControlPointHeader KerxControlPointHeader; -struct KerxControlPointEntry { - UInt16 newState; - UInt16 flags; - UInt16 actionIndex; -}; -typedef struct KerxControlPointEntry KerxControlPointEntry; -struct KerxControlPointAction { - UInt16 markControlPoint; - UInt16 currControlPoint; -}; -typedef struct KerxControlPointAction KerxControlPointAction; -struct KerxAnchorPointAction { - UInt16 markAnchorPoint; - UInt16 currAnchorPoint; -}; -typedef struct KerxAnchorPointAction KerxAnchorPointAction; -struct KerxCoordinateAction { - UInt16 markX; - UInt16 markY; - UInt16 currX; - UInt16 currY; -}; -typedef struct KerxCoordinateAction KerxCoordinateAction; -struct KerxSimpleArrayHeader { - UInt32 rowWidth; - UInt32 leftOffsetTable; - UInt32 rightOffsetTable; - KerxArrayOffset theArray; - UInt32 firstTable[1]; -}; -typedef struct KerxSimpleArrayHeader KerxSimpleArrayHeader; - -struct KerxIndexArrayHeader { - UInt16 glyphCount; - UInt16 kernValueCount; - UInt16 leftClassCount; - UInt16 rightClassCount; - UInt16 flags; - SInt16 kernValue[1]; - UInt16 leftClass[1]; - UInt16 rightClass[1]; - UInt16 kernIndex[1]; -}; -typedef struct KerxIndexArrayHeader KerxIndexArrayHeader; - -union KerxFormatSpecificHeader { - KerxOrderedListHeader orderedList; - KerxStateHeader stateTable; - KerxSimpleArrayHeader simpleArray; - KerxIndexArrayHeader indexArray; - KerxControlPointHeader controlPoint; - -}; -typedef union KerxFormatSpecificHeader KerxFormatSpecificHeader; - -struct KerxSubtableHeader { - UInt32 length; - KerxSubtableCoverage stInfo; - UInt32 tupleIndex; - KerxFormatSpecificHeader fsHeader; -}; -typedef struct KerxSubtableHeader KerxSubtableHeader; -typedef KerxSubtableHeader * KerxSubtableHeaderPtr; - - - -enum { - kBSLNTag = 0x62736C6E, - kBSLNCurrentVersion = 0x00010000, - kBSLNDistanceFormatNoMap = 0, - kBSLNDistanceFormatWithMap = 1, - kBSLNControlPointFormatNoMap = 2, - kBSLNControlPointFormatWithMap = 3 -}; - - -enum { - kBSLNRomanBaseline = 0, - kBSLNIdeographicCenterBaseline = 1, - kBSLNIdeographicLowBaseline = 2, - kBSLNHangingBaseline = 3, - kBSLNMathBaseline = 4, - kBSLNIdeographicHighBaseline = 5, - kBSLNLastBaseline = 31, - kBSLNNumBaselineClasses = kBSLNLastBaseline + 1, - kBSLNNoBaseline = 255, - kBSLNNoBaselineOverride = 255 -}; - - -typedef UInt32 BslnBaselineClass; - -typedef Fixed BslnBaselineRecord[32]; - - - - -struct BslnFormat0Part { - SInt16 deltas[32]; -}; -typedef struct BslnFormat0Part BslnFormat0Part; - -struct BslnFormat1Part { - SInt16 deltas[32]; - SFNTLookupTable mappingData; -}; -typedef struct BslnFormat1Part BslnFormat1Part; - - - - - - -struct BslnFormat2Part { - UInt16 stdGlyph; - SInt16 ctlPoints[32]; -}; -typedef struct BslnFormat2Part BslnFormat2Part; - - - - - -struct BslnFormat3Part { - UInt16 stdGlyph; - SInt16 ctlPoints[32]; - SFNTLookupTable mappingData; -}; -typedef struct BslnFormat3Part BslnFormat3Part; - -union BslnFormatUnion { - BslnFormat0Part fmt0Part; - BslnFormat1Part fmt1Part; - BslnFormat2Part fmt2Part; - BslnFormat3Part fmt3Part; -}; -typedef union BslnFormatUnion BslnFormatUnion; - - -typedef UInt16 BslnTableFormat; - -struct BslnTable { - Fixed version; - BslnTableFormat format; - UInt16 defaultBaseline; - BslnFormatUnion parts; -}; -typedef struct BslnTable BslnTable; -typedef BslnTable * BslnTablePtr; - - - -struct ALMXHeader { - Fixed Version; - UInt16 Flags; - UInt16 NMasters; - UInt16 FirstGlyph; - UInt16 LastGlyph; - - SFNTLookupTable lookup; -}; -typedef struct ALMXHeader ALMXHeader; -struct ALMXGlyphEntry { - SInt16 GlyphIndexOffset; - SInt16 HorizontalAdvance; - SInt16 XOffsetToHOrigin; - SInt16 VerticalAdvance; - SInt16 YOffsetToVOrigin; -}; -typedef struct ALMXGlyphEntry ALMXGlyphEntry; - - - -struct ROTAHeader { - Fixed Version; - UInt16 Flags; - UInt16 NMasters; - UInt16 FirstGlyph; - UInt16 LastGlyph; - - SFNTLookupTable lookup; -}; -typedef struct ROTAHeader ROTAHeader; -struct ROTAGlyphEntry { - SInt16 GlyphIndexOffset; - SInt16 HBaselineOffset; - SInt16 VBaselineOffset; -}; -typedef struct ROTAGlyphEntry ROTAGlyphEntry; - - - -enum { - kANKRCurrentVersion = 0 -}; - - -struct AnchorPoint { - SInt16 x; - SInt16 y; -}; -typedef struct AnchorPoint AnchorPoint; - -struct AnchorPointTable { - UInt32 nPoints; - AnchorPoint points[1]; -}; -typedef struct AnchorPointTable AnchorPointTable; - -struct AnkrTable { - UInt16 version; - UInt16 flags; - UInt32 lookupTableOffset; - UInt32 anchorPointTableOffset; -}; -typedef struct AnkrTable AnkrTable; - - - -enum { - kLTAGCurrentVersion = 1 -}; - - -struct LtagStringRange { - UInt16 offset; - UInt16 length; -}; -typedef struct LtagStringRange LtagStringRange; - -struct LtagTable { - UInt32 version; - UInt32 flags; - UInt32 numTags; - LtagStringRange tagRange[1]; -}; -typedef struct LtagTable LtagTable; - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) -typedef CGPoint ATSPoint; -struct ATSFSSpec { - FSVolumeRefNum vRefNum; - SInt32 parID; - StrFileName name; -}; -typedef struct ATSFSSpec ATSFSSpec; - - - - - -typedef UInt32 FMGeneration; - - - - - - - -typedef SInt16 FMFontFamily; -typedef SInt16 FMFontStyle; -typedef SInt16 FMFontSize; - - - - - - - -typedef UInt32 FMFont; -struct FMFontFamilyInstance { - FMFontFamily fontFamily; - FMFontStyle fontStyle; -}; -typedef struct FMFontFamilyInstance FMFontFamilyInstance; -struct FMFontFamilyIterator { - UInt32 reserved[16]; -}; -typedef struct FMFontFamilyIterator FMFontFamilyIterator; -struct FMFontIterator { - UInt32 reserved[16]; -}; -typedef struct FMFontIterator FMFontIterator; -struct FMFontFamilyInstanceIterator { - UInt32 reserved[16]; -}; -typedef struct FMFontFamilyInstanceIterator FMFontFamilyInstanceIterator; -enum { - kInvalidGeneration = 0, - kInvalidFontFamily = -1, - kInvalidFont = 0 -}; - -enum { - kFMCurrentFilterFormat = 0 -}; - -typedef UInt32 FMFilterSelector; -enum { - kFMFontTechnologyFilterSelector = 1, - kFMFontContainerFilterSelector = 2, - kFMGenerationFilterSelector = 3, - kFMFontFamilyCallbackFilterSelector = 4, - kFMFontCallbackFilterSelector = 5, - kFMFontDirectoryFilterSelector = 6, - kFMFontFileRefFilterSelector = 10 -}; - -enum { - kFMTrueTypeFontTechnology = 'true', - kFMPostScriptFontTechnology = 'typ1' -}; - -typedef OSStatus ( * FMFontFamilyCallbackFilterProcPtr)(FMFontFamily iFontFamily, void *iRefCon); -typedef OSStatus ( * FMFontCallbackFilterProcPtr)(FMFont iFont, void *iRefCon); -typedef FMFontFamilyCallbackFilterProcPtr FMFontFamilyCallbackFilterUPP; -typedef FMFontCallbackFilterProcPtr FMFontCallbackFilterUPP; -extern FMFontFamilyCallbackFilterUPP -NewFMFontFamilyCallbackFilterUPP(FMFontFamilyCallbackFilterProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern FMFontCallbackFilterUPP -NewFMFontCallbackFilterUPP(FMFontCallbackFilterProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -DisposeFMFontFamilyCallbackFilterUPP(FMFontFamilyCallbackFilterUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern void -DisposeFMFontCallbackFilterUPP(FMFontCallbackFilterUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -InvokeFMFontFamilyCallbackFilterUPP( - FMFontFamily iFontFamily, - void * iRefCon, - FMFontFamilyCallbackFilterUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -InvokeFMFontCallbackFilterUPP( - FMFont iFont, - void * iRefCon, - FMFontCallbackFilterUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - inline FMFontFamilyCallbackFilterUPP NewFMFontFamilyCallbackFilterUPP(FMFontFamilyCallbackFilterProcPtr userRoutine) { return userRoutine; } - inline FMFontCallbackFilterUPP NewFMFontCallbackFilterUPP(FMFontCallbackFilterProcPtr userRoutine) { return userRoutine; } - inline void DisposeFMFontFamilyCallbackFilterUPP(FMFontFamilyCallbackFilterUPP) { } - inline void DisposeFMFontCallbackFilterUPP(FMFontCallbackFilterUPP) { } - inline OSStatus InvokeFMFontFamilyCallbackFilterUPP(FMFontFamily iFontFamily, void * iRefCon, FMFontFamilyCallbackFilterUPP userUPP) { return (*userUPP)(iFontFamily, iRefCon); } - inline OSStatus InvokeFMFontCallbackFilterUPP(FMFont iFont, void * iRefCon, FMFontCallbackFilterUPP userUPP) { return (*userUPP)(iFont, iRefCon); } -struct FMFontDirectoryFilter { - SInt16 fontFolderDomain; - UInt32 reserved[2]; -}; -typedef struct FMFontDirectoryFilter FMFontDirectoryFilter; - - - - -struct FMFilter { - UInt32 format; - FMFilterSelector selector; - union { - FourCharCode fontTechnologyFilter; - ATSFSSpec fontContainerFilter; - FMGeneration generationFilter; - FMFontFamilyCallbackFilterUPP fontFamilyCallbackFilter; - FMFontCallbackFilterUPP fontCallbackFilter; - FMFontDirectoryFilter fontDirectoryFilter; - const FSRef * fontFileRefFilter; - } filter; -}; -typedef struct FMFilter FMFilter; - -typedef OptionBits ATSOptionFlags; -typedef UInt32 ATSGeneration; -typedef UInt32 ATSFontContainerRef; -typedef UInt32 ATSFontFamilyRef; - -typedef UInt32 ATSFontRef; - - -typedef UInt16 ATSGlyphRef; -typedef CGFloat ATSFontSize; -typedef UInt32 ATSFontFormat; -enum { - kATSFontFormatUnspecified = 0 -}; - -enum { - kATSGenerationUnspecified = 0, - kATSFontContainerRefUnspecified = 0, - kATSFontFamilyRefUnspecified = 0, - kATSFontRefUnspecified = 0 -}; - - - - - -struct ATSFontMetrics { - UInt32 version; - CGFloat ascent; - - CGFloat descent; - - CGFloat leading; - CGFloat avgAdvanceWidth; - CGFloat maxAdvanceWidth; - CGFloat minLeftSideBearing; - CGFloat minRightSideBearing; - CGFloat stemWidth; - CGFloat stemHeight; - CGFloat capHeight; - CGFloat xHeight; - CGFloat italicAngle; - CGFloat underlinePosition; - CGFloat underlineThickness; -}; -typedef struct ATSFontMetrics ATSFontMetrics; -enum { - kATSItalicQDSkew = (1 << 16) / 4, - kATSBoldQDStretch = (1 << 16) * 3 / 2, - kATSRadiansFactor = 1144 -}; - - -typedef UInt16 ATSCurveType; -enum { - kATSCubicCurveType = 0x0001, - kATSQuadCurveType = 0x0002, - kATSOtherCurveType = 0x0003 -}; - - - - - - -enum { - kATSDeletedGlyphcode = 0xFFFF -}; - -struct ATSUCurvePath { - UInt32 vectors; - UInt32 controlBits[1]; - ATSPoint vector[1]; -}; -typedef struct ATSUCurvePath ATSUCurvePath; -struct ATSUCurvePaths { - UInt32 contours; - ATSUCurvePath contour[1]; -}; -typedef struct ATSUCurvePaths ATSUCurvePaths; - -struct ATSGlyphIdealMetrics { - ATSPoint advance; - ATSPoint sideBearing; - ATSPoint otherSideBearing; -}; -typedef struct ATSGlyphIdealMetrics ATSGlyphIdealMetrics; - -struct ATSGlyphScreenMetrics { - ATSPoint deviceAdvance; - ATSPoint topLeft; - UInt32 height; - UInt32 width; - ATSPoint sideBearing; - ATSPoint otherSideBearing; -}; -typedef struct ATSGlyphScreenMetrics ATSGlyphScreenMetrics; - - -typedef ATSGlyphRef GlyphID; - -#pragma pack(pop) - - -} -extern "C" { - - -#pragma pack(push, 2) - - - - - - - -enum { - kATSUseGlyphAdvance = 0x7FFFFFFF, - kATSUseLineHeight = 0x7FFFFFFF, - kATSNoTracking = (int)0x80000000 -}; -enum { - - - - - - - kATSUseCaretOrigins = 0, - - - - - - - kATSUseDeviceOrigins = 1, - kATSUseFractionalOrigins = 2, - kATSUseOriginFlags = 3 -}; -typedef UInt32 ATSULayoutOperationSelector; -enum { - - - - - kATSULayoutOperationNone = 0x00000000, - - - - - kATSULayoutOperationJustification = 0x00000001, - - - - - kATSULayoutOperationMorph = 0x00000002, - - - - - kATSULayoutOperationKerningAdjustment = 0x00000004, - - - - - kATSULayoutOperationBaselineAdjustment = 0x00000008, - - - - - kATSULayoutOperationTrackingAdjustment = 0x00000010, - - - - - - kATSULayoutOperationPostLayoutAdjustment = 0x00000020, - kATSULayoutOperationAppleReserved = (UInt32)0xFFFFFFC0 -}; -typedef UInt32 ATSULayoutOperationCallbackStatus; -enum { - - - - - - - kATSULayoutOperationCallbackStatusHandled = 0x00000000, - - - - - - - kATSULayoutOperationCallbackStatusContinue = 0x00000001 -}; -typedef UInt32 ATSLineLayoutOptions; -enum { - - - - - kATSLineNoLayoutOptions = 0x00000000, - - - - - kATSLineIsDisplayOnly = 0x00000001, - - - - - kATSLineHasNoHangers = 0x00000002, - - - - - kATSLineHasNoOpticalAlignment = 0x00000004, - - - - - kATSLineKeepSpacesOutOfMargin = 0x00000008, - - - - - kATSLineNoSpecialJustification = 0x00000010, - - - - - - kATSLineLastNoJustification = 0x00000020, - - - - - - kATSLineFractDisable = 0x00000040, - - - - - - kATSLineImposeNoAngleForEnds = 0x00000080, - - - - - - kATSLineFillOutToWidth = 0x00000100, - - - - - - kATSLineTabAdjustEnabled = 0x00000200, - - - - - - kATSLineIgnoreFontLeading = 0x00000400, - - - - - - kATSLineApplyAntiAliasing = 0x00000800, - - - - - - kATSLineNoAntiAliasing = 0x00001000, - - - - - - - kATSLineDisableNegativeJustification = 0x00002000, - - - - - - - - kATSLineDisableAutoAdjustDisplayPos = 0x00004000, - - - - - - kATSLineUseQDRendering = 0x00008000, - - - - - kATSLineDisableAllJustification = 0x00010000, - - - - - kATSLineDisableAllGlyphMorphing = 0x00020000, - - - - - kATSLineDisableAllKerningAdjustments = 0x00040000, - - - - - kATSLineDisableAllBaselineAdjustments = 0x00080000, - - - - - kATSLineDisableAllTrackingAdjustments = 0x00100000, - - - - - kATSLineDisableAllLayoutOperations = kATSLineDisableAllJustification | kATSLineDisableAllGlyphMorphing | kATSLineDisableAllKerningAdjustments | kATSLineDisableAllBaselineAdjustments | kATSLineDisableAllTrackingAdjustments, - - - - - - kATSLineUseDeviceMetrics = 0x01000000, - - - - - - - kATSLineBreakToNearestCharacter = 0x02000000, - - - - - - kATSLineAppleReserved = (UInt32)0xFCE00000 -}; -typedef UInt32 ATSStyleRenderingOptions; -enum { - - - - - kATSStyleNoOptions = 0x00000000, - - - - - - kATSStyleNoHinting = 0x00000001, - - - - - - - kATSStyleApplyAntiAliasing = 0x00000002, - - - - - - - kATSStyleNoAntiAliasing = 0x00000004, - - - - - - kATSStyleAppleReserved = (UInt32)0xFFFFFFF8, - - - - - - - kATSStyleApplyHints = kATSStyleNoOptions -}; -typedef UInt32 ATSGlyphInfoFlags; -enum { - - - - - - kATSGlyphInfoAppleReserved = 0x1FFBFFE8, - - - - - kATSGlyphInfoIsAttachment = (UInt32)0x80000000, - - - - - kATSGlyphInfoIsLTHanger = 0x40000000, - - - - - kATSGlyphInfoIsRBHanger = 0x20000000, - - - - - - kATSGlyphInfoTerminatorGlyph = 0x00080000, - - - - - kATSGlyphInfoIsWhiteSpace = 0x00040000, - - - - - kATSGlyphInfoHasImposedWidth = 0x00000010, - - - - - - - - kATSGlyphInfoByteSizeMask = 0x00000007 -}; -struct ATSLayoutRecord { - - - - - ATSGlyphRef glyphID; - - - - - ATSGlyphInfoFlags flags; - - - - - ByteCount originalOffset; - - - - - Fixed realPos; -}; -typedef struct ATSLayoutRecord ATSLayoutRecord; -struct ATSTrapezoid { - FixedPoint upperLeft; - FixedPoint upperRight; - FixedPoint lowerRight; - FixedPoint lowerLeft; -}; -typedef struct ATSTrapezoid ATSTrapezoid; -struct ATSJustWidthDeltaEntryOverride { - - - - - Fixed beforeGrowLimit; - - - - - Fixed beforeShrinkLimit; - - - - - Fixed afterGrowLimit; - - - - - Fixed afterShrinkLimit; - - - - - JustificationFlags growFlags; - - - - - JustificationFlags shrinkFlags; -}; -typedef struct ATSJustWidthDeltaEntryOverride ATSJustWidthDeltaEntryOverride; - -typedef ATSJustWidthDeltaEntryOverride ATSJustPriorityWidthDeltaOverrides[4]; -typedef struct ATSGlyphVector* ATSULineRef; -typedef OSStatus ( * ATSUDirectLayoutOperationOverrideProcPtr)(ATSULayoutOperationSelector iCurrentOperation, ATSULineRef iLineRef, URefCon iRefCon, void *iOperationCallbackParameterPtr, ATSULayoutOperationCallbackStatus *oCallbackStatus); -typedef ATSUDirectLayoutOperationOverrideProcPtr ATSUDirectLayoutOperationOverrideUPP; -extern ATSUDirectLayoutOperationOverrideUPP -NewATSUDirectLayoutOperationOverrideUPP(ATSUDirectLayoutOperationOverrideProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -extern void -DisposeATSUDirectLayoutOperationOverrideUPP(ATSUDirectLayoutOperationOverrideUPP userUPP) __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); -extern OSStatus -InvokeATSUDirectLayoutOperationOverrideUPP( - ATSULayoutOperationSelector iCurrentOperation, - ATSULineRef iLineRef, - URefCon iRefCon, - void * iOperationCallbackParameterPtr, - ATSULayoutOperationCallbackStatus * oCallbackStatus, - ATSUDirectLayoutOperationOverrideUPP userUPP) __attribute__((availability(macosx,introduced=10.2,deprecated=10.7))); - - - - inline ATSUDirectLayoutOperationOverrideUPP NewATSUDirectLayoutOperationOverrideUPP(ATSUDirectLayoutOperationOverrideProcPtr userRoutine) { return userRoutine; } - inline void DisposeATSUDirectLayoutOperationOverrideUPP(ATSUDirectLayoutOperationOverrideUPP) { } - inline OSStatus InvokeATSUDirectLayoutOperationOverrideUPP(ATSULayoutOperationSelector iCurrentOperation, ATSULineRef iLineRef, URefCon iRefCon, void * iOperationCallbackParameterPtr, ATSULayoutOperationCallbackStatus * oCallbackStatus, ATSUDirectLayoutOperationOverrideUPP userUPP) { return (*userUPP)(iCurrentOperation, iLineRef, iRefCon, iOperationCallbackParameterPtr, oCallbackStatus); } -struct ATSULayoutOperationOverrideSpecifier { - - - - - - - ATSULayoutOperationSelector operationSelector; - ATSUDirectLayoutOperationOverrideUPP overrideUPP; - -}; -typedef struct ATSULayoutOperationOverrideSpecifier ATSULayoutOperationOverrideSpecifier; - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - -struct sfntDirectoryEntry { - FourCharCode tableTag; - UInt32 checkSum; - UInt32 offset; - UInt32 length; -}; -typedef struct sfntDirectoryEntry sfntDirectoryEntry; - -struct sfntDirectory { - FourCharCode format; - UInt16 numOffsets; - UInt16 searchRange; - UInt16 entrySelector; - UInt16 rangeShift; - sfntDirectoryEntry table[1]; -}; -typedef struct sfntDirectory sfntDirectory; -enum { - sizeof_sfntDirectory = 12 -}; - - -enum { - cmapFontTableTag = 'cmap' -}; - -enum { - kFontUnicodePlatform = 0, - kFontMacintoshPlatform = 1, - kFontReservedPlatform = 2, - kFontMicrosoftPlatform = 3, - kFontCustomPlatform = 4 -}; - -enum { - kFontUnicodeDefaultSemantics = 0, - kFontUnicodeV1_1Semantics = 1, - kFontISO10646_1993Semantics = 2, - kFontUnicodeV2_0BMPOnlySemantics = 3, - kFontUnicodeV2_0FullCoverageSemantics = 4, - kFontUnicodeV4_0VariationSequenceSemantics = 5, - kFontUnicode_FullRepertoire = 6 -}; - -enum { - kFontRomanScript = 0, - kFontJapaneseScript = 1, - kFontTraditionalChineseScript = 2, - kFontChineseScript = kFontTraditionalChineseScript, - kFontKoreanScript = 3, - kFontArabicScript = 4, - kFontHebrewScript = 5, - kFontGreekScript = 6, - kFontCyrillicScript = 7, - kFontRussian = kFontCyrillicScript, - kFontRSymbolScript = 8, - kFontDevanagariScript = 9, - kFontGurmukhiScript = 10, - kFontGujaratiScript = 11, - kFontOriyaScript = 12, - kFontBengaliScript = 13, - kFontTamilScript = 14, - kFontTeluguScript = 15, - kFontKannadaScript = 16, - kFontMalayalamScript = 17, - kFontSinhaleseScript = 18, - kFontBurmeseScript = 19, - kFontKhmerScript = 20, - kFontThaiScript = 21, - kFontLaotianScript = 22, - kFontGeorgianScript = 23, - kFontArmenianScript = 24, - kFontSimpleChineseScript = 25, - kFontTibetanScript = 26, - kFontMongolianScript = 27, - kFontGeezScript = 28, - kFontEthiopicScript = kFontGeezScript, - kFontAmharicScript = kFontGeezScript, - kFontSlavicScript = 29, - kFontEastEuropeanRomanScript = kFontSlavicScript, - kFontVietnameseScript = 30, - kFontExtendedArabicScript = 31, - kFontSindhiScript = kFontExtendedArabicScript, - kFontUninterpretedScript = 32 -}; - -enum { - kFontMicrosoftSymbolScript = 0, - kFontMicrosoftStandardScript = 1, - kFontMicrosoftUCS4Script = 10 -}; - - -enum { - kFontCustom8BitScript = 0, - kFontCustom816BitScript = 1, - kFontCustom16BitScript = 2 -}; - - -enum { - kFontEnglishLanguage = 0, - kFontFrenchLanguage = 1, - kFontGermanLanguage = 2, - kFontItalianLanguage = 3, - kFontDutchLanguage = 4, - kFontSwedishLanguage = 5, - kFontSpanishLanguage = 6, - kFontDanishLanguage = 7, - kFontPortugueseLanguage = 8, - kFontNorwegianLanguage = 9, - kFontHebrewLanguage = 10, - kFontJapaneseLanguage = 11, - kFontArabicLanguage = 12, - kFontFinnishLanguage = 13, - kFontGreekLanguage = 14, - kFontIcelandicLanguage = 15, - kFontMalteseLanguage = 16, - kFontTurkishLanguage = 17, - kFontCroatianLanguage = 18, - kFontTradChineseLanguage = 19, - kFontUrduLanguage = 20, - kFontHindiLanguage = 21, - kFontThaiLanguage = 22, - kFontKoreanLanguage = 23, - kFontLithuanianLanguage = 24, - kFontPolishLanguage = 25, - kFontHungarianLanguage = 26, - kFontEstonianLanguage = 27, - kFontLettishLanguage = 28, - kFontLatvianLanguage = kFontLettishLanguage, - kFontSaamiskLanguage = 29, - kFontLappishLanguage = kFontSaamiskLanguage, - kFontFaeroeseLanguage = 30, - kFontFarsiLanguage = 31, - kFontPersianLanguage = kFontFarsiLanguage, - kFontRussianLanguage = 32, - kFontSimpChineseLanguage = 33, - kFontFlemishLanguage = 34, - kFontIrishLanguage = 35, - kFontAlbanianLanguage = 36, - kFontRomanianLanguage = 37, - kFontCzechLanguage = 38, - kFontSlovakLanguage = 39, - kFontSlovenianLanguage = 40, - kFontYiddishLanguage = 41, - kFontSerbianLanguage = 42, - kFontMacedonianLanguage = 43, - kFontBulgarianLanguage = 44, - kFontUkrainianLanguage = 45, - kFontByelorussianLanguage = 46, - kFontUzbekLanguage = 47, - kFontKazakhLanguage = 48, - kFontAzerbaijaniLanguage = 49, - kFontAzerbaijanArLanguage = 50, - kFontArmenianLanguage = 51, - kFontGeorgianLanguage = 52, - kFontMoldavianLanguage = 53, - kFontKirghizLanguage = 54, - kFontTajikiLanguage = 55, - kFontTurkmenLanguage = 56, - kFontMongolianLanguage = 57, - kFontMongolianCyrLanguage = 58, - kFontPashtoLanguage = 59, - kFontKurdishLanguage = 60, - kFontKashmiriLanguage = 61, - kFontSindhiLanguage = 62, - kFontTibetanLanguage = 63, - kFontNepaliLanguage = 64, - kFontSanskritLanguage = 65, - kFontMarathiLanguage = 66, - kFontBengaliLanguage = 67, - kFontAssameseLanguage = 68, - kFontGujaratiLanguage = 69, - kFontPunjabiLanguage = 70, - kFontOriyaLanguage = 71, - kFontMalayalamLanguage = 72, - kFontKannadaLanguage = 73, - kFontTamilLanguage = 74, - kFontTeluguLanguage = 75, - kFontSinhaleseLanguage = 76, - kFontBurmeseLanguage = 77, - kFontKhmerLanguage = 78, - kFontLaoLanguage = 79, - kFontVietnameseLanguage = 80, - kFontIndonesianLanguage = 81, - kFontTagalogLanguage = 82, - kFontMalayRomanLanguage = 83, - kFontMalayArabicLanguage = 84, - kFontAmharicLanguage = 85, - kFontTigrinyaLanguage = 86, - kFontGallaLanguage = 87, - kFontOromoLanguage = kFontGallaLanguage, - kFontSomaliLanguage = 88, - kFontSwahiliLanguage = 89, - kFontRuandaLanguage = 90, - kFontRundiLanguage = 91, - kFontChewaLanguage = 92, - kFontMalagasyLanguage = 93, - kFontEsperantoLanguage = 94, - kFontWelshLanguage = 128, - kFontBasqueLanguage = 129, - kFontCatalanLanguage = 130, - kFontLatinLanguage = 131, - kFontQuechuaLanguage = 132, - kFontGuaraniLanguage = 133, - kFontAymaraLanguage = 134, - kFontTatarLanguage = 135, - kFontUighurLanguage = 136, - kFontDzongkhaLanguage = 137, - kFontJavaneseRomLanguage = 138, - kFontSundaneseRomLanguage = 139 -}; - - - -enum { - kFontNoPlatformCode = (unsigned int)(~0), - kFontNoScriptCode = (unsigned int)(~0), - kFontNoLanguageCode = (unsigned int)(~0) -}; - -struct sfntCMapSubHeader { - UInt16 format; - UInt16 length; - UInt16 languageID; -}; -typedef struct sfntCMapSubHeader sfntCMapSubHeader; -enum { - sizeof_sfntCMapSubHeader = 6 -}; - -struct sfntCMapExtendedSubHeader { - UInt16 format; - UInt16 reserved; - UInt32 length; - UInt32 language; -}; -typedef struct sfntCMapExtendedSubHeader sfntCMapExtendedSubHeader; -enum { - sizeof_sfntCMapExtendedSubHeader = 12 -}; - -struct sfntCMapEncoding { - UInt16 platformID; - UInt16 scriptID; - UInt32 offset; -}; -typedef struct sfntCMapEncoding sfntCMapEncoding; -enum { - sizeof_sfntCMapEncoding = 8 -}; - -struct sfntCMapHeader { - UInt16 version; - UInt16 numTables; - sfntCMapEncoding encoding[1]; -}; -typedef struct sfntCMapHeader sfntCMapHeader; -enum { - sizeof_sfntCMapHeader = 4 -}; - - -enum { - nameFontTableTag = 'name' -}; - -enum { - kFontCopyrightName = 0, - kFontFamilyName = 1, - kFontStyleName = 2, - kFontUniqueName = 3, - kFontFullName = 4, - kFontVersionName = 5, - kFontPostscriptName = 6, - kFontTrademarkName = 7, - kFontManufacturerName = 8, - kFontDesignerName = 9, - kFontDescriptionName = 10, - kFontVendorURLName = 11, - kFontDesignerURLName = 12, - kFontLicenseDescriptionName = 13, - kFontLicenseInfoURLName = 14, - kFontPreferredFamilyName = 16, - kFontPreferredSubfamilyName = 17, - kFontMacCompatibleFullName = 18, - kFontSampleTextName = 19, - kFontPostScriptCIDName = 20, - kFontLastReservedName = 255 -}; - - - -enum { - kFontNoNameCode = (unsigned int)(~0) -}; - -struct sfntNameRecord { - UInt16 platformID; - UInt16 scriptID; - UInt16 languageID; - UInt16 nameID; - UInt16 length; - UInt16 offset; -}; -typedef struct sfntNameRecord sfntNameRecord; -enum { - sizeof_sfntNameRecord = 12 -}; - -struct sfntNameHeader { - UInt16 format; - UInt16 count; - UInt16 stringOffset; - sfntNameRecord rec[1]; -}; -typedef struct sfntNameHeader sfntNameHeader; -enum { - sizeof_sfntNameHeader = 6 -}; - - -enum { - variationFontTableTag = 'fvar' -}; - - -struct sfntVariationAxis { - FourCharCode axisTag; - Fixed minValue; - Fixed defaultValue; - Fixed maxValue; - SInt16 flags; - SInt16 nameID; -}; -typedef struct sfntVariationAxis sfntVariationAxis; -enum { - sizeof_sfntVariationAxis = 20 -}; - - -struct sfntInstance { - SInt16 nameID; - SInt16 flags; - Fixed coord[1]; - -}; -typedef struct sfntInstance sfntInstance; -enum { - sizeof_sfntInstance = 4 -}; - -struct sfntVariationHeader { - Fixed version; - UInt16 offsetToData; - UInt16 countSizePairs; - UInt16 axisCount; - UInt16 axisSize; - UInt16 instanceCount; - UInt16 instanceSize; - - sfntVariationAxis axis[1]; - sfntInstance instance[1]; -}; -typedef struct sfntVariationHeader sfntVariationHeader; -enum { - sizeof_sfntVariationHeader = 16 -}; - - -enum { - descriptorFontTableTag = 'fdsc' -}; - -struct sfntFontDescriptor { - FourCharCode name; - Fixed value; -}; -typedef struct sfntFontDescriptor sfntFontDescriptor; -struct sfntDescriptorHeader { - Fixed version; - SInt32 descriptorCount; - sfntFontDescriptor descriptor[1]; -}; -typedef struct sfntDescriptorHeader sfntDescriptorHeader; -enum { - sizeof_sfntDescriptorHeader = 8 -}; - - -enum { - featureFontTableTag = 'feat' -}; - -struct sfntFeatureName { - UInt16 featureType; - UInt16 settingCount; - SInt32 offsetToSettings; - UInt16 featureFlags; - SInt16 nameID; -}; -typedef struct sfntFeatureName sfntFeatureName; -struct sfntFontFeatureSetting { - UInt16 setting; - SInt16 nameID; -}; -typedef struct sfntFontFeatureSetting sfntFontFeatureSetting; -struct sfntFontRunFeature { - UInt16 featureType; - UInt16 setting; -}; -typedef struct sfntFontRunFeature sfntFontRunFeature; -struct sfntFeatureHeader { - SInt32 version; - UInt16 featureNameCount; - UInt16 featureSetCount; - SInt32 reserved; - sfntFeatureName names[1]; - sfntFontFeatureSetting settings[1]; - sfntFontRunFeature runs[1]; -}; -typedef struct sfntFeatureHeader sfntFeatureHeader; - -enum { - os2FontTableTag = 'OS/2' -}; - - -enum { - nonGlyphID = 65535 -}; - - - -typedef UInt32 FontNameCode; - -typedef UInt32 FontPlatformCode; -typedef UInt32 FontScriptCode; -typedef UInt32 FontLanguageCode; - - - - -struct FontVariation { - FourCharCode name; - Fixed value; -}; -typedef struct FontVariation FontVariation; - -#pragma pack(pop) - - -} - - - - -enum { - kFontNoPlatform = (unsigned int)(~0), - kFontNoScript = (unsigned int)(~0), - kFontNoLanguage = (unsigned int)(~0), - kFontNoName = (unsigned int)(~0) -}; -extern "C" { - - -#pragma pack(push, 2) - - - - - -enum { - kATSOptionFlagsDefault = kNilOptions, - kATSOptionFlagsComposeFontPostScriptName = 1 << 0, - kATSOptionFlagsUseDataForkAsResourceFork = 1 << 8, - kATSOptionFlagsUseResourceFork = 2 << 8, - kATSOptionFlagsUseDataFork = 3 << 8 -}; - -enum { - kATSIterationCompleted = -980L, - kATSInvalidFontFamilyAccess = -981L, - kATSInvalidFontAccess = -982L, - kATSIterationScopeModified = -983L, - kATSInvalidFontTableAccess = -984L, - kATSInvalidFontContainerAccess = -985L, - kATSInvalidGlyphAccess = -986L -}; - - -typedef UInt32 ATSFontContext; -enum { - kATSFontContextUnspecified = 0, - kATSFontContextGlobal = 1, - kATSFontContextLocal = 2 -}; - -enum { - kATSOptionFlagsActivateDisabled = 0x00000001 << 5, - kATSOptionFlagsProcessSubdirectories = 0x00000001 << 6, - kATSOptionFlagsDoNotNotify = 0x00000001 << 7, - kATSOptionFlagsRecordPersistently = 0x00000001 << 18 -}; - - -enum { - kATSOptionFlagsIterateByPrecedenceMask = 0x00000001 << 5, - kATSOptionFlagsIncludeDisabledMask = 0x00000001 << 7, - kATSOptionFlagsIterationScopeMask = 0x00000007 << 12, - kATSOptionFlagsDefaultScope = 0x00000000 << 12, - kATSOptionFlagsUnRestrictedScope = 0x00000001 << 12, - kATSOptionFlagsRestrictedScope = 0x00000002 << 12 -}; - -typedef OSStatus ( * ATSFontFamilyApplierFunction)(ATSFontFamilyRef iFamily, void *iRefCon); -typedef OSStatus ( * ATSFontApplierFunction)(ATSFontRef iFont, void *iRefCon); -typedef struct ATSFontFamilyIterator_* ATSFontFamilyIterator; -typedef struct ATSFontIterator_* ATSFontIterator; -enum { - kATSFontFilterCurrentVersion = 0 -}; - -enum ATSFontFilterSelector { - kATSFontFilterSelectorUnspecified = 0, - kATSFontFilterSelectorGeneration = 3, - kATSFontFilterSelectorFontFamily = 7, - kATSFontFilterSelectorFontFamilyApplierFunction = 8, - kATSFontFilterSelectorFontApplierFunction = 9, - kATSFileReferenceFilterSelector = 10 -}; -typedef enum ATSFontFilterSelector ATSFontFilterSelector; - -struct ATSFontFilter { - UInt32 version; - ATSFontFilterSelector filterSelector; - union { - ATSGeneration generationFilter; - ATSFontFamilyRef fontFamilyFilter; - ATSFontFamilyApplierFunction fontFamilyApplierFunctionFilter; - ATSFontApplierFunction fontApplierFunctionFilter; - const FSRef * fontFileRefFilter; - } filter; -}; -typedef struct ATSFontFilter ATSFontFilter; - -typedef struct ATSFontNotificationRef_* ATSFontNotificationRef; -typedef struct ATSFontNotificationInfoRef_* ATSFontNotificationInfoRef; -enum ATSFontNotifyOption { - - - - - kATSFontNotifyOptionDefault = 0, - kATSFontNotifyOptionReceiveWhileSuspended = 1L << 0 -}; -typedef enum ATSFontNotifyOption ATSFontNotifyOption; -enum ATSFontNotifyAction { - kATSFontNotifyActionFontsChanged = 1, - kATSFontNotifyActionDirectoriesChanged = 2 -}; -typedef enum ATSFontNotifyAction ATSFontNotifyAction; -typedef void ( * ATSNotificationCallback)(ATSFontNotificationInfoRef info, void *refCon); -extern ATSGeneration -ATSGetGeneration(void) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Register for kCTFontManagerRegisteredFontsChangedNotification notifications"))); -extern OSStatus -ATSFontActivateFromFileReference( - const FSRef * iFile, - ATSFontContext iContext, - ATSFontFormat iFormat, - void * iRefCon, - ATSOptionFlags iOptions, - ATSFontContainerRef * oContainer) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use CTFontManagerRegisterFontsForURL() or CTFontManagerRegisterFontsForURLs()"))); -extern OSStatus -ATSFontActivateFromMemory( - LogicalAddress iData, - ByteCount iLength, - ATSFontContext iContext, - ATSFontFormat iFormat, - void * iReserved, - ATSOptionFlags iOptions, - ATSFontContainerRef * oContainer) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontManagerRegisterFontForData() or CGFontCreateWithDataProvider() w/ CTFontManagerRegisterGraphicsFont()"))); -extern OSStatus -ATSFontDeactivate( - ATSFontContainerRef iContainer, - void * iRefCon, - ATSOptionFlags iOptions) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontManagerUnregisterFontsForURL() or CTFontManagerUnregisterFontsForURLs()"))); -extern OSStatus -ATSFontGetContainerFromFileReference( - const FSRef * iFile, - ATSFontContext iContext, - ATSOptionFlags iOptions, - ATSFontContainerRef * oContainer) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use CTFontCopyAttribute() with kCTFontURLAttribute."))); -extern OSStatus -ATSFontGetContainer( - ATSFontRef iFont, - ATSOptionFlags iOptions, - ATSFontContainerRef * oContainer) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use CTFontCopyAttribute() with kCTFontURLAttribute."))); -extern OSStatus -ATSFontSetEnabled( - ATSFontRef iFont, - ATSOptionFlags iOptions, - Boolean iEnabled) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use CTFontManagerEnableFontDescriptors()"))); -extern Boolean -ATSFontIsEnabled(ATSFontRef iFont) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use CTFontCopyAttribute() with kCTFontEnabledAttribute"))); -extern OSStatus -ATSFontFamilyApplyFunction( - ATSFontFamilyApplierFunction iFunction, - void * iRefCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontManagerCopyAvailableFontFamilyNames()"))); -extern OSStatus -ATSFontFamilyIteratorCreate( - ATSFontContext iContext, - const ATSFontFilter * iFilter, - void * iRefCon, - ATSOptionFlags iOptions, - ATSFontFamilyIterator * ioIterator) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontManagerCopyAvailableFontFamilyNames()"))); -extern OSStatus -ATSFontFamilyIteratorRelease(ATSFontFamilyIterator * ioIterator) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -ATSFontFamilyIteratorReset( - ATSFontContext iContext, - const ATSFontFilter * iFilter, - void * iRefCon, - ATSOptionFlags iOptions, - ATSFontFamilyIterator * ioIterator) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -ATSFontFamilyIteratorNext( - ATSFontFamilyIterator iIterator, - ATSFontFamilyRef * oFamily) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ATSFontFamilyRef -ATSFontFamilyFindFromName( - CFStringRef iName, - ATSOptionFlags iOptions) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontDescriptorCreateMatchingFontDescriptors() with kCTFontFamilyNameAttribute"))); -extern ATSGeneration -ATSFontFamilyGetGeneration(ATSFontFamilyRef iFamily) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Register for kCTFontManagerRegisteredFontsChangedNotification notifications"))); -extern OSStatus -ATSFontFamilyGetName( - ATSFontFamilyRef iFamily, - ATSOptionFlags iOptions, - CFStringRef * oName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCopyFamilyName()"))); -extern TextEncoding -ATSFontFamilyGetEncoding(ATSFontFamilyRef iFamily) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontGetStringEncoding()"))); -extern OSStatus -ATSFontApplyFunction( - ATSFontApplierFunction iFunction, - void * iRefCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCollectionCreateFromAvailableFonts()"))); -extern OSStatus -ATSFontIteratorCreate( - ATSFontContext iContext, - const ATSFontFilter * iFilter, - void * iRefCon, - ATSOptionFlags iOptions, - ATSFontIterator * ioIterator) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCollectionCreateFromAvailableFonts()"))); -extern OSStatus -ATSFontIteratorRelease(ATSFontIterator * ioIterator) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -ATSFontIteratorReset( - ATSFontContext iContext, - const ATSFontFilter * iFilter, - void * iRefCon, - ATSOptionFlags iOptions, - ATSFontIterator * ioIterator) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSStatus -ATSFontIteratorNext( - ATSFontIterator iIterator, - ATSFontRef * oFont) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern ATSFontRef -ATSFontFindFromName( - CFStringRef iName, - ATSOptionFlags iOptions) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCreateWithName()"))); -extern ATSFontRef -ATSFontFindFromPostScriptName( - CFStringRef iName, - ATSOptionFlags iOptions) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCreateWithName()"))); -extern OSStatus -ATSFontFindFromContainer( - ATSFontContainerRef iContainer, - ATSOptionFlags iOptions, - ItemCount iCount, - ATSFontRef ioArray[], - ItemCount * oCount) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontDescriptorCreateMatchingFontDescriptors() with kCTFontURLAttribute or use CTFontManagerCreateFontDescriptorsFromURL()"))); -extern ATSGeneration -ATSFontGetGeneration(ATSFontRef iFont) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Register for kCTFontManagerRegisteredFontsChangedNotification notifications"))); -extern OSStatus -ATSFontGetName( - ATSFontRef iFont, - ATSOptionFlags iOptions, - CFStringRef * oName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCopyFullName()"))); -extern OSStatus -ATSFontGetPostScriptName( - ATSFontRef iFont, - ATSOptionFlags iOptions, - CFStringRef * oName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCopyPostScriptName()"))); -extern OSStatus -ATSFontGetTableDirectory( - ATSFontRef iFont, - ByteCount iBufferSize, - void * ioBuffer, - ByteCount * oSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCopyAvailableTables()"))); -extern OSStatus -ATSFontGetTable( - ATSFontRef iFont, - FourCharCode iTag, - ByteOffset iOffset, - ByteCount iBufferSize, - void * ioBuffer, - ByteCount * oSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCopyTable()"))); -extern OSStatus -ATSFontGetHorizontalMetrics( - ATSFontRef iFont, - ATSOptionFlags iOptions, - ATSFontMetrics * oMetrics) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontGetXHeight(), CTFontGetAscent(), and friends to find a specific metric."))); -extern OSStatus -ATSFontGetVerticalMetrics( - ATSFontRef iFont, - ATSOptionFlags iOptions, - ATSFontMetrics * oMetrics) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontGetXHeight(), CTFontGetAscent(), and friends to find a specific metric."))); -extern ATSFontFamilyRef -ATSFontFamilyFindFromQuickDrawName(ConstStr255Param iName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCreateWithQuickdrawInstance()"))); -extern OSStatus -ATSFontFamilyGetQuickDrawName( - ATSFontFamilyRef iFamily, - Str255 oName) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="QuickDraw is deprecated"))); -extern OSStatus -ATSFontGetFileReference( - ATSFontRef iFont, - FSRef * oFile) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="Use CTFontCopyAttribute() with kCTFontURLAttribute."))); -extern OSStatus -ATSFontGetFontFamilyResource( - ATSFontRef iFont, - ByteCount iBufferSize, - void * ioBuffer, - ByteCount * oSize) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8,message="QuickDraw is deprecated"))); -extern OSStatus -ATSFontNotify( - ATSFontNotifyAction action, - void * info) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8,message="Register for kCTFontManagerRegisteredFontsChangedNotification notifications"))); -extern OSStatus -ATSFontNotificationSubscribe( - ATSNotificationCallback callback, - ATSFontNotifyOption options, - void * iRefcon, - ATSFontNotificationRef * oNotificationRef) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8,message="Register for kCTFontManagerRegisteredFontsChangedNotification notifications"))); -extern OSStatus -ATSFontNotificationUnsubscribe(ATSFontNotificationRef notificationRef) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8,message="Unregister for kCTFontManagerRegisteredFontsChangedNotification notifications"))); -struct ATSFontQuerySourceContext { - - - - - - UInt32 version; - - - - - - void * refCon; - - - - - CFAllocatorRetainCallBack retain; - - - - - CFAllocatorReleaseCallBack release; -}; -typedef struct ATSFontQuerySourceContext ATSFontQuerySourceContext; - - - - - - - -enum ATSFontQueryMessageID { - - - - - - - - kATSQueryActivateFontMessage = 'atsa' -}; -typedef enum ATSFontQueryMessageID ATSFontQueryMessageID; -typedef CFPropertyListRef ( * ATSFontQueryCallback)(ATSFontQueryMessageID msgid, CFPropertyListRef data, void *refCon); -extern CFRunLoopSourceRef -ATSCreateFontQueryRunLoopSource( - CFIndex queryOrder, - CFIndex sourceOrder, - ATSFontQueryCallback callout, - const ATSFontQuerySourceContext * context) __attribute__((availability(macosx,introduced=10.2,deprecated=10.8,message="Use CTFontManagerCreateFontRequestRunLoopSource()"))); -enum { - - - - - - - kATSFontAutoActivationDefault = 0, - kATSFontAutoActivationDisabled = 1, - kATSFontAutoActivationEnabled = 2, - - - - - - kATSFontAutoActivationAsk = 4 -}; - - -typedef UInt32 ATSFontAutoActivationSetting; -extern OSStatus -ATSFontSetGlobalAutoActivationSetting(ATSFontAutoActivationSetting iSetting) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use CTFontManagerSetAutoActivationSetting() with kCTFontManagerBundleIdentifier"))); -extern ATSFontAutoActivationSetting -ATSFontGetGlobalAutoActivationSetting(void) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use CTFontManagerGetAutoActivationSetting() with kCTFontManagerBundleIdentifier"))); -extern OSStatus -ATSFontSetAutoActivationSettingForApplication( - ATSFontAutoActivationSetting iSetting, - CFURLRef iApplicationFileURL) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use CTFontManagerSetAutoActivationSetting()"))); -extern ATSFontAutoActivationSetting -ATSFontGetAutoActivationSettingForApplication(CFURLRef iApplicationFileURL) __attribute__((availability(macosx,introduced=10.5,deprecated=10.8,message="Use CTFontManagerGetAutoActivationSetting()"))); - - - - - - - -#pragma pack(pop) - - -} - - - -extern "C" { -} -extern "C" { - - - - -typedef const struct ColorSyncProfile* ColorSyncProfileRef; - -typedef struct ColorSyncProfile* ColorSyncMutableProfileRef; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncGenericGrayProfile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncGenericGrayGamma22Profile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncGenericRGBProfile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncGenericCMYKProfile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDisplayP3Profile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSRGBProfile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncAdobeRGB1998Profile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncGenericLabProfile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncGenericXYZProfile; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncACESCGLinearProfile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDCIP3Profile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncITUR709Profile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncITUR2020Profile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncROMMRGBProfile; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileHeader; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileClass; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileColorSpace; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfilePCS; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileURL; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileDescription; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileMD5Digest; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigAToB0Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigAToB1Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigAToB2Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigBToA0Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigBToA1Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigBToA2Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigCmykData; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigGrayData; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigLabData; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigRgbData; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigXYZData; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigAbstractClass; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigBlueTRCTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigBlueColorantTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigMediaBlackPointTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigCopyrightTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigProfileDescriptionTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigDeviceModelDescTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigDeviceMfgDescTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigGreenTRCTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigGreenColorantTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigGamutTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigGrayTRCTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigLinkClass; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigDisplayClass; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigNamedColor2Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigNamedColorClass; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigPreview0Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigPreview1Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigPreview2Tag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigOutputClass; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigProfileSequenceDescTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigRedTRCTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigRedColorantTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigInputClass; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigColorSpaceClass; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigTechnologyTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigViewingConditionsTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigViewingCondDescTag; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncSigMediaWhitePointTag; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileComputerDomain; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileUserDomain; - - - -__attribute__((visibility("default"))) extern CFTypeID ColorSyncProfileGetTypeID(void); - - - - -__attribute__((visibility("default"))) extern ColorSyncProfileRef ColorSyncProfileCreate(CFDataRef data, CFErrorRef* error); - - - - - - - -__attribute__((visibility("default"))) extern ColorSyncProfileRef ColorSyncProfileCreateWithURL(CFURLRef url, CFErrorRef* error); - - - - - - - -__attribute__((visibility("default"))) extern ColorSyncProfileRef ColorSyncProfileCreateWithName(CFStringRef name); - - - - - - -__attribute__((visibility("default"))) extern ColorSyncProfileRef ColorSyncProfileCreateWithDisplayID (uint32_t displayID); - - - - - - -__attribute__((visibility("default"))) extern ColorSyncProfileRef ColorSyncProfileCreateDeviceProfile (CFStringRef deviceClass, CFUUIDRef deviceID, CFTypeRef profileID); -__attribute__((visibility("default"))) extern ColorSyncMutableProfileRef ColorSyncProfileCreateMutable(void); - - - - -__attribute__((visibility("default"))) extern ColorSyncMutableProfileRef ColorSyncProfileCreateMutableCopy(ColorSyncProfileRef prof); - - - - - - -__attribute__((visibility("default"))) extern ColorSyncProfileRef ColorSyncProfileCreateLink (CFArrayRef profileInfo, CFDictionaryRef options); -__attribute__((visibility("default"))) extern bool ColorSyncProfileVerify (ColorSyncProfileRef prof, CFErrorRef* errors, CFErrorRef* warnings); -__attribute__((visibility("default"))) extern float ColorSyncProfileEstimateGammaWithDisplayID (const int32_t displayID, CFErrorRef* error); -__attribute__((visibility("default"))) extern float ColorSyncProfileEstimateGamma (ColorSyncProfileRef prof, CFErrorRef* error); -typedef struct { uint8_t digest[16]; } ColorSyncMD5; - -__attribute__((visibility("default"))) extern ColorSyncMD5 ColorSyncProfileGetMD5(ColorSyncProfileRef prof); - - - - - - -__attribute__((visibility("default"))) extern CFDataRef ColorSyncProfileCopyData (ColorSyncProfileRef prof, CFErrorRef* error); - - - - - - - -__attribute__((visibility("default"))) extern CFURLRef ColorSyncProfileGetURL (ColorSyncProfileRef prof, CFErrorRef* error); - - - - - - - -__attribute__((visibility("default"))) extern CFDataRef ColorSyncProfileCopyHeader (ColorSyncProfileRef prof); - - - - - - -__attribute__((visibility("default"))) extern void ColorSyncProfileSetHeader (ColorSyncMutableProfileRef prof, CFDataRef header); - - - - - -__attribute__((visibility("default"))) extern CFStringRef ColorSyncProfileCopyDescriptionString (ColorSyncProfileRef prof); - - - - - - -__attribute__((visibility("default"))) extern CFArrayRef ColorSyncProfileCopyTagSignatures (ColorSyncProfileRef prof); - - - - - - -__attribute__((visibility("default"))) extern bool ColorSyncProfileContainsTag (ColorSyncProfileRef prof, CFStringRef signature); - - - - - - - -__attribute__((visibility("default"))) extern CFDataRef ColorSyncProfileCopyTag (ColorSyncProfileRef prof, CFStringRef signature); - - - - - - - -__attribute__((visibility("default"))) extern void ColorSyncProfileSetTag (ColorSyncMutableProfileRef prof, CFStringRef signature, CFDataRef data); - - - - - - -__attribute__((visibility("default"))) extern void ColorSyncProfileRemoveTag (ColorSyncMutableProfileRef prof, CFStringRef signature); - - - - - - - -__attribute__((visibility("default"))) extern bool ColorSyncProfileGetDisplayTransferFormulaFromVCGT(ColorSyncProfileRef profile, - float* redMin, float* redMax, float* redGamma, - float* greenMin, float* greenMax, float* greenGamma, - float* blueMin, float* blueMax, float* blueGamma); - - - - - -__attribute__((visibility("default"))) extern CFDataRef ColorSyncProfileCreateDisplayTransferTablesFromVCGT(ColorSyncProfileRef profile, size_t *nSamplesPerChannel); -typedef bool (*ColorSyncProfileIterateCallback)(CFDictionaryRef profileInfo, void* userInfo); - - - - - - -__attribute__((visibility("default"))) extern void ColorSyncIterateInstalledProfiles (ColorSyncProfileIterateCallback callBack, - uint32_t * seed, - void* userInfo, - CFErrorRef* error); - - - - - - - -__attribute__((visibility("default"))) extern bool ColorSyncProfileInstall(ColorSyncProfileRef profile, CFStringRef domain, CFStringRef subpath, CFErrorRef* error); -__attribute__((visibility("default"))) extern bool ColorSyncProfileUninstall(ColorSyncProfileRef profile, CFErrorRef* error); -} -extern "C" { - - - - -typedef struct ColorSyncTransform* ColorSyncTransformRef; - -__attribute__((visibility("default"))) extern CFTypeID ColorSyncTransformGetTypeID(void); - - - - -__attribute__((visibility("default"))) extern ColorSyncTransformRef ColorSyncTransformCreate (CFArrayRef profileSequence, CFDictionaryRef options); -__attribute__((visibility("default"))) extern CFTypeRef ColorSyncTransformCopyProperty(ColorSyncTransformRef transform, CFTypeRef key, CFDictionaryRef options); - - - - - - -__attribute__((visibility("default"))) extern void ColorSyncTransformSetProperty(ColorSyncTransformRef transform, CFTypeRef key, CFTypeRef property); - - - - - - -enum ColorSyncDataDepth { - kColorSync1BitGamut = 1, - kColorSync8BitInteger = 2, - kColorSync16BitInteger = 3, - kColorSync16BitFloat = 4, - kColorSync32BitInteger = 5, - kColorSync32BitNamedColorIndex = 6, - kColorSync32BitFloat = 7, - kColorSync10BitInteger = 8 -}; - -typedef enum ColorSyncDataDepth ColorSyncDataDepth; - -enum ColorSyncAlphaInfo { - kColorSyncAlphaNone, - kColorSyncAlphaPremultipliedLast, - kColorSyncAlphaPremultipliedFirst, - kColorSyncAlphaLast, - kColorSyncAlphaFirst, - kColorSyncAlphaNoneSkipLast, - kColorSyncAlphaNoneSkipFirst, -}; - -typedef enum ColorSyncAlphaInfo ColorSyncAlphaInfo; - -enum { - kColorSyncAlphaInfoMask = 0x1F, - - kColorSyncByteOrderMask = 0x7000, - kColorSyncByteOrderDefault = (0 << 12), - kColorSyncByteOrder16Little = (1 << 12), - kColorSyncByteOrder32Little = (2 << 12), - kColorSyncByteOrder16Big = (3 << 12), - kColorSyncByteOrder32Big = (4 << 12) -}; - - -typedef uint32_t ColorSyncDataLayout; - -__attribute__((visibility("default"))) extern bool ColorSyncTransformConvert (ColorSyncTransformRef transform, size_t width, size_t height, - void* dst, ColorSyncDataDepth dstDepth, - ColorSyncDataLayout dstLayout, size_t dstBytesPerRow, - const void* src, ColorSyncDataDepth srcDepth, - ColorSyncDataLayout srcLayout, size_t srcBytesPerRow, - CFDictionaryRef options); -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfile; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncRenderingIntent; - - - __attribute__((visibility("default"))) extern CFStringRef kColorSyncRenderingIntentPerceptual; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncRenderingIntentRelative; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncRenderingIntentSaturation; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncRenderingIntentAbsolute; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncRenderingIntentUseProfileHeader; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformTag; - - - __attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformDeviceToPCS; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformPCSToPCS; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformPCSToDevice; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformDeviceToDevice; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformGamutCheck; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncBlackPointCompensation; - - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncPreferredCMM; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConvertQuality; - - - __attribute__((visibility("default"))) extern CFStringRef kColorSyncBestQuality; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncNormalQuality; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncDraftQuality; - - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConvertThreadCount; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConvertUseVectorUnit; - - - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncTranformInfo; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformCreator; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformSrcSpace; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformDstSpace; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformCodeFragmentType; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformFullConversionData; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformSimplifiedConversionData; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncTransformParametricConversionData; - - - - - - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionMatrix; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionParamCurve0; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionParamCurve1; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionParamCurve2; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionParamCurve3; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionParamCurve4; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversion1DLut; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionGridPoints; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionChannelID; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversion3DLut; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionNDLut; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionInpChan; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionOutChan; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncConversionBPC; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncFixedPointRange; - - -} -extern "C" { -typedef struct ColorSyncCMM* ColorSyncCMMRef; - -__attribute__((visibility("default"))) extern CFTypeID ColorSyncCMMGetTypeID(void); - - - - -__attribute__((visibility("default"))) extern ColorSyncCMMRef ColorSyncCMMCreate(CFBundleRef cmmBundle); - -__attribute__((visibility("default"))) extern CFBundleRef ColorSyncCMMGetBundle(ColorSyncCMMRef); - -__attribute__((visibility("default"))) extern CFStringRef ColorSyncCMMCopyLocalizedName(ColorSyncCMMRef); - -__attribute__((visibility("default"))) extern CFStringRef ColorSyncCMMCopyCMMIdentifier(ColorSyncCMMRef); - -typedef bool (*ColorSyncCMMIterateCallback)(ColorSyncCMMRef cmm, void* userInfo); - - - - - -__attribute__((visibility("default"))) extern void ColorSyncIterateInstalledCMMs (ColorSyncCMMIterateCallback callBack, void* userInfo); -typedef bool (*CMMInitializeLinkProfileProc) (ColorSyncMutableProfileRef, CFArrayRef profileInfo, CFDictionaryRef options); - -typedef bool (*CMMInitializeTransformProc) (ColorSyncTransformRef, CFArrayRef profileInfo, CFDictionaryRef options); - -typedef bool (*CMMApplyTransformProc)(ColorSyncTransformRef transform, size_t width, size_t height, - size_t dstPlanes, void* dst[], ColorSyncDataDepth dstDepth, - ColorSyncDataLayout dstFormat, size_t dstBytesPerRow, - size_t srcPlanes, const void* src[], ColorSyncDataDepth srcDepth, - ColorSyncDataLayout srcFormat, size_t srcBytesPerRow, - CFDictionaryRef options); - -typedef CFTypeRef (*CMMCreateTransformPropertyProc)(ColorSyncTransformRef transform, CFTypeRef key, CFDictionaryRef options); - -__attribute__((visibility("default"))) extern CFStringRef kCMMInitializeLinkProfileProcName; -__attribute__((visibility("default"))) extern CFStringRef kCMMInitializeTransformProcName; -__attribute__((visibility("default"))) extern CFStringRef kCMMApplyTransformProcName; -__attribute__((visibility("default"))) extern CFStringRef kCMMCreateTransformPropertyProcName; -} -extern "C" { - - - - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceID; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceClass; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncCameraDeviceClass; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncDisplayDeviceClass; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncPrinterDeviceClass; - __attribute__((visibility("default"))) extern CFStringRef kColorSyncScannerDeviceClass; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceProfileURL; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceDescription; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceDescriptions; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncFactoryProfiles; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncCustomProfiles; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceModeDescription; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceModeDescriptions; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceDefaultProfileID; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceHostScope; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceUserScope; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileHostScope; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncProfileUserScope; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceProfileIsFactory; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceProfileIsDefault; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceProfileIsCurrent; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceProfileID; - -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceRegisteredNotification; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceUnregisteredNotification; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDeviceProfilesNotification; -__attribute__((visibility("default"))) extern CFStringRef kColorSyncDisplayDeviceProfilesNotification; - -__attribute__((visibility("default"))) extern bool ColorSyncRegisterDevice (CFStringRef deviceClass, CFUUIDRef deviceID, CFDictionaryRef deviceInfo); -__attribute__((visibility("default"))) extern bool ColorSyncUnregisterDevice (CFStringRef deviceClass, CFUUIDRef deviceID); - - - - - - -__attribute__((visibility("default"))) extern bool ColorSyncDeviceSetCustomProfiles (CFStringRef deviceClass, CFUUIDRef deviceID, CFDictionaryRef profileInfo); -__attribute__((visibility("default"))) extern CFDictionaryRef ColorSyncDeviceCopyDeviceInfo (CFStringRef deviceClass, CFUUIDRef devID); -typedef bool (*ColorSyncDeviceProfileIterateCallback) (CFDictionaryRef colorSyncDeviceProfileInfo, - void* userInfo); -__attribute__((visibility("default"))) extern void ColorSyncIterateDeviceProfiles(ColorSyncDeviceProfileIterateCallback callBack, - void* userInfo); - - __attribute__((visibility("default"))) extern CFUUIDRef CGDisplayCreateUUIDFromDisplayID (uint32_t displayID); - - - - - __attribute__((visibility("default"))) extern uint32_t CGDisplayGetDisplayIDFromUUID (CFUUIDRef uuid); - - - - - - -} - - - - - - - - - - - -typedef struct CGContext *CGContextRef; - - - - -typedef struct CGColor *CGColorRef; - - - -typedef struct CGColorSpace *CGColorSpaceRef; - - - -typedef struct CGDataProvider *CGDataProviderRef; -typedef size_t (*CGDataProviderGetBytesCallback)(void * _Nullable info, - void * buffer, size_t count); - - - - - -typedef off_t (*CGDataProviderSkipForwardCallback)(void * _Nullable info, - off_t count); - - - - -typedef void (*CGDataProviderRewindCallback)(void * _Nullable info); - - - - -typedef void (*CGDataProviderReleaseInfoCallback)(void * _Nullable info); -struct CGDataProviderSequentialCallbacks { - unsigned int version; - CGDataProviderGetBytesCallback _Nullable getBytes; - CGDataProviderSkipForwardCallback _Nullable skipForward; - CGDataProviderRewindCallback _Nullable rewind; - CGDataProviderReleaseInfoCallback _Nullable releaseInfo; -}; -typedef struct CGDataProviderSequentialCallbacks - CGDataProviderSequentialCallbacks; - - - -typedef const void * _Nullable(*CGDataProviderGetBytePointerCallback)( - void * _Nullable info); - - - - -typedef void (*CGDataProviderReleaseBytePointerCallback)( - void * _Nullable info, const void * pointer); - - - - -typedef size_t (*CGDataProviderGetBytesAtPositionCallback)( - void * _Nullable info, void * buffer, off_t pos, size_t cnt); -struct CGDataProviderDirectCallbacks { - unsigned int version; - CGDataProviderGetBytePointerCallback _Nullable getBytePointer; - CGDataProviderReleaseBytePointerCallback _Nullable releaseBytePointer; - CGDataProviderGetBytesAtPositionCallback _Nullable getBytesAtPosition; - CGDataProviderReleaseInfoCallback _Nullable releaseInfo; -}; -typedef struct CGDataProviderDirectCallbacks CGDataProviderDirectCallbacks; - - - -extern "C" CFTypeID CGDataProviderGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGDataProviderRef _Nullable CGDataProviderCreateSequential( - void * _Nullable info, - const CGDataProviderSequentialCallbacks * _Nullable callbacks) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" CGDataProviderRef _Nullable CGDataProviderCreateDirect( - void * _Nullable info, off_t size, - const CGDataProviderDirectCallbacks * _Nullable callbacks) - __attribute__((availability(macosx,introduced=10.5))); - - - -typedef void (*CGDataProviderReleaseDataCallback)(void * _Nullable info, - const void * data, size_t size); - - - - - -extern "C" CGDataProviderRef _Nullable CGDataProviderCreateWithData( - void * _Nullable info, const void * _Nullable data, size_t size, - CGDataProviderReleaseDataCallback _Nullable releaseData) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGDataProviderRef _Nullable CGDataProviderCreateWithCFData( - CFDataRef _Nullable data) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGDataProviderRef _Nullable CGDataProviderCreateWithURL( - CFURLRef _Nullable url) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGDataProviderRef _Nullable CGDataProviderCreateWithFilename( - const char * _Nullable filename) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGDataProviderRef _Nullable CGDataProviderRetain( - CGDataProviderRef _Nullable provider) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGDataProviderRelease(CGDataProviderRef _Nullable provider) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CFDataRef _Nullable CGDataProviderCopyData( - CGDataProviderRef _Nullable provider) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -typedef int32_t CGColorRenderingIntent; enum { - kCGRenderingIntentDefault, - kCGRenderingIntentAbsoluteColorimetric, - kCGRenderingIntentRelativeColorimetric, - kCGRenderingIntentPerceptual, - kCGRenderingIntentSaturation -}; - - - -typedef int32_t CGColorSpaceModel; enum { - kCGColorSpaceModelUnknown = -1, - kCGColorSpaceModelMonochrome, - kCGColorSpaceModelRGB, - kCGColorSpaceModelCMYK, - kCGColorSpaceModelLab, - kCGColorSpaceModelDeviceN, - kCGColorSpaceModelIndexed, - kCGColorSpaceModelPattern -}; -extern "C" const CFStringRef kCGColorSpaceGenericGray - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" const CFStringRef kCGColorSpaceGenericRGB - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" const CFStringRef kCGColorSpaceGenericCMYK - __attribute__((availability(macosx,introduced=10.4))); - -extern "C" const CFStringRef kCGColorSpaceDisplayP3 - __attribute__((availability(macosx,introduced=10.10))); - - - - -extern "C" const CFStringRef kCGColorSpaceGenericRGBLinear - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" const CFStringRef kCGColorSpaceAdobeRGB1998 - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -extern "C" const CFStringRef kCGColorSpaceSRGB - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" const CFStringRef kCGColorSpaceGenericGrayGamma2_2 - __attribute__((availability(macosx,introduced=10.6))); - -extern "C" const CFStringRef kCGColorSpaceGenericXYZ - __attribute__((availability(macosx,introduced=10.11))); - -extern "C" const CFStringRef kCGColorSpaceACESCGLinear -__attribute__((availability(macosx,introduced=10.11))); - -extern "C" const CFStringRef kCGColorSpaceITUR_709 -__attribute__((availability(macosx,introduced=10.11))); - -extern "C" const CFStringRef kCGColorSpaceITUR_2020 -__attribute__((availability(macosx,introduced=10.11))); - -extern "C" const CFStringRef kCGColorSpaceROMMRGB -__attribute__((availability(macosx,introduced=10.11))); - -extern "C" const CFStringRef kCGColorSpaceDCIP3 -__attribute__((availability(macosx,introduced=10.11))); - - - -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateDeviceGray(void) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateDeviceRGB(void) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateDeviceCMYK(void) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - - -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateCalibratedGray(const CGFloat - whitePoint[3], const CGFloat blackPoint[3], CGFloat gamma) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateCalibratedRGB(const CGFloat - whitePoint[3], const CGFloat blackPoint[3], const CGFloat gamma[3], - const CGFloat matrix[9]) __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateLab(const CGFloat whitePoint[3], - const CGFloat blackPoint[3], const CGFloat range[4]) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateWithICCProfile(CFDataRef _Nullable data) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateICCBased(size_t nComponents, - const CGFloat * _Nullable range, CGDataProviderRef _Nullable profile, - CGColorSpaceRef _Nullable alternate) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateIndexed(CGColorSpaceRef _Nullable baseSpace, - size_t lastIndex, const unsigned char * _Nullable colorTable) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreatePattern(CGColorSpaceRef _Nullable baseSpace) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGColorSpaceRef _Nullable - CGColorSpaceCreateWithPlatformColorSpace(const void * _Nullable ref) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGColorSpaceRef _Nullable CGColorSpaceCreateWithName(CFStringRef _Nullable name) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGColorSpaceRef _Nullable CGColorSpaceRetain(CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGColorSpaceRelease(CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CFStringRef _Nullable CGColorSpaceCopyName(CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" CFTypeID CGColorSpaceGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" size_t CGColorSpaceGetNumberOfComponents(CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGColorSpaceModel CGColorSpaceGetModel(CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" CGColorSpaceRef _Nullable CGColorSpaceGetBaseColorSpace(CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" size_t CGColorSpaceGetColorTableCount(CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" void CGColorSpaceGetColorTable(CGColorSpaceRef _Nullable space, - uint8_t * _Nullable table) __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" CFDataRef _Nullable CGColorSpaceCopyICCProfile(CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -typedef struct CGPattern *CGPatternRef; - - - -typedef int32_t CGPatternTiling; enum { - kCGPatternTilingNoDistortion, - kCGPatternTilingConstantSpacingMinimalDistortion, - kCGPatternTilingConstantSpacing -}; -typedef void (*CGPatternDrawPatternCallback)(void * _Nullable info, - CGContextRef _Nullable context); -typedef void (*CGPatternReleaseInfoCallback)(void * _Nullable info); - -struct CGPatternCallbacks { - unsigned int version; - CGPatternDrawPatternCallback _Nullable drawPattern; - CGPatternReleaseInfoCallback _Nullable releaseInfo; -}; -typedef struct CGPatternCallbacks CGPatternCallbacks; - - - -extern "C" CFTypeID CGPatternGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" CGPatternRef _Nullable CGPatternCreate(void * _Nullable info, - CGRect bounds, CGAffineTransform matrix, CGFloat xStep, CGFloat yStep, - CGPatternTiling tiling, bool isColored, - const CGPatternCallbacks * _Nullable callbacks) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGPatternRef _Nullable CGPatternRetain(CGPatternRef _Nullable pattern) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGPatternRelease(CGPatternRef _Nullable pattern) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGColorRef _Nullable CGColorCreate(CGColorSpaceRef _Nullable space, - const CGFloat * _Nullable components) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGColorRef CGColorCreateGenericGray(CGFloat gray, CGFloat alpha) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" CGColorRef CGColorCreateGenericRGB(CGFloat red, CGFloat green, - CGFloat blue, CGFloat alpha) __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" CGColorRef CGColorCreateGenericCMYK(CGFloat cyan, CGFloat magenta, - CGFloat yellow, CGFloat black, CGFloat alpha) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" CGColorRef _Nullable CGColorGetConstantColor(CFStringRef _Nullable colorName) - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" CGColorRef _Nullable CGColorCreateWithPattern(CGColorSpaceRef _Nullable space, - CGPatternRef _Nullable pattern, const CGFloat * _Nullable components) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGColorRef _Nullable CGColorCreateCopy(CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGColorRef _Nullable CGColorCreateCopyWithAlpha(CGColorRef _Nullable color, - CGFloat alpha) __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGColorRef _Nullable CGColorCreateCopyByMatchingToColorSpace(_Nullable CGColorSpaceRef, - CGColorRenderingIntent intent, CGColorRef _Nullable color, _Nullable CFDictionaryRef options) - __attribute__((availability(macosx,introduced=10.11))); - - - - -extern "C" CGColorRef _Nullable CGColorRetain(CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" void CGColorRelease(CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" bool CGColorEqualToColor(CGColorRef _Nullable color1, CGColorRef _Nullable color2) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" size_t CGColorGetNumberOfComponents(CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" const CGFloat * _Nullable CGColorGetComponents(CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGFloat CGColorGetAlpha(CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGColorSpaceRef _Nullable CGColorGetColorSpace(CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" CGPatternRef _Nullable CGColorGetPattern(CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CFTypeID CGColorGetTypeID(void) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" const CFStringRef kCGColorWhite - __attribute__((availability(macosx,introduced=10.5))); - -extern "C" const CFStringRef kCGColorBlack - __attribute__((availability(macosx,introduced=10.5))); - -extern "C" const CFStringRef kCGColorClear - __attribute__((availability(macosx,introduced=10.5))); - -typedef struct CGFont *CGFontRef; - - - -typedef unsigned short CGFontIndex; - - - -typedef CGFontIndex CGGlyph; - - - - - - -typedef int32_t CGFontPostScriptFormat; enum { - kCGFontPostScriptFormatType1 = 1, - kCGFontPostScriptFormatType3 = 3, - kCGFontPostScriptFormatType42 = 42 -}; -static const CGFontIndex kCGFontIndexMax = ((1 << 16) - 2); - - -static const CGFontIndex kCGFontIndexInvalid = ((1 << 16) - 1); - - -static const CGFontIndex kCGGlyphMax = kCGFontIndexMax; - - - -extern "C" CFTypeID CGFontGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -extern "C" CGFontRef _Nullable CGFontCreateWithPlatformFont( - void * _Nullable platformFontReference) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - - -extern "C" CGFontRef _Nullable CGFontCreateWithDataProvider( - CGDataProviderRef _Nullable provider) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" CGFontRef _Nullable CGFontCreateWithFontName( - CFStringRef _Nullable name) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" CGFontRef _Nullable CGFontCreateCopyWithVariations( - CGFontRef _Nullable font, CFDictionaryRef _Nullable variations) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGFontRef _Nullable CGFontRetain(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGFontRelease(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" size_t CGFontGetNumberOfGlyphs(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" int CGFontGetUnitsPerEm(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CFStringRef _Nullable CGFontCopyPostScriptName(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CFStringRef _Nullable CGFontCopyFullName(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" int CGFontGetAscent(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" int CGFontGetDescent(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" int CGFontGetLeading(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" int CGFontGetCapHeight(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" int CGFontGetXHeight(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" CGRect CGFontGetFontBBox(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" CGFloat CGFontGetItalicAngle(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" CGFloat CGFontGetStemV(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern "C" CFArrayRef _Nullable CGFontCopyVariationAxes(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CFDictionaryRef _Nullable CGFontCopyVariations(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" bool CGFontGetGlyphAdvances(CGFontRef _Nullable font, - const CGGlyph * glyphs, size_t count, int * advances) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - - -extern "C" bool CGFontGetGlyphBBoxes(CGFontRef _Nullable font, - const CGGlyph * glyphs, size_t count, CGRect * bboxes) - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" CGGlyph CGFontGetGlyphWithGlyphName( - CGFontRef _Nullable font, CFStringRef _Nullable name) - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" CFStringRef _Nullable CGFontCopyGlyphNameForGlyph( - CGFontRef _Nullable font, CGGlyph glyph) - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" bool CGFontCanCreatePostScriptSubset(CGFontRef _Nullable font, - CGFontPostScriptFormat format) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" CFDataRef _Nullable CGFontCreatePostScriptSubset( - CGFontRef _Nullable font, CFStringRef _Nullable subsetName, - CGFontPostScriptFormat format, const CGGlyph * _Nullable glyphs, - size_t count, const CGGlyph encoding[256]) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CFDataRef _Nullable CGFontCreatePostScriptEncoding( - CGFontRef _Nullable font, const CGGlyph encoding[256]) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CFArrayRef _Nullable CGFontCopyTableTags(CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" CFDataRef _Nullable CGFontCopyTableForTag( - CGFontRef _Nullable font, uint32_t tag) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -extern "C" const CFStringRef kCGFontVariationAxisName - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" const CFStringRef kCGFontVariationAxisMinValue - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" const CFStringRef kCGFontVariationAxisMaxValue - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" const CFStringRef kCGFontVariationAxisDefaultValue - __attribute__((availability(macosx,introduced=10.4))); - - - -typedef int32_t CGGlypDeprecatedEnum; enum { - CGGlyphMin __attribute__((deprecated)), - CGGlyphMax __attribute__((deprecated)) -}; - - - - - - - -typedef struct CGGradient *CGGradientRef; - - - - - - -typedef uint32_t CGGradientDrawingOptions; enum { - kCGGradientDrawsBeforeStartLocation = (1 << 0), - kCGGradientDrawsAfterEndLocation = (1 << 1) -}; - - - - -extern "C" CFTypeID CGGradientGetTypeID(void) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" CGGradientRef _Nullable CGGradientCreateWithColorComponents( - CGColorSpaceRef _Nullable space, const CGFloat * _Nullable components, - const CGFloat * _Nullable locations, size_t count) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" CGGradientRef _Nullable CGGradientCreateWithColors( - CGColorSpaceRef _Nullable space, CFArrayRef _Nullable colors, - const CGFloat * _Nullable locations) - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" CGGradientRef _Nullable CGGradientRetain( - CGGradientRef _Nullable gradient) - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" void CGGradientRelease(CGGradientRef _Nullable gradient) - __attribute__((availability(macosx,introduced=10.5))); -typedef struct CGImage *CGImageRef; -typedef uint32_t CGImageAlphaInfo; enum { - kCGImageAlphaNone, - kCGImageAlphaPremultipliedLast, - kCGImageAlphaPremultipliedFirst, - kCGImageAlphaLast, - kCGImageAlphaFirst, - kCGImageAlphaNoneSkipLast, - kCGImageAlphaNoneSkipFirst, - kCGImageAlphaOnly -}; - -typedef uint32_t CGBitmapInfo; enum { - kCGBitmapAlphaInfoMask = 0x1F, - kCGBitmapFloatComponents = (1 << 8), - - kCGBitmapByteOrderMask = 0x7000, - kCGBitmapByteOrderDefault = (0 << 12), - kCGBitmapByteOrder16Little = (1 << 12), - kCGBitmapByteOrder32Little = (2 << 12), - kCGBitmapByteOrder16Big = (3 << 12), - kCGBitmapByteOrder32Big = (4 << 12) -} __attribute__((availability(macosx,introduced=10_4))); -extern "C" CFTypeID CGImageGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" CGImageRef _Nullable CGImageCreate(size_t width, size_t height, - size_t bitsPerComponent, size_t bitsPerPixel, size_t bytesPerRow, - CGColorSpaceRef _Nullable space, CGBitmapInfo bitmapInfo, - CGDataProviderRef _Nullable provider, - const CGFloat * _Nullable decode, bool shouldInterpolate, - CGColorRenderingIntent intent) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGImageRef _Nullable CGImageMaskCreate(size_t width, size_t height, - size_t bitsPerComponent, size_t bitsPerPixel, size_t bytesPerRow, - CGDataProviderRef _Nullable provider, const CGFloat * _Nullable decode, - bool shouldInterpolate) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGImageRef _Nullable CGImageCreateCopy(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGImageRef _Nullable CGImageCreateWithJPEGDataProvider( - CGDataProviderRef _Nullable source, const CGFloat * _Nullable decode, - bool shouldInterpolate, - CGColorRenderingIntent intent) - __attribute__((availability(macosx,introduced=10.1))); - - - -extern "C" CGImageRef _Nullable CGImageCreateWithPNGDataProvider( - CGDataProviderRef _Nullable source, const CGFloat * _Nullable decode, - bool shouldInterpolate, - CGColorRenderingIntent intent) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" CGImageRef _Nullable CGImageCreateWithImageInRect( - CGImageRef _Nullable image, CGRect rect) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGImageRef _Nullable CGImageCreateWithMask( - CGImageRef _Nullable image, CGImageRef _Nullable mask) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGImageRef _Nullable CGImageCreateWithMaskingColors( - CGImageRef _Nullable image, const CGFloat * _Nullable components) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" CGImageRef _Nullable CGImageCreateCopyWithColorSpace( - CGImageRef _Nullable image, CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGImageRef _Nullable CGImageRetain(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGImageRelease(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGImageIsMask(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" size_t CGImageGetWidth(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" size_t CGImageGetHeight(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" size_t CGImageGetBitsPerComponent(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" size_t CGImageGetBitsPerPixel(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" size_t CGImageGetBytesPerRow(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGColorSpaceRef _Nullable CGImageGetColorSpace(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGImageAlphaInfo CGImageGetAlphaInfo(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGDataProviderRef _Nullable CGImageGetDataProvider(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" const CGFloat * _Nullable CGImageGetDecode(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" bool CGImageGetShouldInterpolate(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGColorRenderingIntent CGImageGetRenderingIntent(_Nullable CGImageRef image) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGBitmapInfo CGImageGetBitmapInfo(CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CFStringRef _Nullable CGImageGetUTType(_Nullable CGImageRef image) - __attribute__((availability(macosx,introduced=10.11))); -typedef struct CGPath *CGMutablePathRef; -typedef const struct CGPath *CGPathRef; -typedef int32_t CGLineJoin; enum { - kCGLineJoinMiter, - kCGLineJoinRound, - kCGLineJoinBevel -}; - - - -typedef int32_t CGLineCap; enum { - kCGLineCapButt, - kCGLineCapRound, - kCGLineCapSquare -}; - - - -extern "C" CFTypeID CGPathGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" CGMutablePathRef CGPathCreateMutable(void) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" CGPathRef _Nullable CGPathCreateCopy(CGPathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" CGPathRef _Nullable CGPathCreateCopyByTransformingPath( - CGPathRef _Nullable path, const CGAffineTransform * _Nullable transform) - __attribute__((availability(macosx,introduced=10.7))); - - - -extern "C" CGMutablePathRef _Nullable CGPathCreateMutableCopy( - CGPathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" CGMutablePathRef _Nullable CGPathCreateMutableCopyByTransformingPath( - CGPathRef _Nullable path, const CGAffineTransform * _Nullable transform) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" CGPathRef CGPathCreateWithRect(CGRect rect, - const CGAffineTransform * _Nullable transform) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" CGPathRef CGPathCreateWithEllipseInRect(CGRect rect, - const CGAffineTransform * _Nullable transform) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" CGPathRef CGPathCreateWithRoundedRect(CGRect rect, - CGFloat cornerWidth, CGFloat cornerHeight, - const CGAffineTransform * _Nullable transform) - __attribute__((availability(macosx,introduced=10.9))); -extern "C" void CGPathAddRoundedRect(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable transform, CGRect rect, - CGFloat cornerWidth, CGFloat cornerHeight) - __attribute__((availability(macosx,introduced=10.9))); - - - - - - - -extern "C" CGPathRef _Nullable CGPathCreateCopyByDashingPath( - CGPathRef _Nullable path, const CGAffineTransform * _Nullable transform, - CGFloat phase, const CGFloat * _Nullable lengths, size_t count) - __attribute__((availability(macosx,introduced=10.7))); - - - - - - - -extern "C" CGPathRef _Nullable CGPathCreateCopyByStrokingPath( - CGPathRef _Nullable path, const CGAffineTransform * _Nullable transform, - CGFloat lineWidth, CGLineCap lineCap, - CGLineJoin lineJoin, CGFloat miterLimit) - __attribute__((availability(macosx,introduced=10.7))); - - - - -extern "C" CGPathRef _Nullable CGPathRetain(CGPathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" void CGPathRelease(CGPathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" bool CGPathEqualToPath(CGPathRef _Nullable path1, - CGPathRef _Nullable path2) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" void CGPathMoveToPoint(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable m, CGFloat x, CGFloat y) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -extern "C" void CGPathAddLineToPoint(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable m, CGFloat x, CGFloat y) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -extern "C" void CGPathAddQuadCurveToPoint(CGMutablePathRef _Nullable path, - const CGAffineTransform *_Nullable m, CGFloat cpx, CGFloat cpy, - CGFloat x, CGFloat y) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" void CGPathAddCurveToPoint(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable m, CGFloat cp1x, CGFloat cp1y, - CGFloat cp2x, CGFloat cp2y, CGFloat x, CGFloat y) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" void CGPathCloseSubpath(CGMutablePathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" void CGPathAddRect(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable m, CGRect rect) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -extern "C" void CGPathAddRects(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable m, const CGRect * _Nullable rects, - size_t count) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -extern "C" void CGPathAddLines(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable m, const CGPoint * _Nullable points, - size_t count) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" void CGPathAddEllipseInRect(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable m, CGRect rect) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGPathAddRelativeArc(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable matrix, CGFloat x, CGFloat y, - CGFloat radius, CGFloat startAngle, CGFloat delta) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" void CGPathAddArc(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable m, - CGFloat x, CGFloat y, CGFloat radius, CGFloat startAngle, CGFloat endAngle, - bool clockwise) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" void CGPathAddArcToPoint(CGMutablePathRef _Nullable path, - const CGAffineTransform * _Nullable m, CGFloat x1, CGFloat y1, - CGFloat x2, CGFloat y2, CGFloat radius) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" void CGPathAddPath(CGMutablePathRef _Nullable path1, - const CGAffineTransform * _Nullable m, CGPathRef _Nullable path2) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -extern "C" bool CGPathIsEmpty(CGPathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" bool CGPathIsRect(CGPathRef _Nullable path, CGRect * _Nullable rect) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGPoint CGPathGetCurrentPoint(CGPathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" CGRect CGPathGetBoundingBox(CGPathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" CGRect CGPathGetPathBoundingBox(CGPathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.6))); -extern "C" bool CGPathContainsPoint(CGPathRef _Nullable path, - const CGAffineTransform * _Nullable m, CGPoint point, bool eoFill) - __attribute__((availability(macosx,introduced=10.4))); - - - -typedef int32_t CGPathElementType; enum { - kCGPathElementMoveToPoint, - kCGPathElementAddLineToPoint, - kCGPathElementAddQuadCurveToPoint, - kCGPathElementAddCurveToPoint, - kCGPathElementCloseSubpath -}; - - - -struct CGPathElement { - CGPathElementType type; - CGPoint * points; -}; -typedef struct CGPathElement CGPathElement; - - - -typedef void (*CGPathApplierFunction)(void * _Nullable info, - const CGPathElement * element); - - - - -extern "C" void CGPathApply(CGPathRef _Nullable path, void * _Nullable info, - CGPathApplierFunction _Nullable function) - __attribute__((availability(macosx,introduced=10.2))); - -typedef struct CGPDFDocument *CGPDFDocumentRef; - - - - -typedef struct CGPDFPage *CGPDFPageRef; - - - -typedef struct CGPDFDictionary *CGPDFDictionaryRef; - - -typedef struct CGPDFArray *CGPDFArrayRef; - - -typedef unsigned char CGPDFBoolean; - - - -typedef long int CGPDFInteger; - - - -typedef CGFloat CGPDFReal; - - - -typedef union CGPDFObject *CGPDFObjectRef; - - - -typedef int32_t CGPDFObjectType; enum { - kCGPDFObjectTypeNull = 1, - kCGPDFObjectTypeBoolean, - kCGPDFObjectTypeInteger, - kCGPDFObjectTypeReal, - kCGPDFObjectTypeName, - kCGPDFObjectTypeString, - kCGPDFObjectTypeArray, - kCGPDFObjectTypeDictionary, - kCGPDFObjectTypeStream -}; - - - -extern "C" CGPDFObjectType CGPDFObjectGetType(CGPDFObjectRef _Nullable object) - __attribute__((availability(macosx,introduced=10.3))); -extern "C" bool CGPDFObjectGetValue(CGPDFObjectRef _Nullable object, - CGPDFObjectType type, void * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - - - - -typedef struct CGPDFStream *CGPDFStreamRef; - - - - - -typedef int32_t CGPDFDataFormat; enum { - CGPDFDataFormatRaw, CGPDFDataFormatJPEGEncoded, CGPDFDataFormatJPEG2000 -}; - - - - - - - - - - -extern "C" CGPDFDictionaryRef _Nullable CGPDFStreamGetDictionary( - CGPDFStreamRef _Nullable stream) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CFDataRef _Nullable CGPDFStreamCopyData( - CGPDFStreamRef _Nullable stream, - CGPDFDataFormat * _Nullable format) - __attribute__((availability(macosx,introduced=10.3))); -typedef struct CGPDFString *CGPDFStringRef; -extern "C" size_t CGPDFStringGetLength(CGPDFStringRef _Nullable string) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" const unsigned char * _Nullable CGPDFStringGetBytePtr( - CGPDFStringRef _Nullable string) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" CFStringRef _Nullable CGPDFStringCopyTextString( - CGPDFStringRef _Nullable string) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" CFDateRef _Nullable CGPDFStringCopyDate( - CGPDFStringRef _Nullable string) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" size_t CGPDFArrayGetCount(CGPDFArrayRef _Nullable array) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFArrayGetObject(CGPDFArrayRef _Nullable array, size_t index, - CGPDFObjectRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFArrayGetNull(CGPDFArrayRef _Nullable array, size_t index) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFArrayGetBoolean(CGPDFArrayRef _Nullable array, - size_t index, CGPDFBoolean * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFArrayGetInteger(CGPDFArrayRef _Nullable array, - size_t index, CGPDFInteger * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" bool CGPDFArrayGetNumber(CGPDFArrayRef _Nullable array, - size_t index, CGPDFReal * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFArrayGetName(CGPDFArrayRef _Nullable array, - size_t index, const char * _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFArrayGetString(CGPDFArrayRef _Nullable array, - size_t index, CGPDFStringRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFArrayGetArray(CGPDFArrayRef _Nullable array, - size_t index, CGPDFArrayRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFArrayGetDictionary(CGPDFArrayRef _Nullable array, - size_t index, CGPDFDictionaryRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFArrayGetStream(CGPDFArrayRef _Nullable array, - size_t index, CGPDFStreamRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); -extern "C" size_t CGPDFDictionaryGetCount(CGPDFDictionaryRef _Nullable dict) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFDictionaryGetObject(CGPDFDictionaryRef _Nullable dict, - const char * key, CGPDFObjectRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" bool CGPDFDictionaryGetBoolean(CGPDFDictionaryRef _Nullable dict, - const char * key, CGPDFBoolean * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" bool CGPDFDictionaryGetInteger(CGPDFDictionaryRef _Nullable dict, - const char * key, CGPDFInteger * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" bool CGPDFDictionaryGetNumber(CGPDFDictionaryRef _Nullable dict, - const char * key, CGPDFReal * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFDictionaryGetName(CGPDFDictionaryRef _Nullable dict, - const char * key, const char * _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFDictionaryGetString(CGPDFDictionaryRef _Nullable dict, - const char * key, CGPDFStringRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFDictionaryGetArray(CGPDFDictionaryRef _Nullable dict, - const char * key, CGPDFArrayRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" bool CGPDFDictionaryGetDictionary(CGPDFDictionaryRef _Nullable dict, - const char * key, CGPDFDictionaryRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPDFDictionaryGetStream(CGPDFDictionaryRef _Nullable dict, - const char * key, CGPDFStreamRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -typedef void (*CGPDFDictionaryApplierFunction)(const char * key, - CGPDFObjectRef value, void * _Nullable info); - - - - - -extern "C" void CGPDFDictionaryApplyFunction(CGPDFDictionaryRef _Nullable dict, - CGPDFDictionaryApplierFunction _Nullable function, void * _Nullable info) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -typedef int32_t CGPDFBox; enum { - kCGPDFMediaBox = 0, - kCGPDFCropBox = 1, - kCGPDFBleedBox = 2, - kCGPDFTrimBox = 3, - kCGPDFArtBox = 4 -}; - - - - -extern "C" CGPDFPageRef _Nullable CGPDFPageRetain(CGPDFPageRef _Nullable page) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" void CGPDFPageRelease(CGPDFPageRef _Nullable page) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGPDFDocumentRef _Nullable CGPDFPageGetDocument( - CGPDFPageRef _Nullable page) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" size_t CGPDFPageGetPageNumber(CGPDFPageRef _Nullable page) - __attribute__((availability(macosx,introduced=10.3))); - - - - - - -extern "C" CGRect CGPDFPageGetBoxRect(CGPDFPageRef _Nullable page, CGPDFBox box) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" int CGPDFPageGetRotationAngle(CGPDFPageRef _Nullable page) - __attribute__((availability(macosx,introduced=10.3))); -extern "C" CGAffineTransform CGPDFPageGetDrawingTransform( - CGPDFPageRef _Nullable page, CGPDFBox box, CGRect rect, int rotate, - bool preserveAspectRatio) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGPDFDictionaryRef _Nullable CGPDFPageGetDictionary( - CGPDFPageRef _Nullable page) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CFTypeID CGPDFPageGetTypeID(void) - __attribute__((availability(macosx,introduced=10.3))); - - - - - - - - -extern "C" CGPDFDocumentRef _Nullable CGPDFDocumentCreateWithProvider( - CGDataProviderRef _Nullable provider) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGPDFDocumentRef _Nullable CGPDFDocumentCreateWithURL( - CFURLRef _Nullable url) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGPDFDocumentRef _Nullable CGPDFDocumentRetain( - CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGPDFDocumentRelease(CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGPDFDocumentGetVersion(CGPDFDocumentRef _Nullable document, - int * majorVersion, int * minorVersion) - __attribute__((availability(macosx,introduced=10.3))); - - - - - - -extern "C" bool CGPDFDocumentIsEncrypted(CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -extern "C" bool CGPDFDocumentUnlockWithPassword( - CGPDFDocumentRef _Nullable document, const char * password) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -extern "C" bool CGPDFDocumentIsUnlocked(CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" bool CGPDFDocumentAllowsPrinting(CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" bool CGPDFDocumentAllowsCopying(CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" size_t CGPDFDocumentGetNumberOfPages( - CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGPDFPageRef _Nullable CGPDFDocumentGetPage( - CGPDFDocumentRef _Nullable document, size_t pageNumber) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGPDFDictionaryRef _Nullable CGPDFDocumentGetCatalog( - CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGPDFDictionaryRef _Nullable CGPDFDocumentGetInfo( - CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGPDFArrayRef _Nullable CGPDFDocumentGetID( - CGPDFDocumentRef _Nullable document) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CFTypeID CGPDFDocumentGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" CGRect CGPDFDocumentGetMediaBox(CGPDFDocumentRef _Nullable document, - int page) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); - - - - - - -extern "C" CGRect CGPDFDocumentGetCropBox(CGPDFDocumentRef _Nullable document, - int page) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); - - - - - -extern "C" CGRect CGPDFDocumentGetBleedBox(CGPDFDocumentRef _Nullable document, - int page) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); - - - - - -extern "C" CGRect CGPDFDocumentGetTrimBox(CGPDFDocumentRef _Nullable document, - int page) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); - - - - - -extern "C" CGRect CGPDFDocumentGetArtBox(CGPDFDocumentRef _Nullable document, - int page) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); - - - - - -extern "C" int CGPDFDocumentGetRotationAngle(CGPDFDocumentRef _Nullable document, - int page) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -typedef struct CGShading *CGShadingRef; - - - - -typedef struct CGFunction *CGFunctionRef; -typedef void (*CGFunctionEvaluateCallback)(void * _Nullable info, - const CGFloat * in, CGFloat * out); - - - - -typedef void (*CGFunctionReleaseInfoCallback)(void * _Nullable info); -struct CGFunctionCallbacks { - unsigned int version; - CGFunctionEvaluateCallback _Nullable evaluate; - CGFunctionReleaseInfoCallback _Nullable releaseInfo; -}; -typedef struct CGFunctionCallbacks CGFunctionCallbacks; - - - -extern "C" CFTypeID CGFunctionGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" CGFunctionRef _Nullable CGFunctionCreate(void * _Nullable info, - size_t domainDimension, const CGFloat *_Nullable domain, - size_t rangeDimension, const CGFloat * _Nullable range, - const CGFunctionCallbacks * _Nullable callbacks) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGFunctionRef _Nullable CGFunctionRetain( - CGFunctionRef _Nullable function) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" void CGFunctionRelease(CGFunctionRef _Nullable function) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" CFTypeID CGShadingGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" CGShadingRef _Nullable CGShadingCreateAxial( - CGColorSpaceRef _Nullable space, CGPoint start, CGPoint end, - CGFunctionRef _Nullable function, bool extendStart, bool extendEnd) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" CGShadingRef _Nullable CGShadingCreateRadial( - CGColorSpaceRef _Nullable space, - CGPoint start, CGFloat startRadius, CGPoint end, CGFloat endRadius, - CGFunctionRef _Nullable function, bool extendStart, bool extendEnd) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGShadingRef _Nullable CGShadingRetain(CGShadingRef _Nullable shading) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" void CGShadingRelease(CGShadingRef _Nullable shading) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - - -typedef int32_t CGPathDrawingMode; enum { - kCGPathFill, - kCGPathEOFill, - kCGPathStroke, - kCGPathFillStroke, - kCGPathEOFillStroke -}; - - - -typedef int32_t CGTextDrawingMode; enum { - kCGTextFill, - kCGTextStroke, - kCGTextFillStroke, - kCGTextInvisible, - kCGTextFillClip, - kCGTextStrokeClip, - kCGTextFillStrokeClip, - kCGTextClip -}; - - - -typedef int32_t CGTextEncoding; enum { - kCGEncodingFontSpecific, - kCGEncodingMacRoman -} __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - - - -typedef int32_t CGInterpolationQuality; enum { - kCGInterpolationDefault = 0, - kCGInterpolationNone = 1, - kCGInterpolationLow = 2, - kCGInterpolationMedium = 4, - kCGInterpolationHigh = 3 -}; -typedef int32_t CGBlendMode; enum { - - kCGBlendModeNormal, - kCGBlendModeMultiply, - kCGBlendModeScreen, - kCGBlendModeOverlay, - kCGBlendModeDarken, - kCGBlendModeLighten, - kCGBlendModeColorDodge, - kCGBlendModeColorBurn, - kCGBlendModeSoftLight, - kCGBlendModeHardLight, - kCGBlendModeDifference, - kCGBlendModeExclusion, - kCGBlendModeHue, - kCGBlendModeSaturation, - kCGBlendModeColor, - kCGBlendModeLuminosity, - kCGBlendModeClear, - kCGBlendModeCopy, - kCGBlendModeSourceIn, - kCGBlendModeSourceOut, - kCGBlendModeSourceAtop, - kCGBlendModeDestinationOver, - kCGBlendModeDestinationIn, - kCGBlendModeDestinationOut, - kCGBlendModeDestinationAtop, - kCGBlendModeXOR, - kCGBlendModePlusDarker, - kCGBlendModePlusLighter -}; - - - -extern "C" CFTypeID CGContextGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - - -extern "C" void CGContextSaveGState(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextRestoreGState(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" void CGContextScaleCTM(CGContextRef _Nullable c, - CGFloat sx, CGFloat sy) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextTranslateCTM(CGContextRef _Nullable c, - CGFloat tx, CGFloat ty) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextRotateCTM(CGContextRef _Nullable c, CGFloat angle) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextConcatCTM(CGContextRef _Nullable c, - CGAffineTransform transform) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGAffineTransform CGContextGetCTM(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextSetLineWidth(CGContextRef _Nullable c, CGFloat width) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextSetLineCap(CGContextRef _Nullable c, CGLineCap cap) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextSetLineJoin(CGContextRef _Nullable c, CGLineJoin join) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextSetMiterLimit(CGContextRef _Nullable c, CGFloat limit) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextSetLineDash(CGContextRef _Nullable c, CGFloat phase, - const CGFloat * _Nullable lengths, size_t count) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextSetFlatness(CGContextRef _Nullable c, CGFloat flatness) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextSetAlpha(CGContextRef _Nullable c, CGFloat alpha) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextSetBlendMode(CGContextRef _Nullable c, CGBlendMode mode) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGContextBeginPath(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextMoveToPoint(CGContextRef _Nullable c, - CGFloat x, CGFloat y) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextAddLineToPoint(CGContextRef _Nullable c, - CGFloat x, CGFloat y) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextAddCurveToPoint(CGContextRef _Nullable c, CGFloat cp1x, - CGFloat cp1y, CGFloat cp2x, CGFloat cp2y, CGFloat x, CGFloat y) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextAddQuadCurveToPoint(CGContextRef _Nullable c, - CGFloat cpx, CGFloat cpy, CGFloat x, CGFloat y) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextClosePath(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextAddRect(CGContextRef _Nullable c, CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextAddRects(CGContextRef _Nullable c, - const CGRect * _Nullable rects, size_t count) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextAddLines(CGContextRef _Nullable c, - const CGPoint * _Nullable points, size_t count) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextAddEllipseInRect(CGContextRef _Nullable c, CGRect rect) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGContextAddArc(CGContextRef _Nullable c, CGFloat x, CGFloat y, - CGFloat radius, CGFloat startAngle, CGFloat endAngle, int clockwise) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" void CGContextAddArcToPoint(CGContextRef _Nullable c, - CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2, CGFloat radius) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextAddPath(CGContextRef _Nullable c, - CGPathRef _Nullable path) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" void CGContextReplacePathWithStrokedPath(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" bool CGContextIsPathEmpty(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGPoint CGContextGetPathCurrentPoint(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CGRect CGContextGetPathBoundingBox(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGPathRef _Nullable CGContextCopyPath(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" bool CGContextPathContainsPoint(CGContextRef _Nullable c, - CGPoint point, CGPathDrawingMode mode) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" void CGContextDrawPath(CGContextRef _Nullable c, - CGPathDrawingMode mode) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" void CGContextFillPath(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextEOFillPath(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextStrokePath(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextFillRect(CGContextRef _Nullable c, CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextFillRects(CGContextRef _Nullable c, - const CGRect * _Nullable rects, size_t count) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextStrokeRect(CGContextRef _Nullable c, CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextStrokeRectWithWidth(CGContextRef _Nullable c, - CGRect rect, CGFloat width) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextClearRect(CGContextRef _Nullable c, CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextFillEllipseInRect(CGContextRef _Nullable c, - CGRect rect) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGContextStrokeEllipseInRect(CGContextRef _Nullable c, - CGRect rect) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGContextStrokeLineSegments(CGContextRef _Nullable c, - const CGPoint * _Nullable points, size_t count) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" void CGContextClip(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextEOClip(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" void CGContextClipToMask(CGContextRef _Nullable c, CGRect rect, - CGImageRef _Nullable mask) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CGRect CGContextGetClipBoundingBox(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.3))); - - - - - - -extern "C" void CGContextClipToRect(CGContextRef _Nullable c, CGRect rect) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextClipToRects(CGContextRef _Nullable c, - const CGRect * rects, size_t count) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextSetFillColorWithColor(CGContextRef _Nullable c, - CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" void CGContextSetStrokeColorWithColor(CGContextRef _Nullable c, - CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - - - - - -extern "C" void CGContextSetFillColorSpace(CGContextRef _Nullable c, - CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextSetStrokeColorSpace(CGContextRef _Nullable c, - CGColorSpaceRef _Nullable space) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" void CGContextSetFillColor(CGContextRef _Nullable c, - const CGFloat * _Nullable components) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - - -extern "C" void CGContextSetStrokeColor(CGContextRef _Nullable c, - const CGFloat * _Nullable components) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" void CGContextSetFillPattern(CGContextRef _Nullable c, - CGPatternRef _Nullable pattern, const CGFloat * _Nullable components) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" void CGContextSetStrokePattern(CGContextRef _Nullable c, - CGPatternRef _Nullable pattern, const CGFloat * _Nullable components) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextSetPatternPhase(CGContextRef _Nullable c, CGSize phase) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" void CGContextSetGrayFillColor(CGContextRef _Nullable c, - CGFloat gray, CGFloat alpha) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextSetGrayStrokeColor(CGContextRef _Nullable c, - CGFloat gray, CGFloat alpha) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextSetRGBFillColor(CGContextRef _Nullable c, CGFloat red, - CGFloat green, CGFloat blue, CGFloat alpha) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextSetRGBStrokeColor(CGContextRef _Nullable c, - CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextSetCMYKFillColor(CGContextRef _Nullable c, - CGFloat cyan, CGFloat magenta, CGFloat yellow, CGFloat black, CGFloat alpha) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextSetCMYKStrokeColor(CGContextRef _Nullable c, - CGFloat cyan, CGFloat magenta, CGFloat yellow, CGFloat black, CGFloat alpha) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" void CGContextSetRenderingIntent(CGContextRef _Nullable c, - CGColorRenderingIntent intent) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" void CGContextDrawImage(CGContextRef _Nullable c, CGRect rect, - CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" void CGContextDrawTiledImage(CGContextRef _Nullable c, CGRect rect, - CGImageRef _Nullable image) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -extern "C" CGInterpolationQuality - CGContextGetInterpolationQuality(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextSetInterpolationQuality(CGContextRef _Nullable c, - CGInterpolationQuality quality) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" void CGContextSetShadowWithColor(CGContextRef _Nullable c, - CGSize offset, CGFloat blur, CGColorRef _Nullable color) - __attribute__((availability(macosx,introduced=10.3))); - - - - - - -extern "C" void CGContextSetShadow(CGContextRef _Nullable c, CGSize offset, - CGFloat blur) - __attribute__((availability(macosx,introduced=10.3))); -extern "C" void CGContextDrawLinearGradient(CGContextRef _Nullable c, - CGGradientRef _Nullable gradient, CGPoint startPoint, CGPoint endPoint, - CGGradientDrawingOptions options) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" void CGContextDrawRadialGradient(CGContextRef _Nullable c, - CGGradientRef _Nullable gradient, CGPoint startCenter, CGFloat startRadius, - CGPoint endCenter, CGFloat endRadius, CGGradientDrawingOptions options) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" void CGContextDrawShading(CGContextRef _Nullable c, - _Nullable CGShadingRef shading) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - - -extern "C" void CGContextSetCharacterSpacing(CGContextRef _Nullable c, - CGFloat spacing) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextSetTextPosition(CGContextRef _Nullable c, - CGFloat x, CGFloat y) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGPoint CGContextGetTextPosition(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextSetTextMatrix(CGContextRef _Nullable c, - CGAffineTransform t) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGAffineTransform CGContextGetTextMatrix(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextSetTextDrawingMode(CGContextRef _Nullable c, - CGTextDrawingMode mode) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextSetFont(CGContextRef _Nullable c, - CGFontRef _Nullable font) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGContextSetFontSize(CGContextRef _Nullable c, CGFloat size) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" void CGContextShowGlyphsAtPositions(CGContextRef _Nullable c, - const CGGlyph * _Nullable glyphs, const CGPoint * _Nullable Lpositions, - size_t count) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" void CGContextDrawPDFPage(CGContextRef _Nullable c, - CGPDFPageRef _Nullable page) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" void CGContextBeginPage(CGContextRef _Nullable c, - const CGRect * _Nullable mediaBox) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextEndPage(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CGContextRef _Nullable CGContextRetain(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextRelease(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextFlush(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGContextSynchronize(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" void CGContextSetShouldAntialias(CGContextRef _Nullable c, - bool shouldAntialias) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" void CGContextSetAllowsAntialiasing(CGContextRef _Nullable c, - bool allowsAntialiasing) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGContextSetShouldSmoothFonts(CGContextRef _Nullable c, - bool shouldSmoothFonts) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - - -extern "C" void CGContextSetAllowsFontSmoothing(CGContextRef _Nullable c, - bool allowsFontSmoothing) - __attribute__((availability(macosx,introduced=10.2))); - - - - - - -extern "C" void CGContextSetShouldSubpixelPositionFonts( - CGContextRef _Nullable c, bool shouldSubpixelPositionFonts) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" void CGContextSetAllowsFontSubpixelPositioning( - CGContextRef _Nullable c, bool allowsFontSubpixelPositioning) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern "C" void CGContextSetShouldSubpixelQuantizeFonts( - CGContextRef _Nullable c, bool shouldSubpixelQuantizeFonts) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" void CGContextSetAllowsFontSubpixelQuantization( - CGContextRef _Nullable c, bool allowsFontSubpixelQuantization) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" void CGContextBeginTransparencyLayer(CGContextRef _Nullable c, - CFDictionaryRef _Nullable auxiliaryInfo) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" void CGContextBeginTransparencyLayerWithRect( - CGContextRef _Nullable c, CGRect rect, CFDictionaryRef _Nullable auxInfo) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" void CGContextEndTransparencyLayer(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.3))); - - - - - - -extern "C" CGAffineTransform - CGContextGetUserSpaceToDeviceSpaceTransform(CGContextRef _Nullable c) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGPoint CGContextConvertPointToDeviceSpace(CGContextRef _Nullable c, - CGPoint point) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGPoint CGContextConvertPointToUserSpace(CGContextRef _Nullable c, - CGPoint point) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGSize CGContextConvertSizeToDeviceSpace(CGContextRef _Nullable c, - CGSize size) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGSize CGContextConvertSizeToUserSpace(CGContextRef _Nullable c, - CGSize size) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" CGRect CGContextConvertRectToDeviceSpace(CGContextRef _Nullable c, - CGRect rect) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" CGRect CGContextConvertRectToUserSpace(CGContextRef _Nullable c, - CGRect rect) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" void CGContextSelectFont(CGContextRef _Nullable c, - const char * _Nullable name, CGFloat size, CGTextEncoding textEncoding) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - - - - -extern "C" void CGContextShowText(CGContextRef _Nullable c, - const char * _Nullable string, size_t length) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - - - - -extern "C" void CGContextShowTextAtPoint(CGContextRef _Nullable c, - CGFloat x, CGFloat y, const char * _Nullable string, size_t length) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - - - - -extern "C" void CGContextShowGlyphs(CGContextRef _Nullable c, - const CGGlyph * _Nullable g, size_t count) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - - - - -extern "C" void CGContextShowGlyphsAtPoint(CGContextRef _Nullable c, CGFloat x, - CGFloat y, const CGGlyph * _Nullable glyphs, size_t count) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - - - - -extern "C" void CGContextShowGlyphsWithAdvances(CGContextRef _Nullable c, - const CGGlyph * _Nullable glyphs, const CGSize * _Nullable advances, - size_t count) - __attribute__((availability(macosx,introduced=10.3,deprecated=10.9))); - - - - -extern "C" void CGContextDrawPDFDocument(CGContextRef _Nullable c, CGRect rect, - CGPDFDocumentRef _Nullable document, int page) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -typedef void (*CGBitmapContextReleaseDataCallback)(void * _Nullable releaseInfo, - void * _Nullable data); -extern "C" CGContextRef _Nullable CGBitmapContextCreateWithData( - void * _Nullable data, size_t width, size_t height, size_t bitsPerComponent, - size_t bytesPerRow, CGColorSpaceRef _Nullable space, uint32_t bitmapInfo, - CGBitmapContextReleaseDataCallback _Nullable releaseCallback, - void * _Nullable releaseInfo) - __attribute__((availability(macosx,introduced=10.6))); -extern "C" CGContextRef _Nullable CGBitmapContextCreate(void * _Nullable data, - size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow, - CGColorSpaceRef _Nullable space, uint32_t bitmapInfo) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void * _Nullable CGBitmapContextGetData(CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" size_t CGBitmapContextGetWidth(CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" size_t CGBitmapContextGetHeight(CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" size_t CGBitmapContextGetBitsPerComponent(CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" size_t CGBitmapContextGetBitsPerPixel(CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" size_t CGBitmapContextGetBytesPerRow(CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGColorSpaceRef _Nullable CGBitmapContextGetColorSpace( - CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGImageAlphaInfo CGBitmapContextGetAlphaInfo( - CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGBitmapInfo CGBitmapContextGetBitmapInfo( - CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGImageRef _Nullable CGBitmapContextCreateImage( - CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.4))); - - - -typedef struct CGDataConsumer *CGDataConsumerRef; -typedef size_t (*CGDataConsumerPutBytesCallback)(void * _Nullable info, - const void * buffer, size_t count); - - - - -typedef void (*CGDataConsumerReleaseInfoCallback)(void * _Nullable info); - - - - - - - -struct CGDataConsumerCallbacks { - CGDataConsumerPutBytesCallback _Nullable putBytes; - CGDataConsumerReleaseInfoCallback _Nullable releaseConsumer; -}; -typedef struct CGDataConsumerCallbacks CGDataConsumerCallbacks; - - - -extern "C" CFTypeID CGDataConsumerGetTypeID(void) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGDataConsumerRef _Nullable CGDataConsumerCreate( - void * _Nullable info, const CGDataConsumerCallbacks * _Nullable cbks) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGDataConsumerRef _Nullable CGDataConsumerCreateWithURL( - CFURLRef _Nullable url) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGDataConsumerRef _Nullable CGDataConsumerCreateWithCFData( - CFMutableDataRef _Nullable data) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGDataConsumerRef _Nullable CGDataConsumerRetain( - CGDataConsumerRef _Nullable consumer) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" void CGDataConsumerRelease(_Nullable CGDataConsumerRef consumer) - __attribute__((availability(macosx,introduced=10.0))); - -typedef int32_t CGError; enum { - kCGErrorSuccess = 0, - kCGErrorFailure = 1000, - kCGErrorIllegalArgument = 1001, - kCGErrorInvalidConnection = 1002, - kCGErrorInvalidContext = 1003, - kCGErrorCannotComplete = 1004, - kCGErrorNotImplemented = 1006, - kCGErrorRangeCheck = 1007, - kCGErrorTypeCheck = 1008, - kCGErrorInvalidOperation = 1010, - kCGErrorNoneAvailable = 1011, -}; - - - - - -typedef struct CGLayer *CGLayerRef; -extern "C" CGLayerRef _Nullable CGLayerCreateWithContext( - CGContextRef _Nullable context, - CGSize size, CFDictionaryRef _Nullable auxiliaryInfo) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGLayerRef _Nullable CGLayerRetain(CGLayerRef _Nullable layer) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" void CGLayerRelease(CGLayerRef _Nullable layer) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGSize CGLayerGetSize(CGLayerRef _Nullable layer) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGContextRef _Nullable CGLayerGetContext(CGLayerRef _Nullable layer) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" void CGContextDrawLayerInRect(CGContextRef _Nullable context, - CGRect rect, CGLayerRef _Nullable layer) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" void CGContextDrawLayerAtPoint(CGContextRef _Nullable context, - CGPoint point, CGLayerRef _Nullable layer) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CFTypeID CGLayerGetTypeID(void) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - - -typedef struct CGPDFContentStream *CGPDFContentStreamRef; - - - - - - - -extern "C" CGPDFContentStreamRef CGPDFContentStreamCreateWithPage( - CGPDFPageRef page) __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGPDFContentStreamRef CGPDFContentStreamCreateWithStream( - CGPDFStreamRef stream, CGPDFDictionaryRef streamResources, - CGPDFContentStreamRef parent) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGPDFContentStreamRef CGPDFContentStreamRetain( - CGPDFContentStreamRef cs) __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGPDFContentStreamRelease(CGPDFContentStreamRef cs) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CFArrayRef CGPDFContentStreamGetStreams(CGPDFContentStreamRef cs) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGPDFObjectRef CGPDFContentStreamGetResource( - CGPDFContentStreamRef cs, const char *category, const char *name) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGContextRef _Nullable CGPDFContextCreate(CGDataConsumerRef _Nullable consumer, - const CGRect *_Nullable mediaBox, CFDictionaryRef _Nullable auxiliaryInfo) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CGContextRef _Nullable CGPDFContextCreateWithURL(CFURLRef _Nullable url, - const CGRect * _Nullable mediaBox, CFDictionaryRef _Nullable auxiliaryInfo) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" void CGPDFContextClose(CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" void CGPDFContextBeginPage(CGContextRef _Nullable context, - CFDictionaryRef _Nullable pageInfo) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGPDFContextEndPage(CGContextRef _Nullable context) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGPDFContextAddDocumentMetadata(CGContextRef _Nullable context, - CFDataRef _Nullable metadata) __attribute__((availability(macosx,introduced=10.7))); - - - - -extern "C" void CGPDFContextSetURLForRect(CGContextRef _Nullable context, CFURLRef url, - CGRect rect) __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" void CGPDFContextAddDestinationAtPoint(CGContextRef _Nullable context, - CFStringRef name, CGPoint point) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" void CGPDFContextSetDestinationForRect(CGContextRef _Nullable context, - CFStringRef name, CGRect rect) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" const CFStringRef kCGPDFContextMediaBox - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" const CFStringRef kCGPDFContextCropBox - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" const CFStringRef kCGPDFContextBleedBox - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" const CFStringRef kCGPDFContextTrimBox - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" const CFStringRef kCGPDFContextArtBox - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" const CFStringRef kCGPDFContextTitle - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGPDFContextAuthor - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGPDFContextSubject - __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGPDFContextKeywords - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" const CFStringRef kCGPDFContextCreator - __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGPDFContextOwnerPassword - __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGPDFContextUserPassword - __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGPDFContextEncryptionKeyLength - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" const CFStringRef kCGPDFContextAllowsPrinting - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" const CFStringRef kCGPDFContextAllowsCopying - __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGPDFContextOutputIntent - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" const CFStringRef kCGPDFXOutputIntentSubtype - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" const CFStringRef kCGPDFXOutputConditionIdentifier - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" const CFStringRef kCGPDFXOutputCondition - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" const CFStringRef kCGPDFXRegistryName - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" const CFStringRef kCGPDFXInfo - __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGPDFXDestinationOutputProfile - __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGPDFContextOutputIntents - __attribute__((availability(macosx,introduced=10.4))); - - - -typedef struct CGPDFOperatorTable *CGPDFOperatorTableRef; - - -typedef struct CGPDFScanner *CGPDFScannerRef; - - - - - - - - - - -extern "C" CGPDFScannerRef CGPDFScannerCreate( - CGPDFContentStreamRef cs, - CGPDFOperatorTableRef _Nullable table, void * _Nullable info) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGPDFScannerRef _Nullable CGPDFScannerRetain( - CGPDFScannerRef _Nullable scanner) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGPDFScannerRelease(CGPDFScannerRef _Nullable scanner) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" bool CGPDFScannerScan(CGPDFScannerRef _Nullable scanner) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGPDFContentStreamRef CGPDFScannerGetContentStream( - CGPDFScannerRef scanner) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" bool CGPDFScannerPopObject(CGPDFScannerRef scanner, - CGPDFObjectRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" bool CGPDFScannerPopBoolean(CGPDFScannerRef scanner, - CGPDFBoolean * _Nullable value) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" bool CGPDFScannerPopInteger(CGPDFScannerRef scanner, - CGPDFInteger * _Nullable value) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" bool CGPDFScannerPopNumber(CGPDFScannerRef scanner, - CGPDFReal * _Nullable value) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" bool CGPDFScannerPopName(CGPDFScannerRef scanner, - const char * _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" bool CGPDFScannerPopString(CGPDFScannerRef scanner, - CGPDFStringRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" bool CGPDFScannerPopArray(CGPDFScannerRef scanner, - CGPDFArrayRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" bool CGPDFScannerPopDictionary(CGPDFScannerRef scanner, - CGPDFDictionaryRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" bool CGPDFScannerPopStream(CGPDFScannerRef scanner, - CGPDFStreamRef _Nullable * _Nullable value) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -typedef void (*CGPDFOperatorCallback)(CGPDFScannerRef scanner, - void * _Nullable info); - - - -extern "C" CGPDFOperatorTableRef _Nullable CGPDFOperatorTableCreate(void) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGPDFOperatorTableRef _Nullable CGPDFOperatorTableRetain( - CGPDFOperatorTableRef _Nullable table) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGPDFOperatorTableRelease( - CGPDFOperatorTableRef _Nullable table) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGPDFOperatorTableSetCallback( - CGPDFOperatorTableRef _Nullable table, - const char * _Nullable name, CGPDFOperatorCallback _Nullable callback) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - - -typedef uint32_t CGDirectDisplayID; -typedef uint32_t CGOpenGLDisplayMask; -typedef double CGRefreshRate; - -typedef struct CGDisplayMode *CGDisplayModeRef; -extern "C" CGDirectDisplayID CGMainDisplayID(void) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" CGError CGGetDisplaysWithPoint(CGPoint point, uint32_t maxDisplays, - CGDirectDisplayID * _Nullable displays, - uint32_t * _Nullable matchingDisplayCount) - __attribute__((availability(macosx,introduced=10.0))); - -extern "C" CGError CGGetDisplaysWithRect(CGRect rect, uint32_t maxDisplays, - CGDirectDisplayID * _Nullable displays, - uint32_t * _Nullable matchingDisplayCount) - __attribute__((availability(macosx,introduced=10.0))); - -extern "C" CGError CGGetDisplaysWithOpenGLDisplayMask(CGOpenGLDisplayMask mask, - uint32_t maxDisplays, CGDirectDisplayID * _Nullable displays, - uint32_t * _Nullable matchingDisplayCount) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGError CGGetActiveDisplayList(uint32_t maxDisplays, - CGDirectDisplayID * _Nullable activeDisplays, - uint32_t * _Nullable displayCount) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGError CGGetOnlineDisplayList(uint32_t maxDisplays, - CGDirectDisplayID * _Nullable onlineDisplays, - uint32_t * _Nullable displayCount) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGOpenGLDisplayMask CGDisplayIDToOpenGLDisplayMask( - CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CGDirectDisplayID CGOpenGLDisplayMaskToDisplayID( - CGOpenGLDisplayMask mask) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGRect CGDisplayBounds(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" size_t CGDisplayPixelsWide(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" size_t CGDisplayPixelsHigh(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CFArrayRef _Nullable CGDisplayCopyAllDisplayModes( - CGDirectDisplayID display, CFDictionaryRef _Nullable options) - __attribute__((availability(macosx,introduced=10.6))); - -extern "C" const CFStringRef kCGDisplayShowDuplicateLowResolutionModes - __attribute__((availability(macosx,introduced=10.8))); - - - - -extern "C" CGDisplayModeRef _Nullable CGDisplayCopyDisplayMode( - CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.6))); -extern "C" CGError CGDisplaySetDisplayMode(CGDirectDisplayID display, - CGDisplayModeRef _Nullable mode, CFDictionaryRef _Nullable options) - __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" size_t CGDisplayModeGetWidth(CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" size_t CGDisplayModeGetHeight(CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.6))); - - - - -extern "C" CFStringRef _Nullable CGDisplayModeCopyPixelEncoding( - CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.6,deprecated=10.11))); - - - - -extern "C" double CGDisplayModeGetRefreshRate(CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" uint32_t CGDisplayModeGetIOFlags(CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" int32_t CGDisplayModeGetIODisplayModeID( - CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.6))); - - - - -extern "C" bool CGDisplayModeIsUsableForDesktopGUI( - CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" CFTypeID CGDisplayModeGetTypeID(void) - __attribute__((availability(macosx,introduced=10.6))); - - - - -extern "C" CGDisplayModeRef _Nullable CGDisplayModeRetain( - CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.6))); - - - - -extern "C" void CGDisplayModeRelease(CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" size_t CGDisplayModeGetPixelWidth(CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.8))); - - - -extern "C" size_t CGDisplayModeGetPixelHeight(CGDisplayModeRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.8))); -typedef float CGGammaValue; - -extern "C" CGError CGSetDisplayTransferByFormula(CGDirectDisplayID display, - CGGammaValue redMin, CGGammaValue redMax, CGGammaValue redGamma, - CGGammaValue greenMin, CGGammaValue greenMax, CGGammaValue greenGamma, - CGGammaValue blueMin, CGGammaValue blueMax, CGGammaValue blueGamma) - __attribute__((availability(macosx,introduced=10.0))); - - - -extern "C" CGError CGGetDisplayTransferByFormula(CGDirectDisplayID display, - CGGammaValue * _Nullable redMin, CGGammaValue * _Nullable redMax, - CGGammaValue * _Nullable redGamma, - CGGammaValue * _Nullable greenMin, CGGammaValue * _Nullable greenMax, - CGGammaValue * _Nullable greenGamma, - CGGammaValue * _Nullable blueMin, CGGammaValue * _Nullable blueMax, - CGGammaValue * _Nullable blueGamma) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" uint32_t CGDisplayGammaTableCapacity(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.3))); -extern "C" CGError CGSetDisplayTransferByTable(CGDirectDisplayID display, - uint32_t tableSize, const CGGammaValue * _Nullable redTable, - const CGGammaValue * _Nullable greenTable, - const CGGammaValue * _Nullable blueTable) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - - -extern "C" CGError CGGetDisplayTransferByTable(CGDirectDisplayID display, - uint32_t capacity, CGGammaValue * _Nullable redTable, - CGGammaValue * _Nullable greenTable, - CGGammaValue * _Nullable blueTable, uint32_t * _Nullable sampleCount) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGError CGSetDisplayTransferByByteTable(CGDirectDisplayID display, - uint32_t tableSize, const uint8_t * redTable, - const uint8_t * greenTable, const uint8_t * blueTable) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGDisplayRestoreColorSyncSettings(void) - __attribute__((availability(macosx,introduced=10.0))); - - - - -typedef uint32_t CGCaptureOptions; enum { - kCGCaptureNoOptions = 0, - kCGCaptureNoFill __attribute__((deprecated)) = (1 << 0) -}; - - - -extern "C" boolean_t CGDisplayIsCaptured(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - - - -extern "C" CGError CGDisplayCapture(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGError CGDisplayCaptureWithOptions(CGDirectDisplayID display, - CGCaptureOptions options) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGError CGDisplayRelease(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CGError CGCaptureAllDisplays(void) - __attribute__((availability(macosx,introduced=10.0))); - - - - - -extern "C" CGError CGCaptureAllDisplaysWithOptions(CGCaptureOptions options) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" CGError CGReleaseAllDisplays(void) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" uint32_t CGShieldingWindowID(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" int32_t CGShieldingWindowLevel(void) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGImageRef _Nullable CGDisplayCreateImage(CGDirectDisplayID displayID) - __attribute__((availability(macosx,introduced=10.6))); - - - - - - -extern "C" CGImageRef _Nullable CGDisplayCreateImageForRect( - CGDirectDisplayID display, CGRect rect) - __attribute__((availability(macosx,introduced=10.6))); - - - - -extern "C" CGError CGDisplayHideCursor(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" CGError CGDisplayShowCursor(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0))); - - - - - - -extern "C" CGError CGDisplayMoveCursorToPoint(CGDirectDisplayID display, - CGPoint point) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGGetLastMouseDelta(int32_t *_Nullable deltaX, - int32_t * _Nullable deltaY) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGContextRef _Nullable CGDisplayGetDrawingContext( - CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.3))); -typedef uint32_t CGDisplayCount; -typedef CGError CGDisplayErr; - - - - - -extern "C" CFArrayRef _Nullable CGDisplayAvailableModes(CGDirectDisplayID dsp) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - -extern "C" CFDictionaryRef _Nullable CGDisplayBestModeForParameters( - CGDirectDisplayID display, size_t bitsPerPixel, size_t width, size_t height, - boolean_t * _Nullable exactMatch) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - -extern "C" CFDictionaryRef _Nullable CGDisplayBestModeForParametersAndRefreshRate( - CGDirectDisplayID display, size_t bitsPerPixel, size_t width, size_t height, - CGRefreshRate refreshRate, boolean_t * _Nullable exactMatch) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - -extern "C" CFDictionaryRef _Nullable CGDisplayCurrentMode( - CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - -extern "C" CGError CGDisplaySwitchToMode(CGDirectDisplayID display, - CFDictionaryRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -struct CGDeviceColor { - float red; - float green; - float blue; -}; -typedef struct CGDeviceColor CGDeviceColor; -typedef struct _CGDisplayConfigRef *CGDisplayConfigRef; - - - - - - -extern "C" CGError CGBeginDisplayConfiguration( - CGDisplayConfigRef _Nullable * _Nullable config) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGError CGConfigureDisplayOrigin( - CGDisplayConfigRef _Nullable config, - CGDirectDisplayID display, int32_t x, int32_t y) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGError CGConfigureDisplayWithDisplayMode( - CGDisplayConfigRef _Nullable config, - CGDirectDisplayID display, CGDisplayModeRef _Nullable mode, - CFDictionaryRef _Nullable options) - __attribute__((availability(macosx,introduced=10.6))); -extern "C" CGError CGConfigureDisplayStereoOperation( - CGDisplayConfigRef _Nullable config, - CGDirectDisplayID display, boolean_t stereo, boolean_t forceBlueLine) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGError CGConfigureDisplayMirrorOfDisplay( - CGDisplayConfigRef _Nullable config, - CGDirectDisplayID display, CGDirectDisplayID master) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" CGError CGCancelDisplayConfiguration( - CGDisplayConfigRef _Nullable config) - __attribute__((availability(macosx,introduced=10.0))); -typedef uint32_t CGConfigureOption; enum { - kCGConfigureForAppOnly = 0, - kCGConfigureForSession = 1, - kCGConfigurePermanently = 2 -}; - -extern "C" CGError CGCompleteDisplayConfiguration( - CGDisplayConfigRef _Nullable config, - CGConfigureOption option) - __attribute__((availability(macosx,introduced=10.0))); - - - - -extern "C" void CGRestorePermanentDisplayConfiguration(void) - __attribute__((availability(macosx,introduced=10.2))); -typedef uint32_t CGDisplayChangeSummaryFlags; enum { - kCGDisplayBeginConfigurationFlag = (1 << 0), - kCGDisplayMovedFlag = (1 << 1), - kCGDisplaySetMainFlag = (1 << 2), - kCGDisplaySetModeFlag = (1 << 3), - kCGDisplayAddFlag = (1 << 4), - kCGDisplayRemoveFlag = (1 << 5), - kCGDisplayEnabledFlag = (1 << 8), - kCGDisplayDisabledFlag = (1 << 9), - kCGDisplayMirrorFlag = (1 << 10), - kCGDisplayUnMirrorFlag = (1 << 11), - kCGDisplayDesktopShapeChangedFlag = (1 << 12) -}; - - - - -typedef void(*CGDisplayReconfigurationCallBack)(CGDirectDisplayID display, - CGDisplayChangeSummaryFlags flags, void * _Nullable userInfo); - - - - - -extern "C" CGError CGDisplayRegisterReconfigurationCallback( - CGDisplayReconfigurationCallBack _Nullable callback, - void * _Nullable userInfo) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CGError CGDisplayRemoveReconfigurationCallback( - CGDisplayReconfigurationCallBack _Nullable callback, - void * _Nullable userInfo) - __attribute__((availability(macosx,introduced=10.3))); -extern "C" CGError CGDisplaySetStereoOperation(CGDirectDisplayID display, - boolean_t stereo, boolean_t forceBlueLine, CGConfigureOption option) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" boolean_t CGDisplayIsActive(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" boolean_t CGDisplayIsAsleep(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" boolean_t CGDisplayIsOnline(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" boolean_t CGDisplayIsMain(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" boolean_t CGDisplayIsBuiltin(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" boolean_t CGDisplayIsInMirrorSet(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" boolean_t CGDisplayIsAlwaysInMirrorSet(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" boolean_t CGDisplayIsInHWMirrorSet(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - - - -extern "C" CGDirectDisplayID CGDisplayMirrorsDisplay(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" boolean_t CGDisplayUsesOpenGLAcceleration(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" boolean_t CGDisplayIsStereo(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGDirectDisplayID CGDisplayPrimaryDisplay(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" uint32_t CGDisplayUnitNumber(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" uint32_t CGDisplayVendorNumber(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" uint32_t CGDisplayModelNumber(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" uint32_t CGDisplaySerialNumber(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2))); - - - -extern "C" io_service_t CGDisplayIOServicePort(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -extern "C" CGSize CGDisplayScreenSize(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.3))); -extern "C" double CGDisplayRotation(CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" CGColorSpaceRef CGDisplayCopyColorSpace( - CGDirectDisplayID display) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" CGError CGConfigureDisplayMode(CGDisplayConfigRef _Nullable config, - CGDirectDisplayID display, CFDictionaryRef _Nullable mode) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -typedef uint32_t CGDisplayFadeReservationToken; - - -typedef float CGDisplayBlendFraction; -typedef float CGDisplayFadeInterval; -extern "C" CGError CGConfigureDisplayFadeEffect( - CGDisplayConfigRef _Nullable config, - CGDisplayFadeInterval fadeOutSeconds, CGDisplayFadeInterval fadeInSeconds, - float fadeRed, float fadeGreen, float fadeBlue) - __attribute__((availability(macosx,introduced=10.2))); -typedef float CGDisplayReservationInterval; - - - -extern "C" CGError CGAcquireDisplayFadeReservation(CGDisplayReservationInterval - seconds, CGDisplayFadeReservationToken * _Nullable token) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" CGError CGReleaseDisplayFadeReservation( - CGDisplayFadeReservationToken token) - __attribute__((availability(macosx,introduced=10.2))); -extern "C" CGError CGDisplayFade(CGDisplayFadeReservationToken token, - CGDisplayFadeInterval duration, CGDisplayBlendFraction startBlend, - CGDisplayBlendFraction endBlend, float redBlend, float greenBlend, - float blueBlend, boolean_t synchronous) - __attribute__((availability(macosx,introduced=10.2))); - - - - -extern "C" boolean_t CGDisplayFadeOperationInProgress(void) - __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); - - - - - - - - -extern "C" { - -int mlockall(int); -int munlockall(void); - -int mlock(const void *, size_t); - - - -void * mmap(void *, size_t, int, int, int, off_t) __asm("_" "mmap" ); - - -int mprotect(void *, size_t, int) __asm("_" "mprotect" ); - -int msync(void *, size_t, int) __asm("_" "msync" ); - -int munlock(const void *, size_t); - -int munmap(void *, size_t) __asm("_" "munmap" ); - -int shm_open(const char *, int, ...); -int shm_unlink(const char *); - -int posix_madvise(void *, size_t, int); - - -int madvise(void *, size_t, int); -int mincore(const void *, size_t, char *); -int minherit(void *, size_t, int); - - - -} - -extern "C" { - -typedef uid_t au_id_t; -typedef pid_t au_asid_t; -typedef u_int16_t au_event_t; -typedef u_int16_t au_emod_t; -typedef u_int32_t au_class_t; -typedef u_int64_t au_asflgs_t __attribute__ ((aligned (8))); - -struct au_tid { - dev_t port; - u_int32_t machine; -}; -typedef struct au_tid au_tid_t; - -struct au_tid_addr { - dev_t at_port; - u_int32_t at_type; - u_int32_t at_addr[4]; -}; -typedef struct au_tid_addr au_tid_addr_t; - -struct au_mask { - unsigned int am_success; - unsigned int am_failure; -}; -typedef struct au_mask au_mask_t; - -struct auditinfo { - au_id_t ai_auid; - au_mask_t ai_mask; - au_tid_t ai_termid; - au_asid_t ai_asid; -}; -typedef struct auditinfo auditinfo_t; - -struct auditinfo_addr { - au_id_t ai_auid; - au_mask_t ai_mask; - au_tid_addr_t ai_termid; - au_asid_t ai_asid; - au_asflgs_t ai_flags; -}; -typedef struct auditinfo_addr auditinfo_addr_t; - -struct auditpinfo { - pid_t ap_pid; - au_id_t ap_auid; - au_mask_t ap_mask; - au_tid_t ap_termid; - au_asid_t ap_asid; -}; -typedef struct auditpinfo auditpinfo_t; - -struct auditpinfo_addr { - pid_t ap_pid; - au_id_t ap_auid; - au_mask_t ap_mask; - au_tid_addr_t ap_termid; - au_asid_t ap_asid; - au_asflgs_t ap_flags; -}; -typedef struct auditpinfo_addr auditpinfo_addr_t; - -struct au_session { - auditinfo_addr_t *as_aia_p; - au_mask_t as_mask; -}; -typedef struct au_session au_session_t; - - - - -typedef struct au_token token_t; -struct au_qctrl { - int aq_hiwater; - - - int aq_lowater; - - - int aq_bufsz; - int aq_delay; - int aq_minfree; -}; -typedef struct au_qctrl au_qctrl_t; - - - - -struct audit_stat { - unsigned int as_version; - unsigned int as_numevent; - int as_generated; - int as_nonattrib; - int as_kernel; - int as_audit; - int as_auditctl; - int as_enqueue; - int as_written; - int as_wblocked; - int as_rblocked; - int as_dropped; - int as_totalsize; - unsigned int as_memused; -}; -typedef struct audit_stat au_stat_t; - - - - -struct audit_fstat { - u_int64_t af_filesz; - u_int64_t af_currsz; -}; -typedef struct audit_fstat au_fstat_t; - - - - -struct au_evclass_map { - au_event_t ec_number; - au_class_t ec_class; -}; -typedef struct au_evclass_map au_evclass_map_t; - - - - - -int audit(const void *, int); -int auditon(int, void *, int); -int auditctl(const char *); -int getauid(au_id_t *); -int setauid(const au_id_t *); -int getaudit_addr(struct auditinfo_addr *, int); -int setaudit_addr(const struct auditinfo_addr *, int); -int getaudit(struct auditinfo *) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - -int setaudit(const struct auditinfo *) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -mach_port_name_t audit_session_self(void); -au_asid_t audit_session_join(mach_port_name_t port); -int audit_session_port(au_asid_t asid, mach_port_name_t *portname); - - - - -} - - - - - - - - -extern "C" { - - - - - - - -extern "C" { -} - - - - - - - -typedef const struct _xpc_type_s * xpc_type_t; -// @protocol OS_xpc_object <NSObject> /* @end */ - typedef NSObject/*<OS_xpc_object>*/ *xpc_object_t; - - - - - - -static __inline__ __attribute__((__always_inline__)) __attribute__((__nonnull__)) -void -_xpc_object_validate(xpc_object_t object) { - void *isa = *(void * volatile *)( void *)object; - (void)isa; -} -typedef void (*xpc_handler_t)(xpc_object_t object); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_connection; -typedef xpc_object_t xpc_connection_t; -typedef void (*xpc_connection_handler_t)(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_endpoint; -typedef xpc_object_t xpc_endpoint_t; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_null; - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_bool; - - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_bool_s _xpc_bool_true; - - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_bool_s _xpc_bool_false; - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_int64; - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_uint64; - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_double; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_date; - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_data; - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_string; - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_uuid; - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_fd; - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_shmem; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_array; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_dictionary; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_error; - - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const char *const _xpc_error_key_description; - - - - - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const char *const _xpc_event_key_name; - - - -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -xpc_endpoint_t -xpc_endpoint_create(xpc_connection_t connection); -__attribute__((visibility("hidden"))) __attribute__((__used__)) -const char * -xpc_debugger_api_misuse_info(void); - -extern "C" { -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_dictionary_s _xpc_error_connection_interrupted; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_dictionary_s _xpc_error_connection_invalid; -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -const struct _xpc_dictionary_s _xpc_error_termination_imminent; -typedef void (*xpc_finalizer_t)(void *value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_connection_t -xpc_connection_create(const char *name, dispatch_queue_t targetq); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -xpc_connection_t -xpc_connection_create_mach_service(const char *name, dispatch_queue_t targetq, - uint64_t flags); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -xpc_connection_t -xpc_connection_create_from_endpoint(xpc_endpoint_t endpoint); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_connection_set_target_queue(xpc_connection_t connection, - dispatch_queue_t targetq); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) -void -xpc_connection_set_event_handler(xpc_connection_t connection, - xpc_handler_t handler); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) -void -xpc_connection_suspend(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) -void -xpc_connection_resume(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) -void -xpc_connection_send_message(xpc_connection_t connection, xpc_object_t message); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) -void -xpc_connection_send_barrier(xpc_connection_t connection, - dispatch_block_t barrier); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) __attribute__((__nonnull__(4))) -void -xpc_connection_send_message_with_reply(xpc_connection_t connection, - xpc_object_t message, dispatch_queue_t replyq, xpc_handler_t handler); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) __attribute__((__ns_returns_retained__)) -xpc_object_t -xpc_connection_send_message_with_reply_sync(xpc_connection_t connection, - xpc_object_t message); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) -void -xpc_connection_cancel(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) -const char * -xpc_connection_get_name(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) -uid_t -xpc_connection_get_euid(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) -gid_t -xpc_connection_get_egid(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) -pid_t -xpc_connection_get_pid(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) -au_asid_t -xpc_connection_get_asid(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_connection_set_context(xpc_connection_t connection, void *context); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) -void * -xpc_connection_get_context(xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_connection_set_finalizer_f(xpc_connection_t connection, - xpc_finalizer_t finalizer); - -} -extern "C" { -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_INTERVAL; - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_REPEATING; - - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_DELAY; - - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_GRACE_PERIOD; - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const int64_t XPC_ACTIVITY_INTERVAL_1_MIN; - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const int64_t XPC_ACTIVITY_INTERVAL_5_MIN; - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const int64_t XPC_ACTIVITY_INTERVAL_15_MIN; - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const int64_t XPC_ACTIVITY_INTERVAL_30_MIN; - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const int64_t XPC_ACTIVITY_INTERVAL_1_HOUR; - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const int64_t XPC_ACTIVITY_INTERVAL_4_HOURS; - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const int64_t XPC_ACTIVITY_INTERVAL_8_HOURS; - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const int64_t XPC_ACTIVITY_INTERVAL_1_DAY; - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const int64_t XPC_ACTIVITY_INTERVAL_7_DAYS; - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_PRIORITY; - - - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_PRIORITY_MAINTENANCE; - - - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_PRIORITY_UTILITY; - - - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_ALLOW_BATTERY; - - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_REQUIRE_SCREEN_SLEEP; - - - - - - - -__attribute__((availability(macosx,introduced=10.9,deprecated=10.9,message="REQUIRE_BATTERY_LEVEL is not implemented"))) - -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_REQUIRE_BATTERY_LEVEL; - - - - - - - -__attribute__((availability(macosx,introduced=10.9,deprecated=10.9,message="REQUIRE_HDD_SPINNING is not implemented"))) - -extern __attribute__((visibility("default"))) -const char *XPC_ACTIVITY_REQUIRE_HDD_SPINNING; -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const struct _xpc_type_s _xpc_type_activity; -typedef xpc_object_t xpc_activity_t; - - - - - - - -typedef void (*xpc_activity_handler_t)(xpc_activity_t activity); -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -const xpc_object_t XPC_ACTIVITY_CHECK_IN; -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) __attribute__((__nonnull__(3))) -void -xpc_activity_register(const char *identifier, xpc_object_t criteria, - xpc_activity_handler_t handler); -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__ns_returns_retained__)) -xpc_object_t -xpc_activity_copy_criteria(xpc_activity_t activity); - - - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_activity_set_criteria(xpc_activity_t activity, xpc_object_t criteria); -enum { - XPC_ACTIVITY_STATE_CHECK_IN, - XPC_ACTIVITY_STATE_WAIT, - XPC_ACTIVITY_STATE_RUN, - XPC_ACTIVITY_STATE_DEFER, - XPC_ACTIVITY_STATE_CONTINUE, - XPC_ACTIVITY_STATE_DONE, -}; -typedef long xpc_activity_state_t; - - - - - - - -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -xpc_activity_state_t -xpc_activity_get_state(xpc_activity_t activity); -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -bool -xpc_activity_set_state(xpc_activity_t activity, xpc_activity_state_t state); -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) -bool -xpc_activity_should_defer(xpc_activity_t activity); -__attribute__((availability(macosx,introduced=10.9))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_activity_unregister(const char *identifier); - -} - - - - - - - - -typedef struct { - unsigned char mig_vers; - unsigned char if_vers; - unsigned char reserved1; - unsigned char mig_encoding; - unsigned char int_rep; - unsigned char char_rep; - unsigned char float_rep; - unsigned char reserved2; -} NDR_record_t; -extern NDR_record_t NDR_record; - - -typedef mach_port_t notify_port_t; -typedef struct { - mach_msg_header_t not_header; - NDR_record_t NDR; - mach_port_name_t not_port; - mach_msg_format_0_trailer_t trailer; -} mach_port_deleted_notification_t; - -typedef struct { - mach_msg_header_t not_header; - NDR_record_t NDR; - mach_port_name_t not_port; - mach_msg_format_0_trailer_t trailer; -} mach_send_possible_notification_t; - -typedef struct { - mach_msg_header_t not_header; - mach_msg_body_t not_body; - mach_msg_port_descriptor_t not_port; - mach_msg_format_0_trailer_t trailer; -} mach_port_destroyed_notification_t; - -typedef struct { - mach_msg_header_t not_header; - NDR_record_t NDR; - mach_msg_type_number_t not_count; - mach_msg_format_0_trailer_t trailer; -} mach_no_senders_notification_t; - -typedef struct { - mach_msg_header_t not_header; - mach_msg_format_0_trailer_t trailer; -} mach_send_once_notification_t; - -typedef struct { - mach_msg_header_t not_header; - NDR_record_t NDR; - mach_port_name_t not_port; - mach_msg_format_0_trailer_t trailer; -} mach_dead_name_notification_t; - - -typedef void (*mig_stub_routine_t) (mach_msg_header_t *InHeadP, - mach_msg_header_t *OutHeadP); - -typedef mig_stub_routine_t mig_routine_t; - - - - - - -typedef mig_routine_t (*mig_server_routine_t) (mach_msg_header_t *InHeadP); - - - - - - -typedef kern_return_t (*mig_impl_routine_t)(void); - -typedef mach_msg_type_descriptor_t routine_arg_descriptor; -typedef mach_msg_type_descriptor_t *routine_arg_descriptor_t; -typedef mach_msg_type_descriptor_t *mig_routine_arg_descriptor_t; - - - -struct routine_descriptor { - mig_impl_routine_t impl_routine; - mig_stub_routine_t stub_routine; - unsigned int argc; - unsigned int descr_count; - routine_arg_descriptor_t - arg_descr; - unsigned int max_reply_msg; -}; -typedef struct routine_descriptor *routine_descriptor_t; - -typedef struct routine_descriptor mig_routine_descriptor; -typedef mig_routine_descriptor *mig_routine_descriptor_t; - - - -typedef struct mig_subsystem { - mig_server_routine_t server; - mach_msg_id_t start; - mach_msg_id_t end; - mach_msg_size_t maxsize; - vm_address_t reserved; - mig_routine_descriptor - routine[1]; -} *mig_subsystem_t; - - - -typedef struct mig_symtab { - char *ms_routine_name; - int ms_routine_number; - void (*ms_routine)(void); - - - - -} mig_symtab_t; - - -extern "C" { - - -extern mach_port_t mig_get_reply_port(void); - - -extern void mig_dealloc_reply_port(mach_port_t reply_port); - - -extern void mig_put_reply_port(mach_port_t reply_port); - - -extern int mig_strncpy(char *dest, const char *src, int len); - - - -extern void mig_allocate(vm_address_t *, vm_size_t); - - -extern void mig_deallocate(vm_address_t, vm_size_t); - - -} -#pragma pack(4) -typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; -} mig_reply_error_t; -#pragma pack() - - -extern "C" { - - - - -static __inline__ void -__NDR_convert__mig_reply_error_t(__attribute__((unused)) mig_reply_error_t *x) -{ - - - - -} - - -} -extern "C" { - - - - - - -extern - -kern_return_t clock_set_time -( - clock_ctrl_t clock_ctrl, - mach_timespec_t new_time -); - - - - - -extern - -kern_return_t clock_set_attributes -( - clock_ctrl_t clock_ctrl, - clock_flavor_t flavor, - clock_attr_t clock_attr, - mach_msg_type_number_t clock_attrCnt -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_timespec_t new_time; - } __Request__clock_set_time_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - clock_flavor_t flavor; - mach_msg_type_number_t clock_attrCnt; - int clock_attr[1]; - } __Request__clock_set_attributes_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__clock_priv_subsystem { - __Request__clock_set_time_t Request_clock_set_time; - __Request__clock_set_attributes_t Request_clock_set_attributes; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__clock_set_time_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__clock_set_attributes_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__clock_priv_subsystem { - __Reply__clock_set_time_t Reply_clock_set_time; - __Reply__clock_set_attributes_t Reply_clock_set_attributes; -}; -typedef struct ipc_info_space { - natural_t iis_genno_mask; - natural_t iis_table_size; - natural_t iis_table_next; - natural_t iis_tree_size; - natural_t iis_tree_small; - natural_t iis_tree_hash; -} ipc_info_space_t; - -typedef struct ipc_info_space_basic { - natural_t iisb_genno_mask; - natural_t iisb_table_size; - natural_t iisb_table_next; - natural_t iisb_table_inuse; - natural_t iisb_reserved[2]; -} ipc_info_space_basic_t; - -typedef struct ipc_info_name { - mach_port_name_t iin_name; - integer_t iin_collision; - mach_port_type_t iin_type; - mach_port_urefs_t iin_urefs; - natural_t iin_object; - natural_t iin_next; - natural_t iin_hash; -} ipc_info_name_t; - -typedef ipc_info_name_t *ipc_info_name_array_t; - - -typedef struct ipc_info_tree_name { - ipc_info_name_t iitn_name; - mach_port_name_t iitn_lchild; - mach_port_name_t iitn_rchild; -} ipc_info_tree_name_t; - -typedef ipc_info_tree_name_t *ipc_info_tree_name_array_t; -#pragma pack(4) - - - - - -typedef struct mach_vm_info_region { - mach_vm_offset_t vir_start; - mach_vm_offset_t vir_end; - mach_vm_offset_t vir_object; - memory_object_offset_t vir_offset; - boolean_t vir_needs_copy; - vm_prot_t vir_protection; - vm_prot_t vir_max_protection; - vm_inherit_t vir_inheritance; - natural_t vir_wired_count; - natural_t vir_user_wired_count; -} mach_vm_info_region_t; - -typedef struct vm_info_region_64 { - natural_t vir_start; - natural_t vir_end; - natural_t vir_object; - memory_object_offset_t vir_offset; - boolean_t vir_needs_copy; - vm_prot_t vir_protection; - vm_prot_t vir_max_protection; - vm_inherit_t vir_inheritance; - natural_t vir_wired_count; - natural_t vir_user_wired_count; -} vm_info_region_64_t; - -typedef struct vm_info_region { - natural_t vir_start; - natural_t vir_end; - natural_t vir_object; - natural_t vir_offset; - boolean_t vir_needs_copy; - vm_prot_t vir_protection; - vm_prot_t vir_max_protection; - vm_inherit_t vir_inheritance; - natural_t vir_wired_count; - natural_t vir_user_wired_count; -} vm_info_region_t; - - -typedef struct vm_info_object { - natural_t vio_object; - natural_t vio_size; - unsigned int vio_ref_count; - unsigned int vio_resident_page_count; - unsigned int vio_absent_count; - natural_t vio_copy; - natural_t vio_shadow; - natural_t vio_shadow_offset; - natural_t vio_paging_offset; - memory_object_copy_strategy_t vio_copy_strategy; - - vm_offset_t vio_last_alloc; - - unsigned int vio_paging_in_progress; - boolean_t vio_pager_created; - boolean_t vio_pager_initialized; - boolean_t vio_pager_ready; - boolean_t vio_can_persist; - boolean_t vio_internal; - boolean_t vio_temporary; - boolean_t vio_alive; - boolean_t vio_purgable; - boolean_t vio_purgable_volatile; -} vm_info_object_t; - -typedef vm_info_object_t *vm_info_object_array_t; - -#pragma pack() -typedef struct zone_name { - char zn_name[80]; -} zone_name_t; - -typedef zone_name_t *zone_name_array_t; - - -typedef struct zone_info { - integer_t zi_count; - vm_size_t zi_cur_size; - vm_size_t zi_max_size; - vm_size_t zi_elem_size; - vm_size_t zi_alloc_size; - integer_t zi_pageable; - integer_t zi_sleepable; - integer_t zi_exhaustible; - integer_t zi_collectable; -} zone_info_t; - -typedef zone_info_t *zone_info_array_t; -typedef struct mach_zone_name { - char mzn_name[80]; -} mach_zone_name_t; - -typedef mach_zone_name_t *mach_zone_name_array_t; - -typedef struct mach_zone_info_data { - uint64_t mzi_count; - uint64_t mzi_cur_size; - uint64_t mzi_max_size; - uint64_t mzi_elem_size; - uint64_t mzi_alloc_size; - uint64_t mzi_sum_size; - uint64_t mzi_exhaustible; - uint64_t mzi_collectable; -} mach_zone_info_t; - -typedef mach_zone_info_t *mach_zone_info_array_t; - -typedef struct task_zone_info_data { - uint64_t tzi_count; - uint64_t tzi_cur_size; - uint64_t tzi_max_size; - uint64_t tzi_elem_size; - uint64_t tzi_alloc_size; - uint64_t tzi_sum_size; - uint64_t tzi_exhaustible; - uint64_t tzi_collectable; - uint64_t tzi_caller_acct; - uint64_t tzi_task_alloc; - uint64_t tzi_task_free; -} task_zone_info_t; - -typedef task_zone_info_t *task_zone_info_array_t; - -typedef struct mach_memory_info { - uint64_t flags; - uint64_t site; - uint64_t size; - uint64_t free; - uint64_t largest; - uint64_t _resv[3]; -} mach_memory_info_t; - -typedef mach_memory_info_t *mach_memory_info_array_t; -typedef vm_offset_t *page_address_array_t; -typedef struct hash_info_bucket { - natural_t hib_count; -} hash_info_bucket_t; - -typedef hash_info_bucket_t *hash_info_bucket_array_t; -typedef struct lockgroup_info { - char lockgroup_name[64]; - uint64_t lockgroup_attr; - uint64_t lock_spin_cnt; - uint64_t lock_spin_util_cnt; - uint64_t lock_spin_held_cnt; - uint64_t lock_spin_miss_cnt; - uint64_t lock_spin_held_max; - uint64_t lock_spin_held_cum; - uint64_t lock_mtx_cnt; - uint64_t lock_mtx_util_cnt; - uint64_t lock_mtx_held_cnt; - uint64_t lock_mtx_miss_cnt; - uint64_t lock_mtx_wait_cnt; - uint64_t lock_mtx_held_max; - uint64_t lock_mtx_held_cum; - uint64_t lock_mtx_wait_max; - uint64_t lock_mtx_wait_cum; - uint64_t lock_rw_cnt; - uint64_t lock_rw_util_cnt; - uint64_t lock_rw_held_cnt; - uint64_t lock_rw_miss_cnt; - uint64_t lock_rw_wait_cnt; - uint64_t lock_rw_held_max; - uint64_t lock_rw_held_cum; - uint64_t lock_rw_wait_max; - uint64_t lock_rw_wait_cum; -} lockgroup_info_t; - -typedef lockgroup_info_t *lockgroup_info_array_t; - -typedef char symtab_name_t[32]; - -struct mach_core_fileheader -{ - uint64_t signature; - uint64_t log_offset; - uint64_t log_length; - uint64_t gzip_offset; - uint64_t gzip_length; -}; - - - - - - -extern "C" { - - - - - - -extern - -kern_return_t host_get_boot_info -( - host_priv_t host_priv, - kernel_boot_info_t boot_info -); - - - - - -extern - -kern_return_t host_reboot -( - host_priv_t host_priv, - int options -); - - - - - -extern - -kern_return_t host_priv_statistics -( - host_priv_t host_priv, - host_flavor_t flavor, - host_info_t host_info_out, - mach_msg_type_number_t *host_info_outCnt -); - - - - - -extern - -kern_return_t host_default_memory_manager -( - host_priv_t host_priv, - memory_object_default_t *default_manager, - memory_object_cluster_size_t cluster_size -); - - - - - -extern - -kern_return_t vm_wire -( - host_priv_t host_priv, - vm_map_t task, - vm_address_t address, - vm_size_t size, - vm_prot_t desired_access -); - - - - - -extern - -kern_return_t thread_wire -( - host_priv_t host_priv, - thread_act_t thread, - boolean_t wired -); - - - - - -extern - -kern_return_t vm_allocate_cpm -( - host_priv_t host_priv, - vm_map_t task, - vm_address_t *address, - vm_size_t size, - int flags -); - - - - - -extern - -kern_return_t host_processors -( - host_priv_t host_priv, - processor_array_t *out_processor_list, - mach_msg_type_number_t *out_processor_listCnt -); - - - - - -extern - -kern_return_t host_get_clock_control -( - host_priv_t host_priv, - clock_id_t clock_id, - clock_ctrl_t *clock_ctrl -); - - - - - -extern - -kern_return_t kmod_create -( - host_priv_t host_priv, - vm_address_t info, - kmod_t *module -); - - - - - -extern - -kern_return_t kmod_destroy -( - host_priv_t host_priv, - kmod_t module -); - - - - - -extern - -kern_return_t kmod_control -( - host_priv_t host_priv, - kmod_t module, - kmod_control_flavor_t flavor, - kmod_args_t *data, - mach_msg_type_number_t *dataCnt -); - - - - - -extern - -kern_return_t host_get_special_port -( - host_priv_t host_priv, - int node, - int which, - mach_port_t *port -); - - - - - -extern - -kern_return_t host_set_special_port -( - host_priv_t host_priv, - int which, - mach_port_t port -); - - - - - -extern - -kern_return_t host_set_exception_ports -( - host_priv_t host_priv, - exception_mask_t exception_mask, - mach_port_t new_port, - exception_behavior_t behavior, - thread_state_flavor_t new_flavor -); - - - - - -extern - -kern_return_t host_get_exception_ports -( - host_priv_t host_priv, - exception_mask_t exception_mask, - exception_mask_array_t masks, - mach_msg_type_number_t *masksCnt, - exception_handler_array_t old_handlers, - exception_behavior_array_t old_behaviors, - exception_flavor_array_t old_flavors -); - - - - - -extern - -kern_return_t host_swap_exception_ports -( - host_priv_t host_priv, - exception_mask_t exception_mask, - mach_port_t new_port, - exception_behavior_t behavior, - thread_state_flavor_t new_flavor, - exception_mask_array_t masks, - mach_msg_type_number_t *masksCnt, - exception_handler_array_t old_handlerss, - exception_behavior_array_t old_behaviors, - exception_flavor_array_t old_flavors -); - - - - - -extern - -kern_return_t mach_vm_wire -( - host_priv_t host_priv, - vm_map_t task, - mach_vm_address_t address, - mach_vm_size_t size, - vm_prot_t desired_access -); - - - - - -extern - -kern_return_t host_processor_sets -( - host_priv_t host_priv, - processor_set_name_array_t *processor_sets, - mach_msg_type_number_t *processor_setsCnt -); - - - - - -extern - -kern_return_t host_processor_set_priv -( - host_priv_t host_priv, - processor_set_name_t set_name, - processor_set_t *set -); - - - - - -extern - -kern_return_t set_dp_control_port -( - host_priv_t host, - mach_port_t control_port -); - - - - - -extern - -kern_return_t get_dp_control_port -( - host_priv_t host, - mach_port_t *contorl_port -); - - - - - -extern - -kern_return_t host_set_UNDServer -( - host_priv_t host, - UNDServerRef server -); - - - - - -extern - -kern_return_t host_get_UNDServer -( - host_priv_t host, - UNDServerRef *server -); - - - - - -extern - -kern_return_t kext_request -( - host_priv_t host_priv, - uint32_t user_log_flags, - vm_offset_t request_data, - mach_msg_type_number_t request_dataCnt, - vm_offset_t *response_data, - mach_msg_type_number_t *response_dataCnt, - vm_offset_t *log_data, - mach_msg_type_number_t *log_dataCnt, - kern_return_t *op_result -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_get_boot_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int options; - } __Request__host_reboot_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - host_flavor_t flavor; - mach_msg_type_number_t host_info_outCnt; - } __Request__host_priv_statistics_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t default_manager; - - NDR_record_t NDR; - memory_object_cluster_size_t cluster_size; - } __Request__host_default_memory_manager_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t task; - - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - vm_prot_t desired_access; - } __Request__vm_wire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t thread; - - NDR_record_t NDR; - boolean_t wired; - } __Request__thread_wire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t task; - - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - int flags; - } __Request__vm_allocate_cpm_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_processors_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - clock_id_t clock_id; - } __Request__host_get_clock_control_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t info; - } __Request__kmod_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kmod_t module; - } __Request__kmod_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t data; - - NDR_record_t NDR; - kmod_t module; - kmod_control_flavor_t flavor; - mach_msg_type_number_t dataCnt; - } __Request__kmod_control_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int node; - int which; - } __Request__host_get_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t port; - - NDR_record_t NDR; - int which; - } __Request__host_set_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_port; - - NDR_record_t NDR; - exception_mask_t exception_mask; - exception_behavior_t behavior; - thread_state_flavor_t new_flavor; - } __Request__host_set_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - exception_mask_t exception_mask; - } __Request__host_get_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_port; - - NDR_record_t NDR; - exception_mask_t exception_mask; - exception_behavior_t behavior; - thread_state_flavor_t new_flavor; - } __Request__host_swap_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t task; - - NDR_record_t NDR; - mach_vm_address_t address; - mach_vm_size_t size; - vm_prot_t desired_access; - } __Request__mach_vm_wire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_processor_sets_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t set_name; - - } __Request__host_processor_set_priv_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t control_port; - - } __Request__set_dp_control_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__get_dp_control_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t server; - - } __Request__host_set_UNDServer_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_get_UNDServer_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t request_data; - - NDR_record_t NDR; - uint32_t user_log_flags; - mach_msg_type_number_t request_dataCnt; - } __Request__kext_request_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__host_priv_subsystem { - __Request__host_get_boot_info_t Request_host_get_boot_info; - __Request__host_reboot_t Request_host_reboot; - __Request__host_priv_statistics_t Request_host_priv_statistics; - __Request__host_default_memory_manager_t Request_host_default_memory_manager; - __Request__vm_wire_t Request_vm_wire; - __Request__thread_wire_t Request_thread_wire; - __Request__vm_allocate_cpm_t Request_vm_allocate_cpm; - __Request__host_processors_t Request_host_processors; - __Request__host_get_clock_control_t Request_host_get_clock_control; - __Request__kmod_create_t Request_kmod_create; - __Request__kmod_destroy_t Request_kmod_destroy; - __Request__kmod_control_t Request_kmod_control; - __Request__host_get_special_port_t Request_host_get_special_port; - __Request__host_set_special_port_t Request_host_set_special_port; - __Request__host_set_exception_ports_t Request_host_set_exception_ports; - __Request__host_get_exception_ports_t Request_host_get_exception_ports; - __Request__host_swap_exception_ports_t Request_host_swap_exception_ports; - __Request__mach_vm_wire_t Request_mach_vm_wire; - __Request__host_processor_sets_t Request_host_processor_sets; - __Request__host_processor_set_priv_t Request_host_processor_set_priv; - __Request__set_dp_control_port_t Request_set_dp_control_port; - __Request__get_dp_control_port_t Request_get_dp_control_port; - __Request__host_set_UNDServer_t Request_host_set_UNDServer; - __Request__host_get_UNDServer_t Request_host_get_UNDServer; - __Request__kext_request_t Request_kext_request; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t boot_infoOffset; - mach_msg_type_number_t boot_infoCnt; - char boot_info[4096]; - } __Reply__host_get_boot_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__host_reboot_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t host_info_outCnt; - integer_t host_info_out[68]; - } __Reply__host_priv_statistics_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t default_manager; - - } __Reply__host_default_memory_manager_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__vm_wire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_wire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_address_t address; - } __Reply__vm_allocate_cpm_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t out_processor_list; - - NDR_record_t NDR; - mach_msg_type_number_t out_processor_listCnt; - } __Reply__host_processors_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t clock_ctrl; - - } __Reply__host_get_clock_control_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - kmod_t module; - } __Reply__kmod_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__kmod_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t data; - - NDR_record_t NDR; - mach_msg_type_number_t dataCnt; - } __Reply__kmod_control_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t port; - - } __Reply__host_get_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__host_set_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__host_set_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t old_handlers[32]; - - NDR_record_t NDR; - mach_msg_type_number_t masksCnt; - exception_mask_t masks[32]; - exception_behavior_t old_behaviors[32]; - thread_state_flavor_t old_flavors[32]; - } __Reply__host_get_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t old_handlerss[32]; - - NDR_record_t NDR; - mach_msg_type_number_t masksCnt; - exception_mask_t masks[32]; - exception_behavior_t old_behaviors[32]; - thread_state_flavor_t old_flavors[32]; - } __Reply__host_swap_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_vm_wire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t processor_sets; - - NDR_record_t NDR; - mach_msg_type_number_t processor_setsCnt; - } __Reply__host_processor_sets_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t set; - - } __Reply__host_processor_set_priv_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__set_dp_control_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t contorl_port; - - } __Reply__get_dp_control_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__host_set_UNDServer_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t server; - - } __Reply__host_get_UNDServer_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t response_data; - mach_msg_ool_descriptor_t log_data; - - NDR_record_t NDR; - mach_msg_type_number_t response_dataCnt; - mach_msg_type_number_t log_dataCnt; - kern_return_t op_result; - } __Reply__kext_request_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__host_priv_subsystem { - __Reply__host_get_boot_info_t Reply_host_get_boot_info; - __Reply__host_reboot_t Reply_host_reboot; - __Reply__host_priv_statistics_t Reply_host_priv_statistics; - __Reply__host_default_memory_manager_t Reply_host_default_memory_manager; - __Reply__vm_wire_t Reply_vm_wire; - __Reply__thread_wire_t Reply_thread_wire; - __Reply__vm_allocate_cpm_t Reply_vm_allocate_cpm; - __Reply__host_processors_t Reply_host_processors; - __Reply__host_get_clock_control_t Reply_host_get_clock_control; - __Reply__kmod_create_t Reply_kmod_create; - __Reply__kmod_destroy_t Reply_kmod_destroy; - __Reply__kmod_control_t Reply_kmod_control; - __Reply__host_get_special_port_t Reply_host_get_special_port; - __Reply__host_set_special_port_t Reply_host_set_special_port; - __Reply__host_set_exception_ports_t Reply_host_set_exception_ports; - __Reply__host_get_exception_ports_t Reply_host_get_exception_ports; - __Reply__host_swap_exception_ports_t Reply_host_swap_exception_ports; - __Reply__mach_vm_wire_t Reply_mach_vm_wire; - __Reply__host_processor_sets_t Reply_host_processor_sets; - __Reply__host_processor_set_priv_t Reply_host_processor_set_priv; - __Reply__set_dp_control_port_t Reply_set_dp_control_port; - __Reply__get_dp_control_port_t Reply_get_dp_control_port; - __Reply__host_set_UNDServer_t Reply_host_set_UNDServer; - __Reply__host_get_UNDServer_t Reply_host_get_UNDServer; - __Reply__kext_request_t Reply_kext_request; -}; -extern "C" { - - - - - - -extern - -kern_return_t host_security_create_task_token -( - host_security_t host_security, - task_t parent_task, - security_token_t sec_token, - audit_token_t audit_token, - host_t host, - ledger_array_t ledgers, - mach_msg_type_number_t ledgersCnt, - boolean_t inherit_memory, - task_t *child_task -); - - - - - -extern - -kern_return_t host_security_set_task_token -( - host_security_t host_security, - task_t target_task, - security_token_t sec_token, - audit_token_t audit_token, - host_t host -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t parent_task; - mach_msg_port_descriptor_t host; - mach_msg_ool_ports_descriptor_t ledgers; - - NDR_record_t NDR; - security_token_t sec_token; - audit_token_t audit_token; - mach_msg_type_number_t ledgersCnt; - boolean_t inherit_memory; - } __Request__host_security_create_task_token_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t target_task; - mach_msg_port_descriptor_t host; - - NDR_record_t NDR; - security_token_t sec_token; - audit_token_t audit_token; - } __Request__host_security_set_task_token_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__host_security_subsystem { - __Request__host_security_create_task_token_t Request_host_security_create_task_token; - __Request__host_security_set_task_token_t Request_host_security_set_task_token; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t child_task; - - } __Reply__host_security_create_task_token_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__host_security_set_task_token_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__host_security_subsystem { - __Reply__host_security_create_task_token_t Reply_host_security_create_task_token; - __Reply__host_security_set_task_token_t Reply_host_security_set_task_token; -}; -extern "C" { - - - - - - -extern - -kern_return_t lock_acquire -( - lock_set_t lock_set, - int lock_id -); - - - - - -extern - -kern_return_t lock_release -( - lock_set_t lock_set, - int lock_id -); - - - - - -extern - -kern_return_t lock_try -( - lock_set_t lock_set, - int lock_id -); - - - - - -extern - -kern_return_t lock_make_stable -( - lock_set_t lock_set, - int lock_id -); - - - - - -extern - -kern_return_t lock_handoff -( - lock_set_t lock_set, - int lock_id -); - - - - - -extern - -kern_return_t lock_handoff_accept -( - lock_set_t lock_set, - int lock_id -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int lock_id; - } __Request__lock_acquire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int lock_id; - } __Request__lock_release_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int lock_id; - } __Request__lock_try_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int lock_id; - } __Request__lock_make_stable_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int lock_id; - } __Request__lock_handoff_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int lock_id; - } __Request__lock_handoff_accept_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__lock_set_subsystem { - __Request__lock_acquire_t Request_lock_acquire; - __Request__lock_release_t Request_lock_release; - __Request__lock_try_t Request_lock_try; - __Request__lock_make_stable_t Request_lock_make_stable; - __Request__lock_handoff_t Request_lock_handoff; - __Request__lock_handoff_accept_t Request_lock_handoff_accept; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__lock_acquire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__lock_release_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__lock_try_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__lock_make_stable_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__lock_handoff_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__lock_handoff_accept_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__lock_set_subsystem { - __Reply__lock_acquire_t Reply_lock_acquire; - __Reply__lock_release_t Reply_lock_release; - __Reply__lock_try_t Reply_lock_try; - __Reply__lock_make_stable_t Reply_lock_make_stable; - __Reply__lock_handoff_t Reply_lock_handoff; - __Reply__lock_handoff_accept_t Reply_lock_handoff_accept; -}; -extern "C" { - - - - - - -extern - -kern_return_t processor_start -( - processor_t processor -); - - - - - -extern - -kern_return_t processor_exit -( - processor_t processor -); - - - - - -extern - -kern_return_t processor_info -( - processor_t processor, - processor_flavor_t flavor, - host_t *host, - processor_info_t processor_info_out, - mach_msg_type_number_t *processor_info_outCnt -); - - - - - -extern - -kern_return_t processor_control -( - processor_t processor, - processor_info_t processor_cmd, - mach_msg_type_number_t processor_cmdCnt -); - - - - - -extern - -kern_return_t processor_assign -( - processor_t processor, - processor_set_t new_set, - boolean_t wait -); - - - - - -extern - -kern_return_t processor_get_assignment -( - processor_t processor, - processor_set_name_t *assigned_set -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__processor_start_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__processor_exit_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - processor_flavor_t flavor; - mach_msg_type_number_t processor_info_outCnt; - } __Request__processor_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_msg_type_number_t processor_cmdCnt; - integer_t processor_cmd[12]; - } __Request__processor_control_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_set; - - NDR_record_t NDR; - boolean_t wait; - } __Request__processor_assign_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__processor_get_assignment_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__processor_subsystem { - __Request__processor_start_t Request_processor_start; - __Request__processor_exit_t Request_processor_exit; - __Request__processor_info_t Request_processor_info; - __Request__processor_control_t Request_processor_control; - __Request__processor_assign_t Request_processor_assign; - __Request__processor_get_assignment_t Request_processor_get_assignment; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__processor_start_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__processor_exit_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t host; - - NDR_record_t NDR; - mach_msg_type_number_t processor_info_outCnt; - integer_t processor_info_out[12]; - } __Reply__processor_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__processor_control_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__processor_assign_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t assigned_set; - - } __Reply__processor_get_assignment_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__processor_subsystem { - __Reply__processor_start_t Reply_processor_start; - __Reply__processor_exit_t Reply_processor_exit; - __Reply__processor_info_t Reply_processor_info; - __Reply__processor_control_t Reply_processor_control; - __Reply__processor_assign_t Reply_processor_assign; - __Reply__processor_get_assignment_t Reply_processor_get_assignment; -}; -extern "C" { - - - - - - -extern - -kern_return_t processor_set_statistics -( - processor_set_name_t pset, - processor_set_flavor_t flavor, - processor_set_info_t info_out, - mach_msg_type_number_t *info_outCnt -); - - - - - -extern - -kern_return_t processor_set_destroy -( - processor_set_t set -); - - - - - -extern - -kern_return_t processor_set_max_priority -( - processor_set_t processor_set, - int max_priority, - boolean_t change_threads -); - - - - - -extern - -kern_return_t processor_set_policy_enable -( - processor_set_t processor_set, - int policy -); - - - - - -extern - -kern_return_t processor_set_policy_disable -( - processor_set_t processor_set, - int policy, - boolean_t change_threads -); - - - - - -extern - -kern_return_t processor_set_tasks -( - processor_set_t processor_set, - task_array_t *task_list, - mach_msg_type_number_t *task_listCnt -); - - - - - -extern - -kern_return_t processor_set_threads -( - processor_set_t processor_set, - thread_act_array_t *thread_list, - mach_msg_type_number_t *thread_listCnt -); - - - - - -extern - -kern_return_t processor_set_policy_control -( - processor_set_t pset, - processor_set_flavor_t flavor, - processor_set_info_t policy_info, - mach_msg_type_number_t policy_infoCnt, - boolean_t change -); - - - - - -extern - -kern_return_t processor_set_stack_usage -( - processor_set_t pset, - unsigned *ltotal, - vm_size_t *space, - vm_size_t *resident, - vm_size_t *maxusage, - vm_offset_t *maxstack -); - - - - - -extern - -kern_return_t processor_set_info -( - processor_set_name_t set_name, - int flavor, - host_t *host, - processor_set_info_t info_out, - mach_msg_type_number_t *info_outCnt -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - processor_set_flavor_t flavor; - mach_msg_type_number_t info_outCnt; - } __Request__processor_set_statistics_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__processor_set_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int max_priority; - boolean_t change_threads; - } __Request__processor_set_max_priority_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int policy; - } __Request__processor_set_policy_enable_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int policy; - boolean_t change_threads; - } __Request__processor_set_policy_disable_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__processor_set_tasks_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__processor_set_threads_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - processor_set_flavor_t flavor; - mach_msg_type_number_t policy_infoCnt; - integer_t policy_info[5]; - boolean_t change; - } __Request__processor_set_policy_control_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__processor_set_stack_usage_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int flavor; - mach_msg_type_number_t info_outCnt; - } __Request__processor_set_info_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__processor_set_subsystem { - __Request__processor_set_statistics_t Request_processor_set_statistics; - __Request__processor_set_destroy_t Request_processor_set_destroy; - __Request__processor_set_max_priority_t Request_processor_set_max_priority; - __Request__processor_set_policy_enable_t Request_processor_set_policy_enable; - __Request__processor_set_policy_disable_t Request_processor_set_policy_disable; - __Request__processor_set_tasks_t Request_processor_set_tasks; - __Request__processor_set_threads_t Request_processor_set_threads; - __Request__processor_set_policy_control_t Request_processor_set_policy_control; - __Request__processor_set_stack_usage_t Request_processor_set_stack_usage; - __Request__processor_set_info_t Request_processor_set_info; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t info_outCnt; - integer_t info_out[5]; - } __Reply__processor_set_statistics_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__processor_set_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__processor_set_max_priority_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__processor_set_policy_enable_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__processor_set_policy_disable_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t task_list; - - NDR_record_t NDR; - mach_msg_type_number_t task_listCnt; - } __Reply__processor_set_tasks_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t thread_list; - - NDR_record_t NDR; - mach_msg_type_number_t thread_listCnt; - } __Reply__processor_set_threads_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__processor_set_policy_control_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - unsigned ltotal; - vm_size_t space; - vm_size_t resident; - vm_size_t maxusage; - vm_offset_t maxstack; - } __Reply__processor_set_stack_usage_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t host; - - NDR_record_t NDR; - mach_msg_type_number_t info_outCnt; - integer_t info_out[5]; - } __Reply__processor_set_info_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__processor_set_subsystem { - __Reply__processor_set_statistics_t Reply_processor_set_statistics; - __Reply__processor_set_destroy_t Reply_processor_set_destroy; - __Reply__processor_set_max_priority_t Reply_processor_set_max_priority; - __Reply__processor_set_policy_enable_t Reply_processor_set_policy_enable; - __Reply__processor_set_policy_disable_t Reply_processor_set_policy_disable; - __Reply__processor_set_tasks_t Reply_processor_set_tasks; - __Reply__processor_set_threads_t Reply_processor_set_threads; - __Reply__processor_set_policy_control_t Reply_processor_set_policy_control; - __Reply__processor_set_stack_usage_t Reply_processor_set_stack_usage; - __Reply__processor_set_info_t Reply_processor_set_info; -}; -typedef int sync_policy_t; -extern "C" { - -extern kern_return_t semaphore_signal (semaphore_t semaphore); -extern kern_return_t semaphore_signal_all (semaphore_t semaphore); - -extern kern_return_t semaphore_wait (semaphore_t semaphore); - - -extern kern_return_t semaphore_timedwait (semaphore_t semaphore, - mach_timespec_t wait_time); - -extern kern_return_t semaphore_timedwait_signal(semaphore_t wait_semaphore, - semaphore_t signal_semaphore, - mach_timespec_t wait_time); - -extern kern_return_t semaphore_wait_signal (semaphore_t wait_semaphore, - semaphore_t signal_semaphore); - -extern kern_return_t semaphore_signal_thread (semaphore_t semaphore, - thread_t thread); - - -} -extern "C" { - - - - - - -extern - -kern_return_t task_create -( - task_t target_task, - ledger_array_t ledgers, - mach_msg_type_number_t ledgersCnt, - boolean_t inherit_memory, - task_t *child_task -); - - - - - -extern - -kern_return_t task_terminate -( - task_t target_task -); - - - - - -extern - -kern_return_t task_threads -( - task_t target_task, - thread_act_array_t *act_list, - mach_msg_type_number_t *act_listCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t mach_ports_register -( - task_t target_task, - mach_port_array_t init_port_set, - mach_msg_type_number_t init_port_setCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t mach_ports_lookup -( - task_t target_task, - mach_port_array_t *init_port_set, - mach_msg_type_number_t *init_port_setCnt -); - - - - - -extern - -kern_return_t task_info -( - task_name_t target_task, - task_flavor_t flavor, - task_info_t task_info_out, - mach_msg_type_number_t *task_info_outCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_set_info -( - task_t target_task, - task_flavor_t flavor, - task_info_t task_info_in, - mach_msg_type_number_t task_info_inCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_suspend -( - task_t target_task -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_resume -( - task_t target_task -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_get_special_port -( - task_t task, - int which_port, - mach_port_t *special_port -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_set_special_port -( - task_t task, - int which_port, - mach_port_t special_port -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_create -( - task_t parent_task, - thread_act_t *child_act -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_create_running -( - task_t parent_task, - thread_state_flavor_t flavor, - thread_state_t new_state, - mach_msg_type_number_t new_stateCnt, - thread_act_t *child_act -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_set_exception_ports -( - task_t task, - exception_mask_t exception_mask, - mach_port_t new_port, - exception_behavior_t behavior, - thread_state_flavor_t new_flavor -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_get_exception_ports -( - task_t task, - exception_mask_t exception_mask, - exception_mask_array_t masks, - mach_msg_type_number_t *masksCnt, - exception_handler_array_t old_handlers, - exception_behavior_array_t old_behaviors, - exception_flavor_array_t old_flavors -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_swap_exception_ports -( - task_t task, - exception_mask_t exception_mask, - mach_port_t new_port, - exception_behavior_t behavior, - thread_state_flavor_t new_flavor, - exception_mask_array_t masks, - mach_msg_type_number_t *masksCnt, - exception_handler_array_t old_handlerss, - exception_behavior_array_t old_behaviors, - exception_flavor_array_t old_flavors -); - - - - - -extern - -kern_return_t lock_set_create -( - task_t task, - lock_set_t *new_lock_set, - int n_ulocks, - int policy -); - - - - - -extern - -kern_return_t lock_set_destroy -( - task_t task, - lock_set_t lock_set -); - - - - - -extern - -kern_return_t semaphore_create -( - task_t task, - semaphore_t *semaphore, - int policy, - int value -); - - - - - -extern - -kern_return_t semaphore_destroy -( - task_t task, - semaphore_t semaphore -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_policy_set -( - task_t task, - task_policy_flavor_t flavor, - task_policy_t policy_info, - mach_msg_type_number_t policy_infoCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_policy_get -( - task_t task, - task_policy_flavor_t flavor, - task_policy_t policy_info, - mach_msg_type_number_t *policy_infoCnt, - boolean_t *get_default -); - - - - - -extern - -kern_return_t task_sample -( - task_t task, - mach_port_t reply -); - - - - - -extern - -kern_return_t task_policy -( - task_t task, - policy_t policy, - policy_base_t base, - mach_msg_type_number_t baseCnt, - boolean_t set_limit, - boolean_t change -); - - - - - -extern - -kern_return_t task_set_emulation -( - task_t target_port, - vm_address_t routine_entry_pt, - int routine_number -); - - - - - -extern - -kern_return_t task_get_emulation_vector -( - task_t task, - int *vector_start, - emulation_vector_t *emulation_vector, - mach_msg_type_number_t *emulation_vectorCnt -); - - - - - -extern - -kern_return_t task_set_emulation_vector -( - task_t task, - int vector_start, - emulation_vector_t emulation_vector, - mach_msg_type_number_t emulation_vectorCnt -); - - - - - -extern - -kern_return_t task_set_ras_pc -( - task_t target_task, - vm_address_t basepc, - vm_address_t boundspc -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_zone_info -( - task_t target_task, - mach_zone_name_array_t *names, - mach_msg_type_number_t *namesCnt, - task_zone_info_array_t *info, - mach_msg_type_number_t *infoCnt -); - - - - - -extern - -kern_return_t task_assign -( - task_t task, - processor_set_t new_set, - boolean_t assign_threads -); - - - - - -extern - -kern_return_t task_assign_default -( - task_t task, - boolean_t assign_threads -); - - - - - -extern - -kern_return_t task_get_assignment -( - task_t task, - processor_set_name_t *assigned_set -); - - - - - -extern - -kern_return_t task_set_policy -( - task_t task, - processor_set_t pset, - policy_t policy, - policy_base_t base, - mach_msg_type_number_t baseCnt, - policy_limit_t limit, - mach_msg_type_number_t limitCnt, - boolean_t change -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_get_state -( - task_t task, - thread_state_flavor_t flavor, - thread_state_t old_state, - mach_msg_type_number_t *old_stateCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_set_state -( - task_t task, - thread_state_flavor_t flavor, - thread_state_t new_state, - mach_msg_type_number_t new_stateCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_set_phys_footprint_limit -( - task_t task, - int new_limit, - int *old_limit -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_suspend2 -( - task_t target_task, - task_suspension_token_t *suspend_token -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_resume2 -( - task_suspension_token_t suspend_token -); - - - - - -extern - -kern_return_t task_purgable_info -( - task_t task, - task_purgable_info_t *stats -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_get_mach_voucher -( - task_t task, - mach_voucher_selector_t which, - ipc_voucher_t *voucher -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_set_mach_voucher -( - task_t task, - ipc_voucher_t voucher -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_swap_mach_voucher -( - task_t task, - ipc_voucher_t new_voucher, - ipc_voucher_t *old_voucher -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t ledgers; - - NDR_record_t NDR; - mach_msg_type_number_t ledgersCnt; - boolean_t inherit_memory; - } __Request__task_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_terminate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_threads_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t init_port_set; - - NDR_record_t NDR; - mach_msg_type_number_t init_port_setCnt; - } __Request__mach_ports_register_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__mach_ports_lookup_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - task_flavor_t flavor; - mach_msg_type_number_t task_info_outCnt; - } __Request__task_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - task_flavor_t flavor; - mach_msg_type_number_t task_info_inCnt; - integer_t task_info_in[52]; - } __Request__task_set_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_suspend_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_resume_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int which_port; - } __Request__task_get_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t special_port; - - NDR_record_t NDR; - int which_port; - } __Request__task_set_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__thread_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - thread_state_flavor_t flavor; - mach_msg_type_number_t new_stateCnt; - natural_t new_state[224]; - } __Request__thread_create_running_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_port; - - NDR_record_t NDR; - exception_mask_t exception_mask; - exception_behavior_t behavior; - thread_state_flavor_t new_flavor; - } __Request__task_set_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - exception_mask_t exception_mask; - } __Request__task_get_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_port; - - NDR_record_t NDR; - exception_mask_t exception_mask; - exception_behavior_t behavior; - thread_state_flavor_t new_flavor; - } __Request__task_swap_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int n_ulocks; - int policy; - } __Request__lock_set_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t lock_set; - - } __Request__lock_set_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int policy; - int value; - } __Request__semaphore_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t semaphore; - - } __Request__semaphore_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - task_policy_flavor_t flavor; - mach_msg_type_number_t policy_infoCnt; - integer_t policy_info[16]; - } __Request__task_policy_set_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - task_policy_flavor_t flavor; - mach_msg_type_number_t policy_infoCnt; - boolean_t get_default; - } __Request__task_policy_get_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t reply; - - } __Request__task_sample_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - policy_t policy; - mach_msg_type_number_t baseCnt; - integer_t base[5]; - boolean_t set_limit; - boolean_t change; - } __Request__task_policy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t routine_entry_pt; - int routine_number; - } __Request__task_set_emulation_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_get_emulation_vector_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t emulation_vector; - - NDR_record_t NDR; - int vector_start; - mach_msg_type_number_t emulation_vectorCnt; - } __Request__task_set_emulation_vector_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t basepc; - vm_address_t boundspc; - } __Request__task_set_ras_pc_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_zone_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_set; - - NDR_record_t NDR; - boolean_t assign_threads; - } __Request__task_assign_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - boolean_t assign_threads; - } __Request__task_assign_default_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_get_assignment_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t pset; - - NDR_record_t NDR; - policy_t policy; - mach_msg_type_number_t baseCnt; - integer_t base[5]; - mach_msg_type_number_t limitCnt; - integer_t limit[1]; - boolean_t change; - } __Request__task_set_policy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - thread_state_flavor_t flavor; - mach_msg_type_number_t old_stateCnt; - } __Request__task_get_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - thread_state_flavor_t flavor; - mach_msg_type_number_t new_stateCnt; - natural_t new_state[224]; - } __Request__task_set_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int new_limit; - } __Request__task_set_phys_footprint_limit_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_suspend2_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_resume2_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__task_purgable_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_voucher_selector_t which; - } __Request__task_get_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t voucher; - - } __Request__task_set_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_voucher; - mach_msg_port_descriptor_t old_voucher; - - } __Request__task_swap_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__task_subsystem { - __Request__task_create_t Request_task_create; - __Request__task_terminate_t Request_task_terminate; - __Request__task_threads_t Request_task_threads; - __Request__mach_ports_register_t Request_mach_ports_register; - __Request__mach_ports_lookup_t Request_mach_ports_lookup; - __Request__task_info_t Request_task_info; - __Request__task_set_info_t Request_task_set_info; - __Request__task_suspend_t Request_task_suspend; - __Request__task_resume_t Request_task_resume; - __Request__task_get_special_port_t Request_task_get_special_port; - __Request__task_set_special_port_t Request_task_set_special_port; - __Request__thread_create_t Request_thread_create; - __Request__thread_create_running_t Request_thread_create_running; - __Request__task_set_exception_ports_t Request_task_set_exception_ports; - __Request__task_get_exception_ports_t Request_task_get_exception_ports; - __Request__task_swap_exception_ports_t Request_task_swap_exception_ports; - __Request__lock_set_create_t Request_lock_set_create; - __Request__lock_set_destroy_t Request_lock_set_destroy; - __Request__semaphore_create_t Request_semaphore_create; - __Request__semaphore_destroy_t Request_semaphore_destroy; - __Request__task_policy_set_t Request_task_policy_set; - __Request__task_policy_get_t Request_task_policy_get; - __Request__task_sample_t Request_task_sample; - __Request__task_policy_t Request_task_policy; - __Request__task_set_emulation_t Request_task_set_emulation; - __Request__task_get_emulation_vector_t Request_task_get_emulation_vector; - __Request__task_set_emulation_vector_t Request_task_set_emulation_vector; - __Request__task_set_ras_pc_t Request_task_set_ras_pc; - __Request__task_zone_info_t Request_task_zone_info; - __Request__task_assign_t Request_task_assign; - __Request__task_assign_default_t Request_task_assign_default; - __Request__task_get_assignment_t Request_task_get_assignment; - __Request__task_set_policy_t Request_task_set_policy; - __Request__task_get_state_t Request_task_get_state; - __Request__task_set_state_t Request_task_set_state; - __Request__task_set_phys_footprint_limit_t Request_task_set_phys_footprint_limit; - __Request__task_suspend2_t Request_task_suspend2; - __Request__task_resume2_t Request_task_resume2; - __Request__task_purgable_info_t Request_task_purgable_info; - __Request__task_get_mach_voucher_t Request_task_get_mach_voucher; - __Request__task_set_mach_voucher_t Request_task_set_mach_voucher; - __Request__task_swap_mach_voucher_t Request_task_swap_mach_voucher; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t child_task; - - } __Reply__task_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_terminate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t act_list; - - NDR_record_t NDR; - mach_msg_type_number_t act_listCnt; - } __Reply__task_threads_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_ports_register_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t init_port_set; - - NDR_record_t NDR; - mach_msg_type_number_t init_port_setCnt; - } __Reply__mach_ports_lookup_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t task_info_outCnt; - integer_t task_info_out[52]; - } __Reply__task_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_suspend_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_resume_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t special_port; - - } __Reply__task_get_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t child_act; - - } __Reply__thread_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t child_act; - - } __Reply__thread_create_running_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t old_handlers[32]; - - NDR_record_t NDR; - mach_msg_type_number_t masksCnt; - exception_mask_t masks[32]; - exception_behavior_t old_behaviors[32]; - thread_state_flavor_t old_flavors[32]; - } __Reply__task_get_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t old_handlerss[32]; - - NDR_record_t NDR; - mach_msg_type_number_t masksCnt; - exception_mask_t masks[32]; - exception_behavior_t old_behaviors[32]; - thread_state_flavor_t old_flavors[32]; - } __Reply__task_swap_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_lock_set; - - } __Reply__lock_set_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__lock_set_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t semaphore; - - } __Reply__semaphore_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__semaphore_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_policy_set_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t policy_infoCnt; - integer_t policy_info[16]; - boolean_t get_default; - } __Reply__task_policy_get_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_sample_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_policy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_emulation_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t emulation_vector; - - NDR_record_t NDR; - int vector_start; - mach_msg_type_number_t emulation_vectorCnt; - } __Reply__task_get_emulation_vector_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_emulation_vector_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_ras_pc_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t names; - mach_msg_ool_descriptor_t info; - - NDR_record_t NDR; - mach_msg_type_number_t namesCnt; - mach_msg_type_number_t infoCnt; - } __Reply__task_zone_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_assign_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_assign_default_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t assigned_set; - - } __Reply__task_get_assignment_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_policy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t old_stateCnt; - natural_t old_state[224]; - } __Reply__task_get_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - int old_limit; - } __Reply__task_set_phys_footprint_limit_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t suspend_token; - - } __Reply__task_suspend2_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_resume2_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - task_purgable_info_t stats; - } __Reply__task_purgable_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t voucher; - - } __Reply__task_get_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t old_voucher; - - } __Reply__task_swap_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__task_subsystem { - __Reply__task_create_t Reply_task_create; - __Reply__task_terminate_t Reply_task_terminate; - __Reply__task_threads_t Reply_task_threads; - __Reply__mach_ports_register_t Reply_mach_ports_register; - __Reply__mach_ports_lookup_t Reply_mach_ports_lookup; - __Reply__task_info_t Reply_task_info; - __Reply__task_set_info_t Reply_task_set_info; - __Reply__task_suspend_t Reply_task_suspend; - __Reply__task_resume_t Reply_task_resume; - __Reply__task_get_special_port_t Reply_task_get_special_port; - __Reply__task_set_special_port_t Reply_task_set_special_port; - __Reply__thread_create_t Reply_thread_create; - __Reply__thread_create_running_t Reply_thread_create_running; - __Reply__task_set_exception_ports_t Reply_task_set_exception_ports; - __Reply__task_get_exception_ports_t Reply_task_get_exception_ports; - __Reply__task_swap_exception_ports_t Reply_task_swap_exception_ports; - __Reply__lock_set_create_t Reply_lock_set_create; - __Reply__lock_set_destroy_t Reply_lock_set_destroy; - __Reply__semaphore_create_t Reply_semaphore_create; - __Reply__semaphore_destroy_t Reply_semaphore_destroy; - __Reply__task_policy_set_t Reply_task_policy_set; - __Reply__task_policy_get_t Reply_task_policy_get; - __Reply__task_sample_t Reply_task_sample; - __Reply__task_policy_t Reply_task_policy; - __Reply__task_set_emulation_t Reply_task_set_emulation; - __Reply__task_get_emulation_vector_t Reply_task_get_emulation_vector; - __Reply__task_set_emulation_vector_t Reply_task_set_emulation_vector; - __Reply__task_set_ras_pc_t Reply_task_set_ras_pc; - __Reply__task_zone_info_t Reply_task_zone_info; - __Reply__task_assign_t Reply_task_assign; - __Reply__task_assign_default_t Reply_task_assign_default; - __Reply__task_get_assignment_t Reply_task_get_assignment; - __Reply__task_set_policy_t Reply_task_set_policy; - __Reply__task_get_state_t Reply_task_get_state; - __Reply__task_set_state_t Reply_task_set_state; - __Reply__task_set_phys_footprint_limit_t Reply_task_set_phys_footprint_limit; - __Reply__task_suspend2_t Reply_task_suspend2; - __Reply__task_resume2_t Reply_task_resume2; - __Reply__task_purgable_info_t Reply_task_purgable_info; - __Reply__task_get_mach_voucher_t Reply_task_get_mach_voucher; - __Reply__task_set_mach_voucher_t Reply_task_set_mach_voucher; - __Reply__task_swap_mach_voucher_t Reply_task_swap_mach_voucher; -}; -extern "C" { - - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_terminate -( - thread_act_t target_act -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t act_get_state -( - thread_act_t target_act, - int flavor, - thread_state_t old_state, - mach_msg_type_number_t *old_stateCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t act_set_state -( - thread_act_t target_act, - int flavor, - thread_state_t new_state, - mach_msg_type_number_t new_stateCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -kern_return_t thread_get_state -( - thread_act_t target_act, - thread_state_flavor_t flavor, - thread_state_t old_state, - mach_msg_type_number_t *old_stateCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -kern_return_t thread_set_state -( - thread_act_t target_act, - thread_state_flavor_t flavor, - thread_state_t new_state, - mach_msg_type_number_t new_stateCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -kern_return_t thread_suspend -( - thread_act_t target_act -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -kern_return_t thread_resume -( - thread_act_t target_act -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -kern_return_t thread_abort -( - thread_act_t target_act -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -kern_return_t thread_abort_safely -( - thread_act_t target_act -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_depress_abort -( - thread_act_t thread -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_get_special_port -( - thread_act_t thr_act, - int which_port, - mach_port_t *special_port -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_set_special_port -( - thread_act_t thr_act, - int which_port, - mach_port_t special_port -); - - - - - -extern - -kern_return_t thread_info -( - thread_act_t target_act, - thread_flavor_t flavor, - thread_info_t thread_info_out, - mach_msg_type_number_t *thread_info_outCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_set_exception_ports -( - thread_act_t thread, - exception_mask_t exception_mask, - mach_port_t new_port, - exception_behavior_t behavior, - thread_state_flavor_t new_flavor -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_get_exception_ports -( - thread_act_t thread, - exception_mask_t exception_mask, - exception_mask_array_t masks, - mach_msg_type_number_t *masksCnt, - exception_handler_array_t old_handlers, - exception_behavior_array_t old_behaviors, - exception_flavor_array_t old_flavors -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_swap_exception_ports -( - thread_act_t thread, - exception_mask_t exception_mask, - mach_port_t new_port, - exception_behavior_t behavior, - thread_state_flavor_t new_flavor, - exception_mask_array_t masks, - mach_msg_type_number_t *masksCnt, - exception_handler_array_t old_handlers, - exception_behavior_array_t old_behaviors, - exception_flavor_array_t old_flavors -); - - - - - -extern - -kern_return_t thread_policy -( - thread_act_t thr_act, - policy_t policy, - policy_base_t base, - mach_msg_type_number_t baseCnt, - boolean_t set_limit -); - - - - - -extern - -kern_return_t thread_policy_set -( - thread_act_t thread, - thread_policy_flavor_t flavor, - thread_policy_t policy_info, - mach_msg_type_number_t policy_infoCnt -); - - - - - -extern - -kern_return_t thread_policy_get -( - thread_act_t thread, - thread_policy_flavor_t flavor, - thread_policy_t policy_info, - mach_msg_type_number_t *policy_infoCnt, - boolean_t *get_default -); - - - - - -extern - -kern_return_t thread_sample -( - thread_act_t thread, - mach_port_t reply -); - - - - - -extern - -kern_return_t etap_trace_thread -( - thread_act_t target_act, - boolean_t trace_status -); - - - - - -extern - -kern_return_t thread_assign -( - thread_act_t thread, - processor_set_t new_set -); - - - - - -extern - -kern_return_t thread_assign_default -( - thread_act_t thread -); - - - - - -extern - -kern_return_t thread_get_assignment -( - thread_act_t thread, - processor_set_name_t *assigned_set -); - - - - - -extern - -kern_return_t thread_set_policy -( - thread_act_t thr_act, - processor_set_t pset, - policy_t policy, - policy_base_t base, - mach_msg_type_number_t baseCnt, - policy_limit_t limit, - mach_msg_type_number_t limitCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_get_mach_voucher -( - thread_act_t thr_act, - mach_voucher_selector_t which, - ipc_voucher_t *voucher -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_set_mach_voucher -( - thread_act_t thr_act, - ipc_voucher_t voucher -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t thread_swap_mach_voucher -( - thread_act_t thr_act, - ipc_voucher_t new_voucher, - ipc_voucher_t *old_voucher -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__thread_terminate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int flavor; - mach_msg_type_number_t old_stateCnt; - } __Request__act_get_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int flavor; - mach_msg_type_number_t new_stateCnt; - natural_t new_state[224]; - } __Request__act_set_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - thread_state_flavor_t flavor; - mach_msg_type_number_t old_stateCnt; - } __Request__thread_get_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - thread_state_flavor_t flavor; - mach_msg_type_number_t new_stateCnt; - natural_t new_state[224]; - } __Request__thread_set_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__thread_suspend_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__thread_resume_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__thread_abort_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__thread_abort_safely_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__thread_depress_abort_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int which_port; - } __Request__thread_get_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t special_port; - - NDR_record_t NDR; - int which_port; - } __Request__thread_set_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - thread_flavor_t flavor; - mach_msg_type_number_t thread_info_outCnt; - } __Request__thread_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_port; - - NDR_record_t NDR; - exception_mask_t exception_mask; - exception_behavior_t behavior; - thread_state_flavor_t new_flavor; - } __Request__thread_set_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - exception_mask_t exception_mask; - } __Request__thread_get_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_port; - - NDR_record_t NDR; - exception_mask_t exception_mask; - exception_behavior_t behavior; - thread_state_flavor_t new_flavor; - } __Request__thread_swap_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - policy_t policy; - mach_msg_type_number_t baseCnt; - integer_t base[5]; - boolean_t set_limit; - } __Request__thread_policy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - thread_policy_flavor_t flavor; - mach_msg_type_number_t policy_infoCnt; - integer_t policy_info[16]; - } __Request__thread_policy_set_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - thread_policy_flavor_t flavor; - mach_msg_type_number_t policy_infoCnt; - boolean_t get_default; - } __Request__thread_policy_get_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t reply; - - } __Request__thread_sample_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - boolean_t trace_status; - } __Request__etap_trace_thread_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_set; - - } __Request__thread_assign_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__thread_assign_default_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__thread_get_assignment_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t pset; - - NDR_record_t NDR; - policy_t policy; - mach_msg_type_number_t baseCnt; - integer_t base[5]; - mach_msg_type_number_t limitCnt; - integer_t limit[1]; - } __Request__thread_set_policy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_voucher_selector_t which; - } __Request__thread_get_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t voucher; - - } __Request__thread_set_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_voucher; - mach_msg_port_descriptor_t old_voucher; - - } __Request__thread_swap_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__thread_act_subsystem { - __Request__thread_terminate_t Request_thread_terminate; - __Request__act_get_state_t Request_act_get_state; - __Request__act_set_state_t Request_act_set_state; - __Request__thread_get_state_t Request_thread_get_state; - __Request__thread_set_state_t Request_thread_set_state; - __Request__thread_suspend_t Request_thread_suspend; - __Request__thread_resume_t Request_thread_resume; - __Request__thread_abort_t Request_thread_abort; - __Request__thread_abort_safely_t Request_thread_abort_safely; - __Request__thread_depress_abort_t Request_thread_depress_abort; - __Request__thread_get_special_port_t Request_thread_get_special_port; - __Request__thread_set_special_port_t Request_thread_set_special_port; - __Request__thread_info_t Request_thread_info; - __Request__thread_set_exception_ports_t Request_thread_set_exception_ports; - __Request__thread_get_exception_ports_t Request_thread_get_exception_ports; - __Request__thread_swap_exception_ports_t Request_thread_swap_exception_ports; - __Request__thread_policy_t Request_thread_policy; - __Request__thread_policy_set_t Request_thread_policy_set; - __Request__thread_policy_get_t Request_thread_policy_get; - __Request__thread_sample_t Request_thread_sample; - __Request__etap_trace_thread_t Request_etap_trace_thread; - __Request__thread_assign_t Request_thread_assign; - __Request__thread_assign_default_t Request_thread_assign_default; - __Request__thread_get_assignment_t Request_thread_get_assignment; - __Request__thread_set_policy_t Request_thread_set_policy; - __Request__thread_get_mach_voucher_t Request_thread_get_mach_voucher; - __Request__thread_set_mach_voucher_t Request_thread_set_mach_voucher; - __Request__thread_swap_mach_voucher_t Request_thread_swap_mach_voucher; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_terminate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t old_stateCnt; - natural_t old_state[224]; - } __Reply__act_get_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__act_set_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t old_stateCnt; - natural_t old_state[224]; - } __Reply__thread_get_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_set_state_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_suspend_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_resume_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_abort_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_abort_safely_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_depress_abort_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t special_port; - - } __Reply__thread_get_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_set_special_port_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t thread_info_outCnt; - integer_t thread_info_out[32]; - } __Reply__thread_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_set_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t old_handlers[32]; - - NDR_record_t NDR; - mach_msg_type_number_t masksCnt; - exception_mask_t masks[32]; - exception_behavior_t old_behaviors[32]; - thread_state_flavor_t old_flavors[32]; - } __Reply__thread_get_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t old_handlers[32]; - - NDR_record_t NDR; - mach_msg_type_number_t masksCnt; - exception_mask_t masks[32]; - exception_behavior_t old_behaviors[32]; - thread_state_flavor_t old_flavors[32]; - } __Reply__thread_swap_exception_ports_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_policy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_policy_set_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t policy_infoCnt; - integer_t policy_info[16]; - boolean_t get_default; - } __Reply__thread_policy_get_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_sample_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__etap_trace_thread_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_assign_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_assign_default_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t assigned_set; - - } __Reply__thread_get_assignment_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_set_policy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t voucher; - - } __Reply__thread_get_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__thread_set_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t old_voucher; - - } __Reply__thread_swap_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__thread_act_subsystem { - __Reply__thread_terminate_t Reply_thread_terminate; - __Reply__act_get_state_t Reply_act_get_state; - __Reply__act_set_state_t Reply_act_set_state; - __Reply__thread_get_state_t Reply_thread_get_state; - __Reply__thread_set_state_t Reply_thread_set_state; - __Reply__thread_suspend_t Reply_thread_suspend; - __Reply__thread_resume_t Reply_thread_resume; - __Reply__thread_abort_t Reply_thread_abort; - __Reply__thread_abort_safely_t Reply_thread_abort_safely; - __Reply__thread_depress_abort_t Reply_thread_depress_abort; - __Reply__thread_get_special_port_t Reply_thread_get_special_port; - __Reply__thread_set_special_port_t Reply_thread_set_special_port; - __Reply__thread_info_t Reply_thread_info; - __Reply__thread_set_exception_ports_t Reply_thread_set_exception_ports; - __Reply__thread_get_exception_ports_t Reply_thread_get_exception_ports; - __Reply__thread_swap_exception_ports_t Reply_thread_swap_exception_ports; - __Reply__thread_policy_t Reply_thread_policy; - __Reply__thread_policy_set_t Reply_thread_policy_set; - __Reply__thread_policy_get_t Reply_thread_policy_get; - __Reply__thread_sample_t Reply_thread_sample; - __Reply__etap_trace_thread_t Reply_etap_trace_thread; - __Reply__thread_assign_t Reply_thread_assign; - __Reply__thread_assign_default_t Reply_thread_assign_default; - __Reply__thread_get_assignment_t Reply_thread_get_assignment; - __Reply__thread_set_policy_t Reply_thread_set_policy; - __Reply__thread_get_mach_voucher_t Reply_thread_get_mach_voucher; - __Reply__thread_set_mach_voucher_t Reply_thread_set_mach_voucher; - __Reply__thread_swap_mach_voucher_t Reply_thread_swap_mach_voucher; -}; -extern "C" { - - - - - - -extern - -kern_return_t vm_region -( - vm_map_t target_task, - vm_address_t *address, - vm_size_t *size, - vm_region_flavor_t flavor, - vm_region_info_t info, - mach_msg_type_number_t *infoCnt, - mach_port_t *object_name -); - - - - - -extern - -kern_return_t vm_allocate -( - vm_map_t target_task, - vm_address_t *address, - vm_size_t size, - int flags -); - - - - - -extern - -kern_return_t vm_deallocate -( - vm_map_t target_task, - vm_address_t address, - vm_size_t size -); - - - - - -extern - -kern_return_t vm_protect -( - vm_map_t target_task, - vm_address_t address, - vm_size_t size, - boolean_t set_maximum, - vm_prot_t new_protection -); - - - - - -extern - -kern_return_t vm_inherit -( - vm_map_t target_task, - vm_address_t address, - vm_size_t size, - vm_inherit_t new_inheritance -); - - - - - -extern - -kern_return_t vm_read -( - vm_map_t target_task, - vm_address_t address, - vm_size_t size, - vm_offset_t *data, - mach_msg_type_number_t *dataCnt -); - - - - - -extern - -kern_return_t vm_read_list -( - vm_map_t target_task, - vm_read_entry_t data_list, - natural_t count -); - - - - - -extern - -kern_return_t vm_write -( - vm_map_t target_task, - vm_address_t address, - vm_offset_t data, - mach_msg_type_number_t dataCnt -); - - - - - -extern - -kern_return_t vm_copy -( - vm_map_t target_task, - vm_address_t source_address, - vm_size_t size, - vm_address_t dest_address -); - - - - - -extern - -kern_return_t vm_read_overwrite -( - vm_map_t target_task, - vm_address_t address, - vm_size_t size, - vm_address_t data, - vm_size_t *outsize -); - - - - - -extern - -kern_return_t vm_msync -( - vm_map_t target_task, - vm_address_t address, - vm_size_t size, - vm_sync_t sync_flags -); - - - - - -extern - -kern_return_t vm_behavior_set -( - vm_map_t target_task, - vm_address_t address, - vm_size_t size, - vm_behavior_t new_behavior -); - - - - - -extern - -kern_return_t vm_map -( - vm_map_t target_task, - vm_address_t *address, - vm_size_t size, - vm_address_t mask, - int flags, - mem_entry_name_port_t object, - vm_offset_t offset, - boolean_t copy, - vm_prot_t cur_protection, - vm_prot_t max_protection, - vm_inherit_t inheritance -); - - - - - -extern - -kern_return_t vm_machine_attribute -( - vm_map_t target_task, - vm_address_t address, - vm_size_t size, - vm_machine_attribute_t attribute, - vm_machine_attribute_val_t *value -); - - - - - -extern - -kern_return_t vm_remap -( - vm_map_t target_task, - vm_address_t *target_address, - vm_size_t size, - vm_address_t mask, - int flags, - vm_map_t src_task, - vm_address_t src_address, - boolean_t copy, - vm_prot_t *cur_protection, - vm_prot_t *max_protection, - vm_inherit_t inheritance -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_wire -( - vm_map_t target_task, - boolean_t must_wire -); - - - - - -extern - -kern_return_t mach_make_memory_entry -( - vm_map_t target_task, - vm_size_t *size, - vm_offset_t offset, - vm_prot_t permission, - mem_entry_name_port_t *object_handle, - mem_entry_name_port_t parent_entry -); - - - - - -extern - -kern_return_t vm_map_page_query -( - vm_map_t target_map, - vm_offset_t offset, - integer_t *disposition, - integer_t *ref_count -); - - - - - -extern - -kern_return_t mach_vm_region_info -( - vm_map_t task, - vm_address_t address, - vm_info_region_t *region, - vm_info_object_array_t *objects, - mach_msg_type_number_t *objectsCnt -); - - - - - -extern - -kern_return_t vm_mapped_pages_info -( - vm_map_t task, - page_address_array_t *pages, - mach_msg_type_number_t *pagesCnt -); - - - - - -extern - -kern_return_t vm_region_recurse -( - vm_map_t target_task, - vm_address_t *address, - vm_size_t *size, - natural_t *nesting_depth, - vm_region_recurse_info_t info, - mach_msg_type_number_t *infoCnt -); - - - - - -extern - -kern_return_t vm_region_recurse_64 -( - vm_map_t target_task, - vm_address_t *address, - vm_size_t *size, - natural_t *nesting_depth, - vm_region_recurse_info_t info, - mach_msg_type_number_t *infoCnt -); - - - - - -extern - -kern_return_t mach_vm_region_info_64 -( - vm_map_t task, - vm_address_t address, - vm_info_region_64_t *region, - vm_info_object_array_t *objects, - mach_msg_type_number_t *objectsCnt -); - - - - - -extern - -kern_return_t vm_region_64 -( - vm_map_t target_task, - vm_address_t *address, - vm_size_t *size, - vm_region_flavor_t flavor, - vm_region_info_t info, - mach_msg_type_number_t *infoCnt, - mach_port_t *object_name -); - - - - - -extern - -kern_return_t mach_make_memory_entry_64 -( - vm_map_t target_task, - memory_object_size_t *size, - memory_object_offset_t offset, - vm_prot_t permission, - mach_port_t *object_handle, - mem_entry_name_port_t parent_entry -); - - - - - -extern - -kern_return_t vm_map_64 -( - vm_map_t target_task, - vm_address_t *address, - vm_size_t size, - vm_address_t mask, - int flags, - mem_entry_name_port_t object, - memory_object_offset_t offset, - boolean_t copy, - vm_prot_t cur_protection, - vm_prot_t max_protection, - vm_inherit_t inheritance -); - - - - - -extern - -kern_return_t vm_purgable_control -( - vm_map_t target_task, - vm_address_t address, - vm_purgable_t control, - int *state -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_region_flavor_t flavor; - mach_msg_type_number_t infoCnt; - } __Request__vm_region_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - int flags; - } __Request__vm_allocate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - } __Request__vm_deallocate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - boolean_t set_maximum; - vm_prot_t new_protection; - } __Request__vm_protect_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - vm_inherit_t new_inheritance; - } __Request__vm_inherit_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - } __Request__vm_read_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_read_entry_t data_list; - natural_t count; - } __Request__vm_read_list_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t data; - - NDR_record_t NDR; - vm_address_t address; - mach_msg_type_number_t dataCnt; - } __Request__vm_write_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t source_address; - vm_size_t size; - vm_address_t dest_address; - } __Request__vm_copy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - vm_address_t data; - } __Request__vm_read_overwrite_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - vm_sync_t sync_flags; - } __Request__vm_msync_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - vm_behavior_t new_behavior; - } __Request__vm_behavior_set_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t object; - - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - vm_address_t mask; - int flags; - vm_offset_t offset; - boolean_t copy; - vm_prot_t cur_protection; - vm_prot_t max_protection; - vm_inherit_t inheritance; - } __Request__vm_map_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - vm_machine_attribute_t attribute; - vm_machine_attribute_val_t value; - } __Request__vm_machine_attribute_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t src_task; - - NDR_record_t NDR; - vm_address_t target_address; - vm_size_t size; - vm_address_t mask; - int flags; - vm_address_t src_address; - boolean_t copy; - vm_inherit_t inheritance; - } __Request__vm_remap_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - boolean_t must_wire; - } __Request__task_wire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t parent_entry; - - NDR_record_t NDR; - vm_size_t size; - vm_offset_t offset; - vm_prot_t permission; - } __Request__mach_make_memory_entry_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_offset_t offset; - } __Request__vm_map_page_query_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - } __Request__mach_vm_region_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__vm_mapped_pages_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - natural_t nesting_depth; - mach_msg_type_number_t infoCnt; - } __Request__vm_region_recurse_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - natural_t nesting_depth; - mach_msg_type_number_t infoCnt; - } __Request__vm_region_recurse_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - } __Request__mach_vm_region_info_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_region_flavor_t flavor; - mach_msg_type_number_t infoCnt; - } __Request__vm_region_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t parent_entry; - - NDR_record_t NDR; - memory_object_size_t size; - memory_object_offset_t offset; - vm_prot_t permission; - } __Request__mach_make_memory_entry_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t object; - - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - vm_address_t mask; - int flags; - memory_object_offset_t offset; - boolean_t copy; - vm_prot_t cur_protection; - vm_prot_t max_protection; - vm_inherit_t inheritance; - } __Request__vm_map_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - vm_address_t address; - vm_purgable_t control; - int state; - } __Request__vm_purgable_control_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__vm_map_subsystem { - __Request__vm_region_t Request_vm_region; - __Request__vm_allocate_t Request_vm_allocate; - __Request__vm_deallocate_t Request_vm_deallocate; - __Request__vm_protect_t Request_vm_protect; - __Request__vm_inherit_t Request_vm_inherit; - __Request__vm_read_t Request_vm_read; - __Request__vm_read_list_t Request_vm_read_list; - __Request__vm_write_t Request_vm_write; - __Request__vm_copy_t Request_vm_copy; - __Request__vm_read_overwrite_t Request_vm_read_overwrite; - __Request__vm_msync_t Request_vm_msync; - __Request__vm_behavior_set_t Request_vm_behavior_set; - __Request__vm_map_t Request_vm_map; - __Request__vm_machine_attribute_t Request_vm_machine_attribute; - __Request__vm_remap_t Request_vm_remap; - __Request__task_wire_t Request_task_wire; - __Request__mach_make_memory_entry_t Request_mach_make_memory_entry; - __Request__vm_map_page_query_t Request_vm_map_page_query; - __Request__mach_vm_region_info_t Request_mach_vm_region_info; - __Request__vm_mapped_pages_info_t Request_vm_mapped_pages_info; - __Request__vm_region_recurse_t Request_vm_region_recurse; - __Request__vm_region_recurse_64_t Request_vm_region_recurse_64; - __Request__mach_vm_region_info_64_t Request_mach_vm_region_info_64; - __Request__vm_region_64_t Request_vm_region_64; - __Request__mach_make_memory_entry_64_t Request_mach_make_memory_entry_64; - __Request__vm_map_64_t Request_vm_map_64; - __Request__vm_purgable_control_t Request_vm_purgable_control; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t object_name; - - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - mach_msg_type_number_t infoCnt; - int info[10]; - } __Reply__vm_region_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_address_t address; - } __Reply__vm_allocate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__vm_deallocate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__vm_protect_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__vm_inherit_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t data; - - NDR_record_t NDR; - mach_msg_type_number_t dataCnt; - } __Reply__vm_read_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_read_entry_t data_list; - } __Reply__vm_read_list_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__vm_write_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__vm_copy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_size_t outsize; - } __Reply__vm_read_overwrite_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__vm_msync_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__vm_behavior_set_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_address_t address; - } __Reply__vm_map_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_machine_attribute_val_t value; - } __Reply__vm_machine_attribute_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_address_t target_address; - vm_prot_t cur_protection; - vm_prot_t max_protection; - } __Reply__vm_remap_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_wire_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t object_handle; - - NDR_record_t NDR; - vm_size_t size; - } __Reply__mach_make_memory_entry_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - integer_t disposition; - integer_t ref_count; - } __Reply__vm_map_page_query_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t objects; - - NDR_record_t NDR; - vm_info_region_t region; - mach_msg_type_number_t objectsCnt; - } __Reply__mach_vm_region_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t pages; - - NDR_record_t NDR; - mach_msg_type_number_t pagesCnt; - } __Reply__vm_mapped_pages_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_address_t address; - vm_size_t size; - natural_t nesting_depth; - mach_msg_type_number_t infoCnt; - int info[19]; - } __Reply__vm_region_recurse_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_address_t address; - vm_size_t size; - natural_t nesting_depth; - mach_msg_type_number_t infoCnt; - int info[19]; - } __Reply__vm_region_recurse_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t objects; - - NDR_record_t NDR; - vm_info_region_64_t region; - mach_msg_type_number_t objectsCnt; - } __Reply__mach_vm_region_info_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t object_name; - - NDR_record_t NDR; - vm_address_t address; - vm_size_t size; - mach_msg_type_number_t infoCnt; - int info[10]; - } __Reply__vm_region_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t object_handle; - - NDR_record_t NDR; - memory_object_size_t size; - } __Reply__mach_make_memory_entry_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_address_t address; - } __Reply__vm_map_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - int state; - } __Reply__vm_purgable_control_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__vm_map_subsystem { - __Reply__vm_region_t Reply_vm_region; - __Reply__vm_allocate_t Reply_vm_allocate; - __Reply__vm_deallocate_t Reply_vm_deallocate; - __Reply__vm_protect_t Reply_vm_protect; - __Reply__vm_inherit_t Reply_vm_inherit; - __Reply__vm_read_t Reply_vm_read; - __Reply__vm_read_list_t Reply_vm_read_list; - __Reply__vm_write_t Reply_vm_write; - __Reply__vm_copy_t Reply_vm_copy; - __Reply__vm_read_overwrite_t Reply_vm_read_overwrite; - __Reply__vm_msync_t Reply_vm_msync; - __Reply__vm_behavior_set_t Reply_vm_behavior_set; - __Reply__vm_map_t Reply_vm_map; - __Reply__vm_machine_attribute_t Reply_vm_machine_attribute; - __Reply__vm_remap_t Reply_vm_remap; - __Reply__task_wire_t Reply_task_wire; - __Reply__mach_make_memory_entry_t Reply_mach_make_memory_entry; - __Reply__vm_map_page_query_t Reply_vm_map_page_query; - __Reply__mach_vm_region_info_t Reply_mach_vm_region_info; - __Reply__vm_mapped_pages_info_t Reply_vm_mapped_pages_info; - __Reply__vm_region_recurse_t Reply_vm_region_recurse; - __Reply__vm_region_recurse_64_t Reply_vm_region_recurse_64; - __Reply__mach_vm_region_info_64_t Reply_mach_vm_region_info_64; - __Reply__vm_region_64_t Reply_vm_region_64; - __Reply__mach_make_memory_entry_64_t Reply_mach_make_memory_entry_64; - __Reply__vm_map_64_t Reply_vm_map_64; - __Reply__vm_purgable_control_t Reply_vm_purgable_control; -}; -extern "C" { - - - - - - -extern - -kern_return_t mach_port_names -( - ipc_space_t task, - mach_port_name_array_t *names, - mach_msg_type_number_t *namesCnt, - mach_port_type_array_t *types, - mach_msg_type_number_t *typesCnt -); - - - - - -extern - -kern_return_t mach_port_type -( - ipc_space_t task, - mach_port_name_t name, - mach_port_type_t *ptype -); - - - - - -extern - -kern_return_t mach_port_rename -( - ipc_space_t task, - mach_port_name_t old_name, - mach_port_name_t new_name -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t mach_port_allocate_name -( - ipc_space_t task, - mach_port_right_t right, - mach_port_name_t name -); - - - - - -extern - -kern_return_t mach_port_allocate -( - ipc_space_t task, - mach_port_right_t right, - mach_port_name_t *name -); - - - - - -extern - -kern_return_t mach_port_destroy -( - ipc_space_t task, - mach_port_name_t name -); - - - - - -extern - -kern_return_t mach_port_deallocate -( - ipc_space_t task, - mach_port_name_t name -); - - - - - -extern - -kern_return_t mach_port_get_refs -( - ipc_space_t task, - mach_port_name_t name, - mach_port_right_t right, - mach_port_urefs_t *refs -); - - - - - -extern - -kern_return_t mach_port_mod_refs -( - ipc_space_t task, - mach_port_name_t name, - mach_port_right_t right, - mach_port_delta_t delta -); - - - - - -extern - -kern_return_t mach_port_peek -( - ipc_space_t task, - mach_port_name_t name, - mach_msg_trailer_type_t trailer_type, - mach_port_seqno_t *request_seqnop, - mach_msg_size_t *msg_sizep, - mach_msg_id_t *msg_idp, - mach_msg_trailer_info_t trailer_infop, - mach_msg_type_number_t *trailer_infopCnt -); - - - - - -extern - -kern_return_t mach_port_set_mscount -( - ipc_space_t task, - mach_port_name_t name, - mach_port_mscount_t mscount -); - - - - - -extern - -kern_return_t mach_port_get_set_status -( - ipc_space_t task, - mach_port_name_t name, - mach_port_name_array_t *members, - mach_msg_type_number_t *membersCnt -); - - - - - -extern - -kern_return_t mach_port_move_member -( - ipc_space_t task, - mach_port_name_t member, - mach_port_name_t after -); - - - - - -extern - -kern_return_t mach_port_request_notification -( - ipc_space_t task, - mach_port_name_t name, - mach_msg_id_t msgid, - mach_port_mscount_t sync, - mach_port_t notify, - mach_msg_type_name_t notifyPoly, - mach_port_t *previous -); - - - - - -extern - -kern_return_t mach_port_insert_right -( - ipc_space_t task, - mach_port_name_t name, - mach_port_t poly, - mach_msg_type_name_t polyPoly -); - - - - - -extern - -kern_return_t mach_port_extract_right -( - ipc_space_t task, - mach_port_name_t name, - mach_msg_type_name_t msgt_name, - mach_port_t *poly, - mach_msg_type_name_t *polyPoly -); - - - - - -extern - -kern_return_t mach_port_set_seqno -( - ipc_space_t task, - mach_port_name_t name, - mach_port_seqno_t seqno -); - - - - - -extern - -kern_return_t mach_port_get_attributes -( - ipc_space_t task, - mach_port_name_t name, - mach_port_flavor_t flavor, - mach_port_info_t port_info_out, - mach_msg_type_number_t *port_info_outCnt -); - - - - - -extern - -kern_return_t mach_port_set_attributes -( - ipc_space_t task, - mach_port_name_t name, - mach_port_flavor_t flavor, - mach_port_info_t port_info, - mach_msg_type_number_t port_infoCnt -); - - - - - -extern - -kern_return_t mach_port_allocate_qos -( - ipc_space_t task, - mach_port_right_t right, - mach_port_qos_t *qos, - mach_port_name_t *name -); - - - - - -extern - -kern_return_t mach_port_allocate_full -( - ipc_space_t task, - mach_port_right_t right, - mach_port_t proto, - mach_port_qos_t *qos, - mach_port_name_t *name -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t task_set_port_space -( - ipc_space_t task, - int table_entries -); - - - - - -extern - -kern_return_t mach_port_get_srights -( - ipc_space_t task, - mach_port_name_t name, - mach_port_rights_t *srights -); - - - - - -extern - -kern_return_t mach_port_space_info -( - ipc_space_t task, - ipc_info_space_t *space_info, - ipc_info_name_array_t *table_info, - mach_msg_type_number_t *table_infoCnt, - ipc_info_tree_name_array_t *tree_info, - mach_msg_type_number_t *tree_infoCnt -); - - - - - -extern - -kern_return_t mach_port_dnrequest_info -( - ipc_space_t task, - mach_port_name_t name, - unsigned *dnr_total, - unsigned *dnr_used -); - - - - - -extern - -kern_return_t mach_port_kernel_object -( - ipc_space_t task, - mach_port_name_t name, - unsigned *object_type, - unsigned *object_addr -); - - - - - -extern - -kern_return_t mach_port_insert_member -( - ipc_space_t task, - mach_port_name_t name, - mach_port_name_t pset -); - - - - - -extern - -kern_return_t mach_port_extract_member -( - ipc_space_t task, - mach_port_name_t name, - mach_port_name_t pset -); - - - - - -extern - -kern_return_t mach_port_get_context -( - ipc_space_t task, - mach_port_name_t name, - mach_port_context_t *context -); - - - - - -extern - -kern_return_t mach_port_set_context -( - ipc_space_t task, - mach_port_name_t name, - mach_port_context_t context -); - - - - - -extern - -kern_return_t mach_port_kobject -( - ipc_space_t task, - mach_port_name_t name, - natural_t *object_type, - mach_vm_address_t *object_addr -); - - - - - -extern - -kern_return_t mach_port_construct -( - ipc_space_t task, - mach_port_options_ptr_t options, - mach_port_context_t context, - mach_port_name_t *name -); - - - - - -extern - -kern_return_t mach_port_destruct -( - ipc_space_t task, - mach_port_name_t name, - mach_port_delta_t srdelta, - mach_port_context_t guard -); - - - - - -extern - -kern_return_t mach_port_guard -( - ipc_space_t task, - mach_port_name_t name, - mach_port_context_t guard, - boolean_t strict -); - - - - - -extern - -kern_return_t mach_port_unguard -( - ipc_space_t task, - mach_port_name_t name, - mach_port_context_t guard -); - - - - - -extern - -kern_return_t mach_port_space_basic_info -( - ipc_space_t task, - ipc_info_space_basic_t *basic_info -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__mach_port_names_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_type_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t old_name; - mach_port_name_t new_name; - } __Request__mach_port_rename_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_right_t right; - mach_port_name_t name; - } __Request__mach_port_allocate_name_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_right_t right; - } __Request__mach_port_allocate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_deallocate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_right_t right; - } __Request__mach_port_get_refs_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_right_t right; - mach_port_delta_t delta; - } __Request__mach_port_mod_refs_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_msg_trailer_type_t trailer_type; - mach_port_seqno_t request_seqnop; - mach_msg_type_number_t trailer_infopCnt; - } __Request__mach_port_peek_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_mscount_t mscount; - } __Request__mach_port_set_mscount_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_get_set_status_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t member; - mach_port_name_t after; - } __Request__mach_port_move_member_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t notify; - - NDR_record_t NDR; - mach_port_name_t name; - mach_msg_id_t msgid; - mach_port_mscount_t sync; - } __Request__mach_port_request_notification_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t poly; - - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_insert_right_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_msg_type_name_t msgt_name; - } __Request__mach_port_extract_right_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_seqno_t seqno; - } __Request__mach_port_set_seqno_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_flavor_t flavor; - mach_msg_type_number_t port_info_outCnt; - } __Request__mach_port_get_attributes_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_flavor_t flavor; - mach_msg_type_number_t port_infoCnt; - integer_t port_info[17]; - } __Request__mach_port_set_attributes_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_right_t right; - mach_port_qos_t qos; - } __Request__mach_port_allocate_qos_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t proto; - - NDR_record_t NDR; - mach_port_right_t right; - mach_port_qos_t qos; - mach_port_name_t name; - } __Request__mach_port_allocate_full_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - int table_entries; - } __Request__task_set_port_space_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_get_srights_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__mach_port_space_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_dnrequest_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_kernel_object_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_name_t pset; - } __Request__mach_port_insert_member_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_name_t pset; - } __Request__mach_port_extract_member_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_get_context_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_context_t context; - } __Request__mach_port_set_context_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_port_kobject_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t options; - - NDR_record_t NDR; - mach_port_context_t context; - } __Request__mach_port_construct_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_delta_t srdelta; - mach_port_context_t guard; - } __Request__mach_port_destruct_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_context_t guard; - boolean_t strict; - } __Request__mach_port_guard_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - mach_port_context_t guard; - } __Request__mach_port_unguard_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__mach_port_space_basic_info_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__mach_port_subsystem { - __Request__mach_port_names_t Request_mach_port_names; - __Request__mach_port_type_t Request_mach_port_type; - __Request__mach_port_rename_t Request_mach_port_rename; - __Request__mach_port_allocate_name_t Request_mach_port_allocate_name; - __Request__mach_port_allocate_t Request_mach_port_allocate; - __Request__mach_port_destroy_t Request_mach_port_destroy; - __Request__mach_port_deallocate_t Request_mach_port_deallocate; - __Request__mach_port_get_refs_t Request_mach_port_get_refs; - __Request__mach_port_mod_refs_t Request_mach_port_mod_refs; - __Request__mach_port_peek_t Request_mach_port_peek; - __Request__mach_port_set_mscount_t Request_mach_port_set_mscount; - __Request__mach_port_get_set_status_t Request_mach_port_get_set_status; - __Request__mach_port_move_member_t Request_mach_port_move_member; - __Request__mach_port_request_notification_t Request_mach_port_request_notification; - __Request__mach_port_insert_right_t Request_mach_port_insert_right; - __Request__mach_port_extract_right_t Request_mach_port_extract_right; - __Request__mach_port_set_seqno_t Request_mach_port_set_seqno; - __Request__mach_port_get_attributes_t Request_mach_port_get_attributes; - __Request__mach_port_set_attributes_t Request_mach_port_set_attributes; - __Request__mach_port_allocate_qos_t Request_mach_port_allocate_qos; - __Request__mach_port_allocate_full_t Request_mach_port_allocate_full; - __Request__task_set_port_space_t Request_task_set_port_space; - __Request__mach_port_get_srights_t Request_mach_port_get_srights; - __Request__mach_port_space_info_t Request_mach_port_space_info; - __Request__mach_port_dnrequest_info_t Request_mach_port_dnrequest_info; - __Request__mach_port_kernel_object_t Request_mach_port_kernel_object; - __Request__mach_port_insert_member_t Request_mach_port_insert_member; - __Request__mach_port_extract_member_t Request_mach_port_extract_member; - __Request__mach_port_get_context_t Request_mach_port_get_context; - __Request__mach_port_set_context_t Request_mach_port_set_context; - __Request__mach_port_kobject_t Request_mach_port_kobject; - __Request__mach_port_construct_t Request_mach_port_construct; - __Request__mach_port_destruct_t Request_mach_port_destruct; - __Request__mach_port_guard_t Request_mach_port_guard; - __Request__mach_port_unguard_t Request_mach_port_unguard; - __Request__mach_port_space_basic_info_t Request_mach_port_space_basic_info; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t names; - mach_msg_ool_descriptor_t types; - - NDR_record_t NDR; - mach_msg_type_number_t namesCnt; - mach_msg_type_number_t typesCnt; - } __Reply__mach_port_names_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_port_type_t ptype; - } __Reply__mach_port_type_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_rename_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_allocate_name_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_port_name_t name; - } __Reply__mach_port_allocate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_destroy_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_deallocate_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_port_urefs_t refs; - } __Reply__mach_port_get_refs_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_mod_refs_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_port_seqno_t request_seqnop; - mach_msg_size_t msg_sizep; - mach_msg_id_t msg_idp; - mach_msg_type_number_t trailer_infopCnt; - char trailer_infop[68]; - } __Reply__mach_port_peek_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_set_mscount_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t members; - - NDR_record_t NDR; - mach_msg_type_number_t membersCnt; - } __Reply__mach_port_get_set_status_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_move_member_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t previous; - - } __Reply__mach_port_request_notification_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_insert_right_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t poly; - - } __Reply__mach_port_extract_right_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_set_seqno_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t port_info_outCnt; - integer_t port_info_out[17]; - } __Reply__mach_port_get_attributes_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_set_attributes_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_port_qos_t qos; - mach_port_name_t name; - } __Reply__mach_port_allocate_qos_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_port_qos_t qos; - mach_port_name_t name; - } __Reply__mach_port_allocate_full_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__task_set_port_space_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_port_rights_t srights; - } __Reply__mach_port_get_srights_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t table_info; - mach_msg_ool_descriptor_t tree_info; - - NDR_record_t NDR; - ipc_info_space_t space_info; - mach_msg_type_number_t table_infoCnt; - mach_msg_type_number_t tree_infoCnt; - } __Reply__mach_port_space_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - unsigned dnr_total; - unsigned dnr_used; - } __Reply__mach_port_dnrequest_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - unsigned object_type; - unsigned object_addr; - } __Reply__mach_port_kernel_object_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_insert_member_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_extract_member_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_port_context_t context; - } __Reply__mach_port_get_context_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_set_context_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - natural_t object_type; - mach_vm_address_t object_addr; - } __Reply__mach_port_kobject_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_port_name_t name; - } __Reply__mach_port_construct_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_destruct_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_guard_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_port_unguard_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - ipc_info_space_basic_t basic_info; - } __Reply__mach_port_space_basic_info_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__mach_port_subsystem { - __Reply__mach_port_names_t Reply_mach_port_names; - __Reply__mach_port_type_t Reply_mach_port_type; - __Reply__mach_port_rename_t Reply_mach_port_rename; - __Reply__mach_port_allocate_name_t Reply_mach_port_allocate_name; - __Reply__mach_port_allocate_t Reply_mach_port_allocate; - __Reply__mach_port_destroy_t Reply_mach_port_destroy; - __Reply__mach_port_deallocate_t Reply_mach_port_deallocate; - __Reply__mach_port_get_refs_t Reply_mach_port_get_refs; - __Reply__mach_port_mod_refs_t Reply_mach_port_mod_refs; - __Reply__mach_port_peek_t Reply_mach_port_peek; - __Reply__mach_port_set_mscount_t Reply_mach_port_set_mscount; - __Reply__mach_port_get_set_status_t Reply_mach_port_get_set_status; - __Reply__mach_port_move_member_t Reply_mach_port_move_member; - __Reply__mach_port_request_notification_t Reply_mach_port_request_notification; - __Reply__mach_port_insert_right_t Reply_mach_port_insert_right; - __Reply__mach_port_extract_right_t Reply_mach_port_extract_right; - __Reply__mach_port_set_seqno_t Reply_mach_port_set_seqno; - __Reply__mach_port_get_attributes_t Reply_mach_port_get_attributes; - __Reply__mach_port_set_attributes_t Reply_mach_port_set_attributes; - __Reply__mach_port_allocate_qos_t Reply_mach_port_allocate_qos; - __Reply__mach_port_allocate_full_t Reply_mach_port_allocate_full; - __Reply__task_set_port_space_t Reply_task_set_port_space; - __Reply__mach_port_get_srights_t Reply_mach_port_get_srights; - __Reply__mach_port_space_info_t Reply_mach_port_space_info; - __Reply__mach_port_dnrequest_info_t Reply_mach_port_dnrequest_info; - __Reply__mach_port_kernel_object_t Reply_mach_port_kernel_object; - __Reply__mach_port_insert_member_t Reply_mach_port_insert_member; - __Reply__mach_port_extract_member_t Reply_mach_port_extract_member; - __Reply__mach_port_get_context_t Reply_mach_port_get_context; - __Reply__mach_port_set_context_t Reply_mach_port_set_context; - __Reply__mach_port_kobject_t Reply_mach_port_kobject; - __Reply__mach_port_construct_t Reply_mach_port_construct; - __Reply__mach_port_destruct_t Reply_mach_port_destruct; - __Reply__mach_port_guard_t Reply_mach_port_guard; - __Reply__mach_port_unguard_t Reply_mach_port_unguard; - __Reply__mach_port_space_basic_info_t Reply_mach_port_space_basic_info; -}; - -extern "C" { - - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t host_info -( - host_t host, - host_flavor_t flavor, - host_info_t host_info_out, - mach_msg_type_number_t *host_info_outCnt -); - - - - - -extern - -kern_return_t host_kernel_version -( - host_t host, - kernel_version_t kernel_version -); - - - - - -extern - -kern_return_t _host_page_size -( - host_t host, - vm_size_t *out_page_size -); - - - - - -extern - -kern_return_t mach_memory_object_memory_entry -( - host_t host, - boolean_t internal, - vm_size_t size, - vm_prot_t permission, - memory_object_t pager, - mach_port_t *entry_handle -); - - - - - -extern - -kern_return_t host_processor_info -( - host_t host, - processor_flavor_t flavor, - natural_t *out_processor_count, - processor_info_array_t *out_processor_info, - mach_msg_type_number_t *out_processor_infoCnt -); - - - - - -extern - -kern_return_t host_get_io_master -( - host_t host, - io_master_t *io_master -); - - - - - -extern - -kern_return_t host_get_clock_service -( - host_t host, - clock_id_t clock_id, - clock_serv_t *clock_serv -); - - - - - -extern - -kern_return_t kmod_get_info -( - host_t host, - kmod_args_t *modules, - mach_msg_type_number_t *modulesCnt -); - - - - - -extern - -kern_return_t host_zone_info -( - host_priv_t host, - zone_name_array_t *names, - mach_msg_type_number_t *namesCnt, - zone_info_array_t *info, - mach_msg_type_number_t *infoCnt -); - - - - - -extern - -kern_return_t host_virtual_physical_table_info -( - host_t host, - hash_info_bucket_array_t *info, - mach_msg_type_number_t *infoCnt -); - - - - - -extern - -kern_return_t processor_set_default -( - host_t host, - processor_set_name_t *default_set -); - - - - - -extern - -kern_return_t processor_set_create -( - host_t host, - processor_set_t *new_set, - processor_set_name_t *new_name -); - - - - - -extern - -kern_return_t mach_memory_object_memory_entry_64 -( - host_t host, - boolean_t internal, - memory_object_size_t size, - vm_prot_t permission, - memory_object_t pager, - mach_port_t *entry_handle -); - - - - - -extern - -kern_return_t host_statistics -( - host_t host_priv, - host_flavor_t flavor, - host_info_t host_info_out, - mach_msg_type_number_t *host_info_outCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t host_request_notification -( - host_t host, - host_flavor_t notify_type, - mach_port_t notify_port -); - - - - - -extern - -kern_return_t host_lockgroup_info -( - host_t host, - lockgroup_info_array_t *lockgroup_info, - mach_msg_type_number_t *lockgroup_infoCnt -); - - - - - -extern - -kern_return_t host_statistics64 -( - host_t host_priv, - host_flavor_t flavor, - host_info64_t host_info64_out, - mach_msg_type_number_t *host_info64_outCnt -); - - - - - -extern - -kern_return_t mach_zone_info -( - host_priv_t host, - mach_zone_name_array_t *names, - mach_msg_type_number_t *namesCnt, - mach_zone_info_array_t *info, - mach_msg_type_number_t *infoCnt -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t host_create_mach_voucher -( - host_t host, - mach_voucher_attr_raw_recipe_array_t recipes, - mach_msg_type_number_t recipesCnt, - ipc_voucher_t *voucher -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t host_register_mach_voucher_attr_manager -( - host_t host, - mach_voucher_attr_manager_t attr_manager, - mach_voucher_attr_value_handle_t default_value, - mach_voucher_attr_key_t *new_key, - ipc_voucher_attr_control_t *new_attr_control -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t host_register_well_known_mach_voucher_attr_manager -( - host_t host, - mach_voucher_attr_manager_t attr_manager, - mach_voucher_attr_value_handle_t default_value, - mach_voucher_attr_key_t key, - ipc_voucher_attr_control_t *new_attr_control -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t host_set_atm_diagnostic_flag -( - host_priv_t host_priv, - uint32_t diagnostic_flag -); - - - - - -extern - -__attribute__((availability(watchos,unavailable))) -__attribute__((availability(tvos,unavailable))) -kern_return_t host_get_atm_diagnostic_flag -( - host_t host, - uint32_t *diagnostic_flag -); - - - - - -extern - -kern_return_t mach_memory_info -( - host_priv_t host, - mach_zone_name_array_t *names, - mach_msg_type_number_t *namesCnt, - mach_zone_info_array_t *info, - mach_msg_type_number_t *infoCnt, - mach_memory_info_array_t *memory_info, - mach_msg_type_number_t *memory_infoCnt -); - -} -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - host_flavor_t flavor; - mach_msg_type_number_t host_info_outCnt; - } __Request__host_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_kernel_version_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request___host_page_size_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t pager; - - NDR_record_t NDR; - boolean_t internal; - vm_size_t size; - vm_prot_t permission; - } __Request__mach_memory_object_memory_entry_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - processor_flavor_t flavor; - } __Request__host_processor_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_get_io_master_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - clock_id_t clock_id; - } __Request__host_get_clock_service_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__kmod_get_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_zone_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_virtual_physical_table_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__processor_set_default_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__processor_set_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t pager; - - NDR_record_t NDR; - boolean_t internal; - memory_object_size_t size; - vm_prot_t permission; - } __Request__mach_memory_object_memory_entry_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - host_flavor_t flavor; - mach_msg_type_number_t host_info_outCnt; - } __Request__host_statistics_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t notify_port; - - NDR_record_t NDR; - host_flavor_t notify_type; - } __Request__host_request_notification_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_lockgroup_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - host_flavor_t flavor; - mach_msg_type_number_t host_info64_outCnt; - } __Request__host_statistics64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__mach_zone_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_msg_type_number_t recipesCnt; - uint8_t recipes[5120]; - } __Request__host_create_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t attr_manager; - - NDR_record_t NDR; - mach_voucher_attr_value_handle_t default_value; - } __Request__host_register_mach_voucher_attr_manager_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t attr_manager; - - NDR_record_t NDR; - mach_voucher_attr_value_handle_t default_value; - mach_voucher_attr_key_t key; - } __Request__host_register_well_known_mach_voucher_attr_manager_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - uint32_t diagnostic_flag; - } __Request__host_set_atm_diagnostic_flag_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__host_get_atm_diagnostic_flag_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - } __Request__mach_memory_info_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __RequestUnion__mach_host_subsystem { - __Request__host_info_t Request_host_info; - __Request__host_kernel_version_t Request_host_kernel_version; - __Request___host_page_size_t Request__host_page_size; - __Request__mach_memory_object_memory_entry_t Request_mach_memory_object_memory_entry; - __Request__host_processor_info_t Request_host_processor_info; - __Request__host_get_io_master_t Request_host_get_io_master; - __Request__host_get_clock_service_t Request_host_get_clock_service; - __Request__kmod_get_info_t Request_kmod_get_info; - __Request__host_zone_info_t Request_host_zone_info; - __Request__host_virtual_physical_table_info_t Request_host_virtual_physical_table_info; - __Request__processor_set_default_t Request_processor_set_default; - __Request__processor_set_create_t Request_processor_set_create; - __Request__mach_memory_object_memory_entry_64_t Request_mach_memory_object_memory_entry_64; - __Request__host_statistics_t Request_host_statistics; - __Request__host_request_notification_t Request_host_request_notification; - __Request__host_lockgroup_info_t Request_host_lockgroup_info; - __Request__host_statistics64_t Request_host_statistics64; - __Request__mach_zone_info_t Request_mach_zone_info; - __Request__host_create_mach_voucher_t Request_host_create_mach_voucher; - __Request__host_register_mach_voucher_attr_manager_t Request_host_register_mach_voucher_attr_manager; - __Request__host_register_well_known_mach_voucher_attr_manager_t Request_host_register_well_known_mach_voucher_attr_manager; - __Request__host_set_atm_diagnostic_flag_t Request_host_set_atm_diagnostic_flag; - __Request__host_get_atm_diagnostic_flag_t Request_host_get_atm_diagnostic_flag; - __Request__mach_memory_info_t Request_mach_memory_info; -}; - - - - - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t host_info_outCnt; - integer_t host_info_out[68]; - } __Reply__host_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t kernel_versionOffset; - mach_msg_type_number_t kernel_versionCnt; - char kernel_version[512]; - } __Reply__host_kernel_version_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - vm_size_t out_page_size; - } __Reply___host_page_size_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t entry_handle; - - } __Reply__mach_memory_object_memory_entry_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t out_processor_info; - - NDR_record_t NDR; - natural_t out_processor_count; - mach_msg_type_number_t out_processor_infoCnt; - } __Reply__host_processor_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t io_master; - - } __Reply__host_get_io_master_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t clock_serv; - - } __Reply__host_get_clock_service_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t modules; - - NDR_record_t NDR; - mach_msg_type_number_t modulesCnt; - } __Reply__kmod_get_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t names; - mach_msg_ool_descriptor_t info; - - NDR_record_t NDR; - mach_msg_type_number_t namesCnt; - mach_msg_type_number_t infoCnt; - } __Reply__host_zone_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t info; - - NDR_record_t NDR; - mach_msg_type_number_t infoCnt; - } __Reply__host_virtual_physical_table_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t default_set; - - } __Reply__processor_set_default_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_set; - mach_msg_port_descriptor_t new_name; - - } __Reply__processor_set_create_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t entry_handle; - - } __Reply__mach_memory_object_memory_entry_64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t host_info_outCnt; - integer_t host_info_out[68]; - } __Reply__host_statistics_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__host_request_notification_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t lockgroup_info; - - NDR_record_t NDR; - mach_msg_type_number_t lockgroup_infoCnt; - } __Reply__host_lockgroup_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_msg_type_number_t host_info64_outCnt; - integer_t host_info64_out[256]; - } __Reply__host_statistics64_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t names; - mach_msg_ool_descriptor_t info; - - NDR_record_t NDR; - mach_msg_type_number_t namesCnt; - mach_msg_type_number_t infoCnt; - } __Reply__mach_zone_info_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t voucher; - - } __Reply__host_create_mach_voucher_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_attr_control; - - NDR_record_t NDR; - mach_voucher_attr_key_t new_key; - } __Reply__host_register_mach_voucher_attr_manager_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t new_attr_control; - - } __Reply__host_register_well_known_mach_voucher_attr_manager_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__host_set_atm_diagnostic_flag_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - uint32_t diagnostic_flag; - } __Reply__host_get_atm_diagnostic_flag_t __attribute__((unused)); - -#pragma pack() - - - -#pragma pack(4) - - typedef struct { - mach_msg_header_t Head; - - mach_msg_body_t msgh_body; - mach_msg_ool_descriptor_t names; - mach_msg_ool_descriptor_t info; - mach_msg_ool_descriptor_t memory_info; - - NDR_record_t NDR; - mach_msg_type_number_t namesCnt; - mach_msg_type_number_t infoCnt; - mach_msg_type_number_t memory_infoCnt; - } __Reply__mach_memory_info_t __attribute__((unused)); - -#pragma pack() - - - - - - - -union __ReplyUnion__mach_host_subsystem { - __Reply__host_info_t Reply_host_info; - __Reply__host_kernel_version_t Reply_host_kernel_version; - __Reply___host_page_size_t Reply__host_page_size; - __Reply__mach_memory_object_memory_entry_t Reply_mach_memory_object_memory_entry; - __Reply__host_processor_info_t Reply_host_processor_info; - __Reply__host_get_io_master_t Reply_host_get_io_master; - __Reply__host_get_clock_service_t Reply_host_get_clock_service; - __Reply__kmod_get_info_t Reply_kmod_get_info; - __Reply__host_zone_info_t Reply_host_zone_info; - __Reply__host_virtual_physical_table_info_t Reply_host_virtual_physical_table_info; - __Reply__processor_set_default_t Reply_processor_set_default; - __Reply__processor_set_create_t Reply_processor_set_create; - __Reply__mach_memory_object_memory_entry_64_t Reply_mach_memory_object_memory_entry_64; - __Reply__host_statistics_t Reply_host_statistics; - __Reply__host_request_notification_t Reply_host_request_notification; - __Reply__host_lockgroup_info_t Reply_host_lockgroup_info; - __Reply__host_statistics64_t Reply_host_statistics64; - __Reply__mach_zone_info_t Reply_mach_zone_info; - __Reply__host_create_mach_voucher_t Reply_host_create_mach_voucher; - __Reply__host_register_mach_voucher_attr_manager_t Reply_host_register_mach_voucher_attr_manager; - __Reply__host_register_well_known_mach_voucher_attr_manager_t Reply_host_register_well_known_mach_voucher_attr_manager; - __Reply__host_set_atm_diagnostic_flag_t Reply_host_set_atm_diagnostic_flag; - __Reply__host_get_atm_diagnostic_flag_t Reply_host_get_atm_diagnostic_flag; - __Reply__mach_memory_info_t Reply_mach_memory_info; -}; - -typedef unsigned int routine_arg_type; -typedef unsigned int routine_arg_offset; -typedef unsigned int routine_arg_size; - - - - -struct rpc_routine_arg_descriptor { - routine_arg_type type; - routine_arg_size size; - routine_arg_size count; - routine_arg_offset offset; -}; -typedef struct rpc_routine_arg_descriptor *rpc_routine_arg_descriptor_t; - -struct rpc_routine_descriptor { - mig_impl_routine_t impl_routine; - mig_stub_routine_t stub_routine; - unsigned int argc; - unsigned int descr_count; - - rpc_routine_arg_descriptor_t - arg_descr; - - unsigned int max_reply_msg; -}; -typedef struct rpc_routine_descriptor *rpc_routine_descriptor_t; - - - - -struct rpc_signature { - struct rpc_routine_descriptor rd; - struct rpc_routine_arg_descriptor rad[1]; -}; -struct rpc_subsystem { - void *reserved; - - mach_msg_id_t start; - mach_msg_id_t end; - unsigned int maxsize; - vm_address_t base_addr; - - struct rpc_routine_descriptor - routine[1 - ]; - - struct rpc_routine_arg_descriptor - arg_descriptor[1 - ]; -}; -typedef struct rpc_subsystem *rpc_subsystem_t; - - - -extern "C" { -char *mach_error_string( - - - - mach_error_t error_value - ); - -void mach_error( - - - - const char *str, - mach_error_t error_value - ); - -char *mach_error_type( - - - - mach_error_t error_value - ); -} - - - -extern "C" { - - - -extern void panic_init(mach_port_t); -extern void panic(const char *, ...); - -extern void safe_gets(char *, - char *, - int); - -extern void slot_name(cpu_type_t, - cpu_subtype_t, - char **, - char **); - -extern void mig_reply_setup(mach_msg_header_t *, - mach_msg_header_t *); - -__attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) -extern void mach_msg_destroy(mach_msg_header_t *); - -__attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) -extern mach_msg_return_t mach_msg_receive(mach_msg_header_t *); - -__attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) -extern mach_msg_return_t mach_msg_send(mach_msg_header_t *); - -__attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) -extern mach_msg_return_t mach_msg_server_once(boolean_t (*) - (mach_msg_header_t *, - mach_msg_header_t *), - mach_msg_size_t, - mach_port_t, - mach_msg_options_t); - -__attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) -extern mach_msg_return_t mach_msg_server(boolean_t (*) - (mach_msg_header_t *, - mach_msg_header_t *), - mach_msg_size_t, - mach_port_t, - mach_msg_options_t); - -__attribute__((availability(watchos,unavailable))) __attribute__((availability(tvos,unavailable))) -extern mach_msg_return_t mach_msg_server_importance(boolean_t (*) - (mach_msg_header_t *, - mach_msg_header_t *), - mach_msg_size_t, - mach_port_t, - mach_msg_options_t); - - - -extern kern_return_t clock_get_res(mach_port_t, - clock_res_t *); -extern kern_return_t clock_set_res(mach_port_t, - clock_res_t); - -extern kern_return_t clock_sleep(mach_port_t, - int, - mach_timespec_t, - mach_timespec_t *); -typedef struct voucher_mach_msg_state_s *voucher_mach_msg_state_t; -extern boolean_t voucher_mach_msg_set(mach_msg_header_t *msg); -extern void voucher_mach_msg_clear(mach_msg_header_t *msg); -extern voucher_mach_msg_state_t voucher_mach_msg_adopt(mach_msg_header_t *msg); -extern void voucher_mach_msg_revert(voucher_mach_msg_state_t state); - -} - - - -extern "C" { -__attribute__((availability(macosx,introduced=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) __attribute__((__nonnull__(3))) -int -launch_activate_socket(const char *name, int **fds, size_t *cnt); - -typedef struct _launch_data *launch_data_t; -typedef void (*launch_data_dict_iterator_t)(const launch_data_t lval, - const char *key, void *ctx); - -typedef enum { - LAUNCH_DATA_DICTIONARY = 1, - LAUNCH_DATA_ARRAY, - LAUNCH_DATA_FD, - LAUNCH_DATA_INTEGER, - LAUNCH_DATA_REAL, - LAUNCH_DATA_BOOL, - LAUNCH_DATA_STRING, - LAUNCH_DATA_OPAQUE, - LAUNCH_DATA_ERRNO, - LAUNCH_DATA_MACHPORT, -} launch_data_type_t; - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) -launch_data_t -launch_data_alloc(launch_data_type_t type); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -launch_data_t -launch_data_copy(launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -launch_data_type_t -launch_data_get_type(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -launch_data_free(launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) __attribute__((__nonnull__(3))) -bool -launch_data_dict_insert(launch_data_t ldict, const launch_data_t lval, - const char *key); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -launch_data_t -launch_data_dict_lookup(const launch_data_t ldict, const char *key); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -bool -launch_data_dict_remove(launch_data_t ldict, const char *key); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -launch_data_dict_iterate(const launch_data_t ldict, - launch_data_dict_iterator_t iterator, void *ctx); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -size_t -launch_data_dict_get_count(const launch_data_t ldict); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -bool -launch_data_array_set_index(launch_data_t larray, const launch_data_t lval, - size_t idx); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -launch_data_t -launch_data_array_get_index(const launch_data_t larray, size_t idx); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -size_t -launch_data_array_get_count(const launch_data_t larray); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) -launch_data_t -launch_data_new_fd(int fd); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) -launch_data_t -launch_data_new_machport(mach_port_t val); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) -launch_data_t -launch_data_new_integer(long long val); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) -launch_data_t -launch_data_new_bool(bool val); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) -launch_data_t -launch_data_new_real(double val); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) -launch_data_t -launch_data_new_string(const char *val); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) -launch_data_t -launch_data_new_opaque(const void *bytes, size_t sz); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -bool -launch_data_set_fd(launch_data_t ld, int fd); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -bool -launch_data_set_machport(launch_data_t ld, mach_port_t mp); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -bool -launch_data_set_integer(launch_data_t ld, long long val); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -bool -launch_data_set_bool(launch_data_t ld, bool val); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -bool -launch_data_set_real(launch_data_t ld, double val); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -bool -launch_data_set_string(launch_data_t ld, const char *val); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -bool -launch_data_set_opaque(launch_data_t ld, const void *bytes, size_t sz); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -int -launch_data_get_fd(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -mach_port_t -launch_data_get_machport(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -long long -launch_data_get_integer(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -bool -launch_data_get_bool(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -double -launch_data_get_real(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -const char * -launch_data_get_string(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -void * -launch_data_get_opaque(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -size_t -launch_data_get_opaque_size(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -int -launch_data_get_errno(const launch_data_t ld); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) -int -launch_get_fd(void); - -__attribute__((availability(macosx,introduced=10.4,deprecated=10.10))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -launch_data_t -launch_msg(const launch_data_t request); - -} -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -xpc_object_t -xpc_retain(xpc_object_t object); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_release(xpc_object_t object); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) -xpc_type_t -xpc_get_type(xpc_object_t object); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__warn_unused_result__)) __attribute__((__ns_returns_retained__)) -xpc_object_t -xpc_copy(xpc_object_t object); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) __attribute__((__warn_unused_result__)) -bool -xpc_equal(xpc_object_t object1, xpc_object_t object2); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__warn_unused_result__)) -size_t -xpc_hash(xpc_object_t object); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -char * -xpc_copy_description(xpc_object_t object); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_null_create(void); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_bool_create(bool value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -bool -xpc_bool_get_value(xpc_object_t xbool); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_int64_create(int64_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -int64_t -xpc_int64_get_value(xpc_object_t xint); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_uint64_create(uint64_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -uint64_t -xpc_uint64_get_value(xpc_object_t xuint); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_double_create(double value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -double -xpc_double_get_value(xpc_object_t xdouble); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_date_create(int64_t interval); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_date_create_from_current(void); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -int64_t -xpc_date_get_value(xpc_object_t xdate); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_data_create(const void *bytes, size_t length); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -xpc_object_t -xpc_data_create_with_dispatch_data(dispatch_data_t ddata); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -size_t -xpc_data_get_length(xpc_object_t xdata); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -const void * -xpc_data_get_bytes_ptr(xpc_object_t xdata); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -size_t -xpc_data_get_bytes(xpc_object_t xdata, - void *buffer, size_t off, size_t length); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -xpc_object_t -xpc_string_create(const char *string); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -__attribute__((format(printf, 1, 2))) -xpc_object_t -xpc_string_create_with_format(const char *fmt, ...); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -__attribute__((format(printf, 1, 0))) -xpc_object_t -xpc_string_create_with_format_and_arguments(const char *fmt, va_list ap); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -size_t -xpc_string_get_length(xpc_object_t xstring); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -const char * -xpc_string_get_string_ptr(xpc_object_t xstring); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_uuid_create(const uuid_t uuid); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -const uint8_t * -xpc_uuid_get_bytes(xpc_object_t xuuid); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_fd_create(int fd); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -int -xpc_fd_dup(xpc_object_t xfd); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -xpc_object_t -xpc_shmem_create(void *region, size_t length); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -size_t -xpc_shmem_map(xpc_object_t xshmem, void **region); -typedef bool (*xpc_array_applier_t)(size_t index, xpc_object_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_array_create(const xpc_object_t *objects, size_t count); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) -void -xpc_array_set_value(xpc_object_t xarray, size_t index, xpc_object_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_array_append_value(xpc_object_t xarray, xpc_object_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -size_t -xpc_array_get_count(xpc_object_t xarray); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) -xpc_object_t -xpc_array_get_value(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) -bool -xpc_array_apply(xpc_object_t xarray, xpc_array_applier_t applier); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_array_set_bool(xpc_object_t xarray, size_t index, bool value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_array_set_int64(xpc_object_t xarray, size_t index, int64_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_array_set_uint64(xpc_object_t xarray, size_t index, uint64_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_array_set_double(xpc_object_t xarray, size_t index, double value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_array_set_date(xpc_object_t xarray, size_t index, int64_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) -void -xpc_array_set_data(xpc_object_t xarray, size_t index, const void *bytes, - size_t length); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) -void -xpc_array_set_string(xpc_object_t xarray, size_t index, const char *string); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_array_set_uuid(xpc_object_t xarray, size_t index, const uuid_t uuid); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_array_set_fd(xpc_object_t xarray, size_t index, int fd); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) -void -xpc_array_set_connection(xpc_object_t xarray, size_t index, - xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -bool -xpc_array_get_bool(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -int64_t -xpc_array_get_int64(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -uint64_t -xpc_array_get_uint64(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -double -xpc_array_get_double(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -int64_t -xpc_array_get_date(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -const void * -xpc_array_get_data(xpc_object_t xarray, size_t index, size_t *length); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -const char * -xpc_array_get_string(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -const uint8_t * -xpc_array_get_uuid(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -int -xpc_array_dup_fd(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -xpc_connection_t -xpc_array_create_connection(xpc_object_t xarray, size_t index); -__attribute__((availability(macosx,introduced=10.11))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -xpc_object_t -xpc_array_get_dictionary(xpc_object_t self, size_t index); -__attribute__((availability(macosx,introduced=10.11))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -xpc_object_t -xpc_array_get_array(xpc_object_t self, size_t index); -typedef bool (*xpc_dictionary_applier_t)(const char *key, xpc_object_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) -xpc_object_t -xpc_dictionary_create(const char * const *keys, const xpc_object_t *values, - size_t count); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -xpc_object_t -xpc_dictionary_create_reply(xpc_object_t original); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_value(xpc_object_t xdict, const char *key, - xpc_object_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -xpc_object_t -xpc_dictionary_get_value(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -size_t -xpc_dictionary_get_count(xpc_object_t xdict); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__)) -bool -xpc_dictionary_apply(xpc_object_t xdict, xpc_dictionary_applier_t applier); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -xpc_connection_t -xpc_dictionary_get_remote_connection(xpc_object_t xdict); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_bool(xpc_object_t xdict, const char *key, bool value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_int64(xpc_object_t xdict, const char *key, int64_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_uint64(xpc_object_t xdict, const char *key, uint64_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_double(xpc_object_t xdict, const char *key, double value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_date(xpc_object_t xdict, const char *key, int64_t value); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_data(xpc_object_t xdict, const char *key, const void *bytes, - size_t length); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_string(xpc_object_t xdict, const char *key, - const char *string); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_uuid(xpc_object_t xdict, const char *key, const uuid_t uuid); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_fd(xpc_object_t xdict, const char *key, int fd); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -void -xpc_dictionary_set_connection(xpc_object_t xdict, const char *key, - xpc_connection_t connection); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -bool -xpc_dictionary_get_bool(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -int64_t -xpc_dictionary_get_int64(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -uint64_t -xpc_dictionary_get_uint64(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -double -xpc_dictionary_get_double(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -int64_t -xpc_dictionary_get_date(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) -const void * -xpc_dictionary_get_data(xpc_object_t xdict, const char *key, size_t *length); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -const char * -xpc_dictionary_get_string(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(2))) -const uint8_t * -xpc_dictionary_get_uuid(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -int -xpc_dictionary_dup_fd(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__malloc__)) __attribute__((__ns_returns_retained__)) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -xpc_connection_t -xpc_dictionary_create_connection(xpc_object_t xdict, const char *key); -__attribute__((availability(macosx,introduced=10.11))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -xpc_object_t -xpc_dictionary_get_dictionary(xpc_object_t self, const char *key); -__attribute__((availability(macosx,introduced=10.11))) -extern __attribute__((visibility("default"))) __attribute__((__warn_unused_result__)) __attribute__((__nonnull__)) -xpc_object_t -xpc_dictionary_get_array(xpc_object_t self, const char *key); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__noreturn__)) __attribute__((__nonnull__(1))) -void -xpc_main(xpc_connection_handler_t handler); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -void -xpc_transaction_begin(void); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) -void -xpc_transaction_end(void); -__attribute__((availability(macosx,introduced=10.7))) -extern __attribute__((visibility("default"))) __attribute__((__nonnull__(1))) __attribute__((__nonnull__(3))) -void -xpc_set_event_stream_handler(const char *stream, dispatch_queue_t targetq, - xpc_handler_t handler); - - -} - -extern "C" { - - - - -typedef struct __attribute__((objc_bridge(id))) __IOSurface *IOSurfaceRef; - -typedef uint32_t IOSurfaceID; - - - - - - -extern const CFStringRef kIOSurfaceAllocSize __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfaceWidth __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfaceHeight __attribute__((availability(macosx,introduced=10.6))); - - - - -extern const CFStringRef kIOSurfaceBytesPerRow __attribute__((availability(macosx,introduced=10.6))); - - - - -extern const CFStringRef kIOSurfaceBytesPerElement __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfaceElementWidth __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfaceElementHeight __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfaceOffset __attribute__((availability(macosx,introduced=10.6))); - - - - -extern const CFStringRef kIOSurfacePlaneInfo __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfacePlaneWidth __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfacePlaneHeight __attribute__((availability(macosx,introduced=10.6))); - - - - -extern const CFStringRef kIOSurfacePlaneBytesPerRow __attribute__((availability(macosx,introduced=10.6))); - - - -extern const CFStringRef kIOSurfacePlaneOffset __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfacePlaneSize __attribute__((availability(macosx,introduced=10.6))); - - - - -extern const CFStringRef kIOSurfacePlaneBase __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfacePlaneBytesPerElement __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfacePlaneElementWidth __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfacePlaneElementHeight __attribute__((availability(macosx,introduced=10.6))); - - - - -extern const CFStringRef kIOSurfaceCacheMode __attribute__((availability(macosx,introduced=10.6))); - - -extern const CFStringRef kIOSurfaceIsGlobal __attribute__((availability(macosx,introduced=10.6,deprecated=10.11))); - - -extern const CFStringRef kIOSurfacePixelFormat __attribute__((availability(macosx,introduced=10.6))); - -CFTypeID IOSurfaceGetTypeID(void) - __attribute__((availability(macosx,introduced=10.6))); - - -IOSurfaceRef _Nullable IOSurfaceCreate(CFDictionaryRef properties) - __attribute__((availability(macosx,introduced=10.6))); - - - - - - -IOSurfaceRef _Nullable IOSurfaceLookup(IOSurfaceID csid) __attribute__((cf_returns_retained)) - __attribute__((availability(macosx,introduced=10.6))); - - -IOSurfaceID IOSurfaceGetID(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -typedef uint32_t IOSurfaceLockOptions; enum -{ - - - - kIOSurfaceLockReadOnly = 0x00000001, - - - - - kIOSurfaceLockAvoidSync = 0x00000002 -}; -IOReturn IOSurfaceLock(IOSurfaceRef buffer, IOSurfaceLockOptions options, uint32_t * _Nullable seed) - __attribute__((availability(macosx,introduced=10.6))); -IOReturn IOSurfaceUnlock(IOSurfaceRef buffer, IOSurfaceLockOptions options, uint32_t * _Nullable seed) - __attribute__((availability(macosx,introduced=10.6))); - - -size_t IOSurfaceGetAllocSize(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetWidth(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetHeight(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetBytesPerElement(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetBytesPerRow(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -void *IOSurfaceGetBaseAddress(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetElementWidth(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetElementHeight(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -OSType IOSurfaceGetPixelFormat(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - - - -uint32_t IOSurfaceGetSeed(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - - -size_t IOSurfaceGetPlaneCount(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); -size_t IOSurfaceGetWidthOfPlane(IOSurfaceRef buffer, size_t planeIndex) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetHeightOfPlane(IOSurfaceRef buffer, size_t planeIndex) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetBytesPerElementOfPlane(IOSurfaceRef buffer, size_t planeIndex) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetBytesPerRowOfPlane(IOSurfaceRef buffer, size_t planeIndex) - __attribute__((availability(macosx,introduced=10.6))); - -void *IOSurfaceGetBaseAddressOfPlane(IOSurfaceRef buffer, size_t planeIndex) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetElementWidthOfPlane(IOSurfaceRef buffer, size_t planeIndex) - __attribute__((availability(macosx,introduced=10.6))); - -size_t IOSurfaceGetElementHeightOfPlane(IOSurfaceRef buffer, size_t planeIndex) - __attribute__((availability(macosx,introduced=10.6))); - - - - -void IOSurfaceSetValue(IOSurfaceRef buffer, CFStringRef key, CFTypeRef value) - __attribute__((availability(macosx,introduced=10.6))); - -CFTypeRef _Nullable IOSurfaceCopyValue(IOSurfaceRef buffer, CFStringRef key) - __attribute__((availability(macosx,introduced=10.6))); - -void IOSurfaceRemoveValue(IOSurfaceRef buffer, CFStringRef key) - __attribute__((availability(macosx,introduced=10.6))); - - - -void IOSurfaceSetValues(IOSurfaceRef buffer, CFDictionaryRef keysAndValues) - __attribute__((availability(macosx,introduced=10.6))); - -CFDictionaryRef _Nullable IOSurfaceCopyAllValues(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -void IOSurfaceRemoveAllValues(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - - - - - - -mach_port_t IOSurfaceCreateMachPort(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - - - -IOSurfaceRef _Nullable IOSurfaceLookupFromMachPort(mach_port_t port) __attribute__((cf_returns_retained)) - __attribute__((availability(macosx,introduced=10.6))); - - - - -xpc_object_t IOSurfaceCreateXPCObject(IOSurfaceRef aSurface) __attribute__((__ns_returns_retained__)) - __attribute__((availability(macosx,introduced=10.7))); - - -IOSurfaceRef _Nullable IOSurfaceLookupFromXPCObject(xpc_object_t xobj) __attribute__((cf_returns_retained)) - __attribute__((availability(macosx,introduced=10.7))); -size_t IOSurfaceGetPropertyMaximum(CFStringRef property) - __attribute__((availability(macosx,introduced=10.6))); -size_t IOSurfaceGetPropertyAlignment(CFStringRef property) - __attribute__((availability(macosx,introduced=10.6))); - - - -size_t IOSurfaceAlignProperty(CFStringRef property, size_t value) - __attribute__((availability(macosx,introduced=10.6))); -void IOSurfaceIncrementUseCount(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - - -void IOSurfaceDecrementUseCount(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - - -int32_t IOSurfaceGetUseCount(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - - -Boolean IOSurfaceIsInUse(IOSurfaceRef buffer) - __attribute__((availability(macosx,introduced=10.6))); - -} -typedef struct CGDisplayStream *CGDisplayStreamRef; -typedef const struct CGDisplayStreamUpdate *CGDisplayStreamUpdateRef; -typedef int32_t CGDisplayStreamUpdateRectType; enum { - kCGDisplayStreamUpdateRefreshedRects, - kCGDisplayStreamUpdateMovedRects, - kCGDisplayStreamUpdateDirtyRects, - kCGDisplayStreamUpdateReducedDirtyRects, -}; -typedef int32_t CGDisplayStreamFrameStatus; enum{ - kCGDisplayStreamFrameStatusFrameComplete, - kCGDisplayStreamFrameStatusFrameIdle, - kCGDisplayStreamFrameStatusFrameBlank, - kCGDisplayStreamFrameStatusStopped, -}; -typedef void (*CGDisplayStreamFrameAvailableHandler)(CGDisplayStreamFrameStatus status, uint64_t displayTime, - IOSurfaceRef _Nullable frameSurface, - CGDisplayStreamUpdateRef _Nullable updateRef); - - - - - - -extern "C" CFTypeID CGDisplayStreamUpdateGetTypeID(void) - __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CGRect * _Nullable CGDisplayStreamUpdateGetRects(CGDisplayStreamUpdateRef _Nullable updateRef, - CGDisplayStreamUpdateRectType rectType, size_t * rectCount) - __attribute__((availability(macosx,introduced=10.8))); -extern "C" CGDisplayStreamUpdateRef _Nullable CGDisplayStreamUpdateCreateMergedUpdate( - CGDisplayStreamUpdateRef _Nullable firstUpdate, - CGDisplayStreamUpdateRef _Nullable secondUpdate) - __attribute__((availability(macosx,introduced=10.8))); -extern "C" void CGDisplayStreamUpdateGetMovedRectsDelta(CGDisplayStreamUpdateRef _Nullable updateRef, - CGFloat * dx, CGFloat * dy) - __attribute__((availability(macosx,introduced=10.8))); -extern "C" size_t CGDisplayStreamUpdateGetDropCount(CGDisplayStreamUpdateRef _Nullable updateRef) - __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGDisplayStreamSourceRect __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGDisplayStreamDestinationRect __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGDisplayStreamPreserveAspectRatio __attribute__((availability(macosx,introduced=10.8))); - - - - - -extern "C" const CFStringRef kCGDisplayStreamColorSpace __attribute__((availability(macosx,introduced=10.8))); - - - - - -extern "C" const CFStringRef kCGDisplayStreamMinimumFrameTime __attribute__((availability(macosx,introduced=10.8))); - - - - - -extern "C" const CFStringRef kCGDisplayStreamShowCursor __attribute__((availability(macosx,introduced=10.8))); - - - - - -extern "C" const CFStringRef kCGDisplayStreamQueueDepth __attribute__((availability(macosx,introduced=10.8))); - - - - - - -extern "C" const CFStringRef kCGDisplayStreamYCbCrMatrix __attribute__((availability(macosx,introduced=10.8))); - - -extern "C" const CFStringRef kCGDisplayStreamYCbCrMatrix_ITU_R_709_2 __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGDisplayStreamYCbCrMatrix_ITU_R_601_4 __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGDisplayStreamYCbCrMatrix_SMPTE_240M_1995 __attribute__((availability(macosx,introduced=10.8))); - - - - - - -extern "C" CFTypeID CGDisplayStreamGetTypeID(void) - __attribute__((availability(macosx,introduced=10.8))); -extern "C" CGDisplayStreamRef _Nullable CGDisplayStreamCreate(CGDirectDisplayID display, - size_t outputWidth, size_t outputHeight, int32_t pixelFormat, CFDictionaryRef _Nullable properties, - CGDisplayStreamFrameAvailableHandler _Nullable handler) - __attribute__((availability(macosx,introduced=10.8))); -extern "C" CGDisplayStreamRef _Nullable CGDisplayStreamCreateWithDispatchQueue(CGDirectDisplayID display, - size_t outputWidth, size_t outputHeight, int32_t pixelFormat, CFDictionaryRef _Nullable properties, - dispatch_queue_t queue, CGDisplayStreamFrameAvailableHandler _Nullable handler) - __attribute__((availability(macosx,introduced=10.8))); - - - - - - - -extern "C" CGError CGDisplayStreamStart(CGDisplayStreamRef _Nullable displayStream) - __attribute__((availability(macosx,introduced=10.8))); -extern "C" CGError CGDisplayStreamStop(CGDisplayStreamRef _Nullable displayStream) - __attribute__((availability(macosx,introduced=10.8))); -extern "C" CFRunLoopSourceRef _Nullable CGDisplayStreamGetRunLoopSource(CGDisplayStreamRef _Nullable displayStream) - __attribute__((availability(macosx,introduced=10.8))); -typedef CGError CGEventErr; - - - - - - -typedef uint32_t CGButtonCount; - - - - -typedef uint32_t CGWheelCount; - - - - -typedef uint16_t CGCharCode; - - - -typedef uint16_t CGKeyCode; -typedef void (*CGScreenRefreshCallback)(uint32_t count, - const CGRect * rects, - void *_Nullable userInfo); -extern "C" CGError CGRegisterScreenRefreshCallback( - CGScreenRefreshCallback callback, void * _Nullable userInfo) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern "C" void CGUnregisterScreenRefreshCallback( - CGScreenRefreshCallback callback, void * _Nullable userInfo) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern "C" CGError CGWaitForScreenRefreshRects( - CGRect *_Nullable * _Nullable rects, uint32_t * _Nullable count) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - -typedef uint32_t CGScreenUpdateOperation; enum { - kCGScreenUpdateOperationRefresh = 0, - kCGScreenUpdateOperationMove = (1u << 0), - kCGScreenUpdateOperationReducedDirtyRectangleCount = (1u << 31) -}; -struct CGScreenUpdateMoveDelta { - int32_t dX, dY; -}; -typedef struct CGScreenUpdateMoveDelta CGScreenUpdateMoveDelta; -typedef void (*CGScreenUpdateMoveCallback)(CGScreenUpdateMoveDelta delta, - size_t count, const CGRect * rects, void * _Nullable userInfo); - - - - - -extern "C" CGError CGScreenRegisterMoveCallback( - CGScreenUpdateMoveCallback callback, void * _Nullable userInfo) - __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); - - - - -extern "C" void CGScreenUnregisterMoveCallback( - CGScreenUpdateMoveCallback callback, void * _Nullable userInfo) - __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); -extern "C" CGError CGWaitForScreenUpdateRects( - CGScreenUpdateOperation requestedOperations, - CGScreenUpdateOperation * _Nullable currentOperation, - CGRect * _Nullable * _Nullable rects, size_t * _Nullable rectCount, - CGScreenUpdateMoveDelta * _Nullable delta) - __attribute__((availability(macosx,introduced=10.3,deprecated=10.8))); - - - - -extern "C" void CGReleaseScreenRefreshRects(CGRect * _Nullable rects) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - -extern "C" boolean_t CGCursorIsVisible(void) - __attribute__((availability(macosx,introduced=10.3,deprecated=10.9))); -extern "C" boolean_t CGCursorIsDrawnInFramebuffer(void) - __attribute__((availability(macosx,introduced=10.3,deprecated=10.9))); - - - - -extern "C" CGError CGWarpMouseCursorPosition(CGPoint newCursorPosition) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CGError CGAssociateMouseAndMouseCursorPosition(boolean_t connected) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" CFMachPortRef _Nullable CGWindowServerCreateServerPort(void) - __attribute__((availability(macosx,introduced=10.8))); - - - - -extern "C" CGError CGEnableEventStateCombining(boolean_t combineState) - __attribute__((availability(macosx,introduced=10.1,deprecated=10.6))); - - - - - -extern "C" CGError CGInhibitLocalEvents(boolean_t inhibit) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern "C" CGError CGPostMouseEvent(CGPoint mouseCursorPosition, - boolean_t updateMouseCursorPosition, CGButtonCount buttonCount, - boolean_t mouseButtonDown, ... ) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -extern "C" CGError CGPostScrollWheelEvent(CGWheelCount wheelCount, - int32_t wheel1, ... ) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - -extern "C" CGError CGPostKeyboardEvent(CGCharCode keyChar, CGKeyCode virtualKey, - boolean_t keyDown) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - -typedef uint32_t CGEventFilterMask; enum { - kCGEventFilterMaskPermitLocalMouseEvents = 0x00000001, - kCGEventFilterMaskPermitLocalKeyboardEvents = 0x00000002, - kCGEventFilterMaskPermitSystemDefinedEvents = 0x00000004 -}; -typedef uint32_t CGEventSuppressionState; enum { - kCGEventSuppressionStateSuppressionInterval = 0, - kCGEventSuppressionStateRemoteMouseDrag, - kCGNumberOfEventSuppressionStates -}; - - - - -extern "C" CGError CGSetLocalEventsFilterDuringSuppressionState( - CGEventFilterMask filter, CGEventSuppressionState state) - __attribute__((availability(macosx,introduced=10.1,deprecated=10.6))); - - - - -extern "C" CGError CGSetLocalEventsSuppressionInterval(CFTimeInterval seconds) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - - -extern "C" CFMachPortRef _Nullable CGWindowServerCFMachPort(void) __attribute__((cf_returns_retained)) - __attribute__((availability(macosx,introduced=10.1,deprecated=10.8))); -typedef uint32_t CGRectCount; -extern "C" { -__attribute__((availability(macosx,introduced=10.4))) -int32_t OSAtomicAdd32( int32_t __theAmount, volatile int32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -int32_t OSAtomicAdd32Barrier( int32_t __theAmount, volatile int32_t *__theValue ); - - - - - - - -__attribute__((availability(macosx,introduced=10.10))) -int32_t OSAtomicIncrement32( volatile int32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.10))) -int32_t OSAtomicIncrement32Barrier( volatile int32_t *__theValue ); - - - - - -__attribute__((availability(macosx,introduced=10.10))) -int32_t OSAtomicDecrement32( volatile int32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.10))) -int32_t OSAtomicDecrement32Barrier( volatile int32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -int64_t OSAtomicAdd64( int64_t __theAmount, volatile int64_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -int64_t OSAtomicAdd64Barrier( int64_t __theAmount, volatile int64_t *__theValue ); - - - - - - - -__attribute__((availability(macosx,introduced=10.10))) -int64_t OSAtomicIncrement64( volatile int64_t *__theValue ); -__attribute__((availability(macosx,introduced=10.10))) -int64_t OSAtomicIncrement64Barrier( volatile int64_t *__theValue ); - - - - - -__attribute__((availability(macosx,introduced=10.10))) -int64_t OSAtomicDecrement64( volatile int64_t *__theValue ); -__attribute__((availability(macosx,introduced=10.10))) -int64_t OSAtomicDecrement64Barrier( volatile int64_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -int32_t OSAtomicOr32( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -int32_t OSAtomicOr32Barrier( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -int32_t OSAtomicOr32Orig( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -int32_t OSAtomicOr32OrigBarrier( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -int32_t OSAtomicAnd32( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -int32_t OSAtomicAnd32Barrier( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -int32_t OSAtomicAnd32Orig( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -int32_t OSAtomicAnd32OrigBarrier( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -int32_t OSAtomicXor32( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -int32_t OSAtomicXor32Barrier( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -int32_t OSAtomicXor32Orig( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -int32_t OSAtomicXor32OrigBarrier( uint32_t __theMask, volatile uint32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -bool OSAtomicCompareAndSwap32( int32_t __oldValue, int32_t __newValue, volatile int32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -bool OSAtomicCompareAndSwap32Barrier( int32_t __oldValue, int32_t __newValue, volatile int32_t *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -bool OSAtomicCompareAndSwapPtr( void *__oldValue, void *__newValue, void * volatile *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -bool OSAtomicCompareAndSwapPtrBarrier( void *__oldValue, void *__newValue, void * volatile *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -bool OSAtomicCompareAndSwapInt( int __oldValue, int __newValue, volatile int *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -bool OSAtomicCompareAndSwapIntBarrier( int __oldValue, int __newValue, volatile int *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -bool OSAtomicCompareAndSwapLong( long __oldValue, long __newValue, volatile long *__theValue ); -__attribute__((availability(macosx,introduced=10.5))) -bool OSAtomicCompareAndSwapLongBarrier( long __oldValue, long __newValue, volatile long *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -bool OSAtomicCompareAndSwap64( int64_t __oldValue, int64_t __newValue, volatile int64_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -bool OSAtomicCompareAndSwap64Barrier( int64_t __oldValue, int64_t __newValue, volatile int64_t *__theValue ); -__attribute__((availability(macosx,introduced=10.4))) -bool OSAtomicTestAndSet( uint32_t __n, volatile void *__theAddress ); -__attribute__((availability(macosx,introduced=10.4))) -bool OSAtomicTestAndSetBarrier( uint32_t __n, volatile void *__theAddress ); -__attribute__((availability(macosx,introduced=10.4))) -bool OSAtomicTestAndClear( uint32_t __n, volatile void *__theAddress ); -__attribute__((availability(macosx,introduced=10.4))) -bool OSAtomicTestAndClearBarrier( uint32_t __n, volatile void *__theAddress ); -typedef int32_t OSSpinLock; - - - - - - - -__attribute__((availability(macosx,introduced=10.4))) -bool OSSpinLockTry( volatile OSSpinLock *__lock ); -__attribute__((availability(macosx,introduced=10.4))) -void OSSpinLockLock( volatile OSSpinLock *__lock ); - - - -__attribute__((availability(macosx,introduced=10.4))) -void OSSpinLockUnlock( volatile OSSpinLock *__lock ); -typedef volatile struct { - void *opaque1; - long opaque2; -} __attribute__ ((aligned (16))) OSQueueHead; -__attribute__((availability(macosx,introduced=10.5))) -void OSAtomicEnqueue( OSQueueHead *__list, void *__new, size_t __offset); -__attribute__((availability(macosx,introduced=10.5))) -void* OSAtomicDequeue( OSQueueHead *__list, size_t __offset); -typedef volatile struct { - void *opaque1; - void *opaque2; - int opaque3; -} __attribute__ ((aligned (16))) OSFifoQueueHead; -__attribute__((availability(macosx,introduced=10.7))) -void OSAtomicFifoEnqueue( OSFifoQueueHead *__list, void *__new, size_t __offset); -__attribute__((availability(macosx,introduced=10.7))) -void* OSAtomicFifoDequeue( OSFifoQueueHead *__list, size_t __offset); -__attribute__((availability(macosx,introduced=10.4))) -void OSMemoryBarrier( void ); - -} -extern "C" { - - - - -typedef SInt32 IOIndex; -typedef UInt32 IOSelect; -typedef UInt32 IOFixed1616; -typedef UInt32 IODisplayVendorID; -typedef UInt32 IODisplayProductID; - -typedef SInt32 IODisplayModeID; -enum { - - kIODisplayModeIDBootProgrammable = (IODisplayModeID)0xFFFFFFFB, - - kIODisplayModeIDReservedBase = (IODisplayModeID)0x80000000 -}; - -enum { - kIOMaxPixelBits = 64 -}; -typedef char IOPixelEncoding[ kIOMaxPixelBits ]; -enum { - kIOCLUTPixels = 0, - kIOFixedCLUTPixels = 1, - kIORGBDirectPixels = 2, - kIOMonoDirectPixels = 3, - kIOMonoInverseDirectPixels = 4, - kIORGBSignedDirectPixels = 5, - kIORGBSignedFloatingPointPixels = 6 -}; -struct IOPixelInformation { - UInt32 bytesPerRow; - UInt32 bytesPerPlane; - UInt32 bitsPerPixel; - UInt32 pixelType; - UInt32 componentCount; - UInt32 bitsPerComponent; - UInt32 componentMasks[ 8 * 2 ]; - IOPixelEncoding pixelFormat; - UInt32 flags; - UInt32 activeWidth; - UInt32 activeHeight; - UInt32 reserved[ 2 ]; -}; -typedef struct IOPixelInformation IOPixelInformation; - - -typedef UInt32 IOAppleTimingID; -struct IODisplayModeInformation { - UInt32 nominalWidth; - UInt32 nominalHeight; - IOFixed1616 refreshRate; - IOIndex maxDepthIndex; - UInt32 flags; - UInt16 imageWidth; - UInt16 imageHeight; - UInt32 reserved[ 3 ]; -}; -typedef struct IODisplayModeInformation IODisplayModeInformation; - - -enum { - kDisplayModeSafetyFlags = 0x00000007, - - kDisplayModeAlwaysShowFlag = 0x00000008, - kDisplayModeNeverShowFlag = 0x00000080, - kDisplayModeNotResizeFlag = 0x00000010, - kDisplayModeRequiresPanFlag = 0x00000020, - - kDisplayModeInterlacedFlag = 0x00000040, - - kDisplayModeSimulscanFlag = 0x00000100, - kDisplayModeBuiltInFlag = 0x00000400, - kDisplayModeNotPresetFlag = 0x00000200, - kDisplayModeStretchedFlag = 0x00000800, - kDisplayModeNotGraphicsQualityFlag = 0x00001000, - kDisplayModeValidateAgainstDisplay = 0x00002000, - kDisplayModeTelevisionFlag = 0x00100000, - kDisplayModeValidForMirroringFlag = 0x00200000, - kDisplayModeAcceleratorBackedFlag = 0x00400000, - kDisplayModeValidForHiResFlag = 0x00800000, - kDisplayModeValidForAirPlayFlag = 0x01000000, - kDisplayModeNativeFlag = 0x02000000 -}; -enum { - kDisplayModeValidFlag = 0x00000001, - kDisplayModeSafeFlag = 0x00000002, - kDisplayModeDefaultFlag = 0x00000004 -}; - - - - -struct IOFramebufferInformation { - IOPhysicalAddress baseAddress; - UInt32 activeWidth; - UInt32 activeHeight; - IOByteCount bytesPerRow; - IOByteCount bytesPerPlane; - UInt32 bitsPerPixel; - UInt32 pixelType; - UInt32 flags; - UInt32 reserved[ 4 ]; -}; -typedef struct IOFramebufferInformation IOFramebufferInformation; - - - -enum { - kFramebufferSupportsCopybackCache = 0x00010000, - kFramebufferSupportsWritethruCache = 0x00020000, - kFramebufferSupportsGammaCorrection = 0x00040000, - kFramebufferDisableAltivecAccess = 0x00080000 -}; - - -typedef IOIndex IOPixelAperture; -enum { - kIOFBSystemAperture = 0 -}; - - - -typedef UInt16 IOColorComponent; -struct IOColorEntry { - UInt16 index; - IOColorComponent red; - IOColorComponent green; - IOColorComponent blue; -}; -typedef struct IOColorEntry IOColorEntry; - - -enum { - kSetCLUTByValue = 0x00000001, - kSetCLUTImmediately = 0x00000002, - kSetCLUTWithLuminance = 0x00000004 -}; - - - -enum { - kIOPowerStateAttribute = 'pwrs', - kIOPowerAttribute = 'powr', - kIODriverPowerAttribute = 'dpow', - kIOHardwareCursorAttribute = 'crsr', - - kIOMirrorAttribute = 'mirr', - kIOMirrorDefaultAttribute = 'mrdf', - - kIOCapturedAttribute = 'capd', - - kIOCursorControlAttribute = 'crsc', - - kIOSystemPowerAttribute = 'spwr', - kIOWindowServerActiveAttribute = 'wsrv', - kIOVRAMSaveAttribute = 'vrsv', - kIODeferCLUTSetAttribute = 'vclt', - - kIOClamshellStateAttribute = 'clam', - - kIOFBDisplayPortTrainingAttribute = 'dpta', -}; - - -enum { - kIOMirrorIsPrimary = 0x80000000, - kIOMirrorHWClipped = 0x40000000, - kIOMirrorIsMirrored = 0x20000000 -}; - - -enum { - kIOMirrorDefault = 0x00000001, - kIOMirrorForced = 0x00000002 -}; - - - -struct IODetailedTimingInformationV1 { - - UInt32 pixelClock; - UInt32 horizontalActive; - UInt32 horizontalBlanking; - UInt32 horizontalBorder; - UInt32 horizontalSyncOffset; - UInt32 horizontalSyncWidth; - UInt32 verticalActive; - UInt32 verticalBlanking; - UInt32 verticalBorder; - UInt32 verticalSyncOffset; - UInt32 verticalSyncWidth; -}; -typedef struct IODetailedTimingInformationV1 IODetailedTimingInformationV1; -struct IODetailedTimingInformationV2 { - - UInt32 __reservedA[3]; - UInt32 horizontalScaledInset; - UInt32 verticalScaledInset; - - UInt32 scalerFlags; - UInt32 horizontalScaled; - UInt32 verticalScaled; - - UInt32 signalConfig; - UInt32 signalLevels; - - UInt64 pixelClock; - - UInt64 minPixelClock; - UInt64 maxPixelClock; - - UInt32 horizontalActive; - UInt32 horizontalBlanking; - UInt32 horizontalSyncOffset; - UInt32 horizontalSyncPulseWidth; - - UInt32 verticalActive; - UInt32 verticalBlanking; - UInt32 verticalSyncOffset; - UInt32 verticalSyncPulseWidth; - - UInt32 horizontalBorderLeft; - UInt32 horizontalBorderRight; - UInt32 verticalBorderTop; - UInt32 verticalBorderBottom; - - UInt32 horizontalSyncConfig; - UInt32 horizontalSyncLevel; - UInt32 verticalSyncConfig; - UInt32 verticalSyncLevel; - UInt32 numLinks; - - UInt32 __reservedB[7]; -}; -typedef struct IODetailedTimingInformationV2 IODetailedTimingInformationV2; -typedef struct IODetailedTimingInformationV2 IODetailedTimingInformation; - -struct IOTimingInformation { - IOAppleTimingID appleTimingID; - UInt32 flags; - union { - IODetailedTimingInformationV1 v1; - IODetailedTimingInformationV2 v2; - } detailedInfo; -}; -typedef struct IOTimingInformation IOTimingInformation; - -enum { - - kIODetailedTimingValid = 0x80000000, - kIOScalingInfoValid = 0x40000000 -}; - -enum { - - kIOScaleStretchToFit = 0x00000001, - - kIOScaleRotateFlags = 0x000000f0, - - kIOScaleSwapAxes = 0x00000010, - kIOScaleInvertX = 0x00000020, - kIOScaleInvertY = 0x00000040, - - kIOScaleRotate0 = 0x00000000, - kIOScaleRotate90 = kIOScaleSwapAxes | kIOScaleInvertX, - kIOScaleRotate180 = kIOScaleInvertX | kIOScaleInvertY, - kIOScaleRotate270 = kIOScaleSwapAxes | kIOScaleInvertY -}; - - -#pragma pack(push, 4) -struct IOFBDisplayModeDescription { - IODisplayModeInformation info; - IOTimingInformation timingInfo; -}; -typedef struct IOFBDisplayModeDescription IOFBDisplayModeDescription; -#pragma pack(pop) -struct IODisplayTimingRange -{ - UInt32 __reservedA[2]; - UInt32 version; - UInt32 __reservedB[5]; - - UInt64 minPixelClock; - UInt64 maxPixelClock; - - UInt32 maxPixelError; - UInt32 supportedSyncFlags; - UInt32 supportedSignalLevels; - UInt32 supportedSignalConfigs; - - UInt32 minFrameRate; - UInt32 maxFrameRate; - UInt32 minLineRate; - UInt32 maxLineRate; - - UInt32 maxHorizontalTotal; - UInt32 maxVerticalTotal; - UInt32 __reservedD[2]; - - UInt8 charSizeHorizontalActive; - UInt8 charSizeHorizontalBlanking; - UInt8 charSizeHorizontalSyncOffset; - UInt8 charSizeHorizontalSyncPulse; - - UInt8 charSizeVerticalActive; - UInt8 charSizeVerticalBlanking; - UInt8 charSizeVerticalSyncOffset; - UInt8 charSizeVerticalSyncPulse; - - UInt8 charSizeHorizontalBorderLeft; - UInt8 charSizeHorizontalBorderRight; - UInt8 charSizeVerticalBorderTop; - UInt8 charSizeVerticalBorderBottom; - - UInt8 charSizeHorizontalTotal; - UInt8 charSizeVerticalTotal; - UInt16 __reservedE; - - UInt32 minHorizontalActiveClocks; - UInt32 maxHorizontalActiveClocks; - UInt32 minHorizontalBlankingClocks; - UInt32 maxHorizontalBlankingClocks; - - UInt32 minHorizontalSyncOffsetClocks; - UInt32 maxHorizontalSyncOffsetClocks; - UInt32 minHorizontalPulseWidthClocks; - UInt32 maxHorizontalPulseWidthClocks; - - UInt32 minVerticalActiveClocks; - UInt32 maxVerticalActiveClocks; - UInt32 minVerticalBlankingClocks; - UInt32 maxVerticalBlankingClocks; - - UInt32 minVerticalSyncOffsetClocks; - UInt32 maxVerticalSyncOffsetClocks; - UInt32 minVerticalPulseWidthClocks; - UInt32 maxVerticalPulseWidthClocks; - - UInt32 minHorizontalBorderLeft; - UInt32 maxHorizontalBorderLeft; - UInt32 minHorizontalBorderRight; - UInt32 maxHorizontalBorderRight; - - UInt32 minVerticalBorderTop; - UInt32 maxVerticalBorderTop; - UInt32 minVerticalBorderBottom; - UInt32 maxVerticalBorderBottom; - UInt32 maxNumLinks; - UInt32 minLink0PixelClock; - UInt32 maxLink0PixelClock; - UInt32 minLink1PixelClock; - UInt32 maxLink1PixelClock; - - UInt32 __reservedF[3]; -}; -typedef struct IODisplayTimingRange IODisplayTimingRange; - -enum { - - kIORangeSupportsSignal_0700_0300 = 0x00000001, - kIORangeSupportsSignal_0714_0286 = 0x00000002, - kIORangeSupportsSignal_1000_0400 = 0x00000004, - kIORangeSupportsSignal_0700_0000 = 0x00000008 -}; -enum { - - kIORangeSupportsSeparateSyncs = 0x00000001, - kIORangeSupportsSyncOnGreen = 0x00000002, - kIORangeSupportsCompositeSync = 0x00000004, - kIORangeSupportsVSyncSerration = 0x00000008 -}; -enum { - - kIORangeSupportsInterlacedCEATiming = 0x00000004, - kIORangeSupportsInterlacedCEATimingWithConfirm = 0x00000008 -}; - -enum { - - kIODigitalSignal = 0x00000001, - kIOAnalogSetupExpected = 0x00000002, - kIOInterlacedCEATiming = 0x00000004, - kIONTSCTiming = 0x00000008, - kIOPALTiming = 0x00000010 -}; - -enum { - - kIOAnalogSignalLevel_0700_0300 = 0, - kIOAnalogSignalLevel_0714_0286 = 1, - kIOAnalogSignalLevel_1000_0400 = 2, - kIOAnalogSignalLevel_0700_0000 = 3 -}; - -enum { - - kIOSyncPositivePolarity = 0x00000001 -}; -struct IODisplayScalerInformation { - UInt32 __reservedA[1]; - UInt32 version; - UInt32 __reservedB[2]; - - IOOptionBits scalerFeatures; - UInt32 maxHorizontalPixels; - UInt32 maxVerticalPixels; - UInt32 __reservedC[5]; -}; -typedef struct IODisplayScalerInformation IODisplayScalerInformation; - -enum { - - kIOScaleStretchOnly = 0x00000001, - kIOScaleCanUpSamplePixels = 0x00000002, - kIOScaleCanDownSamplePixels = 0x00000004, - kIOScaleCanScaleInterlaced = 0x00000008, - kIOScaleCanSupportInset = 0x00000010, - kIOScaleCanRotate = 0x00000020, - kIOScaleCanBorderInsetOnly = 0x00000040 -}; - - - -enum { - kOrConnections = 0xffffffe, - kAndConnections = 0xffffffd -}; - -enum { - kConnectionFlags = 'flgs', - kConnectionSyncEnable = 'sync', - kConnectionSyncFlags = 'sycf', - kConnectionSupportsAppleSense = 'asns', - kConnectionSupportsLLDDCSense = 'lddc', - kConnectionSupportsHLDDCSense = 'hddc', - kConnectionEnable = 'enab', - kConnectionCheckEnable = 'cena', - kConnectionProbe = 'prob', - kConnectionChanged = 'chng', - kConnectionPower = 'powr', - kConnectionPostWake = 'pwak', - kConnectionDisplayParameterCount = 'pcnt', - kConnectionDisplayParameters = 'parm', - kConnectionOverscan = 'oscn', - kConnectionVideoBest = 'vbst', - - kConnectionRedGammaScale = 'rgsc', - kConnectionGreenGammaScale = 'ggsc', - kConnectionBlueGammaScale = 'bgsc', - kConnectionGammaScale = 'gsc ', - kConnectionFlushParameters = 'flus', - - kConnectionVBLMultiplier = 'vblm', - - kConnectionHandleDisplayPortEvent = 'dpir', - - kConnectionPanelTimingDisable = 'pnlt', - - kConnectionColorMode = 'cyuv', - kConnectionColorModesSupported = 'colr', - kConnectionColorDepthsSupported = ' bpc', - - kConnectionControllerDepthsSupported = '\0grd', - kConnectionControllerColorDepth = '\0dpd', - kConnectionControllerDitherControl = '\0gdc', - - kConnectionDisplayFlags = 'dflg', - - kConnectionEnableAudio = 'aud ', - kConnectionAudioStreaming = 'auds', -}; - - -enum { - kIOConnectionBuiltIn = 0x00000800, - kIOConnectionStereoSync = 0x00008000 -}; - - -enum { - kIOHSyncDisable = 0x00000001, - kIOVSyncDisable = 0x00000002, - kIOCSyncDisable = 0x00000004, - kIONoSeparateSyncControl = 0x00000040, - kIOTriStateSyncs = 0x00000080, - kIOSyncOnBlue = 0x00000008, - kIOSyncOnGreen = 0x00000010, - kIOSyncOnRed = 0x00000020 -}; - - -enum { - kIODPEventStart = 1, - kIODPEventIdle = 2, - - kIODPEventForceRetrain = 3, - - kIODPEventRemoteControlCommandPending = 256, - kIODPEventAutomatedTestRequest = 257, - kIODPEventContentProtection = 258, - kIODPEventMCCS = 259, - kIODPEventSinkSpecific = 260 -}; -enum -{ - kIODisplayColorMode = kConnectionColorMode, -}; -enum -{ - - kIODisplayRGBColorComponentBitsUnknown = 0x00000000, - kIODisplayRGBColorComponentBits6 = 0x00000001, - kIODisplayRGBColorComponentBits8 = 0x00000002, - kIODisplayRGBColorComponentBits10 = 0x00000004, - kIODisplayRGBColorComponentBits12 = 0x00000008, - kIODisplayRGBColorComponentBits14 = 0x00000010, - kIODisplayRGBColorComponentBits16 = 0x00000020, - - kIODisplayYCbCr444ColorComponentBitsUnknown = 0x00000000, - kIODisplayYCbCr444ColorComponentBits6 = 0x00000100, - kIODisplayYCbCr444ColorComponentBits8 = 0x00000200, - kIODisplayYCbCr444ColorComponentBits10 = 0x00000400, - kIODisplayYCbCr444ColorComponentBits12 = 0x00000800, - kIODisplayYCbCr444ColorComponentBits14 = 0x00001000, - kIODisplayYCbCr444ColorComponentBits16 = 0x00002000, - - kIODisplayYCbCr422ColorComponentBitsUnknown = 0x00000000, - kIODisplayYCbCr422ColorComponentBits6 = 0x00010000, - kIODisplayYCbCr422ColorComponentBits8 = 0x00020000, - kIODisplayYCbCr422ColorComponentBits10 = 0x00040000, - kIODisplayYCbCr422ColorComponentBits12 = 0x00080000, - kIODisplayYCbCr422ColorComponentBits14 = 0x00100000, - kIODisplayYCbCr422ColorComponentBits16 = 0x00200000, -}; - -enum -{ - - kIODisplayDitherDisable = 0x00000000, - kIODisplayDitherSpatial = 0x00000001, - kIODisplayDitherTemporal = 0x00000002, - kIODisplayDitherFrameRateControl = 0x00000004, - kIODisplayDitherDefault = 0x00000080, - kIODisplayDitherAll = 0x000000FF, - kIODisplayDitherRGBShift = 0, - kIODisplayDitherYCbCr444Shift = 8, - kIODisplayDitherYCbCr422Shift = 16, -}; - -enum -{ - - kIODisplayNeedsCEAUnderscan = 0x00000001, -}; - -enum -{ - kIODisplayPowerStateOff = 0, - kIODisplayPowerStateMinUsable = 1, - kIODisplayPowerStateOn = 2, -}; -enum { - - kIOFBServerConnectType = 0, - kIOFBSharedConnectType = 1 -}; - -enum { - - kIOFBUserRequestProbe = 0x00000001 -}; - -struct IOGPoint { - SInt16 x; - SInt16 y; -}; -typedef struct IOGPoint IOGPoint; - -struct IOGSize { - SInt16 width; - SInt16 height; -}; -typedef struct IOGSize IOGSize; - -struct IOGBounds { - SInt16 minx; - SInt16 maxx; - SInt16 miny; - SInt16 maxy; -}; -typedef struct IOGBounds IOGBounds; -enum { - kTransparentEncoding = 0, - kInvertingEncoding -}; - -enum { - kTransparentEncodingShift = (kTransparentEncoding << 1), - kTransparentEncodedPixel = (0x01 << kTransparentEncodingShift), - - kInvertingEncodingShift = (kInvertingEncoding << 1), - kInvertingEncodedPixel = (0x01 << kInvertingEncodingShift) -}; - -enum { - kHardwareCursorDescriptorMajorVersion = 0x0001, - kHardwareCursorDescriptorMinorVersion = 0x0000 -}; -struct IOHardwareCursorDescriptor { - UInt16 majorVersion; - UInt16 minorVersion; - UInt32 height; - UInt32 width; - UInt32 bitDepth; - UInt32 maskBitDepth; - UInt32 numColors; - UInt32 * colorEncodings; - UInt32 flags; - UInt32 supportedSpecialEncodings; - UInt32 specialEncodings[16]; -}; -typedef struct IOHardwareCursorDescriptor IOHardwareCursorDescriptor; - -enum { - kHardwareCursorInfoMajorVersion = 0x0001, - kHardwareCursorInfoMinorVersion = 0x0000 -}; -struct IOHardwareCursorInfo { - UInt16 majorVersion; - UInt16 minorVersion; - UInt32 cursorHeight; - UInt32 cursorWidth; - - IOColorEntry * colorMap; - UInt8 * hardwareCursorData; - UInt16 cursorHotSpotX; - UInt16 cursorHotSpotY; - UInt32 reserved[5]; -}; -typedef struct IOHardwareCursorInfo IOHardwareCursorInfo; - - - -enum { - kIOFBVBLInterruptType = 'vbl ', - kIOFBHBLInterruptType = 'hbl ', - kIOFBFrameInterruptType = 'fram', - - kIOFBConnectInterruptType = 'dci ', - - kIOFBChangedInterruptType = 'chng', - - kIOFBOfflineInterruptType = 'remv', - - kIOFBOnlineInterruptType = 'add ', - - kIOFBDisplayPortInterruptType = 'dpir', - - kIOFBDisplayPortLinkChangeInterruptType = 'dplk', - - kIOFBMCCSInterruptType = 'mccs', - - kIOFBWakeInterruptType = 'vwak' -}; - - -enum { - kIOTimingIDInvalid = 0, - kIOTimingIDApple_FixedRateLCD = 42, - kIOTimingIDApple_512x384_60hz = 130, - kIOTimingIDApple_560x384_60hz = 135, - kIOTimingIDApple_640x480_67hz = 140, - kIOTimingIDApple_640x400_67hz = 145, - kIOTimingIDVESA_640x480_60hz = 150, - kIOTimingIDVESA_640x480_72hz = 152, - kIOTimingIDVESA_640x480_75hz = 154, - kIOTimingIDVESA_640x480_85hz = 158, - kIOTimingIDGTF_640x480_120hz = 159, - kIOTimingIDApple_640x870_75hz = 160, - kIOTimingIDApple_640x818_75hz = 165, - kIOTimingIDApple_832x624_75hz = 170, - kIOTimingIDVESA_800x600_56hz = 180, - kIOTimingIDVESA_800x600_60hz = 182, - kIOTimingIDVESA_800x600_72hz = 184, - kIOTimingIDVESA_800x600_75hz = 186, - kIOTimingIDVESA_800x600_85hz = 188, - kIOTimingIDVESA_1024x768_60hz = 190, - kIOTimingIDVESA_1024x768_70hz = 200, - kIOTimingIDVESA_1024x768_75hz = 204, - kIOTimingIDVESA_1024x768_85hz = 208, - kIOTimingIDApple_1024x768_75hz = 210, - kIOTimingIDVESA_1152x864_75hz = 215, - kIOTimingIDApple_1152x870_75hz = 220, - kIOTimingIDAppleNTSC_ST = 230, - kIOTimingIDAppleNTSC_FF = 232, - kIOTimingIDAppleNTSC_STconv = 234, - kIOTimingIDAppleNTSC_FFconv = 236, - kIOTimingIDApplePAL_ST = 238, - kIOTimingIDApplePAL_FF = 240, - kIOTimingIDApplePAL_STconv = 242, - kIOTimingIDApplePAL_FFconv = 244, - kIOTimingIDVESA_1280x960_75hz = 250, - kIOTimingIDVESA_1280x960_60hz = 252, - kIOTimingIDVESA_1280x960_85hz = 254, - kIOTimingIDVESA_1280x1024_60hz = 260, - kIOTimingIDVESA_1280x1024_75hz = 262, - kIOTimingIDVESA_1280x1024_85hz = 268, - kIOTimingIDVESA_1600x1200_60hz = 280, - kIOTimingIDVESA_1600x1200_65hz = 282, - kIOTimingIDVESA_1600x1200_70hz = 284, - kIOTimingIDVESA_1600x1200_75hz = 286, - kIOTimingIDVESA_1600x1200_80hz = 288, - kIOTimingIDVESA_1600x1200_85hz = 289, - kIOTimingIDVESA_1792x1344_60hz = 296, - kIOTimingIDVESA_1792x1344_75hz = 298, - kIOTimingIDVESA_1856x1392_60hz = 300, - kIOTimingIDVESA_1856x1392_75hz = 302, - kIOTimingIDVESA_1920x1440_60hz = 304, - kIOTimingIDVESA_1920x1440_75hz = 306, - kIOTimingIDSMPTE240M_60hz = 400, - kIOTimingIDFilmRate_48hz = 410, - kIOTimingIDSony_1600x1024_76hz = 500, - kIOTimingIDSony_1920x1080_60hz = 510, - kIOTimingIDSony_1920x1080_72hz = 520, - kIOTimingIDSony_1920x1200_76hz = 540, - kIOTimingIDApple_0x0_0hz_Offline = 550, - kIOTimingIDVESA_848x480_60hz = 570, - kIOTimingIDVESA_1360x768_60hz = 590 -}; -enum { - kIOHibernatePreviewActive = 0x00000001, - kIOHibernatePreviewUpdates = 0x00000002 -}; - - - - - - -enum { - kIOFBAVSignalTypeUnknown = 0x00000000, - kIOFBAVSignalTypeVGA = 0x00000001, - kIOFBAVSignalTypeDVI = 0x00000002, - kIOFBAVSignalTypeHDMI = 0x00000008, - kIOFBAVSignalTypeDP = 0x00000010, -}; - - - -struct IOFBDPLinkConfig -{ - uint16_t version; - uint8_t bitRate; - uint8_t __reservedA[1]; - uint16_t t1Time; - uint16_t t2Time; - uint16_t t3Time; - uint8_t idlePatterns; - uint8_t laneCount; - uint8_t voltage; - uint8_t preEmphasis; - uint8_t downspread; - uint8_t scrambler; - uint8_t maxBitRate; - uint8_t maxLaneCount; - uint8_t maxDownspread; - uint8_t __reservedB[9]; -}; -typedef struct IOFBDPLinkConfig IOFBDPLinkConfig; - -enum -{ - kIOFBBitRateRBR = 0x06, - kIOFBBitRateHBR = 0x0A, - kIOFBBitRateHBR2 = 0x14, -}; - -enum { - kIOFBLinkVoltageLevel0 = 0x00, - kIOFBLinkVoltageLevel1 = 0x01, - kIOFBLinkVoltageLevel2 = 0x02, - kIOFBLinkVoltageLevel3 = 0x03 -}; - -enum -{ - kIOFBLinkPreEmphasisLevel0 = 0x00, - kIOFBLinkPreEmphasisLevel1 = 0x01, - kIOFBLinkPreEmphasisLevel2 = 0x02, - kIOFBLinkPreEmphasisLevel3 = 0x03 -}; - -enum -{ - kIOFBLinkDownspreadNone = 0x0, - kIOFBLinkDownspreadMax = 0x1 -}; - -enum -{ - kIOFBLinkScramblerNormal = 0x0, - kIOFBLinkScramblerAlternate = 0x1 -}; -enum { - kDisplayVendorIDUnknown = 'unkn', - kDisplayProductIDGeneric = 0x717 -}; -enum { - kDisplaySubPixelLayoutUndefined = 0x00000000, - kDisplaySubPixelLayoutRGB = 0x00000001, - kDisplaySubPixelLayoutBGR = 0x00000002, - kDisplaySubPixelLayoutQuadGBL = 0x00000003, - kDisplaySubPixelLayoutQuadGBR = 0x00000004, - - kDisplaySubPixelConfigurationUndefined = 0x00000000, - kDisplaySubPixelConfigurationDelta = 0x00000001, - kDisplaySubPixelConfigurationStripe = 0x00000002, - kDisplaySubPixelConfigurationStripeOffset = 0x00000003, - kDisplaySubPixelConfigurationQuad = 0x00000004, - - kDisplaySubPixelShapeUndefined = 0x00000000, - kDisplaySubPixelShapeRound = 0x00000001, - kDisplaySubPixelShapeSquare = 0x00000002, - kDisplaySubPixelShapeRectangular = 0x00000003, - kDisplaySubPixelShapeOval = 0x00000004, - kDisplaySubPixelShapeElliptical = 0x00000005 -}; -} - - - - - - - - - - -typedef struct evsioKeymapping -{ - int size; - char *mapping; -} NXKeyMapping; - -typedef struct evsioMouseScaling -{ - int numScaleLevels; - short scaleThresholds[20]; - short scaleFactors[20]; -} NXMouseScaling; - -typedef enum { - NX_OneButton, - NX_LeftButton, - NX_RightButton -} NXMouseButton; - - -typedef struct __IOFixedPoint32 { - int32_t x; - int32_t y; -} IOFixedPoint32; -typedef int *NXEventSystemInfoType; - -typedef int NXEventSystemInfoData[(1024)]; -typedef struct { - int interface; - int interface_addr; - int dev_type; - int id; -} NXEventSystemDevice; - -typedef struct { - NXEventSystemDevice dev[16]; -} NXEventSystemDeviceList; -typedef enum {EVNOP, EVHIDE, EVSHOW, EVMOVE, EVLEVEL} EvCmd; -typedef float NXCoord; - -typedef struct _NXPoint { - NXCoord x, y; -} NXPoint; - -typedef struct _NXSize { - NXCoord width, height; -} NXSize; -typedef struct _NXTabletPointData { - SInt32 x; - SInt32 y; - SInt32 z; - UInt16 buttons; - UInt16 pressure; - struct { - SInt16 x; - SInt16 y; - } tilt; - UInt16 rotation; - SInt16 tangentialPressure; - UInt16 deviceID; - SInt16 vendor1; - SInt16 vendor2; - SInt16 vendor3; -} NXTabletPointData, *NXTabletPointDataPtr; - - - - - -typedef struct _NXTabletProximityData { - UInt16 vendorID; - UInt16 tabletID; - UInt16 pointerID; - UInt16 deviceID; - UInt16 systemTabletID; - UInt16 vendorPointerType; - UInt32 pointerSerialNumber; - UInt64 uniqueID __attribute__ ((packed)); - UInt32 capabilityMask; - UInt8 pointerType; - UInt8 enterProximity; - SInt16 reserved1; -} NXTabletProximityData, *NXTabletProximityDataPtr; - - - -typedef union { - struct { - UInt8 subx; - UInt8 suby; - SInt16 eventNum; - SInt32 click; - UInt8 pressure; - UInt8 buttonNumber; - UInt8 subType; - UInt8 reserved2; - SInt32 reserved3; - union { - NXTabletPointData point; - NXTabletProximityData proximity; - } tablet; - } mouse; - struct { - SInt32 dx; - SInt32 dy; - UInt8 subx; - UInt8 suby; - UInt8 subType; - UInt8 reserved1; - SInt32 reserved2; - union { - NXTabletPointData point; - NXTabletProximityData proximity; - } tablet; - } mouseMove; - struct { - UInt16 origCharSet; - SInt16 repeat; - UInt16 charSet; - UInt16 charCode; - UInt16 keyCode; - UInt16 origCharCode; - SInt32 reserved1; - UInt32 keyboardType; - SInt32 reserved2; - SInt32 reserved3; - SInt32 reserved4; - SInt32 reserved5[4]; - } key; - struct { - SInt16 reserved; - SInt16 eventNum; - SInt32 trackingNum; - SInt32 userData; - SInt32 reserved1; - SInt32 reserved2; - SInt32 reserved3; - SInt32 reserved4; - SInt32 reserved5; - SInt32 reserved6[4]; - } tracking; - struct { - SInt16 deltaAxis1; - SInt16 deltaAxis2; - SInt16 deltaAxis3; - SInt16 reserved1; - SInt32 fixedDeltaAxis1; - SInt32 fixedDeltaAxis2; - SInt32 fixedDeltaAxis3; - SInt32 pointDeltaAxis1; - SInt32 pointDeltaAxis2; - SInt32 pointDeltaAxis3; - SInt32 reserved8[4]; - } scrollWheel, zoom; - struct { - SInt16 reserved; - SInt16 subType; - union { - float F[11]; - SInt32 L[11]; - SInt16 S[22]; - char C[44]; - } misc; - } compound; - struct { - SInt32 x; - SInt32 y; - SInt32 z; - UInt16 buttons; - UInt16 pressure; - struct { - SInt16 x; - SInt16 y; - } tilt; - UInt16 rotation; - SInt16 tangentialPressure; - UInt16 deviceID; - SInt16 vendor1; - SInt16 vendor2; - SInt16 vendor3; - SInt32 reserved[4]; - } tablet; - struct { - UInt16 vendorID; - UInt16 tabletID; - UInt16 pointerID; - UInt16 deviceID; - UInt16 systemTabletID; - UInt16 vendorPointerType; - UInt32 pointerSerialNumber; - UInt64 uniqueID __attribute__ ((packed)); - UInt32 capabilityMask; - UInt8 pointerType; - UInt8 enterProximity; - SInt16 reserved1; - SInt32 reserved2[4]; - } proximity; -} NXEventData; - - - - - - - -typedef struct _NXEvent { - SInt32 type; - struct { - SInt32 x, y; - } location; - UInt64 time __attribute__ ((packed)); - SInt32 flags; - UInt32 window; - UInt64 service_id __attribute__ ((packed)); - SInt32 ext_pid; - NXEventData data; -} NXEvent, *NXEventPtr; -typedef struct __CGEvent *CGEventRef; - - -typedef uint32_t CGMouseButton; enum { - kCGMouseButtonLeft = 0, - kCGMouseButtonRight = 1, - kCGMouseButtonCenter = 2 -}; - - -typedef uint32_t CGScrollEventUnit; enum { - kCGScrollEventUnitPixel = 0, - kCGScrollEventUnitLine = 1, -}; - - -typedef uint32_t CGMomentumScrollPhase; enum { - kCGMomentumScrollPhaseNone = 0, - kCGMomentumScrollPhaseBegin = 1, - kCGMomentumScrollPhaseContinue = 2, - kCGMomentumScrollPhaseEnd = 3 -}; - - -typedef uint32_t CGScrollPhase; enum { - kCGScrollPhaseBegan = 1, - kCGScrollPhaseChanged = 2, - kCGScrollPhaseEnded = 4, - kCGScrollPhaseCancelled = 8, - kCGScrollPhaseMayBegin = 128 -}; - - -typedef uint32_t CGGesturePhase; enum { - kCGGesturePhaseNone = 0, - kCGGesturePhaseBegan = 1, - kCGGesturePhaseChanged = 2, - kCGGesturePhaseEnded = 4, - kCGGesturePhaseCancelled = 8, - kCGGesturePhaseMayBegin = 128 -}; - - - - - -typedef uint64_t CGEventFlags; enum { - - kCGEventFlagMaskAlphaShift = 0x00010000, - kCGEventFlagMaskShift = 0x00020000, - kCGEventFlagMaskControl = 0x00040000, - kCGEventFlagMaskAlternate = 0x00080000, - kCGEventFlagMaskCommand = 0x00100000, - - - kCGEventFlagMaskHelp = 0x00400000, - kCGEventFlagMaskSecondaryFn = 0x00800000, - - - kCGEventFlagMaskNumericPad = 0x00200000, - - - kCGEventFlagMaskNonCoalesced = 0x00000100 -}; - - -typedef uint32_t CGEventType; enum { - - kCGEventNull = 0, - - - kCGEventLeftMouseDown = 1, - kCGEventLeftMouseUp = 2, - kCGEventRightMouseDown = 3, - kCGEventRightMouseUp = 4, - kCGEventMouseMoved = 5, - kCGEventLeftMouseDragged = 6, - kCGEventRightMouseDragged = 7, - - - kCGEventKeyDown = 10, - kCGEventKeyUp = 11, - kCGEventFlagsChanged = 12, - - - kCGEventScrollWheel = 22, - kCGEventTabletPointer = 23, - kCGEventTabletProximity = 24, - kCGEventOtherMouseDown = 25, - kCGEventOtherMouseUp = 26, - kCGEventOtherMouseDragged = 27, - - - - kCGEventTapDisabledByTimeout = 0xFFFFFFFE, - kCGEventTapDisabledByUserInput = 0xFFFFFFFF -}; - - -typedef uint64_t CGEventTimestamp; - - -typedef uint32_t CGEventField; enum { - - - - kCGMouseEventNumber = 0, - - - - - - kCGMouseEventClickState = 1, - - - - - - kCGMouseEventPressure = 2, - - - - kCGMouseEventButtonNumber = 3, - - - - kCGMouseEventDeltaX = 4, - - - - kCGMouseEventDeltaY = 5, - - - - kCGMouseEventInstantMouser = 6, - - - - kCGMouseEventSubtype = 7, - - - - kCGKeyboardEventAutorepeat = 8, - - - - kCGKeyboardEventKeycode = 9, - - - - kCGKeyboardEventKeyboardType = 10, - - - - - - kCGScrollWheelEventDeltaAxis1 = 11, - - - - - kCGScrollWheelEventDeltaAxis2 = 12, - - - kCGScrollWheelEventDeltaAxis3 = 13, - kCGScrollWheelEventFixedPtDeltaAxis1 = 93, - - - - - - - - kCGScrollWheelEventFixedPtDeltaAxis2 = 94, - - - kCGScrollWheelEventFixedPtDeltaAxis3 = 95, - - - - - - kCGScrollWheelEventPointDeltaAxis1 = 96, - - - - - kCGScrollWheelEventPointDeltaAxis2 = 97, - - - kCGScrollWheelEventPointDeltaAxis3 = 98, - - - kCGScrollWheelEventScrollPhase = 99, - - - kCGScrollWheelEventScrollCount = 100, - - kCGScrollWheelEventMomentumPhase = 123, - - - - - kCGScrollWheelEventInstantMouser = 14, - - - - kCGTabletEventPointX = 15, - - - - kCGTabletEventPointY = 16, - - - - kCGTabletEventPointZ = 17, - - - - - kCGTabletEventPointButtons = 18, - - - - - kCGTabletEventPointPressure = 19, - - - - kCGTabletEventTiltX = 20, - - - - kCGTabletEventTiltY = 21, - - - kCGTabletEventRotation = 22, - - - - - kCGTabletEventTangentialPressure = 23, - - - - kCGTabletEventDeviceID = 24, - - - kCGTabletEventVendor1 = 25, - - - kCGTabletEventVendor2 = 26, - - - kCGTabletEventVendor3 = 27, - - - - kCGTabletProximityEventVendorID = 28, - - - - kCGTabletProximityEventTabletID = 29, - - - - kCGTabletProximityEventPointerID = 30, - - - - kCGTabletProximityEventDeviceID = 31, - - - - kCGTabletProximityEventSystemTabletID = 32, - - - - kCGTabletProximityEventVendorPointerType = 33, - - - - kCGTabletProximityEventVendorPointerSerialNumber = 34, - - - - kCGTabletProximityEventVendorUniqueID = 35, - - - - kCGTabletProximityEventCapabilityMask = 36, - - - kCGTabletProximityEventPointerType = 37, - - - - - kCGTabletProximityEventEnterProximity = 38, - - - - kCGEventTargetProcessSerialNumber = 39, - - - kCGEventTargetUnixProcessID = 40, - - - kCGEventSourceUnixProcessID = 41, - - - - kCGEventSourceUserData = 42, - - - - kCGEventSourceUserID = 43, - - - - kCGEventSourceGroupID = 44, - - - - kCGEventSourceStateID = 45, - - - - - - kCGScrollWheelEventIsContinuous = 88, - - - kCGMouseEventWindowUnderMousePointer = 91, - kCGMouseEventWindowUnderMousePointerThatCanHandleThisEvent = 92 -}; - - -typedef uint32_t CGEventMouseSubtype; enum { - kCGEventMouseSubtypeDefault = 0, - kCGEventMouseSubtypeTabletPoint = 1, - kCGEventMouseSubtypeTabletProximity = 2 -}; - - -typedef uint32_t CGEventTapLocation; enum { - kCGHIDEventTap = 0, - kCGSessionEventTap, - kCGAnnotatedSessionEventTap -}; - - - -typedef uint32_t CGEventTapPlacement; enum { - kCGHeadInsertEventTap = 0, - kCGTailAppendEventTap -}; - - - -typedef uint32_t CGEventTapOptions; enum { - kCGEventTapOptionDefault = 0x00000000, - kCGEventTapOptionListenOnly = 0x00000001 -}; - - - -typedef uint64_t CGEventMask; -typedef struct __CGEventTapProxy *CGEventTapProxy; -typedef CGEventRef _Nullable (*CGEventTapCallBack)(CGEventTapProxy proxy, - CGEventType type, CGEventRef event, void * _Nullable userInfo); -struct __CGEventTapInformation { - uint32_t eventTapID; - CGEventTapLocation tapPoint; - CGEventTapOptions options; - CGEventMask eventsOfInterest; - pid_t tappingProcess; - pid_t processBeingTapped; - bool enabled; - float minUsecLatency; - float avgUsecLatency; - float maxUsecLatency; -}; -typedef struct __CGEventTapInformation CGEventTapInformation; - - -typedef struct __CGEventSource *CGEventSourceRef; - - -typedef int32_t CGEventSourceStateID; enum { - kCGEventSourceStatePrivate = -1, - kCGEventSourceStateCombinedSessionState = 0, - kCGEventSourceStateHIDSystemState = 1 -}; - - - -typedef uint32_t CGEventSourceKeyboardType; - - - - - - - -extern "C" CFTypeID CGEventGetTypeID(void) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGEventRef _Nullable CGEventCreate(CGEventSourceRef _Nullable source) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CFDataRef _Nullable CGEventCreateData( - CFAllocatorRef _Nullable allocator, - CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGEventRef _Nullable CGEventCreateFromData( - CFAllocatorRef _Nullable allocator, CFDataRef _Nullable data) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGEventRef _Nullable CGEventCreateMouseEvent( - CGEventSourceRef _Nullable source, - CGEventType mouseType, CGPoint mouseCursorPosition, - CGMouseButton mouseButton) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGEventRef _Nullable CGEventCreateKeyboardEvent( - CGEventSourceRef _Nullable source, - CGKeyCode virtualKey, bool keyDown) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGEventRef _Nullable CGEventCreateScrollWheelEvent( - CGEventSourceRef _Nullable source, - CGScrollEventUnit units, uint32_t wheelCount, int32_t wheel1, ...) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" CGEventRef _Nullable CGEventCreateCopy(CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGEventSourceRef _Nullable CGEventCreateSourceFromEvent( - CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGEventSetSource(CGEventRef _Nullable event, - CGEventSourceRef _Nullable source) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGEventType CGEventGetType(CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGEventSetType(CGEventRef _Nullable event, CGEventType type) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGEventTimestamp CGEventGetTimestamp(CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGEventSetTimestamp(CGEventRef _Nullable event, - CGEventTimestamp timestamp) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGPoint CGEventGetLocation(CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGPoint CGEventGetUnflippedLocation(CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" void CGEventSetLocation(CGEventRef _Nullable event, CGPoint location) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGEventFlags CGEventGetFlags(CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGEventSetFlags(CGEventRef _Nullable event, CGEventFlags flags) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" void CGEventKeyboardGetUnicodeString(CGEventRef _Nullable event, - UniCharCount maxStringLength, UniCharCount *_Nullable actualStringLength, - UniChar * _Nullable unicodeString) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGEventKeyboardSetUnicodeString(CGEventRef _Nullable event, - UniCharCount stringLength, const UniChar * _Nullable unicodeString) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" int64_t CGEventGetIntegerValueField(CGEventRef _Nullable event, - CGEventField field) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGEventSetIntegerValueField(CGEventRef _Nullable event, - CGEventField field, int64_t value) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" double CGEventGetDoubleValueField(CGEventRef _Nullable event, - CGEventField field) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGEventSetDoubleValueField(CGEventRef _Nullable event, - CGEventField field, double value) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CFMachPortRef _Nullable CGEventTapCreate(CGEventTapLocation tap, - CGEventTapPlacement place, CGEventTapOptions options, - CGEventMask eventsOfInterest, CGEventTapCallBack _Nullable callback, - void * _Nullable userInfo) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" CFMachPortRef _Nullable CGEventTapCreateForPSN( - void * processSerialNumber, - CGEventTapPlacement place, CGEventTapOptions options, - CGEventMask eventsOfInterest, CGEventTapCallBack _Nullable callback, - void *_Nullable userInfo) - __attribute__((availability(macosx,introduced=10.4))); - -extern "C" CFMachPortRef _Nullable CGEventTapCreateForPid(pid_t pid, - CGEventTapPlacement place, CGEventTapOptions options, - CGEventMask eventsOfInterest, CGEventTapCallBack callback, - void *userInfo) __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGEventTapEnable(CFMachPortRef tap, bool enable) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" bool CGEventTapIsEnabled(CFMachPortRef tap) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGEventTapPostEvent(CGEventTapProxy _Nullable proxy, - CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" void CGEventPost(CGEventTapLocation tap, CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGEventPostToPSN(void * _Nullable processSerialNumber, - CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.4))); - -extern "C" void CGEventPostToPid( pid_t pid, - CGEventRef _Nullable event) - __attribute__((availability(macosx,introduced=10.11))); -extern "C" CGError CGGetEventTapList(uint32_t maxNumberOfTaps, - CGEventTapInformation * _Nullable tapList, - uint32_t * _Nullable eventTapCount) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CFTypeID CGEventSourceGetTypeID(void) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CGEventSourceRef _Nullable CGEventSourceCreate( - CGEventSourceStateID stateID) - __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CGEventSourceKeyboardType CGEventSourceGetKeyboardType( - CGEventSourceRef _Nullable source) - __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" void CGEventSourceSetKeyboardType(CGEventSourceRef _Nullable source, - CGEventSourceKeyboardType keyboardType) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" double CGEventSourceGetPixelsPerLine( - CGEventSourceRef _Nullable source) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" void CGEventSourceSetPixelsPerLine(CGEventSourceRef _Nullable source, - double pixelsPerLine) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" CGEventSourceStateID CGEventSourceGetSourceStateID( - CGEventSourceRef _Nullable source) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" bool CGEventSourceButtonState(CGEventSourceStateID stateID, - CGMouseButton button) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" bool CGEventSourceKeyState(CGEventSourceStateID stateID, - CGKeyCode key) - __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" CGEventFlags CGEventSourceFlagsState(CGEventSourceStateID stateID) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" CFTimeInterval CGEventSourceSecondsSinceLastEventType( - CGEventSourceStateID stateID, CGEventType eventType) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" uint32_t CGEventSourceCounterForEventType(CGEventSourceStateID - stateID, CGEventType eventType) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGEventSourceSetUserData(CGEventSourceRef _Nullable source, - int64_t userData) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" int64_t CGEventSourceGetUserData(CGEventSourceRef _Nullable source) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGEventSourceSetLocalEventsFilterDuringSuppressionState( - CGEventSourceRef _Nullable source, CGEventFilterMask filter, - CGEventSuppressionState state) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGEventFilterMask - CGEventSourceGetLocalEventsFilterDuringSuppressionState( - CGEventSourceRef _Nullable source, CGEventSuppressionState state) - __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGEventSourceSetLocalEventsSuppressionInterval( - CGEventSourceRef _Nullable source, CFTimeInterval seconds) - __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" CFTimeInterval CGEventSourceGetLocalEventsSuppressionInterval( - CGEventSourceRef _Nullable source) - __attribute__((availability(macosx,introduced=10.4))); - -typedef struct CGPSConverter *CGPSConverterRef; -typedef void (*CGPSConverterBeginDocumentCallback)(void * _Nullable info); - -typedef void (*CGPSConverterEndDocumentCallback)(void * _Nullable info, - bool success); - -typedef void (*CGPSConverterBeginPageCallback)(void * _Nullable info, - size_t pageNumber, - CFDictionaryRef pageInfo); - -typedef void (*CGPSConverterEndPageCallback)(void * _Nullable info, - size_t pageNumber, - CFDictionaryRef pageInfo); - -typedef void (*CGPSConverterProgressCallback)(void * _Nullable info); - -typedef void (*CGPSConverterMessageCallback)(void * _Nullable info, - CFStringRef message); - -typedef void (*CGPSConverterReleaseInfoCallback)(void * _Nullable info); - -struct CGPSConverterCallbacks { - unsigned int version; - CGPSConverterBeginDocumentCallback _Nullable beginDocument; - CGPSConverterEndDocumentCallback _Nullable endDocument; - CGPSConverterBeginPageCallback _Nullable beginPage; - CGPSConverterEndPageCallback _Nullable endPage; - CGPSConverterProgressCallback _Nullable noteProgress; - CGPSConverterMessageCallback _Nullable noteMessage; - CGPSConverterReleaseInfoCallback _Nullable releaseInfo; -}; -typedef struct CGPSConverterCallbacks CGPSConverterCallbacks; - - - - -extern "C" CGPSConverterRef _Nullable CGPSConverterCreate(void * _Nullable info, - const CGPSConverterCallbacks * callbacks, - CFDictionaryRef _Nullable options) - __attribute__((availability(macosx,introduced=10.3))); - - - - - -extern "C" bool CGPSConverterConvert(CGPSConverterRef converter, - CGDataProviderRef provider, CGDataConsumerRef consumer, - CFDictionaryRef _Nullable options) - __attribute__((availability(macosx,introduced=10.3))); - - - - -extern "C" bool CGPSConverterAbort(CGPSConverterRef converter) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" bool CGPSConverterIsConverting(CGPSConverterRef converter) - __attribute__((availability(macosx,introduced=10.3))); - - - -extern "C" CFTypeID CGPSConverterGetTypeID(void) - __attribute__((availability(macosx,introduced=10.3))); - -extern "C" CFDictionaryRef _Nullable CGSessionCopyCurrentDictionary(void) - __attribute__((availability(macosx,introduced=10.3))); -typedef uint32_t CGWindowID; - - -typedef uint32_t CGWindowSharingType; enum { - kCGWindowSharingNone = 0, - kCGWindowSharingReadOnly = 1, - kCGWindowSharingReadWrite = 2 -}; - - -typedef uint32_t CGWindowBackingType; enum { - kCGBackingStoreRetained = 0, - kCGBackingStoreNonretained = 1, - kCGBackingStoreBuffered = 2 -}; -extern "C" const CFStringRef kCGWindowNumber - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" const CFStringRef kCGWindowStoreType - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" const CFStringRef kCGWindowLayer - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern "C" const CFStringRef kCGWindowBounds - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" const CFStringRef kCGWindowSharingState - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" const CFStringRef kCGWindowAlpha - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" const CFStringRef kCGWindowOwnerPID - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" const CFStringRef kCGWindowMemoryUsage - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern "C" const CFStringRef kCGWindowWorkspace - __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); - - - - -extern "C" const CFStringRef kCGWindowOwnerName - __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" const CFStringRef kCGWindowName - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" const CFStringRef kCGWindowIsOnscreen - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" const CFStringRef kCGWindowBackingLocationVideoMemory - __attribute__((availability(macosx,introduced=10.5))); - - - -typedef uint32_t CGWindowListOption; enum { - - - - kCGWindowListOptionAll = 0, - - - - kCGWindowListOptionOnScreenOnly = (1 << 0), - - - - kCGWindowListOptionOnScreenAboveWindow = (1 << 1), - - - - kCGWindowListOptionOnScreenBelowWindow = (1 << 2), - - - - kCGWindowListOptionIncludingWindow = (1 << 3), - - - kCGWindowListExcludeDesktopElements = (1 << 4) -}; -extern "C" CFArrayRef _Nullable CGWindowListCopyWindowInfo(CGWindowListOption option, - CGWindowID relativeToWindow) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -extern "C" CFArrayRef _Nullable CGWindowListCreate(CGWindowListOption option, - CGWindowID relativeToWindow) - __attribute__((availability(macosx,introduced=10.5))) - __attribute__((availability(swift, unavailable, message="No replacement at present"))); -extern "C" CFArrayRef _Nullable CGWindowListCreateDescriptionFromArray( - CFArrayRef _Nullable windowArray) - __attribute__((availability(macosx,introduced=10.5))); - - - -typedef uint32_t CGWindowImageOption; enum { - - - kCGWindowImageDefault = 0, - - - - kCGWindowImageBoundsIgnoreFraming = (1 << 0), - - - kCGWindowImageShouldBeOpaque = (1 << 1), - - - kCGWindowImageOnlyShadows = (1 << 2), - - - - kCGWindowImageBestResolution = (1 << 3), - - - - kCGWindowImageNominalResolution = (1 << 4) -}; -extern "C" CGImageRef _Nullable CGWindowListCreateImage(CGRect screenBounds, - CGWindowListOption listOption, CGWindowID windowID, - CGWindowImageOption imageOption) - __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern "C" CGImageRef _Nullable CGWindowListCreateImageFromArray( - CGRect screenBounds, CFArrayRef windowArray, - CGWindowImageOption imageOption) - __attribute__((availability(macosx,introduced=10.5))); -typedef int32_t CGWindowLevelKey; enum { - kCGBaseWindowLevelKey = 0, - kCGMinimumWindowLevelKey, - kCGDesktopWindowLevelKey, - kCGBackstopMenuLevelKey, - kCGNormalWindowLevelKey, - kCGFloatingWindowLevelKey, - kCGTornOffMenuWindowLevelKey, - kCGDockWindowLevelKey, - kCGMainMenuWindowLevelKey, - kCGStatusWindowLevelKey, - kCGModalPanelWindowLevelKey, - kCGPopUpMenuWindowLevelKey, - kCGDraggingWindowLevelKey, - kCGScreenSaverWindowLevelKey, - kCGMaximumWindowLevelKey, - kCGOverlayWindowLevelKey, - kCGHelpWindowLevelKey, - kCGUtilityWindowLevelKey, - kCGDesktopIconWindowLevelKey, - kCGCursorWindowLevelKey, - kCGAssistiveTechHighWindowLevelKey, - kCGNumberOfWindowLevelKeys -}; - -typedef int32_t CGWindowLevel; - - - - -extern "C" CGWindowLevel CGWindowLevelForKey(CGWindowLevelKey key) - __attribute__((availability(macosx,introduced=10.0))); -// @protocol MTLDevice; - - - - -extern "C" id/*<MTLDevice>*/ _Nullable CGDirectDisplayCopyCurrentMetalDevice(CGDirectDisplayID display) __attribute__((availability(macosx,introduced=10.11))); - - - -// @class NSFont; -#ifndef _REWRITER_typedef_NSFont -#define _REWRITER_typedef_NSFont -typedef struct objc_object NSFont; -typedef struct {} _objc_exc_NSFont; -#endif - -// @class NSFontCollection; -#ifndef _REWRITER_typedef_NSFontCollection -#define _REWRITER_typedef_NSFontCollection -typedef struct objc_object NSFontCollection; -typedef struct {} _objc_exc_NSFontCollection; -#endif - -// @class NSFontDescriptor; -#ifndef _REWRITER_typedef_NSFontDescriptor -#define _REWRITER_typedef_NSFontDescriptor -typedef struct objc_object NSFontDescriptor; -typedef struct {} _objc_exc_NSFontDescriptor; -#endif - -// @class NSGlyphInfo; -#ifndef _REWRITER_typedef_NSGlyphInfo -#define _REWRITER_typedef_NSGlyphInfo -typedef struct objc_object NSGlyphInfo; -typedef struct {} _objc_exc_NSGlyphInfo; -#endif - -// @class NSMutableFontCollection; -#ifndef _REWRITER_typedef_NSMutableFontCollection -#define _REWRITER_typedef_NSMutableFontCollection -typedef struct objc_object NSMutableFontCollection; -typedef struct {} _objc_exc_NSMutableFontCollection; -#endif - - -// @class NSParagraphStyle; -#ifndef _REWRITER_typedef_NSParagraphStyle -#define _REWRITER_typedef_NSParagraphStyle -typedef struct objc_object NSParagraphStyle; -typedef struct {} _objc_exc_NSParagraphStyle; -#endif - -// @class NSTextTab; -#ifndef _REWRITER_typedef_NSTextTab -#define _REWRITER_typedef_NSTextTab -typedef struct objc_object NSTextTab; -typedef struct {} _objc_exc_NSTextTab; -#endif - -extern "C" { - - - - - - - -extern const CFStringRef kCTFontSymbolicTrait __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontWeightTrait __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontWidthTrait __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontSlantTrait __attribute__((availability(macosx,introduced=10.5))); - - - - - - -enum { - kCTFontClassMaskShift = 28 -}; - - - - - - -typedef uint32_t CTFontSymbolicTraits; enum { - kCTFontTraitItalic = (1 << 0), - kCTFontTraitBold = (1 << 1), - kCTFontTraitExpanded = (1 << 5), - kCTFontTraitCondensed = (1 << 6), - kCTFontTraitMonoSpace = (1 << 10), - kCTFontTraitVertical = (1 << 11), - kCTFontTraitUIOptimized = (1 << 12), - kCTFontTraitColorGlyphs = (1 << 13), - kCTFontTraitComposite = (1 << 14), - - kCTFontTraitClassMask = (15U << kCTFontClassMaskShift), - - - kCTFontItalicTrait = kCTFontTraitItalic, - kCTFontBoldTrait = kCTFontTraitBold, - kCTFontExpandedTrait = kCTFontTraitExpanded, - kCTFontCondensedTrait = kCTFontTraitCondensed, - kCTFontMonoSpaceTrait = kCTFontTraitMonoSpace, - kCTFontVerticalTrait = kCTFontTraitVertical, - kCTFontUIOptimizedTrait = kCTFontTraitUIOptimized, - kCTFontColorGlyphsTrait = kCTFontTraitColorGlyphs, - kCTFontCompositeTrait = kCTFontTraitComposite, - kCTFontClassMaskTrait = kCTFontTraitClassMask -}; - - - - - - -typedef uint32_t CTFontStylisticClass; enum { - kCTFontClassUnknown = (0 << kCTFontClassMaskShift), - kCTFontClassOldStyleSerifs = (1 << kCTFontClassMaskShift), - kCTFontClassTransitionalSerifs = (2 << kCTFontClassMaskShift), - kCTFontClassModernSerifs = (3 << kCTFontClassMaskShift), - kCTFontClassClarendonSerifs = (4 << kCTFontClassMaskShift), - kCTFontClassSlabSerifs = (5 << kCTFontClassMaskShift), - kCTFontClassFreeformSerifs = (7 << kCTFontClassMaskShift), - kCTFontClassSansSerif = (8U << kCTFontClassMaskShift), - kCTFontClassOrnamentals = (9U << kCTFontClassMaskShift), - kCTFontClassScripts = (10U << kCTFontClassMaskShift), - kCTFontClassSymbolic = (12U << kCTFontClassMaskShift), - - kCTFontUnknownClass = kCTFontClassUnknown, - kCTFontOldStyleSerifsClass = kCTFontClassOldStyleSerifs, - kCTFontTransitionalSerifsClass = kCTFontClassTransitionalSerifs, - kCTFontModernSerifsClass = kCTFontClassModernSerifs, - kCTFontClarendonSerifsClass = kCTFontClassClarendonSerifs, - kCTFontSlabSerifsClass = kCTFontClassSlabSerifs, - kCTFontFreeformSerifsClass = kCTFontClassFreeformSerifs, - kCTFontSansSerifClass = kCTFontClassSansSerif, - kCTFontOrnamentalsClass = kCTFontClassOrnamentals, - kCTFontScriptsClass = kCTFontClassScripts, - kCTFontSymbolicClass = kCTFontClassSymbolic -}; - - -} -extern "C" { -typedef const struct __attribute__((objc_bridge(NSFontDescriptor))) __CTFontDescriptor * CTFontDescriptorRef; -CFTypeID CTFontDescriptorGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTFontURLAttribute __attribute__((availability(macosx,introduced=10.6))); - - - - - -extern const CFStringRef kCTFontNameAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontDisplayNameAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFamilyNameAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontStyleNameAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontTraitsAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontVariationAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontSizeAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontMatrixAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontCascadeListAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontCharacterSetAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontLanguagesAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontBaselineAdjustAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontMacintoshEncodingsAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFeaturesAttribute __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTFontFeatureSettingsAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFixedAdvanceAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontOrientationAttribute __attribute__((availability(macosx,introduced=10.5))); - - - - - -typedef uint32_t CTFontOrientation; enum { - kCTFontOrientationDefault __attribute__((availability(macosx,introduced=10.8))) = 0, - kCTFontOrientationHorizontal __attribute__((availability(macosx,introduced=10.8))) = 1, - kCTFontOrientationVertical __attribute__((availability(macosx,introduced=10.8))) = 2, - - kCTFontDefaultOrientation __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontOrientationDefault, - kCTFontHorizontalOrientation __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontOrientationHorizontal, - kCTFontVerticalOrientation __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontOrientationVertical -}; - - - - - - -extern const CFStringRef kCTFontFormatAttribute __attribute__((availability(macosx,introduced=10.6))); -typedef uint32_t CTFontFormat; enum { - kCTFontFormatUnrecognized = 0, - kCTFontFormatOpenTypePostScript = 1, - kCTFontFormatOpenTypeTrueType = 2, - kCTFontFormatTrueType = 3, - kCTFontFormatPostScript = 4, - kCTFontFormatBitmap = 5 -}; - - - - - - -extern const CFStringRef kCTFontRegistrationScopeAttribute __attribute__((availability(macosx,introduced=10.6))); - - - - - -extern const CFStringRef kCTFontPriorityAttribute __attribute__((availability(macosx,introduced=10.6))); -enum { - kCTFontPrioritySystem = 10000, - kCTFontPriorityNetwork = 20000, - kCTFontPriorityComputer = 30000, - kCTFontPriorityUser = 40000, - kCTFontPriorityDynamic = 50000, - kCTFontPriorityProcess = 60000 -}; -typedef uint32_t CTFontPriority; - - - - - - -extern const CFStringRef kCTFontEnabledAttribute __attribute__((availability(macosx,introduced=10.6))); - - - - - - -extern const CFStringRef kCTFontDownloadableAttribute __attribute__((availability(macosx,introduced=10.8))); - - - - - - -extern const CFStringRef kCTFontDownloadedAttribute __attribute__((availability(macosx,unavailable))); -CTFontDescriptorRef CTFontDescriptorCreateWithNameAndSize( - CFStringRef name, - CGFloat size ) __attribute__((availability(macosx,introduced=10.5))); -CTFontDescriptorRef CTFontDescriptorCreateWithAttributes( - CFDictionaryRef attributes ) __attribute__((availability(macosx,introduced=10.5))); -CTFontDescriptorRef CTFontDescriptorCreateCopyWithAttributes( - CTFontDescriptorRef original, - CFDictionaryRef attributes ) __attribute__((availability(macosx,introduced=10.5))); -CTFontDescriptorRef _Nullable CTFontDescriptorCreateCopyWithFamily( - CTFontDescriptorRef original, - CFStringRef family ) __attribute__((availability(macosx,introduced=10.9))); -CTFontDescriptorRef _Nullable CTFontDescriptorCreateCopyWithSymbolicTraits( - CTFontDescriptorRef original, - CTFontSymbolicTraits symTraitValue, - CTFontSymbolicTraits symTraitMask ) __attribute__((availability(macosx,introduced=10.9))); -CTFontDescriptorRef CTFontDescriptorCreateCopyWithVariation( - CTFontDescriptorRef original, - CFNumberRef variationIdentifier, - CGFloat variationValue ) __attribute__((availability(macosx,introduced=10.5))); -CTFontDescriptorRef CTFontDescriptorCreateCopyWithFeature( - CTFontDescriptorRef original, - CFNumberRef featureTypeIdentifier, - CFNumberRef featureSelectorIdentifier ) __attribute__((availability(macosx,introduced=10.5))); -CFArrayRef _Nullable CTFontDescriptorCreateMatchingFontDescriptors( - CTFontDescriptorRef descriptor, - CFSetRef _Nullable mandatoryAttributes ) __attribute__((availability(macosx,introduced=10.5))); -CTFontDescriptorRef _Nullable CTFontDescriptorCreateMatchingFontDescriptor( - CTFontDescriptorRef descriptor, - CFSetRef _Nullable mandatoryAttributes ) __attribute__((availability(macosx,introduced=10.5))); - - - - - - -typedef uint32_t CTFontDescriptorMatchingState; enum { - kCTFontDescriptorMatchingDidBegin, - kCTFontDescriptorMatchingDidFinish, - - kCTFontDescriptorMatchingWillBeginQuerying, - kCTFontDescriptorMatchingStalled, - - - kCTFontDescriptorMatchingWillBeginDownloading, - kCTFontDescriptorMatchingDownloading, - kCTFontDescriptorMatchingDidFinishDownloading, - kCTFontDescriptorMatchingDidMatch, - - kCTFontDescriptorMatchingDidFailWithError -}; - - - - - - -extern const CFStringRef kCTFontDescriptorMatchingSourceDescriptor __attribute__((availability(macosx,introduced=10.8))); - - -extern const CFStringRef kCTFontDescriptorMatchingDescriptors __attribute__((availability(macosx,introduced=10.8))); - - -extern const CFStringRef kCTFontDescriptorMatchingResult __attribute__((availability(macosx,introduced=10.8))); - - -extern const CFStringRef kCTFontDescriptorMatchingPercentage __attribute__((availability(macosx,introduced=10.8))); - - -extern const CFStringRef kCTFontDescriptorMatchingCurrentAssetSize __attribute__((availability(macosx,introduced=10.8))); - - -extern const CFStringRef kCTFontDescriptorMatchingTotalDownloadedSize __attribute__((availability(macosx,introduced=10.8))); - - -extern const CFStringRef kCTFontDescriptorMatchingTotalAssetSize __attribute__((availability(macosx,introduced=10.8))); - - -extern const CFStringRef kCTFontDescriptorMatchingError __attribute__((availability(macosx,introduced=10.8))); - - - - -typedef bool (*CTFontDescriptorProgressHandler)(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter); -bool CTFontDescriptorMatchFontDescriptorsWithProgressHandler( - CFArrayRef descriptors, - CFSetRef _Nullable mandatoryAttributes, - CTFontDescriptorProgressHandler progressBlock) __attribute__((availability(macosx,introduced=10.9))); -CFDictionaryRef CTFontDescriptorCopyAttributes( - CTFontDescriptorRef descriptor ) __attribute__((availability(macosx,introduced=10.5))); -CFTypeRef _Nullable CTFontDescriptorCopyAttribute( - CTFontDescriptorRef descriptor, - CFStringRef attribute ) __attribute__((availability(macosx,introduced=10.5))); -CFTypeRef _Nullable CTFontDescriptorCopyLocalizedAttribute( - CTFontDescriptorRef descriptor, - CFStringRef attribute, - CFStringRef _Nullable * _Nullable language ) __attribute__((availability(macosx,introduced=10.5))); - - -} - - - - - - -extern "C" { -typedef const struct __attribute__((objc_bridge(NSFont))) __CTFont * CTFontRef; - - - - - - - -CFTypeID CTFontGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTFontCopyrightNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontFamilyNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontSubFamilyNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontStyleNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern const CFStringRef kCTFontUniqueNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontFullNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontVersionNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontPostScriptNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontTrademarkNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontManufacturerNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontDesignerNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontDescriptionNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontVendorURLNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontDesignerURLNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontLicenseNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontLicenseURLNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontSampleTextNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - -extern const CFStringRef kCTFontPostScriptCIDNameKey __attribute__((availability(macosx,introduced=10.5))); -CTFontRef CTFontCreateWithName( - CFStringRef _Nullable name, - CGFloat size, - const CGAffineTransform * _Nullable matrix ) __attribute__((availability(macosx,introduced=10.5))); -CTFontRef CTFontCreateWithFontDescriptor( - CTFontDescriptorRef descriptor, - CGFloat size, - const CGAffineTransform * _Nullable matrix ) __attribute__((availability(macosx,introduced=10.5))); -typedef CFOptionFlags CTFontOptions; enum { - kCTFontOptionsDefault = 0, - kCTFontOptionsPreventAutoActivation = 1 << 0, - kCTFontOptionsPreferSystemFont = 1 << 2 -}; -CTFontRef CTFontCreateWithNameAndOptions( - CFStringRef name, - CGFloat size, - const CGAffineTransform * _Nullable matrix, - CTFontOptions options ) __attribute__((availability(macosx,introduced=10.6))); -CTFontRef CTFontCreateWithFontDescriptorAndOptions( - CTFontDescriptorRef descriptor, - CGFloat size, - const CGAffineTransform * _Nullable matrix, - CTFontOptions options ) __attribute__((availability(macosx,introduced=10.6))); - - - - - - -typedef uint32_t CTFontUIFontType; enum { - kCTFontUIFontNone __attribute__((availability(macosx,introduced=10.8))) = (uint32_t)-1, - kCTFontUIFontUser __attribute__((availability(macosx,introduced=10.8))) = 0, - kCTFontUIFontUserFixedPitch __attribute__((availability(macosx,introduced=10.8))) = 1, - kCTFontUIFontSystem __attribute__((availability(macosx,introduced=10.8))) = 2, - kCTFontUIFontEmphasizedSystem __attribute__((availability(macosx,introduced=10.8))) = 3, - kCTFontUIFontSmallSystem __attribute__((availability(macosx,introduced=10.8))) = 4, - kCTFontUIFontSmallEmphasizedSystem __attribute__((availability(macosx,introduced=10.8))) = 5, - kCTFontUIFontMiniSystem __attribute__((availability(macosx,introduced=10.8))) = 6, - kCTFontUIFontMiniEmphasizedSystem __attribute__((availability(macosx,introduced=10.8))) = 7, - kCTFontUIFontViews __attribute__((availability(macosx,introduced=10.8))) = 8, - kCTFontUIFontApplication __attribute__((availability(macosx,introduced=10.8))) = 9, - kCTFontUIFontLabel __attribute__((availability(macosx,introduced=10.8))) = 10, - kCTFontUIFontMenuTitle __attribute__((availability(macosx,introduced=10.8))) = 11, - kCTFontUIFontMenuItem __attribute__((availability(macosx,introduced=10.8))) = 12, - kCTFontUIFontMenuItemMark __attribute__((availability(macosx,introduced=10.8))) = 13, - kCTFontUIFontMenuItemCmdKey __attribute__((availability(macosx,introduced=10.8))) = 14, - kCTFontUIFontWindowTitle __attribute__((availability(macosx,introduced=10.8))) = 15, - kCTFontUIFontPushButton __attribute__((availability(macosx,introduced=10.8))) = 16, - kCTFontUIFontUtilityWindowTitle __attribute__((availability(macosx,introduced=10.8))) = 17, - kCTFontUIFontAlertHeader __attribute__((availability(macosx,introduced=10.8))) = 18, - kCTFontUIFontSystemDetail __attribute__((availability(macosx,introduced=10.8))) = 19, - kCTFontUIFontEmphasizedSystemDetail __attribute__((availability(macosx,introduced=10.8))) = 20, - kCTFontUIFontToolbar __attribute__((availability(macosx,introduced=10.8))) = 21, - kCTFontUIFontSmallToolbar __attribute__((availability(macosx,introduced=10.8))) = 22, - kCTFontUIFontMessage __attribute__((availability(macosx,introduced=10.8))) = 23, - kCTFontUIFontPalette __attribute__((availability(macosx,introduced=10.8))) = 24, - kCTFontUIFontToolTip __attribute__((availability(macosx,introduced=10.8))) = 25, - kCTFontUIFontControlContent __attribute__((availability(macosx,introduced=10.8))) = 26, - - kCTFontNoFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontNone, - kCTFontUserFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontUser, - kCTFontUserFixedPitchFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontUserFixedPitch, - kCTFontSystemFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontSystem, - kCTFontEmphasizedSystemFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontEmphasizedSystem, - kCTFontSmallSystemFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontSmallSystem, - kCTFontSmallEmphasizedSystemFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontSmallEmphasizedSystem, - kCTFontMiniSystemFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontMiniSystem, - kCTFontMiniEmphasizedSystemFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontMiniEmphasizedSystem, - kCTFontViewsFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontViews, - kCTFontApplicationFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontApplication, - kCTFontLabelFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontLabel, - kCTFontMenuTitleFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontMenuTitle, - kCTFontMenuItemFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontMenuItem, - kCTFontMenuItemMarkFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontMenuItemMark, - kCTFontMenuItemCmdKeyFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontMenuItemCmdKey, - kCTFontWindowTitleFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontWindowTitle, - kCTFontPushButtonFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontPushButton, - kCTFontUtilityWindowTitleFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontUtilityWindowTitle, - kCTFontAlertHeaderFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontAlertHeader, - kCTFontSystemDetailFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontSystemDetail, - kCTFontEmphasizedSystemDetailFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontEmphasizedSystemDetail, - kCTFontToolbarFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontToolbar, - kCTFontSmallToolbarFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontSmallToolbar, - kCTFontMessageFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontMessage, - kCTFontPaletteFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontPalette, - kCTFontToolTipFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontToolTip, - kCTFontControlContentFontType __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTFontUIFontControlContent -}; -CTFontRef _Nullable CTFontCreateUIFontForLanguage( - CTFontUIFontType uiType, - CGFloat size, - CFStringRef _Nullable language ) __attribute__((availability(macosx,introduced=10.5))); -CTFontRef CTFontCreateCopyWithAttributes( - CTFontRef font, - CGFloat size, - const CGAffineTransform * _Nullable matrix, - CTFontDescriptorRef _Nullable attributes ) __attribute__((availability(macosx,introduced=10.5))); -CTFontRef _Nullable CTFontCreateCopyWithSymbolicTraits( - CTFontRef font, - CGFloat size, - const CGAffineTransform * _Nullable matrix, - CTFontSymbolicTraits symTraitValue, - CTFontSymbolicTraits symTraitMask ) __attribute__((availability(macosx,introduced=10.5))); -CTFontRef _Nullable CTFontCreateCopyWithFamily( - CTFontRef font, - CGFloat size, - const CGAffineTransform * _Nullable matrix, - CFStringRef family ) __attribute__((availability(macosx,introduced=10.5))); -CTFontRef CTFontCreateForString( - CTFontRef currentFont, - CFStringRef string, - CFRange range ) __attribute__((availability(macosx,introduced=10.5))); -CTFontDescriptorRef CTFontCopyFontDescriptor( - CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFTypeRef _Nullable CTFontCopyAttribute( - CTFontRef font, - CFStringRef attribute ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTFontGetSize( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGAffineTransform CTFontGetMatrix( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CTFontSymbolicTraits CTFontGetSymbolicTraits( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFDictionaryRef CTFontCopyTraits( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFStringRef CTFontCopyPostScriptName( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFStringRef CTFontCopyFamilyName( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFStringRef CTFontCopyFullName( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFStringRef CTFontCopyDisplayName( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFStringRef _Nullable CTFontCopyName( - CTFontRef font, - CFStringRef nameKey ) __attribute__((availability(macosx,introduced=10.5))); -CFStringRef _Nullable CTFontCopyLocalizedName( - CTFontRef font, - CFStringRef nameKey, - CFStringRef _Nullable * _Nullable actualLanguage ) __attribute__((availability(macosx,introduced=10.5))); -CFCharacterSetRef CTFontCopyCharacterSet( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFStringEncoding CTFontGetStringEncoding( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFArrayRef CTFontCopySupportedLanguages( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -bool CTFontGetGlyphsForCharacters( - CTFontRef font, - const UniChar characters[], - CGGlyph glyphs[], - CFIndex count ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTFontGetAscent( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTFontGetDescent( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTFontGetLeading( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -unsigned CTFontGetUnitsPerEm( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFIndex CTFontGetGlyphCount( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGRect CTFontGetBoundingBox( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTFontGetUnderlinePosition( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTFontGetUnderlineThickness( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTFontGetSlantAngle( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTFontGetCapHeight( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTFontGetXHeight( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGGlyph CTFontGetGlyphWithName( - CTFontRef font, - CFStringRef glyphName ) __attribute__((availability(macosx,introduced=10.5))); -CGRect CTFontGetBoundingRectsForGlyphs( - CTFontRef font, - CTFontOrientation orientation, - const CGGlyph glyphs[], - CGRect * _Nullable boundingRects, - CFIndex count ) __attribute__((availability(macosx,introduced=10.5))); -CGRect CTFontGetOpticalBoundsForGlyphs( - CTFontRef font, - const CGGlyph glyphs[], - CGRect * _Nullable boundingRects, - CFIndex count, - CFOptionFlags options ) __attribute__((availability(macosx,introduced=10.8))); -double CTFontGetAdvancesForGlyphs( - CTFontRef font, - CTFontOrientation orientation, - const CGGlyph glyphs[], - CGSize * _Nullable advances, - CFIndex count ) __attribute__((availability(macosx,introduced=10.5))); -void CTFontGetVerticalTranslationsForGlyphs( - CTFontRef font, - const CGGlyph glyphs[], - CGSize translations[], - CFIndex count ) __attribute__((availability(macosx,introduced=10.5))); -CGPathRef _Nullable CTFontCreatePathForGlyph( - CTFontRef font, - CGGlyph glyph, - const CGAffineTransform * _Nullable matrix ) __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTFontVariationAxisIdentifierKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontVariationAxisMinimumValueKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontVariationAxisMaximumValueKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontVariationAxisDefaultValueKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontVariationAxisNameKey __attribute__((availability(macosx,introduced=10.5))); -CFArrayRef _Nullable CTFontCopyVariationAxes( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFDictionaryRef _Nullable CTFontCopyVariation( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTFontOpenTypeFeatureTag __attribute__((availability(macosx,introduced=10.10))); - - - - - -extern const CFStringRef kCTFontOpenTypeFeatureValue __attribute__((availability(macosx,introduced=10.10))); - - - - - -extern const CFStringRef kCTFontFeatureTypeIdentifierKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFeatureTypeNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFeatureTypeExclusiveKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFeatureTypeSelectorsKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFeatureSelectorIdentifierKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFeatureSelectorNameKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFeatureSelectorDefaultKey __attribute__((availability(macosx,introduced=10.5))); - - - - - -extern const CFStringRef kCTFontFeatureSelectorSettingKey __attribute__((availability(macosx,introduced=10.5))); -CFArrayRef _Nullable CTFontCopyFeatures( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CFArrayRef _Nullable CTFontCopyFeatureSettings( CTFontRef font ) __attribute__((availability(macosx,introduced=10.5))); -CGFontRef CTFontCopyGraphicsFont( - CTFontRef font, - CTFontDescriptorRef _Nullable * _Nullable attributes ) __attribute__((availability(macosx,introduced=10.5))); -CTFontRef CTFontCreateWithGraphicsFont( - CGFontRef graphicsFont, - CGFloat size, - const CGAffineTransform * _Nullable matrix, - CTFontDescriptorRef _Nullable attributes ) __attribute__((availability(macosx,introduced=10.5))); -ATSFontRef CTFontGetPlatformFont( - CTFontRef font, - CTFontDescriptorRef _Nullable * _Nullable attributes ) __attribute__((availability(macosx,introduced=10.5))); -CTFontRef _Nullable CTFontCreateWithPlatformFont( - ATSFontRef platformFont, - CGFloat size, - const CGAffineTransform * _Nullable matrix, - CTFontDescriptorRef _Nullable attributes ) __attribute__((availability(macosx,introduced=10.5))); -CTFontRef CTFontCreateWithQuickdrawInstance( - ConstStr255Param _Nullable name, - int16_t identifier, - uint8_t style, - CGFloat size ) __attribute__((availability(macosx,introduced=10.5))); - - - - - -enum { - kCTFontTableBASE = 'BASE', - kCTFontTableCFF = 'CFF ', - kCTFontTableDSIG = 'DSIG', - kCTFontTableEBDT = 'EBDT', - kCTFontTableEBLC = 'EBLC', - kCTFontTableEBSC = 'EBSC', - kCTFontTableGDEF = 'GDEF', - kCTFontTableGPOS = 'GPOS', - kCTFontTableGSUB = 'GSUB', - kCTFontTableJSTF = 'JSTF', - kCTFontTableLTSH = 'LTSH', - kCTFontTableMATH = 'MATH', - kCTFontTableOS2 = 'OS/2', - kCTFontTablePCLT = 'PCLT', - kCTFontTableVDMX = 'VDMX', - kCTFontTableVORG = 'VORG', - kCTFontTableZapf = 'Zapf', - kCTFontTableAcnt = 'acnt', - kCTFontTableAnkr = 'ankr', - kCTFontTableAvar = 'avar', - kCTFontTableBdat = 'bdat', - kCTFontTableBhed = 'bhed', - kCTFontTableBloc = 'bloc', - kCTFontTableBsln = 'bsln', - kCTFontTableCmap = 'cmap', - kCTFontTableCvar = 'cvar', - kCTFontTableCvt = 'cvt ', - kCTFontTableFdsc = 'fdsc', - kCTFontTableFeat = 'feat', - kCTFontTableFmtx = 'fmtx', - kCTFontTableFpgm = 'fpgm', - kCTFontTableFvar = 'fvar', - kCTFontTableGasp = 'gasp', - kCTFontTableGlyf = 'glyf', - kCTFontTableGvar = 'gvar', - kCTFontTableHdmx = 'hdmx', - kCTFontTableHead = 'head', - kCTFontTableHhea = 'hhea', - kCTFontTableHmtx = 'hmtx', - kCTFontTableHsty = 'hsty', - kCTFontTableJust = 'just', - kCTFontTableKern = 'kern', - kCTFontTableKerx = 'kerx', - kCTFontTableLcar = 'lcar', - kCTFontTableLtag = 'ltag', - kCTFontTableLoca = 'loca', - kCTFontTableMaxp = 'maxp', - kCTFontTableMort = 'mort', - kCTFontTableMorx = 'morx', - kCTFontTableName = 'name', - kCTFontTableOpbd = 'opbd', - kCTFontTablePost = 'post', - kCTFontTablePrep = 'prep', - kCTFontTableProp = 'prop', - kCTFontTableSbit = 'sbit', - kCTFontTableSbix = 'sbix', - kCTFontTableTrak = 'trak', - kCTFontTableVhea = 'vhea', - kCTFontTableVmtx = 'vmtx' -}; -typedef FourCharCode CTFontTableTag; - -typedef uint32_t CTFontTableOptions; enum { - kCTFontTableOptionNoOptions __attribute__((availability(macosx,introduced=10.5))) = 0, - kCTFontTableOptionExcludeSynthetic __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))) = (1 << 0) -}; -CFArrayRef _Nullable CTFontCopyAvailableTables( - CTFontRef font, - CTFontTableOptions options ) __attribute__((availability(macosx,introduced=10.5))); -CFDataRef _Nullable CTFontCopyTable( - CTFontRef font, - CTFontTableTag table, - CTFontTableOptions options ) __attribute__((availability(macosx,introduced=10.5))); -void CTFontDrawGlyphs( - CTFontRef font, - const CGGlyph glyphs[], - const CGPoint positions[], - size_t count, - CGContextRef context ) __attribute__((availability(macosx,introduced=10.7))); -CFIndex CTFontGetLigatureCaretPositions( - CTFontRef font, - CGGlyph glyph, - CGFloat * _Nullable positions, - CFIndex maxPositions ) __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTBaselineClassRoman __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTBaselineClassIdeographicCentered __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTBaselineClassIdeographicLow __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTBaselineClassIdeographicHigh __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTBaselineClassHanging __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTBaselineClassMath __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTBaselineReferenceFont __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTBaselineOriginalFont __attribute__((availability(macosx,introduced=10.8))); -CFArrayRef _Nullable CTFontCopyDefaultCascadeListForLanguages( CTFontRef font, CFArrayRef _Nullable languagePrefList ) __attribute__((availability(macosx,introduced=10.8))); - - -} -extern "C" { -typedef const struct __attribute__((objc_bridge(NSFontCollection))) __CTFontCollection * CTFontCollectionRef; -typedef struct __attribute__((objc_bridge_mutable(NSMutableFontCollection))) __CTFontCollection * CTMutableFontCollectionRef; - - - - - - - -CFTypeID CTFontCollectionGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); - - - - - - -typedef CFComparisonResult (*CTFontCollectionSortDescriptorsCallback)( - CTFontDescriptorRef first, - CTFontDescriptorRef second, - void *refCon ); -extern const CFStringRef kCTFontCollectionRemoveDuplicatesOption __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern const CFStringRef kCTFontCollectionIncludeDisabledFontsOption __attribute__((availability(macosx,introduced=10.7))); - - - - - - -extern const CFStringRef kCTFontCollectionDisallowAutoActivationOption __attribute__((availability(macosx,introduced=10.7))); -CTFontCollectionRef CTFontCollectionCreateFromAvailableFonts( - CFDictionaryRef _Nullable options ) __attribute__((availability(macosx,introduced=10.5))); -CTFontCollectionRef CTFontCollectionCreateWithFontDescriptors( - CFArrayRef _Nullable queryDescriptors, - CFDictionaryRef _Nullable options ) __attribute__((availability(macosx,introduced=10.5))); -CTFontCollectionRef CTFontCollectionCreateCopyWithFontDescriptors( - CTFontCollectionRef original, - CFArrayRef _Nullable queryDescriptors, - CFDictionaryRef _Nullable options ) __attribute__((availability(macosx,introduced=10.5))); -CTMutableFontCollectionRef CTFontCollectionCreateMutableCopy( - CTFontCollectionRef original ) __attribute__((availability(macosx,introduced=10.7))); -CFArrayRef _Nullable CTFontCollectionCopyQueryDescriptors( - CTFontCollectionRef collection ) __attribute__((availability(macosx,introduced=10.7))); -void CTFontCollectionSetQueryDescriptors( - CTMutableFontCollectionRef collection, - CFArrayRef _Nullable descriptors ) __attribute__((availability(macosx,introduced=10.7))); -CFArrayRef _Nullable CTFontCollectionCopyExclusionDescriptors( CTFontCollectionRef collection ) __attribute__((availability(macosx,introduced=10.7))); -void CTFontCollectionSetExclusionDescriptors( - CTMutableFontCollectionRef collection, - CFArrayRef _Nullable descriptors ) __attribute__((availability(macosx,introduced=10.7))); -CFArrayRef _Nullable CTFontCollectionCreateMatchingFontDescriptors( - CTFontCollectionRef collection ) __attribute__((availability(macosx,introduced=10.5))); -CFArrayRef _Nullable CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback( - CTFontCollectionRef collection, - CTFontCollectionSortDescriptorsCallback _Nullable sortCallback, - void * _Nullable refCon ) __attribute__((availability(macosx,introduced=10.5))); -CFArrayRef _Nullable CTFontCollectionCreateMatchingFontDescriptorsWithOptions( - CTFontCollectionRef collection, - CFDictionaryRef _Nullable options ) __attribute__((availability(macosx,introduced=10.7))); -CFArrayRef _Nullable CTFontCollectionCreateMatchingFontDescriptorsForFamily( - CTFontCollectionRef collection, - CFStringRef familyName, - CFDictionaryRef _Nullable options ) __attribute__((availability(macosx,introduced=10.7))); -typedef uint32_t CTFontCollectionCopyOptions; enum { - kCTFontCollectionCopyDefaultOptions = 0, - kCTFontCollectionCopyUnique = (1 << 0), - kCTFontCollectionCopyStandardSort = (1 << 1) -} __attribute__((availability(macosx,introduced=10.7))); -CFArrayRef CTFontCollectionCopyFontAttribute( - CTFontCollectionRef collection, - CFStringRef attributeName, - CTFontCollectionCopyOptions options ) __attribute__((availability(macosx,introduced=10.7))); -CFArrayRef CTFontCollectionCopyFontAttributes( - CTFontCollectionRef collection, - CFSetRef attributeNames, - CTFontCollectionCopyOptions options ) __attribute__((availability(macosx,introduced=10.7))); - - -} - -extern "C" { - - - - - - - -extern const CFStringRef kCTFontManagerErrorDomain __attribute__((availability(macosx,introduced=10.6))); - - - - - - -extern const CFStringRef kCTFontManagerErrorFontURLsKey __attribute__((availability(macosx,introduced=10.6))); -typedef CFIndex CTFontManagerError; enum { - kCTFontManagerErrorFileNotFound = 101, - kCTFontManagerErrorInsufficientPermissions = 102, - kCTFontManagerErrorUnrecognizedFormat = 103, - kCTFontManagerErrorInvalidFontData = 104, - kCTFontManagerErrorAlreadyRegistered = 105, - kCTFontManagerErrorNotRegistered = 201, - kCTFontManagerErrorInUse = 202, - kCTFontManagerErrorSystemRequired = 203, -}; - - -} - - - - - - -extern "C" { -CFArrayRef CTFontManagerCopyAvailablePostScriptNames( void ) __attribute__((availability(macosx,introduced=10.6))); - - - - - - - -CFArrayRef CTFontManagerCopyAvailableFontFamilyNames( void ) __attribute__((availability(macosx,introduced=10.6))); - - - - - - - -CFArrayRef CTFontManagerCopyAvailableFontURLs( void ) __attribute__((availability(macosx,introduced=10.6))); -CFComparisonResult CTFontManagerCompareFontFamilyNames( - const void * family1, - const void * family2, - void * _Nullable context ) __attribute__((availability(macosx,introduced=10.6))); -CFArrayRef _Nullable CTFontManagerCreateFontDescriptorsFromURL( - CFURLRef fileURL ) __attribute__((availability(macosx,introduced=10.6))); -CTFontDescriptorRef _Nullable CTFontManagerCreateFontDescriptorFromData( - CFDataRef data ) __attribute__((availability(macosx,introduced=10.7))); -typedef uint32_t CTFontManagerScope; enum { - kCTFontManagerScopeNone = 0, - kCTFontManagerScopeProcess = 1, - kCTFontManagerScopeUser = 2, - kCTFontManagerScopeSession = 3 -}; -bool CTFontManagerRegisterFontsForURL( - CFURLRef fontURL, - CTFontManagerScope scope, - CFErrorRef * error ) __attribute__((availability(macosx,introduced=10.6))); -bool CTFontManagerUnregisterFontsForURL( - CFURLRef fontURL, - CTFontManagerScope scope, - CFErrorRef * error ) __attribute__((availability(macosx,introduced=10.6))); -bool CTFontManagerRegisterGraphicsFont( - CGFontRef font, - CFErrorRef * error ) __attribute__((availability(macosx,introduced=10.8))); -bool CTFontManagerUnregisterGraphicsFont( - CGFontRef font, - CFErrorRef * error ) __attribute__((availability(macosx,introduced=10.8))); -bool CTFontManagerRegisterFontsForURLs( - CFArrayRef fontURLs, - CTFontManagerScope scope, - CFArrayRef _Nullable * _Nullable errors ) __attribute__((availability(macosx,introduced=10.6))); -bool CTFontManagerUnregisterFontsForURLs( - CFArrayRef fontURLs, - CTFontManagerScope scope, - CFArrayRef _Nullable * _Nullable errors ) __attribute__((availability(macosx,introduced=10.6))); -void CTFontManagerEnableFontDescriptors( - CFArrayRef descriptors, - bool enable ) __attribute__((availability(macosx,introduced=10.6))); -CTFontManagerScope CTFontManagerGetScopeForURL( - CFURLRef fontURL ) __attribute__((availability(macosx,introduced=10.6))); -bool CTFontManagerIsSupportedFont( - CFURLRef fontURL ) __attribute__((availability(macosx,introduced=10.6))); -CFRunLoopSourceRef _Nullable CTFontManagerCreateFontRequestRunLoopSource( - CFIndex sourceOrder, - CFArrayRef (*createMatchesCallback)(CFDictionaryRef requestAttributes, pid_t requestingProcess)) __attribute__((availability(macosx,introduced=10.6))); - - - - - - - -extern const CFStringRef kCTFontManagerBundleIdentifier __attribute__((availability(macosx,introduced=10.6))); -typedef uint32_t CTFontManagerAutoActivationSetting; enum { - kCTFontManagerAutoActivationDefault = 0, - kCTFontManagerAutoActivationDisabled = 1, - kCTFontManagerAutoActivationEnabled = 2, - kCTFontManagerAutoActivationPromptUser = 3 -}; -void CTFontManagerSetAutoActivationSetting( - CFStringRef _Nullable bundleIdentifier, - CTFontManagerAutoActivationSetting setting ) __attribute__((availability(macosx,introduced=10.6))); -CTFontManagerAutoActivationSetting CTFontManagerGetAutoActivationSetting( - CFStringRef _Nullable bundleIdentifier ) __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kCTFontManagerRegisteredFontsChangedNotification __attribute__((availability(macosx,introduced=10.6))); - - -} - -extern "C" { - - - - - - -typedef const struct __attribute__((objc_bridge(id))) __CTFrame * CTFrameRef; - - - - - - - -CFTypeID CTFrameGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -typedef uint32_t CTFrameProgression; enum { - kCTFrameProgressionTopToBottom = 0, - kCTFrameProgressionRightToLeft = 1, - kCTFrameProgressionLeftToRight = 2 -}; -extern const CFStringRef kCTFrameProgressionAttributeName __attribute__((availability(macosx,introduced=10.5))); -typedef uint32_t CTFramePathFillRule; enum { - kCTFramePathFillEvenOdd = 0, - kCTFramePathFillWindingNumber = 1 -}; -extern const CFStringRef kCTFramePathFillRuleAttributeName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kCTFramePathWidthAttributeName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kCTFrameClippingPathsAttributeName __attribute__((availability(macosx,introduced=10.7))); -extern const CFStringRef kCTFramePathClippingPathAttributeName __attribute__((availability(macosx,introduced=10.7))); -CFRange CTFrameGetStringRange( - CTFrameRef frame ) __attribute__((availability(macosx,introduced=10.5))); -CFRange CTFrameGetVisibleStringRange( - CTFrameRef frame ) __attribute__((availability(macosx,introduced=10.5))); -CGPathRef CTFrameGetPath( - CTFrameRef frame ) __attribute__((availability(macosx,introduced=10.5))); -CFDictionaryRef _Nullable CTFrameGetFrameAttributes( - CTFrameRef frame ) __attribute__((availability(macosx,introduced=10.5))); -CFArrayRef CTFrameGetLines( - CTFrameRef frame ) __attribute__((availability(macosx,introduced=10.5))); -void CTFrameGetLineOrigins( - CTFrameRef frame, - CFRange range, - CGPoint origins[] ) __attribute__((availability(macosx,introduced=10.5))); -void CTFrameDraw( - CTFrameRef frame, - CGContextRef context ) __attribute__((availability(macosx,introduced=10.5))); - - - -} -extern "C" { - - - - - - -typedef const struct __attribute__((objc_bridge(id))) __CTLine * CTLineRef; -typedef CFOptionFlags CTLineBoundsOptions; enum { - kCTLineBoundsExcludeTypographicLeading = 1 << 0, - kCTLineBoundsExcludeTypographicShifts = 1 << 1, - kCTLineBoundsUseHangingPunctuation = 1 << 2, - kCTLineBoundsUseGlyphPathBounds = 1 << 3, - kCTLineBoundsUseOpticalBounds = 1 << 4, - kCTLineBoundsIncludeLanguageExtents __attribute__((availability(macosx,introduced=10.11))) = 1 << 5, -}; -typedef uint32_t CTLineTruncationType; enum { - kCTLineTruncationStart = 0, - kCTLineTruncationEnd = 1, - kCTLineTruncationMiddle = 2 -}; - - - - - - - -CFTypeID CTLineGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -CTLineRef CTLineCreateWithAttributedString( - CFAttributedStringRef attrString ) __attribute__((availability(macosx,introduced=10.5))); -CTLineRef _Nullable CTLineCreateTruncatedLine( - CTLineRef line, - double width, - CTLineTruncationType truncationType, - CTLineRef _Nullable truncationToken ) __attribute__((availability(macosx,introduced=10.5))); -CTLineRef _Nullable CTLineCreateJustifiedLine( - CTLineRef line, - CGFloat justificationFactor, - double justificationWidth ) __attribute__((availability(macosx,introduced=10.5))); -CFIndex CTLineGetGlyphCount( - CTLineRef line ) __attribute__((availability(macosx,introduced=10.5))); -CFArrayRef CTLineGetGlyphRuns( - CTLineRef line ) __attribute__((availability(macosx,introduced=10.5))); -CFRange CTLineGetStringRange( - CTLineRef line ) __attribute__((availability(macosx,introduced=10.5))); -double CTLineGetPenOffsetForFlush( - CTLineRef line, - CGFloat flushFactor, - double flushWidth ) __attribute__((availability(macosx,introduced=10.5))); -void CTLineDraw( - CTLineRef line, - CGContextRef context ) __attribute__((availability(macosx,introduced=10.5))); -double CTLineGetTypographicBounds( - CTLineRef line, - CGFloat * _Nullable ascent, - CGFloat * _Nullable descent, - CGFloat * _Nullable leading ) __attribute__((availability(macosx,introduced=10.5))); -CGRect CTLineGetBoundsWithOptions( - CTLineRef line, - CTLineBoundsOptions options ) __attribute__((availability(macosx,introduced=10.8))); -double CTLineGetTrailingWhitespaceWidth( - CTLineRef line ) __attribute__((availability(macosx,introduced=10.5))); -CGRect CTLineGetImageBounds( - CTLineRef line, - CGContextRef _Nullable context ) __attribute__((availability(macosx,introduced=10.5))); -CFIndex CTLineGetStringIndexForPosition( - CTLineRef line, - CGPoint position ) __attribute__((availability(macosx,introduced=10.5))); -CGFloat CTLineGetOffsetForStringIndex( - CTLineRef line, - CFIndex charIndex, - CGFloat * _Nullable secondaryOffset ) __attribute__((availability(macosx,introduced=10.5))); -void CTLineEnumerateCaretOffsets( - CTLineRef line, - void (*block)(double offset, CFIndex charIndex, bool leadingEdge, bool* stop) ) __attribute__((availability(macosx,introduced=10.11))); - - - - - -} - - -extern "C" { - - - - - - -typedef const struct __attribute__((objc_bridge(id))) __CTTypesetter * CTTypesetterRef; - - - - - - - -CFTypeID CTTypesetterGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTTypesetterOptionDisableBidiProcessing __attribute__((availability(macosx,introduced=10.5,deprecated=10.8))); -extern const CFStringRef kCTTypesetterOptionForcedEmbeddingLevel __attribute__((availability(macosx,introduced=10.5))); -CTTypesetterRef CTTypesetterCreateWithAttributedString( - CFAttributedStringRef string ) __attribute__((availability(macosx,introduced=10.5))); -CTTypesetterRef CTTypesetterCreateWithAttributedStringAndOptions( - CFAttributedStringRef string, - CFDictionaryRef _Nullable options ) __attribute__((availability(macosx,introduced=10.5))); -CTLineRef CTTypesetterCreateLineWithOffset( - CTTypesetterRef typesetter, - CFRange stringRange, - double offset ) __attribute__((availability(macosx,introduced=10.6))); - - - - - - -CTLineRef CTTypesetterCreateLine( - CTTypesetterRef typesetter, - CFRange stringRange ) __attribute__((availability(macosx,introduced=10.5))); -CFIndex CTTypesetterSuggestLineBreakWithOffset( - CTTypesetterRef typesetter, - CFIndex startIndex, - double width, - double offset ) __attribute__((availability(macosx,introduced=10.6))); - - - - - - -CFIndex CTTypesetterSuggestLineBreak( - CTTypesetterRef typesetter, - CFIndex startIndex, - double width ) __attribute__((availability(macosx,introduced=10.5))); -CFIndex CTTypesetterSuggestClusterBreakWithOffset( - CTTypesetterRef typesetter, - CFIndex startIndex, - double width, - double offset ) __attribute__((availability(macosx,introduced=10.6))); - - - - - - - -CFIndex CTTypesetterSuggestClusterBreak( - CTTypesetterRef typesetter, - CFIndex startIndex, - double width ) __attribute__((availability(macosx,introduced=10.5))); - - - -} - - -extern "C" { - - - - - - -typedef const struct __attribute__((objc_bridge(id))) __CTFramesetter * CTFramesetterRef; - - - - - - - -CFTypeID CTFramesetterGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -CTFramesetterRef CTFramesetterCreateWithAttributedString( - CFAttributedStringRef string ) __attribute__((availability(macosx,introduced=10.5))); -CTFrameRef CTFramesetterCreateFrame( - CTFramesetterRef framesetter, - CFRange stringRange, - CGPathRef path, - CFDictionaryRef _Nullable frameAttributes ) __attribute__((availability(macosx,introduced=10.5))); -CTTypesetterRef CTFramesetterGetTypesetter( - CTFramesetterRef framesetter ) __attribute__((availability(macosx,introduced=10.5))); -CGSize CTFramesetterSuggestFrameSizeWithConstraints( - CTFramesetterRef framesetter, - CFRange stringRange, - CFDictionaryRef _Nullable frameAttributes, - CGSize constraints, - CFRange * _Nullable fitRange ) __attribute__((availability(macosx,introduced=10.5))); - - - -} -extern "C" { -typedef const struct __attribute__((objc_bridge(NSGlyphInfo))) __CTGlyphInfo * CTGlyphInfoRef; - - - - - - - -CFTypeID CTGlyphInfoGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -typedef uint16_t CTCharacterCollection; enum { - kCTCharacterCollectionIdentityMapping __attribute__((availability(macosx,introduced=10.8))) = 0, - kCTCharacterCollectionAdobeCNS1 __attribute__((availability(macosx,introduced=10.8))) = 1, - kCTCharacterCollectionAdobeGB1 __attribute__((availability(macosx,introduced=10.8))) = 2, - kCTCharacterCollectionAdobeJapan1 __attribute__((availability(macosx,introduced=10.8))) = 3, - kCTCharacterCollectionAdobeJapan2 __attribute__((availability(macosx,introduced=10.8))) = 4, - kCTCharacterCollectionAdobeKorea1 __attribute__((availability(macosx,introduced=10.8))) = 5, - - kCTIdentityMappingCharacterCollection __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTCharacterCollectionIdentityMapping, - kCTAdobeCNS1CharacterCollection __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTCharacterCollectionAdobeCNS1, - kCTAdobeGB1CharacterCollection __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTCharacterCollectionAdobeGB1, - kCTAdobeJapan1CharacterCollection __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTCharacterCollectionAdobeJapan1, - kCTAdobeJapan2CharacterCollection __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTCharacterCollectionAdobeJapan2, - kCTAdobeKorea1CharacterCollection __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTCharacterCollectionAdobeKorea1 -}; -CTGlyphInfoRef CTGlyphInfoCreateWithGlyphName( - CFStringRef glyphName, - CTFontRef font, - CFStringRef baseString ) __attribute__((availability(macosx,introduced=10.5))); -CTGlyphInfoRef CTGlyphInfoCreateWithGlyph( - CGGlyph glyph, - CTFontRef font, - CFStringRef baseString ) __attribute__((availability(macosx,introduced=10.5))); -CTGlyphInfoRef CTGlyphInfoCreateWithCharacterIdentifier( - CGFontIndex cid, - CTCharacterCollection collection, - CFStringRef baseString ) __attribute__((availability(macosx,introduced=10.5))); -CFStringRef _Nullable CTGlyphInfoGetGlyphName( - CTGlyphInfoRef glyphInfo ) __attribute__((availability(macosx,introduced=10.5))); -CGFontIndex CTGlyphInfoGetCharacterIdentifier( - CTGlyphInfoRef glyphInfo ) __attribute__((availability(macosx,introduced=10.5))); -CTCharacterCollection CTGlyphInfoGetCharacterCollection( - CTGlyphInfoRef glyphInfo ) __attribute__((availability(macosx,introduced=10.5))); - - - -} - -extern "C" { - - - - - - -typedef const struct __attribute__((objc_bridge_related(NSParagraphStyle,,))) __CTParagraphStyle * CTParagraphStyleRef; - - - - - - - -CFTypeID CTParagraphStyleGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -typedef uint8_t CTTextAlignment; enum { - kCTTextAlignmentLeft __attribute__((availability(macosx,introduced=10.8))) = 0, - kCTTextAlignmentRight __attribute__((availability(macosx,introduced=10.8))) = 1, - kCTTextAlignmentCenter __attribute__((availability(macosx,introduced=10.8))) = 2, - kCTTextAlignmentJustified __attribute__((availability(macosx,introduced=10.8))) = 3, - kCTTextAlignmentNatural __attribute__((availability(macosx,introduced=10.8))) = 4, - - kCTLeftTextAlignment __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTTextAlignmentLeft, - kCTRightTextAlignment __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTTextAlignmentRight, - kCTCenterTextAlignment __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTTextAlignmentCenter, - kCTJustifiedTextAlignment __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTTextAlignmentJustified, - kCTNaturalTextAlignment __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))) = kCTTextAlignmentNatural -}; -typedef uint8_t CTLineBreakMode; enum { - kCTLineBreakByWordWrapping = 0, - kCTLineBreakByCharWrapping = 1, - kCTLineBreakByClipping = 2, - kCTLineBreakByTruncatingHead = 3, - kCTLineBreakByTruncatingTail = 4, - kCTLineBreakByTruncatingMiddle = 5 -}; -typedef int8_t CTWritingDirection; enum { - kCTWritingDirectionNatural = -1, - kCTWritingDirectionLeftToRight = 0, - kCTWritingDirectionRightToLeft = 1 -}; -typedef uint32_t CTParagraphStyleSpecifier; enum { - kCTParagraphStyleSpecifierAlignment = 0, - kCTParagraphStyleSpecifierFirstLineHeadIndent = 1, - kCTParagraphStyleSpecifierHeadIndent = 2, - kCTParagraphStyleSpecifierTailIndent = 3, - kCTParagraphStyleSpecifierTabStops = 4, - kCTParagraphStyleSpecifierDefaultTabInterval = 5, - kCTParagraphStyleSpecifierLineBreakMode = 6, - kCTParagraphStyleSpecifierLineHeightMultiple = 7, - kCTParagraphStyleSpecifierMaximumLineHeight = 8, - kCTParagraphStyleSpecifierMinimumLineHeight = 9, - kCTParagraphStyleSpecifierLineSpacing = 10, - kCTParagraphStyleSpecifierParagraphSpacing = 11, - kCTParagraphStyleSpecifierParagraphSpacingBefore = 12, - kCTParagraphStyleSpecifierBaseWritingDirection = 13, - kCTParagraphStyleSpecifierMaximumLineSpacing = 14, - kCTParagraphStyleSpecifierMinimumLineSpacing = 15, - kCTParagraphStyleSpecifierLineSpacingAdjustment = 16, - kCTParagraphStyleSpecifierLineBoundsOptions = 17, - - kCTParagraphStyleSpecifierCount -}; -typedef struct CTParagraphStyleSetting -{ - CTParagraphStyleSpecifier spec; - size_t valueSize; - const void * value; - -} CTParagraphStyleSetting; -CTParagraphStyleRef CTParagraphStyleCreate( - const CTParagraphStyleSetting * _Nullable settings, - size_t settingCount ) __attribute__((availability(macosx,introduced=10.5))); -CTParagraphStyleRef CTParagraphStyleCreateCopy( - CTParagraphStyleRef paragraphStyle ) __attribute__((availability(macosx,introduced=10.5))); -bool CTParagraphStyleGetValueForSpecifier( - CTParagraphStyleRef paragraphStyle, - CTParagraphStyleSpecifier spec, - size_t valueBufferSize, - void * valueBuffer ) __attribute__((availability(macosx,introduced=10.5))); - - - -} -extern "C" { - - - - - - -typedef const struct __attribute__((objc_bridge(id))) __CTRubyAnnotation * CTRubyAnnotationRef; - - - - - - - -CFTypeID CTRubyAnnotationGetTypeID( void ) __attribute__((availability(macosx,introduced=10.10))); -typedef uint8_t CTRubyAlignment; enum { - kCTRubyAlignmentInvalid = (uint8_t)-1, - kCTRubyAlignmentAuto = 0, - kCTRubyAlignmentStart = 1, - kCTRubyAlignmentCenter = 2, - kCTRubyAlignmentEnd = 3, - kCTRubyAlignmentDistributeLetter = 4, - kCTRubyAlignmentDistributeSpace = 5, - kCTRubyAlignmentLineEdge = 6 -} __attribute__((availability(macosx,introduced=10.10))); -typedef uint8_t CTRubyOverhang; enum { - kCTRubyOverhangInvalid = (uint8_t)-1, - kCTRubyOverhangAuto = 0, - kCTRubyOverhangStart = 1, - kCTRubyOverhangEnd = 2, - kCTRubyOverhangNone = 3 -} __attribute__((availability(macosx,introduced=10.10))); -typedef uint8_t CTRubyPosition; enum { - kCTRubyPositionBefore = 0, - kCTRubyPositionAfter = 1, - kCTRubyPositionInterCharacter = 2, - kCTRubyPositionInline = 3, - kCTRubyPositionCount -} __attribute__((availability(macosx,introduced=10.10))); -CTRubyAnnotationRef CTRubyAnnotationCreate( - CTRubyAlignment alignment, - CTRubyOverhang overhang, - CGFloat sizeFactor, - CFStringRef text[kCTRubyPositionCount] ) __attribute__((availability(macosx,introduced=10.10))); -CTRubyAnnotationRef CTRubyAnnotationCreateCopy( - CTRubyAnnotationRef rubyAnnotation ) __attribute__((availability(macosx,introduced=10.10))); -CTRubyAlignment CTRubyAnnotationGetAlignment( - CTRubyAnnotationRef rubyAnnotation ) __attribute__((availability(macosx,introduced=10.10))); -CTRubyOverhang CTRubyAnnotationGetOverhang( - CTRubyAnnotationRef rubyAnnotation ) __attribute__((availability(macosx,introduced=10.10))); -CGFloat CTRubyAnnotationGetSizeFactor( - CTRubyAnnotationRef rubyAnnotation ) __attribute__((availability(macosx,introduced=10.10))); -CFStringRef _Nullable CTRubyAnnotationGetTextForPosition( - CTRubyAnnotationRef rubyAnnotation, - CTRubyPosition position ) __attribute__((availability(macosx,introduced=10.10))); - - - -} -extern "C" { - - - - - - -typedef const struct __attribute__((objc_bridge(id))) __CTRun * CTRunRef; -typedef uint32_t CTRunStatus; enum -{ - kCTRunStatusNoStatus = 0, - kCTRunStatusRightToLeft = (1 << 0), - kCTRunStatusNonMonotonic = (1 << 1), - kCTRunStatusHasNonIdentityMatrix = (1 << 2) -}; - - - - - - - -CFTypeID CTRunGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -CFIndex CTRunGetGlyphCount( - CTRunRef run ) __attribute__((availability(macosx,introduced=10.5))); -CFDictionaryRef CTRunGetAttributes( - CTRunRef run ) __attribute__((availability(macosx,introduced=10.5))); -CTRunStatus CTRunGetStatus( - CTRunRef run ) __attribute__((availability(macosx,introduced=10.5))); -const CGGlyph * _Nullable CTRunGetGlyphsPtr( - CTRunRef run ) __attribute__((availability(macosx,introduced=10.5))); -void CTRunGetGlyphs( - CTRunRef run, - CFRange range, - CGGlyph buffer[] ) __attribute__((availability(macosx,introduced=10.5))); -const CGPoint * _Nullable CTRunGetPositionsPtr( - CTRunRef run ) __attribute__((availability(macosx,introduced=10.5))); -void CTRunGetPositions( - CTRunRef run, - CFRange range, - CGPoint buffer[] ) __attribute__((availability(macosx,introduced=10.5))); -const CGSize * _Nullable CTRunGetAdvancesPtr( - CTRunRef run ) __attribute__((availability(macosx,introduced=10.5))); -void CTRunGetAdvances( - CTRunRef run, - CFRange range, - CGSize buffer[] ) __attribute__((availability(macosx,introduced=10.5))); -const CFIndex * _Nullable CTRunGetStringIndicesPtr( - CTRunRef run ) __attribute__((availability(macosx,introduced=10.5))); -void CTRunGetStringIndices( - CTRunRef run, - CFRange range, - CFIndex buffer[] ) __attribute__((availability(macosx,introduced=10.5))); -CFRange CTRunGetStringRange( - CTRunRef run ) __attribute__((availability(macosx,introduced=10.5))); -double CTRunGetTypographicBounds( - CTRunRef run, - CFRange range, - CGFloat * _Nullable ascent, - CGFloat * _Nullable descent, - CGFloat * _Nullable leading ) __attribute__((availability(macosx,introduced=10.5))); -CGRect CTRunGetImageBounds( - CTRunRef run, - CGContextRef _Nullable context, - CFRange range ) __attribute__((availability(macosx,introduced=10.5))); -CGAffineTransform CTRunGetTextMatrix( - CTRunRef run ) __attribute__((availability(macosx,introduced=10.5))); -void CTRunDraw( - CTRunRef run, - CGContextRef context, - CFRange range ) __attribute__((availability(macosx,introduced=10.5))); - - - -} -extern "C" { - - - - - - -typedef const struct __attribute__((objc_bridge(id))) __CTRunDelegate * CTRunDelegateRef; - - - - - - -CFTypeID CTRunDelegateGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -typedef void (*CTRunDelegateDeallocateCallback) ( - void * refCon ); -typedef CGFloat (*CTRunDelegateGetAscentCallback) ( - void * refCon ); -typedef CGFloat (*CTRunDelegateGetDescentCallback) ( - void * refCon ); -typedef CGFloat (*CTRunDelegateGetWidthCallback) ( - void * refCon ); -typedef struct -{ - CFIndex version; - CTRunDelegateDeallocateCallback dealloc; - CTRunDelegateGetAscentCallback getAscent; - CTRunDelegateGetDescentCallback getDescent; - CTRunDelegateGetWidthCallback getWidth; -} CTRunDelegateCallbacks; -enum { - kCTRunDelegateVersion1 = 1, - kCTRunDelegateCurrentVersion = kCTRunDelegateVersion1 -}; -CTRunDelegateRef _Nullable CTRunDelegateCreate( - const CTRunDelegateCallbacks* callbacks, - void * _Nullable refCon ) __attribute__((availability(macosx,introduced=10.5))); -void * CTRunDelegateGetRefCon( - CTRunDelegateRef runDelegate ) __attribute__((availability(macosx,introduced=10.5))); - - - -} -extern "C" { -extern const CFStringRef kCTFontAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTForegroundColorFromContextAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTKernAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTLigatureAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTForegroundColorAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTParagraphStyleAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTStrokeWidthAttributeName __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kCTStrokeColorAttributeName __attribute__((availability(macosx,introduced=10.6))); -extern const CFStringRef kCTUnderlineStyleAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTSuperscriptAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTUnderlineColorAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTVerticalFormsAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTGlyphInfoAttributeName __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTCharacterShapeAttributeName __attribute__((availability(macosx,introduced=10.5,deprecated=10.11))); -extern const CFStringRef kCTLanguageAttributeName __attribute__((availability(macosx,introduced=10.9))); -extern const CFStringRef kCTRunDelegateAttributeName __attribute__((availability(macosx,introduced=10.5))); -typedef int32_t CTUnderlineStyle; enum { - kCTUnderlineStyleNone = 0x00, - kCTUnderlineStyleSingle = 0x01, - kCTUnderlineStyleThick = 0x02, - kCTUnderlineStyleDouble = 0x09 -}; -typedef int32_t CTUnderlineStyleModifiers; enum { - kCTUnderlinePatternSolid = 0x0000, - kCTUnderlinePatternDot = 0x0100, - kCTUnderlinePatternDash = 0x0200, - kCTUnderlinePatternDashDot = 0x0300, - kCTUnderlinePatternDashDotDot = 0x0400 -}; -extern const CFStringRef kCTBaselineClassAttributeName __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTBaselineInfoAttributeName __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTBaselineReferenceInfoAttributeName __attribute__((availability(macosx,introduced=10.8))); -extern const CFStringRef kCTWritingDirectionAttributeName __attribute__((availability(macosx,introduced=10.8))); -enum { - kCTWritingDirectionEmbedding = (0 << 1), - kCTWritingDirectionOverride = (1 << 1) -}; -extern const CFStringRef kCTRubyAnnotationAttributeName __attribute__((availability(macosx,introduced=10.10))); - - - -} -extern "C" { -typedef const struct __attribute__((objc_bridge_related(NSTextTab,,))) __CTTextTab * CTTextTabRef; - - - - - - - -CFTypeID CTTextTabGetTypeID( void ) __attribute__((availability(macosx,introduced=10.5))); -extern const CFStringRef kCTTabColumnTerminatorsAttributeName __attribute__((availability(macosx,introduced=10.5))); -CTTextTabRef CTTextTabCreate( - CTTextAlignment alignment, - double location, - CFDictionaryRef _Nullable options ) __attribute__((availability(macosx,introduced=10.5))); -CTTextAlignment CTTextTabGetAlignment( - CTTextTabRef tab ) __attribute__((availability(macosx,introduced=10.5))); -double CTTextTabGetLocation( - CTTextTabRef tab ) __attribute__((availability(macosx,introduced=10.5))); -CFDictionaryRef _Nullable CTTextTabGetOptions( - CTTextTabRef tab ) __attribute__((availability(macosx,introduced=10.5))); - - - -} - - - - -extern "C" { -uint32_t CTGetCoreTextVersion( void ) __attribute__((availability(macosx,introduced=10.5))); -} - - - -extern "C" { -} -extern "C" { - - - - -#pragma pack(push, 2) - - -enum { - cmICCProfileVersion4 = 0x04000000, - cmICCProfileVersion2 = 0x02000000, - cmICCProfileVersion21 = 0x02100000, - cmCS2ProfileVersion = cmICCProfileVersion2, - cmCS1ProfileVersion = 0x00000100 -}; - - -enum { - cmProfileMajorVersionMask = (int)0xFF000000, - cmCurrentProfileMajorVersion = 0x02000000 -}; - - -enum { - cmMagicNumber = 'acsp' -}; - - - - - - -enum { - cmICCReservedFlagsMask = 0x0000FFFF, - cmEmbeddedMask = 0x00000001, - cmEmbeddedUseMask = 0x00000002, - cmBlackPointCompensationMask = 0x00000004, - cmCMSReservedFlagsMask = (int)0xFFFF0000, - cmQualityMask = 0x00030000, - cmInterpolationMask = 0x00040000, - cmGamutCheckingMask = 0x00080000 -}; - - -enum { - cmEmbeddedProfile = 0, - cmEmbeddedUse = 1 -}; - - -enum { - cmNormalMode = 0, - cmDraftMode = 1, - cmBestMode = 2 -}; - - -enum { - cmBlackPointCompensation = 1 -}; - - - - - - -enum { - cmReflectiveTransparentMask = 0x00000001, - cmGlossyMatteMask = 0x00000002 -}; - - -enum { - cmReflective = 0, - cmGlossy = 1 -}; - - - -enum { - cmPerceptual = 0, - cmRelativeColorimetric = 1, - cmSaturation = 2, - cmAbsoluteColorimetric = 3 -}; - - - - -enum { - cmAsciiData = 0, - cmBinaryData = 1 -}; - - -enum { - cmPrtrDefaultScreens = 0, - cmLinesPer = 1 -}; - - -enum { - cmNumHeaderElements = 10 -}; - - -enum { - cmAToB0Tag = 'A2B0', - cmAToB1Tag = 'A2B1', - cmAToB2Tag = 'A2B2', - cmBlueColorantTag = 'bXYZ', - cmBlueTRCTag = 'bTRC', - cmBToA0Tag = 'B2A0', - cmBToA1Tag = 'B2A1', - cmBToA2Tag = 'B2A2', - cmCalibrationDateTimeTag = 'calt', - cmChromaticAdaptationTag = 'chad', - cmCharTargetTag = 'targ', - cmCopyrightTag = 'cprt', - cmDeviceMfgDescTag = 'dmnd', - cmDeviceModelDescTag = 'dmdd', - cmGamutTag = 'gamt', - cmGrayTRCTag = 'kTRC', - cmGreenColorantTag = 'gXYZ', - cmGreenTRCTag = 'gTRC', - cmLuminanceTag = 'lumi', - cmMeasurementTag = 'meas', - cmMediaBlackPointTag = 'bkpt', - cmMediaWhitePointTag = 'wtpt', - cmNamedColorTag = 'ncol', - cmNamedColor2Tag = 'ncl2', - cmPreview0Tag = 'pre0', - cmPreview1Tag = 'pre1', - cmPreview2Tag = 'pre2', - cmProfileDescriptionTag = 'desc', - cmProfileSequenceDescTag = 'pseq', - cmPS2CRD0Tag = 'psd0', - cmPS2CRD1Tag = 'psd1', - cmPS2CRD2Tag = 'psd2', - cmPS2CRD3Tag = 'psd3', - cmPS2CSATag = 'ps2s', - cmPS2RenderingIntentTag = 'ps2i', - cmRedColorantTag = 'rXYZ', - cmRedTRCTag = 'rTRC', - cmScreeningDescTag = 'scrd', - cmScreeningTag = 'scrn', - cmTechnologyTag = 'tech', - cmUcrBgTag = 'bfd ', - cmViewingConditionsDescTag = 'vued', - cmViewingConditionsTag = 'view' -}; - - -enum { - cmPS2CRDVMSizeTag = 'psvm', - cmVideoCardGammaTag = 'vcgt', - cmMakeAndModelTag = 'mmod', - cmProfileDescriptionMLTag = 'dscm', - cmNativeDisplayInfoTag = 'ndin' -}; - - -enum { - cmSigCrdInfoType = 'crdi', - cmSigCurveType = 'curv', - cmSigDataType = 'data', - cmSigDateTimeType = 'dtim', - cmSigLut16Type = 'mft2', - cmSigLut8Type = 'mft1', - cmSigMeasurementType = 'meas', - cmSigMultiFunctA2BType = 'mAB ', - cmSigMultiFunctB2AType = 'mBA ', - cmSigNamedColorType = 'ncol', - cmSigNamedColor2Type = 'ncl2', - cmSigParametricCurveType = 'para', - cmSigProfileDescriptionType = 'desc', - cmSigProfileSequenceDescType = 'pseq', - cmSigScreeningType = 'scrn', - cmSigS15Fixed16Type = 'sf32', - cmSigSignatureType = 'sig ', - cmSigTextType = 'text', - cmSigU16Fixed16Type = 'uf32', - cmSigU1Fixed15Type = 'uf16', - cmSigUInt8Type = 'ui08', - cmSigUInt16Type = 'ui16', - cmSigUInt32Type = 'ui32', - cmSigUInt64Type = 'ui64', - cmSigUcrBgType = 'bfd ', - cmSigUnicodeTextType = 'utxt', - cmSigViewingConditionsType = 'view', - cmSigXYZType = 'XYZ ' -}; - - -enum { - cmSigPS2CRDVMSizeType = 'psvm', - cmSigVideoCardGammaType = 'vcgt', - cmSigMakeAndModelType = 'mmod', - cmSigNativeDisplayInfoType = 'ndin', - cmSigMultiLocalizedUniCodeType = 'mluc' -}; - - - -enum { - cmTechnologyDigitalCamera = 'dcam', - cmTechnologyFilmScanner = 'fscn', - cmTechnologyReflectiveScanner = 'rscn', - cmTechnologyInkJetPrinter = 'ijet', - cmTechnologyThermalWaxPrinter = 'twax', - cmTechnologyElectrophotographicPrinter = 'epho', - cmTechnologyElectrostaticPrinter = 'esta', - cmTechnologyDyeSublimationPrinter = 'dsub', - cmTechnologyPhotographicPaperPrinter = 'rpho', - cmTechnologyFilmWriter = 'fprn', - cmTechnologyVideoMonitor = 'vidm', - cmTechnologyVideoCamera = 'vidc', - cmTechnologyProjectionTelevision = 'pjtv', - cmTechnologyCRTDisplay = 'CRT ', - cmTechnologyPMDisplay = 'PMD ', - cmTechnologyAMDisplay = 'AMD ', - cmTechnologyPhotoCD = 'KPCD', - cmTechnologyPhotoImageSetter = 'imgs', - cmTechnologyGravure = 'grav', - cmTechnologyOffsetLithography = 'offs', - cmTechnologySilkscreen = 'silk', - cmTechnologyFlexography = 'flex' -}; - - - - -enum { - cmFlare0 = 0x00000000, - cmFlare100 = 0x00000001 -}; - - -enum { - cmGeometryUnknown = 0x00000000, - cmGeometry045or450 = 0x00000001, - cmGeometry0dord0 = 0x00000002 -}; - - -enum { - cmStdobsUnknown = 0x00000000, - cmStdobs1931TwoDegrees = 0x00000001, - cmStdobs1964TenDegrees = 0x00000002 -}; - - -enum { - cmIlluminantUnknown = 0x00000000, - cmIlluminantD50 = 0x00000001, - cmIlluminantD65 = 0x00000002, - cmIlluminantD93 = 0x00000003, - cmIlluminantF2 = 0x00000004, - cmIlluminantD55 = 0x00000005, - cmIlluminantA = 0x00000006, - cmIlluminantEquiPower = 0x00000007, - cmIlluminantF8 = 0x00000008 -}; - - -enum { - cmSpotFunctionUnknown = 0, - cmSpotFunctionDefault = 1, - cmSpotFunctionRound = 2, - cmSpotFunctionDiamond = 3, - cmSpotFunctionEllipse = 4, - cmSpotFunctionLine = 5, - cmSpotFunctionSquare = 6, - cmSpotFunctionCross = 7 -}; - - -enum { - cmXYZData = 'XYZ ', - cmLabData = 'Lab ', - cmLuvData = 'Luv ', - cmYCbCrData = 'YCbr', - cmYxyData = 'Yxy ', - cmRGBData = 'RGB ', - cmSRGBData = 'sRGB', - cmGrayData = 'GRAY', - cmHSVData = 'HSV ', - cmHLSData = 'HLS ', - cmCMYKData = 'CMYK', - cmCMYData = 'CMY ', - cmMCH5Data = 'MCH5', - cmMCH6Data = 'MCH6', - cmMCH7Data = 'MCH7', - cmMCH8Data = 'MCH8', - cm3CLRData = '3CLR', - cm4CLRData = '4CLR', - cm5CLRData = '5CLR', - cm6CLRData = '6CLR', - cm7CLRData = '7CLR', - cm8CLRData = '8CLR', - cm9CLRData = '9CLR', - cm10CLRData = 'ACLR', - cm11CLRData = 'BCLR', - cm12CLRData = 'CCLR', - cm13CLRData = 'DCLR', - cm14CLRData = 'ECLR', - cm15CLRData = 'FCLR', - cmNamedData = 'NAME' -}; - - -enum { - cmInputClass = 'scnr', - cmDisplayClass = 'mntr', - cmOutputClass = 'prtr', - cmLinkClass = 'link', - cmAbstractClass = 'abst', - cmColorSpaceClass = 'spac', - cmNamedColorClass = 'nmcl' -}; - - -enum { - cmMacintosh = 'APPL', - cmMicrosoft = 'MSFT', - cmSolaris = 'SUNW', - cmSiliconGraphics = 'SGI ', - cmTaligent = 'TGNT' -}; - - -enum { - cmParametricType0 = 0, - cmParametricType1 = 1, - cmParametricType2 = 2, - cmParametricType3 = 3, - cmParametricType4 = 4 -}; - - - -enum { - cmCS1ChromTag = 'chrm', - cmCS1TRCTag = 'trc ', - cmCS1NameTag = 'name', - cmCS1CustTag = 'cust' -}; - - -typedef struct CMDateTime { - UInt16 year; - UInt16 month; - UInt16 dayOfTheMonth; - UInt16 hours; - UInt16 minutes; - UInt16 seconds; -} CMDateTime __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMFixedXYColor { - Fixed x; - Fixed y; -} CMFixedXYColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMFixedXYZColor { - Fixed X; - Fixed Y; - Fixed Z; -} CMFixedXYZColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef UInt16 CMXYZComponent; - -typedef struct CMXYZColor { - CMXYZComponent X; - CMXYZComponent Y; - CMXYZComponent Z; -} CMXYZColor; - - - - -typedef unsigned char CMProfileMD5[16] __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -typedef CMProfileMD5 * CMProfileMD5Ptr __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - - - - - inline Boolean CMProfileMD5AreEqual(CMProfileMD5 a, CMProfileMD5 b) - { - return ((UInt32*)a)[0]==((UInt32*)b)[0] && ((UInt32*)a)[1]==((UInt32*)b)[1] && - ((UInt32*)a)[2]==((UInt32*)b)[2] && ((UInt32*)a)[3]==((UInt32*)b)[3]; - } - - - - - - -typedef struct CM2Header { - UInt32 size; - OSType CMMType; - UInt32 profileVersion; - OSType profileClass; - OSType dataColorSpace; - OSType profileConnectionSpace; - CMDateTime dateTime; - OSType CS2profileSignature; - OSType platform; - UInt32 flags; - OSType deviceManufacturer; - UInt32 deviceModel; - UInt32 deviceAttributes[2]; - UInt32 renderingIntent; - CMFixedXYZColor white; - OSType creator; - char reserved[44]; -} CM2Header __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CM4Header { - UInt32 size; - OSType CMMType; - UInt32 profileVersion; - OSType profileClass; - OSType dataColorSpace; - OSType profileConnectionSpace; - CMDateTime dateTime; - OSType CS2profileSignature; - OSType platform; - UInt32 flags; - OSType deviceManufacturer; - UInt32 deviceModel; - UInt32 deviceAttributes[2]; - UInt32 renderingIntent; - CMFixedXYZColor white; - OSType creator; - CMProfileMD5 digest; - char reserved[28]; -} CM4Header __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMTagRecord { - OSType tag; - UInt32 elementOffset; - UInt32 elementSize; -} CMTagRecord __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMTagElemTable { - UInt32 count; - CMTagRecord tagList[1]; -} CMTagElemTable __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CM2Profile { - CM2Header header; - CMTagElemTable tagTable; - char elemData[1]; -} CM2Profile, *CM2ProfilePtr, **CM2ProfileHandle __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - -typedef struct CMAdaptationMatrixType { - OSType typeDescriptor; - UInt32 reserved; - Fixed adaptationMatrix[9]; -} CMAdaptationMatrixType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMCurveType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 countValue; - UInt16 data[1]; -} CMCurveType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMDataType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 dataFlag; - char data[1]; -} CMDataType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMDateTimeType { - OSType typeDescriptor; - UInt32 reserved; - CMDateTime dateTime; -} CMDateTimeType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMLut16Type { - OSType typeDescriptor; - UInt32 reserved; - UInt8 inputChannels; - UInt8 outputChannels; - UInt8 gridPoints; - UInt8 reserved2; - Fixed matrix[3][3]; - UInt16 inputTableEntries; - UInt16 outputTableEntries; - UInt16 inputTable[1]; -} CMLut16Type __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMLut8Type { - OSType typeDescriptor; - UInt32 reserved; - UInt8 inputChannels; - UInt8 outputChannels; - UInt8 gridPoints; - UInt8 reserved2; - Fixed matrix[3][3]; - UInt8 inputTable[1]; -} CMLut8Type __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMultiFunctLutType { - OSType typeDescriptor; - UInt32 reserved; - UInt8 inputChannels; - UInt8 outputChannels; - UInt16 reserved2; - UInt32 offsetBcurves; - UInt32 offsetMatrix; - UInt32 offsetMcurves; - UInt32 offsetCLUT; - UInt32 offsetAcurves; - UInt8 data[1]; -} CMMultiFunctLutType, CMMultiFunctLutA2BType, CMMultiFunctLutB2AType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMultiFunctCLUTType { - UInt8 gridPoints[16]; - UInt8 entrySize; - UInt8 reserved[3]; - UInt8 data[2]; -} CMMultiFunctCLUTType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMeasurementType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 standardObserver; - CMFixedXYZColor backingXYZ; - UInt32 geometry; - UInt32 flare; - UInt32 illuminant; -} CMMeasurementType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMNamedColorType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 vendorFlag; - UInt32 count; - UInt8 prefixName[1]; -} CMNamedColorType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMNamedColor2EntryType { - UInt8 rootName[32]; - UInt16 PCSColorCoords[3]; - UInt16 DeviceColorCoords[1]; -} CMNamedColor2EntryType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMNamedColor2Type { - OSType typeDescriptor; - UInt32 reserved; - UInt32 vendorFlag; - UInt32 count; - UInt32 deviceChannelCount; - UInt8 prefixName[32]; - UInt8 suffixName[32]; - char data[1]; -} CMNamedColor2Type __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMNativeDisplayInfo { - UInt32 dataSize; - CMFixedXYColor redPhosphor; - CMFixedXYColor greenPhosphor; - CMFixedXYColor bluePhosphor; - CMFixedXYColor whitePoint; - Fixed redGammaValue; - Fixed greenGammaValue; - Fixed blueGammaValue; - - - - UInt16 gammaChannels; - UInt16 gammaEntryCount; - UInt16 gammaEntrySize; - char gammaData[1]; -} CMNativeDisplayInfo __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMNativeDisplayInfoType { - OSType typeDescriptor; - UInt32 reserved; - CMNativeDisplayInfo nativeDisplayInfo; -} CMNativeDisplayInfoType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMParametricCurveType { - OSType typeDescriptor; - UInt32 reserved; - UInt16 functionType; - UInt16 reserved2; - Fixed value[1]; -} CMParametricCurveType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMTextDescriptionType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 ASCIICount; - UInt8 ASCIIName[2]; -} CMTextDescriptionType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMTextType { - OSType typeDescriptor; - UInt32 reserved; - UInt8 text[1]; -} CMTextType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMUnicodeTextType { - OSType typeDescriptor; - UInt32 reserved; - UniChar text[1]; -} CMUnicodeTextType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMScreeningChannelRec { - Fixed frequency; - Fixed angle; - UInt32 spotFunction; -} CMScreeningChannelRec __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMScreeningType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 screeningFlag; - UInt32 channelCount; - CMScreeningChannelRec channelInfo[1]; -} CMScreeningType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMSignatureType { - OSType typeDescriptor; - UInt32 reserved; - OSType signature; -} CMSignatureType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMS15Fixed16ArrayType { - OSType typeDescriptor; - UInt32 reserved; - Fixed value[1]; -} CMS15Fixed16ArrayType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMU16Fixed16ArrayType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 value[1]; -} CMU16Fixed16ArrayType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMUInt8ArrayType { - OSType typeDescriptor; - UInt32 reserved; - UInt8 value[1]; -} CMUInt8ArrayType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMUInt16ArrayType { - OSType typeDescriptor; - UInt32 reserved; - UInt16 value[1]; -} CMUInt16ArrayType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMUInt32ArrayType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 value[1]; -} CMUInt32ArrayType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMUInt64ArrayType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 value[1]; -} CMUInt64ArrayType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMViewingConditionsType { - OSType typeDescriptor; - UInt32 reserved; - CMFixedXYZColor illuminant; - CMFixedXYZColor surround; - UInt32 stdIlluminant; -} CMViewingConditionsType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMXYZType { - OSType typeDescriptor; - UInt32 reserved; - CMFixedXYZColor XYZ[1]; -} CMXYZType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMProfileSequenceDescType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 count; - char data[1]; -} CMProfileSequenceDescType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMUcrBgType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 ucrCount; - UInt16 ucrValues[1]; -} CMUcrBgType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - - -typedef struct CMIntentCRDVMSize { - UInt32 renderingIntent; - UInt32 VMSize; -} CMIntentCRDVMSize __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMPS2CRDVMSizeType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 count; - CMIntentCRDVMSize intentCRD[1]; -} CMPS2CRDVMSizeType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - -enum { - cmVideoCardGammaTableType = 0, - cmVideoCardGammaFormulaType = 1 -}; - -typedef struct CMVideoCardGammaTable { - UInt16 channels; - UInt16 entryCount; - UInt16 entrySize; - char data[1]; -} CMVideoCardGammaTable __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMVideoCardGammaFormula { - Fixed redGamma; - Fixed redMin; - Fixed redMax; - Fixed greenGamma; - Fixed greenMin; - Fixed greenMax; - Fixed blueGamma; - Fixed blueMin; - Fixed blueMax; -} CMVideoCardGammaFormula __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMVideoCardGamma { - UInt32 tagType; - union { - CMVideoCardGammaTable table; - CMVideoCardGammaFormula formula; - } u; -} CMVideoCardGamma __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMVideoCardGammaType { - OSType typeDescriptor; - UInt32 reserved; - CMVideoCardGamma gamma; -} CMVideoCardGammaType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMakeAndModel { - OSType manufacturer; - UInt32 model; - UInt32 serialNumber; - UInt32 manufactureDate; - UInt32 reserved1; - UInt32 reserved2; - UInt32 reserved3; - UInt32 reserved4; -} CMMakeAndModel __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMakeAndModelType { - OSType typeDescriptor; - UInt32 reserved; - CMMakeAndModel makeAndModel; -} CMMakeAndModelType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMultiLocalizedUniCodeEntryRec { - char languageCode[2]; - char regionCode[2]; - UInt32 textLength; - UInt32 textOffset; -} CMMultiLocalizedUniCodeEntryRec __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMultiLocalizedUniCodeType { - OSType typeDescriptor; - UInt32 reserved; - UInt32 entryCount; - UInt32 entrySize; - - -} CMMultiLocalizedUniCodeType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -#pragma pack(pop) - - - - -typedef OSStatus CMError __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - -typedef struct OpaqueCMProfileRef* CMProfileRef __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -typedef struct OpaqueCMWorldRef* CMWorldRef __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - -typedef UInt32 CMDisplayIDType __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -typedef UInt32 CMChromaticAdaptation __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -enum { - cmUseDefaultChromaticAdaptation = 0, - cmLinearChromaticAdaptation = 1, - cmVonKriesChromaticAdaptation = 2, - cmBradfordChromaticAdaptation = 3 -}; - - - - -typedef OSErr ( * CMFlattenProcPtr)(SInt32 command, long *size, void *data, void *refCon); - -typedef CMFlattenProcPtr CMFlattenUPP; -typedef Boolean ( * CMBitmapCallBackProcPtr)(SInt32 progress, void *refCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef CMBitmapCallBackProcPtr CMBitmapCallBackUPP __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - -typedef Boolean ( * CMConcatCallBackProcPtr)(SInt32 progress, void *refCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef CMConcatCallBackProcPtr CMConcatCallBackUPP __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -} - - - - - -extern "C" { -enum { - kDefaultCMMSignature = 'appl' -}; -enum { - cmPS7bit = 1, - cmPS8bit = 2 -}; -enum { - cmOpenReadSpool = 1, - cmOpenWriteSpool = 2, - cmReadSpool = 3, - cmWriteSpool = 4, - cmCloseSpool = 5 -}; - - -enum { - cmOpenReadAccess = 1, - cmOpenWriteAccess = 2, - cmReadAccess = 3, - cmWriteAccess = 4, - cmCloseAccess = 5, - cmCreateNewAccess = 6, - cmAbortWriteAccess = 7, - cmBeginAccess = 8, - cmEndAccess = 9 -}; - - -enum { - cmInputUse = 'inpt', - cmOutputUse = 'outp', - cmDisplayUse = 'dply', - cmProofUse = 'pruf' -}; - - - -union CMAppleProfileHeader { - - - - CM2Header cm2; - CM4Header cm4; -}; -typedef union CMAppleProfileHeader CMAppleProfileHeader __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - -typedef struct CMConcatProfileSet { - UInt16 keyIndex; - UInt16 count; - CMProfileRef profileSet[1]; -} CMConcatProfileSet __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - -typedef struct NCMConcatProfileSpec { - UInt32 renderingIntent; - UInt32 transformTag; - CMProfileRef profile; -} NCMConcatProfileSpec __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct NCMConcatProfileSet { - OSType cmm; - UInt32 flags; - UInt32 flagsMask; - UInt32 profileCount; - NCMConcatProfileSpec profileSpecs[1]; -} NCMConcatProfileSet __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -enum { - kNoTransform = 0, - kUseAtoB = 1, - kUseBtoA = 2, - kUseBtoB = 3, - - kDeviceToPCS = kUseAtoB, - kPCSToDevice = kUseBtoA, - kPCSToPCS = kUseBtoB, - kUseProfileIntent = (int)0xFFFFFFFF -}; - - - -typedef struct CMRGBColor { - UInt16 red; - UInt16 green; - UInt16 blue; -} CMRGBColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMCMYKColor { - UInt16 cyan; - UInt16 magenta; - UInt16 yellow; - UInt16 black; -} CMCMYKColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMCMYColor { - UInt16 cyan; - UInt16 magenta; - UInt16 yellow; -} CMCMYColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMHLSColor { - UInt16 hue; - UInt16 lightness; - UInt16 saturation; -} CMHLSColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMHSVColor { - UInt16 hue; - UInt16 saturation; - UInt16 value; -} CMHSVColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMLabColor { - UInt16 L; - UInt16 a; - UInt16 b; -} CMLabColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMLuvColor { - UInt16 L; - UInt16 u; - UInt16 v; -} CMLuvColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMYxyColor { - UInt16 capY; - UInt16 x; - UInt16 y; -} CMYxyColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMGrayColor { - UInt16 gray; -} CMGrayColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMultichannel5Color { - UInt8 components[5]; -} CMMultichannel5Color __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMultichannel6Color { - UInt8 components[6]; -} CMMultichannel6Color __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMultichannel7Color { - UInt8 components[7]; -} CMMultichannel7Color __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMMultichannel8Color { - UInt8 components[8]; -} CMMultichannel8Color __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMNamedColor { - UInt32 namedColorIndex; -} CMNamedColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef union CMColor { - CMRGBColor rgb; - CMHSVColor hsv; - CMHLSColor hls; - CMXYZColor XYZ; - CMLabColor Lab; - CMLuvColor Luv; - CMYxyColor Yxy; - CMCMYKColor cmyk; - CMCMYColor cmy; - CMGrayColor gray; - CMMultichannel5Color mc5; - CMMultichannel6Color mc6; - CMMultichannel7Color mc7; - CMMultichannel8Color mc8; - CMNamedColor namedColor; -} CMColor __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -typedef struct CMMInfo { - size_t dataSize; - OSType CMMType; - OSType CMMMfr; - UInt32 CMMVersion; - unsigned char ASCIIName[32]; - unsigned char ASCIIDesc[256]; - UniCharCount UniCodeNameCount; - UniChar UniCodeName[32]; - UniCharCount UniCodeDescCount; - UniChar UniCodeDesc[256]; -} CMMInfo __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -enum { - cmColorSpaceSpaceMask = 0x0000003F, - cmColorSpacePremulAlphaMask = 0x00000040, - cmColorSpaceAlphaMask = 0x00000080, - cmColorSpaceSpaceAndAlphaMask = 0x000000FF, - cmColorSpacePackingMask = 0x0000FF00, - cmColorSpaceEncodingMask = 0x000F0000, - cmColorSpaceReservedMask = (int)0xFFF00000 -}; - - -enum { - cmNoColorPacking = 0x0000, - cmWord5ColorPacking = 0x0500, - cmWord565ColorPacking = 0x0600, - cmLong8ColorPacking = 0x0800, - cmLong10ColorPacking = 0x0A00, - cmAlphaFirstPacking = 0x1000, - cmOneBitDirectPacking = 0x0B00, - cmAlphaLastPacking = 0x0000, - cm8_8ColorPacking = 0x2800, - cm16_8ColorPacking = 0x2000, - cm24_8ColorPacking = 0x2100, - cm32_8ColorPacking = cmLong8ColorPacking, - cm40_8ColorPacking = 0x2200, - cm48_8ColorPacking = 0x2300, - cm56_8ColorPacking = 0x2400, - cm64_8ColorPacking = 0x2500, - cm32_16ColorPacking = 0x2600, - cm48_16ColorPacking = 0x2900, - cm64_16ColorPacking = 0x2A00, - cm32_32ColorPacking = 0x2700, - cmLittleEndianPacking = 0x4000, - cmReverseChannelPacking = 0x8000 -}; - - -enum { - cmSRGB16ChannelEncoding = 0x00010000 -}; - - -enum { - cmNoSpace = 0x0000, - cmRGBSpace = 0x0001, - cmCMYKSpace = 0x0002, - cmHSVSpace = 0x0003, - cmHLSSpace = 0x0004, - cmYXYSpace = 0x0005, - cmXYZSpace = 0x0006, - cmLUVSpace = 0x0007, - cmLABSpace = 0x0008, - cmReservedSpace1 = 0x0009, - cmGraySpace = 0x000A, - cmReservedSpace2 = 0x000B, - cmGamutResultSpace = 0x000C, - cmNamedIndexedSpace = 0x0010, - cmMCFiveSpace = 0x0011, - cmMCSixSpace = 0x0012, - cmMCSevenSpace = 0x0013, - cmMCEightSpace = 0x0014, - cmAlphaPmulSpace = 0x0040, - cmAlphaSpace = 0x0080, - cmRGBASpace = cmRGBSpace + cmAlphaSpace, - cmGrayASpace = cmGraySpace + cmAlphaSpace, - cmRGBAPmulSpace = cmRGBASpace + cmAlphaPmulSpace, - cmGrayAPmulSpace = cmGrayASpace + cmAlphaPmulSpace -}; - - - - -enum { - cmGray8Space = cmGraySpace + cm8_8ColorPacking, - cmGray16Space = cmGraySpace, - cmGray16LSpace = cmGraySpace + cmLittleEndianPacking, - cmGrayA16Space = cmGrayASpace + cm16_8ColorPacking, - cmGrayA32Space = cmGrayASpace, - cmGrayA32LSpace = cmGrayASpace + cmLittleEndianPacking, - cmGrayA16PmulSpace = cmGrayAPmulSpace + cm16_8ColorPacking, - cmGrayA32PmulSpace = cmGrayAPmulSpace, - cmGrayA32LPmulSpace = cmGrayAPmulSpace + cmLittleEndianPacking, - cmRGB16Space = cmRGBSpace + cmWord5ColorPacking, - cmRGB16LSpace = cmRGBSpace + cmWord5ColorPacking + cmLittleEndianPacking, - cmRGB565Space = cmRGBSpace + cmWord565ColorPacking, - cmRGB565LSpace = cmRGBSpace + cmWord565ColorPacking + cmLittleEndianPacking, - cmRGB24Space = cmRGBSpace + cm24_8ColorPacking, - cmRGB32Space = cmRGBSpace + cm32_8ColorPacking, - cmRGB48Space = cmRGBSpace + cm48_16ColorPacking, - cmRGB48LSpace = cmRGBSpace + cm48_16ColorPacking + cmLittleEndianPacking, - cmARGB32Space = cmRGBASpace + cm32_8ColorPacking + cmAlphaFirstPacking, - cmARGB64Space = cmRGBASpace + cm64_16ColorPacking + cmAlphaFirstPacking, - cmARGB64LSpace = cmRGBASpace + cm64_16ColorPacking + cmAlphaFirstPacking + cmLittleEndianPacking, - cmRGBA32Space = cmRGBASpace + cm32_8ColorPacking + cmAlphaLastPacking, - cmRGBA64Space = cmRGBASpace + cm64_16ColorPacking + cmAlphaLastPacking, - cmRGBA64LSpace = cmRGBASpace + cm64_16ColorPacking + cmAlphaLastPacking + cmLittleEndianPacking, - cmARGB32PmulSpace = cmRGBAPmulSpace + cm32_8ColorPacking + cmAlphaFirstPacking, - cmARGB64PmulSpace = cmRGBAPmulSpace + cm64_16ColorPacking + cmAlphaFirstPacking, - cmARGB64LPmulSpace = cmRGBAPmulSpace + cm64_16ColorPacking + cmAlphaFirstPacking + cmLittleEndianPacking, - cmRGBA32PmulSpace = cmRGBAPmulSpace + cm32_8ColorPacking + cmAlphaLastPacking, - cmRGBA64PmulSpace = cmRGBAPmulSpace + cm64_16ColorPacking + cmAlphaLastPacking, - cmRGBA64LPmulSpace = cmRGBAPmulSpace + cm64_16ColorPacking + cmAlphaLastPacking + cmLittleEndianPacking, - cmCMYK32Space = cmCMYKSpace + cm32_8ColorPacking, - cmCMYK64Space = cmCMYKSpace + cm64_16ColorPacking, - cmCMYK64LSpace = cmCMYKSpace + cm64_16ColorPacking + cmLittleEndianPacking, - cmHSV32Space = cmHSVSpace + cmLong10ColorPacking, - cmHLS32Space = cmHLSSpace + cmLong10ColorPacking, - cmYXY32Space = cmYXYSpace + cmLong10ColorPacking, - cmXYZ24Space = cmXYZSpace + cm24_8ColorPacking, - cmXYZ32Space = cmXYZSpace + cmLong10ColorPacking, - cmXYZ48Space = cmXYZSpace + cm48_16ColorPacking, - cmXYZ48LSpace = cmXYZSpace + cm48_16ColorPacking + cmLittleEndianPacking, - cmLUV32Space = cmLUVSpace + cmLong10ColorPacking, - cmLAB24Space = cmLABSpace + cm24_8ColorPacking, - cmLAB32Space = cmLABSpace + cmLong10ColorPacking, - cmLAB48Space = cmLABSpace + cm48_16ColorPacking, - cmLAB48LSpace = cmLABSpace + cm48_16ColorPacking + cmLittleEndianPacking, - cmGamutResult1Space = cmOneBitDirectPacking + cmGamutResultSpace, - cmNamedIndexed32Space = cm32_32ColorPacking + cmNamedIndexedSpace, - cmNamedIndexed32LSpace = cm32_32ColorPacking + cmNamedIndexedSpace + cmLittleEndianPacking, - cmMCFive8Space = cm40_8ColorPacking + cmMCFiveSpace, - cmMCSix8Space = cm48_8ColorPacking + cmMCSixSpace, - cmMCSeven8Space = cm56_8ColorPacking + cmMCSevenSpace, - cmMCEight8Space = cm64_8ColorPacking + cmMCEightSpace -}; - - -typedef UInt32 CMBitmapColorSpace __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMBitmap { - char * image; - size_t width; - size_t height; - size_t rowBytes; - size_t pixelSize; - CMBitmapColorSpace space; - UInt32 user1; - UInt32 user2; -} CMBitmap __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - -enum { - - - - - - - CS_MAX_PATH = 1024 - -}; - - -enum { - cmNoProfileBase = 0, - - - - - - - cmPathBasedProfile = 5, - cmBufferBasedProfile = 6 -}; -typedef struct CMHandleLocation { - Handle h; -} CMHandleLocation __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -typedef struct CMPathLocation { - - - - char path[CS_MAX_PATH]; - -} CMPathLocation __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMBufferLocation { - void * buffer; - UInt32 size; -} CMBufferLocation __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef union CMProfLoc { - - - - CMHandleLocation handleLoc; - - - - - CMPathLocation pathLoc; - CMBufferLocation bufferLoc; -} CMProfLoc __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct CMProfileLocation { - short locType; - CMProfLoc u; -} CMProfileLocation __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -enum { - cmOriginalProfileLocationSize = 72, - cmCurrentProfileLocationSize = sizeof(CMProfileLocation) -}; - - - - -enum { - cmProfileIterateDataVersion1 = 0x00010000, - cmProfileIterateDataVersion2 = 0x00020000, - cmProfileIterateDataVersion3 = 0x00030000, - cmProfileIterateDataVersion4 = 0x00040000 -}; - -typedef struct CMProfileIterateData { - UInt32 dataVersion; - CM2Header header; - ScriptCode code; - Str255 name; - CMProfileLocation location; - UniCharCount uniCodeNameCount; - UniChar * uniCodeName; - unsigned char * asciiName; - CMMakeAndModel * makeAndModel; - CMProfileMD5 * digest; -} CMProfileIterateData __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - -typedef OSErr ( * CMProfileIterateProcPtr)(CMProfileIterateData *iterateData, void *refCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef CMProfileIterateProcPtr CMProfileIterateUPP __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - -typedef OSErr ( * CMMIterateProcPtr)(CMMInfo *iterateData, void *refCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef CMMIterateProcPtr CMMIterateUPP __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - -typedef void ( * CMLabToLabProcPtr)(float *L, float *a, float *b, void *refcon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -} - - - - - -extern "C" { - - - - - - - -enum CMFloatBitmapFlags { - kCMFloatBitmapFlagsNone = 0, - kCMFloatBitmapFlagsAlpha = 1, - kCMFloatBitmapFlagsAlphaPremul = 2, - kCMFloatBitmapFlagsRangeClipped = 4 -}; -typedef enum CMFloatBitmapFlags CMFloatBitmapFlags; -typedef struct CMFloatBitmap { - unsigned long version; - float * buffers[16]; - size_t height; - size_t width; - ptrdiff_t rowStride; - ptrdiff_t colStride; - OSType space; - CMFloatBitmapFlags flags; -} CMFloatBitmap __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -} - - - - - -extern "C" { - - - -} -extern "C" { -enum { - cmDeviceInfoVersion1 = 0x00010000, - cmDeviceProfileInfoVersion1 = 0x00010000, - cmDeviceProfileInfoVersion2 = 0x00020000 -}; - -enum { - cmCurrentDeviceInfoVersion = cmDeviceInfoVersion1, - cmCurrentProfileInfoVersion = cmDeviceProfileInfoVersion1 -}; - - - - - -enum { - cmDefaultDeviceID = 0, - cmDefaultProfileID = 0 -}; - - - - - -enum { - cmDeviceStateDefault = 0x00000000, - cmDeviceStateOffline = 0x00000001, - cmDeviceStateBusy = 0x00000002, - cmDeviceStateForceNotify = (int)0x80000000, - cmDeviceStateDeviceRsvdBits = 0x00FF0000, - cmDeviceStateAppleRsvdBits = (int)0xFF00FFFF -}; -enum { - cmIterateFactoryDeviceProfiles = 0x00000001, - cmIterateCustomDeviceProfiles = 0x00000002, - cmIterateCurrentDeviceProfiles = 0x00000003, - cmIterateAllDeviceProfiles = 0x00000004, - cmIterateDeviceProfilesMask = 0x0000000F -}; - - - - -enum { - cmDeviceDBNotFoundErr = -4227, - cmDeviceAlreadyRegistered = -4228, - cmDeviceNotRegistered = -4229, - cmDeviceProfilesNotFound = -4230, - cmInternalCFErr = -4231, - cmPrefsSynchError = -4232 -}; -typedef UInt32 CMDeviceState __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - - -typedef UInt32 CMDeviceID __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - -typedef UInt32 CMDeviceProfileID __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - -enum { - cmScannerDeviceClass = 'scnr', - cmCameraDeviceClass = 'cmra', - cmDisplayDeviceClass = 'mntr', - cmPrinterDeviceClass = 'prtr', - cmProofDeviceClass = 'pruf' -}; - -typedef OSType CMDeviceClass; - - - - - -typedef struct CMDeviceScope { - CFStringRef deviceUser; - CFStringRef deviceHost; -} CMDeviceScope, CMDeviceProfileScope __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - - -typedef struct CMDeviceInfo { - UInt32 dataVersion; - CMDeviceClass deviceClass; - CMDeviceID deviceID; - CMDeviceScope deviceScope; - CMDeviceState deviceState; - CMDeviceProfileID defaultProfileID; - CFDictionaryRef * deviceName; - - UInt32 profileCount; - UInt32 reserved; -} CMDeviceInfo, *CMDeviceInfoPtr __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - - -typedef struct CMDeviceProfileInfo { - UInt32 dataVersion; - CMDeviceProfileID profileID; - CMProfileLocation profileLoc; - CFDictionaryRef profileName; - UInt32 reserved; -} CMDeviceProfileInfo __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - -typedef struct NCMDeviceProfileInfo { - UInt32 dataVersion; - CMDeviceProfileID profileID; - CMProfileLocation profileLoc; - CFDictionaryRef profileName; - CMDeviceProfileScope profileScope; - UInt32 reserved; -} NCMDeviceProfileInfo __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - - - - -typedef struct CMDeviceProfileArray { - UInt32 profileCount; - CMDeviceProfileInfo profiles[1]; -} CMDeviceProfileArray, *CMDeviceProfileArrayPtr __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); - - - - - - -typedef OSErr ( * CMIterateDeviceInfoProcPtr)(const CMDeviceInfo *deviceInfo, void *refCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -typedef OSErr ( * CMIterateDeviceProfileProcPtr)(const CMDeviceInfo *deviceInfo, const NCMDeviceProfileInfo *profileInfo, void *refCon) __attribute__((availability(macosx,introduced=10.0,deprecated=10.6))); -} - - - - - - -extern "C" { - - -#pragma pack(push, 2) - - -typedef struct OpaqueGrafPtr* GrafPtr; -typedef GrafPtr CGrafPtr; -typedef CGrafPtr GWorldPtr; -typedef short QDErr; -typedef unsigned long GWorldFlags; - - -enum { - srcCopy = 0 -}; - - - -struct BitMap { - Ptr baseAddr; - short rowBytes; - Rect bounds; -}; -typedef struct BitMap BitMap; -typedef BitMap * BitMapPtr; -typedef BitMapPtr * BitMapHandle; -struct RGBColor { - unsigned short red; - unsigned short green; - unsigned short blue; -}; -typedef struct RGBColor RGBColor; -struct ColorSpec { - short value; - RGBColor rgb; -}; -typedef struct ColorSpec ColorSpec; -typedef ColorSpec * ColorSpecPtr; -typedef ColorSpec CSpecArray[1]; -struct ColorTable { - SInt32 ctSeed; - short ctFlags; - short ctSize; - CSpecArray ctTable; -}; -typedef struct ColorTable ColorTable; -typedef ColorTable * CTabPtr; -typedef CTabPtr * CTabHandle; -struct PixMap { - Ptr baseAddr; - short rowBytes; - Rect bounds; - short pmVersion; - short packType; - SInt32 packSize; - Fixed hRes; - Fixed vRes; - short pixelType; - short pixelSize; - short cmpCount; - short cmpSize; - OSType pixelFormat; - CTabHandle pmTable; - void * pmExt; -}; -typedef struct PixMap PixMap; -typedef PixMap * PixMapPtr; -typedef PixMapPtr * PixMapHandle; - - - - -enum { - - k1MonochromePixelFormat = 0x00000001, - k2IndexedPixelFormat = 0x00000002, - k4IndexedPixelFormat = 0x00000004, - k8IndexedPixelFormat = 0x00000008, - k16BE555PixelFormat = 0x00000010, - k24RGBPixelFormat = 0x00000018, - k32ARGBPixelFormat = 0x00000020, - - k1IndexedGrayPixelFormat = 0x00000021, - k2IndexedGrayPixelFormat = 0x00000022, - k4IndexedGrayPixelFormat = 0x00000024, - k8IndexedGrayPixelFormat = 0x00000028, - k16LE555PixelFormat = 'L555', - k16LE5551PixelFormat = '5551', - k16BE565PixelFormat = 'B565', - k16LE565PixelFormat = 'L565', - k24BGRPixelFormat = '24BG', - k32BGRAPixelFormat = 'BGRA', - k32ABGRPixelFormat = 'ABGR', - k32RGBAPixelFormat = 'RGBA', - kYUVSPixelFormat = 'yuvs', - kYUVUPixelFormat = 'yuvu', - kYVU9PixelFormat = 'YVU9', - kYUV411PixelFormat = 'Y411', - kYVYU422PixelFormat = 'YVYU', - kUYVY422PixelFormat = 'UYVY', - kYUV211PixelFormat = 'Y211', - k2vuyPixelFormat = '2vuy' -}; - - -struct Pattern { - UInt8 pat[8]; -}; -typedef struct Pattern Pattern; -typedef Pattern * PatPtr; -typedef PatPtr * PatHandle; -struct PixPat { - short patType; - PixMapHandle patMap; - Handle patData; - Handle patXData; - short patXValid; - Handle patXMap; - Pattern pat1Data; -}; -typedef struct PixPat PixPat; -typedef PixPat * PixPatPtr; -typedef PixPatPtr * PixPatHandle; -typedef struct OpaqueRgnHandle* RgnHandle; -typedef struct GDevice GDevice; -typedef GDevice * GDPtr; -typedef GDPtr * GDHandle; -struct GDevice { - short gdRefNum; - short gdID; - short gdType; - Handle gdITable; - short gdResPref; - Handle gdSearchProc; - Handle gdCompProc; - short gdFlags; - PixMapHandle gdPMap; - SInt32 gdRefCon; - GDHandle gdNextGD; - Rect gdRect; - SInt32 gdMode; - short gdCCBytes; - short gdCCDepth; - Handle gdCCXData; - Handle gdCCXMask; - Handle gdExt; -}; - -struct Picture { - short picSize; - Rect picFrame; -}; -typedef struct Picture Picture; -typedef Picture * PicPtr; -typedef PicPtr * PicHandle; -struct OpenCPicParams { - Rect srcRect; - Fixed hRes; - Fixed vRes; - short version; - short reserved1; - SInt32 reserved2; -}; -typedef struct OpenCPicParams OpenCPicParams; -struct FontInfo { - short ascent; - short descent; - short widMax; - short leading; -}; -typedef struct FontInfo FontInfo; - -typedef SInt32 QDRegionParseDirection; -typedef OSStatus ( * RegionToRectsProcPtr)(UInt16 message, RgnHandle rgn, const Rect *rect, void *refCon); -typedef RegionToRectsProcPtr RegionToRectsUPP; - - -typedef short TruncCode; - -typedef UInt16 DragConstraint; -enum { - kNoConstraint = 0, - kVerticalConstraint = 1, - kHorizontalConstraint = 2 -}; - - - -typedef void ( * DragGrayRgnProcPtr)(void); -typedef Boolean ( * ColorSearchProcPtr)(RGBColor *rgb, long *position); -typedef Boolean ( * ColorComplementProcPtr)(RGBColor * rgb); -typedef DragGrayRgnProcPtr DragGrayRgnUPP; -typedef ColorSearchProcPtr ColorSearchUPP; -typedef ColorComplementProcPtr ColorComplementUPP; - - - - - - - -typedef struct OpaqueWindowPtr* WindowPtr; -typedef struct OpaqueDialogPtr* DialogPtr; -typedef WindowPtr WindowRef; - - - - - - - -struct VDGammaRecord { - Ptr csGTable; -}; -typedef struct VDGammaRecord VDGammaRecord; -typedef VDGammaRecord * VDGamRecPtr; - - -struct MacPolygon { - short polySize; - Rect polyBBox; - Point polyPoints[1]; -}; -typedef struct MacPolygon MacPolygon; - - - - -typedef MacPolygon Polygon; -typedef MacPolygon * PolyPtr; -typedef PolyPtr * PolyHandle; -typedef SInt8 GrafVerb; -typedef SInt32 PrinterStatusOpcode; -typedef void ( * QDTextProcPtr)(short byteCount, const void *textBuf, Point numer, Point denom); -typedef void ( * QDLineProcPtr)(Point newPt); -typedef void ( * QDRectProcPtr)(GrafVerb verb, const Rect *r); -typedef void ( * QDRRectProcPtr)(GrafVerb verb, const Rect *r, short ovalWidth, short ovalHeight); -typedef void ( * QDOvalProcPtr)(GrafVerb verb, const Rect *r); -typedef void ( * QDArcProcPtr)(GrafVerb verb, const Rect *r, short startAngle, short arcAngle); -typedef void ( * QDPolyProcPtr)(GrafVerb verb, PolyHandle poly); -typedef void ( * QDRgnProcPtr)(GrafVerb verb, RgnHandle rgn); -typedef void ( * QDBitsProcPtr)(const BitMap *srcBits, const Rect *srcRect, const Rect *dstRect, short mode, RgnHandle maskRgn); -typedef void ( * QDCommentProcPtr)(short kind, short dataSize, Handle dataHandle); -typedef short ( * QDTxMeasProcPtr)(short byteCount, const void *textAddr, Point *numer, Point *denom, FontInfo *info); -typedef void ( * QDGetPicProcPtr)(void *dataPtr, short byteCount); -typedef void ( * QDPutPicProcPtr)(const void *dataPtr, short byteCount); -typedef void ( * QDOpcodeProcPtr)(const Rect *fromRect, const Rect *toRect, UInt16 opcode, SInt16 version); - -typedef OSStatus ( * QDStdGlyphsProcPtr)(void *dataStream, ByteCount size); -typedef void ( * QDJShieldCursorProcPtr)(short left, short top, short right, short bottom); -typedef OSStatus ( * QDPrinterStatusProcPtr)(PrinterStatusOpcode opcode, CGrafPtr currentPort, void *printerStatus); -typedef QDTextProcPtr QDTextUPP; -typedef QDLineProcPtr QDLineUPP; -typedef QDRectProcPtr QDRectUPP; -typedef QDRRectProcPtr QDRRectUPP; -typedef QDOvalProcPtr QDOvalUPP; -typedef QDArcProcPtr QDArcUPP; -typedef QDPolyProcPtr QDPolyUPP; -typedef QDRgnProcPtr QDRgnUPP; -typedef QDBitsProcPtr QDBitsUPP; -typedef QDCommentProcPtr QDCommentUPP; -typedef QDTxMeasProcPtr QDTxMeasUPP; -typedef QDGetPicProcPtr QDGetPicUPP; -typedef QDPutPicProcPtr QDPutPicUPP; -typedef QDOpcodeProcPtr QDOpcodeUPP; -typedef QDStdGlyphsProcPtr QDStdGlyphsUPP; -typedef QDJShieldCursorProcPtr QDJShieldCursorUPP; -typedef QDPrinterStatusProcPtr QDPrinterStatusUPP; - - -struct CQDProcs { - QDTextUPP textProc; - QDLineUPP lineProc; - QDRectUPP rectProc; - QDRRectUPP rRectProc; - QDOvalUPP ovalProc; - QDArcUPP arcProc; - QDPolyUPP polyProc; - QDRgnUPP rgnProc; - QDBitsUPP bitsProc; - QDCommentUPP commentProc; - QDTxMeasUPP txMeasProc; - QDGetPicUPP getPicProc; - QDPutPicUPP putPicProc; - QDOpcodeUPP opcodeProc; - UniversalProcPtr newProc1; - QDStdGlyphsUPP glyphsProc; - QDPrinterStatusUPP printerStatusProc; - UniversalProcPtr newProc4; - UniversalProcPtr newProc5; - UniversalProcPtr newProc6; -}; -typedef struct CQDProcs CQDProcs; -typedef CQDProcs * CQDProcsPtr; - - - -struct GrafPort { - short whatever[87]; -}; -typedef struct GrafPort GrafPort; -typedef GrafPort CGrafPort; - - -#pragma pack(pop) - - -} -extern "C" { -typedef const struct __HIShape* HIShapeRef; -typedef struct __HIShape* HIMutableShapeRef; - - - - - -enum { - - - - - kHIShapeEnumerateInit = 1, - - - - - - kHIShapeEnumerateRect = 2, - - - - - kHIShapeEnumerateTerminate = 3 -}; - - - - - - -enum { - - - - - - kHIShapeParseFromTop = 0, - - - - - kHIShapeParseFromBottom = (1 << 0), - - - - - - kHIShapeParseFromLeft = 0, - - - - - kHIShapeParseFromRight = (1 << 1), - - - - - - kHIShapeParseFromTopLeft = kHIShapeParseFromTop | kHIShapeParseFromLeft, - - - - - kHIShapeParseFromBottomRight = kHIShapeParseFromBottom | kHIShapeParseFromRight -}; -typedef OSStatus ( * HIShapeEnumerateProcPtr)(int inMessage, HIShapeRef inShape, const CGRect *inRect, void *inRefcon); -extern CFTypeID -HIShapeGetTypeID(void) __attribute__((availability(macosx,introduced=10.2))); -extern HIShapeRef -HIShapeCreateEmpty(void) __attribute__((availability(macosx,introduced=10.4))); -extern HIShapeRef -HIShapeCreateWithQDRgn(RgnHandle inRgn) __attribute__((availability(macosx,introduced=10.2))); -extern HIShapeRef -HIShapeCreateWithRect(const CGRect * inRect) __attribute__((availability(macosx,introduced=10.2))); -extern HIShapeRef -HIShapeCreateCopy(HIShapeRef inShape) __attribute__((availability(macosx,introduced=10.2))); -extern HIShapeRef -HIShapeCreateIntersection( - HIShapeRef inShape1, - HIShapeRef inShape2) __attribute__((availability(macosx,introduced=10.2))); -extern HIShapeRef -HIShapeCreateDifference( - HIShapeRef inShape1, - HIShapeRef inShape2) __attribute__((availability(macosx,introduced=10.2))); -extern HIShapeRef -HIShapeCreateUnion( - HIShapeRef inShape1, - HIShapeRef inShape2) __attribute__((availability(macosx,introduced=10.2))); -extern HIShapeRef -HIShapeCreateXor( - HIShapeRef inShape1, - HIShapeRef inShape2) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -HIShapeIsEmpty(HIShapeRef inShape) __attribute__((availability(macosx,introduced=10.2))); -extern Boolean -HIShapeIsRectangular(HIShapeRef inShape) __attribute__((availability(macosx,introduced=10.2))); -extern Boolean -HIShapeContainsPoint( - HIShapeRef inShape, - const CGPoint * inPoint) __attribute__((availability(macosx,introduced=10.2))); -extern Boolean -HIShapeIntersectsRect( - HIShapeRef inShape, - const CGRect * inRect) __attribute__((availability(macosx,introduced=10.4))); -extern CGRect * -HIShapeGetBounds( - HIShapeRef inShape, - CGRect * outRect) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -HIShapeGetAsQDRgn( - HIShapeRef inShape, - RgnHandle outRgn) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -HIShapeReplacePathInCGContext( - HIShapeRef inShape, - CGContextRef inContext) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -HIShapeEnumerate( - HIShapeRef inShape, - OptionBits inOptions, - HIShapeEnumerateProcPtr inProc, - void * inRefcon) __attribute__((availability(macosx,introduced=10.5))); -extern HIMutableShapeRef -HIShapeCreateMutable(void) __attribute__((availability(macosx,introduced=10.2))); -extern HIMutableShapeRef -HIShapeCreateMutableCopy(HIShapeRef inOrig) __attribute__((availability(macosx,introduced=10.2))); -extern HIMutableShapeRef -HIShapeCreateMutableWithRect(const CGRect * inRect) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -HIShapeSetEmpty(HIMutableShapeRef inShape) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -HIShapeSetWithShape( - HIMutableShapeRef inDestShape, - HIShapeRef inSrcShape) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -HIShapeIntersect( - HIShapeRef inShape1, - HIShapeRef inShape2, - HIMutableShapeRef outResult) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -HIShapeDifference( - HIShapeRef inShape1, - HIShapeRef inShape2, - HIMutableShapeRef outResult) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -HIShapeUnion( - HIShapeRef inShape1, - HIShapeRef inShape2, - HIMutableShapeRef outResult) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -HIShapeXor( - HIShapeRef inShape1, - HIShapeRef inShape2, - HIMutableShapeRef outResult) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -HIShapeOffset( - HIMutableShapeRef inShape, - CGFloat inDX, - CGFloat inDY) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -HIShapeInset( - HIMutableShapeRef inShape, - CGFloat inDX, - CGFloat inDY) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -HIShapeUnionWithRect( - HIMutableShapeRef inShape, - const CGRect * inRect) __attribute__((availability(macosx,introduced=10.5))); - - - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - - -enum { - kAlignNone = 0x00, - kAlignVerticalCenter = 0x01, - kAlignTop = 0x02, - kAlignBottom = 0x03, - kAlignHorizontalCenter = 0x04, - kAlignAbsoluteCenter = kAlignVerticalCenter | kAlignHorizontalCenter, - kAlignCenterTop = kAlignTop | kAlignHorizontalCenter, - kAlignCenterBottom = kAlignBottom | kAlignHorizontalCenter, - kAlignLeft = 0x08, - kAlignCenterLeft = kAlignVerticalCenter | kAlignLeft, - kAlignTopLeft = kAlignTop | kAlignLeft, - kAlignBottomLeft = kAlignBottom | kAlignLeft, - kAlignRight = 0x0C, - kAlignCenterRight = kAlignVerticalCenter | kAlignRight, - kAlignTopRight = kAlignTop | kAlignRight, - kAlignBottomRight = kAlignBottom | kAlignRight -}; - - -enum { - atNone = kAlignNone, - atVerticalCenter = kAlignVerticalCenter, - atTop = kAlignTop, - atBottom = kAlignBottom, - atHorizontalCenter = kAlignHorizontalCenter, - atAbsoluteCenter = kAlignAbsoluteCenter, - atCenterTop = kAlignCenterTop, - atCenterBottom = kAlignCenterBottom, - atLeft = kAlignLeft, - atCenterLeft = kAlignCenterLeft, - atTopLeft = kAlignTopLeft, - atBottomLeft = kAlignBottomLeft, - atRight = kAlignRight, - atCenterRight = kAlignCenterRight, - atTopRight = kAlignTopRight, - atBottomRight = kAlignBottomRight -}; - -typedef SInt16 IconAlignmentType; - -enum { - kTransformNone = 0x00, - kTransformDisabled = 0x01, - kTransformOffline = 0x02, - kTransformOpen = 0x03, - kTransformLabel1 = 0x0100, - kTransformLabel2 = 0x0200, - kTransformLabel3 = 0x0300, - kTransformLabel4 = 0x0400, - kTransformLabel5 = 0x0500, - kTransformLabel6 = 0x0600, - kTransformLabel7 = 0x0700, - kTransformSelected = 0x4000, - kTransformSelectedDisabled = kTransformSelected | kTransformDisabled, - kTransformSelectedOffline = kTransformSelected | kTransformOffline, - kTransformSelectedOpen = kTransformSelected | kTransformOpen -}; - - -enum { - ttNone = kTransformNone, - ttDisabled = kTransformDisabled, - ttOffline = kTransformOffline, - ttOpen = kTransformOpen, - ttLabel1 = kTransformLabel1, - ttLabel2 = kTransformLabel2, - ttLabel3 = kTransformLabel3, - ttLabel4 = kTransformLabel4, - ttLabel5 = kTransformLabel5, - ttLabel6 = kTransformLabel6, - ttLabel7 = kTransformLabel7, - ttSelected = kTransformSelected, - ttSelectedDisabled = kTransformSelectedDisabled, - ttSelectedOffline = kTransformSelectedOffline, - ttSelectedOpen = kTransformSelectedOpen -}; - -typedef SInt16 IconTransformType; - -enum { - kSelectorLarge1Bit = 0x00000001, - kSelectorLarge4Bit = 0x00000002, - kSelectorLarge8Bit = 0x00000004, - kSelectorLarge32Bit = 0x00000008, - kSelectorLarge8BitMask = 0x00000010, - kSelectorSmall1Bit = 0x00000100, - kSelectorSmall4Bit = 0x00000200, - kSelectorSmall8Bit = 0x00000400, - kSelectorSmall32Bit = 0x00000800, - kSelectorSmall8BitMask = 0x00001000, - kSelectorMini1Bit = 0x00010000, - kSelectorMini4Bit = 0x00020000, - kSelectorMini8Bit = 0x00040000, - kSelectorHuge1Bit = 0x01000000, - kSelectorHuge4Bit = 0x02000000, - kSelectorHuge8Bit = 0x04000000, - kSelectorHuge32Bit = 0x08000000, - kSelectorHuge8BitMask = 0x10000000, - kSelectorAllLargeData = 0x000000FF, - kSelectorAllSmallData = 0x0000FF00, - kSelectorAllMiniData = 0x00FF0000, - kSelectorAllHugeData = (UInt32)0xFF000000, - kSelectorAll1BitData = kSelectorLarge1Bit | kSelectorSmall1Bit | kSelectorMini1Bit | kSelectorHuge1Bit, - kSelectorAll4BitData = kSelectorLarge4Bit | kSelectorSmall4Bit | kSelectorMini4Bit | kSelectorHuge4Bit, - kSelectorAll8BitData = kSelectorLarge8Bit | kSelectorSmall8Bit | kSelectorMini8Bit | kSelectorHuge8Bit, - kSelectorAll32BitData = kSelectorLarge32Bit | kSelectorSmall32Bit | kSelectorHuge32Bit, - kSelectorAllAvailableData = (UInt32)0xFFFFFFFF -}; - -typedef UInt32 IconSelectorValue; - -enum { - svLarge1Bit = kSelectorLarge1Bit, - svLarge4Bit = kSelectorLarge4Bit, - svLarge8Bit = kSelectorLarge8Bit, - svSmall1Bit = kSelectorSmall1Bit, - svSmall4Bit = kSelectorSmall4Bit, - svSmall8Bit = kSelectorSmall8Bit, - svMini1Bit = kSelectorMini1Bit, - svMini4Bit = kSelectorMini4Bit, - svMini8Bit = kSelectorMini8Bit, - svAllLargeData = kSelectorAllLargeData, - svAllSmallData = kSelectorAllSmallData, - svAllMiniData = kSelectorAllMiniData, - svAll1BitData = kSelectorAll1BitData, - svAll4BitData = kSelectorAll4BitData, - svAll8BitData = kSelectorAll8BitData, - svAllAvailableData = kSelectorAllAvailableData -}; - -typedef OSErr ( * IconActionProcPtr)(ResType theType, Handle *theIcon, void *yourDataPtr); -typedef Handle ( * IconGetterProcPtr)(ResType theType, void *yourDataPtr); -typedef IconActionProcPtr IconActionUPP; -typedef IconGetterProcPtr IconGetterUPP; -extern IconActionUPP -NewIconActionUPP(IconActionProcPtr userRoutine) ; -extern IconGetterUPP -NewIconGetterUPP(IconGetterProcPtr userRoutine) ; -extern void -DisposeIconActionUPP(IconActionUPP userUPP) ; -extern void -DisposeIconGetterUPP(IconGetterUPP userUPP) ; -extern OSErr -InvokeIconActionUPP( - ResType theType, - Handle * theIcon, - void * yourDataPtr, - IconActionUPP userUPP) ; -extern Handle -InvokeIconGetterUPP( - ResType theType, - void * yourDataPtr, - IconGetterUPP userUPP) ; - - - - inline IconActionUPP NewIconActionUPP(IconActionProcPtr userRoutine) { return userRoutine; } - inline IconGetterUPP NewIconGetterUPP(IconGetterProcPtr userRoutine) { return userRoutine; } - inline void DisposeIconActionUPP(IconActionUPP) { } - inline void DisposeIconGetterUPP(IconGetterUPP) { } - inline OSErr InvokeIconActionUPP(ResType theType, Handle * theIcon, void * yourDataPtr, IconActionUPP userUPP) { return (*userUPP)(theType, theIcon, yourDataPtr); } - inline Handle InvokeIconGetterUPP(ResType theType, void * yourDataPtr, IconGetterUPP userUPP) { return (*userUPP)(theType, yourDataPtr); } -typedef UInt32 PlotIconRefFlags; -enum { - - - - - kPlotIconRefNormalFlags = 0, - - - - - kPlotIconRefNoImage = (1 << 1), - - - - - kPlotIconRefNoMask = (1 << 2) -}; -extern OSErr -IconRefToIconFamily( - IconRef theIconRef, - IconSelectorValue whichIcons, - IconFamilyHandle * iconFamily) ; -extern OSErr -SetIconFamilyData( - IconFamilyHandle iconFamily, - OSType iconType, - Handle h) ; -extern OSErr -GetIconFamilyData( - IconFamilyHandle iconFamily, - OSType iconType, - Handle h) ; -extern OSStatus -PlotIconRefInContext( - CGContextRef inContext, - const CGRect * inRect, - IconAlignmentType inAlign, - IconTransformType inTransform, - const RGBColor * inLabelColor, - PlotIconRefFlags inFlags, - IconRef inIconRef) __attribute__((availability(macosx,introduced=10.1))); -extern Boolean -IconRefContainsCGPoint( - const CGPoint * testPt, - const CGRect * iconRect, - IconAlignmentType align, - IconServicesUsageFlags iconServicesUsageFlags, - IconRef theIconRef) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -IconRefIntersectsCGRect( - const CGRect * testRect, - const CGRect * iconRect, - IconAlignmentType align, - IconServicesUsageFlags iconServicesUsageFlags, - IconRef theIconRef) __attribute__((availability(macosx,introduced=10.5))); -extern HIShapeRef -IconRefToHIShape( - const CGRect * iconRect, - IconAlignmentType align, - IconServicesUsageFlags iconServicesUsageFlags, - IconRef theIconRef) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -IsIconRefMaskEmpty(IconRef iconRef) ; -extern IconRef -GetIconRefVariant( - IconRef inIconRef, - OSType inVariant, - IconTransformType * outTransform) ; -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - - - - - -enum { - icPrefNotFoundErr = -666, - icPermErr = -667, - icPrefDataErr = -668, - icInternalErr = -669, - icTruncatedErr = -670, - icNoMoreWritersErr = -671, - icNothingToOverrideErr = -672, - icNoURLErr = -673, - icConfigNotFoundErr = -674, - icConfigInappropriateErr = -675, - icProfileNotFoundErr = -676, - icTooManyProfilesErr = -677 -}; - - - - - -enum { - kICComponentInterfaceVersion0 = 0x00000000, - kICComponentInterfaceVersion1 = 0x00010000, - kICComponentInterfaceVersion2 = 0x00020000, - kICComponentInterfaceVersion3 = 0x00030000, - kICComponentInterfaceVersion4 = 0x00040000, - kICComponentInterfaceVersion = kICComponentInterfaceVersion4 -}; - - - - - -typedef struct OpaqueICInstance* ICInstance; -typedef UInt32 ICAttr; -enum { - kICAttrLockedBit = 0, - kICAttrVolatileBit = 1 -}; - -enum { - kICAttrNoChange = (UInt32)0xFFFFFFFF, - kICAttrLockedMask = 0x00000001, - kICAttrVolatileMask = 0x00000002 -}; - - - - -typedef UInt8 ICPerm; -enum { - icNoPerm = 0, - icReadOnlyPerm = 1, - icReadWritePerm = 2 -}; - - - - - -typedef SInt32 ICProfileID; -typedef ICProfileID * ICProfileIDPtr; -enum { - kICNilProfileID = 0 -}; - - - - -enum { - kICNoUserInteractionBit = 0 -}; - -enum { - kICNoUserInteractionMask = 0x00000001 -}; - -enum { - kICFileType = 'ICAp', - kICCreator = 'ICAp' -}; - - - - -enum { - kInternetEventClass = 'GURL', - kAEGetURL = 'GURL', - kAEFetchURL = 'FURL', - keyAEAttaching = 'Atch' -}; - - -enum { - kICEditPreferenceEventClass = 'ICAp', - kICEditPreferenceEvent = 'ICAp', - keyICEditPreferenceDestination = 'dest' -}; - - - - -enum { - kICComponentVersion = 0, - kICNumVersion = 1 -}; - - - - -struct ICFontRecord { - SInt16 size; - Style face; - char pad; - Str255 font; -}; -typedef struct ICFontRecord ICFontRecord; -typedef ICFontRecord * ICFontRecordPtr; -typedef ICFontRecordPtr * ICFontRecordHandle; - - - - -struct ICCharTable { - unsigned char netToMac[256]; - unsigned char macToNet[256]; -}; -typedef struct ICCharTable ICCharTable; -typedef ICCharTable * ICCharTablePtr; -typedef ICCharTablePtr * ICCharTableHandle; - - - - -struct ICAppSpec { - OSType fCreator; - Str63 name; -}; -typedef struct ICAppSpec ICAppSpec; -typedef ICAppSpec * ICAppSpecPtr; -typedef ICAppSpecPtr * ICAppSpecHandle; -struct ICAppSpecList { - SInt16 numberOfItems; - ICAppSpec appSpecs[1]; -}; -typedef struct ICAppSpecList ICAppSpecList; -typedef ICAppSpecList * ICAppSpecListPtr; -typedef ICAppSpecListPtr * ICAppSpecListHandle; - - - - -struct ICFileSpec { - Str31 volName; - SInt32 volCreationDate; - FSSpec fss; - AliasRecord alias; - - -}; -typedef struct ICFileSpec ICFileSpec; -typedef ICFileSpec * ICFileSpecPtr; -typedef ICFileSpecPtr * ICFileSpecHandle; -enum { - kICFileSpecHeaderSize = sizeof(ICFileSpec) - sizeof(AliasRecord) -}; - - - - -typedef SInt32 ICMapEntryFlags; -typedef SInt16 ICFixedLength; -struct ICMapEntry { - SInt16 totalLength; - ICFixedLength fixedLength; - SInt16 version; - OSType fileType; - OSType fileCreator; - OSType postCreator; - ICMapEntryFlags flags; - - Str255 extension; - Str255 creatorAppName; - Str255 postAppName; - Str255 MIMEType; - Str255 entryName; -}; -typedef struct ICMapEntry ICMapEntry; -typedef ICMapEntry * ICMapEntryPtr; -typedef ICMapEntryPtr * ICMapEntryHandle; -enum { - kICMapFixedLength = 22 -}; - -enum { - kICMapBinaryBit = 0, - kICMapResourceForkBit = 1, - kICMapDataForkBit = 2, - kICMapPostBit = 3, - kICMapNotIncomingBit = 4, - kICMapNotOutgoingBit = 5 -}; - -enum { - kICMapBinaryMask = 0x00000001, - kICMapResourceForkMask = 0x00000002, - kICMapDataForkMask = 0x00000004, - kICMapPostMask = 0x00000008, - kICMapNotIncomingMask = 0x00000010, - kICMapNotOutgoingMask = 0x00000020 -}; - - - - -typedef SInt16 ICServiceEntryFlags; -struct ICServiceEntry { - Str255 name; - SInt16 port; - ICServiceEntryFlags flags; -}; -typedef struct ICServiceEntry ICServiceEntry; -typedef ICServiceEntry * ICServiceEntryPtr; -typedef ICServiceEntryPtr * ICServiceEntryHandle; - -enum { - kICServicesTCPBit = 0, - kICServicesUDPBit = 1 -}; - -enum { - kICServicesTCPMask = 0x00000001, - kICServicesUDPMask = 0x00000002 -}; - -struct ICServices { - SInt16 count; - ICServiceEntry services[1]; -}; -typedef struct ICServices ICServices; -typedef ICServices * ICServicesPtr; -typedef ICServicesPtr * ICServicesHandle; -extern OSStatus -ICStart( - ICInstance * inst, - OSType signature) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICStop(ICInstance inst) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetVersion( - ICInstance inst, - long whichVersion, - UInt32 * version) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetConfigName( - ICInstance inst, - Boolean longname, - Str255 name) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetSeed( - ICInstance inst, - long * seed) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetPerm( - ICInstance inst, - ICPerm * perm) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICBegin( - ICInstance inst, - ICPerm perm) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetPref( - ICInstance inst, - ConstStr255Param key, - ICAttr * attr, - void * buf, - long * size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICSetPref( - ICInstance inst, - ConstStr255Param key, - ICAttr attr, - const void * buf, - long size) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICFindPrefHandle( - ICInstance inst, - ConstStr255Param key, - ICAttr * attr, - Handle prefh) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetPrefHandle( - ICInstance inst, - ConstStr255Param key, - ICAttr * attr, - Handle * prefh) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICSetPrefHandle( - ICInstance inst, - ConstStr255Param key, - ICAttr attr, - Handle prefh) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICCountPref( - ICInstance inst, - long * count) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetIndPref( - ICInstance inst, - long index, - Str255 key) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICDeletePref( - ICInstance inst, - ConstStr255Param key) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICEnd(ICInstance inst) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetDefaultPref( - ICInstance inst, - ConstStr255Param key, - Handle prefH) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICEditPreferences( - ICInstance inst, - ConstStr255Param key) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICLaunchURL( - ICInstance inst, - ConstStr255Param hint, - const void * data, - long len, - long * selStart, - long * selEnd) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICParseURL( - ICInstance inst, - ConstStr255Param hint, - const void * data, - long len, - long * selStart, - long * selEnd, - Handle url) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICCreateGURLEvent( - ICInstance inst, - OSType helperCreator, - Handle urlH, - AppleEvent * theEvent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICSendGURLEvent( - ICInstance inst, - AppleEvent * theEvent) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICMapFilename( - ICInstance inst, - ConstStr255Param filename, - ICMapEntry * entry) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICMapTypeCreator( - ICInstance inst, - OSType fType, - OSType fCreator, - ConstStr255Param filename, - ICMapEntry * entry) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICMapEntriesFilename( - ICInstance inst, - Handle entries, - ConstStr255Param filename, - ICMapEntry * entry) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICMapEntriesTypeCreator( - ICInstance inst, - Handle entries, - OSType fType, - OSType fCreator, - ConstStr255Param filename, - ICMapEntry * entry) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICCountMapEntries( - ICInstance inst, - Handle entries, - long * count) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetIndMapEntry( - ICInstance inst, - Handle entries, - long index, - long * pos, - ICMapEntry * entry) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetMapEntry( - ICInstance inst, - Handle entries, - long pos, - ICMapEntry * entry) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICSetMapEntry( - ICInstance inst, - Handle entries, - long pos, - const ICMapEntry * entry) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICDeleteMapEntry( - ICInstance inst, - Handle entries, - long pos) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICAddMapEntry( - ICInstance inst, - Handle entries, - const ICMapEntry * entry) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetCurrentProfile( - ICInstance inst, - ICProfileID * currentID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICSetCurrentProfile( - ICInstance inst, - ICProfileID newID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICCountProfiles( - ICInstance inst, - long * count) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetIndProfile( - ICInstance inst, - long index, - ICProfileID * thisID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICGetProfileName( - ICInstance inst, - ICProfileID thisID, - Str255 name) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICSetProfileName( - ICInstance inst, - ICProfileID thisID, - ConstStr255Param name) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICAddProfile( - ICInstance inst, - ICProfileID prototypeID, - ICProfileID * newID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); -extern OSStatus -ICDeleteProfile( - ICInstance inst, - ICProfileID thisID) __attribute__((availability(macosx,introduced=10.0,deprecated=10.7))); - - - - - - - - -#pragma pack(pop) - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - -enum { - - kNoProcess = 0, - kSystemProcess = 1, - kCurrentProcess = 2 -}; - - - -typedef UInt16 LaunchFlags; -enum { - launchContinue = 0x4000, - launchNoFileFlags = 0x0800, - launchUseMinimum = 0x0400, - launchDontSwitch = 0x0200, - launchAllow24Bit = 0x0100, - launchInhibitDaemon = 0x0080 -}; - - - -struct AppParameters { - struct { - UInt16 what; - UInt32 message; - UInt32 when; - Point where; - UInt16 modifiers; - } theMsgEvent; - UInt32 eventRefCon; - UInt32 messageLength; -}; -typedef struct AppParameters AppParameters; -typedef AppParameters * AppParametersPtr; - - -struct LaunchParamBlockRec { - UInt32 reserved1; - UInt16 reserved2; - UInt16 launchBlockID; - UInt32 launchEPBLength; - UInt16 launchFileFlags; - LaunchFlags launchControlFlags; - FSRefPtr launchAppRef; - ProcessSerialNumber launchProcessSN; - UInt32 launchPreferredSize; - UInt32 launchMinimumSize; - UInt32 launchAvailableSize; - AppParametersPtr launchAppParameters; -}; -typedef struct LaunchParamBlockRec LaunchParamBlockRec; -typedef LaunchParamBlockRec * LaunchPBPtr; - - -enum { - extendedBlock = 0x4C43, - extendedBlockLen = sizeof(LaunchParamBlockRec) - 12 -}; - -enum { - - modeReserved = 0x01000000, - modeControlPanel = 0x00080000, - modeLaunchDontSwitch = 0x00040000, - modeDeskAccessory = 0x00020000, - modeMultiLaunch = 0x00010000, - modeNeedSuspendResume = 0x00004000, - modeCanBackground = 0x00001000, - modeDoesActivateOnFGSwitch = 0x00000800, - modeOnlyBackground = 0x00000400, - modeGetFrontClicks = 0x00000200, - modeGetAppDiedMsg = 0x00000100, - mode32BitCompatible = 0x00000080, - modeHighLevelEventAware = 0x00000040, - modeLocalAndRemoteHLEvents = 0x00000020, - modeStationeryAware = 0x00000010, - modeUseTextEditServices = 0x00000008, - modeDisplayManagerAware = 0x00000004 -}; - -typedef UInt32 ProcessApplicationTransformState; -enum { - kProcessTransformToForegroundApplication = 1, - kProcessTransformToBackgroundApplication = 2, - kProcessTransformToUIElementApplication = 4 -}; -struct ProcessInfoRec { - UInt32 processInfoLength; - StringPtr processName; - ProcessSerialNumber processNumber; - UInt32 processType; - OSType processSignature; - UInt32 processMode; - Ptr processLocation; - UInt32 processSize; - UInt32 processFreeMem; - ProcessSerialNumber processLauncher; - UInt32 processLaunchDate; - UInt32 processActiveTime; - FSRefPtr processAppRef; -}; -typedef struct ProcessInfoRec ProcessInfoRec; -typedef ProcessInfoRec * ProcessInfoRecPtr; -struct ProcessInfoExtendedRec { - UInt32 processInfoLength; - StringPtr processName; - ProcessSerialNumber processNumber; - UInt32 processType; - OSType processSignature; - UInt32 processMode; - Ptr processLocation; - UInt32 processSize; - UInt32 processFreeMem; - ProcessSerialNumber processLauncher; - UInt32 processLaunchDate; - UInt32 processActiveTime; - FSRefPtr processAppRef; - UInt32 processTempMemTotal; - UInt32 processPurgeableTempMemTotal; -}; -typedef struct ProcessInfoExtendedRec ProcessInfoExtendedRec; -typedef ProcessInfoExtendedRec * ProcessInfoExtendedRecPtr; - -struct SizeResourceRec { - UInt16 flags; - UInt32 preferredHeapSize; - UInt32 minimumHeapSize; -}; -typedef struct SizeResourceRec SizeResourceRec; -typedef SizeResourceRec * SizeResourceRecPtr; -typedef SizeResourceRecPtr * SizeResourceRecHandle; - - - - - -enum { - - - - - - kProcessDictionaryIncludeAllInformationMask = (int)0xFFFFFFFF -}; -enum { - kQuitBeforeNormalTimeMask = 1, - kQuitAtNormalTimeMask = 2, - kQuitBeforeFBAsQuitMask = 4, - kQuitBeforeShellQuitsMask = 8, - kQuitBeforeTerminatorAppQuitsMask = 16, - kQuitNeverMask = 32, - kQuitOptionsMask = 0x7F, - kQuitNotQuitDuringInstallMask = 0x0100, - kQuitNotQuitDuringLogoutMask = 0x0200 -}; -extern OSErr -LaunchApplication(LaunchPBPtr LaunchParams) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern OSErr -GetCurrentProcess(ProcessSerialNumber * PSN) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern OSErr -GetFrontProcess(ProcessSerialNumber * PSN) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern OSErr -GetNextProcess(ProcessSerialNumber * PSN) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern OSErr -GetProcessInformation( - const ProcessSerialNumber * PSN, - ProcessInfoRec * info) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern CFDictionaryRef -ProcessInformationCopyDictionary( - const ProcessSerialNumber * PSN, - UInt32 infoToReturn) __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -extern OSErr -SetFrontProcess(const ProcessSerialNumber * PSN) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); - - - - - - - -enum { - - - - - - - kSetFrontProcessFrontWindowOnly = (1 << 0), - kSetFrontProcessCausedByUser = (1 << 1) -}; -extern OSStatus -SetFrontProcessWithOptions( - const ProcessSerialNumber * inProcess, - OptionBits inOptions) __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -extern OSErr -WakeUpProcess(const ProcessSerialNumber * PSN) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern OSErr -SameProcess( - const ProcessSerialNumber * PSN1, - const ProcessSerialNumber * PSN2, - Boolean * result) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -void ExitToShell( void ) __attribute__ (( __noreturn__ )) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern OSErr -KillProcess(const ProcessSerialNumber * inProcess) __attribute__((availability(macosx,introduced=10.2,deprecated=10.9))); -extern OSStatus -GetProcessBundleLocation( - const ProcessSerialNumber * psn, - FSRef * location) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern OSStatus -CopyProcessName( - const ProcessSerialNumber * psn, - CFStringRef * name) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern OSStatus -GetProcessPID( - const ProcessSerialNumber * psn, - pid_t * pid) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern OSStatus -GetProcessForPID( - pid_t pid, - ProcessSerialNumber * psn) __attribute__((availability(macosx,introduced=10.0,deprecated=10.9))); -extern Boolean -IsProcessVisible(const ProcessSerialNumber * psn) __attribute__((availability(macosx,introduced=10.1,deprecated=10.9))); -extern OSErr -ShowHideProcess( - const ProcessSerialNumber * psn, - Boolean visible) __attribute__((availability(macosx,introduced=10.1,deprecated=10.9))); -extern OSStatus -TransformProcessType( - const ProcessSerialNumber * psn, - ProcessApplicationTransformState transformState) __attribute__((availability(macosx,introduced=10.3))); - - - - - -enum { - initDev = 0, - hitDev = 1, - closeDev = 2, - nulDev = 3, - updateDev = 4, - activDev = 5, - deactivDev = 6, - keyEvtDev = 7, - macDev = 8, - undoDev = 9, - cutDev = 10, - copyDev = 11, - pasteDev = 12, - clearDev = 13, - cursorDev = 14 -}; - - -enum { - cdevGenErr = -1, - cdevMemErr = 0, - cdevResErr = 1, - cdevUnset = 3 -}; - - - - - -#pragma pack(pop) - - -} - - - -extern "C" { -typedef struct OpaquePasteboardRef* PasteboardRef; -typedef void * PasteboardItemID; - -enum { - badPasteboardSyncErr = -25130, - badPasteboardIndexErr = -25131, - badPasteboardItemErr = -25132, - badPasteboardFlavorErr = -25133, - duplicatePasteboardFlavorErr = -25134, - notPasteboardOwnerErr = -25135, - noPasteboardPromiseKeeperErr = -25136 -}; -typedef OptionBits PasteboardSyncFlags; -enum { - kPasteboardModified = (1 << 0), - - - - - - - - kPasteboardClientIsOwner = (1 << 1) -}; -typedef OptionBits PasteboardFlavorFlags; -enum { - - - - - kPasteboardFlavorNoFlags = 0, - - - - - - - - kPasteboardFlavorSenderOnly = (1 << 0), - - - - - - - kPasteboardFlavorSenderTranslated = (1 << 1), - - - - - - - - kPasteboardFlavorNotSaved = (1 << 2), - kPasteboardFlavorRequestOnly = (1 << 3), - kPasteboardFlavorSystemTranslated = (1 << 8), - kPasteboardFlavorPromised = (1 << 9) -}; -typedef OSType PasteboardStandardLocation; -enum { - - - - - - - - kPasteboardStandardLocationTrash = 'trsh', - - - - - kPasteboardStandardLocationUnknown = 'unkn' -}; -extern CFTypeID -PasteboardGetTypeID(void) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardCreate( - CFStringRef inName, - PasteboardRef * outPasteboard) __attribute__((availability(macosx,introduced=10.3))); -extern PasteboardSyncFlags -PasteboardSynchronize(PasteboardRef inPasteboard) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardClear(PasteboardRef inPasteboard) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardCopyName( - PasteboardRef inPasteboard, - CFStringRef * outName) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PasteboardGetItemCount( - PasteboardRef inPasteboard, - ItemCount * outItemCount) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardGetItemIdentifier( - PasteboardRef inPasteboard, - CFIndex inIndex, - PasteboardItemID * outItem) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardCopyItemFlavors( - PasteboardRef inPasteboard, - PasteboardItemID inItem, - CFArrayRef * outFlavorTypes) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardGetItemFlavorFlags( - PasteboardRef inPasteboard, - PasteboardItemID inItem, - CFStringRef inFlavorType, - PasteboardFlavorFlags * outFlags) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardCopyItemFlavorData( - PasteboardRef inPasteboard, - PasteboardItemID inItem, - CFStringRef inFlavorType, - CFDataRef * outData) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardPutItemFlavor( - PasteboardRef inPasteboard, - PasteboardItemID inItem, - CFStringRef inFlavorType, - CFDataRef inData, - PasteboardFlavorFlags inFlags) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardCopyPasteLocation( - PasteboardRef inPasteboard, - CFURLRef * outPasteLocation) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardSetPasteLocation( - PasteboardRef inPasteboard, - CFURLRef inPasteLocation) __attribute__((availability(macosx,introduced=10.3))); -typedef OSStatus ( * PasteboardPromiseKeeperProcPtr)(PasteboardRef pasteboard, PasteboardItemID item, CFStringRef flavorType, void *context); -extern OSStatus -PasteboardSetPromiseKeeper( - PasteboardRef inPasteboard, - PasteboardPromiseKeeperProcPtr inPromiseKeeper, - void * inContext) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PasteboardResolvePromises(PasteboardRef inPasteboard) __attribute__((availability(macosx,introduced=10.3))); - - - - -} - - - -extern "C" { -typedef struct OpaqueTranslationRef* TranslationRef; - -enum { - - - - - - badTranslationRefErr = -3031 -}; -typedef OptionBits TranslationFlags; -enum { - - - - - - kTranslationDataTranslation = (1 << 0), - - - - - - kTranslationFileTranslation = (1 << 1) -}; -extern CFTypeID -TranslationGetTypeID(void) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TranslationCreate( - CFStringRef inSourceType, - CFStringRef inDestinationType, - TranslationFlags inTranslationFlags, - TranslationRef * outTranslation) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TranslationCreateWithSourceArray( - CFArrayRef inSourceTypes, - TranslationFlags inTranslationFlags, - CFArrayRef * outDestinationTypes, - CFDictionaryRef * outTranslations) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TranslationPerformForData( - TranslationRef inTranslation, - CFDataRef inSourceData, - CFDataRef * outDestinationData) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TranslationPerformForFile( - TranslationRef inTranslation, - const FSRef * inSourceFile, - const FSRef * inDestinationDirectory, - CFStringRef inDestinationName, - FSRef * outTranslatedFile) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TranslationPerformForURL( - TranslationRef inTranslation, - CFURLRef inSourceURL, - CFURLRef inDestinationURL, - CFURLRef * outTranslatedURL) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TranslationCopySourceType( - TranslationRef inTranslation, - CFStringRef * outSourceType) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TranslationCopyDestinationType( - TranslationRef inTranslation, - CFStringRef * outDestinationType) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -TranslationGetTranslationFlags( - TranslationRef inTranslation, - TranslationFlags * outTranslationFlags) __attribute__((availability(macosx,introduced=10.3))); - - - - -} - - - -extern "C" { -typedef SInt32 AXError; enum { - - kAXErrorSuccess = 0, - - - kAXErrorFailure = -25200, - - - kAXErrorIllegalArgument = -25201, - - - kAXErrorInvalidUIElement = -25202, - - - kAXErrorInvalidUIElementObserver = -25203, - - - kAXErrorCannotComplete = -25204, - - - kAXErrorAttributeUnsupported = -25205, - - - kAXErrorActionUnsupported = -25206, - - - kAXErrorNotificationUnsupported = -25207, - - - kAXErrorNotImplemented = -25208, - - - kAXErrorNotificationAlreadyRegistered = -25209, - - - kAXErrorNotificationNotRegistered = -25210, - - - kAXErrorAPIDisabled = -25211, - - - kAXErrorNoValue = -25212, - - - kAXErrorParameterizedAttributeUnsupported = -25213, - - - kAXErrorNotEnoughPrecision = -25214 -}; - - - -} -typedef UInt32 AXMenuItemModifiers; enum { - kAXMenuItemModifierNone = 0, - kAXMenuItemModifierShift = (1 << 0), - kAXMenuItemModifierOption = (1 << 1), - kAXMenuItemModifierControl = (1 << 2), - kAXMenuItemModifierNoCommand = (1 << 3) -}; -typedef CFIndex AXPriority; enum { - kAXPriorityLow = 10, - kAXPriorityMedium = 50, - kAXPriorityHigh = 90 -} __attribute__((availability(macosx,introduced=10_9))); -extern "C" { -extern Boolean AXAPIEnabled (void) __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" ))); -extern Boolean AXIsProcessTrustedWithOptions (CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10_9))); - -extern CFStringRef kAXTrustedCheckOptionPrompt __attribute__((availability(macosx,introduced=10_9))); - - - - - - - -extern Boolean AXIsProcessTrusted (void) __attribute__((availability(macosx,introduced=10_4))); -extern AXError AXMakeProcessTrusted (CFStringRef executablePath) __attribute__((availability(macosx,introduced=10_4,deprecated=10_9,message="" ))); -typedef const struct __attribute__((objc_bridge(id))) __AXUIElement *AXUIElementRef; - - - - - - -typedef UInt32 AXCopyMultipleAttributeOptions; enum { - kAXCopyMultipleAttributeOptionStopOnError = 0x1 -}; - - - - - - - -extern CFTypeID AXUIElementGetTypeID (void); -extern AXError AXUIElementCopyAttributeNames (AXUIElementRef element, CFArrayRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) names); -extern AXError AXUIElementCopyAttributeValue (AXUIElementRef element, CFStringRef attribute, CFTypeRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) value); -extern AXError AXUIElementGetAttributeValueCount (AXUIElementRef element, CFStringRef attribute, CFIndex *count); -extern AXError AXUIElementCopyAttributeValues (AXUIElementRef element, CFStringRef attribute, CFIndex index, CFIndex maxValues, CFArrayRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) values); -extern AXError AXUIElementIsAttributeSettable (AXUIElementRef element, CFStringRef attribute, Boolean *settable); -extern AXError AXUIElementSetAttributeValue (AXUIElementRef element, CFStringRef attribute, CFTypeRef value); -extern AXError AXUIElementCopyMultipleAttributeValues (AXUIElementRef element, CFArrayRef attributes, AXCopyMultipleAttributeOptions options, CFArrayRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) values) __attribute__((availability(macosx,introduced=10_4))); -extern AXError AXUIElementCopyParameterizedAttributeNames (AXUIElementRef element, CFArrayRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) names) __attribute__((availability(macosx,introduced=10_3))); -extern AXError AXUIElementCopyParameterizedAttributeValue (AXUIElementRef element, CFStringRef parameterizedAttribute, CFTypeRef parameter, CFTypeRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) result) __attribute__((availability(macosx,introduced=10_3))); -extern AXError AXUIElementCopyActionNames (AXUIElementRef element, CFArrayRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) names); -extern AXError AXUIElementCopyActionDescription (AXUIElementRef element, CFStringRef action, CFStringRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) description); -extern AXError AXUIElementPerformAction (AXUIElementRef element, CFStringRef action); -extern AXError AXUIElementCopyElementAtPosition (AXUIElementRef application, float x,float y, AXUIElementRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) element); -extern AXUIElementRef AXUIElementCreateApplication (pid_t pid); -extern AXUIElementRef AXUIElementCreateSystemWide (void); -extern AXError AXUIElementGetPid (AXUIElementRef element, pid_t *pid); -extern AXError AXUIElementSetMessagingTimeout (AXUIElementRef element, float timeoutInSeconds) __attribute__((availability(macosx,introduced=10_4))); -extern AXError AXUIElementPostKeyboardEvent (AXUIElementRef application, CGCharCode keyChar, CGKeyCode virtualKey, Boolean keyDown) __attribute__((availability(macosx,introduced=10_0,deprecated=10_9,message="" )));; -typedef struct __attribute__((objc_bridge(id))) __AXObserver *AXObserverRef; -typedef void (*AXObserverCallback)(AXObserverRef observer, AXUIElementRef element, CFStringRef notification, void * _Nullable refcon); -typedef void (*AXObserverCallbackWithInfo)(AXObserverRef observer, AXUIElementRef element, CFStringRef notification, CFDictionaryRef info, void * _Nullable refcon); - - - - - - - -CFTypeID AXObserverGetTypeID (void); -extern AXError AXObserverCreate (pid_t application, AXObserverCallback callback, AXObserverRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) outObserver); -extern AXError AXObserverCreateWithInfoCallback (pid_t application, AXObserverCallbackWithInfo callback, AXObserverRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) outObserver); -extern AXError AXObserverAddNotification (AXObserverRef observer, AXUIElementRef element, CFStringRef notification, void * _Nullable refcon); -extern AXError AXObserverRemoveNotification (AXObserverRef observer, AXUIElementRef element, CFStringRef notification); -extern CFRunLoopSourceRef AXObserverGetRunLoopSource (AXObserverRef observer); - - - - -} -extern "C" { -typedef UInt32 AXValueType; enum { - kAXValueTypeCGPoint __attribute__((availability(macosx,introduced=10_11))) = 1, - kAXValueTypeCGSize __attribute__((availability(macosx,introduced=10_11))) = 2, - kAXValueTypeCGRect __attribute__((availability(macosx,introduced=10_11))) = 3, - kAXValueTypeCFRange __attribute__((availability(macosx,introduced=10_11))) = 4, - kAXValueTypeAXError __attribute__((availability(macosx,introduced=10_11))) = 5, - kAXValueTypeIllegal __attribute__((availability(macosx,introduced=10_11))) = 0, -}; - - -static const UInt32 kAXValueCGPointType = kAXValueTypeCGPoint; -static const UInt32 kAXValueCGSizeType = kAXValueTypeCGSize; -static const UInt32 kAXValueCGRectType = kAXValueTypeCGRect; -static const UInt32 kAXValueCFRangeType = kAXValueTypeCFRange; -static const UInt32 kAXValueAXErrorType = kAXValueTypeAXError; -static const UInt32 kAXValueIllegalType = kAXValueTypeIllegal; -typedef const struct __attribute__((objc_bridge(id))) __AXValue *AXValueRef; -extern CFTypeID AXValueGetTypeID() __attribute__((availability(macosx,introduced=10.3))); -extern AXValueRef _Nullable AXValueCreate (AXValueType theType, const void *valuePtr); -extern AXValueType AXValueGetType(AXValueRef value); -extern Boolean AXValueGetValue(AXValueRef value, AXValueType theType, void *valuePtr); - - - - - -} -extern "C" { -extern CFStringRef kAXFontTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXForegroundColorTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXBackgroundColorTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXUnderlineColorTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXStrikethroughColorTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXUnderlineTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXSuperscriptTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXStrikethroughTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXShadowTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern CFStringRef kAXAttachmentTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXLinkTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXNaturalLanguageTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXReplacementStringTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern CFStringRef kAXMisspelledTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern CFStringRef kAXMarkedMisspelledTextAttribute __attribute__((availability(macosx,introduced=10.9))); - - - - - - -extern CFStringRef kAXAutocorrectedTextAttribute __attribute__((availability(macosx,introduced=10.7))); - - - - - - -extern CFStringRef kAXListItemPrefixTextAttribute __attribute__((availability(macosx,introduced=10.11))); - - - - -extern CFStringRef kAXListItemIndexTextAttribute __attribute__((availability(macosx,introduced=10.11))); - - - - -extern CFStringRef kAXListItemLevelTextAttribute __attribute__((availability(macosx,introduced=10.11))); -extern CFStringRef kAXFontNameKey __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXFontFamilyKey __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXVisibleNameKey __attribute__((availability(macosx,introduced=10.4))); - - - - -extern CFStringRef kAXFontSizeKey __attribute__((availability(macosx,introduced=10.4))); - - - - - -typedef UInt32 AXUnderlineStyle; enum { - kAXUnderlineStyleNone = 0x0, - kAXUnderlineStyleSingle = 0x1, - kAXUnderlineStyleThick = 0x2, - kAXUnderlineStyleDouble = 0x9 -}; - - - -extern CFStringRef kAXForegoundColorTextAttribute __attribute__((availability(macosx,introduced=10.4))); - - - -} - - -extern "C" { -typedef UInt32 UAZoomChangeFocusType; - - - - - - -enum { - - - - kUAZoomFocusTypeOther = 0, - - - - kUAZoomFocusTypeInsertionPoint = 1 -}; -extern Boolean -UAZoomEnabled(void) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -UAZoomChangeFocus( - const CGRect * inRect, - const CGRect * inHighlightRect, - UAZoomChangeFocusType inType) __attribute__((availability(macosx,introduced=10.4))); - - - - -} - - - - -typedef struct __attribute__((objc_bridge(id))) CGImageSource * CGImageSourceRef; - - - -typedef const struct __attribute__((objc_bridge(id))) CGImageMetadata *CGImageMetadataRef; - - - - - - - -extern "C" CFTypeID CGImageMetadataGetTypeID(void); - - - - - - - -typedef struct __attribute__((objc_bridge(id))) CGImageMetadata *CGMutableImageMetadataRef; - - - - - -extern "C" CGMutableImageMetadataRef _Nonnull CGImageMetadataCreateMutable(void) __attribute__((availability(macosx,introduced=10.8))); -extern "C" CGMutableImageMetadataRef _Nullable CGImageMetadataCreateMutableCopy(CGImageMetadataRef _Nonnull metadata) __attribute__((availability(macosx,introduced=10.8))); -typedef struct __attribute__((objc_bridge(id))) CGImageMetadataTag *CGImageMetadataTagRef; - - - - - - - -extern "C" CFTypeID CGImageMetadataTagGetTypeID(void) __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataNamespaceExif __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataNamespaceExifAux __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataNamespaceExifEX __attribute__((availability(macosx,introduced=10.9))); -extern "C" const CFStringRef kCGImageMetadataNamespaceDublinCore __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataNamespaceIPTCCore __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataNamespacePhotoshop __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataNamespaceTIFF __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataNamespaceXMPBasic __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataNamespaceXMPRights __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataPrefixExif __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataPrefixExifAux __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataPrefixExifEX __attribute__((availability(macosx,introduced=10.9))); -extern "C" const CFStringRef kCGImageMetadataPrefixDublinCore __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataPrefixIPTCCore __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataPrefixPhotoshop __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataPrefixTIFF __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataPrefixXMPBasic __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageMetadataPrefixXMPRights __attribute__((availability(macosx,introduced=10.8))); -typedef int32_t CGImageMetadataType; enum { - kCGImageMetadataTypeInvalid = -1, - kCGImageMetadataTypeDefault = 0, - kCGImageMetadataTypeString = 1, - kCGImageMetadataTypeArrayUnordered = 2, - kCGImageMetadataTypeArrayOrdered = 3, - kCGImageMetadataTypeAlternateArray = 4, - kCGImageMetadataTypeAlternateText = 5, - kCGImageMetadataTypeStructure = 6 -}; -extern "C" CGImageMetadataTagRef _Nullable CGImageMetadataTagCreate (CFStringRef _Nonnull xmlns, CFStringRef _Nullable prefix, CFStringRef _Nonnull name, CGImageMetadataType type, CFTypeRef _Nonnull value) __attribute__((availability(macosx,introduced=10.8))); -extern "C" CFStringRef _Nullable CGImageMetadataTagCopyNamespace(CGImageMetadataTagRef _Nonnull tag) __attribute__((availability(macosx,introduced=10.8))); - - - - - -extern "C" CFStringRef _Nullable CGImageMetadataTagCopyPrefix(CGImageMetadataTagRef _Nonnull tag) __attribute__((availability(macosx,introduced=10.8))); - - - - - -extern "C" CFStringRef _Nullable CGImageMetadataTagCopyName(CGImageMetadataTagRef _Nonnull tag) __attribute__((availability(macosx,introduced=10.8))); -extern "C" CFTypeRef _Nullable CGImageMetadataTagCopyValue(CGImageMetadataTagRef _Nonnull tag) __attribute__((availability(macosx,introduced=10.8))); - - - - - - - -extern "C" CGImageMetadataType CGImageMetadataTagGetType(CGImageMetadataTagRef _Nonnull tag) __attribute__((availability(macosx,introduced=10.8))); -extern "C" CFArrayRef _Nullable CGImageMetadataTagCopyQualifiers(CGImageMetadataTagRef _Nonnull tag) __attribute__((availability(macosx,introduced=10.8))); -extern "C" CFArrayRef _Nullable CGImageMetadataCopyTags(CGImageMetadataRef _Nonnull metadata) __attribute__((availability(macosx,introduced=10.8))); -extern "C" CGImageMetadataTagRef _Nullable CGImageMetadataCopyTagWithPath(CGImageMetadataRef _Nonnull metadata, CGImageMetadataTagRef _Nullable parent, CFStringRef _Nonnull path) __attribute__((availability(macosx,introduced=10.8))); -extern "C" CFStringRef _Nullable CGImageMetadataCopyStringValueWithPath(CGImageMetadataRef _Nonnull metadata, CGImageMetadataTagRef _Nullable parent, CFStringRef _Nonnull path) __attribute__((availability(macosx,introduced=10.8))); -extern "C" bool CGImageMetadataRegisterNamespaceForPrefix(CGMutableImageMetadataRef _Nonnull metadata, CFStringRef _Nonnull xmlns, CFStringRef _Nonnull prefix, _Nullable CFErrorRef * _Nullable err) __attribute__((availability(macosx,introduced=10.8))); -extern "C" bool CGImageMetadataSetTagWithPath(CGMutableImageMetadataRef _Nonnull metadata, CGImageMetadataTagRef _Nullable parent, CFStringRef _Nonnull path, CGImageMetadataTagRef _Nonnull tag) __attribute__((availability(macosx,introduced=10.8))); -extern "C" bool CGImageMetadataSetValueWithPath(CGMutableImageMetadataRef _Nonnull metadata, CGImageMetadataTagRef _Nullable parent, CFStringRef _Nonnull path, CFTypeRef _Nonnull value) __attribute__((availability(macosx,introduced=10.8))); -extern "C" bool CGImageMetadataRemoveTagWithPath(CGMutableImageMetadataRef _Nonnull metadata, CGImageMetadataTagRef _Nullable parent, CFStringRef _Nonnull path) __attribute__((availability(macosx,introduced=10.8))); -typedef bool(*CGImageMetadataTagBlock)(CFStringRef _Nonnull path, CGImageMetadataTagRef _Nonnull tag); -extern "C" void CGImageMetadataEnumerateTagsUsingBlock(CGImageMetadataRef _Nonnull metadata, CFStringRef _Nullable rootPath, CFDictionaryRef _Nullable options, CGImageMetadataTagBlock _Nonnull block) __attribute__((availability(macosx,introduced=10.8))); - - - - - - -extern "C" const CFStringRef _Nonnull kCGImageMetadataEnumerateRecursively __attribute__((availability(macosx,introduced=10.8))); -extern "C" CGImageMetadataTagRef _Nullable CGImageMetadataCopyTagMatchingImageProperty(CGImageMetadataRef _Nonnull metadata, CFStringRef _Nonnull dictionaryName, CFStringRef _Nonnull propertyName) __attribute__((availability(macosx,introduced=10.8))); -extern "C" bool CGImageMetadataSetValueMatchingImageProperty(CGMutableImageMetadataRef _Nonnull metadata, CFStringRef _Nonnull dictionaryName, CFStringRef _Nonnull propertyName, CFTypeRef _Nonnull value) __attribute__((availability(macosx,introduced=10.8))); -extern "C" CFDataRef _Nullable CGImageMetadataCreateXMPData (CGImageMetadataRef _Nonnull metadata, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.8))); -extern "C" CGImageMetadataRef _Nullable CGImageMetadataCreateFromXMPData (CFDataRef _Nonnull data) __attribute__((availability(macosx,introduced=10.8))); - - - - - - -extern "C" const CFStringRef _Nonnull kCFErrorDomainCGImageMetadata; - - - - - -typedef int32_t CGImageMetadataErrors; enum { - kCGImageMetadataErrorUnknown = 0, - kCGImageMetadataErrorUnsupportedFormat = 1, - kCGImageMetadataErrorBadArgument = 2, - kCGImageMetadataErrorConflictingArguments = 3, - kCGImageMetadataErrorPrefixConflict = 4, -}; - - - -typedef int32_t CGImageSourceStatus; enum { - kCGImageStatusUnexpectedEOF = -5, - kCGImageStatusInvalidData = -4, - kCGImageStatusUnknownType = -3, - kCGImageStatusReadingHeader = -2, - kCGImageStatusIncomplete = -1, - kCGImageStatusComplete = 0 -}; -extern "C" const CFStringRef kCGImageSourceTypeIdentifierHint __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImageSourceShouldCache __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" const CFStringRef kCGImageSourceShouldCacheImmediately __attribute__((availability(macosx,introduced=10.9))); - - - - - - - -extern "C" const CFStringRef kCGImageSourceShouldAllowFloat __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImageSourceCreateThumbnailFromImageIfAbsent __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImageSourceCreateThumbnailFromImageAlways __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" const CFStringRef kCGImageSourceThumbnailMaxPixelSize __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" const CFStringRef kCGImageSourceCreateThumbnailWithTransform __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImageSourceSubsampleFactor __attribute__((availability(macosx,introduced=10.11))); - - - - - - -extern "C" CFTypeID CGImageSourceGetTypeID (void) __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CFArrayRef _Nonnull CGImageSourceCopyTypeIdentifiers(void) __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CGImageSourceRef _Nullable CGImageSourceCreateWithDataProvider(CGDataProviderRef _Nonnull provider, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CGImageSourceRef _Nullable CGImageSourceCreateWithData(CFDataRef _Nonnull data, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CGImageSourceRef _Nullable CGImageSourceCreateWithURL(CFURLRef _Nonnull url, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" CFStringRef _Nullable CGImageSourceGetType(CGImageSourceRef _Nonnull isrc) __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" size_t CGImageSourceGetCount(CGImageSourceRef _Nonnull isrc) __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CFDictionaryRef _Nullable CGImageSourceCopyProperties(CGImageSourceRef _Nonnull isrc, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" CFDictionaryRef _Nullable CGImageSourceCopyPropertiesAtIndex(CGImageSourceRef _Nonnull isrc, size_t index, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CGImageMetadataRef _Nullable CGImageSourceCopyMetadataAtIndex (CGImageSourceRef _Nonnull isrc, size_t index, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.8))); - - - - - -extern "C" CGImageRef _Nullable CGImageSourceCreateImageAtIndex(CGImageSourceRef _Nonnull isrc, size_t index, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" void CGImageSourceRemoveCacheAtIndex(CGImageSourceRef _Nonnull isrc, size_t index) __attribute__((availability(macosx,introduced=10.9))); - - - - - - -extern "C" CGImageRef _Nullable CGImageSourceCreateThumbnailAtIndex(CGImageSourceRef _Nonnull isrc, size_t index, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" CGImageSourceRef _Nonnull CGImageSourceCreateIncremental(CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" void CGImageSourceUpdateData(CGImageSourceRef _Nonnull isrc, CFDataRef _Nonnull data, bool final) __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" void CGImageSourceUpdateDataProvider(CGImageSourceRef _Nonnull isrc, CGDataProviderRef _Nonnull provider, bool final) __attribute__((availability(macosx,introduced=10.4))); - - - - - -extern "C" CGImageSourceStatus CGImageSourceGetStatus(CGImageSourceRef _Nonnull isrc) __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" CGImageSourceStatus CGImageSourceGetStatusAtIndex(CGImageSourceRef _Nonnull isrc, size_t index) __attribute__((availability(macosx,introduced=10.4))); - -typedef struct __attribute__((objc_bridge(id))) CGImageDestination * CGImageDestinationRef; -extern "C" const CFStringRef kCGImageDestinationLossyCompressionQuality __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImageDestinationBackgroundColor __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImageDestinationImageMaxPixelSize __attribute__((availability(macosx,introduced=10.10))); - - - - -extern "C" const CFStringRef kCGImageDestinationEmbedThumbnail __attribute__((availability(macosx,introduced=10.10))); - - - - - - -extern "C" CFTypeID CGImageDestinationGetTypeID(void) __attribute__((availability(macosx,introduced=10.4))); - - - -extern "C" CFArrayRef _Nonnull CGImageDestinationCopyTypeIdentifiers(void) __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGImageDestinationRef _Nullable CGImageDestinationCreateWithDataConsumer(CGDataConsumerRef _Nonnull consumer, CFStringRef _Nonnull type, size_t count, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" CGImageDestinationRef _Nullable CGImageDestinationCreateWithData(CFMutableDataRef _Nonnull data, CFStringRef _Nonnull type, size_t count, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); -extern "C" CGImageDestinationRef _Nullable CGImageDestinationCreateWithURL(CFURLRef _Nonnull url, CFStringRef _Nonnull type, size_t count, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" void CGImageDestinationSetProperties(CGImageDestinationRef _Nonnull idst, CFDictionaryRef _Nullable properties) __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" void CGImageDestinationAddImage(CGImageDestinationRef _Nonnull idst, CGImageRef _Nonnull image, CFDictionaryRef _Nullable properties) __attribute__((availability(macosx,introduced=10.4))); -extern "C" void CGImageDestinationAddImageFromSource(CGImageDestinationRef _Nonnull idst, CGImageSourceRef _Nonnull isrc, size_t index, CFDictionaryRef _Nullable properties) __attribute__((availability(macosx,introduced=10.4))); - - - - - - - -extern "C" bool CGImageDestinationFinalize(CGImageDestinationRef _Nonnull idst) __attribute__((availability(macosx,introduced=10.4))); - - - - - - -extern "C" void CGImageDestinationAddImageAndMetadata(CGImageDestinationRef _Nonnull idst, CGImageRef _Nonnull image, CGImageMetadataRef _Nullable metadata, CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageDestinationMetadata __attribute__((availability(macosx,introduced=10.8))); -extern "C" const CFStringRef kCGImageDestinationMergeMetadata __attribute__((availability(macosx,introduced=10.8))); - - - - - - -extern "C" const CFStringRef kCGImageMetadataShouldExcludeXMP __attribute__((availability(macosx,introduced=10.8))); - - - - - - - -extern "C" const CFStringRef kCGImageMetadataShouldExcludeGPS __attribute__((availability(macosx,introduced=10.10))); - - - - - - - -extern "C" const CFStringRef kCGImageDestinationDateTime __attribute__((availability(macosx,introduced=10.8))); - - - - - -extern "C" const CFStringRef kCGImageDestinationOrientation __attribute__((availability(macosx,introduced=10.8))); -extern "C" bool CGImageDestinationCopyImageSource(CGImageDestinationRef _Nonnull idst, CGImageSourceRef _Nonnull isrc, CFDictionaryRef _Nullable options, _Nullable CFErrorRef * _Nullable err) __attribute__((availability(macosx,introduced=10.8))); - -extern "C" const CFStringRef kCGImagePropertyTIFFDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGIFDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyJFIFDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyPNGDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyRawDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyCIFFDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyMakerCanonDictionary __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonDictionary __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerMinoltaDictionary __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerFujiDictionary __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerOlympusDictionary __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerPentaxDictionary __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImageProperty8BIMDictionary __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyDNGDictionary __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyExifAuxDictionary __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyOpenEXRDictionary __attribute__((availability(macosx,introduced=10.9))); -extern "C" const CFStringRef kCGImagePropertyMakerAppleDictionary __attribute__((availability(macosx,introduced=10.10))); -extern "C" const CFStringRef kCGImagePropertyFileSize __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyPixelHeight __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyPixelWidth __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyDPIHeight __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyDPIWidth __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyDepth __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyOrientation __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyIsFloat __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyIsIndexed __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyHasAlpha __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyColorModel __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyProfileName __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyColorModelRGB __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyColorModelGray __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyColorModelCMYK __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyColorModelLab __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyTIFFCompression __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFPhotometricInterpretation __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFDocumentName __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFImageDescription __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFMake __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFModel __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFOrientation __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFXResolution __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFYResolution __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFResolutionUnit __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFSoftware __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFTransferFunction __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFDateTime __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFArtist __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFHostComputer __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFCopyright __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFWhitePoint __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFPrimaryChromaticities __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyTIFFTileWidth __attribute__((availability(macosx,introduced=10.11))); -extern "C" const CFStringRef kCGImagePropertyTIFFTileLength __attribute__((availability(macosx,introduced=10.11))); - - - -extern "C" const CFStringRef kCGImagePropertyJFIFVersion __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyJFIFXDensity __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyJFIFYDensity __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyJFIFDensityUnit __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyJFIFIsProgressive __attribute__((availability(macosx,introduced=10.4))); - - - - -extern "C" const CFStringRef kCGImagePropertyExifExposureTime __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFNumber __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifExposureProgram __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSpectralSensitivity __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifISOSpeedRatings __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifOECF __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSensitivityType __attribute__((availability(macosx,introduced=10.9))); -extern "C" const CFStringRef kCGImagePropertyExifStandardOutputSensitivity __attribute__((availability(macosx,introduced=10.9))); -extern "C" const CFStringRef kCGImagePropertyExifRecommendedExposureIndex __attribute__((availability(macosx,introduced=10.9))); -extern "C" const CFStringRef kCGImagePropertyExifISOSpeed __attribute__((availability(macosx,introduced=10.9))); -extern "C" const CFStringRef kCGImagePropertyExifISOSpeedLatitudeyyy __attribute__((availability(macosx,introduced=10.9))); -extern "C" const CFStringRef kCGImagePropertyExifISOSpeedLatitudezzz __attribute__((availability(macosx,introduced=10.9))); -extern "C" const CFStringRef kCGImagePropertyExifVersion __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifDateTimeOriginal __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifDateTimeDigitized __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifComponentsConfiguration __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifCompressedBitsPerPixel __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifShutterSpeedValue __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifApertureValue __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifBrightnessValue __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifExposureBiasValue __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifMaxApertureValue __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSubjectDistance __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifMeteringMode __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifLightSource __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFlash __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFocalLength __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSubjectArea __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifMakerNote __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifUserComment __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSubsecTime __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSubsecTimeOriginal __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSubsecTimeDigitized __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFlashPixVersion __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifColorSpace __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifPixelXDimension __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifPixelYDimension __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifRelatedSoundFile __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFlashEnergy __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSpatialFrequencyResponse __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFocalPlaneXResolution __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFocalPlaneYResolution __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFocalPlaneResolutionUnit __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSubjectLocation __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifExposureIndex __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSensingMethod __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFileSource __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSceneType __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifCFAPattern __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifCustomRendered __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifExposureMode __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifWhiteBalance __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifDigitalZoomRatio __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifFocalLenIn35mmFilm __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSceneCaptureType __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifGainControl __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifContrast __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSaturation __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSharpness __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifDeviceSettingDescription __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifSubjectDistRange __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifImageUniqueID __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyExifCameraOwnerName __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyExifBodySerialNumber __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyExifLensSpecification __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyExifLensMake __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyExifLensModel __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyExifLensSerialNumber __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyExifGamma __attribute__((availability(macosx,introduced=10.4))); - - -extern "C" const CFStringRef kCGImagePropertyExifSubsecTimeOrginal __attribute__((availability(macosx,introduced=10.4))); - - -extern "C" const CFStringRef kCGImagePropertyExifAuxLensInfo __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyExifAuxLensModel __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyExifAuxSerialNumber __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyExifAuxLensID __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyExifAuxLensSerialNumber __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyExifAuxImageNumber __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyExifAuxFlashCompensation __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyExifAuxOwnerName __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyExifAuxFirmware __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" const CFStringRef kCGImagePropertyGIFLoopCount __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGIFDelayTime __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGIFImageColorMap __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGIFHasGlobalColorMap __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGIFUnclampedDelayTime __attribute__((availability(macosx,introduced=10.7))); - - - -extern "C" const CFStringRef kCGImagePropertyPNGGamma __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyPNGInterlaceType __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyPNGXPixelsPerMeter __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyPNGYPixelsPerMeter __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyPNGsRGBIntent __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyPNGChromaticities __attribute__((availability(macosx,introduced=10.4))); - -extern "C" const CFStringRef kCGImagePropertyPNGAuthor __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyPNGCopyright __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyPNGCreationTime __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyPNGDescription __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyPNGModificationTime __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyPNGSoftware __attribute__((availability(macosx,introduced=10.7))); -extern "C" const CFStringRef kCGImagePropertyPNGTitle __attribute__((availability(macosx,introduced=10.7))); - -extern "C" const CFStringRef kCGImagePropertyAPNGLoopCount __attribute__((availability(macosx,introduced=10.10))); -extern "C" const CFStringRef kCGImagePropertyAPNGDelayTime __attribute__((availability(macosx,introduced=10.10))); -extern "C" const CFStringRef kCGImagePropertyAPNGUnclampedDelayTime __attribute__((availability(macosx,introduced=10.10))); - - - -extern "C" const CFStringRef kCGImagePropertyGPSVersion __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSLatitudeRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSLatitude __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSLongitudeRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSLongitude __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSAltitudeRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSAltitude __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSTimeStamp __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSSatellites __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSStatus __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSMeasureMode __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDOP __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSSpeedRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSSpeed __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSTrackRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSTrack __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSImgDirectionRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSImgDirection __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSMapDatum __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDestLatitudeRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDestLatitude __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDestLongitudeRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDestLongitude __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDestBearingRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDestBearing __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDestDistanceRef __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDestDistance __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSProcessingMethod __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSAreaInformation __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDateStamp __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSDifferental __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyGPSHPositioningError __attribute__((availability(macosx,introduced=10.10))); - - - -extern "C" const CFStringRef kCGImagePropertyIPTCObjectTypeReference __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCObjectAttributeReference __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCObjectName __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCEditStatus __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCEditorialUpdate __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCUrgency __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCSubjectReference __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCCategory __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCSupplementalCategory __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCFixtureIdentifier __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCKeywords __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCContentLocationCode __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCContentLocationName __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCReleaseDate __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCReleaseTime __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCExpirationDate __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCExpirationTime __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCSpecialInstructions __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCActionAdvised __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCReferenceService __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCReferenceDate __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCReferenceNumber __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCDateCreated __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCTimeCreated __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCDigitalCreationDate __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCDigitalCreationTime __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCOriginatingProgram __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCProgramVersion __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCObjectCycle __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCByline __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCBylineTitle __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCCity __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCSubLocation __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCProvinceState __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCCountryPrimaryLocationCode __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCCountryPrimaryLocationName __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCOriginalTransmissionReference __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCHeadline __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCCredit __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCSource __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCCopyrightNotice __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCContact __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCCaptionAbstract __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCWriterEditor __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCImageType __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCImageOrientation __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCLanguageIdentifier __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCStarRating __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImagePropertyIPTCCreatorContactInfo __attribute__((availability(macosx,introduced=10.6))); -extern "C" const CFStringRef kCGImagePropertyIPTCRightsUsageTerms __attribute__((availability(macosx,introduced=10.6))); -extern "C" const CFStringRef kCGImagePropertyIPTCScene __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" const CFStringRef kCGImagePropertyIPTCContactInfoCity __attribute__((availability(macosx,introduced=10.6))); -extern "C" const CFStringRef kCGImagePropertyIPTCContactInfoCountry __attribute__((availability(macosx,introduced=10.6))); -extern "C" const CFStringRef kCGImagePropertyIPTCContactInfoAddress __attribute__((availability(macosx,introduced=10.6))); -extern "C" const CFStringRef kCGImagePropertyIPTCContactInfoPostalCode __attribute__((availability(macosx,introduced=10.6))); -extern "C" const CFStringRef kCGImagePropertyIPTCContactInfoStateProvince __attribute__((availability(macosx,introduced=10.6))); -extern "C" const CFStringRef kCGImagePropertyIPTCContactInfoEmails __attribute__((availability(macosx,introduced=10.6))); -extern "C" const CFStringRef kCGImagePropertyIPTCContactInfoPhones __attribute__((availability(macosx,introduced=10.6))); -extern "C" const CFStringRef kCGImagePropertyIPTCContactInfoWebURLs __attribute__((availability(macosx,introduced=10.6))); - - - -extern "C" const CFStringRef kCGImageProperty8BIMLayerNames __attribute__((availability(macosx,introduced=10.4))); -extern "C" const CFStringRef kCGImageProperty8BIMVersion __attribute__((availability(macosx,introduced=10.10))); - - - -extern "C" const CFStringRef kCGImagePropertyDNGVersion __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyDNGBackwardVersion __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyDNGUniqueCameraModel __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyDNGLocalizedCameraModel __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyDNGCameraSerialNumber __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyDNGLensInfo __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" const CFStringRef kCGImagePropertyCIFFDescription __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFFirmware __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFOwnerName __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFImageName __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFImageFileName __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFReleaseMethod __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFReleaseTiming __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFRecordID __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFSelfTimingTime __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFCameraSerialNumber __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFImageSerialNumber __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFContinuousDrive __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFFocusMode __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFMeteringMode __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFShootingMode __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFLensModel __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFLensMaxMM __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFLensMinMM __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFWhiteBalanceIndex __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFFlashExposureComp __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyCIFFMeasuredEV __attribute__((availability(macosx,introduced=10.5))); - - - - -extern "C" const CFStringRef kCGImagePropertyMakerNikonISOSetting __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonColorMode __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonQuality __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonWhiteBalanceMode __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonSharpenMode __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonFocusMode __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonFlashSetting __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonISOSelection __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonFlashExposureComp __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonImageAdjustment __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonLensAdapter __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonLensType __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonLensInfo __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonFocusDistance __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonDigitalZoom __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonShootingMode __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonCameraSerialNumber __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerNikonShutterCount __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" const CFStringRef kCGImagePropertyMakerCanonOwnerName __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerCanonCameraSerialNumber __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerCanonImageSerialNumber __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerCanonFlashExposureComp __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerCanonContinuousDrive __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerCanonLensModel __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerCanonFirmware __attribute__((availability(macosx,introduced=10.5))); -extern "C" const CFStringRef kCGImagePropertyMakerCanonAspectRatioInfo __attribute__((availability(macosx,introduced=10.5))); - - - -extern "C" const CFStringRef kCGImagePropertyOpenEXRAspectRatio __attribute__((availability(macosx,introduced=10.9))); - - - -typedef uint32_t CGImagePropertyOrientation; enum { - kCGImagePropertyOrientationUp = 1, - kCGImagePropertyOrientationUpMirrored, - kCGImagePropertyOrientationDown, - kCGImagePropertyOrientationDownMirrored, - kCGImagePropertyOrientationLeftMirrored, - kCGImagePropertyOrientationRight, - kCGImagePropertyOrientationRightMirrored, - kCGImagePropertyOrientationLeft -}; -extern "C" const CFStringRef kCGImagePropertyPNGCompressionFilter __attribute__((availability(macosx,introduced=10.11))); - - - -extern "C" { - - -#pragma options align=power -enum { - kDictionaryFileType = 'dict', - kDCMDictionaryHeaderSignature = 'dict', - kDCMDictionaryHeaderVersion = 2 -}; - -enum { - kDCMAnyFieldTag = typeWildCard, - kDCMAnyFieldType = typeWildCard -}; - - - - -enum { - keyDCMFieldTag = 'ftag', - keyDCMFieldType = 'ftyp', - keyDCMMaxRecordSize = 'mrsz', - keyDCMFieldAttributes = 'fatr', - keyDCMFieldDefaultData = 'fdef', - keyDCMFieldName = 'fnam', - keyDCMFieldFindMethods = 'ffnd' -}; - - - - -enum { - typeDCMFieldAttributes = 'fatr', - typeDCMFindMethod = 'fmth' -}; - - - - - -enum { - kDCMIndexedFieldMask = 0x00000001, - kDCMRequiredFieldMask = 0x00000002, - kDCMIdentifyFieldMask = 0x00000004, - kDCMFixedSizeFieldMask = 0x00000008, - kDCMHiddenFieldMask = (int)0x80000000 -}; - -typedef OptionBits DCMFieldAttributes; - - - -enum { - pDCMAccessMethod = 'amtd', - pDCMPermission = 'perm', - pDCMListing = 'list', - pDCMMaintenance = 'mtnc', - pDCMLocale = 'locl', - pDCMClass = pClass, - pDCMCopyright = 'info' -}; - - - - -enum { - kDCMReadOnlyDictionary = 0, - kDCMReadWriteDictionary = 1 -}; - - - - -enum { - kDCMAllowListing = 0, - kDCMProhibitListing = 1 -}; - - - - -enum { - kDCMUserDictionaryClass = 0, - kDCMSpecificDictionaryClass = 1, - kDCMBasicDictionaryClass = 2 -}; - - - - -enum { - kDCMFindMethodExactMatch = kAEEquals, - kDCMFindMethodBeginningMatch = kAEBeginsWith, - kDCMFindMethodContainsMatch = kAEContains, - kDCMFindMethodEndingMatch = kAEEndsWith, - kDCMFindMethodForwardTrie = 'ftri', - kDCMFindMethodBackwardTrie = 'btri' -}; - -typedef OSType DCMFindMethod; - - - -enum { - kDCMCanUseFileDictionaryMask = 0x00000001, - kDCMCanUseMemoryDictionaryMask = 0x00000002, - kDCMCanStreamDictionaryMask = 0x00000004, - kDCMCanHaveMultipleIndexMask = 0x00000008, - kDCMCanModifyDictionaryMask = 0x00000010, - kDCMCanCreateDictionaryMask = 0x00000020, - kDCMCanAddDictionaryFieldMask = 0x00000040, - kDCMCanUseTransactionMask = 0x00000080 -}; - -typedef OptionBits DCMAccessMethodFeature; -typedef UInt32 DCMUniqueID; -typedef struct OpaqueDCMObjectID* DCMObjectID; -typedef DCMObjectID DCMAccessMethodID; -typedef DCMObjectID DCMDictionaryID; - -typedef struct OpaqueDCMObjectRef* DCMObjectRef; -typedef DCMObjectRef DCMDictionaryRef; -typedef DCMObjectRef DCMDictionaryStreamRef; - -typedef struct OpaqueDCMObjectIterator* DCMObjectIterator; -typedef DCMObjectIterator DCMAccessMethodIterator; -typedef DCMObjectIterator DCMDictionaryIterator; -typedef struct OpaqueDCMFoundRecordIterator* DCMFoundRecordIterator; - - - -typedef DescType DCMFieldTag; -typedef DescType DCMFieldType; - - - -struct DCMDictionaryHeader { - FourCharCode headerSignature; - UInt32 headerVersion; - UInt32 headerSize; - Str63 accessMethod; -}; -typedef struct DCMDictionaryHeader DCMDictionaryHeader; - - - -typedef Boolean ( * DCMProgressFilterProcPtr)(Boolean determinateProcess, UInt16 percentageComplete, UInt32 callbackUD); -typedef DCMProgressFilterProcPtr DCMProgressFilterUPP; - inline Boolean DCMDictionaryManagerAvailable() { return true; } -enum { - kMaxYomiLengthInAppleJapaneseDictionary = 40, - kMaxKanjiLengthInAppleJapaneseDictionary = 64 -}; - - - - -enum { - kDCMJapaneseYomiTag = 'yomi', - kDCMJapaneseHyokiTag = 'hyok', - kDCMJapaneseHinshiTag = 'hins', - kDCMJapaneseWeightTag = 'hind', - kDCMJapanesePhoneticTag = 'hton', - kDCMJapaneseAccentTag = 'acnt', - kDCMJapaneseOnKunReadingTag = 'OnKn', - kDCMJapaneseFukugouInfoTag = 'fuku' -}; - -enum { - kDCMJapaneseYomiType = typeUnicodeText, - kDCMJapaneseHyokiType = typeUnicodeText, - kDCMJapaneseHinshiType = 'hins', - kDCMJapaneseWeightType = typeSInt16, - kDCMJapanesePhoneticType = typeUnicodeText, - kDCMJapaneseAccentType = 'byte', - kDCMJapaneseOnKunReadingType = typeUnicodeText, - kDCMJapaneseFukugouInfoType = 'fuku' -}; - - - -#pragma options align=reset - - -} -extern "C" { - - -#pragma options align=power - -typedef struct OpaqueLAEnvironmentRef* LAEnvironmentRef; -typedef struct OpaqueLAContextRef* LAContextRef; -typedef AEKeyword LAPropertyKey; -typedef DescType LAPropertyType; - - - -struct LAMorphemeRec { - UInt32 sourceTextLength; - LogicalAddress sourceTextPtr; - UInt32 morphemeTextLength; - LogicalAddress morphemeTextPtr; - UInt32 partOfSpeech; -}; -typedef struct LAMorphemeRec LAMorphemeRec; -struct LAMorphemesArray { - ItemCount morphemesCount; - UInt32 processedTextLength; - UInt32 morphemesTextLength; - LAMorphemeRec morphemes[1]; -}; -typedef struct LAMorphemesArray LAMorphemesArray; -typedef LAMorphemesArray * LAMorphemesArrayPtr; -enum { - kLAMorphemesArrayVersion = 0 -}; - - - - -typedef AERecord LAMorphemeBundle; -typedef AERecord LAMorphemePath; -typedef AERecord LAMorpheme; -typedef AERecord LAHomograph; -enum { - keyAELAMorphemeBundle = 'lmfb', - keyAELAMorphemePath = 'lmfp', - keyAELAMorpheme = 'lmfn', - keyAELAHomograph = 'lmfh' -}; - -enum { - typeLAMorphemeBundle = typeAERecord, - typeLAMorphemePath = typeAERecord, - typeLAMorpheme = typeAEList, - typeLAHomograph = typeAEList -}; - - - - -enum { - keyAEMorphemePartOfSpeechCode = 'lamc', - keyAEMorphemeTextRange = 'lamt' -}; - -enum { - typeAEMorphemePartOfSpeechCode = 'lamc', - typeAEMorphemeTextRange = 'lamt' -}; - -typedef UInt32 MorphemePartOfSpeech; -struct MorphemeTextRange { - UInt32 sourceOffset; - UInt32 length; -}; -typedef struct MorphemeTextRange MorphemeTextRange; - - - -enum { - kLAEndOfSourceTextMask = 0x00000001 -}; - - - - -enum { - kLADefaultEdge = 0, - kLAFreeEdge = 1, - kLAIncompleteEdge = 2 -}; - - - - -enum { - kLAAllMorphemes = 0 -}; - inline Boolean LALanguageAnalysisAvailable() { return true; } -enum { - kAppleJapaneseDictionarySignature = 'jlan' -}; - - - - -enum { - kMaxInputLengthOfAppleJapaneseEngine = 200 -}; - - - - - -typedef MorphemePartOfSpeech JapanesePartOfSpeech; -typedef UInt16 HomographWeight; -typedef UInt8 HomographAccent; - - - -enum { - keyAEHomographDicInfo = 'lahd', - keyAEHomographWeight = 'lahw', - keyAEHomographAccent = 'laha' -}; - -enum { - typeAEHomographDicInfo = 'lahd', - typeAEHomographWeight = typeSInt16, - typeAEHomographAccent = 'laha' -}; - - - - -struct HomographDicInfoRec { - DCMDictionaryID dictionaryID; - DCMUniqueID uniqueID; -}; -typedef struct HomographDicInfoRec HomographDicInfoRec; -enum { - kLASpeechRoughClassMask = 0x0000F000, - kLASpeechMediumClassMask = 0x0000FF00, - kLASpeechStrictClassMask = 0x0000FFF0, - kLASpeechKatsuyouMask = 0x0000000F -}; - - - - - -enum { - kLASpeechMeishi = 0x00000000, - kLASpeechFutsuuMeishi = 0x00000000, - kLASpeechJinmei = 0x00000100, - kLASpeechJinmeiSei = 0x00000110, - kLASpeechJinmeiMei = 0x00000120, - kLASpeechChimei = 0x00000200, - kLASpeechSetsubiChimei = 0x00000210, - kLASpeechSoshikimei = 0x00000300, - kLASpeechKoyuuMeishi = 0x00000400, - kLASpeechSahenMeishi = 0x00000500, - kLASpeechKeidouMeishi = 0x00000600, - kLASpeechRentaishi = 0x00001000, - kLASpeechFukushi = 0x00002000, - kLASpeechSetsuzokushi = 0x00003000, - kLASpeechKandoushi = 0x00004000, - kLASpeechDoushi = 0x00005000, - kLASpeechGodanDoushi = 0x00005000, - kLASpeechKagyouGodan = 0x00005000, - kLASpeechSagyouGodan = 0x00005010, - kLASpeechTagyouGodan = 0x00005020, - kLASpeechNagyouGodan = 0x00005030, - kLASpeechMagyouGodan = 0x00005040, - kLASpeechRagyouGodan = 0x00005050, - kLASpeechWagyouGodan = 0x00005060, - kLASpeechGagyouGodan = 0x00005070, - kLASpeechBagyouGodan = 0x00005080, - kLASpeechIchidanDoushi = 0x00005100, - kLASpeechKahenDoushi = 0x00005200, - kLASpeechSahenDoushi = 0x00005300, - kLASpeechZahenDoushi = 0x00005400, - kLASpeechKeiyoushi = 0x00006000, - kLASpeechKeiyoudoushi = 0x00007000, - kLASpeechSettougo = 0x00008000, - kLASpeechSuujiSettougo = 0x00008100, - kLASpeechSetsubigo = 0x00009000, - kLASpeechJinmeiSetsubigo = 0x00009100, - kLASpeechChimeiSetsubigo = 0x00009200, - kLASpeechSoshikimeiSetsubigo = 0x00009300, - kLASpeechSuujiSetsubigo = 0x00009400, - kLASpeechMuhinshi = 0x0000A000, - kLASpeechTankanji = 0x0000A000, - kLASpeechKigou = 0x0000A100, - kLASpeechKuten = 0x0000A110, - kLASpeechTouten = 0x0000A120, - kLASpeechSuushi = 0x0000A200, - kLASpeechDokuritsugo = 0x0000A300, - kLASpeechSeiku = 0x0000A400, - kLASpeechJodoushi = 0x0000B000, - kLASpeechJoshi = 0x0000C000 -}; - - - - - -enum { - kLASpeechKatsuyouGokan = 0x00000001, - kLASpeechKatsuyouMizen = 0x00000002, - kLASpeechKatsuyouRenyou = 0x00000003, - kLASpeechKatsuyouSyuushi = 0x00000004, - kLASpeechKatsuyouRentai = 0x00000005, - kLASpeechKatsuyouKatei = 0x00000006, - kLASpeechKatsuyouMeirei = 0x00000007 -}; - - - -#pragma options align=reset - - -} - - - -typedef const void * PMObject; -typedef struct OpaquePMPrintSettings* PMPrintSettings; -typedef struct OpaquePMPageFormat* PMPageFormat; -typedef struct OpaquePMPrintSession* PMPrintSession; -typedef struct OpaquePMPrinter* PMPrinter; -typedef struct OpaquePMServer* PMServer; -typedef struct OpaquePMPreset* PMPreset; -typedef struct OpaquePMPaper* PMPaper; -enum { - kPMCancel = 0x0080 -}; -typedef UInt16 PMDestinationType; -enum { - kPMDestinationInvalid = 0, - kPMDestinationPrinter = 1, - kPMDestinationFile = 2, - kPMDestinationFax = 3, - kPMDestinationPreview = 4, - kPMDestinationProcessPDF = 5 -}; - - - -typedef UInt16 PMOrientation; -enum { - kPMPortrait = 1, - kPMLandscape = 2, - kPMReversePortrait = 3, - kPMReverseLandscape = 4 -}; - - -typedef UInt16 PMPrinterState; -enum { - kPMPrinterIdle = 3, - kPMPrinterProcessing = 4, - kPMPrinterStopped = 5 -}; - -typedef UInt32 PMColorSpaceModel; -enum { - kPMUnknownColorSpaceModel = 0, - kPMGrayColorSpaceModel = 1, - kPMRGBColorSpaceModel = 2, - kPMCMYKColorSpaceModel = 3, - kPMDevNColorSpaceModel = 4 -}; - - - - -typedef UInt32 PMQualityMode; -enum { - kPMQualityLowest = 0x0000, - kPMQualityInkSaver = 0x0001, - kPMQualityDraft = 0x0004, - kPMQualityNormal = 0x0008, - kPMQualityPhoto = 0x000B, - kPMQualityBest = 0x000D, - kPMQualityHighest = 0x000F -}; - - - -typedef UInt32 PMPaperType; -enum { - kPMPaperTypeUnknown = 0x0000, - kPMPaperTypePlain = 0x0001, - kPMPaperTypeCoated = 0x0002, - kPMPaperTypePremium = 0x0003, - kPMPaperTypeGlossy = 0x0004, - kPMPaperTypeTransparency = 0x0005, - kPMPaperTypeTShirt = 0x0006 -}; - - -typedef UInt16 PMScalingAlignment; -enum { - kPMScalingPinTopLeft = 1, - kPMScalingPinTopRight = 2, - kPMScalingPinBottomLeft = 3, - kPMScalingPinBottomRight = 4, - kPMScalingCenterOnPaper = 5, - kPMScalingCenterOnImgArea = 6 -}; - - -typedef UInt32 PMDuplexMode; -enum { - kPMDuplexNone = 0x0001, - kPMDuplexNoTumble = 0x0002, - kPMDuplexTumble = 0x0003, - kPMSimplexTumble = 0x0004 -}; - - -typedef UInt16 PMLayoutDirection; -enum { - - kPMLayoutLeftRightTopBottom = 1, - kPMLayoutLeftRightBottomTop = 2, - kPMLayoutRightLeftTopBottom = 3, - kPMLayoutRightLeftBottomTop = 4, - kPMLayoutTopBottomLeftRight = 5, - kPMLayoutTopBottomRightLeft = 6, - kPMLayoutBottomTopLeftRight = 7, - kPMLayoutBottomTopRightLeft = 8 -}; - - -typedef UInt16 PMBorderType; -enum { - kPMBorderSingleHairline = 1, - kPMBorderDoubleHairline = 2, - kPMBorderSingleThickline = 3, - kPMBorderDoubleThickline = 4 -}; - - - - - -typedef OptionBits PMPrintDialogOptionFlags; -enum { - kPMHideInlineItems = (0L << 0), - kPMShowDefaultInlineItems = (1L << 15), - kPMShowInlineCopies = (1L << 0), - kPMShowInlinePageRange = (1L << 1), - kPMShowInlinePageRangeWithSelection = (1L << 6), - kPMShowInlinePaperSize = (1L << 2), - kPMShowInlineOrientation = (1L << 3), - kPMShowInlineScale = (1L << 7), - kPMShowPageAttributesPDE = (1L << 8), -}; - -typedef UInt16 PMPPDDomain; -enum { - kAllPPDDomains = 1, - kSystemPPDDomain = 2, - kLocalPPDDomain = 3, - kNetworkPPDDomain = 4, - kUserPPDDomain = 5, - kCUPSPPDDomain = 6 -}; -enum { - kPMNoError = noErr, - kPMGeneralError = -30870, - kPMOutOfScope = -30871, - kPMInvalidParameter = paramErr, - kPMNoDefaultPrinter = -30872, - kPMNotImplemented = -30873, - kPMNoSuchEntry = -30874, - kPMInvalidPrintSettings = -30875, - kPMInvalidPageFormat = -30876, - kPMValueOutOfRange = -30877, - kPMLockIgnored = -30878 -}; - -enum { - kPMInvalidPrintSession = -30879, - kPMInvalidPrinter = -30880, - kPMObjectInUse = -30881, - kPMInvalidPreset = -30899 -}; - - -enum { - kPMPrintAllPages = -1 -}; - -enum { - kPMUnlocked = false -}; - -struct PMRect { - double top; - double left; - double bottom; - double right; -}; -typedef struct PMRect PMRect; -struct PMResolution { - double hRes; - double vRes; -}; -typedef struct PMResolution PMResolution; -struct PMLanguageInfo { - Str32 level; - Str32 version; - Str32 release; -}; -typedef struct PMLanguageInfo PMLanguageInfo; - -typedef PMRect PMPaperMargins; -enum PMDataFormat { - kPMDataFormatXMLDefault = 0, - kPMDataFormatXMLMinimal = 1, - kPMDataFormatXMLCompressed = 2 -}; -typedef enum PMDataFormat PMDataFormat; - - - -extern "C" { -extern OSStatus -PMRetain(PMObject _Nullable object) ; -extern OSStatus -PMRelease(PMObject _Nullable object) ; -extern OSStatus -PMCreateSession(_Nonnull PMPrintSession* _Nonnull printSession) ; -extern OSStatus -PMSessionError(PMPrintSession printSession) ; -extern OSStatus -PMSessionSetError( - PMPrintSession printSession, - OSStatus printError) ; -extern OSStatus -PMSessionBeginCGDocumentNoDialog( - PMPrintSession printSession, - PMPrintSettings printSettings, - PMPageFormat pageFormat) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMSessionEndDocumentNoDialog(PMPrintSession printSession) ; -extern OSStatus -PMSessionBeginPageNoDialog( - PMPrintSession printSession, - PMPageFormat _Nullable pageFormat, - const PMRect * _Nullable pageFrame) ; -extern OSStatus -PMSessionEndPageNoDialog(PMPrintSession printSession) ; -extern OSStatus -PMSessionGetCGGraphicsContext( - PMPrintSession printSession, - CGContextRef _Nullable * _Nonnull context) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMSessionGetDestinationType( - PMPrintSession printSession, - PMPrintSettings printSettings, - PMDestinationType * destTypeP) __attribute__((availability(macosx,introduced=10.1))); -extern OSStatus -PMSessionCopyDestinationFormat( - PMPrintSession printSession, - PMPrintSettings printSettings, - CFStringRef _Nullable * _Nonnull destFormatP) __attribute__((availability(macosx,introduced=10.1))); -extern OSStatus -PMSessionCopyDestinationLocation( - PMPrintSession printSession, - PMPrintSettings printSettings, - CFURLRef _Nullable * _Nonnull destLocationP) __attribute__((availability(macosx,introduced=10.1))); -extern OSStatus -PMSessionSetDestination( - PMPrintSession printSession, - PMPrintSettings printSettings, - PMDestinationType destType, - CFStringRef _Nullable destFormat, - CFURLRef _Nullable destLocation) __attribute__((availability(macosx,introduced=10.1))); -extern OSStatus -PMSessionCopyOutputFormatList( - PMPrintSession printSession, - PMDestinationType destType, - CFArrayRef _Nullable * _Nonnull documentFormatP) __attribute__((availability(macosx,introduced=10.1))); -extern OSStatus -PMSessionCreatePageFormatList( - PMPrintSession printSession, - PMPrinter _Nullable printer, - CFArrayRef _Nullable * _Nonnull pageFormatList) __attribute__((availability(macosx,introduced=10.1))); -extern OSStatus -PMSessionCreatePrinterList( - PMPrintSession printSession, - CFArrayRef _Nonnull * _Nonnull printerList, - CFIndex * _Nullable currentIndex, - PMPrinter _Nonnull * _Nullable currentPrinter) __attribute__((availability(macosx,introduced=10.1))); -extern OSStatus -PMSessionGetCurrentPrinter( - PMPrintSession printSession, - PMPrinter _Nonnull * _Nonnull currentPrinter) ; -extern OSStatus -PMSessionSetCurrentPMPrinter( - PMPrintSession session, - PMPrinter printer) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMSessionGetDataFromSession( - PMPrintSession printSession, - CFStringRef key, - CFTypeRef _Nullable * _Nonnull data) ; -extern OSStatus -PMSessionSetDataInSession( - PMPrintSession printSession, - CFStringRef key, - CFTypeRef data) ; -extern OSStatus -PMCreatePageFormat(PMPageFormat _Nonnull * _Nonnull pageFormat) ; -extern OSStatus -PMSessionDefaultPageFormat( - PMPrintSession printSession, - PMPageFormat pageFormat) ; -extern OSStatus -PMSessionValidatePageFormat( - PMPrintSession printSession, - PMPageFormat pageFormat, - Boolean * _Nullable changed) ; -extern OSStatus -PMCopyPageFormat( - PMPageFormat formatSrc, - PMPageFormat formatDest) ; -extern OSStatus -PMCreatePageFormatWithPMPaper( - PMPageFormat _Nonnull * _Nonnull pageFormat, - PMPaper paper) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPageFormatCreateDataRepresentation( - PMPageFormat pageFormat, - CFDataRef _Nonnull * _Nonnull data, - PMDataFormat format) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPageFormatCreateWithDataRepresentation( - CFDataRef data, - PMPageFormat _Nonnull * _Nonnull pageFormat) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMGetAdjustedPageRect( - PMPageFormat pageFormat, - PMRect * pageRect) ; -extern OSStatus -PMGetAdjustedPaperRect( - PMPageFormat pageFormat, - PMRect * paperRect) ; -extern OSStatus -PMGetOrientation( - PMPageFormat pageFormat, - PMOrientation * orientation) ; -extern OSStatus -PMGetPageFormatExtendedData( - PMPageFormat pageFormat, - OSType dataID, - UInt32 * _Nullable size, - void * _Nullable extendedData) ; -extern OSStatus -PMPageFormatGetPrinterID( - PMPageFormat pageFormat, - CFStringRef _Nullable * _Nonnull printerID ) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMGetScale( - PMPageFormat pageFormat, - double * scale) ; -extern OSStatus -PMGetUnadjustedPageRect( - PMPageFormat pageFormat, - PMRect * pageRect) ; -extern OSStatus -PMGetUnadjustedPaperRect( - PMPageFormat pageFormat, - PMRect * paperRect) ; -extern OSStatus -PMSetOrientation( - PMPageFormat pageFormat, - PMOrientation orientation, - Boolean lock) ; -extern OSStatus -PMSetPageFormatExtendedData( - PMPageFormat pageFormat, - OSType dataID, - UInt32 size, - void * extendedData) ; -extern OSStatus -PMSetScale( - PMPageFormat pageFormat, - double scale) ; -extern OSStatus -PMCreatePrintSettings( - PMPrintSettings _Nonnull * _Nonnull printSettings) ; -extern OSStatus -PMSessionDefaultPrintSettings( - PMPrintSession printSession, - PMPrintSettings printSettings) ; -extern OSStatus -PMSessionValidatePrintSettings( - PMPrintSession printSession, - PMPrintSettings printSettings, - Boolean * _Nullable changed) ; -extern OSStatus -PMCopyPrintSettings( - PMPrintSettings settingSrc, - PMPrintSettings settingDest) ; -extern OSStatus -PMPrintSettingsCreateDataRepresentation( - PMPrintSettings printSettings, - CFDataRef _Nonnull * _Nonnull data, - PMDataFormat format) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPrintSettingsCreateWithDataRepresentation( - CFDataRef data, - PMPrintSettings _Nonnull * _Nonnull printSettings) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMGetCollate( - PMPrintSettings printSettings, - Boolean * collate) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -PMGetCopies( - PMPrintSettings printSettings, - UInt32 * copies) ; -extern OSStatus -PMGetDuplex( - PMPrintSettings printSettings, - PMDuplexMode * duplexSetting) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMGetFirstPage( - PMPrintSettings printSettings, - UInt32 * first) ; -extern OSStatus -PMGetLastPage( - PMPrintSettings printSettings, - UInt32 * last) ; -extern OSStatus -PMGetPageRange( - PMPrintSettings printSettings, - UInt32 * minPage, - UInt32 * maxPage) ; -extern OSStatus -PMPrintSettingsGetJobName( - PMPrintSettings printSettings, - CFStringRef _Nullable * _Nonnull name) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMPrintSettingsGetValue( - PMPrintSettings printSettings, - CFStringRef key, - CFTypeRef _Nullable * _Nonnull value) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMSetCollate( - PMPrintSettings printSettings, - Boolean collate) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -PMSetCopies( - PMPrintSettings printSettings, - UInt32 copies, - Boolean lock) ; -extern OSStatus -PMSetDuplex( - PMPrintSettings printSettings, - PMDuplexMode duplexSetting) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMSetFirstPage( - PMPrintSettings printSettings, - UInt32 first, - Boolean lock) ; -extern OSStatus -PMSetLastPage( - PMPrintSettings printSettings, - UInt32 last, - Boolean lock) ; -extern OSStatus -PMSetPageRange( - PMPrintSettings printSettings, - UInt32 minPage, - UInt32 maxPage) ; -extern OSStatus -PMPrintSettingsSetJobName( - PMPrintSettings printSettings, - CFStringRef name) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMPrintSettingsSetValue( - PMPrintSettings printSettings, - CFStringRef key, - CFTypeRef _Nullable value, - Boolean locked) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMPrintSettingsCopyAsDictionary( - PMPrintSettings printSettings, - CFDictionaryRef _Nullable * _Nonnull settingsDictionary) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPrintSettingsCopyKeys( - PMPrintSettings printSettings, - CFArrayRef _Nullable * _Nonnull settingsKeys) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMCreateGenericPrinter( - PMPrinter _Nonnull * _Nonnull printer) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMServerCreatePrinterList( - PMServer _Nullable server, - CFArrayRef _Nullable * _Nonnull printerList) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -PMServerLaunchPrinterBrowser( - PMServer _Nullable server, - CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.5))); -extern PMPrinter _Nullable -PMPrinterCreateFromPrinterID(CFStringRef printerID) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMPrinterCopyDescriptionURL( - PMPrinter printer, - CFStringRef descriptionType, - CFURLRef _Nullable * _Nonnull fileURL) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMPrinterCopyDeviceURI( - PMPrinter printer, - CFURLRef _Nullable * _Nonnull deviceURI) __attribute__((availability(macosx,introduced=10.4))); -extern OSStatus -PMPrinterCopyHostName( - PMPrinter printer, - CFStringRef _Nonnull * _Nonnull hostNameP) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPrinterCopyPresets( - PMPrinter printer, - CFArrayRef _Nullable * _Nonnull presetList) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPrinterGetCommInfo( - PMPrinter printer, - Boolean * _Nullable supportsControlCharRangeP, - Boolean * _Nullable supportsEightBitP) __attribute__((availability(macosx,introduced=10.3))); -extern CFStringRef _Nullable -PMPrinterGetID(PMPrinter printer) __attribute__((availability(macosx,introduced=10.2))); -extern CFStringRef _Nullable -PMPrinterGetLocation(PMPrinter printer) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -PMPrinterGetDriverCreator( - PMPrinter printer, - OSType * creator) ; -extern OSStatus -PMPrinterGetDriverReleaseInfo( - PMPrinter printer, - VersRec * release) ; -extern OSStatus -PMPrinterGetPrinterResolutionCount( - PMPrinter printer, - UInt32 * countP) ; -extern OSStatus -PMPrinterGetIndexedPrinterResolution( - PMPrinter printer, - UInt32 index, - PMResolution * resolutionP) ; -OSStatus PMPrinterGetOutputResolution( - PMPrinter printer, - PMPrintSettings printSettings, - PMResolution *resolutionP) __attribute__((availability(macosx,introduced=10.5))); -OSStatus PMPrinterSetOutputResolution( - PMPrinter printer, - PMPrintSettings printSettings, - const PMResolution *resolutionP) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPrinterGetLanguageInfo( - PMPrinter printer, - PMLanguageInfo * info) ; -extern OSStatus -PMPrinterGetMakeAndModelName( - PMPrinter printer, - CFStringRef _Nullable * _Nonnull makeAndModel) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -PMPrinterGetMimeTypes( - PMPrinter printer, - PMPrintSettings _Nullable settings, - CFArrayRef _Nullable * _Nonnull mimeTypes) __attribute__((availability(macosx,introduced=10.3))); -extern CFStringRef _Nullable -PMPrinterGetName(PMPrinter printer) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -PMPrinterGetPaperList( - PMPrinter printer, - CFArrayRef _Nullable * _Nonnull paperList) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPrinterGetState( - PMPrinter printer, - PMPrinterState * state) __attribute__((availability(macosx,introduced=10.2))); -extern Boolean -PMPrinterIsDefault(PMPrinter printer) __attribute__((availability(macosx,introduced=10.2))); -extern Boolean -PMPrinterIsFavorite(PMPrinter printer) __attribute__((availability(macosx,introduced=10.2))); -extern Boolean -PMPrinterIsPostScriptCapable(PMPrinter printer) __attribute__((availability(macosx,introduced=10.2))); -extern OSStatus -PMPrinterIsPostScriptPrinter(PMPrinter printer, Boolean *isPSPrinter) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPrinterIsRemote( - PMPrinter printer, - Boolean * isRemoteP) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus PMPrinterSetDefault(PMPrinter printer) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPresetCopyName( - PMPreset preset, - CFStringRef _Nullable * _Nonnull name) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPresetCreatePrintSettings( - PMPreset preset, - PMPrintSession session, - PMPrintSettings _Nonnull * _Nonnull printSettings) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPresetGetAttributes( - PMPreset preset, - CFDictionaryRef _Nullable * _Nonnull attributes) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMGetPageFormatPaper( - PMPageFormat format, - PMPaper _Nonnull * _Nonnull paper) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPaperCreateCustom( - PMPrinter _Nullable printer, - CFStringRef _Nullable id, - CFStringRef _Nullable name, - double width, - double height, - const PMPaperMargins * margins, - PMPaper _Nullable * _Nonnull paperP) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPaperGetWidth( - PMPaper paper, - double * paperWidth) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPaperGetHeight( - PMPaper paper, - double * paperHeight) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPaperGetMargins( - PMPaper paper, - PMPaperMargins * paperMargins) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPaperGetID( - PMPaper paper, - CFStringRef _Nonnull * _Nonnull paperID) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPaperGetPPDPaperName( - PMPaper paper, - CFStringRef _Nullable * _Nonnull paperName) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPaperCreateLocalizedName( - PMPaper paper, - PMPrinter printer, - CFStringRef _Nullable * _Nonnull paperName) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPaperGetPrinterID( - PMPaper paper, - CFStringRef _Nullable * _Nonnull printerID) __attribute__((availability(macosx,introduced=10.5))); -extern Boolean -PMPaperIsCustom(PMPaper paper ) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMWorkflowCopyItems( - CFArrayRef _Nullable * _Nonnull workflowItems) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMWorkflowSubmitPDFWithOptions( - CFURLRef workflowItem, - CFStringRef _Nullable title, - const char* _Nullable options, - CFURLRef pdfFile) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMWorkflowSubmitPDFWithSettings( - CFURLRef workflowItem, - PMPrintSettings settings, - CFURLRef pdfFile) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPrinterPrintWithProvider( - PMPrinter printer, - PMPrintSettings settings, - PMPageFormat _Nullable format, - CFStringRef mimeType, - CGDataProviderRef provider) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPrinterPrintWithFile( - PMPrinter printer, - PMPrintSettings settings, - PMPageFormat _Nullable format, - CFStringRef _Nullable mimeType, - CFURLRef fileURL) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPrinterWritePostScriptToURL( - PMPrinter printer, - PMPrintSettings settings, - PMPageFormat _Nullable format, - CFStringRef _Nullable mimeType, - CFURLRef sourceFileURL, - CFURLRef destinationFileURL) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPrintSettingsToOptions( - PMPrintSettings settings, - char* _Nullable * _Nonnull options) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMPrintSettingsToOptionsWithPrinterAndPageFormat( - PMPrintSettings settings, - PMPrinter printer, - PMPageFormat _Nullable pageFormat, - char* _Nullable * _Nonnull options) __attribute__((availability(macosx,introduced=10.5))); -extern OSStatus -PMPrinterSendCommand( - PMPrinter printer, - CFStringRef commandString, - CFStringRef _Nullable jobTitle, - CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.6))); -extern OSStatus -PMPrinterCopyState( - PMPrinter printer, - CFDictionaryRef _Nonnull * _Nonnull stateDict) __attribute__((availability(macosx,introduced=10.6))); -extern OSStatus -PMCopyAvailablePPDs( - PMPPDDomain domain, - CFArrayRef _Nullable * _Nonnull ppds) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMCopyLocalizedPPD( - CFURLRef ppd, - CFURLRef _Nullable * _Nonnull localizedPPD) __attribute__((availability(macosx,introduced=10.3))); -extern OSStatus -PMCopyPPDData( - CFURLRef ppd, - CFDataRef _Nullable * _Nonnull data) __attribute__((availability(macosx,introduced=10.3))); -extern CGImageRef _Nullable -PMCGImageCreateWithEPSDataProvider( - CGDataProviderRef _Nullable epsDataProvider, - CGImageRef epsPreview) __attribute__((availability(macosx,introduced=10.1))); - - - -} - - - -extern "C" { -} - - - -extern "C" { -enum { - kPMCoverPageNone = 1, - - kPMCoverPageBefore = 2, - - kPMCoverPageAfter = 3 -}; -typedef enum{ - kPMPageToPaperMappingNone = 1, - kPMPageToPaperMappingScaleToFit, -}PMPageToPaperMappingType; -} - - - -extern "C" { - - -enum { - kPMAllocationFailure = memFullErr, - kPMInternalError = kPMGeneralError, - - kPMInvalidIndex = -30882, - kPMStringConversionFailure = -30883, - kPMXMLParseError = -30884, - - kPMInvalidJobTemplate = -30885, - kPMInvalidPrinterInfo = -30886, - kPMInvalidConnection = -30887, - kPMInvalidKey = -30888, - kPMInvalidValue = -30889, - kPMInvalidAllocator = -30890, - kPMInvalidTicket = -30891, - kPMInvalidItem = -30892, - kPMInvalidType = -30893, - kPMInvalidReply = -30894, - kPMInvalidFileType = -30895, - kPMInvalidObject = -30896, - kPMInvalidPaper = -30897, - kPMInvalidCalibrationTarget = -30898, - - - kPMNoDefaultItem = -9500, - kPMNoDefaultSettings = -9501, - kPMInvalidPDEContext = -9530, - kPMDontSwitchPDEError = -9531, - kPMUnableToFindProcess = -9532, - kPMFeatureNotInstalled = -9533, - - - kPMInvalidPBMRef = -9540, - kPMNoSelectedPrinters = -9541, - kPMInvalidLookupSpec = -9542, - kPMSyncRequestFailed = -9543, - kPMEditRequestFailed = -9544, - kPMPrBrowserNoUI = -9545, - - - kPMTicketTypeNotFound = -9580, - kPMUpdateTicketFailed = -9581, - kPMValidateTicketFailed = -9582, - kPMSubTicketNotFound = -9583, - kPMInvalidSubTicket = -9584, - kPMDeleteSubTicketFailed = -9585, - kPMItemIsLocked = -9586, - kPMTicketIsLocked = -9587, - kPMTemplateIsLocked = -9588, - kPMKeyNotFound = -9589, - kPMKeyNotUnique = -9590, - kPMUnknownDataType = -9591, - - - kPMCreateMessageFailed = -9620, - kPMServerCommunicationFailed = -9621, - kPMKeyOrValueNotFound = -9623, - kPMMessagingError = -9624, - - - kPMServerNotFound = -9630, - kPMServerAlreadyRunning = -9631, - kPMServerSuspended = -9632, - kPMServerAttributeRestricted = -9633, - kPMFileOrDirOperationFailed = -9634, - kPMUserOrGroupNotFound = -9635, - kPMPermissionError = -9636, - kPMUnknownMessage = -9637, - kPMQueueNotFound = -9638, - kPMQueueAlreadyExists = -9639, - kPMQueueJobFailed = -9640, - kPMJobNotFound = -9641, - kPMJobBusy = -9642, - kPMJobCanceled = -9643, - kPMDocumentNotFound = -9644, - - - kPMPMSymbolNotFound = -9660, - kPMIOMSymbolNotFound = -9661, - kPMCVMSymbolNotFound = -9662, - kPMInvalidPMContext = -9663, - kPMInvalidIOMContext = -9664, - kPMInvalidCVMContext = -9665, - kPMInvalidJobID = -9666, - kPMNoPrinterJobID = -9667, - kPMJobStreamOpenFailed = -9668, - kPMJobStreamReadFailed = -9669, - kPMJobStreamEndError = -9670, - kPMJobManagerAborted = -9671, - kPMJobGetTicketBadFormatError = -9672, - kPMJobGetTicketReadError = -9673, - - - kPMPluginNotFound = -9701, - kPMPluginRegisterationFailed = -9702, - kPMFontNotFound = -9703, - kPMFontNameTooLong = -9704, - kPMGeneralCGError = -9705, - kPMInvalidState = -9706, - kPMUnexpectedImagingError = -9707, - - - - - kPMInvalidPrinterAddress = -9780, - kPMOpenFailed = -9781, - kPMReadFailed = -9782, - kPMWriteFailed = -9783, - kPMStatusFailed = -9784, - kPMCloseFailed = -9785, - kPMUnsupportedConnection = -9786, - kPMIOAttrNotAvailable = -9787, - kPMReadGotZeroData = -9788, - - kPMLastErrorCodeToMakeMaintenanceOfThisListEasier = -9799 -}; - - -} - - - -#pragma pack(push, 2) - -struct FontRec { - SInt16 fontType; - SInt16 firstChar; - SInt16 lastChar; - SInt16 widMax; - SInt16 kernMax; - SInt16 nDescent; - SInt16 fRectWidth; - SInt16 fRectHeight; - UInt16 owTLoc; - SInt16 ascent; - SInt16 descent; - SInt16 leading; - SInt16 rowWords; -}; -typedef struct FontRec FontRec; -typedef FontRec * FontRecPtr; -typedef FontRecPtr * FontRecHdl; -struct FMInput { - short family; - short size; - Style face; - Boolean needBits; - short device; - Point numer; - Point denom; -}; -typedef struct FMInput FMInput; -struct FamRec { - SInt16 ffFlags; - SInt16 ffFamID; - SInt16 ffFirstChar; - SInt16 ffLastChar; - SInt16 ffAscent; - SInt16 ffDescent; - SInt16 ffLeading; - SInt16 ffWidMax; - SInt32 ffWTabOff; - SInt32 ffKernOff; - SInt32 ffStylOff; - SInt16 ffProperty[9]; - SInt16 ffIntl[2]; - SInt16 ffVersion; -}; -typedef struct FamRec FamRec; -struct AsscEntry { - SInt16 fontSize; - SInt16 fontStyle; - SInt16 fontID; -}; -typedef struct AsscEntry AsscEntry; -struct FontAssoc { - SInt16 numAssoc; -}; -typedef struct FontAssoc FontAssoc; -struct StyleTable { - SInt16 fontClass; - SInt32 offset; - SInt32 reserved; - char indexes[48]; -}; -typedef struct StyleTable StyleTable; -struct NameTable { - SInt16 stringCount; - Str255 baseFontName; -}; -typedef struct NameTable NameTable; -struct KernPair { - char kernFirst; - char kernSecond; - SInt16 kernWidth; -}; -typedef struct KernPair KernPair; -struct KernEntry { - SInt16 kernStyle; - SInt16 kernLength; -}; -typedef struct KernEntry KernEntry; -struct KernTable { - SInt16 numKerns; -}; -typedef struct KernTable KernTable; - -#pragma pack(pop) - - - -extern "C" { - - -#pragma pack(push, 2) -typedef struct OpaqueATSUTextLayout* ATSUTextLayout; -typedef struct OpaqueATSUStyle* ATSUStyle; -typedef struct OpaqueATSUFontFallbacks* ATSUFontFallbacks; -typedef Fixed ATSUTextMeasurement; -typedef FMFont ATSUFontID; -typedef UInt16 ATSUFontFeatureType; -typedef UInt16 ATSUFontFeatureSelector; -typedef FourCharCode ATSUFontVariationAxis; -typedef Fixed ATSUFontVariationValue; -typedef UInt32 ATSUAttributeTag; -enum { - - - - - - kATSULineWidthTag = 1, - - - - - - kATSULineRotationTag = 2, - - - - - - - kATSULineDirectionTag = 3, - - - - - - kATSULineJustificationFactorTag = 4, - - - - - - kATSULineFlushFactorTag = 5, - - - - - - - kATSULineBaselineValuesTag = 6, - - - - - - - - kATSULineLayoutOptionsTag = 7, - kATSULineAscentTag = 8, - kATSULineDescentTag = 9, - - - - - - - kATSULineLangRegionTag = 10, - - - - - - - kATSULineTextLocatorTag = 11, - - - - - - - kATSULineTruncationTag = 12, - kATSULineFontFallbacksTag = 13, - - - - - - - - kATSULineDecimalTabCharacterTag = 14, - - - - - - - - kATSULayoutOperationOverrideTag = 15, - - - - - - - kATSULineHighlightCGColorTag = 17, - - - - - - kATSUMaxLineTag = 18, - - - - - kATSULineLanguageTag = 10, - kATSUCGContextTag = 32767, - - - - - - - - kATSUQDBoldfaceTag = 256, - - - - - - - - kATSUQDItalicTag = 257, - - - - - - kATSUQDUnderlineTag = 258, - - - - - - kATSUQDCondensedTag = 259, - - - - - - kATSUQDExtendedTag = 260, - - - - - - kATSUFontTag = 261, - - - - - - kATSUSizeTag = 262, - - - - - - kATSUColorTag = 263, - - - - - - - kATSULangRegionTag = 264, - - - - - - - - kATSUVerticalCharacterTag = 265, - - - - - - kATSUImposeWidthTag = 266, - - - - - kATSUBeforeWithStreamShiftTag = 267, - - - - - kATSUAfterWithStreamShiftTag = 268, - - - - - kATSUCrossStreamShiftTag = 269, - - - - - - kATSUTrackingTag = 270, - - - - - kATSUHangingInhibitFactorTag = 271, - - - - - kATSUKerningInhibitFactorTag = 272, - - - - - - kATSUDecompositionFactorTag = 273, - - - - - - - - kATSUBaselineClassTag = 274, - - - - - - - kATSUPriorityJustOverrideTag = 275, - - - - - - - kATSUNoLigatureSplitTag = 276, - - - - - - - kATSUNoCaretAngleTag = 277, - - - - - - - kATSUSuppressCrossKerningTag = 278, - - - - - - - kATSUNoOpticalAlignmentTag = 279, - - - - - - - kATSUForceHangingTag = 280, - - - - - - - kATSUNoSpecialJustificationTag = 281, - - - - - - - kATSUStyleTextLocatorTag = 282, - - - - - - - - kATSUStyleRenderingOptionsTag = 283, - kATSUAscentTag = 284, - kATSUDescentTag = 285, - kATSULeadingTag = 286, - - - - - - - kATSUGlyphSelectorTag = 287, - - - - - - - kATSURGBAlphaColorTag = 288, - - - - - - - - kATSUFontMatrixTag = 289, - - - - - - - kATSUStyleUnderlineCountOptionTag = 290, - - - - - - - kATSUStyleUnderlineColorOptionTag = 291, - - - - - - kATSUStyleStrikeThroughTag = 292, - - - - - - - kATSUStyleStrikeThroughCountOptionTag = 293, - - - - - - - kATSUStyleStrikeThroughColorOptionTag = 294, - - - - - - - kATSUStyleDropShadowTag = 295, - - - - - - kATSUStyleDropShadowBlurOptionTag = 296, - - - - - - - kATSUStyleDropShadowOffsetOptionTag = 297, - - - - - - kATSUStyleDropShadowColorOptionTag = 298, - - - - - - kATSUMaxStyleTag = 299, - - - - - - - kATSULanguageTag = 264, - kATSUMaxATSUITagValue = 65535 -}; -typedef void * ATSUAttributeValuePtr; -typedef const void * ConstATSUAttributeValuePtr; -struct ATSUAttributeInfo { - ATSUAttributeTag fTag; - ByteCount fValueSize; -}; -typedef struct ATSUAttributeInfo ATSUAttributeInfo; -struct ATSUCaret { - Fixed fX; - Fixed fY; - Fixed fDeltaX; - Fixed fDeltaY; -}; -typedef struct ATSUCaret ATSUCaret; -typedef UInt16 ATSUCursorMovementType; -enum { - - - - - - kATSUByCharacter = 0, - - - - - - kATSUByTypographicCluster = 1, - - - - - kATSUByWord = 2, - - - - - kATSUByCharacterCluster = 3, - - - - - kATSUByCluster = 1 -}; -typedef UInt32 ATSULineTruncation; -enum { - kATSUTruncateNone = 0, - kATSUTruncateStart = 1, - kATSUTruncateEnd = 2, - kATSUTruncateMiddle = 3, - kATSUTruncateSpecificationMask = 0x00000007, - kATSUTruncFeatNoSquishing = 0x00000008 -}; -typedef UInt16 ATSUStyleLineCountType; -enum { - kATSUStyleSingleLineCount = 1, - kATSUStyleDoubleLineCount = 2 -}; -typedef UInt16 ATSUVerticalCharacterType; -enum { - kATSUStronglyHorizontal = 0, - kATSUStronglyVertical = 1 -}; -typedef UInt16 ATSUStyleComparison; -enum { - kATSUStyleUnequal = 0, - kATSUStyleContains = 1, - kATSUStyleEquals = 2, - kATSUStyleContainedBy = 3 -}; -typedef UInt16 ATSUFontFallbackMethod; -enum { - - - - - - kATSUDefaultFontFallbacks = 0, - - - - - - kATSULastResortOnlyFallback = 1, - kATSUSequentialFallbacksPreferred = 2, - kATSUSequentialFallbacksExclusive = 3 -}; -typedef UInt16 ATSUTabType; -enum { - kATSULeftTab = 0, - kATSUCenterTab = 1, - kATSURightTab = 2, - kATSUDecimalTab = 3, - kATSUNumberTabTypes = 4 -}; -struct ATSUTab { - ATSUTextMeasurement tabPosition; - ATSUTabType tabType; -}; -typedef struct ATSUTab ATSUTab; -struct ATSURGBAlphaColor { - float red; - float green; - float blue; - float alpha; -}; -typedef struct ATSURGBAlphaColor ATSURGBAlphaColor; -typedef UInt16 GlyphCollection; -enum { - kGlyphCollectionGID = 0, - kGlyphCollectionAdobeCNS1 = 1, - kGlyphCollectionAdobeGB1 = 2, - kGlyphCollectionAdobeJapan1 = 3, - kGlyphCollectionAdobeJapan2 = 4, - kGlyphCollectionAdobeKorea1 = 5, - kGlyphCollectionUnspecified = 0xFF -}; -struct ATSUGlyphSelector { - - - - - - GlyphCollection collection; - - - - - - - GlyphID glyphID; -}; -typedef struct ATSUGlyphSelector ATSUGlyphSelector; -struct ATSUGlyphInfo { - GlyphID glyphID; - UInt16 reserved; - UInt32 layoutFlags; - UniCharArrayOffset charIndex; - ATSUStyle style; - Float32 deltaY; - Float32 idealX; - SInt16 screenX; - SInt16 caretX; -}; -typedef struct ATSUGlyphInfo ATSUGlyphInfo; -struct ATSUGlyphInfoArray { - ATSUTextLayout layout; - ItemCount numGlyphs; - ATSUGlyphInfo glyphs[1]; -}; -typedef struct ATSUGlyphInfoArray ATSUGlyphInfoArray; -typedef UInt32 ATSUHighlightMethod; -enum { - kInvertHighlighting = 0, - kRedrawHighlighting = 1 -}; -typedef UInt32 ATSUBackgroundDataType; -enum { - kATSUBackgroundColor = 0, - kATSUBackgroundCallback = 1 -}; -typedef ATSURGBAlphaColor ATSUBackgroundColor; -typedef Boolean ( * RedrawBackgroundProcPtr)(ATSUTextLayout iLayout, UniCharArrayOffset iTextOffset, UniCharCount iTextLength, ATSTrapezoid iUnhighlightArea[], ItemCount iTrapezoidCount); -typedef RedrawBackgroundProcPtr RedrawBackgroundUPP; -union ATSUBackgroundData { - - - - - ATSUBackgroundColor backgroundColor; - - - - - - RedrawBackgroundUPP backgroundUPP; -}; -typedef union ATSUBackgroundData ATSUBackgroundData; -struct ATSUUnhighlightData { - - - - - - - - ATSUBackgroundDataType dataType; - - - - - - - ATSUBackgroundData unhighlightData; -}; -typedef struct ATSUUnhighlightData ATSUUnhighlightData; -enum { - - - - - kATSULeftToRightBaseDirection = 0, - - - - - kATSURightToLeftBaseDirection = 1 -}; -enum { - kATSUInvalidFontID = 0 -}; -enum { - kATSUUseLineControlWidth = 0x7FFFFFFF -}; -enum { - kATSUNoSelector = 0x0000FFFF -}; -enum { - - - - - kATSUFromTextBeginning = (UInt32)0xFFFFFFFF, - - - - - kATSUToTextEnd = (UInt32)0xFFFFFFFF, - - - - - kATSUFromPreviousLayout = (UInt32)0xFFFFFFFE, - - - - - kATSUFromFollowingLayout = (UInt32)0xFFFFFFFD -}; - - - - - - -enum { - - - - - - - kATSUUseGrafPortPenLoc = (UInt32)0xFFFFFFFF, - - - - - - - kATSUClearAll = (UInt32)0xFFFFFFFF -}; - - -#pragma pack(pop) - - -} - - - -extern "C" { -typedef OSStatus ( * ATSQuadraticNewPathProcPtr)(void * callBackDataPtr); -typedef ATSQuadraticNewPathProcPtr ATSQuadraticNewPathUPP; -typedef OSStatus ( * ATSQuadraticLineProcPtr)(const Float32Point *pt1, const Float32Point *pt2, void *callBackDataPtr); -typedef ATSQuadraticLineProcPtr ATSQuadraticLineUPP; -typedef OSStatus ( * ATSQuadraticCurveProcPtr)(const Float32Point *pt1, const Float32Point *controlPt, const Float32Point *pt2, void *callBackDataPtr); -typedef ATSQuadraticCurveProcPtr ATSQuadraticCurveUPP; -typedef OSStatus ( * ATSQuadraticClosePathProcPtr)(void * callBackDataPtr); -typedef ATSQuadraticClosePathProcPtr ATSQuadraticClosePathUPP; -typedef OSStatus ( * ATSCubicMoveToProcPtr)(const Float32Point *pt, void *callBackDataPtr); -typedef ATSCubicMoveToProcPtr ATSCubicMoveToUPP; -typedef OSStatus ( * ATSCubicLineToProcPtr)(const Float32Point *pt, void *callBackDataPtr); -typedef ATSCubicLineToProcPtr ATSCubicLineToUPP; -typedef OSStatus ( * ATSCubicCurveToProcPtr)(const Float32Point *pt1, const Float32Point *pt2, const Float32Point *pt3, void *callBackDataPtr); -typedef ATSCubicCurveToProcPtr ATSCubicCurveToUPP; -typedef OSStatus ( * ATSCubicClosePathProcPtr)(void * callBackDataPtr); -typedef ATSCubicClosePathProcPtr ATSCubicClosePathUPP; - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - -typedef UInt32 ATSUFlattenedDataStreamFormat; -enum { - kATSUDataStreamUnicodeStyledText = 'ustl' -}; - - - - - - - -typedef UInt32 ATSUFlattenStyleRunOptions; -enum { - kATSUFlattenOptionNoOptionsMask = 0x00000000 -}; - - - - - - -typedef UInt32 ATSUUnFlattenStyleRunOptions; -enum { - kATSUUnFlattenOptionNoOptionsMask = 0x00000000 -}; -struct ATSUStyleRunInfo { - UInt32 runLength; - UInt32 styleObjectIndex; -}; -typedef struct ATSUStyleRunInfo ATSUStyleRunInfo; -enum { - kATSFlatDataUstlVersion0 = 0, - kATSFlatDataUstlVersion1 = 1, - kATSFlatDataUstlVersion2 = 2, - kATSFlatDataUstlCurrentVersion = kATSFlatDataUstlVersion2 -}; -struct ATSFlatDataMainHeaderBlock { - - - - - UInt32 version; - - - - UInt32 sizeOfDataBlock; - - - - UInt32 offsetToTextLayouts; - - - - UInt32 offsetToStyleRuns; - - - - UInt32 offsetToStyleList; -}; -typedef struct ATSFlatDataMainHeaderBlock ATSFlatDataMainHeaderBlock; -struct ATSFlatDataTextLayoutDataHeader { - - - - UInt32 sizeOfLayoutData; - - - UInt32 textLayoutLength; - - - - - UInt32 offsetToLayoutControls; - - - - - UInt32 offsetToLineInfo; - - - - - - - -}; -typedef struct ATSFlatDataTextLayoutDataHeader ATSFlatDataTextLayoutDataHeader; - - - - - -struct ATSFlatDataTextLayoutHeader { - - - - - UInt32 numFlattenedTextLayouts; - - - - - ATSFlatDataTextLayoutDataHeader flattenedTextLayouts[1]; -}; -typedef struct ATSFlatDataTextLayoutHeader ATSFlatDataTextLayoutHeader; - - - - - -struct ATSFlatDataLayoutControlsDataHeader { - - - - UInt32 numberOfLayoutControls; - ATSUAttributeInfo controlArray[1]; -}; -typedef struct ATSFlatDataLayoutControlsDataHeader ATSFlatDataLayoutControlsDataHeader; -struct ATSFlatDataLineInfoData { - - - UInt32 lineLength; - - - - UInt32 numberOfLineControls; - - - - -}; -typedef struct ATSFlatDataLineInfoData ATSFlatDataLineInfoData; - - - - - -struct ATSFlatDataLineInfoHeader { - - - - - - UInt32 numberOfLines; - - - - - ATSFlatDataLineInfoData lineInfoArray[1]; -}; -typedef struct ATSFlatDataLineInfoHeader ATSFlatDataLineInfoHeader; -struct ATSFlatDataStyleRunDataHeader { - - - UInt32 numberOfStyleRuns; - - - - - ATSUStyleRunInfo styleRunArray[1]; -}; -typedef struct ATSFlatDataStyleRunDataHeader ATSFlatDataStyleRunDataHeader; -struct ATSFlatDataStyleListStyleDataHeader { - - - - - UInt32 sizeOfStyleInfo; - - - - - UInt32 numberOfSetAttributes; - - - - UInt32 numberOfSetFeatures; - - - - UInt32 numberOfSetVariations; -}; -typedef struct ATSFlatDataStyleListStyleDataHeader ATSFlatDataStyleListStyleDataHeader; - - - - - -struct ATSFlatDataStyleListHeader { - - - UInt32 numberOfStyles; - - - - - - - ATSFlatDataStyleListStyleDataHeader styleDataArray[1]; - -}; -typedef struct ATSFlatDataStyleListHeader ATSFlatDataStyleListHeader; - - - - - -struct ATSFlatDataStyleListFeatureData { - - - ATSUFontFeatureType theFeatureType; - - - ATSUFontFeatureSelector theFeatureSelector; -}; -typedef struct ATSFlatDataStyleListFeatureData ATSFlatDataStyleListFeatureData; - - - - - - -struct ATSFlatDataStyleListVariationData { - - - ATSUFontVariationAxis theVariationAxis; - - - ATSUFontVariationValue theVariationValue; -}; -typedef struct ATSFlatDataStyleListVariationData ATSFlatDataStyleListVariationData; -typedef UInt32 ATSFlatDataFontSpeciferType; -enum { - - - kATSFlattenedFontSpecifierRawNameData = 'namd' -}; - - - - - - -struct ATSFlatDataFontNameDataHeader { - - - ATSFlatDataFontSpeciferType nameSpecifierType; - - - - - - UInt32 nameSpecifierSize; - - - - - - - -}; -typedef struct ATSFlatDataFontNameDataHeader ATSFlatDataFontNameDataHeader; - - - - - - - -struct ATSFlatDataFontSpecRawNameData { - - - FontNameCode fontNameType; - - - - - - FontPlatformCode fontNamePlatform; - - - - - - FontScriptCode fontNameScript; - - - - - FontLanguageCode fontNameLanguage; - - - - UInt32 fontNameLength; - - - - -}; -typedef struct ATSFlatDataFontSpecRawNameData ATSFlatDataFontSpecRawNameData; -struct ATSFlatDataFontSpecRawNameDataHeader { - - - - UInt32 numberOfFlattenedNames; - - - - - - ATSFlatDataFontSpecRawNameData nameDataArray[1]; - -}; -typedef struct ATSFlatDataFontSpecRawNameDataHeader ATSFlatDataFontSpecRawNameDataHeader; - - - - - -#pragma pack(pop) - - -} - - - -extern "C" { -typedef UInt32 ATSUDirectDataSelector; -enum { - kATSUDirectDataAdvanceDeltaFixedArray = 0, - kATSUDirectDataBaselineDeltaFixedArray = 1, - kATSUDirectDataDeviceDeltaSInt16Array = 2, - kATSUDirectDataStyleIndexUInt16Array = 3, - kATSUDirectDataStyleSettingATSUStyleSettingRefArray = 4, - kATSUDirectDataLayoutRecordATSLayoutRecordVersion1 = 100, - kATSUDirectDataLayoutRecordATSLayoutRecordCurrent = kATSUDirectDataLayoutRecordATSLayoutRecordVersion1 -}; -typedef struct LLCStyleInfo* ATSUStyleSettingRef; - - -} - - - -extern "C" { - - -#pragma pack(push, 2) - -enum { - kTextToSpeechSynthType = 'ttsc', - kTextToSpeechVoiceType = 'ttvd', - kTextToSpeechVoiceFileType = 'ttvf', - kTextToSpeechVoiceBundleType = 'ttvb' -}; - -enum { - kNoEndingProsody = 1, - kNoSpeechInterrupt = 2, - kPreflightThenPause = 4 -}; - -enum { - kImmediate = 0, - kEndOfWord = 1, - kEndOfSentence = 2 -}; - - - - - -enum { - soStatus = 'stat', - soErrors = 'erro', - soInputMode = 'inpt', - soCharacterMode = 'char', - soNumberMode = 'nmbr', - soRate = 'rate', - soPitchBase = 'pbas', - soPitchMod = 'pmod', - soVolume = 'volm', - soSynthType = 'vers', - soRecentSync = 'sync', - soPhonemeSymbols = 'phsy', - soCurrentVoice = 'cvox', - soCommandDelimiter = 'dlim', - soReset = 'rset', - soCurrentA5 = 'myA5', - soRefCon = 'refc', - soTextDoneCallBack = 'tdcb', - soSpeechDoneCallBack = 'sdcb', - soSyncCallBack = 'sycb', - soErrorCallBack = 'ercb', - soPhonemeCallBack = 'phcb', - soWordCallBack = 'wdcb', - soSynthExtension = 'xtnd', - soSoundOutput = 'sndo', - soOutputToFileWithCFURL = 'opaf', - soOutputToExtAudioFile = 'opax', - soOutputToAudioDevice = 'opad', - soPhonemeOptions = 'popt' -}; - - - - - -enum { - modeText = 'TEXT', - modePhonemes = 'PHON', - modeTune = 'TUNE', - modeNormal = 'NORM', - modeLiteral = 'LTRL' -}; - - -enum { - soVoiceDescription = 'info', - soVoiceFile = 'fref' -}; - - - - -enum { - kSpeechGenerateTune = 1, - kSpeechRelativePitch = 2, - kSpeechRelativeDuration = 4, - kSpeechShowSyllables = 8 -}; - - - - -enum { - kAudioUnitSubType_SpeechSynthesis = 'ttsp', - kAudioUnitProperty_Voice = 3330, - kAudioUnitProperty_SpeechChannel = 3331 -}; - - - - - -struct SpeechChannelRecord { - long data[1]; -}; -typedef struct SpeechChannelRecord SpeechChannelRecord; -typedef SpeechChannelRecord * SpeechChannel; - -struct VoiceSpec { - OSType creator; - OSType id; -}; -typedef struct VoiceSpec VoiceSpec; -typedef VoiceSpec * VoiceSpecPtr; - -enum { - kNeuter = 0, - kMale = 1, - kFemale = 2 -}; - - - - -struct VoiceDescription { - SInt32 length; - VoiceSpec voice; - SInt32 version; - Str63 name; - Str255 comment; - SInt16 gender; - SInt16 age; - SInt16 script; - SInt16 language; - SInt16 region; - SInt32 reserved[4]; -}; -typedef struct VoiceDescription VoiceDescription; - - -struct VoiceFileInfo { - FSSpec fileSpec; - SInt16 resID; -}; -typedef struct VoiceFileInfo VoiceFileInfo; -struct SpeechStatusInfo { - Boolean outputBusy; - Boolean outputPaused; - long inputBytesLeft; - SInt16 phonemeCode; -}; -typedef struct SpeechStatusInfo SpeechStatusInfo; - - -struct SpeechErrorInfo { - SInt16 count; - OSErr oldest; - long oldPos; - OSErr newest; - long newPos; -}; -typedef struct SpeechErrorInfo SpeechErrorInfo; - - -struct SpeechVersionInfo { - OSType synthType; - OSType synthSubType; - OSType synthManufacturer; - SInt32 synthFlags; - NumVersion synthVersion; -}; -typedef struct SpeechVersionInfo SpeechVersionInfo; - - -struct PhonemeInfo { - SInt16 opcode; - Str15 phStr; - Str31 exampleStr; - SInt16 hiliteStart; - SInt16 hiliteEnd; -}; -typedef struct PhonemeInfo PhonemeInfo; - -struct PhonemeDescriptor { - SInt16 phonemeCount; - PhonemeInfo thePhonemes[1]; -}; -typedef struct PhonemeDescriptor PhonemeDescriptor; -struct SpeechXtndData { - OSType synthCreator; - Byte synthData[2]; -}; -typedef struct SpeechXtndData SpeechXtndData; - -struct DelimiterInfo { - Byte startDelimiter[2]; - Byte endDelimiter[2]; -}; -typedef struct DelimiterInfo DelimiterInfo; -extern CFStringRef const kSpeechStatusProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechErrorsProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechInputModeProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechCharacterModeProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechNumberModeProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechRateProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPitchBaseProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPitchModProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechVolumeProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechSynthesizerInfoProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechRecentSyncProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPhonemeSymbolsProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechCurrentVoiceProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechCommandDelimiterProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechResetProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechOutputToFileURLProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechOutputToExtAudioFileProperty __attribute__((availability(macosx,introduced=10.6))); -extern CFStringRef const kSpeechOutputToAudioDeviceProperty __attribute__((availability(macosx,introduced=10.6))); - - - - - - -extern CFStringRef const kSpeechOutputToFileDescriptorProperty __attribute__((availability(macosx,introduced=10.9))); - - - - - - -extern CFStringRef const kSpeechAudioOutputFormatProperty __attribute__((availability(macosx,introduced=10.9))); - - - - - - - -extern CFStringRef const kSpeechOutputChannelMapProperty __attribute__((availability(macosx,introduced=10.9))); -extern CFStringRef const kSpeechRefConProperty __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechTextDoneCallBack __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechSpeechDoneCallBack __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechSyncCallBack __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPhonemeCallBack __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechErrorCFCallBack __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechWordCFCallBack __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPhonemeOptionsProperty __attribute__((availability(macosx,introduced=10.6))); -extern CFStringRef const kSpeechAudioUnitProperty __attribute__((availability(macosx,introduced=10.6))); -extern CFStringRef const kSpeechAudioGraphProperty __attribute__((availability(macosx,introduced=10.6))); -extern CFStringRef const kSpeechSynthExtensionProperty __attribute__((availability(macosx,introduced=10.9))); -extern CFStringRef const kSpeechModeText __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechModePhoneme __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechModeTune __attribute__((availability(macosx,introduced=10.6))); -extern CFStringRef const kSpeechModeNormal __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechModeLiteral __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechNoEndingProsody __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechNoSpeechInterrupt __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPreflightThenPause __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechStatusOutputBusy __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechStatusOutputPaused __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechStatusNumberOfCharactersLeft __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechStatusPhonemeCode __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechErrorCount __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechErrorOldest __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechErrorOldestCharacterOffset __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechErrorNewest __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechErrorNewestCharacterOffset __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechSynthesizerInfoIdentifier __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechSynthesizerInfoManufacturer __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechSynthesizerInfoVersion __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPhonemeInfoOpcode __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPhonemeInfoSymbol __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPhonemeInfoExample __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPhonemeInfoHiliteStart __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechPhonemeInfoHiliteEnd __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechVoiceCreator __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechVoiceID __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechCommandPrefix __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechCommandSuffix __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechDictionaryLocaleIdentifier __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechDictionaryModificationDate __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechDictionaryPronunciations __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechDictionaryAbbreviations __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechDictionaryEntrySpelling __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechDictionaryEntryPhonemes __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechErrorCallbackSpokenString __attribute__((availability(macosx,introduced=10.5))); -extern CFStringRef const kSpeechErrorCallbackCharacterOffset __attribute__((availability(macosx,introduced=10.5))); - -typedef void ( * SpeechTextDoneProcPtr)(SpeechChannel chan, SRefCon refCon, const void * _Nullable * _Nullable nextBuf, unsigned long *byteLen, SInt32 *controlFlags); -typedef void ( * SpeechDoneProcPtr)(SpeechChannel chan, SRefCon refCon); -typedef void ( * SpeechSyncProcPtr)(SpeechChannel chan, SRefCon refCon, OSType syncMessage); -typedef void ( * SpeechErrorProcPtr)(SpeechChannel chan, SRefCon refCon, OSErr theError, long bytePos); -typedef void ( * SpeechPhonemeProcPtr)(SpeechChannel chan, SRefCon refCon, SInt16 phonemeOpcode); -typedef void ( * SpeechWordProcPtr)(SpeechChannel chan, SRefCon refCon, unsigned long wordPos, UInt16 wordLen); -typedef SpeechTextDoneProcPtr SpeechTextDoneUPP; -typedef SpeechDoneProcPtr SpeechDoneUPP; -typedef SpeechSyncProcPtr SpeechSyncUPP; -typedef SpeechErrorProcPtr SpeechErrorUPP; -typedef SpeechPhonemeProcPtr SpeechPhonemeUPP; -typedef SpeechWordProcPtr SpeechWordUPP; -extern SpeechTextDoneUPP -NewSpeechTextDoneUPP(SpeechTextDoneProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SpeechDoneUPP -NewSpeechDoneUPP(SpeechDoneProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SpeechSyncUPP -NewSpeechSyncUPP(SpeechSyncProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SpeechErrorUPP -NewSpeechErrorUPP(SpeechErrorProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SpeechPhonemeUPP -NewSpeechPhonemeUPP(SpeechPhonemeProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern SpeechWordUPP -NewSpeechWordUPP(SpeechWordProcPtr userRoutine) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeSpeechTextDoneUPP(SpeechTextDoneUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeSpeechDoneUPP(SpeechDoneUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeSpeechSyncUPP(SpeechSyncUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeSpeechErrorUPP(SpeechErrorUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeSpeechPhonemeUPP(SpeechPhonemeUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -DisposeSpeechWordUPP(SpeechWordUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeSpeechTextDoneUPP( - SpeechChannel chan, - SRefCon refCon, - const void * _Nullable * _Nullable nextBuf, - unsigned long * byteLen, - SInt32 * controlFlags, - SpeechTextDoneUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeSpeechDoneUPP( - SpeechChannel chan, - SRefCon refCon, - SpeechDoneUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeSpeechSyncUPP( - SpeechChannel chan, - SRefCon refCon, - OSType syncMessage, - SpeechSyncUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeSpeechErrorUPP( - SpeechChannel chan, - SRefCon refCon, - OSErr theError, - long bytePos, - SpeechErrorUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeSpeechPhonemeUPP( - SpeechChannel chan, - SRefCon refCon, - SInt16 phonemeOpcode, - SpeechPhonemeUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern void -InvokeSpeechWordUPP( - SpeechChannel chan, - SRefCon refCon, - unsigned long wordPos, - UInt16 wordLen, - SpeechWordUPP userUPP) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); - - - - inline SpeechTextDoneUPP NewSpeechTextDoneUPP(SpeechTextDoneProcPtr userRoutine) { return userRoutine; } - inline SpeechDoneUPP NewSpeechDoneUPP(SpeechDoneProcPtr userRoutine) { return userRoutine; } - inline SpeechSyncUPP NewSpeechSyncUPP(SpeechSyncProcPtr userRoutine) { return userRoutine; } - inline SpeechErrorUPP NewSpeechErrorUPP(SpeechErrorProcPtr userRoutine) { return userRoutine; } - inline SpeechPhonemeUPP NewSpeechPhonemeUPP(SpeechPhonemeProcPtr userRoutine) { return userRoutine; } - inline SpeechWordUPP NewSpeechWordUPP(SpeechWordProcPtr userRoutine) { return userRoutine; } - inline void DisposeSpeechTextDoneUPP(SpeechTextDoneUPP) { } - inline void DisposeSpeechDoneUPP(SpeechDoneUPP) { } - inline void DisposeSpeechSyncUPP(SpeechSyncUPP) { } - inline void DisposeSpeechErrorUPP(SpeechErrorUPP) { } - inline void DisposeSpeechPhonemeUPP(SpeechPhonemeUPP) { } - inline void DisposeSpeechWordUPP(SpeechWordUPP) { } - inline void InvokeSpeechTextDoneUPP(SpeechChannel chan, SRefCon refCon, const void * _Nullable * _Nullable nextBuf, unsigned long * byteLen, SInt32 * controlFlags, SpeechTextDoneUPP userUPP) { (*userUPP)(chan, refCon, nextBuf, byteLen, controlFlags); } - inline void InvokeSpeechDoneUPP(SpeechChannel chan, SRefCon refCon, SpeechDoneUPP userUPP) { (*userUPP)(chan, refCon); } - inline void InvokeSpeechSyncUPP(SpeechChannel chan, SRefCon refCon, OSType syncMessage, SpeechSyncUPP userUPP) { (*userUPP)(chan, refCon, syncMessage); } - inline void InvokeSpeechErrorUPP(SpeechChannel chan, SRefCon refCon, OSErr theError, long bytePos, SpeechErrorUPP userUPP) { (*userUPP)(chan, refCon, theError, bytePos); } - inline void InvokeSpeechPhonemeUPP(SpeechChannel chan, SRefCon refCon, SInt16 phonemeOpcode, SpeechPhonemeUPP userUPP) { (*userUPP)(chan, refCon, phonemeOpcode); } - inline void InvokeSpeechWordUPP(SpeechChannel chan, SRefCon refCon, unsigned long wordPos, UInt16 wordLen, SpeechWordUPP userUPP) { (*userUPP)(chan, refCon, wordPos, wordLen); } -typedef void ( * SpeechErrorCFProcPtr)(SpeechChannel chan, SRefCon refCon, CFErrorRef theError); -typedef void ( * SpeechWordCFProcPtr)(SpeechChannel chan, SRefCon refCon, CFStringRef aString, CFRange wordRange); -extern NumVersion -SpeechManagerVersion(void) ; -extern OSErr -MakeVoiceSpec( - OSType creator, - OSType id, - VoiceSpec * voice) ; -extern OSErr -CountVoices(SInt16 * numVoices) ; -extern OSErr -GetIndVoice( - SInt16 index, - VoiceSpec * voice) ; -extern OSErr -GetVoiceDescription( - const VoiceSpec * _Nullable voice, - VoiceDescription * _Nullable info, - long infoLength) ; -extern OSErr -GetVoiceInfo( - const VoiceSpec * _Nullable voice, - OSType selector, - void * voiceInfo) ; -extern OSErr -NewSpeechChannel( - VoiceSpec * _Nullable voice, - SpeechChannel _Nullable * _Nonnull chan) ; -extern OSErr -DisposeSpeechChannel(SpeechChannel chan) ; -extern OSErr -SpeakString(ConstStr255Param textToBeSpoken) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -SpeakText( - SpeechChannel chan, - const void * textBuf, - unsigned long textBytes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -SpeakBuffer( - SpeechChannel chan, - const void * textBuf, - unsigned long textBytes, - SInt32 controlFlags) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -StopSpeech(SpeechChannel chan) ; -extern OSErr -StopSpeechAt( - SpeechChannel chan, - SInt32 whereToStop) ; -extern OSErr -PauseSpeechAt( - SpeechChannel chan, - SInt32 whereToPause) ; -extern OSErr -ContinueSpeech(SpeechChannel chan) ; -extern SInt16 -SpeechBusy(void) ; -extern SInt16 -SpeechBusySystemWide(void) ; -extern OSErr -SetSpeechRate( - SpeechChannel chan, - Fixed rate) ; -extern OSErr -GetSpeechRate( - SpeechChannel chan, - Fixed * rate) ; -extern OSErr -SetSpeechPitch( - SpeechChannel chan, - Fixed pitch) ; -extern OSErr -GetSpeechPitch( - SpeechChannel chan, - Fixed * pitch) ; -extern OSErr -SetSpeechInfo( - SpeechChannel chan, - OSType selector, - const void * _Nullable speechInfo) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -GetSpeechInfo( - SpeechChannel chan, - OSType selector, - void * speechInfo) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -TextToPhonemes( - SpeechChannel chan, - const void * textBuf, - unsigned long textBytes, - Handle _Nonnull phonemeBuf, - long * phonemeBytes) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -UseDictionary( - SpeechChannel chan, - Handle _Nonnull dictionary) __attribute__((availability(macosx,introduced=10.0,deprecated=10.8))); -extern OSErr -SpeakCFString( - SpeechChannel chan, - CFStringRef aString, - CFDictionaryRef _Nullable options) __attribute__((availability(macosx,introduced=10.5))); -extern OSErr -UseSpeechDictionary( - SpeechChannel chan, - CFDictionaryRef speechDictionary) __attribute__((availability(macosx,introduced=10.5))); -extern OSErr -CopyPhonemesFromText( - SpeechChannel chan, - CFStringRef text, - CFStringRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) phonemes) __attribute__((availability(macosx,introduced=10.5))); -extern OSErr -CopySpeechProperty( - SpeechChannel chan, - CFStringRef property, - CFTypeRef _Nullable * _Nonnull __attribute__((cf_returns_retained)) object) __attribute__((availability(macosx,introduced=10.5))); -extern OSErr -SetSpeechProperty( - SpeechChannel chan, - CFStringRef property, - CFTypeRef _Nullable object) __attribute__((availability(macosx,introduced=10.5))); -extern OSErr -SpeechSynthesisRegisterModuleURL(CFURLRef url) __attribute__((availability(macosx,introduced=10.6))); -extern OSErr -SpeechSynthesisUnregisterModuleURL(CFURLRef url) __attribute__((availability(macosx,introduced=10.6))); - - - - -#pragma pack(pop) - - -} - -// @class NSData; -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - - - - -typedef NSUInteger NSAppleEventSendOptions; enum { - NSAppleEventSendNoReply = kAENoReply, - NSAppleEventSendQueueReply = kAEQueueReply, - NSAppleEventSendWaitForReply = kAEWaitReply, - NSAppleEventSendNeverInteract = kAENeverInteract, - NSAppleEventSendCanInteract = kAECanInteract, - NSAppleEventSendAlwaysInteract = kAEAlwaysInteract, - NSAppleEventSendCanSwitchLayer = kAECanSwitchLayer, - NSAppleEventSendDontRecord = kAEDontRecord, - NSAppleEventSendDontExecute = kAEDontExecute, - NSAppleEventSendDontAnnotate = kAEDoNotAutomaticallyAddAnnotationsToEvent, - - NSAppleEventSendDefaultOptions = NSAppleEventSendWaitForReply | NSAppleEventSendCanInteract -} __attribute__((availability(macosx,introduced=10_11))); - - -#ifndef _REWRITER_typedef_NSAppleEventDescriptor -#define _REWRITER_typedef_NSAppleEventDescriptor -typedef struct objc_object NSAppleEventDescriptor; -typedef struct {} _objc_exc_NSAppleEventDescriptor; -#endif - -struct NSAppleEventDescriptor_IMPL { - struct NSObject_IMPL NSObject_IVARS; - AEDesc _desc; - BOOL _hasValidDesc; - char _padding[3]; -}; - - - -// + (NSAppleEventDescriptor *)nullDescriptor; - - -// + (nullable NSAppleEventDescriptor *)descriptorWithDescriptorType:(DescType)descriptorType bytes:(nullable const void *)bytes length:(NSUInteger)byteCount; -// + (nullable NSAppleEventDescriptor *)descriptorWithDescriptorType:(DescType)descriptorType data:(nullable NSData *)data; - - -// + (NSAppleEventDescriptor *)descriptorWithBoolean:(Boolean)boolean; -// + (NSAppleEventDescriptor *)descriptorWithEnumCode:(OSType)enumerator; -// + (NSAppleEventDescriptor *)descriptorWithInt32:(SInt32)signedInt; -// + (NSAppleEventDescriptor *)descriptorWithDouble:(double)doubleValue __attribute__((availability(macosx,introduced=10_11))); -// + (NSAppleEventDescriptor *)descriptorWithTypeCode:(OSType)typeCode; - - -// + (NSAppleEventDescriptor *)descriptorWithString:(NSString *)string; -// + (NSAppleEventDescriptor *)descriptorWithDate:(NSDate *)date __attribute__((availability(macosx,introduced=10_11))); -// + (NSAppleEventDescriptor *)descriptorWithFileURL:(NSURL *)fileURL __attribute__((availability(macosx,introduced=10_11))); - - -// + (NSAppleEventDescriptor *)appleEventWithEventClass:(AEEventClass)eventClass eventID:(AEEventID)eventID targetDescriptor:(nullable NSAppleEventDescriptor *)targetDescriptor returnID:(AEReturnID)returnID transactionID:(AETransactionID)transactionID; -// + (NSAppleEventDescriptor *)listDescriptor; -// + (NSAppleEventDescriptor *)recordDescriptor; - - -// + (NSAppleEventDescriptor *)currentProcessDescriptor __attribute__((availability(macosx,introduced=10_11))); -// + (NSAppleEventDescriptor *)descriptorWithProcessIdentifier:(pid_t)processIdentifier __attribute__((availability(macosx,introduced=10_11))); -// + (NSAppleEventDescriptor *)descriptorWithBundleIdentifier:(NSString *)bundleIdentifier __attribute__((availability(macosx,introduced=10_11))); -// + (NSAppleEventDescriptor *)descriptorWithApplicationURL:(NSURL *)applicationURL __attribute__((availability(macosx,introduced=10_11))); - - -// - (instancetype)initWithAEDescNoCopy:(const AEDesc *)aeDesc __attribute__((objc_designated_initializer)); - - -// - (nullable instancetype)initWithDescriptorType:(DescType)descriptorType bytes:(nullable const void *)bytes length:(NSUInteger)byteCount; -// - (nullable instancetype)initWithDescriptorType:(DescType)descriptorType data:(nullable NSData *)data; -// - (instancetype)initWithEventClass:(AEEventClass)eventClass eventID:(AEEventID)eventID targetDescriptor:(nullable NSAppleEventDescriptor *)targetDescriptor returnID:(AEReturnID)returnID transactionID:(AETransactionID)transactionID; -// - (instancetype)initListDescriptor; -// - (instancetype)initRecordDescriptor; - - -// @property (nullable, readonly) const AEDesc *aeDesc __attribute__((objc_returns_inner_pointer)); - - -// @property (readonly) DescType descriptorType; -// @property (readonly, copy) NSData *data; - - -// @property (readonly) Boolean booleanValue; -// @property (readonly) OSType enumCodeValue; -// @property (readonly) SInt32 int32Value; -// @property (readonly) double doubleValue __attribute__((availability(macosx,introduced=10_11))); -// @property (readonly) OSType typeCodeValue; - - -// @property (nullable, readonly, copy) NSString *stringValue; -// @property (nullable, readonly, copy) NSDate *dateValue __attribute__((availability(macosx,introduced=10_11))); -// @property (nullable, readonly, copy) NSURL *fileURLValue __attribute__((availability(macosx,introduced=10_11))); - - -// @property (readonly) AEEventClass eventClass; -// @property (readonly) AEEventID eventID; -// @property (readonly) AEReturnID returnID; -// @property (readonly) AETransactionID transactionID; - - -// - (void)setParamDescriptor:(NSAppleEventDescriptor *)descriptor forKeyword:(AEKeyword)keyword; -// - (nullable NSAppleEventDescriptor *)paramDescriptorForKeyword:(AEKeyword)keyword; -// - (void)removeParamDescriptorWithKeyword:(AEKeyword)keyword; - - -// - (void)setAttributeDescriptor:(NSAppleEventDescriptor *)descriptor forKeyword:(AEKeyword)keyword; -// - (nullable NSAppleEventDescriptor *)attributeDescriptorForKeyword:(AEKeyword)keyword; - - -// - (nullable NSAppleEventDescriptor *)sendEventWithOptions:(NSAppleEventSendOptions)sendOptions timeout:(NSTimeInterval)timeoutInSeconds error:(NSError **)error __attribute__((availability(macosx,introduced=10_11))); - - -// @property (readonly) BOOL isRecordDescriptor __attribute__((availability(macosx,introduced=10_11))); - - -// @property (readonly) NSInteger numberOfItems; - - -// - (void)insertDescriptor:(NSAppleEventDescriptor *)descriptor atIndex:(NSInteger)index; -// - (nullable NSAppleEventDescriptor *)descriptorAtIndex:(NSInteger)index; -// - (void)removeDescriptorAtIndex:(NSInteger)index; - - -// - (void)setDescriptor:(NSAppleEventDescriptor *)descriptor forKeyword:(AEKeyword)keyword; -// - (nullable NSAppleEventDescriptor *)descriptorForKeyword:(AEKeyword)keyword; -// - (void)removeDescriptorWithKeyword:(AEKeyword)keyword; - - -// - (AEKeyword)keywordForDescriptorAtIndex:(NSInteger)index; - - -// - (nullable NSAppleEventDescriptor *)coerceToDescriptorType:(DescType)descriptorType; - -/* @end */ - - - - - - - - - -// @class NSAppleEventDescriptor; -#ifndef _REWRITER_typedef_NSAppleEventDescriptor -#define _REWRITER_typedef_NSAppleEventDescriptor -typedef struct objc_object NSAppleEventDescriptor; -typedef struct {} _objc_exc_NSAppleEventDescriptor; -#endif - - - - -typedef const struct __NSAppleEventManagerSuspension* NSAppleEventManagerSuspensionID; - -extern const double NSAppleEventTimeOutDefault; -extern const double NSAppleEventTimeOutNone; - -extern NSString *NSAppleEventManagerWillProcessFirstEventNotification; - - -#ifndef _REWRITER_typedef_NSAppleEventManager -#define _REWRITER_typedef_NSAppleEventManager -typedef struct objc_object NSAppleEventManager; -typedef struct {} _objc_exc_NSAppleEventManager; -#endif - -struct NSAppleEventManager_IMPL { - struct NSObject_IMPL NSObject_IVARS; - BOOL _isPreparedForDispatch; - char _padding[3]; -}; - - - -// + (NSAppleEventManager *)sharedAppleEventManager; - - - - -// - (void)setEventHandler:(id)handler andSelector:(SEL)handleEventSelector forEventClass:(AEEventClass)eventClass andEventID:(AEEventID)eventID; -// - (void)removeEventHandlerForEventClass:(AEEventClass)eventClass andEventID:(AEEventID)eventID; - - - -// - (OSErr)dispatchRawAppleEvent:(const AppleEvent *)theAppleEvent withRawReply:(AppleEvent *)theReply handlerRefCon:(SRefCon)handlerRefCon; - - -// @property (nullable, readonly, retain) NSAppleEventDescriptor *currentAppleEvent; - - -// @property (nullable, readonly, retain) NSAppleEventDescriptor *currentReplyAppleEvent; - - -// - (nullable NSAppleEventManagerSuspensionID)suspendCurrentAppleEvent __attribute__((objc_returns_inner_pointer)); - - -// - (NSAppleEventDescriptor *)appleEventForSuspensionID:(NSAppleEventManagerSuspensionID)suspensionID; - - -// - (NSAppleEventDescriptor *)replyAppleEventForSuspensionID:(NSAppleEventManagerSuspensionID)suspensionID; - - -// - (void)setCurrentAppleEventAndReplyEventWithSuspensionID:(NSAppleEventManagerSuspensionID)suspensionID; - - -// - (void)resumeWithSuspensionID:(NSAppleEventManagerSuspensionID)suspensionID; - -/* @end */ - - - - - - - - - -// @class NSAppleEventDescriptor; -#ifndef _REWRITER_typedef_NSAppleEventDescriptor -#define _REWRITER_typedef_NSAppleEventDescriptor -typedef struct objc_object NSAppleEventDescriptor; -typedef struct {} _objc_exc_NSAppleEventDescriptor; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - - - - - -extern "C" NSString *const NSAppleScriptErrorMessage __attribute__((availability(macosx,introduced=10_2))); -extern "C" NSString *const NSAppleScriptErrorNumber __attribute__((availability(macosx,introduced=10_2))); -extern "C" NSString *const NSAppleScriptErrorAppName __attribute__((availability(macosx,introduced=10_2))); -extern "C" NSString *const NSAppleScriptErrorBriefMessage __attribute__((availability(macosx,introduced=10_2))); -extern "C" NSString *const NSAppleScriptErrorRange __attribute__((availability(macosx,introduced=10_2))); - - -#ifndef _REWRITER_typedef_NSAppleScript -#define _REWRITER_typedef_NSAppleScript -typedef struct objc_object NSAppleScript; -typedef struct {} _objc_exc_NSAppleScript; -#endif - -struct NSAppleScript_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSString *_source; - unsigned int _compiledScriptID; - void *_reserved1; - void *_reserved2; -}; - - - -// - (nullable instancetype)initWithContentsOfURL:(NSURL *)url error:(NSDictionary<NSString *, id> * _Nullable * _Nullable)errorInfo __attribute__((objc_designated_initializer)); - - -// - (nullable instancetype)initWithSource:(NSString *)source __attribute__((objc_designated_initializer)); - - -// @property (nullable, readonly, copy) NSString *source; - - -// @property (readonly, getter=isCompiled) BOOL compiled; - - -// - (BOOL)compileAndReturnError:(NSDictionary<NSString *, id> * _Nullable * _Nullable)errorInfo; - - -// - (NSAppleEventDescriptor *)executeAndReturnError:(NSDictionary<NSString *, id> * _Nullable * _Nullable)errorInfo; - - -// - (NSAppleEventDescriptor *)executeAppleEvent:(NSAppleEventDescriptor *)event error:(NSDictionary<NSString *, id> * _Nullable * _Nullable)errorInfo; - -/* @end */ - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - - - - - -#ifndef _REWRITER_typedef_NSClassDescription -#define _REWRITER_typedef_NSClassDescription -typedef struct objc_object NSClassDescription; -typedef struct {} _objc_exc_NSClassDescription; -#endif - -struct NSClassDescription_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// + (void)registerClassDescription:(NSClassDescription *)description forClass:(Class)aClass; -// + (void)invalidateClassDescriptionCache; -// + (nullable NSClassDescription *)classDescriptionForClass:(Class)aClass; - -// @property (readonly, copy) NSArray<NSString *> *attributeKeys; -// @property (readonly, copy) NSArray<NSString *> *toOneRelationshipKeys; -// @property (readonly, copy) NSArray<NSString *> *toManyRelationshipKeys; -// - (nullable NSString *)inverseForRelationshipKey:(NSString *)relationshipKey; - -/* @end */ - - -// @interface NSObject (NSClassDescriptionPrimitives) - -// @property (readonly, copy) NSClassDescription *classDescription; -// @property (readonly, copy) NSArray<NSString *> *attributeKeys; -// @property (readonly, copy) NSArray<NSString *> *toOneRelationshipKeys; -// @property (readonly, copy) NSArray<NSString *> *toManyRelationshipKeys; -// - (nullable NSString *)inverseForRelationshipKey:(NSString *)relationshipKey; - -/* @end */ - - -extern "C" NSString *NSClassDescriptionNeededForClassNotification; - - - - - - -// @class NSDate; -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - - - - - -#ifndef _REWRITER_typedef_NSDistributedLock -#define _REWRITER_typedef_NSDistributedLock -typedef struct objc_object NSDistributedLock; -typedef struct {} _objc_exc_NSDistributedLock; -#endif - -struct NSDistributedLock_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_priv; -}; - - -// + (nullable NSDistributedLock *)lockWithPath:(NSString *)path; - -// - (instancetype)init __attribute__((unavailable)); -// - (nullable instancetype)initWithPath:(NSString *)path __attribute__((objc_designated_initializer)); - -// - (BOOL)tryLock; -// - (void)unlock; -// - (void)breakLock; -// @property (readonly, copy) NSDate *lockDate; - -/* @end */ - - - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_5,deprecated=10_10,message="" "Building Garbage Collected apps is no longer supported."))) - - - - -__attribute__((availability(swift, unavailable, message="Garbage Collection is not supported"))) - -#ifndef _REWRITER_typedef_NSGarbageCollector -#define _REWRITER_typedef_NSGarbageCollector -typedef struct objc_object NSGarbageCollector; -typedef struct {} _objc_exc_NSGarbageCollector; -#endif - -struct NSGarbageCollector_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// + (id)defaultCollector; - -// - (BOOL)isCollecting __attribute__((availability(macosx,introduced=10_0,deprecated=10_6,message="" ))); - -// - (void)disable; -// - (void)enable; -// - (BOOL)isEnabled; - -// - (void)collectIfNeeded; -// - (void)collectExhaustively; - -// - (void)disableCollectorForPointer:(const void *)ptr; -// - (void)enableCollectorForPointer:(const void *)ptr; - -// - (NSZone *)zone; - -/* @end */ - - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - -extern "C" NSString *NSFileTypeForHFSTypeCode(OSType hfsFileTypeCode); - - -extern "C" OSType NSHFSTypeCodeFromFileType(NSString *fileTypeString); - - -extern "C" NSString *NSHFSTypeOfFile(NSString *fullFilePath); - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSMutableArray -#define _REWRITER_typedef_NSMutableArray -typedef struct objc_object NSMutableArray; -typedef struct {} _objc_exc_NSMutableArray; -#endif - - - - - -#ifndef _REWRITER_typedef_NSHost -#define _REWRITER_typedef_NSHost -typedef struct objc_object NSHost; -typedef struct {} _objc_exc_NSHost; -#endif - -struct NSHost_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSArray *names; - NSArray *addresses; - id reserved; -}; - - -// + (instancetype)currentHost; -// + (instancetype)hostWithName:(nullable NSString *)name; -// + (instancetype)hostWithAddress:(NSString *)address; - -// - (BOOL)isEqualToHost:(NSHost *)aHost; - -// @property (nullable, readonly, copy) NSString *name; -// @property (readonly, copy) NSArray<NSString *> *names; - -// @property (nullable, readonly, copy) NSString *address; -// @property (readonly, copy) NSArray<NSString *> *addresses; - -// @property (nullable, readonly, copy) NSString *localizedName __attribute__((availability(macosx,introduced=10_6))); - - -// + (void)setHostCacheEnabled:(BOOL)flag __attribute__((availability(macosx,introduced=10_0,deprecated=10_7,message="" ))); -// + (BOOL)isHostCacheEnabled __attribute__((availability(macosx,introduced=10_0,deprecated=10_7,message="" ))); -// + (void)flushHostCache __attribute__((availability(macosx,introduced=10_0,deprecated=10_7,message="" ))); -/* @end */ - - - - - - - - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSScriptObjectSpecifier -#define _REWRITER_typedef_NSScriptObjectSpecifier -typedef struct objc_object NSScriptObjectSpecifier; -typedef struct {} _objc_exc_NSScriptObjectSpecifier; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -// @interface NSObject(NSScripting) - - - -// - (nullable id)scriptingValueForSpecifier:(NSScriptObjectSpecifier *)objectSpecifier __attribute__((availability(macosx,introduced=10_5))); -// @property (nullable, copy) NSDictionary<NSString *, id> *scriptingProperties; - - - -// - (nullable id)copyScriptingValue:(id)value forKey:(NSString *)key withProperties:(NSDictionary<NSString *, id> *)properties __attribute__((availability(macosx,introduced=10_5))); - - - -// - (nullable id)newScriptingObjectOfClass:(Class)objectClass forValueForKey:(NSString *)key withContentsValue:(nullable id)contentsValue properties:(NSDictionary<NSString *, id> *)properties __attribute__((availability(macosx,introduced=10_5))); - - -/* @end */ - - - - - - - - - -// @class NSScriptCommandDescription; -#ifndef _REWRITER_typedef_NSScriptCommandDescription -#define _REWRITER_typedef_NSScriptCommandDescription -typedef struct objc_object NSScriptCommandDescription; -typedef struct {} _objc_exc_NSScriptCommandDescription; -#endif - - - - - -#ifndef _REWRITER_typedef_NSScriptClassDescription -#define _REWRITER_typedef_NSScriptClassDescription -typedef struct objc_object NSScriptClassDescription; -typedef struct {} _objc_exc_NSScriptClassDescription; -#endif - -struct NSScriptClassDescription_IMPL { - struct NSClassDescription_IMPL NSClassDescription_IVARS; - NSString *_suiteName; - NSString *_objcClassName; - FourCharCode _appleEventCode; - NSObject *_superclassNameOrDescription; - NSArray *_attributeDescriptions; - NSArray *_toOneRelationshipDescriptions; - NSArray *_toManyRelationshipDescriptions; - NSDictionary *_commandMethodSelectorsByName; - id _moreVars; -}; - - - - -// + (nullable NSScriptClassDescription *)classDescriptionForClass:(Class)aClass; - - - -// - (nullable instancetype)initWithSuiteName:(NSString *)suiteName className:(NSString *)className dictionary:(nullable NSDictionary *)classDeclaration __attribute__((objc_designated_initializer)); - - - -// @property (nullable, readonly, copy) NSString *suiteName; -// @property (nullable, readonly, copy) NSString *className; - - - -// @property (nullable, readonly, copy) NSString *implementationClassName; - - - -// @property (nullable, readonly, retain) NSScriptClassDescription *superclassDescription; - - - -// @property (readonly) FourCharCode appleEventCode; - - - -// - (BOOL)matchesAppleEventCode:(FourCharCode)appleEventCode; - - - -// - (BOOL)supportsCommand:(NSScriptCommandDescription *)commandDescription; - - - -// - (nullable SEL)selectorForCommand:(NSScriptCommandDescription *)commandDescription; - - - -// - (nullable NSString *)typeForKey:(NSString *)key; - - - -// - (nullable NSScriptClassDescription *)classDescriptionForKey:(NSString *)key; - - - -// - (FourCharCode)appleEventCodeForKey:(NSString *)key; - - - -// - (nullable NSString *)keyWithAppleEventCode:(FourCharCode)appleEventCode; - - - -// @property (nullable, readonly, copy) NSString *defaultSubcontainerAttributeKey; - - - -// - (BOOL)isLocationRequiredToCreateForKey:(NSString *)toManyRelationshipKey; - - - -// - (BOOL)hasPropertyForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)hasOrderedToManyRelationshipForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)hasReadablePropertyForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_5))); -// - (BOOL)hasWritablePropertyForKey:(NSString *)key __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - -// @interface NSScriptClassDescription(NSDeprecated) - - - -// - (BOOL)isReadOnlyKey:(NSString *)key __attribute__((availability(macosx,introduced=10_0,deprecated=10_5,message="" ))); - -/* @end */ - - -// @interface NSObject(NSScriptClassDescription) - - - -// @property (readonly) FourCharCode classCode; - - - -// @property (readonly, copy) NSString *className; - -/* @end */ - - - - - - - - - - -#ifndef _REWRITER_typedef_NSScriptCoercionHandler -#define _REWRITER_typedef_NSScriptCoercionHandler -typedef struct objc_object NSScriptCoercionHandler; -typedef struct {} _objc_exc_NSScriptCoercionHandler; -#endif - -struct NSScriptCoercionHandler_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _coercers; -}; - - -// + (NSScriptCoercionHandler *)sharedCoercionHandler; - -// - (nullable id)coerceValue:(id)value toClass:(Class)toClass; - -// - (void)registerCoercer:(id)coercer selector:(SEL)selector toConvertFromClass:(Class)fromClass toClass:(Class)toClass; - - -/* @end */ - - - - - - - - -// @class NSAppleEventDescriptor; -#ifndef _REWRITER_typedef_NSAppleEventDescriptor -#define _REWRITER_typedef_NSAppleEventDescriptor -typedef struct objc_object NSAppleEventDescriptor; -typedef struct {} _objc_exc_NSAppleEventDescriptor; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSScriptObjectSpecifier -#define _REWRITER_typedef_NSScriptObjectSpecifier -typedef struct objc_object NSScriptObjectSpecifier; -typedef struct {} _objc_exc_NSScriptObjectSpecifier; -#endif - -#ifndef _REWRITER_typedef_NSScriptCommandDescription -#define _REWRITER_typedef_NSScriptCommandDescription -typedef struct objc_object NSScriptCommandDescription; -typedef struct {} _objc_exc_NSScriptCommandDescription; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - -enum { - NSNoScriptError = 0, - NSReceiverEvaluationScriptError, - NSKeySpecifierEvaluationScriptError, - NSArgumentEvaluationScriptError, - NSReceiversCantHandleCommandScriptError, - NSRequiredArgumentsMissingScriptError, - NSArgumentsWrongScriptError, - NSUnknownKeyScriptError, - NSInternalScriptError, - NSOperationNotSupportedForKeyScriptError, - NSCannotCreateScriptCommandError -}; - - -#ifndef _REWRITER_typedef_NSScriptCommand -#define _REWRITER_typedef_NSScriptCommand -typedef struct objc_object NSScriptCommand; -typedef struct {} _objc_exc_NSScriptCommand; -#endif - -struct NSScriptCommand_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSScriptCommandDescription *_commandDescription; - id _directParameter; - NSScriptObjectSpecifier *_receiversSpecifier; - id _evaluatedReceivers; - NSDictionary *_arguments; - NSMutableDictionary *_evaluatedArguments; - - struct { - unsigned int hasEvaluatedReceivers : 1; - unsigned int hasEvaluatedArguments : 1; - unsigned int RESERVED : 30; - } _flags; - id _moreVars; - void *_reserved; -}; - - -// - (instancetype)initWithCommandDescription:(NSScriptCommandDescription *)commandDef __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder; - -// @property (readonly, retain) NSScriptCommandDescription *commandDescription; - - -// @property (nullable, retain) id directParameter; - - -// @property (nullable, retain) NSScriptObjectSpecifier *receiversSpecifier; - - - -// @property (nullable, readonly, retain) id evaluatedReceivers; - - -// @property (nullable, copy) NSDictionary<NSString *, id> *arguments; -// @property (nullable, readonly, copy) NSDictionary<NSString *, id> *evaluatedArguments; - - -// @property (getter=isWellFormed, readonly) BOOL wellFormed; - - - - -// - (nullable id)performDefaultImplementation; - - - -// - (nullable id)executeCommand; - - -// @property NSInteger scriptErrorNumber; -// @property (nullable, retain) NSAppleEventDescriptor *scriptErrorOffendingObjectDescriptor __attribute__((availability(macosx,introduced=10_5))); -// @property (nullable, retain) NSAppleEventDescriptor *scriptErrorExpectedTypeDescriptor __attribute__((availability(macosx,introduced=10_5))); -// @property (nullable, copy) NSString *scriptErrorString; - - -// + (nullable NSScriptCommand *)currentCommand; - - -// @property (nullable, readonly, copy) NSAppleEventDescriptor *appleEvent; - - -// - (void)suspendExecution; - - - - - -// - (void)resumeExecutionWithResult:(nullable id)result; - -/* @end */ - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSScriptCommand -#define _REWRITER_typedef_NSScriptCommand -typedef struct objc_object NSScriptCommand; -typedef struct {} _objc_exc_NSScriptCommand; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - -#ifndef _REWRITER_typedef_NSScriptCommandDescription -#define _REWRITER_typedef_NSScriptCommandDescription -typedef struct objc_object NSScriptCommandDescription; -typedef struct {} _objc_exc_NSScriptCommandDescription; -#endif - -struct NSScriptCommandDescription_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSString *_suiteName; - NSString *_plistCommandName; - FourCharCode _classAppleEventCode; - FourCharCode _idAppleEventCode; - NSString *_objcClassName; - NSObject *_resultTypeNameOrDescription; - FourCharCode _plistResultTypeAppleEventCode; - id _moreVars; -}; - - -// - (id)init __attribute__((unavailable)); - - - -// - (nullable instancetype)initWithSuiteName:(NSString *)suiteName commandName:(NSString *)commandName dictionary:(nullable NSDictionary *)commandDeclaration __attribute__((objc_designated_initializer)); - -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); - - - -// @property (readonly, copy) NSString *suiteName; -// @property (readonly, copy) NSString *commandName; - - - -// @property (readonly) FourCharCode appleEventClassCode; -// @property (readonly) FourCharCode appleEventCode; - - - -// @property (readonly, copy) NSString *commandClassName; - - - -// @property (nullable, readonly, copy) NSString *returnType; - - - -// @property (readonly) FourCharCode appleEventCodeForReturnType; - - - -// @property (readonly, copy) NSArray<NSString *> *argumentNames; - - - -// - (nullable NSString *)typeForArgumentWithName:(NSString *)argumentName; - - - -// - (FourCharCode)appleEventCodeForArgumentWithName:(NSString *)argumentName; - - - -// - (BOOL)isOptionalArgumentWithName:(NSString *)argumentName; - - - -// - (NSScriptCommand *)createCommandInstance; -// - (NSScriptCommand *)createCommandInstanceWithZone:(nullable NSZone *)zone; - -/* @end */ - - - - - - - - -// @class NSConnection; -#ifndef _REWRITER_typedef_NSConnection -#define _REWRITER_typedef_NSConnection -typedef struct objc_object NSConnection; -typedef struct {} _objc_exc_NSConnection; -#endif - - - - - -#ifndef _REWRITER_typedef_NSScriptExecutionContext -#define _REWRITER_typedef_NSScriptExecutionContext -typedef struct objc_object NSScriptExecutionContext; -typedef struct {} _objc_exc_NSScriptExecutionContext; -#endif - -struct NSScriptExecutionContext_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _topLevelObject; - id _objectBeingTested; - id _rangeContainerObject; - id _moreVars; -}; - - -// + (NSScriptExecutionContext *)sharedScriptExecutionContext; - -// @property (nullable, retain) id topLevelObject; -// @property (nullable, retain) id objectBeingTested; -// @property (nullable, retain) id rangeContainerObject; - -/* @end */ - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -extern NSString *NSOperationNotSupportedForKeyException; - -// @interface NSObject(NSScriptKeyValueCoding) - - - -// - (nullable id)valueAtIndex:(NSUInteger)index inPropertyWithKey:(NSString *)key; - - - -// - (nullable id)valueWithName:(NSString *)name inPropertyWithKey:(NSString *)key; - - - -// - (nullable id)valueWithUniqueID:(id)uniqueID inPropertyWithKey:(NSString *)key; - - - -// - (void)insertValue:(id)value atIndex:(NSUInteger)index inPropertyWithKey:(NSString *)key; -// - (void)removeValueAtIndex:(NSUInteger)index fromPropertyWithKey:(NSString *)key; -// - (void)replaceValueAtIndex:(NSUInteger)index inPropertyWithKey:(NSString *)key withValue:(id)value; - - - -// - (void)insertValue:(id)value inPropertyWithKey:(NSString *)key; - - - -// - (nullable id)coerceValue:(nullable id)value forKey:(NSString *)key; - -/* @end */ - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSAppleEventDescriptor -#define _REWRITER_typedef_NSAppleEventDescriptor -typedef struct objc_object NSAppleEventDescriptor; -typedef struct {} _objc_exc_NSAppleEventDescriptor; -#endif - -#ifndef _REWRITER_typedef_NSNumber -#define _REWRITER_typedef_NSNumber -typedef struct objc_object NSNumber; -typedef struct {} _objc_exc_NSNumber; -#endif - -#ifndef _REWRITER_typedef_NSScriptClassDescription -#define _REWRITER_typedef_NSScriptClassDescription -typedef struct objc_object NSScriptClassDescription; -typedef struct {} _objc_exc_NSScriptClassDescription; -#endif - -#ifndef _REWRITER_typedef_NSScriptWhoseTest -#define _REWRITER_typedef_NSScriptWhoseTest -typedef struct objc_object NSScriptWhoseTest; -typedef struct {} _objc_exc_NSScriptWhoseTest; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - - -enum { - NSNoSpecifierError = 0, - NSNoTopLevelContainersSpecifierError, - NSContainerSpecifierError, - NSUnknownKeySpecifierError, - NSInvalidIndexSpecifierError, - NSInternalSpecifierError, - NSOperationNotSupportedForKeySpecifierError -}; - - -typedef NSUInteger NSInsertionPosition; enum { - NSPositionAfter, - NSPositionBefore, - NSPositionBeginning, - NSPositionEnd, - NSPositionReplace -}; - -typedef NSUInteger NSRelativePosition; enum { - NSRelativeAfter = 0, - NSRelativeBefore -}; - -typedef NSUInteger NSWhoseSubelementIdentifier; enum { - NSIndexSubelement = 0, - NSEverySubelement = 1, - NSMiddleSubelement = 2, - NSRandomSubelement = 3, - NSNoSubelement = 4 -}; - - - - - - -#ifndef _REWRITER_typedef_NSScriptObjectSpecifier -#define _REWRITER_typedef_NSScriptObjectSpecifier -typedef struct objc_object NSScriptObjectSpecifier; -typedef struct {} _objc_exc_NSScriptObjectSpecifier; -#endif - -struct NSScriptObjectSpecifier_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSScriptObjectSpecifier *_container; - NSScriptObjectSpecifier *_child; - NSString *_key; - NSScriptClassDescription *_containerClassDescription; - BOOL _containerIsObjectBeingTested; - BOOL _containerIsRangeContainerObject; - char _padding[2]; - NSAppleEventDescriptor *_descriptor; - NSInteger _error; -}; - - - - -// + (nullable NSScriptObjectSpecifier *)objectSpecifierWithDescriptor:(NSAppleEventDescriptor *)descriptor __attribute__((availability(macosx,introduced=10_5))); - -// - (instancetype)initWithContainerSpecifier:(NSScriptObjectSpecifier *)container key:(NSString *)property; - - -// - (instancetype)initWithContainerClassDescription:(NSScriptClassDescription *)classDesc containerSpecifier:(nullable NSScriptObjectSpecifier *)container key:(NSString *)property __attribute__((objc_designated_initializer)); - -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); - -// @property (nullable, assign) NSScriptObjectSpecifier *childSpecifier; - - -// @property (nullable, retain) NSScriptObjectSpecifier *containerSpecifier; - - -// @property BOOL containerIsObjectBeingTested; - -// @property BOOL containerIsRangeContainerObject; - - - -// @property (copy) NSString *key; - - -// @property (nullable, retain) NSScriptClassDescription *containerClassDescription; -// @property (nullable, readonly, retain) NSScriptClassDescription *keyClassDescription; - -// - (nullable NSInteger *)indicesOfObjectsByEvaluatingWithContainer:(id)container count:(NSInteger *)count __attribute__((objc_returns_inner_pointer)); - - -// - (nullable id)objectsByEvaluatingWithContainers:(id)containers; -// @property (nullable, readonly, retain) id objectsByEvaluatingSpecifier; - -// @property NSInteger evaluationErrorNumber; -// @property (nullable, readonly, retain) NSScriptObjectSpecifier *evaluationErrorSpecifier; - - - -// @property (nullable, readonly, copy) NSAppleEventDescriptor *descriptor __attribute__((availability(macosx,introduced=10_5))); - -/* @end */ - - - -// @interface NSObject (NSScriptObjectSpecifiers) - -// @property (nullable, readonly, retain) NSScriptObjectSpecifier *objectSpecifier; - - -// - (nullable NSArray<NSNumber *> *)indicesOfObjectsByEvaluatingObjectSpecifier:(NSScriptObjectSpecifier *)specifier; - - -/* @end */ - - - - - - -#ifndef _REWRITER_typedef_NSIndexSpecifier -#define _REWRITER_typedef_NSIndexSpecifier -typedef struct objc_object NSIndexSpecifier; -typedef struct {} _objc_exc_NSIndexSpecifier; -#endif - -struct NSIndexSpecifier_IMPL { - struct NSScriptObjectSpecifier_IMPL NSScriptObjectSpecifier_IVARS; - NSInteger _index; -}; - - -// - (instancetype)initWithContainerClassDescription:(NSScriptClassDescription *)classDesc containerSpecifier:(nullable NSScriptObjectSpecifier *)container key:(NSString *)property index:(NSInteger)index __attribute__((objc_designated_initializer)); - -// @property NSInteger index; - -/* @end */ - - - - - - -#ifndef _REWRITER_typedef_NSMiddleSpecifier -#define _REWRITER_typedef_NSMiddleSpecifier -typedef struct objc_object NSMiddleSpecifier; -typedef struct {} _objc_exc_NSMiddleSpecifier; -#endif - -struct NSMiddleSpecifier_IMPL { - struct NSScriptObjectSpecifier_IMPL NSScriptObjectSpecifier_IVARS; -}; - - -/* @end */ - - - - - - -#ifndef _REWRITER_typedef_NSNameSpecifier -#define _REWRITER_typedef_NSNameSpecifier -typedef struct objc_object NSNameSpecifier; -typedef struct {} _objc_exc_NSNameSpecifier; -#endif - -struct NSNameSpecifier_IMPL { - struct NSScriptObjectSpecifier_IMPL NSScriptObjectSpecifier_IVARS; - NSString *_name; -}; - - -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); -// - (instancetype)initWithContainerClassDescription:(NSScriptClassDescription *)classDesc containerSpecifier:(nullable NSScriptObjectSpecifier *)container key:(NSString *)property name:(NSString *)name __attribute__((objc_designated_initializer)); -// @property (copy) NSString *name; - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSPositionalSpecifier -#define _REWRITER_typedef_NSPositionalSpecifier -typedef struct objc_object NSPositionalSpecifier; -typedef struct {} _objc_exc_NSPositionalSpecifier; -#endif - -struct NSPositionalSpecifier_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSScriptObjectSpecifier *_specifier; - NSInsertionPosition _unadjustedPosition; - NSScriptClassDescription *_insertionClassDescription; - id _moreVars; - void *_reserved0; -}; - - - -// - (instancetype)initWithPosition:(NSInsertionPosition)position objectSpecifier:(NSScriptObjectSpecifier *)specifier __attribute__((objc_designated_initializer)); - - -// @property (readonly) NSInsertionPosition position __attribute__((availability(macosx,introduced=10_5))); -// @property (readonly, retain) NSScriptObjectSpecifier *objectSpecifier __attribute__((availability(macosx,introduced=10_5))); - - -// - (void)setInsertionClassDescription:(NSScriptClassDescription *)classDescription; - - -// - (void)evaluate; - - -// @property (nullable, readonly, retain) id insertionContainer; - - -// @property (nullable, readonly, copy) NSString *insertionKey; - - -// @property (readonly) NSInteger insertionIndex; - - -// @property (readonly) BOOL insertionReplaces; - -/* @end */ - - - - - - -#ifndef _REWRITER_typedef_NSPropertySpecifier -#define _REWRITER_typedef_NSPropertySpecifier -typedef struct objc_object NSPropertySpecifier; -typedef struct {} _objc_exc_NSPropertySpecifier; -#endif - -struct NSPropertySpecifier_IMPL { - struct NSScriptObjectSpecifier_IMPL NSScriptObjectSpecifier_IVARS; -}; - - -/* @end */ - - - - - - -#ifndef _REWRITER_typedef_NSRandomSpecifier -#define _REWRITER_typedef_NSRandomSpecifier -typedef struct objc_object NSRandomSpecifier; -typedef struct {} _objc_exc_NSRandomSpecifier; -#endif - -struct NSRandomSpecifier_IMPL { - struct NSScriptObjectSpecifier_IMPL NSScriptObjectSpecifier_IVARS; -}; - - -/* @end */ - - - - - - -#ifndef _REWRITER_typedef_NSRangeSpecifier -#define _REWRITER_typedef_NSRangeSpecifier -typedef struct objc_object NSRangeSpecifier; -typedef struct {} _objc_exc_NSRangeSpecifier; -#endif - -struct NSRangeSpecifier_IMPL { - struct NSScriptObjectSpecifier_IMPL NSScriptObjectSpecifier_IVARS; - NSScriptObjectSpecifier *_startSpec; - NSScriptObjectSpecifier *_endSpec; -}; - -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); -// - (instancetype)initWithContainerClassDescription:(NSScriptClassDescription *)classDesc containerSpecifier:(nullable NSScriptObjectSpecifier *)container key:(NSString *)property startSpecifier:(nullable NSScriptObjectSpecifier *)startSpec endSpecifier:(nullable NSScriptObjectSpecifier *)endSpec __attribute__((objc_designated_initializer)); - -// @property (nullable, retain) NSScriptObjectSpecifier *startSpecifier; - -// @property (nullable, retain) NSScriptObjectSpecifier *endSpecifier; - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSRelativeSpecifier -#define _REWRITER_typedef_NSRelativeSpecifier -typedef struct objc_object NSRelativeSpecifier; -typedef struct {} _objc_exc_NSRelativeSpecifier; -#endif - -struct NSRelativeSpecifier_IMPL { - struct NSScriptObjectSpecifier_IMPL NSScriptObjectSpecifier_IVARS; - NSRelativePosition _relativePosition; - NSScriptObjectSpecifier *_baseSpecifier; -}; - -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); -// - (instancetype)initWithContainerClassDescription:(NSScriptClassDescription *)classDesc containerSpecifier:(nullable NSScriptObjectSpecifier *)container key:(NSString *)property relativePosition:(NSRelativePosition)relPos baseSpecifier:(nullable NSScriptObjectSpecifier *)baseSpecifier __attribute__((objc_designated_initializer)); - -// @property NSRelativePosition relativePosition; - -// @property (nullable, retain) NSScriptObjectSpecifier *baseSpecifier; - - -/* @end */ - - - - - - -#ifndef _REWRITER_typedef_NSUniqueIDSpecifier -#define _REWRITER_typedef_NSUniqueIDSpecifier -typedef struct objc_object NSUniqueIDSpecifier; -typedef struct {} _objc_exc_NSUniqueIDSpecifier; -#endif - -struct NSUniqueIDSpecifier_IMPL { - struct NSScriptObjectSpecifier_IMPL NSScriptObjectSpecifier_IVARS; - id _uniqueID; -}; - -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); -// - (instancetype)initWithContainerClassDescription:(NSScriptClassDescription *)classDesc containerSpecifier:(nullable NSScriptObjectSpecifier *)container key:(NSString *)property uniqueID:(id)uniqueID __attribute__((objc_designated_initializer)); - -// @property (copy) id uniqueID; - -/* @end */ - - -#ifndef _REWRITER_typedef_NSWhoseSpecifier -#define _REWRITER_typedef_NSWhoseSpecifier -typedef struct objc_object NSWhoseSpecifier; -typedef struct {} _objc_exc_NSWhoseSpecifier; -#endif - -struct NSWhoseSpecifier_IMPL { - struct NSScriptObjectSpecifier_IMPL NSScriptObjectSpecifier_IVARS; - NSScriptWhoseTest *_test; - NSWhoseSubelementIdentifier _startSubelementIdentifier; - NSInteger _startSubelementIndex; - NSWhoseSubelementIdentifier _endSubelementIdentifier; - NSInteger _endSubelementIndex; -}; - - -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); -// - (instancetype)initWithContainerClassDescription:(NSScriptClassDescription *)classDesc containerSpecifier:(nullable NSScriptObjectSpecifier *)container key:(NSString *)property test:(NSScriptWhoseTest *)test __attribute__((objc_designated_initializer)); - -// @property (retain) NSScriptWhoseTest *test; -// @property NSWhoseSubelementIdentifier startSubelementIdentifier; - -// @property NSInteger startSubelementIndex; - - -// @property NSWhoseSubelementIdentifier endSubelementIdentifier; - -// @property NSInteger endSubelementIndex; - - -/* @end */ - - - - - - - - -// @class NSDictionary; -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -// @class NSScriptObjectSpecifier; -#ifndef _REWRITER_typedef_NSScriptObjectSpecifier -#define _REWRITER_typedef_NSScriptObjectSpecifier -typedef struct objc_object NSScriptObjectSpecifier; -typedef struct {} _objc_exc_NSScriptObjectSpecifier; -#endif - -// @class NSScriptClassDescription; -#ifndef _REWRITER_typedef_NSScriptClassDescription -#define _REWRITER_typedef_NSScriptClassDescription -typedef struct objc_object NSScriptClassDescription; -typedef struct {} _objc_exc_NSScriptClassDescription; -#endif - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -typedef NSUInteger NSSaveOptions; enum { - NSSaveOptionsYes = 0, - NSSaveOptionsNo, - NSSaveOptionsAsk -}; - - -#ifndef _REWRITER_typedef_NSCloneCommand -#define _REWRITER_typedef_NSCloneCommand -typedef struct objc_object NSCloneCommand; -typedef struct {} _objc_exc_NSCloneCommand; -#endif - -struct NSCloneCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; - NSScriptObjectSpecifier *_keySpecifier; -}; - - -// - (void)setReceiversSpecifier:(nullable NSScriptObjectSpecifier *)receiversRef; - - -// @property (readonly, retain) NSScriptObjectSpecifier *keySpecifier; - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSCloseCommand -#define _REWRITER_typedef_NSCloseCommand -typedef struct objc_object NSCloseCommand; -typedef struct {} _objc_exc_NSCloseCommand; -#endif - -struct NSCloseCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; -}; - - -// @property (readonly) NSSaveOptions saveOptions; - - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSCountCommand -#define _REWRITER_typedef_NSCountCommand -typedef struct objc_object NSCountCommand; -typedef struct {} _objc_exc_NSCountCommand; -#endif - -struct NSCountCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; -}; - - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSCreateCommand -#define _REWRITER_typedef_NSCreateCommand -typedef struct objc_object NSCreateCommand; -typedef struct {} _objc_exc_NSCreateCommand; -#endif - -struct NSCreateCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; - id _moreVars2; -}; - - -// @property (readonly, retain) NSScriptClassDescription *createClassDescription; - - -// @property (readonly, copy) NSDictionary<NSString *, id> *resolvedKeyDictionary; - - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSDeleteCommand -#define _REWRITER_typedef_NSDeleteCommand -typedef struct objc_object NSDeleteCommand; -typedef struct {} _objc_exc_NSDeleteCommand; -#endif - -struct NSDeleteCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; - NSScriptObjectSpecifier *_keySpecifier; -}; - - -// - (void)setReceiversSpecifier:(nullable NSScriptObjectSpecifier *)receiversRef; - - -// @property (readonly, retain) NSScriptObjectSpecifier *keySpecifier; - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSExistsCommand -#define _REWRITER_typedef_NSExistsCommand -typedef struct objc_object NSExistsCommand; -typedef struct {} _objc_exc_NSExistsCommand; -#endif - -struct NSExistsCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; -}; - - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSGetCommand -#define _REWRITER_typedef_NSGetCommand -typedef struct objc_object NSGetCommand; -typedef struct {} _objc_exc_NSGetCommand; -#endif - -struct NSGetCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; -}; - - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSMoveCommand -#define _REWRITER_typedef_NSMoveCommand -typedef struct objc_object NSMoveCommand; -typedef struct {} _objc_exc_NSMoveCommand; -#endif - -struct NSMoveCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; - NSScriptObjectSpecifier *_keySpecifier; -}; - - -// - (void)setReceiversSpecifier:(nullable NSScriptObjectSpecifier *)receiversRef; - - -// @property (readonly, retain) NSScriptObjectSpecifier *keySpecifier; - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSQuitCommand -#define _REWRITER_typedef_NSQuitCommand -typedef struct objc_object NSQuitCommand; -typedef struct {} _objc_exc_NSQuitCommand; -#endif - -struct NSQuitCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; -}; - - -// @property (readonly) NSSaveOptions saveOptions; - - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSSetCommand -#define _REWRITER_typedef_NSSetCommand -typedef struct objc_object NSSetCommand; -typedef struct {} _objc_exc_NSSetCommand; -#endif - -struct NSSetCommand_IMPL { - struct NSScriptCommand_IMPL NSScriptCommand_IVARS; - NSScriptObjectSpecifier *_keySpecifier; -}; - - -// - (void)setReceiversSpecifier:(nullable NSScriptObjectSpecifier *)receiversRef; - - -// @property (readonly, retain) NSScriptObjectSpecifier *keySpecifier; - -/* @end */ - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSBundle -#define _REWRITER_typedef_NSBundle -typedef struct objc_object NSBundle; -typedef struct {} _objc_exc_NSBundle; -#endif - -#ifndef _REWRITER_typedef_NSData -#define _REWRITER_typedef_NSData -typedef struct objc_object NSData; -typedef struct {} _objc_exc_NSData; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSMutableArray -#define _REWRITER_typedef_NSMutableArray -typedef struct objc_object NSMutableArray; -typedef struct {} _objc_exc_NSMutableArray; -#endif - -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSMutableSet -#define _REWRITER_typedef_NSMutableSet -typedef struct objc_object NSMutableSet; -typedef struct {} _objc_exc_NSMutableSet; -#endif - -#ifndef _REWRITER_typedef_NSScriptClassDescription -#define _REWRITER_typedef_NSScriptClassDescription -typedef struct objc_object NSScriptClassDescription; -typedef struct {} _objc_exc_NSScriptClassDescription; -#endif - -#ifndef _REWRITER_typedef_NSScriptCommandDescription -#define _REWRITER_typedef_NSScriptCommandDescription -typedef struct objc_object NSScriptCommandDescription; -typedef struct {} _objc_exc_NSScriptCommandDescription; -#endif - - - - - -#ifndef _REWRITER_typedef_NSScriptSuiteRegistry -#define _REWRITER_typedef_NSScriptSuiteRegistry -typedef struct objc_object NSScriptSuiteRegistry; -typedef struct {} _objc_exc_NSScriptSuiteRegistry; -#endif - -struct NSScriptSuiteRegistry_IMPL { - struct NSObject_IMPL NSObject_IVARS; - BOOL _isLoadingSDEFFiles; - BOOL _isLoadingSecurityOverride; - BOOL _hasLoadedIntrinsics; - char _reserved1[1]; - NSMutableSet *_seenBundles; - NSMutableArray *_suiteDescriptionsBeingCollected; - NSScriptClassDescription *_classDescriptionNeedingRegistration; - NSMutableArray *_suiteDescriptions; - NSScriptCommandDescription *_commandDescriptionNeedingRegistration; - NSMutableDictionary *_cachedClassDescriptionsByAppleEventCode; - NSMutableDictionary *_cachedCommandDescriptionsByAppleEventCodes; - NSDictionary *_cachedSuiteDescriptionsByName; - NSMutableDictionary *_complexTypeDescriptionsByName; - NSMutableDictionary *_listTypeDescriptionsByName; - unsigned int _nextComplexTypeAppleEventCode; - void *_reserved2[4]; -}; - - - - -// + (NSScriptSuiteRegistry *)sharedScriptSuiteRegistry; -// + (void)setSharedScriptSuiteRegistry:(NSScriptSuiteRegistry *)registry; - - - -// - (void)loadSuitesFromBundle:(NSBundle *)bundle; - - - -// - (void)loadSuiteWithDictionary:(NSDictionary *)suiteDeclaration fromBundle:(NSBundle *)bundle; - - - -// - (void)registerClassDescription:(NSScriptClassDescription *)classDescription; -// - (void)registerCommandDescription:(NSScriptCommandDescription *)commandDescription; - - - -// @property (readonly, copy) NSArray<NSString *> *suiteNames; - - - -// - (FourCharCode)appleEventCodeForSuite:(NSString *)suiteName; - - - -// - (nullable NSBundle *)bundleForSuite:(NSString *)suiteName; - - - -// - (nullable NSDictionary<NSString *, NSScriptClassDescription *> *)classDescriptionsInSuite:(NSString *)suiteName; -// - (nullable NSDictionary<NSString *, NSScriptCommandDescription *> *)commandDescriptionsInSuite:(NSString *)suiteName; - - - -// - (nullable NSString *)suiteForAppleEventCode:(FourCharCode)appleEventCode; - - - -// - (nullable NSScriptClassDescription *)classDescriptionWithAppleEventCode:(FourCharCode)appleEventCode; - - - -// - (nullable NSScriptCommandDescription *)commandDescriptionWithAppleEventClass:(FourCharCode)appleEventClassCode andAppleEventCode:(FourCharCode)appleEventIDCode; - - - -// - (nullable NSData *)aeteResource:(NSString *)languageName; - -/* @end */ - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -// @class NSScriptObjectSpecifier; -#ifndef _REWRITER_typedef_NSScriptObjectSpecifier -#define _REWRITER_typedef_NSScriptObjectSpecifier -typedef struct objc_object NSScriptObjectSpecifier; -typedef struct {} _objc_exc_NSScriptObjectSpecifier; -#endif - -// @class NSSpecifierTest; -#ifndef _REWRITER_typedef_NSSpecifierTest -#define _REWRITER_typedef_NSSpecifierTest -typedef struct objc_object NSSpecifierTest; -typedef struct {} _objc_exc_NSSpecifierTest; -#endif - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - - - - -typedef NSUInteger NSTestComparisonOperation; enum { - NSEqualToComparison = 0, - NSLessThanOrEqualToComparison, - NSLessThanComparison, - NSGreaterThanOrEqualToComparison, - NSGreaterThanComparison, - NSBeginsWithComparison, - NSEndsWithComparison, - NSContainsComparison -}; - - -#ifndef _REWRITER_typedef_NSScriptWhoseTest -#define _REWRITER_typedef_NSScriptWhoseTest -typedef struct objc_object NSScriptWhoseTest; -typedef struct {} _objc_exc_NSScriptWhoseTest; -#endif - -struct NSScriptWhoseTest_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// - (BOOL)isTrue; -// - (instancetype)init __attribute__((objc_designated_initializer)); -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); - -/* @end */ - - - - -#ifndef _REWRITER_typedef_NSLogicalTest -#define _REWRITER_typedef_NSLogicalTest -typedef struct objc_object NSLogicalTest; -typedef struct {} _objc_exc_NSLogicalTest; -#endif - -struct NSLogicalTest_IMPL { - struct NSScriptWhoseTest_IMPL NSScriptWhoseTest_IVARS; - int _operator; - id _subTests; -}; - - -// - (instancetype)initAndTestWithTests:(NSArray<NSSpecifierTest *> *)subTests __attribute__((objc_designated_initializer)); -// - (instancetype)initOrTestWithTests:(NSArray<NSSpecifierTest *> *)subTests __attribute__((objc_designated_initializer)); -// - (instancetype)initNotTestWithTest:(NSScriptWhoseTest *)subTest __attribute__((objc_designated_initializer)); - -/* @end */ - - - - - - - -#ifndef _REWRITER_typedef_NSSpecifierTest -#define _REWRITER_typedef_NSSpecifierTest -typedef struct objc_object NSSpecifierTest; -typedef struct {} _objc_exc_NSSpecifierTest; -#endif - -struct NSSpecifierTest_IMPL { - struct NSScriptWhoseTest_IMPL NSScriptWhoseTest_IVARS; - NSTestComparisonOperation _comparisonOperator; - NSScriptObjectSpecifier *_object1; - id _object2; -}; - -// - (instancetype)init __attribute__((unavailable)); -// - (nullable instancetype)initWithCoder:(NSCoder *)inCoder __attribute__((objc_designated_initializer)); -// - (instancetype)initWithObjectSpecifier:(nullable NSScriptObjectSpecifier *)obj1 comparisonOperator:(NSTestComparisonOperation)compOp testObject:(nullable id)obj2 __attribute__((objc_designated_initializer)); - -/* @end */ - - - -// @interface NSObject (NSComparisonMethods) -// - (BOOL)isEqualTo:(nullable id)object; - -// - (BOOL)isLessThanOrEqualTo:(nullable id)object; - -// - (BOOL)isLessThan:(nullable id)object; - -// - (BOOL)isGreaterThanOrEqualTo:(nullable id)object; - -// - (BOOL)isGreaterThan:(nullable id)object; - -// - (BOOL)isNotEqualTo:(nullable id)object; - -// - (BOOL)doesContain:(id)object; - - -// - (BOOL)isLike:(NSString *)object; - - - -// - (BOOL)isCaseInsensitiveLike:(NSString *)object; -/* @end */ - - - -// @interface NSObject (NSScriptingComparisonMethods) - - - - - - -// - (BOOL)scriptingIsEqualTo:(id)object; -// - (BOOL)scriptingIsLessThanOrEqualTo:(id)object; -// - (BOOL)scriptingIsLessThan:(id)object; -// - (BOOL)scriptingIsGreaterThanOrEqualTo:(id)object; -// - (BOOL)scriptingIsGreaterThan:(id)object; - -// - (BOOL)scriptingBeginsWith:(id)object; -// - (BOOL)scriptingEndsWith:(id)object; -// - (BOOL)scriptingContains:(id)object; - -/* @end */ - - - - - - - - - -// @class NSArray; -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSOrthography -#define _REWRITER_typedef_NSOrthography -typedef struct objc_object NSOrthography; -typedef struct {} _objc_exc_NSOrthography; -#endif - -// @protocol NSSpellServerDelegate; - -#ifndef _REWRITER_typedef_NSSpellServer -#define _REWRITER_typedef_NSSpellServer -typedef struct objc_object NSSpellServer; -typedef struct {} _objc_exc_NSSpellServer; -#endif - - struct __ssFlags { - unsigned int delegateLearnsWords : 1; - unsigned int delegateForgetsWords : 1; - unsigned int busy : 1; - unsigned int _reserved : 29; - } ; -struct NSSpellServer_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _delegate; - NSInteger _caseSensitive; - id _spellServerConnection; - id _dictionaries; - NSArray *_learnedDictionaries; - - struct __ssFlags _ssFlags; - id _checker; - void *_reservedSpellServer; -}; - - -// @property (nullable, assign) id<NSSpellServerDelegate> delegate; - - -// - (BOOL)registerLanguage:(nullable NSString *)language byVendor:(nullable NSString *)vendor; - - -// - (BOOL)isWordInUserDictionaries:(NSString *)word caseSensitive:(BOOL)flag; - - -// - (void)run; - -/* @end */ - -// @protocol NSSpellServerDelegate <NSObject> -/* @optional */ - -// - (NSRange)spellServer:(NSSpellServer *)sender findMisspelledWordInString:(NSString *)stringToCheck language:(NSString *)language wordCount:(NSInteger *)wordCount countOnly:(BOOL)countOnly; - -// - (nullable NSArray<NSString *> *)spellServer:(NSSpellServer *)sender suggestGuessesForWord:(NSString *)word inLanguage:(NSString *)language; - -// - (void)spellServer:(NSSpellServer *)sender didLearnWord:(NSString *)word inLanguage:(NSString *)language; - -// - (void)spellServer:(NSSpellServer *)sender didForgetWord:(NSString *)word inLanguage:(NSString *)language; - -// - (nullable NSArray<NSString *> *)spellServer:(NSSpellServer *)sender suggestCompletionsForPartialWordRange:(NSRange)range inString:(NSString *)string language:(NSString *)language; - -// - (NSRange)spellServer:(NSSpellServer *)sender checkGrammarInString:(NSString *)stringToCheck language:(nullable NSString *)language details:(NSArray<NSDictionary<NSString *, id> *> * _Nullable * _Nullable)details __attribute__((availability(macosx,introduced=10_5))); - - -extern "C" NSString *const NSGrammarRange __attribute__((availability(macosx,introduced=10_5))); -extern "C" NSString *const NSGrammarUserDescription __attribute__((availability(macosx,introduced=10_5))); -extern "C" NSString *const NSGrammarCorrections __attribute__((availability(macosx,introduced=10_5))); - -// - (nullable NSArray<NSTextCheckingResult *> *)spellServer:(NSSpellServer *)sender checkString:(NSString *)stringToCheck offset:(NSUInteger)offset types:(NSTextCheckingTypes)checkingTypes options:(nullable NSDictionary<NSString *, id> *)options orthography:(nullable NSOrthography *)orthography wordCount:(NSInteger *)wordCount __attribute__((availability(macosx,introduced=10_6))); - -// - (void)spellServer:(NSSpellServer *)sender recordResponse:(NSUInteger)response toCorrection:(NSString *)correction forWord:(NSString *)word language:(NSString *)language __attribute__((availability(macosx,introduced=10_7))); - -/* @end */ - - - - - - - - -// @class NSString; -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDateComponents -#define _REWRITER_typedef_NSDateComponents -typedef struct objc_object NSDateComponents; -typedef struct {} _objc_exc_NSDateComponents; -#endif - -#ifndef _REWRITER_typedef_NSDate -#define _REWRITER_typedef_NSDate -typedef struct objc_object NSDate; -typedef struct {} _objc_exc_NSDate; -#endif - -#ifndef _REWRITER_typedef_NSTimeZone -#define _REWRITER_typedef_NSTimeZone -typedef struct objc_object NSTimeZone; -typedef struct {} _objc_exc_NSTimeZone; -#endif - -#ifndef _REWRITER_typedef_NSImage -#define _REWRITER_typedef_NSImage -typedef struct objc_object NSImage; -typedef struct {} _objc_exc_NSImage; -#endif - -#ifndef _REWRITER_typedef_NSAttributedString -#define _REWRITER_typedef_NSAttributedString -typedef struct objc_object NSAttributedString; -typedef struct {} _objc_exc_NSAttributedString; -#endif - -#ifndef _REWRITER_typedef_NSUserNotificationAction -#define _REWRITER_typedef_NSUserNotificationAction -typedef struct objc_object NSUserNotificationAction; -typedef struct {} _objc_exc_NSUserNotificationAction; -#endif - -// @protocol NSUserNotificationCenterDelegate; - - - - -typedef NSInteger NSUserNotificationActivationType; enum { - NSUserNotificationActivationTypeNone = 0, - NSUserNotificationActivationTypeContentsClicked = 1, - NSUserNotificationActivationTypeActionButtonClicked = 2, - NSUserNotificationActivationTypeReplied __attribute__((availability(macosx,introduced=10_9))) = 3, - NSUserNotificationActivationTypeAdditionalActionClicked __attribute__((availability(macosx,introduced=10_10))) = 4, -} __attribute__((availability(macosx,introduced=10_8))); - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSUserNotification -#define _REWRITER_typedef_NSUserNotification -typedef struct objc_object NSUserNotification; -typedef struct {} _objc_exc_NSUserNotification; -#endif - -struct NSUserNotification_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _internal; -}; - - -// - (instancetype)init __attribute__((objc_designated_initializer)); - - - - - -// @property (nullable, copy) NSString *title; - - -// @property (nullable, copy) NSString *subtitle; - - -// @property (nullable, copy) NSString *informativeText; - - -// @property (copy) NSString *actionButtonTitle; - - -// @property (nullable, copy) NSDictionary<NSString *, id> *userInfo; - - -// @property (nullable, copy) NSDate *deliveryDate; - - -// @property (nullable, copy) NSTimeZone *deliveryTimeZone; - - -// @property (nullable, copy) NSDateComponents *deliveryRepeatInterval; - - -// @property (nullable, readonly, copy) NSDate *actualDeliveryDate; - - -// @property (readonly, getter=isPresented) BOOL presented; - - -// @property (readonly, getter=isRemote) BOOL remote; - - -// @property (nullable, copy) NSString *soundName; - - -// @property BOOL hasActionButton; - - -// @property (readonly) NSUserNotificationActivationType activationType; - - -// @property (copy) NSString *otherButtonTitle; - - -// @property (nullable, copy) NSString *identifier __attribute__((availability(macosx,introduced=10_9))); - - -// @property (nullable, copy) NSImage *contentImage __attribute__((availability(macosx,introduced=10_9))); - - -// @property BOOL hasReplyButton __attribute__((availability(macosx,introduced=10_9))); - - -// @property (nullable, copy) NSString *responsePlaceholder __attribute__((availability(macosx,introduced=10_9))); - - -// @property (nullable, readonly, copy) NSAttributedString *response __attribute__((availability(macosx,introduced=10_9))); - - -// @property (nullable, copy) NSArray<NSUserNotificationAction *> *additionalActions __attribute__((availability(macosx,introduced=10_10))); - -// @property (nullable, readonly, copy) NSUserNotificationAction *additionalActivationAction __attribute__((availability(macosx,introduced=10_10))); - -/* @end */ - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_10))) - -#ifndef _REWRITER_typedef_NSUserNotificationAction -#define _REWRITER_typedef_NSUserNotificationAction -typedef struct objc_object NSUserNotificationAction; -typedef struct {} _objc_exc_NSUserNotificationAction; -#endif - -struct NSUserNotificationAction_IMPL { - struct NSObject_IMPL NSObject_IVARS; -}; - - -// + (instancetype)actionWithIdentifier:(nullable NSString *)identifier title:(nullable NSString *)title; - -// @property (nullable, readonly, copy) NSString *identifier; - - -// @property (nullable, readonly, copy) NSString *title; - -/* @end */ - - -extern "C" NSString * const NSUserNotificationDefaultSoundName __attribute__((availability(macosx,introduced=10_8))); - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSUserNotificationCenter -#define _REWRITER_typedef_NSUserNotificationCenter -typedef struct objc_object NSUserNotificationCenter; -typedef struct {} _objc_exc_NSUserNotificationCenter; -#endif - -struct NSUserNotificationCenter_IMPL { - struct NSObject_IMPL NSObject_IVARS; - id _internal; -}; - - - -// + (NSUserNotificationCenter *)defaultUserNotificationCenter; - -// @property (nullable, assign) id <NSUserNotificationCenterDelegate> delegate; -// @property (copy) NSArray<NSUserNotification *> *scheduledNotifications; - - -// - (void)scheduleNotification:(NSUserNotification *)notification; - - -// - (void)removeScheduledNotification:(NSUserNotification *)notification; - - - - -// @property (readonly, copy) NSArray<NSUserNotification *> *deliveredNotifications; - - -// - (void)deliverNotification:(NSUserNotification *)notification; - - -// - (void)removeDeliveredNotification:(NSUserNotification *)notification; - - -// - (void)removeAllDeliveredNotifications; - -/* @end */ - - -// @protocol NSUserNotificationCenterDelegate <NSObject> -/* @optional */ - - -// - (void)userNotificationCenter:(NSUserNotificationCenter *)center didDeliverNotification:(NSUserNotification *)notification; - - - -// - (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification; - - -// - (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification; - -/* @end */ - - - - - - - - -// @class NSAppleEventDescriptor; -#ifndef _REWRITER_typedef_NSAppleEventDescriptor -#define _REWRITER_typedef_NSAppleEventDescriptor -typedef struct objc_object NSAppleEventDescriptor; -typedef struct {} _objc_exc_NSAppleEventDescriptor; -#endif - -#ifndef _REWRITER_typedef_NSArray -#define _REWRITER_typedef_NSArray -typedef struct objc_object NSArray; -typedef struct {} _objc_exc_NSArray; -#endif - -#ifndef _REWRITER_typedef_NSDictionary -#define _REWRITER_typedef_NSDictionary -typedef struct objc_object NSDictionary; -typedef struct {} _objc_exc_NSDictionary; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -#ifndef _REWRITER_typedef_NSFileHandle -#define _REWRITER_typedef_NSFileHandle -typedef struct objc_object NSFileHandle; -typedef struct {} _objc_exc_NSFileHandle; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSURL -#define _REWRITER_typedef_NSURL -typedef struct objc_object NSURL; -typedef struct {} _objc_exc_NSURL; -#endif - -#ifndef _REWRITER_typedef_NSXPCConnection -#define _REWRITER_typedef_NSXPCConnection -typedef struct objc_object NSXPCConnection; -typedef struct {} _objc_exc_NSXPCConnection; -#endif - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSUserScriptTask -#define _REWRITER_typedef_NSUserScriptTask -typedef struct objc_object NSUserScriptTask; -typedef struct {} _objc_exc_NSUserScriptTask; -#endif - -struct NSUserScriptTask_IMPL { - struct NSObject_IMPL NSObject_IVARS; - NSURL *_scriptURL; - NSXPCConnection *_connection; - BOOL _hasExeced; - BOOL _hasTerminated; - NSFileHandle *_stdin; - NSFileHandle *_stdout; - NSFileHandle *_stderr; -}; - - - -// - (nullable instancetype)initWithURL:(NSURL *)url error:(NSError **)error __attribute__((objc_designated_initializer)); - -// @property (readonly, copy) NSURL *scriptURL; - - -typedef void (*NSUserScriptTaskCompletionHandler)(NSError * _Nullable error); -// - (void)executeWithCompletionHandler:(nullable NSUserScriptTaskCompletionHandler)handler; - -/* @end */ - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSUserUnixTask -#define _REWRITER_typedef_NSUserUnixTask -typedef struct objc_object NSUserUnixTask; -typedef struct {} _objc_exc_NSUserUnixTask; -#endif - -struct NSUserUnixTask_IMPL { - struct NSUserScriptTask_IMPL NSUserScriptTask_IVARS; -}; - - - -// @property (nullable, retain) NSFileHandle *standardInput; -// @property (nullable, retain) NSFileHandle *standardOutput; -// @property (nullable, retain) NSFileHandle *standardError; - - -typedef void (*NSUserUnixTaskCompletionHandler)(NSError *_Nullable error); -// - (void)executeWithArguments:(nullable NSArray<NSString *> *)arguments completionHandler:(nullable NSUserUnixTaskCompletionHandler)handler; - -/* @end */ - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSUserAppleScriptTask -#define _REWRITER_typedef_NSUserAppleScriptTask -typedef struct objc_object NSUserAppleScriptTask; -typedef struct {} _objc_exc_NSUserAppleScriptTask; -#endif - -struct NSUserAppleScriptTask_IMPL { - struct NSUserScriptTask_IMPL NSUserScriptTask_IVARS; - BOOL _isParentDefaultTarget; -}; - - - -typedef void (*NSUserAppleScriptTaskCompletionHandler)(NSAppleEventDescriptor * _Nullable result, NSError * _Nullable error); -// - (void)executeWithAppleEvent:(nullable NSAppleEventDescriptor *)event completionHandler:(nullable NSUserAppleScriptTaskCompletionHandler)handler; - -/* @end */ - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSUserAutomatorTask -#define _REWRITER_typedef_NSUserAutomatorTask -typedef struct objc_object NSUserAutomatorTask; -typedef struct {} _objc_exc_NSUserAutomatorTask; -#endif - -struct NSUserAutomatorTask_IMPL { - struct NSUserScriptTask_IMPL NSUserScriptTask_IVARS; - NSDictionary *_variables; -}; - - - -// @property (nullable, copy) NSDictionary<NSString *, id> *variables; - - -typedef void (*NSUserAutomatorTaskCompletionHandler)(id _Nullable result, NSError * _Nullable error); -// - (void)executeWithInput:(nullable id <NSSecureCoding>)input completionHandler:(nullable NSUserAutomatorTaskCompletionHandler)handler; - -/* @end */ - -// @class NSMutableDictionary; -#ifndef _REWRITER_typedef_NSMutableDictionary -#define _REWRITER_typedef_NSMutableDictionary -typedef struct objc_object NSMutableDictionary; -typedef struct {} _objc_exc_NSMutableDictionary; -#endif - -#ifndef _REWRITER_typedef_NSString -#define _REWRITER_typedef_NSString -typedef struct objc_object NSString; -typedef struct {} _objc_exc_NSString; -#endif - -#ifndef _REWRITER_typedef_NSOperationQueue -#define _REWRITER_typedef_NSOperationQueue -typedef struct objc_object NSOperationQueue; -typedef struct {} _objc_exc_NSOperationQueue; -#endif - -#ifndef _REWRITER_typedef_NSSet -#define _REWRITER_typedef_NSSet -typedef struct objc_object NSSet; -typedef struct {} _objc_exc_NSSet; -#endif - -#ifndef _REWRITER_typedef_NSLock -#define _REWRITER_typedef_NSLock -typedef struct objc_object NSLock; -typedef struct {} _objc_exc_NSLock; -#endif - -#ifndef _REWRITER_typedef_NSError -#define _REWRITER_typedef_NSError -typedef struct objc_object NSError; -typedef struct {} _objc_exc_NSError; -#endif - -// @class NSXPCConnection; -#ifndef _REWRITER_typedef_NSXPCConnection -#define _REWRITER_typedef_NSXPCConnection -typedef struct objc_object NSXPCConnection; -typedef struct {} _objc_exc_NSXPCConnection; -#endif - -#ifndef _REWRITER_typedef_NSXPCListener -#define _REWRITER_typedef_NSXPCListener -typedef struct objc_object NSXPCListener; -typedef struct {} _objc_exc_NSXPCListener; -#endif - -#ifndef _REWRITER_typedef_NSXPCInterface -#define _REWRITER_typedef_NSXPCInterface -typedef struct objc_object NSXPCInterface; -typedef struct {} _objc_exc_NSXPCInterface; -#endif - -#ifndef _REWRITER_typedef_NSXPCListenerEndpoint -#define _REWRITER_typedef_NSXPCListenerEndpoint -typedef struct objc_object NSXPCListenerEndpoint; -typedef struct {} _objc_exc_NSXPCListenerEndpoint; -#endif - -// @protocol NSXPCListenerDelegate; - - - - -// @protocol NSXPCProxyCreating - - -// - (id)remoteObjectProxy; - - -// - (id)remoteObjectProxyWithErrorHandler:(void (^)(NSError *error))handler; - -/* @end */ - - - - - -typedef NSUInteger NSXPCConnectionOptions; enum { - - NSXPCConnectionPrivileged = (1 << 12UL) -} __attribute__((availability(macosx,introduced=10_8))); - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSXPCConnection -#define _REWRITER_typedef_NSXPCConnection -typedef struct objc_object NSXPCConnection; -typedef struct {} _objc_exc_NSXPCConnection; -#endif - -struct NSXPCConnection_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_xconnection; - id _repliesExpected; - dispatch_queue_t _userQueue; - uint32_t _state; - uint32_t _state2; - void (*_interruptionHandler)(); - void (*_invalidationHandler)(); - id _exportInfo; - id _repliesRequested; - id _importInfo; - id _otherInfo; - id _reserved1; - id _lock; - NSXPCInterface *_remoteObjectInterface; - NSString *_serviceName; - NSXPCListenerEndpoint *_endpoint; - id _eCache; - id _dCache; -}; - - - -// - (instancetype)initWithServiceName:(NSString *)serviceName; -// @property (nullable, readonly, copy) NSString *serviceName; - - -// - (instancetype)initWithMachServiceName:(NSString *)name options:(NSXPCConnectionOptions)options; - - -// - (instancetype)initWithListenerEndpoint:(NSXPCListenerEndpoint *)endpoint; -// @property (readonly, retain) NSXPCListenerEndpoint *endpoint; - - -// @property (nullable, retain) NSXPCInterface *exportedInterface; - - -// @property (nullable, retain) id exportedObject; - - -// @property (nullable, retain) NSXPCInterface *remoteObjectInterface; - - -// @property (readonly, retain) id remoteObjectProxy; - -// - (id)remoteObjectProxyWithErrorHandler:(void (^)(NSError *error))handler; - - - -// @property (nullable, copy) void (^interruptionHandler)(void); - - - - -// @property (nullable, copy) void (^invalidationHandler)(void); - - -// - (void)resume; - - -// - (void)suspend; - - -// - (void)invalidate; - - -// @property (readonly) au_asid_t auditSessionIdentifier; -// @property (readonly) pid_t processIdentifier; -// @property (readonly) uid_t effectiveUserIdentifier; -// @property (readonly) gid_t effectiveGroupIdentifier; - -/* @end */ - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSXPCListener -#define _REWRITER_typedef_NSXPCListener -typedef struct objc_object NSXPCListener; -typedef struct {} _objc_exc_NSXPCListener; -#endif - -struct NSXPCListener_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_xconnection; - dispatch_queue_t _userQueue; - void *reserved0; - id _delegate; - NSString *_serviceName; - uint64_t _state; - id _reserved1; - id _reserved2; -}; - - - -// + (NSXPCListener *)serviceListener; - - -// + (NSXPCListener *)anonymousListener; - - -// - (instancetype)initWithMachServiceName:(NSString *)name __attribute__((objc_designated_initializer)); - - -// @property (nullable, assign) id <NSXPCListenerDelegate> delegate; - - -// @property (readonly, retain) NSXPCListenerEndpoint *endpoint; - - -// - (void)resume; - - -// - (void)suspend; - - -// - (void)invalidate; - -/* @end */ - - -// @protocol NSXPCListenerDelegate <NSObject> -/* @optional */ - -// - (BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection; - -/* @end */ - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSXPCInterface -#define _REWRITER_typedef_NSXPCInterface -typedef struct objc_object NSXPCInterface; -typedef struct {} _objc_exc_NSXPCInterface; -#endif - -struct NSXPCInterface_IMPL { - struct NSObject_IMPL NSObject_IVARS; - Protocol *_protocol; - CFMutableDictionaryRef _methods2; - id _reserved1; -}; - - - -// + (NSXPCInterface *)interfaceWithProtocol:(Protocol *)protocol; - - -// @property (assign) Protocol *protocol; - - - -// - (void)setClasses:(NSSet<Class> *)classes forSelector:(SEL)sel argumentIndex:(NSUInteger)arg ofReply:(BOOL)ofReply; -// - (NSSet<Class> *)classesForSelector:(SEL)sel argumentIndex:(NSUInteger)arg ofReply:(BOOL)ofReply; - - -// - (void)setInterface:(NSXPCInterface *)ifc forSelector:(SEL)sel argumentIndex:(NSUInteger)arg ofReply:(BOOL)ofReply; -// - (nullable NSXPCInterface *)interfaceForSelector:(SEL)sel argumentIndex:(NSUInteger)arg ofReply:(BOOL)ofReply; - -/* @end */ - - - - - -__attribute__((visibility("default"))) __attribute__((availability(macosx,introduced=10_8))) - -#ifndef _REWRITER_typedef_NSXPCListenerEndpoint -#define _REWRITER_typedef_NSXPCListenerEndpoint -typedef struct objc_object NSXPCListenerEndpoint; -typedef struct {} _objc_exc_NSXPCListenerEndpoint; -#endif - -struct NSXPCListenerEndpoint_IMPL { - struct NSObject_IMPL NSObject_IVARS; - void *_internal; -}; - -/* @end */ - -typedef struct objc_method *Method; - - -typedef struct objc_ivar *Ivar; - - -typedef struct objc_category *Category; - - -typedef struct objc_property *objc_property_t; - -struct objc_class { - Class isa __attribute__((deprecated)); -} __attribute__((unavailable)); - - - - - -// @class Protocol; -#ifndef _REWRITER_typedef_Protocol -#define _REWRITER_typedef_Protocol -typedef struct objc_object Protocol; -typedef struct {} _objc_exc_Protocol; -#endif - - - - - - -struct objc_method_description { - SEL name; - char *types; -}; - - -typedef struct { - const char *name; - const char *value; -} objc_property_attribute_t; -extern "C" __attribute__((visibility("default"))) id object_copy(id obj, size_t size) - __attribute__((availability(macosx,introduced=10.0))) - ; -extern "C" __attribute__((visibility("default"))) id object_dispose(id obj) - __attribute__((availability(macosx,introduced=10.0))) - ; -extern "C" __attribute__((visibility("default"))) Class object_getClass(id obj) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Class object_setClass(id obj, Class cls) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL object_isClass(id obj) - __attribute__((availability(macosx,introduced=10.10))); -extern "C" __attribute__((visibility("default"))) const char *object_getClassName(id obj) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) void *object_getIndexedIvars(id obj) - __attribute__((availability(macosx,introduced=10.0))) - ; -extern "C" __attribute__((visibility("default"))) id object_getIvar(id obj, Ivar ivar) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) void object_setIvar(id obj, Ivar ivar, id value) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Ivar object_setInstanceVariable(id obj, const char *name, void *value) - __attribute__((availability(macosx,introduced=10.0))) - ; -extern "C" __attribute__((visibility("default"))) Ivar object_getInstanceVariable(id obj, const char *name, void **outValue) - __attribute__((availability(macosx,introduced=10.0))) - ; -extern "C" __attribute__((visibility("default"))) Class objc_getClass(const char *name) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) Class objc_getMetaClass(const char *name) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) Class objc_lookUpClass(const char *name) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) Class objc_getRequiredClass(const char *name) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) int objc_getClassList(Class *buffer, int bufferCount) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) Class *objc_copyClassList(unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) const char *class_getName(Class cls) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL class_isMetaClass(Class cls) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Class class_getSuperclass(Class cls) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Class class_setSuperclass(Class cls, Class newSuper) - __attribute__((availability(macosx,introduced=10.5,deprecated=10.5))); -extern "C" __attribute__((visibility("default"))) int class_getVersion(Class cls) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) void class_setVersion(Class cls, int version) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) size_t class_getInstanceSize(Class cls) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Ivar class_getInstanceVariable(Class cls, const char *name) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) Ivar class_getClassVariable(Class cls, const char *name) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Ivar *class_copyIvarList(Class cls, unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Method class_getInstanceMethod(Class cls, SEL name) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) Method class_getClassMethod(Class cls, SEL name) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) IMP class_getMethodImplementation(Class cls, SEL name) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) IMP class_getMethodImplementation_stret(Class cls, SEL name) - __attribute__((availability(macosx,introduced=10.5))) - ; -extern "C" __attribute__((visibility("default"))) BOOL class_respondsToSelector(Class cls, SEL sel) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Method *class_copyMethodList(Class cls, unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL class_conformsToProtocol(Class cls, Protocol *protocol) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Protocol * __attribute__((objc_ownership(none))) *class_copyProtocolList(Class cls, unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) objc_property_t class_getProperty(Class cls, const char *name) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const uint8_t *class_getIvarLayout(Class cls) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const uint8_t *class_getWeakIvarLayout(Class cls) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL class_addMethod(Class cls, SEL name, IMP imp, - const char *types) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) IMP class_replaceMethod(Class cls, SEL name, IMP imp, - const char *types) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL class_addIvar(Class cls, const char *name, size_t size, - uint8_t alignment, const char *types) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL class_addProtocol(Class cls, Protocol *protocol) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) void class_replaceProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount) - __attribute__((availability(macosx,introduced=10.7))); - - - - - - - -extern "C" __attribute__((visibility("default"))) void class_setIvarLayout(Class cls, const uint8_t *layout) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - - -extern "C" __attribute__((visibility("default"))) void class_setWeakIvarLayout(Class cls, const uint8_t *layout) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Class objc_getFutureClass(const char *name) - __attribute__((availability(macosx,introduced=10.5))) - ; -extern "C" __attribute__((visibility("default"))) id class_createInstance(Class cls, size_t extraBytes) - __attribute__((availability(macosx,introduced=10.0))) - ; -extern "C" __attribute__((visibility("default"))) id objc_constructInstance(Class cls, void *bytes) - __attribute__((availability(macosx,introduced=10.6))) - ; -extern "C" __attribute__((visibility("default"))) void *objc_destructInstance(id obj) - __attribute__((availability(macosx,introduced=10.6))) - ; -extern "C" __attribute__((visibility("default"))) Class objc_allocateClassPair(Class superclass, const char *name, - size_t extraBytes) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern "C" __attribute__((visibility("default"))) void objc_registerClassPair(Class cls) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern "C" __attribute__((visibility("default"))) Class objc_duplicateClass(Class original, const char *name, size_t extraBytes) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) void objc_disposeClassPair(Class cls) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) SEL method_getName(Method m) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) IMP method_getImplementation(Method m) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const char *method_getTypeEncoding(Method m) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) unsigned int method_getNumberOfArguments(Method m) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) char *method_copyReturnType(Method m) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) char *method_copyArgumentType(Method m, unsigned int index) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) void method_getReturnType(Method m, char *dst, size_t dst_len) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) void method_getArgumentType(Method m, unsigned int index, - char *dst, size_t dst_len) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) struct objc_method_description *method_getDescription(Method m) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) IMP method_setImplementation(Method m, IMP imp) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) void method_exchangeImplementations(Method m1, Method m2) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const char *ivar_getName(Ivar v) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const char *ivar_getTypeEncoding(Ivar v) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) ptrdiff_t ivar_getOffset(Ivar v) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const char *property_getName(objc_property_t property) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const char *property_getAttributes(objc_property_t property) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) objc_property_attribute_t *property_copyAttributeList(objc_property_t property, unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) char *property_copyAttributeValue(objc_property_t property, const char *attributeName) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) Protocol *objc_getProtocol(const char *name) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Protocol * __attribute__((objc_ownership(none))) *objc_copyProtocolList(unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL protocol_conformsToProtocol(Protocol *proto, Protocol *other) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL protocol_isEqual(Protocol *proto, Protocol *other) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const char *protocol_getName(Protocol *p) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) struct objc_method_description protocol_getMethodDescription(Protocol *p, SEL aSel, BOOL isRequiredMethod, BOOL isInstanceMethod) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) struct objc_method_description *protocol_copyMethodDescriptionList(Protocol *p, BOOL isRequiredMethod, BOOL isInstanceMethod, unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) objc_property_t protocol_getProperty(Protocol *proto, const char *name, BOOL isRequiredProperty, BOOL isInstanceProperty) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Protocol * __attribute__((objc_ownership(none))) *protocol_copyProtocolList(Protocol *proto, unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) Protocol *objc_allocateProtocol(const char *name) - __attribute__((availability(macosx,introduced=10.7))); - - - - - - - -extern "C" __attribute__((visibility("default"))) void objc_registerProtocol(Protocol *proto) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) void protocol_addMethodDescription(Protocol *proto, SEL name, const char *types, BOOL isRequiredMethod, BOOL isInstanceMethod) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) void protocol_addProtocol(Protocol *proto, Protocol *addition) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) void protocol_addProperty(Protocol *proto, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount, BOOL isRequiredProperty, BOOL isInstanceProperty) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) const char **objc_copyImageNames(unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const char *class_getImageName(Class cls) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const char **objc_copyClassNamesForImage(const char *image, - unsigned int *outCount) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) const char *sel_getName(SEL sel) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) SEL sel_getUid(const char *str) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) SEL sel_registerName(const char *str) - __attribute__((availability(macosx,introduced=10.0))); -extern "C" __attribute__((visibility("default"))) BOOL sel_isEqual(SEL lhs, SEL rhs) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) void objc_enumerationMutation(id obj) - __attribute__((availability(macosx,introduced=10.5))); - - - - - - -extern "C" __attribute__((visibility("default"))) void objc_setEnumerationMutationHandler(void (*handler)(id)) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) void objc_setForwardHandler(void *fwd, void *fwd_stret) - __attribute__((availability(macosx,introduced=10.5))); -extern "C" __attribute__((visibility("default"))) IMP imp_implementationWithBlock(id block) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) id imp_getBlock(IMP anImp) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) BOOL imp_removeBlock(IMP anImp) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) id objc_loadWeak(id *location) - __attribute__((availability(macosx,introduced=10.7))); -extern "C" __attribute__((visibility("default"))) id objc_storeWeak(id *location, id obj) - __attribute__((availability(macosx,introduced=10.7))); -typedef uintptr_t objc_AssociationPolicy; enum { - OBJC_ASSOCIATION_ASSIGN = 0, - OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, - - OBJC_ASSOCIATION_COPY_NONATOMIC = 3, - - OBJC_ASSOCIATION_RETAIN = 01401, - - OBJC_ASSOCIATION_COPY = 01403 - -}; -extern "C" __attribute__((visibility("default"))) void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) - __attribute__((availability(macosx,introduced=10.6))); -extern "C" __attribute__((visibility("default"))) id objc_getAssociatedObject(id object, const void *key) - __attribute__((availability(macosx,introduced=10.6))); -extern "C" __attribute__((visibility("default"))) void objc_removeAssociatedObjects(id object) - __attribute__((availability(macosx,introduced=10.6))); -struct objc_method_list; - - - - - - -extern "C" __attribute__((visibility("default"))) IMP class_lookupMethod(Class cls, SEL sel) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern "C" __attribute__((visibility("default"))) BOOL class_respondsToMethod(Class cls, SEL sel) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); -extern "C" __attribute__((visibility("default"))) void _objc_flush_caches(Class cls) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))); - -extern "C" __attribute__((visibility("default"))) id object_copyFromZone(id anObject, size_t nBytes, void *z) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))) - ; -extern "C" __attribute__((visibility("default"))) id object_realloc(id anObject, size_t nBytes) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) id object_reallocFromZone(id anObject, size_t nBytes, void *z) __attribute__((unavailable)); - - -extern "C" __attribute__((visibility("default"))) void *objc_getClasses(void) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) void objc_addClass(Class myClass) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) void objc_setClassHandler(int (*)(const char *)) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) void objc_setMultithreaded (BOOL flag) __attribute__((unavailable)); - -extern "C" __attribute__((visibility("default"))) id class_createInstanceFromZone(Class, size_t idxIvars, void *z) - __attribute__((availability(macosx,introduced=10.0,deprecated=10.5))) - ; - -extern "C" __attribute__((visibility("default"))) void class_addMethods(Class, struct objc_method_list *) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) void class_removeMethods(Class, struct objc_method_list *) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) void _objc_resolve_categories_for_class(Class cls) __attribute__((unavailable)); - -extern "C" __attribute__((visibility("default"))) Class class_poseAs(Class imposter, Class original) __attribute__((unavailable)); - -extern "C" __attribute__((visibility("default"))) unsigned int method_getSizeOfArguments(Method m) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) unsigned method_getArgumentInfo(struct objc_method *m, int arg, const char **type, int *offset) __attribute__((unavailable)); - -extern "C" __attribute__((visibility("default"))) Class objc_getOrigClass(const char *name) __attribute__((unavailable)); - -extern "C" __attribute__((visibility("default"))) struct objc_method_list *class_nextMethodList(Class, void **) __attribute__((unavailable)); - - - - - - - -extern "C" __attribute__((visibility("default"))) id (*_alloc)(Class, size_t) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) id (*_copy)(id, size_t) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) id (*_realloc)(id, size_t) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) id (*_dealloc)(id) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) id (*_zoneAlloc)(Class, size_t, void *) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) id (*_zoneRealloc)(id, size_t, void *) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) id (*_zoneCopy)(id, size_t, void *) __attribute__((unavailable)); -extern "C" __attribute__((visibility("default"))) void (*_error)(id, const char *, va_list) __attribute__((unavailable)); - -int main(int argc, const char * argv[]) { - /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; - } - return 0; -} -static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 }; diff --git a/objc/objc-runtime/debug-objc/main.m b/objc/objc-runtime/debug-objc/main.m deleted file mode 100644 index c5bbbf8..0000000 --- a/objc/objc-runtime/debug-objc/main.m +++ /dev/null @@ -1,22 +0,0 @@ -// -// main.m -// debug-objc -// -// Created by Draveness on 2/24/16. -// -// - -#import <Foundation/Foundation.h> -#import <objc/runtime.h> -#import "XXObject.h" - -int main(int argc, const char * argv[]) { - @autoreleasepool { - - XXObject *obj = [[XXObject alloc] init]; - obj.strongObject = @300; - - [obj class]; - } - return 0; -} diff --git a/objc/objc-runtime/include/Block_private.h b/objc/objc-runtime/include/Block_private.h deleted file mode 100755 index f6d40d6..0000000 --- a/objc/objc-runtime/include/Block_private.h +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Block_private.h - * - * SPI for Blocks - * - * Copyright (c) 2008-2010 Apple Inc. All rights reserved. - * - * @APPLE_LLVM_LICENSE_HEADER@ - * - */ - -#ifndef _BLOCK_PRIVATE_H_ -#define _BLOCK_PRIVATE_H_ - -#include <Availability.h> -#include <AvailabilityMacros.h> -#include <TargetConditionals.h> - -#include <stdbool.h> -#include <stdio.h> - -#include <Block.h> - -#if __cplusplus -extern "C" { -#endif - - - -enum { - BLOCK_DEALLOCATING = (0x0001), // runtime - BLOCK_REFCOUNT_MASK = (0xfffe), // runtime - BLOCK_NEEDS_FREE = (1 << 24), // runtime - BLOCK_HAS_COPY_DISPOSE = (1 << 25), // compiler - BLOCK_HAS_CTOR = (1 << 26), // compiler: helpers have C++ code - BLOCK_IS_GC = (1 << 27), // runtime - BLOCK_IS_GLOBAL = (1 << 28), // compiler - BLOCK_USE_STRET = (1 << 29), // compiler: undefined if !BLOCK_HAS_SIGNATURE - BLOCK_HAS_SIGNATURE = (1 << 30) // compiler -}; - -// revised new layout - -#define BLOCK_DESCRIPTOR_1 1 -struct Block_descriptor_1 { - unsigned long int reserved; - unsigned long int size; -}; - -#define BLOCK_DESCRIPTOR_2 1 -struct Block_descriptor_2 { - // requires BLOCK_HAS_COPY_DISPOSE - void (*copy)(void *dst, const void *src); - void (*dispose)(const void *); -}; - -#define BLOCK_DESCRIPTOR_3 1 -struct Block_descriptor_3 { - // requires BLOCK_HAS_SIGNATURE - const char *signature; - const char *layout; -}; - -struct Block_layout { - void *isa; - volatile int flags; // contains ref count - int reserved; - void (*invoke)(void *, ...); - struct Block_descriptor_1 *descriptor; - // imported variables -}; - - -struct Block_byref { - void *isa; - struct Block_byref *forwarding; - volatile int flags; // contains ref count - unsigned int size; - void (*byref_keep)(struct Block_byref *dst, struct Block_byref *src); - void (*byref_destroy)(struct Block_byref *); - // long shared[0]; -}; - -struct Block_byref_header { - void *isa; - struct Block_byref *forwarding; - int flags; - unsigned int size; -}; - - -// Runtime support functions used by compiler when generating copy/dispose helpers - -enum { - // see function implementation for a more complete description of these fields and combinations - BLOCK_FIELD_IS_OBJECT = 3, // id, NSObject, __attribute__((NSObject)), block, ... - BLOCK_FIELD_IS_BLOCK = 7, // a block variable - BLOCK_FIELD_IS_BYREF = 8, // the on stack structure holding the __block variable - BLOCK_FIELD_IS_WEAK = 16, // declared __weak, only used in byref copy helpers - BLOCK_BYREF_CALLER = 128, // called from __block (byref) copy/dispose support routines. -}; - -enum { - BLOCK_ALL_COPY_DISPOSE_FLAGS = - BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_BLOCK | BLOCK_FIELD_IS_BYREF | - BLOCK_FIELD_IS_WEAK | BLOCK_BYREF_CALLER -}; - -// Runtime entry point called by compiler when assigning objects inside copy helper routines -BLOCK_EXPORT void _Block_object_assign(void *destAddr, const void *object, const int flags); - // BLOCK_FIELD_IS_BYREF is only used from within block copy helpers - - -// runtime entry point called by the compiler when disposing of objects inside dispose helper routine -BLOCK_EXPORT void _Block_object_dispose(const void *object, const int flags); - - - -// Other support functions - -// runtime entry to get total size of a closure -BLOCK_EXPORT size_t Block_size(void *aBlock); - -// indicates whether block was compiled with compiler that sets the ABI related metadata bits -BLOCK_EXPORT bool _Block_has_signature(void *aBlock) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -// returns TRUE if return value of block is on the stack, FALSE otherwise -BLOCK_EXPORT bool _Block_use_stret(void *aBlock) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -// Returns a string describing the block's parameter and return types. -// The encoding scheme is the same as Objective-C @encode. -// Returns NULL for blocks compiled with some compilers. -BLOCK_EXPORT const char * _Block_signature(void *aBlock) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -// Returns a string describing the block's GC layout. -// Returns NULL for blocks compiled with some compilers. -BLOCK_EXPORT const char * _Block_layout(void *aBlock) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -// Callable only from the ARR weak subsystem while in exclusion zone -BLOCK_EXPORT bool _Block_tryRetain(const void *aBlock) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -// Callable only from the ARR weak subsystem while in exclusion zone -BLOCK_EXPORT bool _Block_isDeallocating(const void *aBlock) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - - -// the raw data space for runtime classes for blocks -// class+meta used for stack, malloc, and collectable based blocks -BLOCK_EXPORT void * _NSConcreteMallocBlock[32] - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2); -BLOCK_EXPORT void * _NSConcreteAutoBlock[32] - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2); -BLOCK_EXPORT void * _NSConcreteFinalizingBlock[32] - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2); -BLOCK_EXPORT void * _NSConcreteWeakBlockVariable[32] - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2); -// declared in Block.h -// BLOCK_EXPORT void * _NSConcreteGlobalBlock[32]; -// BLOCK_EXPORT void * _NSConcreteStackBlock[32]; - - -// the intercept routines that must be used under GC -BLOCK_EXPORT void _Block_use_GC( void *(*alloc)(const unsigned long, const bool isOne, const bool isObject), - void (*setHasRefcount)(const void *, const bool), - void (*gc_assign_strong)(void *, void **), - void (*gc_assign_weak)(const void *, void *), - void (*gc_memmove)(void *, void *, unsigned long)); - -// earlier version, now simply transitional -BLOCK_EXPORT void _Block_use_GC5( void *(*alloc)(const unsigned long, const bool isOne, const bool isObject), - void (*setHasRefcount)(const void *, const bool), - void (*gc_assign_strong)(void *, void **), - void (*gc_assign_weak)(const void *, void *)); - -BLOCK_EXPORT void _Block_use_RR( void (*retain)(const void *), - void (*release)(const void *)); - -struct Block_callbacks_RR { - size_t size; // size == sizeof(struct Block_callbacks_RR) - void (*retain)(const void *); - void (*release)(const void *); - void (*destructInstance)(const void *); -}; -typedef struct Block_callbacks_RR Block_callbacks_RR; - -BLOCK_EXPORT void _Block_use_RR2(const Block_callbacks_RR *callbacks); - -// make a collectable GC heap based Block. Not useful under non-GC. -BLOCK_EXPORT void *_Block_copy_collectable(const void *aBlock); - -// thread-unsafe diagnostic -BLOCK_EXPORT const char *_Block_dump(const void *block); - - -// Obsolete - -// first layout -struct Block_basic { - void *isa; - int Block_flags; // int32_t - int Block_size; // XXX should be packed into Block_flags - void (*Block_invoke)(void *); - void (*Block_copy)(void *dst, void *src); // iff BLOCK_HAS_COPY_DISPOSE - void (*Block_dispose)(void *); // iff BLOCK_HAS_COPY_DISPOSE - //long params[0]; // where const imports, __block storage references, etc. get laid down -}; - - -#if __cplusplus -} -#endif - - -#endif diff --git a/objc/objc-runtime/include/CrashReporterClient.h b/objc/objc-runtime/include/CrashReporterClient.h deleted file mode 100755 index 1c9c61a..0000000 --- a/objc/objc-runtime/include/CrashReporterClient.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2010 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@ - */ - -/*********************************************************************** - * Not to be installed in /usr/local/include - ***********************************************************************/ - -#ifndef _LIBC_CRASHREPORTERCLIENT_H -#define _LIBC_CRASHREPORTERCLIENT_H - -#ifdef LIBC_NO_LIBCRASHREPORTERCLIENT - -/* Fake the CrashReporterClient API */ -#define CRGetCrashLogMessage() 0 -#define CRSetCrashLogMessage(x) /* nothing */ -#define CRSetCrashLogMessage2(x) /* nothing */ - -#else /* !LIBC_NO_LIBCRASHREPORTERCLIENT */ - -/* Include the real CrashReporterClient.h */ -#include_next <CrashReporterClient.h> - -#endif /* !LIBC_NO_LIBCRASHREPORTERCLIENT */ - -#endif /* _LIBC_CRASHREPORTERCLIENT_H */ diff --git a/objc/objc-runtime/include/System/i386/cpu_capabilities.h b/objc/objc-runtime/include/System/i386/cpu_capabilities.h deleted file mode 100755 index 470e8a3..0000000 --- a/objc/objc-runtime/include/System/i386/cpu_capabilities.h +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright (c) 2003-2009 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifdef PRIVATE - -#ifndef _I386_CPU_CAPABILITIES_H -#define _I386_CPU_CAPABILITIES_H - -#ifndef __ASSEMBLER__ -#include <stdint.h> -#endif - -/* - * This API only supported for Apple internal use. - */ - -/* Bit definitions for _cpu_capabilities: */ - -#define kHasMMX 0x00000001 -#define kHasSSE 0x00000002 -#define kHasSSE2 0x00000004 -#define kHasSSE3 0x00000008 -#define kCache32 0x00000010 /* cache line size is 32 bytes */ -#define kCache64 0x00000020 -#define kCache128 0x00000040 -#define kFastThreadLocalStorage 0x00000080 /* TLS ptr is kept in a user-mode-readable register */ -#define kHasSupplementalSSE3 0x00000100 -#define k64Bit 0x00000200 /* processor supports EM64T (not what mode you're running in) */ -#define kHasSSE4_1 0x00000400 -#define kHasSSE4_2 0x00000800 -#define kHasAES 0x00001000 -#define kInOrderPipeline 0x00002000 /* in-order execution */ -#define kSlow 0x00004000 /* tsc < nanosecond */ -#define kUP 0x00008000 /* set if (kNumCPUs == 1) */ -#define kNumCPUs 0x00FF0000 /* number of CPUs (see _NumCPUs() below) */ - -#define kNumCPUsShift 16 /* see _NumCPUs() below */ - -#ifndef __ASSEMBLER__ -#include <sys/cdefs.h> - -__BEGIN_DECLS -extern int _get_cpu_capabilities( void ); -__END_DECLS - -inline static -int _NumCPUs( void ) -{ - return (_get_cpu_capabilities() & kNumCPUs) >> kNumCPUsShift; -} - -#endif /* __ASSEMBLER__ */ - - -/* - * The shared kernel/user "comm page(s)": - * - * The last several pages of every address space are reserved for the kernel/user - * "comm area". During system initialization, the kernel populates the comm pages with - * code customized for the particular processor and platform. - * - * Because Mach VM cannot map the last page of an address space, we don't use it. - */ - -#define _COMM_PAGE32_AREA_LENGTH ( 19 * 4096 ) /* reserved length of entire comm area */ -#define _COMM_PAGE32_BASE_ADDRESS ( 0xfffec000 ) /* base address of allocated memory, -20 pages */ -#define _COMM_PAGE32_START_ADDRESS ( 0xffff0000 ) /* address traditional commpage code starts on, -16 pages */ -#define _COMM_PAGE32_AREA_USED ( 19 * 4096 ) /* this is the amt actually allocated */ -#define _COMM_PAGE32_SIGS_OFFSET 0x8000 /* offset to routine signatures */ - -#define _COMM_PAGE64_AREA_LENGTH ( 2 * 1024 * 1024 ) /* reserved length of entire comm area (2MB) */ -#define _COMM_PAGE64_BASE_ADDRESS ( 0x00007fffffe00000ULL ) /* base address of allocated memory */ -#define _COMM_PAGE64_START_ADDRESS ( _COMM_PAGE64_BASE_ADDRESS ) /* address traditional commpage code starts on */ -#define _COMM_PAGE64_AREA_USED ( 2 * 4096 ) /* this is the amt actually populated */ - -/* no need for an Objective-C area on Intel */ -#define _COMM_PAGE32_OBJC_SIZE 0ULL -#define _COMM_PAGE32_OBJC_BASE 0ULL -#define _COMM_PAGE64_OBJC_SIZE 0ULL -#define _COMM_PAGE64_OBJC_BASE 0ULL - -#ifdef KERNEL_PRIVATE - -/* Inside the kernel, comm page addresses are absolute addresses - * assuming they are a part of the 32-bit commpage. They may - * be mapped somewhere else, especially for the 64-bit commpage. - */ -#define _COMM_PAGE_START_ADDRESS _COMM_PAGE32_START_ADDRESS -#define _COMM_PAGE_SIGS_OFFSET _COMM_PAGE32_SIGS_OFFSET - -#else /* !KERNEL_PRIVATE */ - -#if defined(__i386__) - -#define _COMM_PAGE_AREA_LENGTH _COMM_PAGE32_AREA_LENGTH -#define _COMM_PAGE_BASE_ADDRESS _COMM_PAGE32_BASE_ADDRESS -#define _COMM_PAGE_START_ADDRESS _COMM_PAGE32_START_ADDRESS -#define _COMM_PAGE_AREA_USED _COMM_PAGE32_AREA_USED -#define _COMM_PAGE_SIGS_OFFSET _COMM_PAGE32_SIGS_OFFSET - -#elif defined(__x86_64__) - -#define _COMM_PAGE_AREA_LENGTH _COMM_PAGE64_AREA_LENGTH -#define _COMM_PAGE_BASE_ADDRESS _COMM_PAGE64_BASE_ADDRESS -#define _COMM_PAGE_START_ADDRESS _COMM_PAGE64_START_ADDRESS -#define _COMM_PAGE_AREA_USED _COMM_PAGE64_AREA_USED - -#else -#error architecture not supported -#endif - -#endif /* !KERNEL_PRIVATE */ - -/* data in the comm page */ - -#define _COMM_PAGE_SIGNATURE (_COMM_PAGE_START_ADDRESS+0x000) /* first few bytes are a signature */ -#define _COMM_PAGE_VERSION (_COMM_PAGE_START_ADDRESS+0x01E) /* 16-bit version# */ -#define _COMM_PAGE_THIS_VERSION 11 /* version of the commarea format */ - -#define _COMM_PAGE_CPU_CAPABILITIES (_COMM_PAGE_START_ADDRESS+0x020) /* uint32_t _cpu_capabilities */ -#define _COMM_PAGE_NCPUS (_COMM_PAGE_START_ADDRESS+0x022) /* uint8_t number of configured CPUs */ -#define _COMM_PAGE_CACHE_LINESIZE (_COMM_PAGE_START_ADDRESS+0x026) /* uint16_t cache line size */ - -#define _COMM_PAGE_SCHED_GEN (_COMM_PAGE_START_ADDRESS+0x028) /* uint32_t scheduler generation number (count of pre-emptions) */ -#define _COMM_PAGE_MEMORY_PRESSURE (_COMM_PAGE_START_ADDRESS+0x02c) /* uint32_t copy of vm_memory_pressure */ -#define _COMM_PAGE_SPIN_COUNT (_COMM_PAGE_START_ADDRESS+0x030) /* uint32_t max spin count for mutex's */ - -#define _COMM_PAGE_UNUSED1 (_COMM_PAGE_START_ADDRESS+0x034) /* 12 unused bytes */ - -#ifdef KERNEL_PRIVATE - -/* slots defined in all cases, but commpage setup code must not populate for 64-bit commpage */ -#define _COMM_PAGE_2_TO_52 (_COMM_PAGE_START_ADDRESS+0x040) /* double float constant 2**52 */ -#define _COMM_PAGE_10_TO_6 (_COMM_PAGE_START_ADDRESS+0x048) /* double float constant 10**6 */ - -#else /* !KERNEL_PRIVATE */ - -#if defined(__i386__) /* following are not defined in 64-bit */ -#define _COMM_PAGE_2_TO_52 (_COMM_PAGE_START_ADDRESS+0x040) /* double float constant 2**52 */ -#define _COMM_PAGE_10_TO_6 (_COMM_PAGE_START_ADDRESS+0x048) /* double float constant 10**6 */ -#else -#define _COMM_PAGE_UNUSED2 (_COMM_PAGE_START_ADDRESS+0x040) /* 16 unused bytes */ -#endif - -#endif /* !KERNEL_PRIVATE */ - -#define _COMM_PAGE_TIME_DATA_START (_COMM_PAGE_START_ADDRESS+0x050) /* base of offsets below (_NT_SCALE etc) */ -#define _COMM_PAGE_NT_TSC_BASE (_COMM_PAGE_START_ADDRESS+0x050) /* used by nanotime() */ -#define _COMM_PAGE_NT_SCALE (_COMM_PAGE_START_ADDRESS+0x058) /* used by nanotime() */ -#define _COMM_PAGE_NT_SHIFT (_COMM_PAGE_START_ADDRESS+0x05c) /* used by nanotime() */ -#define _COMM_PAGE_NT_NS_BASE (_COMM_PAGE_START_ADDRESS+0x060) /* used by nanotime() */ -#define _COMM_PAGE_NT_GENERATION (_COMM_PAGE_START_ADDRESS+0x068) /* used by nanotime() */ -#define _COMM_PAGE_GTOD_GENERATION (_COMM_PAGE_START_ADDRESS+0x06c) /* used by gettimeofday() */ -#define _COMM_PAGE_GTOD_NS_BASE (_COMM_PAGE_START_ADDRESS+0x070) /* used by gettimeofday() */ -#define _COMM_PAGE_GTOD_SEC_BASE (_COMM_PAGE_START_ADDRESS+0x078) /* used by gettimeofday() */ - -/* Warning: kernel commpage.h has a matching c typedef for the following. They must be kept in sync. */ -/* These offsets are from _COMM_PAGE_TIME_DATA_START */ - -#define _NT_TSC_BASE 0 -#define _NT_SCALE 8 -#define _NT_SHIFT 12 -#define _NT_NS_BASE 16 -#define _NT_GENERATION 24 -#define _GTOD_GENERATION 28 -#define _GTOD_NS_BASE 32 -#define _GTOD_SEC_BASE 40 - - /* jump table (jmp to this address, which may be a branch to the actual code somewhere else) */ - /* When new jump table entries are added, corresponding symbols should be added below */ - /* New slots should be allocated with at least 16-byte alignment. Some like bcopy require */ - /* 32-byte alignment, and should be aligned as such in the assembly source before they are relocated */ -#define _COMM_PAGE_COMPARE_AND_SWAP32 (_COMM_PAGE_START_ADDRESS+0x080) /* compare-and-swap word */ -#define _COMM_PAGE_COMPARE_AND_SWAP64 (_COMM_PAGE_START_ADDRESS+0x0c0) /* compare-and-swap doubleword */ -#define _COMM_PAGE_ENQUEUE (_COMM_PAGE_START_ADDRESS+0x100) /* enqueue */ -#define _COMM_PAGE_DEQUEUE (_COMM_PAGE_START_ADDRESS+0x140) /* dequeue */ -#define _COMM_PAGE_MEMORY_BARRIER (_COMM_PAGE_START_ADDRESS+0x180) /* memory barrier */ -#define _COMM_PAGE_ATOMIC_ADD32 (_COMM_PAGE_START_ADDRESS+0x1a0) /* add atomic word */ -#define _COMM_PAGE_ATOMIC_ADD64 (_COMM_PAGE_START_ADDRESS+0x1c0) /* add atomic doubleword */ - -#define _COMM_PAGE_CPU_NUMBER (_COMM_PAGE_START_ADDRESS+0x1e0) /* user-level cpu_number() */ - -#define _COMM_PAGE_ABSOLUTE_TIME (_COMM_PAGE_START_ADDRESS+0x200) /* mach_absolute_time() */ -#define _COMM_PAGE_SPINLOCK_TRY (_COMM_PAGE_START_ADDRESS+0x220) /* spinlock_try() */ -#define _COMM_PAGE_SPINLOCK_LOCK (_COMM_PAGE_START_ADDRESS+0x260) /* spinlock_lock() */ -#define _COMM_PAGE_SPINLOCK_UNLOCK (_COMM_PAGE_START_ADDRESS+0x2a0) /* spinlock_unlock() */ -#define _COMM_PAGE_PTHREAD_GETSPECIFIC (_COMM_PAGE_START_ADDRESS+0x2c0) /* pthread_getspecific() */ -#define _COMM_PAGE_GETTIMEOFDAY (_COMM_PAGE_START_ADDRESS+0x2e0) /* used by gettimeofday() */ -#define _COMM_PAGE_FLUSH_DCACHE (_COMM_PAGE_START_ADDRESS+0x4e0) /* sys_dcache_flush() */ -#define _COMM_PAGE_FLUSH_ICACHE (_COMM_PAGE_START_ADDRESS+0x520) /* sys_icache_invalidate() */ -#define _COMM_PAGE_PTHREAD_SELF (_COMM_PAGE_START_ADDRESS+0x580) /* pthread_self() */ - -#define _COMM_PAGE_PREEMPT (_COMM_PAGE_START_ADDRESS+0x5a0) /* used by PFZ code */ - -#define _COMM_PAGE_RELINQUISH (_COMM_PAGE_START_ADDRESS+0x5c0) /* used by spinlocks */ -#define _COMM_PAGE_BTS (_COMM_PAGE_START_ADDRESS+0x5e0) /* bit test-and-set */ -#define _COMM_PAGE_BTC (_COMM_PAGE_START_ADDRESS+0x5f0) /* bit test-and-clear */ - -#define _COMM_PAGE_BZERO (_COMM_PAGE_START_ADDRESS+0x600) /* bzero() */ -#define _COMM_PAGE_BCOPY (_COMM_PAGE_START_ADDRESS+0x780) /* bcopy() */ -#define _COMM_PAGE_MEMCPY (_COMM_PAGE_START_ADDRESS+0x7a0) /* memcpy() */ -#define _COMM_PAGE_MEMMOVE (_COMM_PAGE_START_ADDRESS+0x7a0) /* memmove() */ -#define _COMM_PAGE_BCOPY_END (_COMM_PAGE_START_ADDRESS+0xfff) /* used by rosetta */ - -#define _COMM_PAGE_MEMSET_PATTERN (_COMM_PAGE_START_ADDRESS+0x1000) /* used by nonzero memset() */ -#define _COMM_PAGE_LONGCOPY (_COMM_PAGE_START_ADDRESS+0x1200) /* used by bcopy() for very long operands */ -#define _COMM_PAGE_LONGCOPY_END (_COMM_PAGE_START_ADDRESS+0x15ff) /* used by rosetta */ - -#define _COMM_PAGE_BACKOFF (_COMM_PAGE_START_ADDRESS+0x1600) /* called from PFZ */ -#define _COMM_PAGE_FIFO_ENQUEUE (_COMM_PAGE_START_ADDRESS+0x1680) /* FIFO enqueue */ -#define _COMM_PAGE_FIFO_DEQUEUE (_COMM_PAGE_START_ADDRESS+0x16c0) /* FIFO dequeue */ -#define _COMM_PAGE_NANOTIME (_COMM_PAGE_START_ADDRESS+0x1700) /* nanotime() */ -#define _COMM_PAGE_MUTEX_LOCK (_COMM_PAGE_START_ADDRESS+0x1780) /* pthread_mutex_lock() */ - -#define _COMM_PAGE_UNUSED5 (_COMM_PAGE_START_ADDRESS+0x17e0) /* unused space for regular code up to 0x1c00 */ - -#define _COMM_PAGE_PFZ_START (_COMM_PAGE_START_ADDRESS+0x1c00) /* start of Preemption Free Zone */ - -#define _COMM_PAGE_PFZ_ENQUEUE (_COMM_PAGE_START_ADDRESS+0x1c00) /* internal routine for FIFO enqueue */ -#define _COMM_PAGE_PFZ_DEQUEUE (_COMM_PAGE_START_ADDRESS+0x1c80) /* internal routine for FIFO dequeue */ -#define _COMM_PAGE_PFZ_MUTEX_LOCK (_COMM_PAGE_START_ADDRESS+0x1d00) /* internal routine for pthread_mutex_lock() */ - -#define _COMM_PAGE_UNUSED6 (_COMM_PAGE_START_ADDRESS+0x1d80) /* unused space for PFZ code up to 0x1fff */ - -#define _COMM_PAGE_PFZ_END (_COMM_PAGE_START_ADDRESS+0x1fff) /* end of Preemption Free Zone */ - -#define _COMM_PAGE_END (_COMM_PAGE_START_ADDRESS+0x1fff) /* end of common page - insert new stuff here */ - -/* _COMM_PAGE_COMPARE_AND_SWAP{32,64}B are not used on x86 and are - * maintained here for source compatability. These will be removed at - * some point, so don't go relying on them. */ -#define _COMM_PAGE_COMPARE_AND_SWAP32B (_COMM_PAGE_START_ADDRESS+0xf80) /* compare-and-swap word w barrier */ -#define _COMM_PAGE_COMPARE_AND_SWAP64B (_COMM_PAGE_START_ADDRESS+0xfc0) /* compare-and-swap doubleword w barrier */ - -#ifdef __ASSEMBLER__ -#ifdef __COMM_PAGE_SYMBOLS - -#define CREATE_COMM_PAGE_SYMBOL(symbol_name, symbol_address) \ - .org (symbol_address - (_COMM_PAGE_START_ADDRESS & 0xFFFFE000)) ;\ -symbol_name: nop - - .text /* Required to make a well behaved symbol file */ - - CREATE_COMM_PAGE_SYMBOL(___compare_and_swap32, _COMM_PAGE_COMPARE_AND_SWAP32) - CREATE_COMM_PAGE_SYMBOL(___compare_and_swap64, _COMM_PAGE_COMPARE_AND_SWAP64) - CREATE_COMM_PAGE_SYMBOL(___atomic_enqueue, _COMM_PAGE_ENQUEUE) - CREATE_COMM_PAGE_SYMBOL(___atomic_dequeue, _COMM_PAGE_DEQUEUE) - CREATE_COMM_PAGE_SYMBOL(___memory_barrier, _COMM_PAGE_MEMORY_BARRIER) - CREATE_COMM_PAGE_SYMBOL(___atomic_add32, _COMM_PAGE_ATOMIC_ADD32) - CREATE_COMM_PAGE_SYMBOL(___atomic_add64, _COMM_PAGE_ATOMIC_ADD64) - CREATE_COMM_PAGE_SYMBOL(___cpu_number, _COMM_PAGE_CPU_NUMBER) - CREATE_COMM_PAGE_SYMBOL(___mach_absolute_time, _COMM_PAGE_ABSOLUTE_TIME) - CREATE_COMM_PAGE_SYMBOL(___spin_lock_try, _COMM_PAGE_SPINLOCK_TRY) - CREATE_COMM_PAGE_SYMBOL(___spin_lock, _COMM_PAGE_SPINLOCK_LOCK) - CREATE_COMM_PAGE_SYMBOL(___spin_unlock, _COMM_PAGE_SPINLOCK_UNLOCK) - CREATE_COMM_PAGE_SYMBOL(___pthread_getspecific, _COMM_PAGE_PTHREAD_GETSPECIFIC) - CREATE_COMM_PAGE_SYMBOL(___gettimeofday, _COMM_PAGE_GETTIMEOFDAY) - CREATE_COMM_PAGE_SYMBOL(___sys_dcache_flush, _COMM_PAGE_FLUSH_DCACHE) - CREATE_COMM_PAGE_SYMBOL(___sys_icache_invalidate, _COMM_PAGE_FLUSH_ICACHE) - CREATE_COMM_PAGE_SYMBOL(___pthread_self, _COMM_PAGE_PTHREAD_SELF) - CREATE_COMM_PAGE_SYMBOL(___pfz_preempt, _COMM_PAGE_PREEMPT) - CREATE_COMM_PAGE_SYMBOL(___spin_lock_relinquish, _COMM_PAGE_RELINQUISH) - CREATE_COMM_PAGE_SYMBOL(___bit_test_and_set, _COMM_PAGE_BTS) - CREATE_COMM_PAGE_SYMBOL(___bit_test_and_clear, _COMM_PAGE_BTC) - CREATE_COMM_PAGE_SYMBOL(___bzero, _COMM_PAGE_BZERO) - CREATE_COMM_PAGE_SYMBOL(___bcopy, _COMM_PAGE_BCOPY) - CREATE_COMM_PAGE_SYMBOL(___memcpy, _COMM_PAGE_MEMCPY) -/* CREATE_COMM_PAGE_SYMBOL(___memmove, _COMM_PAGE_MEMMOVE) */ - CREATE_COMM_PAGE_SYMBOL(___memset_pattern, _COMM_PAGE_MEMSET_PATTERN) - CREATE_COMM_PAGE_SYMBOL(___longcopy, _COMM_PAGE_LONGCOPY) - CREATE_COMM_PAGE_SYMBOL(___backoff, _COMM_PAGE_BACKOFF) - CREATE_COMM_PAGE_SYMBOL(___fifo_enqueue, _COMM_PAGE_FIFO_ENQUEUE) - CREATE_COMM_PAGE_SYMBOL(___fifo_dequeue, _COMM_PAGE_FIFO_DEQUEUE) - CREATE_COMM_PAGE_SYMBOL(___nanotime, _COMM_PAGE_NANOTIME) - CREATE_COMM_PAGE_SYMBOL(___mutex_lock, _COMM_PAGE_MUTEX_LOCK) - CREATE_COMM_PAGE_SYMBOL(___pfz_enqueue, _COMM_PAGE_PFZ_ENQUEUE) - CREATE_COMM_PAGE_SYMBOL(___pfz_dequeue, _COMM_PAGE_PFZ_DEQUEUE) - CREATE_COMM_PAGE_SYMBOL(___pfz_mutex_lock, _COMM_PAGE_PFZ_MUTEX_LOCK) - CREATE_COMM_PAGE_SYMBOL(___end_comm_page, _COMM_PAGE_END) - - .data /* Required to make a well behaved symbol file */ - .long 0 /* Required to make a well behaved symbol file */ - -#endif /* __COMM_PAGE_SYMBOLS */ -#endif /* __ASSEMBLER__ */ - -#endif /* _I386_CPU_CAPABILITIES_H */ -#endif /* PRIVATE */ diff --git a/objc/objc-runtime/include/System/machine/cpu_capabilities.h b/objc/objc-runtime/include/System/machine/cpu_capabilities.h deleted file mode 100755 index 606ec28..0000000 --- a/objc/objc-runtime/include/System/machine/cpu_capabilities.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifdef PRIVATE - -#ifndef _MACHINE_CPU_CAPABILITIES_H -#define _MACHINE_CPU_CAPABILITIES_H - -#ifdef KERNEL_PRIVATE -#if defined (__ppc__) -#include "ppc/cpu_capabilities.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/cpu_capabilities.h" -#else -#error architecture not supported -#endif - -#else /* !KERNEL_PRIVATE -- System Framework header */ -#if defined (__ppc__) || defined(__ppc64__) -#include <System/ppc/cpu_capabilities.h> -#elif defined (__i386__) || defined(__x86_64__) -#include <System/i386/cpu_capabilities.h> -#else -#error architecture not supported -#endif -#endif /* KERNEL_PRIVATE */ - -#endif /* _MACHINE_CPU_CAPABILITIES_H */ -#endif /* PRIVATE */ diff --git a/objc/objc-runtime/include/System/ppc/cpu_capabilities.h b/objc/objc-runtime/include/System/ppc/cpu_capabilities.h deleted file mode 100755 index 268666c..0000000 --- a/objc/objc-runtime/include/System/ppc/cpu_capabilities.h +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (c) 2003-2006 Apple Computer, Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifdef PRIVATE - -#ifndef _PPC_CPU_CAPABILITIES_H -#define _PPC_CPU_CAPABILITIES_H - -/* _cpu_capabilities - * - * This is the authoritative way to determine from user mode what - * implementation-specific processor features are available. - * This API is only supported for Apple internal use. - */ - -#ifndef __ASSEMBLER__ - -extern int _cpu_capabilities; - -#endif /* __ASSEMBLER__ */ - -/* Bit definitions for _cpu_capabilities: */ - -#define kHasAltivec 0x00000001 -#define k64Bit 0x00000002 // 64-bit GPRs -#define kCache32 0x00000004 // cache line size is 32 bytes -#define kCache64 0x00000008 -#define kCache128 0x00000010 -#define kDcbaRecommended 0x00000020 // PPC: dcba is available and recommended -#define kDcbaAvailable 0x00000040 // PPC: dcba is available (but may or may not be recommended) -#define kDataStreamsRecommended 0x00000080 // PPC: dst, dstt, dstst, dss, and dssall instructions available and recommended -#define kDataStreamsAvailable 0x00000100 // PPC: dst, dstt, dstst, dss, and dssall instructions available (may or may not be rec'd) -#define kDcbtStreamsRecommended 0x00000200 // PPC: enhanced dcbt instruction available and recommended -#define kDcbtStreamsAvailable 0x00000400 // PPC: enhanced dcbt instruction available (but may or may not be recommended) -#define kFastThreadLocalStorage 0x00000800 // TLS ptr is kept in a user-mode-readable register - -#define kUP 0x00008000 // set if (kNumCPUs == 1) -#define kNumCPUs 0x00FF0000 // number of CPUs (see _NumCPUs() below) - -#define kNumCPUsShift 16 // see _NumCPUs() below - -#define kHasGraphicsOps 0x08000000 // PPC: has fres, frsqrte, and fsel instructions -#define kHasStfiwx 0x10000000 // PPC: has stfiwx instruction -#define kHasFsqrt 0x20000000 // PPC: has fsqrt and fsqrts instructions - -#ifndef __ASSEMBLER__ - -static __inline__ int _NumCPUs( void ) { return (_cpu_capabilities & kNumCPUs) >> kNumCPUsShift; } - -#endif /* __ASSEMBLER__ */ - - -/* - * The shared kernel/user "comm page(s)": - * - * The last eight pages of every address space are reserved for the kernel/user - * "comm area". Because they can be addressed via a sign-extended 16-bit field, - * it is particularly efficient to access code or data in the comm area with - * absolute branches (ba, bla, bca) or absolute load/stores ("lwz r0,-4096(0)"). - * Because the comm area can be reached from anywhere, dyld is not needed. - * Although eight pages are reserved, presently only two are populated and mapped. - * - * Routines on the comm page(s) can be thought of as the firmware for extended processor - * instructions, whose opcodes are special forms of "bla". Ie, they are cpu - * capabilities. During system initialization, the kernel populates the comm page with - * code customized for the particular processor and platform. - * - * Because Mach VM cannot map the last page of an address space, the max length of - * the comm area is seven pages. - */ - -#define _COMM_PAGE_BASE_ADDRESS (-8*4096) // start at page -8, ie 0xFFFF8000 -#define _COMM_PAGE_AREA_LENGTH ( 7*4096) // reserved length of entire comm area -#define _COMM_PAGE_AREA_USED ( 2*4096) // we use two pages so far - -/* The following set of definitions are used in the kernel, which needs to distinguish between - * the 32 and 64-bit commpage addresses and lengths. On PPC they are the same, but on Imtel - * they are not. - */ -#define _COMM_PAGE32_BASE_ADDRESS ( _COMM_PAGE_BASE_ADDRESS ) -#define _COMM_PAGE64_BASE_ADDRESS ( _COMM_PAGE_BASE_ADDRESS ) -#define _COMM_PAGE32_AREA_LENGTH ( _COMM_PAGE_AREA_LENGTH ) -#define _COMM_PAGE64_AREA_LENGTH ( _COMM_PAGE_AREA_LENGTH ) -#define _COMM_PAGE32_AREA_USED ( _COMM_PAGE_AREA_USED ) -#define _COMM_PAGE64_AREA_USED ( _COMM_PAGE_AREA_USED ) - -/* The Objective-C runtime fixed address page to optimize message dispatch */ -#define _OBJC_PAGE_BASE_ADDRESS (-20*4096) // start at page -20, ie 0xFFFEC000 - -/* - * Objective-C needs an "absolute" area all the way up to the top of the - * address space. - * For a ppc32 task, that area gets allocated at runtime from user space. - * For a ppc64 task, that area is not within the user-accessible address range, - * so we pre-allocate it at exec time (see vm_map_exec()) along with the - * comm page. - * - * NOTE: that means we can't "nest" the 64-bit comm page... - */ -#define _COMM_PAGE32_OBJC_SIZE 0ULL -#define _COMM_PAGE32_OBJC_BASE 0ULL -#if 0 -#define _COMM_PAGE64_OBJC_SIZE (4 * 4096) -#define _COMM_PAGE64_OBJC_BASE (_OBJC_PAGE_BASE_ADDRESS) -#else -/* - * PPC51: ppc64 is limited to 51-bit addresses. - * PPC64 has a 51-bit address space limit, so we can't just go and - * map the Obj-C area up there. We would have to create a nested pmap - * and make a special mapping that redirects the large virtual addresses to - * that other address space with lower addresses that fit within the 51-bit - * limit. - * VM would then have to handle this redirection when we fault one - * of these pages in but it doesn't do that at this point, so no - * Obj-C area for ppc64 for now :-( - */ -#define _COMM_PAGE64_OBJC_SIZE 0ULL -#define _COMM_PAGE64_OBJC_BASE 0ULL -#endif - -/* data in the comm page */ - -#define _COMM_PAGE_SIGNATURE (_COMM_PAGE_BASE_ADDRESS+0x000) // first few bytes are a signature -#define _COMM_PAGE_VERSION (_COMM_PAGE_BASE_ADDRESS+0x01E) // 16-bit version# -#define _COMM_PAGE_THIS_VERSION 2 // this is version 2 of the commarea format - -#define _COMM_PAGE_CPU_CAPABILITIES (_COMM_PAGE_BASE_ADDRESS+0x020) // mirror of extern int _cpu_capabilities -#define _COMM_PAGE_NCPUS (_COMM_PAGE_BASE_ADDRESS+0x021) // number of configured CPUs -#define _COMM_PAGE_ALTIVEC (_COMM_PAGE_BASE_ADDRESS+0x024) // nonzero if Altivec available -#define _COMM_PAGE_64_BIT (_COMM_PAGE_BASE_ADDRESS+0x025) // nonzero if 64-bit processor -#define _COMM_PAGE_CACHE_LINESIZE (_COMM_PAGE_BASE_ADDRESS+0x026) // cache line size (16-bit field) - -#define _COMM_PAGE_UNUSED1 (_COMM_PAGE_BASE_ADDRESS+0x028) // 24 unused bytes - -#define _COMM_PAGE_2_TO_52 (_COMM_PAGE_BASE_ADDRESS+0x040) // double float constant 2**52 -#define _COMM_PAGE_10_TO_6 (_COMM_PAGE_BASE_ADDRESS+0x048) // double float constant 10**6 -#define _COMM_PAGE_MAGIC_FE (_COMM_PAGE_BASE_ADDRESS+0x050) // magic constant 0xFEFEFEFEFEFEFEFF (to find 0s) -#define _COMM_PAGE_MAGIC_80 (_COMM_PAGE_BASE_ADDRESS+0x058) // magic constant 0x8080808080808080 (to find 0s) - -#define _COMM_PAGE_TIMEBASE (_COMM_PAGE_BASE_ADDRESS+0x060) // used by gettimeofday() -#define _COMM_PAGE_TIMESTAMP (_COMM_PAGE_BASE_ADDRESS+0x068) // used by gettimeofday() -#define _COMM_PAGE_SEC_PER_TICK (_COMM_PAGE_BASE_ADDRESS+0x070) // used by gettimeofday() - - /* jump table (bla to this address, which may be a branch to the actual code somewhere else) */ - /* When new jump table entries are added, corresponding symbols should be added below */ - -#define _COMM_PAGE_COMPARE_AND_SWAP32 (_COMM_PAGE_BASE_ADDRESS+0x080) // compare-and-swap word, no barrier -#define _COMM_PAGE_COMPARE_AND_SWAP64 (_COMM_PAGE_BASE_ADDRESS+0x0c0) // compare-and-swap doubleword, no barrier -#define _COMM_PAGE_ENQUEUE (_COMM_PAGE_BASE_ADDRESS+0x100) // enqueue -#define _COMM_PAGE_DEQUEUE (_COMM_PAGE_BASE_ADDRESS+0x140) // dequeue -#define _COMM_PAGE_MEMORY_BARRIER (_COMM_PAGE_BASE_ADDRESS+0x180) // memory barrier -#define _COMM_PAGE_ATOMIC_ADD32 (_COMM_PAGE_BASE_ADDRESS+0x1a0) // add atomic word -#define _COMM_PAGE_ATOMIC_ADD64 (_COMM_PAGE_BASE_ADDRESS+0x1c0) // add atomic doubleword - -#define _COMM_PAGE_UNUSED3 (_COMM_PAGE_BASE_ADDRESS+0x1e0) // 32 unused bytes - -#define _COMM_PAGE_ABSOLUTE_TIME (_COMM_PAGE_BASE_ADDRESS+0x200) // mach_absolute_time() -#define _COMM_PAGE_SPINLOCK_TRY (_COMM_PAGE_BASE_ADDRESS+0x220) // spinlock_try() -#define _COMM_PAGE_SPINLOCK_LOCK (_COMM_PAGE_BASE_ADDRESS+0x260) // spinlock_lock() -#define _COMM_PAGE_SPINLOCK_UNLOCK (_COMM_PAGE_BASE_ADDRESS+0x2a0) // spinlock_unlock() -#define _COMM_PAGE_PTHREAD_GETSPECIFIC (_COMM_PAGE_BASE_ADDRESS+0x2c0) // pthread_getspecific() -#define _COMM_PAGE_GETTIMEOFDAY (_COMM_PAGE_BASE_ADDRESS+0x2e0) // used by gettimeofday() -#define _COMM_PAGE_FLUSH_DCACHE (_COMM_PAGE_BASE_ADDRESS+0x4e0) // sys_dcache_flush() -#define _COMM_PAGE_FLUSH_ICACHE (_COMM_PAGE_BASE_ADDRESS+0x520) // sys_icache_invalidate() -#define _COMM_PAGE_PTHREAD_SELF (_COMM_PAGE_BASE_ADDRESS+0x580) // pthread_self() - -#define _COMM_PAGE_UNUSED4 (_COMM_PAGE_BASE_ADDRESS+0x5a0) // 32 unused bytes - -#define _COMM_PAGE_RELINQUISH (_COMM_PAGE_BASE_ADDRESS+0x5c0) // used by spinlocks - -#define _COMM_PAGE_UNUSED5 (_COMM_PAGE_BASE_ADDRESS+0x5e0) // 32 unused bytes - -#define _COMM_PAGE_BZERO (_COMM_PAGE_BASE_ADDRESS+0x600) // bzero() -#define _COMM_PAGE_BCOPY (_COMM_PAGE_BASE_ADDRESS+0x780) // bcopy() -#define _COMM_PAGE_MEMCPY (_COMM_PAGE_BASE_ADDRESS+0x7a0) // memcpy() -#define _COMM_PAGE_MEMMOVE (_COMM_PAGE_BASE_ADDRESS+0x7a0) // memmove() - -#define _COMM_PAGE_COMPARE_AND_SWAP32B (_COMM_PAGE_BASE_ADDRESS+0xf80) // compare-and-swap word w barrier -#define _COMM_PAGE_COMPARE_AND_SWAP64B (_COMM_PAGE_BASE_ADDRESS+0xfc0) // compare-and-swap doubleword w barrier - -#define _COMM_PAGE_MEMSET_PATTERN (_COMM_PAGE_BASE_ADDRESS+0x1000)// used by nonzero memset() -#define _COMM_PAGE_BIGCOPY (_COMM_PAGE_BASE_ADDRESS+0x1140)// very-long-operand copies - -#define _COMM_PAGE_END (_COMM_PAGE_BASE_ADDRESS+0x1700)// end of commpage area - -#ifdef __ASSEMBLER__ -#ifdef __COMM_PAGE_SYMBOLS - -#define CREATE_COMM_PAGE_SYMBOL(symbol_name, symbol_address) \ - .org (symbol_address - _COMM_PAGE_BASE_ADDRESS) @\ -symbol_name: nop - - .text // Required to make a well behaved symbol file - - CREATE_COMM_PAGE_SYMBOL(___compare_and_swap32, _COMM_PAGE_COMPARE_AND_SWAP32) - CREATE_COMM_PAGE_SYMBOL(___compare_and_swap64, _COMM_PAGE_COMPARE_AND_SWAP64) - CREATE_COMM_PAGE_SYMBOL(___atomic_enqueue, _COMM_PAGE_ENQUEUE) - CREATE_COMM_PAGE_SYMBOL(___atomic_dequeue, _COMM_PAGE_DEQUEUE) - CREATE_COMM_PAGE_SYMBOL(___memory_barrier, _COMM_PAGE_MEMORY_BARRIER) - CREATE_COMM_PAGE_SYMBOL(___atomic_add32, _COMM_PAGE_ATOMIC_ADD32) - CREATE_COMM_PAGE_SYMBOL(___atomic_add64, _COMM_PAGE_ATOMIC_ADD64) - CREATE_COMM_PAGE_SYMBOL(___mach_absolute_time, _COMM_PAGE_ABSOLUTE_TIME) - CREATE_COMM_PAGE_SYMBOL(___spin_lock_try, _COMM_PAGE_SPINLOCK_TRY) - CREATE_COMM_PAGE_SYMBOL(___spin_lock, _COMM_PAGE_SPINLOCK_LOCK) - CREATE_COMM_PAGE_SYMBOL(___spin_unlock, _COMM_PAGE_SPINLOCK_UNLOCK) - CREATE_COMM_PAGE_SYMBOL(___pthread_getspecific, _COMM_PAGE_PTHREAD_GETSPECIFIC) - CREATE_COMM_PAGE_SYMBOL(___gettimeofday, _COMM_PAGE_GETTIMEOFDAY) - CREATE_COMM_PAGE_SYMBOL(___sys_dcache_flush, _COMM_PAGE_FLUSH_DCACHE) - CREATE_COMM_PAGE_SYMBOL(___sys_icache_invalidate, _COMM_PAGE_FLUSH_ICACHE) - CREATE_COMM_PAGE_SYMBOL(___pthread_self, _COMM_PAGE_PTHREAD_SELF) - CREATE_COMM_PAGE_SYMBOL(___spin_lock_relinquish, _COMM_PAGE_RELINQUISH) - CREATE_COMM_PAGE_SYMBOL(___bzero, _COMM_PAGE_BZERO) - CREATE_COMM_PAGE_SYMBOL(___bcopy, _COMM_PAGE_BCOPY) - CREATE_COMM_PAGE_SYMBOL(___memcpy, _COMM_PAGE_MEMCPY) -// CREATE_COMM_PAGE_SYMBOL(___memmove, _COMM_PAGE_MEMMOVE) - CREATE_COMM_PAGE_SYMBOL(___compare_and_swap32b, _COMM_PAGE_COMPARE_AND_SWAP32B) - CREATE_COMM_PAGE_SYMBOL(___compare_and_swap64b, _COMM_PAGE_COMPARE_AND_SWAP64B) - CREATE_COMM_PAGE_SYMBOL(___memset_pattern, _COMM_PAGE_MEMSET_PATTERN) - CREATE_COMM_PAGE_SYMBOL(___bigcopy, _COMM_PAGE_BIGCOPY) - - CREATE_COMM_PAGE_SYMBOL(___end_comm_page, _COMM_PAGE_END) - - .data // Required to make a well behaved symbol file - .long 0 // Required to make a well behaved symbol file - -#endif /* __COMM_PAGE_SYMBOLS */ -#endif /* __ASSEMBLER__ */ - -#endif /* _PPC_CPU_CAPABILITIES_H */ -#endif /* PRIVATE */ diff --git a/objc/objc-runtime/include/System/pthread_machdep.h b/objc/objc-runtime/include/System/pthread_machdep.h deleted file mode 100755 index 83e4435..0000000 --- a/objc/objc-runtime/include/System/pthread_machdep.h +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright (c) 2003-2004, 2008, 2011 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@ - */ -/* - * Copyright 1996 1995 by Open Software Foundation, Inc. 1997 1996 1995 1994 1993 1992 1991 - * All Rights Reserved - * - * Permission to use, copy, modify, and distribute this software and - * its documentation for any purpose and without fee is hereby granted, - * provided that the above copyright notice appears in all copies and - * that both the copyright notice and this permission notice appear in - * supporting documentation. - * - * OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE - * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE. - * - * IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR - * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT, - * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION - * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ -/* - * MkLinux - */ - -/* Machine-dependent definitions for pthread internals. */ - -#ifndef _POSIX_PTHREAD_MACHDEP_H -#define _POSIX_PTHREAD_MACHDEP_H - -#ifndef __ASSEMBLER__ - -#include <System/machine/cpu_capabilities.h> -#ifdef __arm__ -#include <arm/arch.h> -#endif -#include <TargetConditionals.h> -#include <stdint.h> - -/* - ** Define macros for inline pthread_getspecific() usage. - ** We reserve a number of slots for Apple internal use. - ** This number can grow dynamically, no need to fix it. - */ - -/* This header contains pre defined thread specific keys */ -/* 0 is used for pthread_self */ -//#define _PTHREAD_TSD_SLOT_PTHREAD_SELF 0 -/* Keys 1- 9 for use by dyld, directly or indirectly */ -#define _PTHREAD_TSD_SLOT_DYLD_1 1 -#define _PTHREAD_TSD_SLOT_DYLD_2 2 -#define _PTHREAD_TSD_SLOT_DYLD_3 3 -#define _PTHREAD_TSD_RESERVED_SLOT_COUNT 4 -/* To mirror the usage by dyld for Unwind_SjLj */ -#define _PTHREAD_TSD_SLOT_DYLD_8 8 - -/* Keys 10 - 29 are for Libc/Libsystem internal ussage */ -/* used as __pthread_tsd_first + Num */ -#define __PTK_LIBC_LOCALE_KEY 10 -#define __PTK_LIBC_TTYNAME_KEY 11 -#define __PTK_LIBC_LOCALTIME_KEY 12 -#define __PTK_LIBC_GMTIME_KEY 13 -#define __PTK_LIBC_GDTOA_BIGINT_KEY 14 -#define __PTK_LIBC_PARSEFLOAT_KEY 15 -/* for usage by dyld */ -#define __PTK_LIBC_DYLD_Unwind_SjLj_Key 18 - -/* Keys 20-25 for libdispactch usage */ -#define __PTK_LIBDISPATCH_KEY0 20 -#define __PTK_LIBDISPATCH_KEY1 21 -#define __PTK_LIBDISPATCH_KEY2 22 -#define __PTK_LIBDISPATCH_KEY3 23 -#define __PTK_LIBDISPATCH_KEY4 24 -#define __PTK_LIBDISPATCH_KEY5 25 - -/* Keys 30-255 for Non Libsystem usage */ - -/* Keys 30-39 for Graphic frameworks usage */ -#define _PTHREAD_TSD_SLOT_OPENGL 30 /* backwards compat sake */ -#define __PTK_FRAMEWORK_OPENGL_KEY 30 -#define __PTK_FRAMEWORK_GRAPHICS_KEY1 31 -#define __PTK_FRAMEWORK_GRAPHICS_KEY2 32 -#define __PTK_FRAMEWORK_GRAPHICS_KEY3 33 -#define __PTK_FRAMEWORK_GRAPHICS_KEY4 34 -#define __PTK_FRAMEWORK_GRAPHICS_KEY5 35 -#define __PTK_FRAMEWORK_GRAPHICS_KEY6 36 -#define __PTK_FRAMEWORK_GRAPHICS_KEY7 37 -#define __PTK_FRAMEWORK_GRAPHICS_KEY8 38 -#define __PTK_FRAMEWORK_GRAPHICS_KEY9 39 - -/* Keys 40-49 for Objective-C runtime usage */ -#define __PTK_FRAMEWORK_OBJC_KEY0 40 -#define __PTK_FRAMEWORK_OBJC_KEY1 41 -#define __PTK_FRAMEWORK_OBJC_KEY2 42 -#define __PTK_FRAMEWORK_OBJC_KEY3 43 -#define __PTK_FRAMEWORK_OBJC_KEY4 44 -#define __PTK_FRAMEWORK_OBJC_KEY5 45 -#define __PTK_FRAMEWORK_OBJC_KEY6 46 -#define __PTK_FRAMEWORK_OBJC_KEY7 47 -#define __PTK_FRAMEWORK_OBJC_KEY8 48 -#define __PTK_FRAMEWORK_OBJC_KEY9 49 - -/* Keys 50-59 for Core Foundation usage */ -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY0 50 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY1 51 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY2 52 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY3 53 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY4 54 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY5 55 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY6 56 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY7 57 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY8 58 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY9 59 - -/* Keys 60-69 for Foundation usage */ -#define __PTK_FRAMEWORK_FOUNDATION_KEY0 60 -#define __PTK_FRAMEWORK_FOUNDATION_KEY1 61 -#define __PTK_FRAMEWORK_FOUNDATION_KEY2 62 -#define __PTK_FRAMEWORK_FOUNDATION_KEY3 63 -#define __PTK_FRAMEWORK_FOUNDATION_KEY4 64 -#define __PTK_FRAMEWORK_FOUNDATION_KEY5 65 -#define __PTK_FRAMEWORK_FOUNDATION_KEY6 66 -#define __PTK_FRAMEWORK_FOUNDATION_KEY7 67 -#define __PTK_FRAMEWORK_FOUNDATION_KEY8 68 -#define __PTK_FRAMEWORK_FOUNDATION_KEY9 69 - -/* Keys 70-79 for Core Animation/QuartzCore usage */ -#define __PTK_FRAMEWORK_QUARTZCORE_KEY0 70 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY1 71 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY2 72 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY3 73 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY4 74 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY5 75 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY6 76 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY7 77 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY8 78 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY9 79 - - -/* Keys 80-89 for Garbage Collection */ -#define __PTK_FRAMEWORK_OLDGC_KEY0 80 -#define __PTK_FRAMEWORK_OLDGC_KEY1 81 -#define __PTK_FRAMEWORK_OLDGC_KEY2 82 -#define __PTK_FRAMEWORK_OLDGC_KEY3 83 -#define __PTK_FRAMEWORK_OLDGC_KEY4 84 -#define __PTK_FRAMEWORK_OLDGC_KEY5 85 -#define __PTK_FRAMEWORK_OLDGC_KEY6 86 -#define __PTK_FRAMEWORK_OLDGC_KEY7 87 -#define __PTK_FRAMEWORK_OLDGC_KEY8 88 -#define __PTK_FRAMEWORK_OLDGC_KEY9 89 - -/* Keys 90-94 for JavaScriptCore Collection */ -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY0 90 -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY1 91 -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY2 92 -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY3 93 -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY4 94 -/* Keys 95 for CoreText */ -#define __PTK_FRAMEWORK_CORETEXT_KEY0 95 - -/* Keys 110-119 for Garbage Collection */ -#define __PTK_FRAMEWORK_GC_KEY0 110 -#define __PTK_FRAMEWORK_GC_KEY1 111 -#define __PTK_FRAMEWORK_GC_KEY2 112 -#define __PTK_FRAMEWORK_GC_KEY3 113 -#define __PTK_FRAMEWORK_GC_KEY4 114 -#define __PTK_FRAMEWORK_GC_KEY5 115 -#define __PTK_FRAMEWORK_GC_KEY6 116 -#define __PTK_FRAMEWORK_GC_KEY7 117 -#define __PTK_FRAMEWORK_GC_KEY8 118 -#define __PTK_FRAMEWORK_GC_KEY9 119 - -/* - ** Define macros for inline pthread_getspecific() usage. - ** We reserve a number of slots for Apple internal use. - ** This number can grow dynamically, no need to fix it. - */ - - -#if defined(__cplusplus) -extern "C" { -#endif - - extern void *pthread_getspecific(unsigned long); - extern int pthread_setspecific(unsigned long, const void *); - /* setup destructor function for static key as it is not created with pthread_key_create() */ - int pthread_key_init_np(int, void (*)(void *)); - -#if defined(__cplusplus) -} -#endif - -typedef int pthread_lock_t; - -//__inline__ static int -//_pthread_has_direct_tsd(void) -//{ -//#if TARGET_IPHONE_SIMULATOR -// /* Simulator will use the host implementation, so bypass the macro that is in the target code */ -// return 0; -//#elif defined(__ppc__) -// int *caps = (int *)_COMM_PAGE_CPU_CAPABILITIES; -// if (*caps & kFastThreadLocalStorage) { -// return 1; -// } else { -// return 0; -// } -//#else -// return 1; -//#endif -//} - -#if TARGET_IPHONE_SIMULATOR || defined(__ppc__) || defined(__ppc64__) || \ -(defined(__arm__) && !defined(_ARM_ARCH_7) && defined(_ARM_ARCH_6) && defined(__thumb__)) - -#define _pthread_getspecific_direct(key) pthread_getspecific((key)) -#define _pthread_setspecific_direct(key, val) pthread_setspecific((key), (val)) - -#else - -#include <pthread/tsd_private.h> - -///* To be used with static constant keys only */ -//__inline__ static void * -//_pthread_getspecific_direct(unsigned long slot) -//{ -// void *ret; -//#if defined(__i386__) || defined(__x86_64__) -// __asm__("mov %%gs:%1, %0" : "=r" (ret) : "m" (*(void **)(slot * sizeof(void *)))); -//#elif (defined(__arm__) && (defined(_ARM_ARCH_6) || defined(_ARM_ARCH_5))) -// void **__pthread_tsd; -//#if defined(__arm__) && defined(_ARM_ARCH_6) -// uintptr_t __pthread_tpid; -// __asm__("mrc p15, 0, %0, c13, c0, 3" : "=r" (__pthread_tpid)); -// __pthread_tsd = (void**)(__pthread_tpid & ~0x3ul); -//#elif defined(__arm__) && defined(_ARM_ARCH_5) -// register uintptr_t __pthread_tpid asm ("r9"); -// __pthread_tsd = (void**)__pthread_tpid; -//#endif -// ret = __pthread_tsd[slot]; -//#else -//#error no _pthread_getspecific_direct implementation for this arch -//#endif -// return ret; -//} -// -///* To be used with static constant keys only */ -//__inline__ static int -//_pthread_setspecific_direct(unsigned long slot, void * val) -//{ -//#if defined(__i386__) -//#if defined(__PIC__) -// __asm__("movl %1,%%gs:%0" : "=m" (*(void **)(slot * sizeof(void *))) : "rn" (val)); -//#else -// __asm__("movl %1,%%gs:%0" : "=m" (*(void **)(slot * sizeof(void *))) : "ri" (val)); -//#endif -//#elif defined(__x86_64__) -// /* PIC is free and cannot be disabled, even with: gcc -mdynamic-no-pic ... */ -// __asm__("movq %1,%%gs:%0" : "=m" (*(void **)(slot * sizeof(void *))) : "rn" (val)); -//#elif (defined(__arm__) && (defined(_ARM_ARCH_6) || defined(_ARM_ARCH_5))) -// void **__pthread_tsd; -//#if defined(__arm__) && defined(_ARM_ARCH_6) -// uintptr_t __pthread_tpid; -// __asm__("mrc p15, 0, %0, c13, c0, 3" : "=r" (__pthread_tpid)); -// __pthread_tsd = (void**)(__pthread_tpid & ~0x3ul); -//#elif defined(__arm__) && defined(_ARM_ARCH_5) -// register uintptr_t __pthread_tpid asm ("r9"); -// __pthread_tsd = (void**)__pthread_tpid; -//#endif -// __pthread_tsd[slot] = val; -//#else -//#error no _pthread_setspecific_direct implementation for this arch -//#endif -// return 0; -//} - -#endif - -#define LOCK_INIT(l) ((l) = 0) -#define LOCK_INITIALIZER 0 - -#endif /* ! __ASSEMBLER__ */ -#endif /* _POSIX_PTHREAD_MACHDEP_H */ \ No newline at end of file diff --git a/objc/objc-runtime/include/auto_zone.h b/objc/objc-runtime/include/auto_zone.h deleted file mode 100755 index 54e1d6f..0000000 --- a/objc/objc-runtime/include/auto_zone.h +++ /dev/null @@ -1,694 +0,0 @@ -/* - * Copyright (c) 2011 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@ - */ -/* - auto_zone.h - Automatic Garbage Collection. - Copyright (c) 2002-2011 Apple Inc. All rights reserved. - */ - -#ifndef __AUTO_ZONE__ -#define __AUTO_ZONE__ - -#include <stdint.h> -#include <stdio.h> -#include <sys/types.h> -#include <malloc/malloc.h> -#include <Availability.h> -#include <AvailabilityMacros.h> -#include <TargetConditionals.h> - -#include <dispatch/dispatch.h> - -#define AUTO_EXPORT extern __attribute__((visibility("default"))) - -__BEGIN_DECLS - -typedef malloc_zone_t auto_zone_t; - // an auto zone carries a little more state but can be cast into a malloc_zone_t - -AUTO_EXPORT auto_zone_t *auto_zone_create(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // create an garbage collected zone. Can be (theoretically) done more than once. - // memory can be allocated by malloc_zone_malloc(result, size) - // by default, this memory must be malloc_zone_free(result, ptr) as well (or generic free()) - -AUTO_EXPORT struct malloc_introspection_t auto_zone_introspection() - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // access the zone introspection functions independent of any particular auto zone instance. - // this is used by tools to be able to introspect a zone in another process. - // the introspection functions returned are required to do version checking on the zone. - -#define AUTO_RETAINED_BLOCK_TYPE 0x100 /* zone enumerator returns only blocks with nonzero retain count */ - -/********* External (Global) Use counting ************/ - -AUTO_EXPORT void auto_zone_retain(auto_zone_t *zone, void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); -AUTO_EXPORT unsigned int auto_zone_release(auto_zone_t *zone, void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); -AUTO_EXPORT unsigned int auto_zone_retain_count(auto_zone_t *zone, const void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // All pointer in the auto zone have an explicit retain count - // Objects will not be collected when the retain count is non-zero - -/********* Object information ************/ - -AUTO_EXPORT const void *auto_zone_base_pointer(auto_zone_t *zone, const void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // return base of interior pointer (or NULL). -AUTO_EXPORT boolean_t auto_zone_is_valid_pointer(auto_zone_t *zone, const void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // is this a pointer to the base of an allocated block? -AUTO_EXPORT size_t auto_zone_size(auto_zone_t *zone, const void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - -/********* Write-barrier ************/ - -AUTO_EXPORT boolean_t auto_zone_set_write_barrier(auto_zone_t *zone, const void *dest, const void *new_value) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // must be used when an object field/slot in the auto zone is set to another object in the auto zone - // returns true if the dest was a valid target whose write-barrier was set - -AUTO_EXPORT boolean_t auto_zone_atomicCompareAndSwap(auto_zone_t *zone, void *existingValue, void *newValue, void *volatile *location, boolean_t isGlobal, boolean_t issueBarrier) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // Atomically update a location with a new GC value. These use OSAtomicCompareAndSwapPtr{Barrier} with appropriate write-barrier interlocking logic. - -AUTO_EXPORT boolean_t auto_zone_atomicCompareAndSwapPtr(auto_zone_t *zone, void *existingValue, void *newValue, void *volatile *location, boolean_t issueBarrier) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); - // Atomically update a location with a new GC value. These use OSAtomicCompareAndSwapPtr{Barrier} with appropriate write-barrier interlocking logic. - // This version checks location, and if it points into global storage, registers a root. - -AUTO_EXPORT void *auto_zone_write_barrier_memmove(auto_zone_t *zone, void *dst, const void *src, size_t size) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // copy content from an arbitrary source area to an arbitrary destination area - // marking write barrier if necessary - -/********* Read-barrier ************/ - -AUTO_EXPORT void *auto_zone_strong_read_barrier(auto_zone_t *zone, void **source) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -/********* Statistics ************/ - -typedef uint64_t auto_date_t; - -typedef struct { - auto_date_t total_duration; - auto_date_t scan_duration; - auto_date_t enlivening_duration; - auto_date_t finalize_duration; - auto_date_t reclaim_duration; -} auto_collection_durations_t; - -typedef struct { - /* Memory usage */ - malloc_statistics_t malloc_statistics; - /* GC stats */ - // version 0 - uint32_t version; // set to 1 before calling - /* When there is an array, 0 stands for full collection, 1 for generational */ - size_t num_collections[2]; - boolean_t last_collection_was_generational; - size_t bytes_in_use_after_last_collection[2]; - size_t bytes_allocated_after_last_collection[2]; - size_t bytes_freed_during_last_collection[2]; - // durations - auto_collection_durations_t total[2]; // running total of each field - auto_collection_durations_t last[2]; // most recent result - auto_collection_durations_t maximum[2]; // on a per item basis, the max. Thus, total != scan + finalize ... - // version 1 additions - size_t thread_collections_total; - size_t thread_blocks_recovered_total; - size_t thread_bytes_recovered_total; -} auto_statistics_t; - -AUTO_EXPORT void auto_zone_statistics(auto_zone_t *zone, auto_statistics_t *stats) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_7, __IPHONE_5_0,__IPHONE_5_0); - // set version to 0 - -/********* Garbage Collection ************/ - -enum { - AUTO_COLLECT_RATIO_COLLECTION = (0 << 0), // run generational or full depending on applying AUTO_COLLECTION_RATIO - AUTO_COLLECT_GENERATIONAL_COLLECTION = (1 << 0), // collect young objects. Internal only. - AUTO_COLLECT_FULL_COLLECTION = (2 << 0), // collect entire heap. Internal only. - AUTO_COLLECT_EXHAUSTIVE_COLLECTION = (3 << 0), // run full collections until object count stabilizes. - AUTO_COLLECT_SYNCHRONOUS = (1 << 2), // block caller until scanning is finished. - AUTO_COLLECT_IF_NEEDED = (1 << 3), // only collect if AUTO_COLLECTION_THRESHOLD exceeded. -}; -typedef uint32_t auto_collection_mode_t; - -enum { - AUTO_LOG_COLLECTIONS = (1 << 1), // log block statistics whenever a collection occurs - AUTO_LOG_TIMINGS = (1 << 2), // log timing data whenever a collection occurs - AUTO_LOG_REGIONS = (1 << 4), // log whenever a new region is allocated - AUTO_LOG_UNUSUAL = (1 << 5), // log unusual circumstances - AUTO_LOG_WEAK = (1 << 6), // log weak reference manipulation - AUTO_LOG_ALL = (~0u), - AUTO_LOG_NONE = 0 -}; -typedef uint32_t auto_log_mask_t; - -enum { - AUTO_HEAP_HOLES_SHRINKING = 1, // total size of holes is approaching zero - AUTO_HEAP_HOLES_EXHAUSTED = 2, // all holes exhausted, will use hitherto unused memory in "subzone" - AUTO_HEAP_SUBZONE_EXHAUSTED = 3, // will add subzone - AUTO_HEAP_REGION_EXHAUSTED = 4, // no more subzones available, need to add region - AUTO_HEAP_ARENA_EXHAUSTED = 5, // arena exhausted. (64-bit only) -}; -typedef uint32_t auto_heap_growth_info_t; - -typedef struct auto_zone_cursor *auto_zone_cursor_t; -typedef void (*auto_zone_foreach_object_t) (auto_zone_cursor_t cursor, void (*op) (void *ptr, void *data), void* data); - -typedef struct { - uint32_t version; // sizeof(auto_collection_control_t) - void (*batch_invalidate) (auto_zone_t *zone, auto_zone_foreach_object_t foreach, auto_zone_cursor_t cursor, size_t cursor_size); - // After unreached objects are found, collector calls this routine with internal context. - // Typically, one enters a try block to call back into the collector with a function pointer to be used to - // invalidate each object. This amortizes the cost of the try block as well as allows the collector to use - // efficient contexts. - void (*resurrect) (auto_zone_t *zone, void *ptr); - // Objects on the garbage list may be assigned into live objects in an attempted resurrection. This is not allowed. - // This function, if supplied, is called for these objects to turn them into zombies. The zombies may well hold - // pointers to other objects on the garbage list. No attempt is made to preserved these objects beyond this collection. - const unsigned char* (*layout_for_address)(auto_zone_t *zone, void *ptr); - // The collector assumes that the first word of every "object" is a class pointer. - // For each class pointer discovered this function is called to return a layout, or NULL - // if the object should be scanned conservatively. - // The layout format is nibble pairs {skipcount, scancount} XXX - const unsigned char* (*weak_layout_for_address)(auto_zone_t *zone, void *ptr); - // called once for each allocation encountered for which we don't know the weak layout - // the callee returns a weak layout for the allocation or NULL if the allocation has no weak references. - char* (*name_for_address) (auto_zone_t *zone, vm_address_t base, vm_address_t offset); - // if supplied, is used during logging for errors such as resurrections - auto_log_mask_t log; - // set to auto_log_mask_t bits as desired - boolean_t disable_generational; - // if true, ignores requests to do generational GC. - boolean_t malloc_stack_logging; - // if true, logs allocations for malloc stack logging. Automatically set if MallocStackLogging{NoCompact} is set - void (*scan_external_callout)(void *context, void (*scanner)(void *context, void *start, void *end)) DEPRECATED_ATTRIBUTE; - // no longer used - - void (*will_grow)(auto_zone_t *zone, auto_heap_growth_info_t) DEPRECATED_ATTRIBUTE; - // no longer used - - size_t collection_threshold; - // if_needed threshold: collector will initiate a collection after this number of bytes is allocated. - size_t full_vs_gen_frequency; - // after full_vs_gen_frequency generational collections, a full collection will occur, if the if_needed threshold exceeded - const char* (*name_for_object) (auto_zone_t *zone, void *object); - // provides a type name for an AUTO_OBJECT -} auto_collection_control_t; - -AUTO_EXPORT auto_collection_control_t *auto_collection_parameters(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // FIXME: API is to get the control struct and slam it - // sets a parameter that decides when callback gets called - -AUTO_EXPORT void auto_collector_disable(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); -AUTO_EXPORT void auto_collector_reenable(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - // these two functions turn off/on the collector - // default is on - // use with great care. - -AUTO_EXPORT boolean_t auto_zone_is_enabled(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); -AUTO_EXPORT boolean_t auto_zone_is_collecting(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - -AUTO_EXPORT void auto_collect(auto_zone_t *zone, auto_collection_mode_t mode, void *collection_context) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_7, __IPHONE_5_0,__IPHONE_5_0); - // deprecated, use auto_zone_collect() instead - -AUTO_EXPORT void auto_collect_multithreaded(auto_zone_t *zone) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_7, __IPHONE_5_0,__IPHONE_5_0); - // deprecated - - -// Options to auto_zone_collect(). -enum { - /* - Request a collection with no options. This produces an advisory collection request which - allows the collector to choose what collection is performed (or none) based on its internal - heuristics. This is generally the only option that should be used in production code. - All other options are intended primarily to support debugging and unit tests and may change - meaning without notice. - */ - AUTO_ZONE_COLLECT_NO_OPTIONS = 0, - - // The low order nibble specifies a request for a global heap collection. - // Note that the ordinal value is significant. Higher numbered collection modes can override lower numbered. - AUTO_ZONE_COLLECT_RATIO_COLLECTION = 1, // requests either a generational or a full collection, based on memory use heuristics. - AUTO_ZONE_COLLECT_GENERATIONAL_COLLECTION = 2, // requests a generational heap collection. - AUTO_ZONE_COLLECT_FULL_COLLECTION = 3, // requests a full heap collection. - AUTO_ZONE_COLLECT_EXHAUSTIVE_COLLECTION = 4, // requests an exhaustive heap collection. - - AUTO_ZONE_COLLECT_GLOBAL_MODE_MAX = AUTO_ZONE_COLLECT_EXHAUSTIVE_COLLECTION, // the highest numbered global mode - AUTO_ZONE_COLLECT_GLOBAL_MODE_COUNT = AUTO_ZONE_COLLECT_EXHAUSTIVE_COLLECTION+1, // the highest numbered global mode - AUTO_ZONE_COLLECT_GLOBAL_COLLECTION_MODE_MASK = 0xf, - - - // These bits requests a local collections be performed on the calling thread. It is permitted to request both a local collection and a global collection, in which case both will be performed. - - AUTO_ZONE_COLLECT_LOCAL_COLLECTION = (1<<8), // perform a normal thread local collection - - AUTO_ZONE_COLLECT_COALESCE = (1<<15), // allows the request to be skipped if a collection is in progress -}; - -/* - auto_zone_collect() is the entry point to request a collection. - - Normally AUTO_ZONE_COLLECT_NO_OPTIONS should be passed for options. This indicates the call is an advisory - collection request and the collector is free to perform any action it deems fit (including none). This is - the only option that should be used in shipping production code. The other options provide fine grained control of - the collector intended for debugging and unit tests. Misuse of these options can degrade performance. - */ -typedef intptr_t auto_zone_options_t; -AUTO_EXPORT void auto_zone_collect(auto_zone_t *zone, auto_zone_options_t options) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#ifdef __BLOCKS__ -AUTO_EXPORT void auto_zone_collect_and_notify(auto_zone_t *zone, auto_zone_options_t options, dispatch_queue_t callback_queue, dispatch_block_t completion_callback) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#endif - -/* - auto_zone_compact() is the entry point to request a stop-the-world compaction of the heap. This can only be called from binaries - which are marked by the linker (see <rdar://problem/7421695>) as supporting compaction. Currently there are no options to control - compaction, but you can pass a queue/block callback pair that will be invoked after compaction finishes. - */ - -enum { - AUTO_ZONE_COMPACT_NO_OPTIONS = 0, - AUTO_ZONE_COMPACT_IF_IDLE = 1, /* primes compaction to start after delay, if no dispatch threads intervene. */ - AUTO_ZONE_COMPACT_ANALYZE = 2, /* runs a compaction analysis to file specified by environment variable. */ -}; - -typedef uintptr_t auto_zone_compact_options_t; - -#ifdef __BLOCKS__ -AUTO_EXPORT void auto_zone_compact(auto_zone_t *zone, auto_zone_compact_options_t options, dispatch_queue_t callback_queue, dispatch_block_t completion_callback) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#endif - -/* - Compaction is enabled by default. The client runtime should call auto_zone_disable_compaction() when it detects that code that - is incompatible with compaction has been loaded. This is safe to call immediately after auto_zone_create(). - */ -AUTO_EXPORT void auto_zone_disable_compaction(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -/* - External resource tracking. - - The garbage collector tracks use of collectable memory. But it may be necessary to trigger garbage collections - based on use of other resources not tracked by the garbage collector, such as file descriptors. The garbage - collector provides this interface to register other resources tracking systems so the collector can query - if collection is needed. The garbage collector will periodically call all registered should_collect() blocks - and if any of them return true a collection cycle will execute. (However, the collector stops querying - external resource trackers once it has determined that a collection is necessary. In many cases the collector - will collect due to memory use without querying any external resource trackers at all.) - - Resource tracking implementations should take care to avoid running collections continuously based on high - resource use when no resources are recovered. One strategy is to track resources allocated since the last - triggered collection instead of a total allocation count. - */ - -/* - Register should_collect() as an external resource tracker. The string passed in description is used - as a descriptive name for the resource tracker. When an external resource tracker triggers a collection the - description string appears in the log if AUTO_LOG_COLLECTIONS is enabled. The description string is copied. - */ -#ifdef __BLOCKS__ -AUTO_EXPORT void auto_zone_register_resource_tracker(auto_zone_t *zone, const char *description, boolean_t (^should_collect)(void)) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#endif - -/* - Unregister a should_collect() block that was previously registered with auto_zone_register_resource_tracker(). - The garbage collector will no longer query the resource tracker. - */ -AUTO_EXPORT void auto_zone_unregister_resource_tracker(auto_zone_t *zone, const char *description) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -/* - auto_zone_reap_all_local_blocks() will immediately finalize and reclaim all blocks which are thread local to the calling thread. - No scanning or other liveness analysis will be performed. This function can be called as an optimization in the very specific - case where it is known that the stack cannot be rooting any blocks, such as a pthread event loop. (Note that this cannot be called - from a thread created by NSThread.) - */ -AUTO_EXPORT void auto_zone_reap_all_local_blocks(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Block Memory Type Flags -// ======================= -// Blocks of memory allocated by auto_zone_allocate_object() are broadly classified as scanned/unscanned -// and object/non-object. When objects become garbage, they are finalized by calling the batch_invalidate() callback. -// For scanned objects, the collector uses the layout_for_address callback, to obtain a layout map that describes which -// pointer sized words should be scanned, and which should be ignored. Scanned objects may also contain weak references -// which are created via auto_assign_weak_reference(). The weak_layout_for_address callback is used to automatically -// unregister non-NULL weak references in weak_unregister_with_layout(). Finally, the pointers_only bit applies only for -// scanned memory and indicates that all otherwise unspecified fields are pointers, the most interesting consequence is that -// they can be relocated during compaction. -// -// These flags are represented by auto_memory_type_t. see the comments below for the legal flag combinations. Once allocated, -// SPI is provided to change the bits in only proscribed ways; to turn off "object" treatment; to turn off scanning; -// to turn on all-pointers. - -enum { - AUTO_TYPE_UNKNOWN = -1, // this is an error value - // memory type bits. - AUTO_UNSCANNED = (1 << 0), - AUTO_OBJECT = (1 << 1), - AUTO_POINTERS_ONLY = (1 << 2), - // allowed combinations of flags. - AUTO_MEMORY_SCANNED = !AUTO_UNSCANNED, // conservatively scanned memory - AUTO_MEMORY_UNSCANNED = AUTO_UNSCANNED, // unscanned memory (bits) - AUTO_MEMORY_ALL_POINTERS = AUTO_POINTERS_ONLY, // scanned array of pointers - AUTO_MEMORY_ALL_WEAK_POINTERS = (AUTO_UNSCANNED | AUTO_POINTERS_ONLY), // unscanned, weak array of pointers - AUTO_OBJECT_SCANNED = AUTO_OBJECT, // object memory, exactly scanned with layout maps, conservatively scanned remainder, will be finalized - AUTO_OBJECT_UNSCANNED = AUTO_OBJECT | AUTO_UNSCANNED, // unscanned object memory, will be finalized - AUTO_OBJECT_ALL_POINTERS = AUTO_OBJECT | AUTO_POINTERS_ONLY // object memory, exactly scanned with layout maps, all-pointers scanned remainder, will be finalized -}; -typedef int32_t auto_memory_type_t; - -AUTO_EXPORT auto_memory_type_t auto_zone_get_layout_type(auto_zone_t *zone, void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - -AUTO_EXPORT void* auto_zone_allocate_object(auto_zone_t *zone, size_t size, auto_memory_type_t type, boolean_t initial_refcount_to_one, boolean_t clear) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - -/* Batch allocator. Returns number of blocks allocated, which may be 0. */ -/* All blocks have the given memory type and initial reference count, and all blocks are zeroed. */ -AUTO_EXPORT unsigned auto_zone_batch_allocate(auto_zone_t *zone, size_t size, auto_memory_type_t type, boolean_t initial_refcount_to_one, boolean_t clear, void **results, unsigned num_requested) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Create copy of AUTO_MEMORY object preserving "scanned" attribute -// If not auto memory then create unscanned memory copy -AUTO_EXPORT void *auto_zone_create_copy(auto_zone_t *zone, void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - - -AUTO_EXPORT void auto_zone_register_thread(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - -AUTO_EXPORT void auto_zone_unregister_thread(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - -AUTO_EXPORT void auto_zone_assert_thread_registered(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); - -AUTO_EXPORT void auto_zone_register_datasegment(auto_zone_t *zone, void *address, size_t size) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); -AUTO_EXPORT void auto_zone_unregister_datasegment(auto_zone_t *zone, void *address, size_t size) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); - - -// Weak references - -// The collector maintains a weak reference system. -// Essentially, locations in which references are stored are registered along with the reference itself. -// The location should not be within scanned GC memory. -// After a collection, before finalization, all registered locations are examined and any containing references to -// newly discovered garbage will be "zeroed" and the registration cancelled. -// -// Reading values from locations must be done through the weak read function because there is a race with such -// reads and the collector having just determined that that value read is in fact otherwise garbage. -// -// The address of a callback block may be supplied optionally. If supplied, if the location is zeroed, the callback -// block is queued to be called later with the arguments supplied in the callback block. The same callback block both -// can and should be used as an aggregation point. A table of weak locations could supply each registration with the -// same pointer to a callback block that will call that table if items are zerod. The callbacks are made before -// finalization. Note that only thread-safe operations may be performed by this callback. -// -// It is important to cancel all registrations before deallocating the memory containing locations or callback blocks. -// Cancellation is done by calling the registration function with a NULL "reference" parameter for that location. - -#if defined(AUTO_USE_NEW_WEAK_CALLBACK) -typedef struct new_auto_weak_callback_block auto_weak_callback_block_t; -#else -typedef struct old_auto_weak_callback_block auto_weak_callback_block_t; -#endif - -struct new_auto_weak_callback_block { - void *isa; // provides layout for exact scanning. - auto_weak_callback_block_t *next; // must be set to zero before first use. - void (*callback_function)(void *__strong target); - void *__strong target; -}; - -struct old_auto_weak_callback_block { - auto_weak_callback_block_t *next; // must be set to zero before first use. - void (*callback_function)(void *arg1, void *arg2); - void *arg1; - void *arg2; -} DEPRECATED_ATTRIBUTE; - -AUTO_EXPORT void auto_assign_weak_reference(auto_zone_t *zone, const void *value, const void **location, auto_weak_callback_block_t *block) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - -// Read a weak-reference, informing the collector that it is now strongly referenced. -AUTO_EXPORT void* auto_read_weak_reference(auto_zone_t *zone, void **referrer) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - -// Compaction notification - -// Registers an observer that gets called whenever pointers are updated (by compaction) inside a block. -// This could be used to trigger rehashing a hash table. The implementation isn't particularly efficient. -#ifdef __BLOCKS__ -AUTO_EXPORT void auto_zone_set_compaction_observer(auto_zone_t *zone, void *block, void (^observer) (void)) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#endif - -// Global references - -AUTO_EXPORT void auto_zone_add_root(auto_zone_t *zone, void *address_of_root_ptr, void *value) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); -AUTO_EXPORT void auto_zone_remove_root(auto_zone_t *zone, void *address_of_root_ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - -AUTO_EXPORT void auto_zone_root_write_barrier(auto_zone_t *zone, void *address_of_possible_root_ptr, void *value) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - - -// Associative references. - -// This informs the collector that an object A wishes to associate one or more secondary objects with object A's lifetime. -// This can be used to implement GC-safe associations that will neither cause uncollectable cycles, nor suffer the limitations -// of weak references. - -AUTO_EXPORT void auto_zone_set_associative_ref(auto_zone_t *zone, void *object, void *key, void *value) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); -AUTO_EXPORT void *auto_zone_get_associative_ref(auto_zone_t *zone, void *object, void *key) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); -AUTO_EXPORT void auto_zone_erase_associative_refs(auto_zone_t *zone, void *object) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); - -AUTO_EXPORT size_t auto_zone_get_associative_hash(auto_zone_t *zone, void *object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Enumerates all known object, value pairs associated with the key parameter. Calls the specified block while the -// assocations table locks are held, therefore adding/removing assocations will likely crash. -#ifdef __BLOCKS__ -AUTO_EXPORT void auto_zone_enumerate_associative_refs(auto_zone_t *zone, void *key, boolean_t (^block) (void *object, void *value)) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#endif - -// Collection Checking - -// Collection checking is a debugging tool by which developers can verify that blocks are collecting as expected. -// When collection checking is enabled the program can report memory blocks to the collector -// that are expected to collect soon using auto_zone_track_pointer(). -// The program can detect which of these blocks were not collected by calling auto_zone_enumerate_uncollected(). -// Pointers that survive more than a few collections can be investigated as leaks. -// While collection checking is enabled collector performance is degraded and memory use is increased. -// While most garbage objects are detected and collected in just one collection attempt, there are -// cases where several collections are required to reclaim a memory block even though it has no references. -// Note also that a conservative stack reference is never cleared by running more collections. - -// Enable/disable collection checking. An "enabled" counter is maintained, so calls should be paried if desired. -// Disabling collection checking and causes all previously tracked blocks to be unregistered (no longer tracked). -AUTO_EXPORT boolean_t auto_zone_enable_collection_checking(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -AUTO_EXPORT void auto_zone_disable_collection_checking(auto_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Inform the collector that the pointer is expected to collect soon. pointer will subsequently be reported by -// auto_zone_enumerate_uncollected() until it is collected. -// Note that pointer is still rooted on the stack in the scope where auto_zone_block_should_collect() is called. -AUTO_EXPORT void auto_zone_track_pointer(auto_zone_t *zone, void *pointer) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -#ifdef __BLOCKS__ -typedef struct { - boolean_t is_object; - size_t survived_count; -} auto_zone_collection_checking_info; - -// Typedef for a handler block used to report uncollected memory. The collector provides: -// pointer - the memory block in question, which was previously passed to auto_zone_track_pointer() -// info - a pointer to a auto_zone_collection_checking_info struct containing: -// is_object - true if the block was allocated as an object, false if it is not an object -// survived_count - a minimum count of collections the block has survived (the actual count may be higher) -typedef void (^auto_zone_collection_checking_callback_t)(void *pointer, auto_zone_collection_checking_info *info); - -// Enumerate the memory blocks that were previously passed to auto_zone_track_pointer(). -// Any which have not been collected are reported using the callback. -// The callback may be NULL, in which case the uncollected blocks are simply logged. -AUTO_EXPORT void auto_zone_enumerate_uncollected(auto_zone_t *zone, auto_zone_collection_checking_callback_t callback) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#endif - - - -/***** SPI ******/ - -AUTO_EXPORT boolean_t auto_zone_is_finalized(auto_zone_t *zone, const void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); -AUTO_EXPORT void auto_zone_set_nofinalize(auto_zone_t *zone, void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); -AUTO_EXPORT void auto_zone_set_unscanned(auto_zone_t *zone, void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); -AUTO_EXPORT void auto_zone_set_scan_exactly(auto_zone_t *zone, void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -AUTO_EXPORT void auto_zone_clear_stack(auto_zone_t *zone, unsigned long options) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); - -// Reference count logging support for ObjectAlloc et. al. - -enum { - AUTO_RETAIN_EVENT = 14, - AUTO_RELEASE_EVENT = 15 -}; -AUTO_EXPORT void (*__auto_reference_logger)(uint32_t eventtype, void *ptr, uintptr_t data) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); - - -// Reference tracing - -// referrer_base[referrer_offset] -> referent -typedef struct -{ - vm_address_t referent; - vm_address_t referrer_base; - intptr_t referrer_offset; -} auto_reference_t; - -typedef void (*auto_reference_recorder_t)(auto_zone_t *zone, void *ctx, - auto_reference_t reference); - -AUTO_EXPORT void auto_enumerate_references(auto_zone_t *zone, void *referent, - auto_reference_recorder_t callback, - void *stack_bottom, void *ctx) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - - -AUTO_EXPORT void **auto_weak_find_first_referrer(auto_zone_t *zone, void **location, unsigned long count) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_5_0); - - -/************ DEPRECATED ***********/ - -AUTO_EXPORT auto_zone_t *auto_zone(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_7, __IPHONE_5_0,__IPHONE_5_0); - // returns a pointer to the first garbage collected zone created. - - -/************ DELETED ***********/ - -AUTO_EXPORT void auto_zone_stats(void) - UNAVAILABLE_ATTRIBUTE; -AUTO_EXPORT void auto_zone_start_monitor(boolean_t force) - UNAVAILABLE_ATTRIBUTE; -AUTO_EXPORT void auto_zone_set_class_list(int (*get_class_list)(void **buffer, int count)) - UNAVAILABLE_ATTRIBUTE; -AUTO_EXPORT void auto_zone_write_stats(FILE *f) - UNAVAILABLE_ATTRIBUTE; -AUTO_EXPORT char *auto_zone_stats_string() - UNAVAILABLE_ATTRIBUTE; -AUTO_EXPORT double auto_zone_utilization(auto_zone_t *zone) - UNAVAILABLE_ATTRIBUTE; -AUTO_EXPORT unsigned auto_zone_touched_size(auto_zone_t *zone) - UNAVAILABLE_ATTRIBUTE; - - -/************* EXPERIMENTAL *********/ -#ifdef __BLOCKS__ - -typedef void (^auto_zone_stack_dump)(const void *base, unsigned long byte_size); -typedef void (^auto_zone_register_dump)(const void *base, unsigned long byte_size); -typedef void (^auto_zone_node_dump)(const void *address, unsigned long size, unsigned int layout, unsigned long refcount); -typedef void (^auto_zone_root_dump)(const void **address); -typedef void (^auto_zone_weak_dump)(const void **address, const void *item); - -// Instruments.app utility; causes significant disruption. -// This is SPI for Apple's use only. Can and likely will change without regard to 3rd party use. -AUTO_EXPORT void auto_zone_dump(auto_zone_t *zone, - auto_zone_stack_dump stack_dump, - auto_zone_register_dump register_dump, - auto_zone_node_dump thread_local_node_dump, // unsupported - auto_zone_root_dump root_dump, - auto_zone_node_dump global_node_dump, - auto_zone_weak_dump weak_dump) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_7, __IPHONE_5_0,__IPHONE_5_0); - -// auto_zone_dump() is now deprecated, use auto_zone_visit() instead. - -typedef struct { - void *begin; - void *end; -} auto_address_range_t; - -typedef struct { - uint32_t version; // sizeof(auto_zone_visitor_t) - void (^visit_thread)(pthread_t thread, auto_address_range_t stack_range, auto_address_range_t registers); - void (^visit_node)(const void *address, size_t size, auto_memory_type_t type, uint32_t refcount, boolean_t is_thread_local); - void (^visit_root)(const void **address); - void (^visit_weak)(const void *value, void *const*location, auto_weak_callback_block_t *callback); - void (^visit_association)(const void *object, const void *key, const void *value); -} auto_zone_visitor_t; - -AUTO_EXPORT void auto_zone_visit(auto_zone_t *zone, auto_zone_visitor_t *visitor) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -enum { - auto_is_not_auto = 0, - auto_is_auto = (1 << 1), // always on for a start of a node - auto_is_local = (1 << 2), // is/was node local -}; - -typedef int auto_probe_results_t; - -// Instruments.app utility; causes significant disruption. -// This is SPI for Apple's use only. Can and likely will change without regard to 3rd party use. -AUTO_EXPORT auto_probe_results_t auto_zone_probe_unlocked(auto_zone_t *zone, void *address) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); -AUTO_EXPORT void auto_zone_scan_exact(auto_zone_t *zone, void *address, void (^callback)(void *base, unsigned long byte_offset, void *candidate)) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0); - -#endif - -__END_DECLS - -#endif /* __AUTO_ZONE__ */ diff --git a/objc/objc-runtime/include/dispatch/benchmark.h b/objc/objc-runtime/include/dispatch/benchmark.h deleted file mode 100755 index df42a8a..0000000 --- a/objc/objc-runtime/include/dispatch/benchmark.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2008-2009 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@ - */ - -/* - * IMPORTANT: This header file describes INTERNAL interfaces to libdispatch - * which are subject to change in future releases of Mac OS X. Any applications - * relying on these interfaces WILL break. - */ - -#ifndef __DISPATCH_BENCHMARK__ -#define __DISPATCH_BENCHMARK__ - -#ifndef __DISPATCH_INDIRECT__ -#error "Please #include <dispatch/dispatch.h> instead of this file directly." -#include <dispatch/base.h> // for HeaderDoc -#endif - -__BEGIN_DECLS - -/*! - * @function dispatch_benchmark - * - * @abstract - * Count the average number of cycles a given block takes to execute. - * - * @param count - * The number of times to serially execute the given block. - * - * @param block - * The block to execute. - * - * @result - * The approximate number of cycles the block takes to execute. - * - * @discussion - * This function is for debugging and performance analysis work. For the best - * results, pass a high count value to dispatch_benchmark(). When benchmarking - * concurrent code, please compare the serial version of the code against the - * concurrent version, and compare the concurrent version on different classes - * of hardware. Please look for inflection points with various data sets and - * keep the following facts in mind: - * - * 1) Code bound by computational bandwidth may be inferred by proportional - * changes in performance as concurrency is increased. - * 2) Code bound by memory bandwidth may be inferred by negligible changes in - * performance as concurrency is increased. - * 3) Code bound by critical sections may be inferred by retrograde changes in - * performance as concurrency is increased. - * 3a) Intentional: locks, mutexes, and condition variables. - * 3b) Accidental: unrelated and frequently modified data on the same - * cache-line. - */ -#ifdef __BLOCKS__ -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT DISPATCH_NONNULL2 DISPATCH_NOTHROW -uint64_t -dispatch_benchmark(size_t count, void (^block)(void)); -#endif - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT DISPATCH_NONNULL3 DISPATCH_NOTHROW -uint64_t -dispatch_benchmark_f(size_t count, void *ctxt, void (*func)(void *)); - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/include/dispatch/private.h b/objc/objc-runtime/include/dispatch/private.h deleted file mode 100755 index 9bb0e01..0000000 --- a/objc/objc-runtime/include/dispatch/private.h +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2008-2011 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@ - */ - -/* - * IMPORTANT: This header file describes INTERNAL interfaces to libdispatch - * which are subject to change in future releases of Mac OS X. Any applications - * relying on these interfaces WILL break. - */ - -#ifndef __DISPATCH_PRIVATE__ -#define __DISPATCH_PRIVATE__ - -#ifdef __APPLE__ -#include <TargetConditionals.h> -#endif - -#if TARGET_OS_MAC -#include <mach/boolean.h> -#include <mach/mach.h> -#include <mach/message.h> -#endif -#if HAVE_UNISTD_H -#include <unistd.h> -#endif -#if HAVE_SYS_CDEFS_H -#include <sys/cdefs.h> -#endif -#include <pthread.h> - -#define DISPATCH_NO_LEGACY 1 -#ifdef DISPATCH_LEGACY // <rdar://problem/7366725> -#error "Dispatch legacy API unavailable." -#endif - -#ifndef __DISPATCH_BUILDING_DISPATCH__ -#include_next <dispatch/dispatch.h> - -// Workaround <rdar://problem/6597365/> -#ifndef __DISPATCH_PUBLIC__ -#include "/usr/include/dispatch/dispatch.h" -#endif - -#ifndef __DISPATCH_INDIRECT__ -#define __DISPATCH_INDIRECT__ -#endif - -#include <dispatch/benchmark.h> -#include <dispatch/queue_private.h> -#include <dispatch/source_private.h> - -#undef __DISPATCH_INDIRECT__ - -#endif /* !__DISPATCH_BUILDING_DISPATCH__ */ - -/* LEGACY: Use DISPATCH_API_VERSION */ -#define LIBDISPATCH_VERSION DISPATCH_API_VERSION - -__BEGIN_DECLS - -DISPATCH_EXPORT DISPATCH_NOTHROW -void -libdispatch_init(void); - -#if TARGET_OS_MAC -#define DISPATCH_COCOA_COMPAT 1 -#if DISPATCH_COCOA_COMPAT - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT DISPATCH_CONST DISPATCH_WARN_RESULT DISPATCH_NOTHROW -mach_port_t -_dispatch_get_main_queue_port_4CF(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT DISPATCH_NOTHROW -void -_dispatch_main_queue_callback_4CF(mach_msg_header_t *msg); - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT -void (*dispatch_begin_thread_4GC)(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT -void (*dispatch_end_thread_4GC)(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_3) -DISPATCH_EXPORT -void (*dispatch_no_worker_threads_4GC)(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT -void *(*_dispatch_begin_NSAutoReleasePool)(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT -void (*_dispatch_end_NSAutoReleasePool)(void *); - -#define _dispatch_time_after_nsec(t) \ - dispatch_time(DISPATCH_TIME_NOW, (t)) -#define _dispatch_time_after_usec(t) \ - dispatch_time(DISPATCH_TIME_NOW, (t) * NSEC_PER_USEC) -#define _dispatch_time_after_msec(t) \ - dispatch_time(DISPATCH_TIME_NOW, (t) * NSEC_PER_MSEC) -#define _dispatch_time_after_sec(t) \ - dispatch_time(DISPATCH_TIME_NOW, (t) * NSEC_PER_SEC) - -#endif -#endif /* TARGET_OS_MAC */ - -/* pthreads magic */ - -DISPATCH_EXPORT DISPATCH_NOTHROW void dispatch_atfork_prepare(void); -DISPATCH_EXPORT DISPATCH_NOTHROW void dispatch_atfork_parent(void); -DISPATCH_EXPORT DISPATCH_NOTHROW void dispatch_atfork_child(void); - -#if TARGET_OS_MAC -/* - * Extract the context pointer from a mach message trailer. - */ -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT DISPATCH_PURE DISPATCH_WARN_RESULT DISPATCH_NONNULL_ALL -DISPATCH_NOTHROW -void * -dispatch_mach_msg_get_context(mach_msg_header_t *msg); -#endif /* TARGET_OS_MAC */ - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/include/dispatch/queue_private.h b/objc/objc-runtime/include/dispatch/queue_private.h deleted file mode 100755 index 5ec36d0..0000000 --- a/objc/objc-runtime/include/dispatch/queue_private.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2008-2010 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@ - */ - -/* - * IMPORTANT: This header file describes INTERNAL interfaces to libdispatch - * which are subject to change in future releases of Mac OS X. Any applications - * relying on these interfaces WILL break. - */ - -#ifndef __DISPATCH_QUEUE_PRIVATE__ -#define __DISPATCH_QUEUE_PRIVATE__ - -#ifndef __DISPATCH_INDIRECT__ -#error "Please #include <dispatch/dispatch.h> instead of this file directly." -#include <dispatch/base.h> // for HeaderDoc -#endif - -__BEGIN_DECLS - - -/*! - * @enum dispatch_queue_flags_t - * - * @constant DISPATCH_QUEUE_OVERCOMMIT - * The queue will create a new thread for invoking blocks, regardless of how - * busy the computer is. - */ -enum { - DISPATCH_QUEUE_OVERCOMMIT = 0x2ull, -}; - -#define DISPATCH_QUEUE_FLAGS_MASK (DISPATCH_QUEUE_OVERCOMMIT) - -/*! - * @function dispatch_queue_set_width - * - * @abstract - * Set the width of concurrency for a given queue. The width of a serial queue - * is one. - * - * @discussion - * This SPI is DEPRECATED and will be removed in a future release. - * Uses of this SPI to make a queue concurrent by setting its width to LONG_MAX - * should be replaced by passing DISPATCH_QUEUE_CONCURRENT to - * dispatch_queue_create(). - * Uses of this SPI to limit queue concurrency are not recommended and should - * be replaced by alternative mechanisms such as a dispatch semaphore created - * with the desired concurrency width. - * - * @param queue - * The queue to adjust. Passing the main queue or a global concurrent queue - * will be ignored. - * - * @param width - * The new maximum width of concurrency depending on available resources. - * If zero is passed, then the value is promoted to one. - * Negative values are magic values that map to automatic width values. - * Unknown negative values default to DISPATCH_QUEUE_WIDTH_MAX_LOGICAL_CPUS. - */ -#define DISPATCH_QUEUE_WIDTH_ACTIVE_CPUS -1 -#define DISPATCH_QUEUE_WIDTH_MAX_PHYSICAL_CPUS -2 -#define DISPATCH_QUEUE_WIDTH_MAX_LOGICAL_CPUS -3 - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_NOTHROW -void -dispatch_queue_set_width(dispatch_queue_t dq, long width); // DEPRECATED - -/*! - * @function dispatch_set_current_target_queue - * - * @abstract - * Synchronously sets the target queue of the current serial queue. - * - * @discussion - * This SPI is provided for a limited purpose case when calling - * dispatch_set_target_queue() is not sufficient. It works similarly to - * dispatch_set_target_queue() except the target queue of the current queue - * is immediately changed so that pending blocks on the queue will run on the - * new target queue. Calling this from outside of a block executing on a serial - * queue is undefined. - * - * @param queue - * The new target queue for the object. The queue is retained, and the - * previous target queue, if any, is released. - * If queue is DISPATCH_TARGET_QUEUE_DEFAULT, set the object's target queue - * to the default target queue for the given object type. - */ - -__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_5_0) -DISPATCH_EXPORT DISPATCH_NOTHROW -void -dispatch_set_current_target_queue(dispatch_queue_t queue); - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT const struct dispatch_queue_offsets_s { - // always add new fields at the end - const uint16_t dqo_version; - const uint16_t dqo_label; - const uint16_t dqo_label_size; - const uint16_t dqo_flags; - const uint16_t dqo_flags_size; - const uint16_t dqo_serialnum; - const uint16_t dqo_serialnum_size; - const uint16_t dqo_width; - const uint16_t dqo_width_size; - const uint16_t dqo_running; - const uint16_t dqo_running_size; -} dispatch_queue_offsets; - - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/include/dispatch/source_private.h b/objc/objc-runtime/include/dispatch/source_private.h deleted file mode 100755 index 576f64a..0000000 --- a/objc/objc-runtime/include/dispatch/source_private.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2008-2011 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@ - */ - -/* - * IMPORTANT: This header file describes INTERNAL interfaces to libdispatch - * which are subject to change in future releases of Mac OS X. Any applications - * relying on these interfaces WILL break. - */ - -#ifndef __DISPATCH_SOURCE_PRIVATE__ -#define __DISPATCH_SOURCE_PRIVATE__ - -#ifndef __DISPATCH_INDIRECT__ -#error "Please #include <dispatch/dispatch.h> instead of this file directly." -#include <dispatch/base.h> // for HeaderDoc -#endif - -/*! - * @const DISPATCH_SOURCE_TYPE_VFS - * @discussion Apple-internal dispatch source that monitors for vfs events - * defined by dispatch_vfs_flags_t. - * The handle is a process identifier (pid_t). - */ -#define DISPATCH_SOURCE_TYPE_VFS (&_dispatch_source_type_vfs) -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT const struct dispatch_source_type_s _dispatch_source_type_vfs; - -/*! - * @const DISPATCH_SOURCE_TYPE_VM - * @discussion A dispatch source that monitors virtual memory - * The mask is a mask of desired events from dispatch_source_vm_flags_t. - */ -#define DISPATCH_SOURCE_TYPE_VM (&_dispatch_source_type_vm) -__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_3) -DISPATCH_EXPORT const struct dispatch_source_type_s _dispatch_source_type_vm; - -/*! - * @enum dispatch_source_vfs_flags_t - * - * @constant DISPATCH_VFS_NOTRESP - * Server down. - * - * @constant DISPATCH_VFS_NEEDAUTH - * Server bad auth. - * - * @constant DISPATCH_VFS_LOWDISK - * We're low on space. - * - * @constant DISPATCH_VFS_MOUNT - * New filesystem arrived. - * - * @constant DISPATCH_VFS_UNMOUNT - * Filesystem has left. - * - * @constant DISPATCH_VFS_DEAD - * Filesystem is dead, needs force unmount. - * - * @constant DISPATCH_VFS_ASSIST - * Filesystem needs assistance from external program. - * - * @constant DISPATCH_VFS_NOTRESPLOCK - * Server lockd down. - * - * @constant DISPATCH_VFS_UPDATE - * Filesystem information has changed. - * - * @constant DISPATCH_VFS_VERYLOWDISK - * File system has *very* little disk space left. - */ -enum { - DISPATCH_VFS_NOTRESP = 0x0001, - DISPATCH_VFS_NEEDAUTH = 0x0002, - DISPATCH_VFS_LOWDISK = 0x0004, - DISPATCH_VFS_MOUNT = 0x0008, - DISPATCH_VFS_UNMOUNT = 0x0010, - DISPATCH_VFS_DEAD = 0x0020, - DISPATCH_VFS_ASSIST = 0x0040, - DISPATCH_VFS_NOTRESPLOCK = 0x0080, - DISPATCH_VFS_UPDATE = 0x0100, - DISPATCH_VFS_VERYLOWDISK = 0x0200, -}; - -/*! - * @enum dispatch_source_mach_send_flags_t - * - * @constant DISPATCH_MACH_SEND_POSSIBLE - * The mach port corresponding to the given send right has space available - * for messages. Delivered only once a mach_msg() to that send right with - * options MACH_SEND_MSG|MACH_SEND_TIMEOUT|MACH_SEND_NOTIFY has returned - * MACH_SEND_TIMED_OUT (and not again until the next such mach_msg() timeout). - * NOTE: The source must have registered the send right for monitoring with the - * system for such a mach_msg() to arm the send-possible notifcation, so - * the initial send attempt must occur from a source registration handler. - */ -enum { - DISPATCH_MACH_SEND_POSSIBLE = 0x8, -}; - -/*! - * @enum dispatch_source_proc_flags_t - * - * @constant DISPATCH_PROC_REAP - * The process has been reaped by the parent process via - * wait*(). - */ -enum { - DISPATCH_PROC_REAP = 0x10000000, -}; - -/*! - * @enum dispatch_source_vm_flags_t - * - * @constant DISPATCH_VM_PRESSURE - * The VM has experienced memory pressure. - */ - -enum { - DISPATCH_VM_PRESSURE = 0x80000000, -}; - -#if TARGET_IPHONE_SIMULATOR // rdar://problem/9219483 -#define DISPATCH_VM_PRESSURE DISPATCH_VNODE_ATTRIB -#endif - -__BEGIN_DECLS - -#if TARGET_OS_MAC -/*! - * @typedef dispatch_mig_callback_t - * - * @abstract - * The signature of a function that handles Mach message delivery and response. - */ -typedef boolean_t (*dispatch_mig_callback_t)(mach_msg_header_t *message, - mach_msg_header_t *reply); - -__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0) -DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_NOTHROW -mach_msg_return_t -dispatch_mig_server(dispatch_source_t ds, size_t maxmsgsz, - dispatch_mig_callback_t callback); -#endif - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/include/libkern/OSCrossEndian.h b/objc/objc-runtime/include/libkern/OSCrossEndian.h deleted file mode 100755 index 0bbbf58..0000000 --- a/objc/objc-runtime/include/libkern/OSCrossEndian.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2000-2006 Apple Computer, Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ - -/* - * This private header exports 3 APIs. - * _OSRosettaCheck() - An inline function that returns true if we are - * currently running under Rosetta. - * IF_ROSETTA() - Which is used to as a regular conditional - * expression that is true only if the current - * code is executing in the Rosetta - * translation space. - * ROSETTA_ONLY(exprs) - Which is used to create a block code that only - * executes if we are running in Rosetta. - * - * for example - * - * IF_ROSETTA() { - * // Do Cross endian swapping of input data - * outdata = OSSwap??(indata); - * } - * else { - * // Do straight through - * outdata = indata; - * } - * - * outdata = indata; - * ROSETTA_ONLY( - * // Do Cross endian swapping of input data - * outdata = OSSwap??(outdata); - * ); - */ - -#ifndef _LIBKERN_OSCROSSENDIAN_H -#define _LIBKERN_OSCROSSENDIAN_H - -#include <sys/sysctl.h> - -#if __ppc__ - -static __inline__ int -_OSRosettaCheck(void) -{ - int isCrossEndian = 0; - int val = 0; - size_t size = sizeof val; - - if (sysctlbyname("sysctl.proc_native", &val, &size, NULL, 0) == -1) - isCrossEndian = 0; - else - isCrossEndian = val ? 0 : 1; - - return isCrossEndian; -} - -#else /* __ppc__ */ - -static __inline__ int _OSRosettaCheck(void) { return 0; } - -#endif /* __ppc__ */ - -#define IF_ROSETTA() if (__builtin_expect(_OSRosettaCheck(), 0) ) - -#define ROSETTA_ONLY(exprs) \ -do { \ - IF_ROSETTA() { \ - exprs \ - } \ -} while(0) - -#endif /* _LIBKERN_OSCROSSENDIAN_H */ diff --git a/objc/objc-runtime/include/mach-o/dyld_priv.h b/objc/objc-runtime/include/mach-o/dyld_priv.h deleted file mode 100755 index 07ef161..0000000 --- a/objc/objc-runtime/include/mach-o/dyld_priv.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- - * - * Copyright (c) 2003-2008 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 _MACH_O_DYLD_PRIV_H_ -#define _MACH_O_DYLD_PRIV_H_ - - -#include <mach-o/dyld.h> -#include <mach-o/dyld_images.h> - -#if __cplusplus -extern "C" { -#endif /* __cplusplus */ - - -// -// Possible state changes for which you can register to be notified -// -enum dyld_image_states -{ - dyld_image_state_mapped = 10, // No batch notification for this - dyld_image_state_dependents_mapped = 20, // Only batch notification for this - dyld_image_state_rebased = 30, - dyld_image_state_bound = 40, - dyld_image_state_dependents_initialized = 45, // Only single notification for this - dyld_image_state_initialized = 50, - dyld_image_state_terminated = 60 // Only single notification for this -}; - -// -// Callback that provides a bottom-up array of images -// For dyld_image_state_[dependents_]mapped state only, returning non-NULL will cause dyld to abort loading all those images -// and append the returned string to its load failure error message. dyld does not free the string, so -// it should be a literal string or a static buffer -// -typedef const char* (*dyld_image_state_change_handler)(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[]); - -// -// Register a handler to be called when any image changes to the requested state. -// If 'batch' is true, the callback is called with an array of all images that are in the requested state sorted by dependency. -// If 'batch' is false, the callback is called with one image at a time as each image transitions to the the requested state. -// During the call to this function, the handler may be called back with existing images and the handler should -// not return a string, since there is no load to abort. In batch mode, existing images at or past the request -// state supplied in the callback. In non-batch mode, the callback is called for each image exactly in the -// requested state. -// -extern void -dyld_register_image_state_change_handler(enum dyld_image_states state, bool batch, dyld_image_state_change_handler handler); - - -// -// get slide for a given loaded mach_header -// Mac OS X 10.6 and later -// -extern intptr_t _dyld_get_image_slide(const struct mach_header* mh); - - -// -// get pointer to this process's dyld_all_image_infos -// Exists in Mac OS X 10.4 and later through _dyld_func_lookup() -// Exists in Mac OS X 10.6 and later through libSystem.dylib -// -const struct dyld_all_image_infos* _dyld_get_all_image_infos(); - - - -struct dyld_unwind_sections -{ - const struct mach_header* mh; - const void* dwarf_section; - uintptr_t dwarf_section_length; - const void* compact_unwind_section; - uintptr_t compact_unwind_section_length; -}; - - -// -// Returns true iff some loaded mach-o image contains "addr". -// info->mh mach header of image containing addr -// info->dwarf_section pointer to start of __TEXT/__eh_frame section -// info->dwarf_section_length length of __TEXT/__eh_frame section -// info->compact_unwind_section pointer to start of __TEXT/__unwind_info section -// info->compact_unwind_section_length length of __TEXT/__unwind_info section -// -// Exists in Mac OS X 10.6 and later -extern bool _dyld_find_unwind_sections(void* addr, struct dyld_unwind_sections* info); - - -// -// This is an optimized form of dladdr() that only returns the dli_fname field. -// -// Exists in Mac OS X 10.6 and later -extern const char* dyld_image_path_containing_address(const void* addr); - - - - - - - -#if __cplusplus -} -#endif /* __cplusplus */ - -#endif /* _MACH_O_DYLD_PRIV_H_ */ diff --git a/objc/objc-runtime/include/mach/clock_reply_server.h b/objc/objc-runtime/include/mach/clock_reply_server.h deleted file mode 100755 index 325f832..0000000 --- a/objc/objc-runtime/include/mach/clock_reply_server.h +++ /dev/null @@ -1,140 +0,0 @@ -#ifndef _clock_reply_server_ -#define _clock_reply_server_ - -/* Module clock_reply */ - -#include <string.h> -#include <mach/ndr.h> -#include <mach/boolean.h> -#include <mach/kern_return.h> -#include <mach/notify.h> -#include <mach/mach_types.h> -#include <mach/message.h> -#include <mach/mig_errors.h> -#include <mach/port.h> - -#ifdef AUTOTEST -#ifndef FUNCTION_PTR_T -#define FUNCTION_PTR_T -typedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t); -typedef struct { - char *name; - function_ptr_t function; -} function_table_entry; -typedef function_table_entry *function_table_t; -#endif /* FUNCTION_PTR_T */ -#endif /* AUTOTEST */ - -#ifndef clock_reply_MSG_COUNT -#define clock_reply_MSG_COUNT 1 -#endif /* clock_reply_MSG_COUNT */ - -#include <mach/std_types.h> -#include <mach/mig.h> -#include <mach/mach_types.h> - -#ifdef __BeforeMigServerHeader -__BeforeMigServerHeader -#endif /* __BeforeMigServerHeader */ - - -/* SimpleRoutine clock_alarm_reply */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t clock_alarm_reply -( - clock_reply_t alarm_port, - kern_return_t alarm_code, - alarm_type_t alarm_type, - mach_timespec_t alarm_time -); - -extern boolean_t clock_reply_server( - mach_msg_header_t *InHeadP, - mach_msg_header_t *OutHeadP); - -extern mig_routine_t clock_reply_server_routine( - mach_msg_header_t *InHeadP); - - -/* Description of this subsystem, for use in direct RPC */ -extern const struct clock_reply_subsystem { - mig_server_routine_t server; /* Server routine */ - mach_msg_id_t start; /* Min routine number */ - mach_msg_id_t end; /* Max routine number + 1 */ - unsigned int maxsize; /* Max msg size */ - vm_address_t reserved; /* Reserved */ - struct routine_descriptor /*Array of routine descriptors */ - routine[1]; -} clock_reply_subsystem; - -/* typedefs for all requests */ - -#ifndef __Request__clock_reply_subsystem__defined -#define __Request__clock_reply_subsystem__defined - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t alarm_code; - alarm_type_t alarm_type; - mach_timespec_t alarm_time; - } __Request__clock_alarm_reply_t; -#ifdef __MigPackStructs -#pragma pack() -#endif -#endif /* !__Request__clock_reply_subsystem__defined */ - - -/* union of all requests */ - -#ifndef __RequestUnion__clock_reply_subsystem__defined -#define __RequestUnion__clock_reply_subsystem__defined -union __RequestUnion__clock_reply_subsystem { - __Request__clock_alarm_reply_t Request_clock_alarm_reply; -}; -#endif /* __RequestUnion__clock_reply_subsystem__defined */ -/* typedefs for all replies */ - -#ifndef __Reply__clock_reply_subsystem__defined -#define __Reply__clock_reply_subsystem__defined - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__clock_alarm_reply_t; -#ifdef __MigPackStructs -#pragma pack() -#endif -#endif /* !__Reply__clock_reply_subsystem__defined */ - - -/* union of all replies */ - -#ifndef __ReplyUnion__clock_reply_subsystem__defined -#define __ReplyUnion__clock_reply_subsystem__defined -union __ReplyUnion__clock_reply_subsystem { - __Reply__clock_alarm_reply_t Reply_clock_alarm_reply; -}; -#endif /* __RequestUnion__clock_reply_subsystem__defined */ - -#ifndef subsystem_to_name_map_clock_reply -#define subsystem_to_name_map_clock_reply \ - { "clock_alarm_reply", 3125107 } -#endif - -#ifdef __AfterMigServerHeader -__AfterMigServerHeader -#endif /* __AfterMigServerHeader */ - -#endif /* _clock_reply_server_ */ diff --git a/objc/objc-runtime/include/mach/exc_server.h b/objc/objc-runtime/include/mach/exc_server.h deleted file mode 100755 index 2f26071..0000000 --- a/objc/objc-runtime/include/mach/exc_server.h +++ /dev/null @@ -1,263 +0,0 @@ -#ifndef _exc_server_ -#define _exc_server_ - -/* Module exc */ - -#include <string.h> -#include <mach/ndr.h> -#include <mach/boolean.h> -#include <mach/kern_return.h> -#include <mach/notify.h> -#include <mach/mach_types.h> -#include <mach/message.h> -#include <mach/mig_errors.h> -#include <mach/port.h> - -#ifdef AUTOTEST -#ifndef FUNCTION_PTR_T -#define FUNCTION_PTR_T -typedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t); -typedef struct { - char *name; - function_ptr_t function; -} function_table_entry; -typedef function_table_entry *function_table_t; -#endif /* FUNCTION_PTR_T */ -#endif /* AUTOTEST */ - -#ifndef exc_MSG_COUNT -#define exc_MSG_COUNT 3 -#endif /* exc_MSG_COUNT */ - -#include <mach/std_types.h> -#include <mach/mig.h> -#include <mach/mig.h> -#include <mach/mach_types.h> - -#ifdef __BeforeMigServerHeader -__BeforeMigServerHeader -#endif /* __BeforeMigServerHeader */ - - -/* Routine exception_raise */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t catch_exception_raise -( - mach_port_t exception_port, - mach_port_t thread, - mach_port_t task, - exception_type_t exception, - exception_data_t code, - mach_msg_type_number_t codeCnt -); - -/* Routine exception_raise_state */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t catch_exception_raise_state -( - mach_port_t exception_port, - exception_type_t exception, - const exception_data_t code, - mach_msg_type_number_t codeCnt, - int *flavor, - const thread_state_t old_state, - mach_msg_type_number_t old_stateCnt, - thread_state_t new_state, - mach_msg_type_number_t *new_stateCnt -); - -/* Routine exception_raise_state_identity */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t catch_exception_raise_state_identity -( - mach_port_t exception_port, - mach_port_t thread, - mach_port_t task, - exception_type_t exception, - exception_data_t code, - mach_msg_type_number_t codeCnt, - int *flavor, - thread_state_t old_state, - mach_msg_type_number_t old_stateCnt, - thread_state_t new_state, - mach_msg_type_number_t *new_stateCnt -); - -extern boolean_t exc_server( - mach_msg_header_t *InHeadP, - mach_msg_header_t *OutHeadP); - -extern mig_routine_t exc_server_routine( - mach_msg_header_t *InHeadP); - - -/* Description of this subsystem, for use in direct RPC */ -extern const struct catch_exc_subsystem { - mig_server_routine_t server; /* Server routine */ - mach_msg_id_t start; /* Min routine number */ - mach_msg_id_t end; /* Max routine number + 1 */ - unsigned int maxsize; /* Max msg size */ - vm_address_t reserved; /* Reserved */ - struct routine_descriptor /*Array of routine descriptors */ - routine[3]; -} catch_exc_subsystem; - -/* typedefs for all requests */ - -#ifndef __Request__exc_subsystem__defined -#define __Request__exc_subsystem__defined - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - /* start of the kernel processed data */ - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t thread; - mach_msg_port_descriptor_t task; - /* end of the kernel processed data */ - NDR_record_t NDR; - exception_type_t exception; - mach_msg_type_number_t codeCnt; - integer_t code[2]; - } __Request__exception_raise_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - exception_type_t exception; - mach_msg_type_number_t codeCnt; - integer_t code[2]; - int flavor; - mach_msg_type_number_t old_stateCnt; - natural_t old_state[144]; - } __Request__exception_raise_state_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - /* start of the kernel processed data */ - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t thread; - mach_msg_port_descriptor_t task; - /* end of the kernel processed data */ - NDR_record_t NDR; - exception_type_t exception; - mach_msg_type_number_t codeCnt; - integer_t code[2]; - int flavor; - mach_msg_type_number_t old_stateCnt; - natural_t old_state[144]; - } __Request__exception_raise_state_identity_t; -#ifdef __MigPackStructs -#pragma pack() -#endif -#endif /* !__Request__exc_subsystem__defined */ - - -/* union of all requests */ - -#ifndef __RequestUnion__catch_exc_subsystem__defined -#define __RequestUnion__catch_exc_subsystem__defined -union __RequestUnion__catch_exc_subsystem { - __Request__exception_raise_t Request_exception_raise; - __Request__exception_raise_state_t Request_exception_raise_state; - __Request__exception_raise_state_identity_t Request_exception_raise_state_identity; -}; -#endif /* __RequestUnion__catch_exc_subsystem__defined */ -/* typedefs for all replies */ - -#ifndef __Reply__exc_subsystem__defined -#define __Reply__exc_subsystem__defined - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__exception_raise_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - int flavor; - mach_msg_type_number_t new_stateCnt; - natural_t new_state[144]; - } __Reply__exception_raise_state_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - int flavor; - mach_msg_type_number_t new_stateCnt; - natural_t new_state[144]; - } __Reply__exception_raise_state_identity_t; -#ifdef __MigPackStructs -#pragma pack() -#endif -#endif /* !__Reply__exc_subsystem__defined */ - - -/* union of all replies */ - -#ifndef __ReplyUnion__catch_exc_subsystem__defined -#define __ReplyUnion__catch_exc_subsystem__defined -union __ReplyUnion__catch_exc_subsystem { - __Reply__exception_raise_t Reply_exception_raise; - __Reply__exception_raise_state_t Reply_exception_raise_state; - __Reply__exception_raise_state_identity_t Reply_exception_raise_state_identity; -}; -#endif /* __RequestUnion__catch_exc_subsystem__defined */ - -#ifndef subsystem_to_name_map_exc -#define subsystem_to_name_map_exc \ - { "exception_raise", 2401 },\ - { "exception_raise_state", 2402 },\ - { "exception_raise_state_identity", 2403 } -#endif - -#ifdef __AfterMigServerHeader -__AfterMigServerHeader -#endif /* __AfterMigServerHeader */ - -#endif /* _exc_server_ */ diff --git a/objc/objc-runtime/include/mach/mach_exc_server.h b/objc/objc-runtime/include/mach/mach_exc_server.h deleted file mode 100755 index d537ff0..0000000 --- a/objc/objc-runtime/include/mach/mach_exc_server.h +++ /dev/null @@ -1,263 +0,0 @@ -#ifndef _mach_exc_server_ -#define _mach_exc_server_ - -/* Module mach_exc */ - -#include <string.h> -#include <mach/ndr.h> -#include <mach/boolean.h> -#include <mach/kern_return.h> -#include <mach/notify.h> -#include <mach/mach_types.h> -#include <mach/message.h> -#include <mach/mig_errors.h> -#include <mach/port.h> - -#ifdef AUTOTEST -#ifndef FUNCTION_PTR_T -#define FUNCTION_PTR_T -typedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t); -typedef struct { - char *name; - function_ptr_t function; -} function_table_entry; -typedef function_table_entry *function_table_t; -#endif /* FUNCTION_PTR_T */ -#endif /* AUTOTEST */ - -#ifndef mach_exc_MSG_COUNT -#define mach_exc_MSG_COUNT 3 -#endif /* mach_exc_MSG_COUNT */ - -#include <mach/std_types.h> -#include <mach/mig.h> -#include <mach/mig.h> -#include <mach/mach_types.h> - -#ifdef __BeforeMigServerHeader -__BeforeMigServerHeader -#endif /* __BeforeMigServerHeader */ - - -/* Routine mach_exception_raise */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t catch_mach_exception_raise -( - mach_port_t exception_port, - mach_port_t thread, - mach_port_t task, - exception_type_t exception, - mach_exception_data_t code, - mach_msg_type_number_t codeCnt -); - -/* Routine mach_exception_raise_state */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t catch_mach_exception_raise_state -( - mach_port_t exception_port, - exception_type_t exception, - const mach_exception_data_t code, - mach_msg_type_number_t codeCnt, - int *flavor, - const thread_state_t old_state, - mach_msg_type_number_t old_stateCnt, - thread_state_t new_state, - mach_msg_type_number_t *new_stateCnt -); - -/* Routine mach_exception_raise_state_identity */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t catch_mach_exception_raise_state_identity -( - mach_port_t exception_port, - mach_port_t thread, - mach_port_t task, - exception_type_t exception, - mach_exception_data_t code, - mach_msg_type_number_t codeCnt, - int *flavor, - thread_state_t old_state, - mach_msg_type_number_t old_stateCnt, - thread_state_t new_state, - mach_msg_type_number_t *new_stateCnt -); - -extern boolean_t mach_exc_server( - mach_msg_header_t *InHeadP, - mach_msg_header_t *OutHeadP); - -extern mig_routine_t mach_exc_server_routine( - mach_msg_header_t *InHeadP); - - -/* Description of this subsystem, for use in direct RPC */ -extern const struct catch_mach_exc_subsystem { - mig_server_routine_t server; /* Server routine */ - mach_msg_id_t start; /* Min routine number */ - mach_msg_id_t end; /* Max routine number + 1 */ - unsigned int maxsize; /* Max msg size */ - vm_address_t reserved; /* Reserved */ - struct routine_descriptor /*Array of routine descriptors */ - routine[3]; -} catch_mach_exc_subsystem; - -/* typedefs for all requests */ - -#ifndef __Request__mach_exc_subsystem__defined -#define __Request__mach_exc_subsystem__defined - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - /* start of the kernel processed data */ - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t thread; - mach_msg_port_descriptor_t task; - /* end of the kernel processed data */ - NDR_record_t NDR; - exception_type_t exception; - mach_msg_type_number_t codeCnt; - int64_t code[2]; - } __Request__mach_exception_raise_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - exception_type_t exception; - mach_msg_type_number_t codeCnt; - int64_t code[2]; - int flavor; - mach_msg_type_number_t old_stateCnt; - natural_t old_state[144]; - } __Request__mach_exception_raise_state_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - /* start of the kernel processed data */ - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t thread; - mach_msg_port_descriptor_t task; - /* end of the kernel processed data */ - NDR_record_t NDR; - exception_type_t exception; - mach_msg_type_number_t codeCnt; - int64_t code[2]; - int flavor; - mach_msg_type_number_t old_stateCnt; - natural_t old_state[144]; - } __Request__mach_exception_raise_state_identity_t; -#ifdef __MigPackStructs -#pragma pack() -#endif -#endif /* !__Request__mach_exc_subsystem__defined */ - - -/* union of all requests */ - -#ifndef __RequestUnion__catch_mach_exc_subsystem__defined -#define __RequestUnion__catch_mach_exc_subsystem__defined -union __RequestUnion__catch_mach_exc_subsystem { - __Request__mach_exception_raise_t Request_mach_exception_raise; - __Request__mach_exception_raise_state_t Request_mach_exception_raise_state; - __Request__mach_exception_raise_state_identity_t Request_mach_exception_raise_state_identity; -}; -#endif /* __RequestUnion__catch_mach_exc_subsystem__defined */ -/* typedefs for all replies */ - -#ifndef __Reply__mach_exc_subsystem__defined -#define __Reply__mach_exc_subsystem__defined - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_exception_raise_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - int flavor; - mach_msg_type_number_t new_stateCnt; - natural_t new_state[144]; - } __Reply__mach_exception_raise_state_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - int flavor; - mach_msg_type_number_t new_stateCnt; - natural_t new_state[144]; - } __Reply__mach_exception_raise_state_identity_t; -#ifdef __MigPackStructs -#pragma pack() -#endif -#endif /* !__Reply__mach_exc_subsystem__defined */ - - -/* union of all replies */ - -#ifndef __ReplyUnion__catch_mach_exc_subsystem__defined -#define __ReplyUnion__catch_mach_exc_subsystem__defined -union __ReplyUnion__catch_mach_exc_subsystem { - __Reply__mach_exception_raise_t Reply_mach_exception_raise; - __Reply__mach_exception_raise_state_t Reply_mach_exception_raise_state; - __Reply__mach_exception_raise_state_identity_t Reply_mach_exception_raise_state_identity; -}; -#endif /* __RequestUnion__catch_mach_exc_subsystem__defined */ - -#ifndef subsystem_to_name_map_mach_exc -#define subsystem_to_name_map_mach_exc \ - { "mach_exception_raise", 2405 },\ - { "mach_exception_raise_state", 2406 },\ - { "mach_exception_raise_state_identity", 2407 } -#endif - -#ifdef __AfterMigServerHeader -__AfterMigServerHeader -#endif /* __AfterMigServerHeader */ - -#endif /* _mach_exc_server_ */ diff --git a/objc/objc-runtime/include/mach/notify_server.h b/objc/objc-runtime/include/mach/notify_server.h deleted file mode 100755 index 780a4b9..0000000 --- a/objc/objc-runtime/include/mach/notify_server.h +++ /dev/null @@ -1,290 +0,0 @@ -#ifndef _notify_server_ -#define _notify_server_ - -/* Module notify */ - -#include <string.h> -#include <mach/ndr.h> -#include <mach/boolean.h> -#include <mach/kern_return.h> -#include <mach/notify.h> -#include <mach/mach_types.h> -#include <mach/message.h> -#include <mach/mig_errors.h> -#include <mach/port.h> - -#ifdef AUTOTEST -#ifndef FUNCTION_PTR_T -#define FUNCTION_PTR_T -typedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t); -typedef struct { - char *name; - function_ptr_t function; -} function_table_entry; -typedef function_table_entry *function_table_t; -#endif /* FUNCTION_PTR_T */ -#endif /* AUTOTEST */ - -#ifndef notify_MSG_COUNT -#define notify_MSG_COUNT 9 -#endif /* notify_MSG_COUNT */ - -#include <mach/std_types.h> -#include <mach/mig.h> - -#ifdef __BeforeMigServerHeader -__BeforeMigServerHeader -#endif /* __BeforeMigServerHeader */ - - -/* SimpleRoutine mach_notify_port_deleted */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t do_mach_notify_port_deleted -( - mach_port_t notify, - mach_port_name_t name -); - -/* SimpleRoutine mach_notify_port_destroyed */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t do_mach_notify_port_destroyed -( - mach_port_t notify, - mach_port_t rights -); - -/* SimpleRoutine mach_notify_no_senders */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t do_mach_notify_no_senders -( - mach_port_t notify, - mach_port_mscount_t mscount -); - -/* SimpleRoutine mach_notify_send_once */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t do_mach_notify_send_once -( - mach_port_t notify -); - -/* SimpleRoutine mach_notify_dead_name */ -#ifdef mig_external -mig_external -#else -extern -#endif /* mig_external */ -kern_return_t do_mach_notify_dead_name -( - mach_port_t notify, - mach_port_name_t name -); - -extern boolean_t notify_server( - mach_msg_header_t *InHeadP, - mach_msg_header_t *OutHeadP); - -extern mig_routine_t notify_server_routine( - mach_msg_header_t *InHeadP); - - -/* Description of this subsystem, for use in direct RPC */ -extern const struct do_notify_subsystem { - mig_server_routine_t server; /* Server routine */ - mach_msg_id_t start; /* Min routine number */ - mach_msg_id_t end; /* Max routine number + 1 */ - unsigned int maxsize; /* Max msg size */ - vm_address_t reserved; /* Reserved */ - struct routine_descriptor /*Array of routine descriptors */ - routine[9]; -} do_notify_subsystem; - -/* typedefs for all requests */ - -#ifndef __Request__notify_subsystem__defined -#define __Request__notify_subsystem__defined - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_notify_port_deleted_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - /* start of the kernel processed data */ - mach_msg_body_t msgh_body; - mach_msg_port_descriptor_t rights; - /* end of the kernel processed data */ - } __Request__mach_notify_port_destroyed_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_mscount_t mscount; - } __Request__mach_notify_no_senders_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - } __Request__mach_notify_send_once_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_port_name_t name; - } __Request__mach_notify_dead_name_t; -#ifdef __MigPackStructs -#pragma pack() -#endif -#endif /* !__Request__notify_subsystem__defined */ - - -/* union of all requests */ - -#ifndef __RequestUnion__do_notify_subsystem__defined -#define __RequestUnion__do_notify_subsystem__defined -union __RequestUnion__do_notify_subsystem { - __Request__mach_notify_port_deleted_t Request_mach_notify_port_deleted; - __Request__mach_notify_port_destroyed_t Request_mach_notify_port_destroyed; - __Request__mach_notify_no_senders_t Request_mach_notify_no_senders; - __Request__mach_notify_send_once_t Request_mach_notify_send_once; - __Request__mach_notify_dead_name_t Request_mach_notify_dead_name; -}; -#endif /* __RequestUnion__do_notify_subsystem__defined */ -/* typedefs for all replies */ - -#ifndef __Reply__notify_subsystem__defined -#define __Reply__notify_subsystem__defined - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_notify_port_deleted_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_notify_port_destroyed_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_notify_no_senders_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_notify_send_once_t; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - } __Reply__mach_notify_dead_name_t; -#ifdef __MigPackStructs -#pragma pack() -#endif -#endif /* !__Reply__notify_subsystem__defined */ - - -/* union of all replies */ - -#ifndef __ReplyUnion__do_notify_subsystem__defined -#define __ReplyUnion__do_notify_subsystem__defined -union __ReplyUnion__do_notify_subsystem { - __Reply__mach_notify_port_deleted_t Reply_mach_notify_port_deleted; - __Reply__mach_notify_port_destroyed_t Reply_mach_notify_port_destroyed; - __Reply__mach_notify_no_senders_t Reply_mach_notify_no_senders; - __Reply__mach_notify_send_once_t Reply_mach_notify_send_once; - __Reply__mach_notify_dead_name_t Reply_mach_notify_dead_name; -}; -#endif /* __RequestUnion__do_notify_subsystem__defined */ - -#ifndef subsystem_to_name_map_notify -#define subsystem_to_name_map_notify \ - { "mach_notify_port_deleted", 65 },\ - { "mach_notify_port_destroyed", 69 },\ - { "mach_notify_no_senders", 70 },\ - { "mach_notify_send_once", 71 },\ - { "mach_notify_dead_name", 72 } -#endif - -#ifdef __AfterMigServerHeader -__AfterMigServerHeader -#endif /* __AfterMigServerHeader */ - -#endif /* _notify_server_ */ diff --git a/objc/objc-runtime/include/machine/Makefile b/objc/objc-runtime/include/machine/Makefile deleted file mode 100755 index d68ef2f..0000000 --- a/objc/objc-runtime/include/machine/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -export MakeInc_cmd=${SRCROOT}/makedefs/MakeInc.cmd -export MakeInc_def=${SRCROOT}/makedefs/MakeInc.def -export MakeInc_rule=${SRCROOT}/makedefs/MakeInc.rule -export MakeInc_dir=${SRCROOT}/makedefs/MakeInc.dir - - -include $(MakeInc_cmd) -include $(MakeInc_def) - - -DATAFILES = \ - cpu_number.h \ - cpu_capabilities.h \ - io_map_entries.h \ - lock.h \ - locks.h \ - machine_routines.h \ - simple_lock.h - -INSTALL_MI_LCL_LIST = cpu_capabilities.h - -INSTALL_MI_DIR = machine - -EXPORT_MI_LIST = ${DATAFILES} - -EXPORT_MI_DIR = machine - -include $(MakeInc_rule) -include $(MakeInc_dir) - - diff --git a/objc/objc-runtime/include/machine/asm.h b/objc/objc-runtime/include/machine/asm.h deleted file mode 100755 index 70c246c..0000000 --- a/objc/objc-runtime/include/machine/asm.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_ASM_H -#define _MACHINE_ASM_H - -#if defined (__ppc__) -#include "ppc/asm.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/asm.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_ASM_H */ diff --git a/objc/objc-runtime/include/machine/ast.h b/objc/objc-runtime/include/machine/ast.h deleted file mode 100755 index 0c01fc7..0000000 --- a/objc/objc-runtime/include/machine/ast.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_AST_H -#define _MACHINE_AST_H - -#if defined (__ppc__) -#include "ppc/ast.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/ast.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_AST_H */ diff --git a/objc/objc-runtime/include/machine/ast_types.h b/objc/objc-runtime/include/machine/ast_types.h deleted file mode 100755 index fc7d1d2..0000000 --- a/objc/objc-runtime/include/machine/ast_types.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_AST_TYPES_H -#define _MACHINE_AST_TYPES_H - -#if defined (__ppc__) -#include "ppc/ast_types.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/ast_types.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_AST_TYPES_H */ diff --git a/objc/objc-runtime/include/machine/commpage.h b/objc/objc-runtime/include/machine/commpage.h deleted file mode 100755 index c3d3a99..0000000 --- a/objc/objc-runtime/include/machine/commpage.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ - -#ifndef _MACHINE_COMMPAGE_H -#define _MACHINE_COMMPAGE_H - -#if defined (__ppc__) -#include "ppc/commpage/commpage.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/commpage/commpage.h" -#else -#error architecture not supported -#endif - -#ifndef __ASSEMBLER__ - -extern void commpage_populate( void ); /* called once during startup */ - -#endif /* __ASSEMBLER__ */ - -#endif /* _MACHINE_COMMPAGE_H */ diff --git a/objc/objc-runtime/include/machine/cpu_affinity.h b/objc/objc-runtime/include/machine/cpu_affinity.h deleted file mode 100755 index 990c856..0000000 --- a/objc/objc-runtime/include/machine/cpu_affinity.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifdef KERNEL_PRIVATE - -#ifndef _MACHINE_CPU_AFFINITY_H -#define _MACHINE_CPU_AFFINITY_H - -#if defined (__ppc__) -#include "ppc/cpu_affinity.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/cpu_affinity.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_CPU_AFFINITY_H */ - -#endif /* KERNEL_PRIVATE */ diff --git a/objc/objc-runtime/include/machine/cpu_capabilities.h b/objc/objc-runtime/include/machine/cpu_capabilities.h deleted file mode 100755 index 606ec28..0000000 --- a/objc/objc-runtime/include/machine/cpu_capabilities.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifdef PRIVATE - -#ifndef _MACHINE_CPU_CAPABILITIES_H -#define _MACHINE_CPU_CAPABILITIES_H - -#ifdef KERNEL_PRIVATE -#if defined (__ppc__) -#include "ppc/cpu_capabilities.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/cpu_capabilities.h" -#else -#error architecture not supported -#endif - -#else /* !KERNEL_PRIVATE -- System Framework header */ -#if defined (__ppc__) || defined(__ppc64__) -#include <System/ppc/cpu_capabilities.h> -#elif defined (__i386__) || defined(__x86_64__) -#include <System/i386/cpu_capabilities.h> -#else -#error architecture not supported -#endif -#endif /* KERNEL_PRIVATE */ - -#endif /* _MACHINE_CPU_CAPABILITIES_H */ -#endif /* PRIVATE */ diff --git a/objc/objc-runtime/include/machine/cpu_data.h b/objc/objc-runtime/include/machine/cpu_data.h deleted file mode 100755 index 0a04748..0000000 --- a/objc/objc-runtime/include/machine/cpu_data.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_CPU_DATA_H -#define _MACHINE_CPU_DATA_H - -#if defined (__ppc__) -#include "ppc/cpu_data.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/cpu_data.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_CPU_DATA_H */ diff --git a/objc/objc-runtime/include/machine/cpu_number.h b/objc/objc-runtime/include/machine/cpu_number.h deleted file mode 100755 index 47e71ba..0000000 --- a/objc/objc-runtime/include/machine/cpu_number.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifdef KERNEL_PRIVATE - -#ifndef _MACHINE_CPU_NUMBER_H -#define _MACHINE_CPU_NUMBER_H - -#if defined (__ppc__) -#include "ppc/cpu_number.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/cpu_number.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_CPU_NUMBER_H */ - -#endif /* KERNEL_PRIVATE */ diff --git a/objc/objc-runtime/include/machine/db_machdep.h b/objc/objc-runtime/include/machine/db_machdep.h deleted file mode 100755 index ae38b44..0000000 --- a/objc/objc-runtime/include/machine/db_machdep.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_DB_MACHDEP_H -#define _MACHINE_DB_MACHDEP_H - -#if defined (__ppc__) -#include "ppc/db_machdep.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/db_machdep.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_DB_MACHDEP_H */ diff --git a/objc/objc-runtime/include/machine/endian.h b/objc/objc-runtime/include/machine/endian.h deleted file mode 100755 index 5f9c0b9..0000000 --- a/objc/objc-runtime/include/machine/endian.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_ENDIAN_H -#define _MACHINE_ENDIAN_H - -#if defined (__ppc__) -#include "ppc/endian.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/endian.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_ENDIAN_H */ diff --git a/objc/objc-runtime/include/machine/io_map_entries.h b/objc/objc-runtime/include/machine/io_map_entries.h deleted file mode 100755 index 8e9e9e4..0000000 --- a/objc/objc-runtime/include/machine/io_map_entries.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifdef KERNEL_PRIVATE - -#ifndef _MACHINE_IO_MAP_ENTRIES_H_ -#define _MACHINE_IO_MAP_ENTRIES_H_ - -#if defined (__ppc__) -#include "ppc/io_map_entries.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/io_map_entries.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_IO_MAP_ENTRIES_H_ */ - -#endif /* KERNEL_PRIVATE */ diff --git a/objc/objc-runtime/include/machine/lock.h b/objc/objc-runtime/include/machine/lock.h deleted file mode 100755 index 558e780..0000000 --- a/objc/objc-runtime/include/machine/lock.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifdef KERNEL_PRIVATE - -#ifndef _MACHINE_LOCK_H_ -#define _MACHINE_LOCK_H_ - -#if defined (__ppc__) -#include "ppc/lock.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/lock.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_LOCK_H_ */ - -#endif diff --git a/objc/objc-runtime/include/machine/locks.h b/objc/objc-runtime/include/machine/locks.h deleted file mode 100755 index 7864195..0000000 --- a/objc/objc-runtime/include/machine/locks.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2004-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_LOCKS_H_ -#define _MACHINE_LOCKS_H_ - -#if defined (__ppc__) -#include "ppc/locks.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/locks.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_LOCKS_H_ */ diff --git a/objc/objc-runtime/include/machine/machine_cpu.h b/objc/objc-runtime/include/machine/machine_cpu.h deleted file mode 100755 index fdc556a..0000000 --- a/objc/objc-runtime/include/machine/machine_cpu.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_MACHINE_CPU_H -#define _MACHINE_MACHINE_CPU_H - -#if defined (__ppc__) -#include "ppc/machine_cpu.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/machine_cpu.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_MACHINE_CPU_H */ diff --git a/objc/objc-runtime/include/machine/machine_routines.h b/objc/objc-runtime/include/machine/machine_routines.h deleted file mode 100755 index a92705f..0000000 --- a/objc/objc-runtime/include/machine/machine_routines.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_MACHINE_ROUTINES_H -#define _MACHINE_MACHINE_ROUTINES_H - -#if defined (__ppc__) -#include "ppc/machine_routines.h" -#elif defined (__i386__) || defined(__x86_64__) -#include "i386/machine_routines.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_MACHINE_ROUTINES_H */ diff --git a/objc/objc-runtime/include/machine/machine_rpc.h b/objc/objc-runtime/include/machine/machine_rpc.h deleted file mode 100755 index 0fe29c9..0000000 --- a/objc/objc-runtime/include/machine/machine_rpc.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_MACHINE_RPC_H -#define _MACHINE_MACHINE_RPC_H - -#if defined (__ppc__) -#include "ppc/machine_rpc.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/machine_rpc.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_MACHINE_RPC_H */ diff --git a/objc/objc-runtime/include/machine/machlimits.h b/objc/objc-runtime/include/machine/machlimits.h deleted file mode 100755 index f9d4684..0000000 --- a/objc/objc-runtime/include/machine/machlimits.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_MACHLIMITS_H -#define _MACHINE_MACHLIMITS_H - -#if defined (__ppc__) -#include "ppc/machlimits.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/machlimits.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_MACHLIMITS_H */ diff --git a/objc/objc-runtime/include/machine/machparam.h b/objc/objc-runtime/include/machine/machparam.h deleted file mode 100755 index 3e83253..0000000 --- a/objc/objc-runtime/include/machine/machparam.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_MACHPARAM_H -#define _MACHINE_MACHPARAM_H - -#if defined (__ppc__) -#include "ppc/machparam.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/machparam.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_MACHPARAM_H */ diff --git a/objc/objc-runtime/include/machine/pmap.h b/objc/objc-runtime/include/machine/pmap.h deleted file mode 100755 index b629003..0000000 --- a/objc/objc-runtime/include/machine/pmap.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_PMAP_H -#define _MACHINE_PMAP_H - -#if defined (__ppc__) -#include "ppc/pmap.h" -#elif defined (__x86_64__) || defined (__i386__) -#include "i386/pmap.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_PMAP_H */ diff --git a/objc/objc-runtime/include/machine/sched_param.h b/objc/objc-runtime/include/machine/sched_param.h deleted file mode 100755 index 04c23c7..0000000 --- a/objc/objc-runtime/include/machine/sched_param.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_SCHED_PARAM_H -#define _MACHINE_SCHED_PARAM_H - -#if defined (__ppc__) -#include "ppc/sched_param.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/sched_param.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_SCHED_PARAM_H */ diff --git a/objc/objc-runtime/include/machine/setjmp.h b/objc/objc-runtime/include/machine/setjmp.h deleted file mode 100755 index c597030..0000000 --- a/objc/objc-runtime/include/machine/setjmp.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_SETJMP_H -#define _MACHINE_SETJMP_H - -#if defined (__ppc__) -#include "ppc/setjmp.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/setjmp.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_SETJMP_H */ diff --git a/objc/objc-runtime/include/machine/simple_lock.h b/objc/objc-runtime/include/machine/simple_lock.h deleted file mode 100755 index 799b74c..0000000 --- a/objc/objc-runtime/include/machine/simple_lock.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifdef KERNEL_PRIVATE - -#ifndef _MACHINE_SIMPLE_LOCK_H_ -#define _MACHINE_SIMPLE_LOCK_H_ - -#if defined (__ppc__) -#include "ppc/simple_lock.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/simple_lock.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_SIMPLE_LOCK_H_ */ - -#endif diff --git a/objc/objc-runtime/include/machine/task.h b/objc/objc-runtime/include/machine/task.h deleted file mode 100755 index faf4ba5..0000000 --- a/objc/objc-runtime/include/machine/task.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_TASK_H -#define _MACHINE_TASK_H - -#if defined (__ppc__) -#include "ppc/task.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/task.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_TASK_H */ diff --git a/objc/objc-runtime/include/machine/thread.h b/objc/objc-runtime/include/machine/thread.h deleted file mode 100755 index 5eeccbd..0000000 --- a/objc/objc-runtime/include/machine/thread.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_THREAD_H -#define _MACHINE_THREAD_H - -#if defined (__ppc__) -#include "ppc/thread.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/thread.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_THREADx_H */ diff --git a/objc/objc-runtime/include/machine/timer.h b/objc/objc-runtime/include/machine/timer.h deleted file mode 100755 index a80a74b..0000000 --- a/objc/objc-runtime/include/machine/timer.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_TIMER_H -#define _MACHINE_TIMER_H - -#if defined (__ppc__) -#include "ppc/timer.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/timer.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_TIMER_H */ diff --git a/objc/objc-runtime/include/machine/trap.h b/objc/objc-runtime/include/machine/trap.h deleted file mode 100755 index 5429870..0000000 --- a/objc/objc-runtime/include/machine/trap.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_TRAP_H -#define _MACHINE_TRAP_H - -#if defined (__ppc__) -#include "ppc/trap.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/trap.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_TRAP_H */ diff --git a/objc/objc-runtime/include/machine/vm_tuning.h b/objc/objc-runtime/include/machine/vm_tuning.h deleted file mode 100755 index a5906bb..0000000 --- a/objc/objc-runtime/include/machine/vm_tuning.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_VM_TUNING_H -#define _MACHINE_VM_TUNING_H - -#if defined (__ppc__) -#include "ppc/vm_tuning.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/vm_tuning.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_VM_TUNING_H */ diff --git a/objc/objc-runtime/include/machine/xpr.h b/objc/objc-runtime/include/machine/xpr.h deleted file mode 100755 index 089a5cc..0000000 --- a/objc/objc-runtime/include/machine/xpr.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2000-2007 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ -#ifndef _MACHINE_XPR_H -#define _MACHINE_XPR_H - -#if defined (__ppc__) -#include "ppc/xpr.h" -#elif defined (__i386__) || defined (__x86_64__) -#include "i386/xpr.h" -#else -#error architecture not supported -#endif - -#endif /* _MACHINE_XPR_H */ diff --git a/objc/objc-runtime/include/objc-shared-cache.h b/objc/objc-runtime/include/objc-shared-cache.h deleted file mode 100755 index dfccf26..0000000 --- a/objc/objc-runtime/include/objc-shared-cache.h +++ /dev/null @@ -1,1363 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -/* -Portions derived from: - --------------------------------------------------------------------- -lookup8.c, by Bob Jenkins, January 4 1997, Public Domain. -hash(), hash2(), hash3, and mix() are externally useful functions. -Routines to test the hash are included if SELF_TEST is defined. -You can use this free for any purpose. It has no warranty. --------------------------------------------------------------------- - ------------------------------------------------------------------------------- -perfect.c: code to generate code for a hash for perfect hashing. -(c) Bob Jenkins, September 1996, December 1999 -You may use this code in any way you wish, and it is free. No warranty. -I hereby place this in the public domain. -Source is http://burtleburtle.net/bob/c/perfect.c ------------------------------------------------------------------------------- -*/ - -/* - * objc-selopt.h - * Interface between libobjc and dyld - * for selector uniquing in the dyld shared cache. - * - * When building the shared cache, dyld locates all selectors and selector - * references in the cached images. It builds a perfect hash table out of - * them and writes the table into the shared cache copy of libobjc. - * libobjc then uses that table as the builtin selector list. - * - * Versioning - * The table has a version number. dyld and objc can both ignore the table - * if the other used the wrong version number. - * - * Completeness - * Not all libraries are in the shared cache. Libraries that are in the - * shared cache and were optimized are specially marked. Libraries on - * disk never include those marks. - * - * Coherency - * Libraries optimized in the shared cache can be replaced by unoptimized - * copies from disk when loaded. The copy from disk is not marked and will - * be fixed up by libobjc. The shared cache copy is still mapped into the - * process, so the table can point to cstring data in that library's part - * of the shared cache without trouble. - * - * Atomicity - * dyld writes the table itself last. If dyld marks some metadata as - * updated but then fails to write a table for some reason, libobjc - * fixes up all metadata as if it were not marked. - */ - -#ifndef _OBJC_SELOPT_H -#define _OBJC_SELOPT_H - -/* - DO NOT INCLUDE ANY objc HEADERS HERE - dyld USES THIS FILE AND CANNOT SEE THEM -*/ -#include <stdint.h> -#include <stdlib.h> -#ifdef SELOPT_WRITE -#include <ext/hash_map> -#endif -/* - DO NOT INCLUDE ANY objc HEADERS HERE - dyld USES THIS FILE AND CANNOT SEE THEM -*/ - -#ifndef STATIC_ASSERT -# define STATIC_ASSERT(x) _STATIC_ASSERT2(x, __LINE__) -# define _STATIC_ASSERT2(x, line) _STATIC_ASSERT3(x, line) -# define _STATIC_ASSERT3(x, line) \ - typedef struct { \ - int _static_assert[(x) ? 0 : -1]; \ - } _static_assert_ ## line __attribute__((unavailable)) -#endif - -#define SELOPT_DEBUG 0 - -#define S32(x) x = little_endian ? OSSwapHostToLittleInt32(x) : OSSwapHostToBigInt32(x) -#define S64(x) x = little_endian ? OSSwapHostToLittleInt64(x) : OSSwapHostToBigInt64(x) - -namespace objc_opt { - -typedef int32_t objc_stringhash_offset_t; -typedef uint8_t objc_stringhash_check_t; - -#ifdef SELOPT_WRITE - -// Perfect hash code is at the end of this file. - -struct perfect_hash { - uint32_t capacity; - uint32_t occupied; - uint32_t shift; - uint32_t mask; - uint64_t salt; - - uint32_t scramble[256]; - uint8_t *tab; // count == mask+1; free with delete[] - - perfect_hash() : tab(0) { } - - ~perfect_hash() { if (tab) delete[] tab; } -}; - -struct eqstr { - bool operator()(const char* s1, const char* s2) const { - return strcmp(s1, s2) == 0; - } -}; - -// cstring => cstring's vmaddress -// (used for selector names and class names) -typedef __gnu_cxx::hash_map<const char *, uint64_t, __gnu_cxx::hash<const char *>, eqstr> string_map; - -// class name => (class vmaddress, header_info vmaddress) -typedef __gnu_cxx::hash_multimap<const char *, std::pair<uint64_t, uint64_t>, __gnu_cxx::hash<const char *>, eqstr> class_map; - -static perfect_hash make_perfect(const string_map& strings); - -#endif - -static uint64_t lookup8( uint8_t *k, size_t length, uint64_t level); - -// Precomputed perfect hash table of strings. -// Base class for precomputed selector table and class table. -// Edit objc-sel-table.s and OPT_INITIALIZER if you change this structure. -struct objc_stringhash_t { - uint32_t capacity; - uint32_t occupied; - uint32_t shift; - uint32_t mask; - uint32_t zero; - uint32_t unused; // alignment pad - uint64_t salt; - - uint32_t scramble[256]; - uint8_t tab[0]; /* tab[mask+1] (always power-of-2) */ - // uint8_t checkbytes[capacity]; /* check byte for each string */ - // int32_t offsets[capacity]; /* offsets from &capacity to cstrings */ - - objc_stringhash_check_t *checkbytes() { return (objc_stringhash_check_t *)&tab[mask+1]; } - const objc_stringhash_check_t *checkbytes() const { return (const objc_stringhash_check_t *)&tab[mask+1]; } - - objc_stringhash_offset_t *offsets() { return (objc_stringhash_offset_t *)&checkbytes()[capacity]; } - const objc_stringhash_offset_t *offsets() const { return (const objc_stringhash_offset_t *)&checkbytes()[capacity]; } - - uint32_t hash(const char *key) const - { - uint64_t val = lookup8((uint8_t*)key, strlen(key), salt); - uint32_t index = (uint32_t)(val>>shift) ^ scramble[tab[val&mask]]; - return index; - } - - // The check bytes areused to reject strings that aren't in the table - // without paging in the table's cstring data. This checkbyte calculation - // catches 4785/4815 rejects when launching Safari; a perfect checkbyte - // would catch 4796/4815. - objc_stringhash_check_t checkbyte(const char *key) const - { - return - ((key[0] & 0x7) << 5) - | - (strlen(key) & 0x1f); - } - -#define INDEX_NOT_FOUND (~(uint32_t)0) - - uint32_t getIndex(const char *key) const - { - uint32_t h = hash(key); - - // Use check byte to reject without paging in the table's cstrings - objc_stringhash_check_t h_check = checkbytes()[h]; - objc_stringhash_check_t key_check = checkbyte(key); - bool check_fail = (h_check != key_check); -#if ! SELOPT_DEBUG - if (check_fail) return INDEX_NOT_FOUND; -#endif - - const char *result = (const char *)this + offsets()[h]; - if (0 != strcmp(key, result)) return INDEX_NOT_FOUND; - -#if SELOPT_DEBUG - if (check_fail) abort(); -#endif - - return h; - } - -#ifdef SELOPT_WRITE - - size_t size() - { - return sizeof(objc_stringhash_t) - + mask+1 - + capacity * sizeof(objc_stringhash_check_t) - + capacity * sizeof(objc_stringhash_offset_t); - } - - void byteswap(bool little_endian) - { - // tab and checkbytes are arrays of bytes, no swap needed - for (uint32_t i = 0; i < 256; i++) { - S32(scramble[i]); - } - objc_stringhash_offset_t *o = offsets(); - for (uint32_t i = 0; i < capacity; i++) { - S32(o[i]); - } - - S32(capacity); - S32(occupied); - S32(shift); - S32(mask); - S32(zero); - S64(salt); - } - - const char *write(uint64_t base, size_t remaining, string_map& strings) - { - if (sizeof(objc_stringhash_t) > remaining) { - return "selector section too small (metadata not optimized)"; - } - - if (strings.size() == 0) { - bzero(this, sizeof(objc_stringhash_t)); - return NULL; - } - - perfect_hash phash = make_perfect(strings); - if (phash.capacity == 0) { - return "perfect hash failed (metadata not optimized)"; - } - - // Set header - capacity = phash.capacity; - occupied = phash.occupied; - shift = phash.shift; - mask = phash.mask; - zero = 0; - unused = 0; - salt = phash.salt; - - if (size() > remaining) { - return "selector section too small (metadata not optimized)"; - } - - // Set hash data - for (uint32_t i = 0; i < 256; i++) { - scramble[i] = phash.scramble[i]; - } - for (uint32_t i = 0; i < phash.mask+1; i++) { - tab[i] = phash.tab[i]; - } - - // Set offsets to "" - for (uint32_t i = 0; i < phash.capacity; i++) { - offsets()[i] = - (objc_stringhash_offset_t)offsetof(objc_stringhash_t, zero); - } - // Set checkbytes to 0 - for (uint32_t i = 0; i < phash.capacity; i++) { - checkbytes()[i] = 0; - } - - // Set real string offsets and checkbytes -# define SHIFT (64 - 8*sizeof(objc_stringhash_offset_t)) - string_map::const_iterator s; - for (s = strings.begin(); s != strings.end(); ++s) { - int64_t offset = s->second - base; - if ((offset<<SHIFT)>>SHIFT != offset) { - return "selector offset too big (metadata not optimized)"; - } - - uint32_t h = hash(s->first); - offsets()[h] = (objc_stringhash_offset_t)offset; - checkbytes()[h] = checkbyte(s->first); - } -# undef SHIFT - - return NULL; - } - -// SELOPT_WRITE -#endif -}; - - -// Precomputed selector table. -// Edit objc-sel-table.s and OPT_INITIALIZER if you change this structure. -struct objc_selopt_t : objc_stringhash_t { - const char *get(const char *key) const - { - uint32_t h = getIndex(key); - if (h == INDEX_NOT_FOUND) return NULL; - - return (const char *)this + offsets()[h]; - } -}; - -// Precomputed class list. -// Edit objc-sel-table.s and OPT_INITIALIZER if you change these structures. - -struct objc_classheader_t { - objc_stringhash_offset_t clsOffset; - objc_stringhash_offset_t hiOffset; - - // For duplicate class names: - // clsOffset = count<<1 | 1 - // duplicated classes are duplicateOffsets[hiOffset..hiOffset+count-1] - bool isDuplicate() const { return clsOffset & 1; } - uint32_t duplicateCount() const { return clsOffset >> 1; } - uint32_t duplicateIndex() const { return hiOffset; } -}; - - -struct objc_clsopt_t : objc_stringhash_t { - // ...objc_stringhash_t fields... - // objc_classheader_t classOffsets[capacity]; /* offsets from &capacity to class_t and header_info */ - // uint32_t duplicateCount; - // objc_classheader_t duplicateOffsets[duplicatedClasses]; - - objc_classheader_t *classOffsets() { return (objc_classheader_t *)&offsets()[capacity]; } - const objc_classheader_t *classOffsets() const { return (const objc_classheader_t *)&offsets()[capacity]; } - - uint32_t& duplicateCount() { return *(uint32_t *)&classOffsets()[capacity]; } - const uint32_t& duplicateCount() const { return *(const uint32_t *)&classOffsets()[capacity]; } - - objc_classheader_t *duplicateOffsets() { return (objc_classheader_t *)(&duplicateCount()+1); } - const objc_classheader_t *duplicateOffsets() const { return (const objc_classheader_t *)(&duplicateCount()+1); } - - // 0/NULL/NULL: not found - // 1/ptr/ptr: found exactly one - // n/NULL/NULL: found N - use getClassesAndHeaders() instead - uint32_t getClassAndHeader(const char *key, void*& cls, void*& hi) const - { - uint32_t h = getIndex(key); - if (h == INDEX_NOT_FOUND) { - cls = NULL; - hi = NULL; - return 0; - } - - const objc_classheader_t& clshi = classOffsets()[h]; - if (! clshi.isDuplicate()) { - // class appears in exactly one header - cls = (void *)((const char *)this + clshi.clsOffset); - hi = (void *)((const char *)this + clshi.hiOffset); - return 1; - } - else { - // class appears in more than one header - use getClassesAndHeaders - cls = NULL; - hi = NULL; - return clshi.duplicateCount(); - } - } - - void getClassesAndHeaders(const char *key, void **cls, void **hi) const - { - uint32_t h = getIndex(key); - if (h == INDEX_NOT_FOUND) return; - - const objc_classheader_t& clshi = classOffsets()[h]; - if (! clshi.isDuplicate()) { - // class appears in exactly one header - cls[0] = (void *)((const char *)this + clshi.clsOffset); - hi[0] = (void *)((const char *)this + clshi.hiOffset); - } - else { - // class appears in more than one header - uint32_t count = clshi.duplicateCount(); - const objc_classheader_t *list = - &duplicateOffsets()[clshi.duplicateIndex()]; - for (uint32_t i = 0; i < count; i++) { - cls[i] = (void *)((const char *)this + list[i].clsOffset); - hi[i] = (void *)((const char *)this + list[i].hiOffset); - } - } - } - -#ifdef SELOPT_WRITE - - size_t size() - { - return - objc_stringhash_t::size() - + capacity * sizeof(objc_classheader_t) - + sizeof(duplicateCount()) - + duplicateCount() * sizeof(objc_classheader_t); - } - - void byteswap(bool little_endian) - { - objc_classheader_t *o; - - o = classOffsets(); - for (uint32_t i = 0; i < capacity; i++) { - S32(o[i].clsOffset); - S32(o[i].hiOffset); - } - - o = duplicateOffsets(); - for (uint32_t i = 0; i < duplicateCount(); i++) { - S32(o[i].clsOffset); - S32(o[i].hiOffset); - } - - S32(duplicateCount()); - - objc_stringhash_t::byteswap(little_endian); - } - - const char *write(uint64_t base, size_t remaining, - string_map& strings, class_map& classes, bool verbose) - { - const char *err; - err = objc_stringhash_t::write(base, remaining, strings); - if (err) return err; - - if (size() > remaining) { - return "selector section too small (metadata not optimized)"; - } - - // Set class offsets to &zero - objc_stringhash_offset_t zeroOffset = - (objc_stringhash_offset_t)offsetof(objc_stringhash_t, zero); - for (uint32_t i = 0; i < capacity; i++) { - classOffsets()[i].clsOffset = zeroOffset; - classOffsets()[i].hiOffset = zeroOffset; - } - - // Set real class offsets -# define SHIFT (64 - 8*sizeof(objc_stringhash_offset_t)) - class_map::const_iterator c; - for (c = classes.begin(); c != classes.end(); ++c) { - uint32_t h = getIndex(c->first); - if (h == INDEX_NOT_FOUND) { - return "class list busted (metadata not optimized)"; - } - - if (classOffsets()[h].clsOffset != zeroOffset) { - // already did this class - continue; - } - - uint32_t count = classes.count(c->first); - if (count == 1) { - // only one class with this name - - int64_t coff = c->second.first - base; - int64_t hoff = c->second.second - base; - if ((coff<<SHIFT)>>SHIFT != coff) { - return "class offset too big (metadata not optimized)"; - } - if ((hoff<<SHIFT)>>SHIFT != hoff) { - return "header offset too big (metadata not optimized)"; - } - - classOffsets()[h].clsOffset = (objc_stringhash_offset_t)coff; - classOffsets()[h].hiOffset = (objc_stringhash_offset_t)hoff; - } - else { - // class name has duplicates - write them all now - if (verbose) { - fprintf(stderr, "update_dyld_shared_cache: %u duplicates of Objective-C class %s\n", count, c->first); - } - - uint32_t dest = duplicateCount(); - duplicateCount() += count; - if (size() > remaining) { - return "selector section too small (metadata not optimized)"; - } - - // classOffsets() instead contains count and array index - classOffsets()[h].clsOffset = count*2 + 1; - classOffsets()[h].hiOffset = dest; - - std::pair<class_map::const_iterator, class_map::const_iterator> - duplicates = classes.equal_range(c->first); - class_map::const_iterator dup; - for (dup = duplicates.first; dup != duplicates.second; ++dup) { - int64_t coff = dup->second.first - base; - int64_t hoff = dup->second.second - base; - if ((coff<<SHIFT)>>SHIFT != coff) { - return "class offset too big (metadata not optimized)"; - } - if ((hoff<<SHIFT)>>SHIFT != hoff) { - return "header offset too big (metadata not optimized)"; - } - - duplicateOffsets()[dest].clsOffset = (objc_stringhash_offset_t)coff; - duplicateOffsets()[dest].hiOffset = (objc_stringhash_offset_t)hoff; - dest++; - } - } - } -# undef SHIFT - - return NULL; - } - -// SELOPT_WRITE -#endif -}; - -// Precomputed image list. -struct objc_headeropt_t; - -// Precomputed class list. -struct objc_clsopt_t; - -// Edit objc-sel-table.s if you change this value. -enum { VERSION = 13 }; - -// Top-level optimization structure. -// Edit objc-sel-table.s and OPT_INITIALIZER if you change this structure. -struct objc_opt_t { - uint32_t version; - int32_t selopt_offset; - int32_t headeropt_offset; - int32_t clsopt_offset; - - const objc_selopt_t* selopt() const { - if (selopt_offset == 0) return NULL; - return (objc_selopt_t *)((uint8_t *)this + selopt_offset); - } - objc_selopt_t* selopt() { - if (selopt_offset == 0) return NULL; - return (objc_selopt_t *)((uint8_t *)this + selopt_offset); - } - - struct objc_headeropt_t* headeropt() const { - if (headeropt_offset == 0) return NULL; - return (struct objc_headeropt_t *)((uint8_t *)this + headeropt_offset); - } - - struct objc_clsopt_t* clsopt() const { - if (clsopt_offset == 0) return NULL; - return (objc_clsopt_t *)((uint8_t *)this + clsopt_offset); - } -}; - -// sizeof(objc_opt_t) must be pointer-aligned -STATIC_ASSERT(sizeof(objc_opt_t) % sizeof(void*) == 0); - -// Initializer for empty opt of type uint32_t[]. -#define X8(x) x, x, x, x, x, x, x, x -#define X64(x) X8(x), X8(x), X8(x), X8(x), X8(x), X8(x), X8(x), X8(x) -#define X256(x) X64(x), X64(x), X64(x), X64(x) -#define OPT_INITIALIZER { \ - /* objc_opt_t */ \ - objc_opt::VERSION, 16, 0, 0, \ - /* objc_selopt_t */ \ - 4, 4, 63, 3, 0, 0, 0,0, X256(0), 0, 0, 16, 16, 16, 16 \ - /* no objc_headeropt_t */ \ - /* no objc_clsopt_t */ \ -} - - -/* --------------------------------------------------------------------- -mix -- mix 3 64-bit values reversibly. -mix() takes 48 machine instructions, but only 24 cycles on a superscalar - machine (like Intel's new MMX architecture). It requires 4 64-bit - registers for 4::2 parallelism. -All 1-bit deltas, all 2-bit deltas, all deltas composed of top bits of - (a,b,c), and all deltas of bottom bits were tested. All deltas were - tested both on random keys and on keys that were nearly all zero. - These deltas all cause every bit of c to change between 1/3 and 2/3 - of the time (well, only 113/400 to 287/400 of the time for some - 2-bit delta). These deltas all cause at least 80 bits to change - among (a,b,c) when the mix is run either forward or backward (yes it - is reversible). -This implies that a hash using mix64 has no funnels. There may be - characteristics with 3-bit deltas or bigger, I didn't test for - those. --------------------------------------------------------------------- -*/ -#define mix64(a,b,c) \ -{ \ - a -= b; a -= c; a ^= (c>>43); \ - b -= c; b -= a; b ^= (a<<9); \ - c -= a; c -= b; c ^= (b>>8); \ - a -= b; a -= c; a ^= (c>>38); \ - b -= c; b -= a; b ^= (a<<23); \ - c -= a; c -= b; c ^= (b>>5); \ - a -= b; a -= c; a ^= (c>>35); \ - b -= c; b -= a; b ^= (a<<49); \ - c -= a; c -= b; c ^= (b>>11); \ - a -= b; a -= c; a ^= (c>>12); \ - b -= c; b -= a; b ^= (a<<18); \ - c -= a; c -= b; c ^= (b>>22); \ -} - -/* --------------------------------------------------------------------- -hash() -- hash a variable-length key into a 64-bit value - k : the key (the unaligned variable-length array of bytes) - len : the length of the key, counting by bytes - level : can be any 8-byte value -Returns a 64-bit value. Every bit of the key affects every bit of -the return value. No funnels. Every 1-bit and 2-bit delta achieves -avalanche. About 41+5len instructions. - -The best hash table sizes are powers of 2. There is no need to do -mod a prime (mod is sooo slow!). If you need less than 64 bits, -use a bitmask. For example, if you need only 10 bits, do - h = (h & hashmask(10)); -In which case, the hash table should have hashsize(10) elements. - -If you are hashing n strings (uint8_t **)k, do it like this: - for (i=0, h=0; i<n; ++i) h = hash( k[i], len[i], h); - -By Bob Jenkins, Jan 4 1997. bob_jenkins@burtleburtle.net. You may -use this code any way you wish, private, educational, or commercial, -but I would appreciate if you give me credit. - -See http://burtleburtle.net/bob/hash/evahash.html -Use for hash table lookup, or anything where one collision in 2^^64 -is acceptable. Do NOT use for cryptographic purposes. --------------------------------------------------------------------- -*/ - -static uint64_t lookup8( uint8_t *k, size_t length, uint64_t level) -// uint8_t *k; /* the key */ -// uint64_t length; /* the length of the key */ -// uint64_t level; /* the previous hash, or an arbitrary value */ -{ - uint64_t a,b,c; - size_t len; - - /* Set up the internal state */ - len = length; - a = b = level; /* the previous hash value */ - c = 0x9e3779b97f4a7c13LL; /* the golden ratio; an arbitrary value */ - - /*---------------------------------------- handle most of the key */ - while (len >= 24) - { - a += (k[0] +((uint64_t)k[ 1]<< 8)+((uint64_t)k[ 2]<<16)+((uint64_t)k[ 3]<<24) - +((uint64_t)k[4 ]<<32)+((uint64_t)k[ 5]<<40)+((uint64_t)k[ 6]<<48)+((uint64_t)k[ 7]<<56)); - b += (k[8] +((uint64_t)k[ 9]<< 8)+((uint64_t)k[10]<<16)+((uint64_t)k[11]<<24) - +((uint64_t)k[12]<<32)+((uint64_t)k[13]<<40)+((uint64_t)k[14]<<48)+((uint64_t)k[15]<<56)); - c += (k[16] +((uint64_t)k[17]<< 8)+((uint64_t)k[18]<<16)+((uint64_t)k[19]<<24) - +((uint64_t)k[20]<<32)+((uint64_t)k[21]<<40)+((uint64_t)k[22]<<48)+((uint64_t)k[23]<<56)); - mix64(a,b,c); - k += 24; len -= 24; - } - - /*------------------------------------- handle the last 23 bytes */ - c += length; - switch(len) /* all the case statements fall through */ - { - case 23: c+=((uint64_t)k[22]<<56); - case 22: c+=((uint64_t)k[21]<<48); - case 21: c+=((uint64_t)k[20]<<40); - case 20: c+=((uint64_t)k[19]<<32); - case 19: c+=((uint64_t)k[18]<<24); - case 18: c+=((uint64_t)k[17]<<16); - case 17: c+=((uint64_t)k[16]<<8); - /* the first byte of c is reserved for the length */ - case 16: b+=((uint64_t)k[15]<<56); - case 15: b+=((uint64_t)k[14]<<48); - case 14: b+=((uint64_t)k[13]<<40); - case 13: b+=((uint64_t)k[12]<<32); - case 12: b+=((uint64_t)k[11]<<24); - case 11: b+=((uint64_t)k[10]<<16); - case 10: b+=((uint64_t)k[ 9]<<8); - case 9: b+=((uint64_t)k[ 8]); - case 8: a+=((uint64_t)k[ 7]<<56); - case 7: a+=((uint64_t)k[ 6]<<48); - case 6: a+=((uint64_t)k[ 5]<<40); - case 5: a+=((uint64_t)k[ 4]<<32); - case 4: a+=((uint64_t)k[ 3]<<24); - case 3: a+=((uint64_t)k[ 2]<<16); - case 2: a+=((uint64_t)k[ 1]<<8); - case 1: a+=((uint64_t)k[ 0]); - /* case 0: nothing left to add */ - } - mix64(a,b,c); - /*-------------------------------------------- report the result */ - return c; -} - - -#ifdef SELOPT_WRITE - -/* ------------------------------------------------------------------------------- -This generates a minimal perfect hash function. That means, given a -set of n keys, this determines a hash function that maps each of -those keys into a value in 0..n-1 with no collisions. - -The perfect hash function first uses a normal hash function on the key -to determine (a,b) such that the pair (a,b) is distinct for all -keys, then it computes a^scramble[tab[b]] to get the final perfect hash. -tab[] is an array of 1-byte values and scramble[] is a 256-term array of -2-byte or 4-byte values. If there are n keys, the length of tab[] is a -power of two between n/3 and n. - -I found the idea of computing distinct (a,b) values in "Practical minimal -perfect hash functions for large databases", Fox, Heath, Chen, and Daoud, -Communications of the ACM, January 1992. They found the idea in Chichelli -(CACM Jan 1980). Beyond that, our methods differ. - -The key is hashed to a pair (a,b) where a in 0..*alen*-1 and b in -0..*blen*-1. A fast hash function determines both a and b -simultaneously. Any decent hash function is likely to produce -hashes so that (a,b) is distinct for all pairs. I try the hash -using different values of *salt* until all pairs are distinct. - -The final hash is (a XOR scramble[tab[b]]). *scramble* is a -predetermined mapping of 0..255 into 0..smax-1. *tab* is an -array that we fill in in such a way as to make the hash perfect. - -First we fill in all values of *tab* that are used by more than one -key. We try all possible values for each position until one works. - -This leaves m unmapped keys and m values that something could hash to. -If you treat unmapped keys as lefthand nodes and unused hash values -as righthand nodes, and draw a line connecting each key to each hash -value it could map to, you get a bipartite graph. We attempt to -find a perfect matching in this graph. If we succeed, we have -determined a perfect hash for the whole set of keys. - -*scramble* is used because (a^tab[i]) clusters keys around *a*. ------------------------------------------------------------------------------- -*/ - -typedef uint64_t ub8; -#define UB8MAXVAL 0xffffffffffffffffLL -#define UB8BITS 64 -typedef uint32_t ub4; -#define UB4MAXVAL 0xffffffff -#define UB4BITS 32 -typedef uint16_t ub2; -#define UB2MAXVAL 0xffff -#define UB2BITS 16 -typedef uint8_t ub1; -#define UB1MAXVAL 0xff -#define UB1BITS 8 - -#define TRUE 1 -#define FALSE 0 - -#define SCRAMBLE_LEN 256 // ((ub4)1<<16) /* length of *scramble* */ -#define RETRY_INITKEY 2048 /* number of times to try to find distinct (a,b) */ -#define RETRY_PERFECT 4 /* number of times to try to make a perfect hash */ - - -/* representation of a key */ -struct key -{ - ub1 *name_k; /* the actual key */ - ub4 len_k; /* the length of the actual key */ - ub4 hash_k; /* the initial hash value for this key */ -/* beyond this point is mapping-dependent */ - ub4 a_k; /* a, of the key maps to (a,b) */ - ub4 b_k; /* b, of the key maps to (a,b) */ - struct key *nextb_k; /* next key with this b */ -}; -typedef struct key key; - -/* things indexed by b of original (a,b) pair */ -struct bstuff -{ - ub2 val_b; /* hash=a^tabb[b].val_b */ - key *list_b; /* tabb[i].list_b is list of keys with b==i */ - ub4 listlen_b; /* length of list_b */ - ub4 water_b; /* high watermark of who has visited this map node */ -}; -typedef struct bstuff bstuff; - -/* things indexed by final hash value */ -struct hstuff -{ - key *key_h; /* tabh[i].key_h is the key with a hash of i */ -}; -typedef struct hstuff hstuff; - -/* things indexed by queue position */ -struct qstuff -{ - bstuff *b_q; /* b that currently occupies this hash */ - ub4 parent_q; /* queue position of parent that could use this hash */ - ub2 newval_q; /* what to change parent tab[b] to to use this hash */ - ub2 oldval_q; /* original value of tab[b] */ -}; -typedef struct qstuff qstuff; - - -/* ------------------------------------------------------------------------------- -Find the mapping that will produce a perfect hash ------------------------------------------------------------------------------- -*/ - -/* return the ceiling of the log (base 2) of val */ -static ub4 log2u(ub4 val) -{ - ub4 i; - for (i=0; ((ub4)1<<i) < val; ++i) - ; - return i; -} - -/* compute p(x), where p is a permutation of 0..(1<<nbits)-1 */ -/* permute(0)=0. This is intended and useful. */ -static ub4 permute(ub4 x, ub4 nbits) -// ub4 x; /* input, a value in some range */ -// ub4 nbits; /* input, number of bits in range */ -{ - int i; - int mask = ((ub4)1<<nbits)-1; /* all ones */ - int const2 = 1+nbits/2; - int const3 = 1+nbits/3; - int const4 = 1+nbits/4; - int const5 = 1+nbits/5; - for (i=0; i<20; ++i) - { - x = (x+(x<<const2)) & mask; - x = (x^(x>>const3)); - x = (x+(x<<const4)) & mask; - x = (x^(x>>const5)); - } - return x; -} - -/* initialize scramble[] with distinct random values in 0..smax-1 */ -static void scrambleinit(ub4 *scramble, ub4 smax) -// ub4 *scramble; /* hash is a^scramble[tab[b]] */ -// ub4 smax; /* scramble values should be in 0..smax-1 */ -{ - ub4 i; - - /* fill scramble[] with distinct random integers in 0..smax-1 */ - for (i=0; i<SCRAMBLE_LEN; ++i) - { - scramble[i] = permute(i, log2u(smax)); - } -} - - -/* - * put keys in tabb according to key->b_k - * check if the initial hash might work - */ -static int inittab(bstuff *tabb, ub4 blen, key *keys, ub4 nkeys, int complete) -// bstuff *tabb; /* output, list of keys with b for (a,b) */ -// ub4 blen; /* length of tabb */ -// key *keys; /* list of keys already hashed */ -// int complete; /* TRUE means to complete init despite collisions */ -{ - int nocollision = TRUE; - ub4 i; - - memset((void *)tabb, 0, (size_t)(sizeof(bstuff)*blen)); - - /* Two keys with the same (a,b) guarantees a collision */ - for (i = 0; i < nkeys; i++) { - key *mykey = keys+i; - key *otherkey; - - for (otherkey=tabb[mykey->b_k].list_b; - otherkey; - otherkey=otherkey->nextb_k) - { - if (mykey->a_k == otherkey->a_k) - { - nocollision = FALSE; - if (!complete) - return FALSE; - } - } - ++tabb[mykey->b_k].listlen_b; - mykey->nextb_k = tabb[mykey->b_k].list_b; - tabb[mykey->b_k].list_b = mykey; - } - - /* no two keys have the same (a,b) pair */ - return nocollision; -} - - -/* Do the initial hash for normal mode (use lookup and checksum) */ -static void initnorm(key *keys, ub4 nkeys, ub4 alen, ub4 blen, ub4 smax, ub8 salt) -// key *keys; /* list of all keys */ -// ub4 alen; /* (a,b) has a in 0..alen-1, a power of 2 */ -// ub4 blen; /* (a,b) has b in 0..blen-1, a power of 2 */ -// ub4 smax; /* maximum range of computable hash values */ -// ub4 salt; /* used to initialize the hash function */ -// gencode *final; /* output, code for the final hash */ -{ - ub4 loga = log2u(alen); /* log based 2 of blen */ - ub4 i; - for (i = 0; i < nkeys; i++) { - key *mykey = keys+i; - ub8 hash = lookup8(mykey->name_k, mykey->len_k, salt); - mykey->a_k = (loga > 0) ? hash>>(UB8BITS-loga) : 0; - mykey->b_k = (blen > 1) ? hash&(blen-1) : 0; - } -} - - -/* Try to apply an augmenting list */ -static int apply(bstuff *tabb, hstuff *tabh, qstuff *tabq, ub4 blen, ub4 *scramble, ub4 tail, int rollback) -// bstuff *tabb; -// hstuff *tabh; -// qstuff *tabq; -// ub4 blen; -// ub4 *scramble; -// ub4 tail; -// int rollback; /* FALSE applies augmenting path, TRUE rolls back */ -{ - ub4 hash; - key *mykey; - bstuff *pb; - ub4 child; - ub4 parent; - ub4 stabb; /* scramble[tab[b]] */ - - /* walk from child to parent */ - for (child=tail-1; child; child=parent) - { - parent = tabq[child].parent_q; /* find child's parent */ - pb = tabq[parent].b_q; /* find parent's list of siblings */ - - /* erase old hash values */ - stabb = scramble[pb->val_b]; - for (mykey=pb->list_b; mykey; mykey=mykey->nextb_k) - { - hash = mykey->a_k^stabb; - if (mykey == tabh[hash].key_h) - { /* erase hash for all of child's siblings */ - tabh[hash].key_h = (key *)0; - } - } - - /* change pb->val_b, which will change the hashes of all parent siblings */ - pb->val_b = (rollback ? tabq[child].oldval_q : tabq[child].newval_q); - - /* set new hash values */ - stabb = scramble[pb->val_b]; - for (mykey=pb->list_b; mykey; mykey=mykey->nextb_k) - { - hash = mykey->a_k^stabb; - if (rollback) - { - if (parent == 0) continue; /* root never had a hash */ - } - else if (tabh[hash].key_h) - { - /* very rare: roll back any changes */ - apply(tabb, tabh, tabq, blen, scramble, tail, TRUE); - return FALSE; /* failure, collision */ - } - tabh[hash].key_h = mykey; - } - } - return TRUE; -} - - -/* -------------------------------------------------------------------------------- -augment(): Add item to the mapping. - -Construct a spanning tree of *b*s with *item* as root, where each -parent can have all its hashes changed (by some new val_b) with -at most one collision, and each child is the b of that collision. - -I got this from Tarjan's "Data Structures and Network Algorithms". The -path from *item* to a *b* that can be remapped with no collision is -an "augmenting path". Change values of tab[b] along the path so that -the unmapped key gets mapped and the unused hash value gets used. - -Assuming 1 key per b, if m out of n hash values are still unused, -you should expect the transitive closure to cover n/m nodes before -an unused node is found. Sum(i=1..n)(n/i) is about nlogn, so expect -this approach to take about nlogn time to map all single-key b's. -------------------------------------------------------------------------------- -*/ -static int augment(bstuff *tabb, hstuff *tabh, qstuff *tabq, ub4 blen, ub4 *scramble, ub4 smax, bstuff *item, ub4 nkeys, - ub4 highwater) -// bstuff *tabb; /* stuff indexed by b */ -// hstuff *tabh; /* which key is associated with which hash, indexed by hash */ -// qstuff *tabq; /* queue of *b* values, this is the spanning tree */ -// ub4 blen; /* length of tabb */ -// ub4 *scramble; /* final hash is a^scramble[tab[b]] */ -// ub4 smax; /* highest value in scramble */ -// bstuff *item; /* &tabb[b] for the b to be mapped */ -// ub4 nkeys; /* final hash must be in 0..nkeys-1 */ -// ub4 highwater; /* a value higher than any now in tabb[].water_b */ -{ - ub4 q; /* current position walking through the queue */ - ub4 tail; /* tail of the queue. 0 is the head of the queue. */ - ub4 limit=UB1MAXVAL+1; - ub4 highhash = smax; - - /* initialize the root of the spanning tree */ - tabq[0].b_q = item; - tail = 1; - - /* construct the spanning tree by walking the queue, add children to tail */ - for (q=0; q<tail; ++q) - { - bstuff *myb = tabq[q].b_q; /* the b for this node */ - ub4 i; /* possible value for myb->val_b */ - - if (q == 1) - break; /* don't do transitive closure */ - - for (i=0; i<limit; ++i) - { - bstuff *childb = (bstuff *)0; /* the b that this i maps to */ - key *mykey; /* for walking through myb's keys */ - - for (mykey = myb->list_b; mykey; mykey=mykey->nextb_k) - { - key *childkey; - ub4 hash = mykey->a_k^scramble[i]; - - if (hash >= highhash) break; /* out of bounds */ - childkey = tabh[hash].key_h; - - if (childkey) - { - bstuff *hitb = &tabb[childkey->b_k]; - - if (childb) - { - if (childb != hitb) break; /* hit at most one child b */ - } - else - { - childb = hitb; /* remember this as childb */ - if (childb->water_b == highwater) break; /* already explored */ - } - } - } - if (mykey) continue; /* myb with i has multiple collisions */ - - /* add childb to the queue of reachable things */ - if (childb) childb->water_b = highwater; - tabq[tail].b_q = childb; - tabq[tail].newval_q = i; /* how to make parent (myb) use this hash */ - tabq[tail].oldval_q = myb->val_b; /* need this for rollback */ - tabq[tail].parent_q = q; - ++tail; - - if (!childb) - { /* found an *i* with no collisions? */ - /* try to apply the augmenting path */ - if (apply(tabb, tabh, tabq, blen, scramble, tail, FALSE)) - return TRUE; /* success, item was added to the perfect hash */ - - --tail; /* don't know how to handle such a child! */ - } - } - } - return FALSE; -} - - -/* find a mapping that makes this a perfect hash */ -static int perfect(bstuff *tabb, hstuff *tabh, qstuff *tabq, ub4 blen, ub4 smax, ub4 *scramble, ub4 nkeys) -{ - ub4 maxkeys; /* maximum number of keys for any b */ - ub4 i, j; - -#if SELOPT_DEBUG - fprintf(stderr, " blen %d smax %d nkeys %d\n", blen, smax, nkeys); -#endif - - /* clear any state from previous attempts */ - memset((void *)tabh, 0, sizeof(hstuff)*smax); - memset((void *)tabq, 0, sizeof(qstuff)*(blen+1)); - - for (maxkeys=0,i=0; i<blen; ++i) - if (tabb[i].listlen_b > maxkeys) - maxkeys = tabb[i].listlen_b; - - /* In descending order by number of keys, map all *b*s */ - for (j=maxkeys; j>0; --j) - for (i=0; i<blen; ++i) - if (tabb[i].listlen_b == j) - if (!augment(tabb, tabh, tabq, blen, scramble, smax, &tabb[i], nkeys, - i+1)) - { - return FALSE; - } - - /* Success! We found a perfect hash of all keys into 0..nkeys-1. */ - return TRUE; -} - - -/* guess initial values for alen and blen */ -static void initalen(ub4 *alen, ub4 *blen, ub4 smax, ub4 nkeys) -// ub4 *alen; /* output, initial alen */ -// ub4 *blen; /* output, initial blen */ -// ub4 smax; /* input, power of two greater or equal to max hash value */ -// ub4 nkeys; /* number of keys being hashed */ -{ - /* - * Find initial *alen, *blen - * Initial alen and blen values were found empirically. Some factors: - * - * If smax<256 there is no scramble, so tab[b] needs to cover 0..smax-1. - * - * alen and blen must be powers of 2 because the values in 0..alen-1 and - * 0..blen-1 are produced by applying a bitmask to the initial hash function. - * - * alen must be less than smax, in fact less than nkeys, because otherwise - * there would often be no i such that a^scramble[i] is in 0..nkeys-1 for - * all the *a*s associated with a given *b*, so there would be no legal - * value to assign to tab[b]. This only matters when we're doing a minimal - * perfect hash. - * - * It takes around 800 trials to find distinct (a,b) with nkey=smax*(5/8) - * and alen*blen = smax*smax/32. - * - * Values of blen less than smax/4 never work, and smax/2 always works. - * - * We want blen as small as possible because it is the number of bytes in - * the huge array we must create for the perfect hash. - * - * When nkey <= smax*(5/8), blen=smax/4 works much more often with - * alen=smax/8 than with alen=smax/4. Above smax*(5/8), blen=smax/4 - * doesn't seem to care whether alen=smax/8 or alen=smax/4. I think it - * has something to do with 5/8 = 1/8 * 5. For example examine 80000, - * 85000, and 90000 keys with different values of alen. This only matters - * if we're doing a minimal perfect hash. - * - * When alen*blen <= 1<<UB4BITS, the initial hash must produce one integer. - * Bigger than that it must produce two integers, which increases the - * cost of the hash per character hashed. - */ - *alen = smax; /* no reason to restrict alen to smax/2 */ - *blen = ((nkeys <= smax*0.6) ? smax/16 : - (nkeys <= smax*0.8) ? smax/8 : smax/4); - - if (*alen < 1) *alen = 1; - if (*blen < 1) *blen = 1; - -#if SELOPT_DEBUG - fprintf(stderr, "alen %d blen %d smax %d nkeys %d\n", *alen, *blen, smax, nkeys); -#endif -} - -/* -** Try to find a perfect hash function. -** Return the successful initializer for the initial hash. -** Return 0 if no perfect hash could be found. -*/ -static int findhash(bstuff **tabb, ub4 *alen, ub4 *blen, ub8 *salt, - ub4 *scramble, ub4 smax, key *keys, ub4 nkeys) -// bstuff **tabb; /* output, tab[] of the perfect hash, length *blen */ -// ub4 *alen; /* output, 0..alen-1 is range for a of (a,b) */ -// ub4 *blen; /* output, 0..blen-1 is range for b of (a,b) */ -// ub4 *salt; /* output, initializes initial hash */ -// ub4 *scramble; /* input, hash = a^scramble[tab[b]] */ -// ub4 smax; /* input, scramble[i] in 0..smax-1 */ -// key *keys; /* input, keys to hash */ -// ub4 nkeys; /* input, number of keys being hashed */ -{ - ub4 bad_initkey; /* how many times did initkey fail? */ - ub4 bad_perfect; /* how many times did perfect fail? */ - ub4 si; /* trial initializer for initial hash */ - ub4 maxalen; - hstuff *tabh; /* table of keys indexed by hash value */ - qstuff *tabq; /* table of stuff indexed by queue value, used by augment */ - - /* guess initial values for alen and blen */ - initalen(alen, blen, smax, nkeys); - - scrambleinit(scramble, smax); - - maxalen = smax; - - /* allocate working memory */ - *tabb = new bstuff[*blen]; - tabq = new qstuff[*blen+1]; - tabh = new hstuff[smax]; - - /* Actually find the perfect hash */ - *salt = 0; - bad_initkey = 0; - bad_perfect = 0; - for (si=1; ; ++si) - { - ub4 rslinit; - /* Try to find distinct (A,B) for all keys */ - *salt = si * 0x9e3779b97f4a7c13LL; /* golden ratio (arbitrary value) */ - initnorm(keys, nkeys, *alen, *blen, smax, *salt); - rslinit = inittab(*tabb, *blen, keys, nkeys, FALSE); - if (rslinit == 0) - { - /* didn't find distinct (a,b) */ - if (++bad_initkey >= RETRY_INITKEY) - { - /* Try to put more bits in (A,B) to make distinct (A,B) more likely */ - if (*alen < maxalen) - { - *alen *= 2; - } - else if (*blen < smax) - { - *blen *= 2; - delete[] tabq; - delete[] *tabb; - *tabb = new bstuff[*blen]; - tabq = new qstuff[*blen+1]; - } - bad_initkey = 0; - bad_perfect = 0; - } - continue; /* two keys have same (a,b) pair */ - } - - /* Given distinct (A,B) for all keys, build a perfect hash */ - if (!perfect(*tabb, tabh, tabq, *blen, smax, scramble, nkeys)) - { - if (++bad_perfect >= RETRY_PERFECT) - { - if (*blen < smax) - { - *blen *= 2; - delete[] *tabb; - delete[] tabq; - *tabb = new bstuff[*blen]; - tabq = new qstuff[*blen+1]; - --si; /* we know this salt got distinct (A,B) */ - } - else - { - return 0; - } - bad_perfect = 0; - } - continue; - } - - break; - } - - /* free working memory */ - delete[] tabh; - delete[] tabq; - - return 1; -} - -/* ------------------------------------------------------------------------------- -Input/output type routines ------------------------------------------------------------------------------- -*/ - -/* get the list of keys */ -static void getkeys(key **keys, ub4 *nkeys, const string_map& strings) -{ - key *buf = new key[strings.size()]; - size_t i; - string_map::const_iterator s; - for (i = 0, s = strings.begin(); s != strings.end(); ++s, ++i) { - key *mykey = buf+i; - mykey->name_k = (ub1 *)s->first; - mykey->len_k = (ub4)strlen(s->first); - } - *keys = buf; - *nkeys = strings.size(); -} - - -static perfect_hash -make_perfect(const string_map& strings) -{ - ub4 nkeys; /* number of keys */ - key *keys; /* head of list of keys */ - bstuff *tab; /* table indexed by b */ - ub4 smax; /* scramble[] values in 0..smax-1, a power of 2 */ - ub4 alen; /* a in 0..alen-1, a power of 2 */ - ub4 blen; /* b in 0..blen-1, a power of 2 */ - ub8 salt; /* a parameter to the hash function */ - ub4 scramble[SCRAMBLE_LEN]; /* used in final hash function */ - int ok; - int i; - perfect_hash result; - - /* read in the list of keywords */ - getkeys(&keys, &nkeys, strings); - - /* find the hash */ - smax = ((ub4)1<<log2u(nkeys)); - ok = findhash(&tab, &alen, &blen, &salt, - scramble, smax, keys, nkeys); - if (!ok) { - smax = 2 * ((ub4)1<<log2u(nkeys)); - ok = findhash(&tab, &alen, &blen, &salt, - scramble, smax, keys, nkeys); - } - if (!ok) { - bzero(&result, sizeof(result)); - } else { - /* build the tables */ - result.capacity = smax; - result.occupied = nkeys; - result.shift = UB8BITS - log2u(alen); - result.mask = blen - 1; - result.salt = salt; - - result.tab = new uint8_t[blen]; - for (i = 0; i < blen; i++) { - result.tab[i] = tab[i].val_b; - } - for (i = 0; i < 256; i++) { - result.scramble[i] = scramble[i]; - } - } - - delete[] keys; - delete[] tab; - - return result; -} - -// SELOPT_WRITE -#endif - -// namespace objc_selopt -}; - -#undef S32 -#undef S64 - -#endif diff --git a/objc/objc-runtime/include/os/tsd.h b/objc/objc-runtime/include/os/tsd.h deleted file mode 100644 index 279f65d..0000000 --- a/objc/objc-runtime/include/os/tsd.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2012 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_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. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * 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_OSREFERENCE_LICENSE_HEADER_END@ - */ - -#ifndef OS_TSD_H -#define OS_TSD_H - -#include <stdint.h> - -/* The low nine slots of the TSD are reserved for libsyscall usage. */ -#define __TSD_RESERVED_BASE 0 -#define __TSD_RESERVED_MAX 9 - -#define __TSD_THREAD_SELF 0 -#define __TSD_ERRNO 1 -#define __TSD_MIG_REPLY 2 -#define __TSD_SEMAPHORE_CACHE 9 - - -__attribute__((always_inline)) -static __inline__ unsigned int -_os_cpu_number(void) -{ - /* Not yet implemented */ - return 0; -} - -__attribute__((always_inline)) -static __inline__ void* -_os_tsd_get_direct(unsigned long slot) -{ - void *ret; -#if defined(__i386__) || defined(__x86_64__) - __asm__("mov %%gs:%1, %0" : "=r" (ret) : "m" (*(void **)(slot * sizeof(void *)))); -#endif - - - return ret; -} - -__attribute__((always_inline)) -static __inline__ int -_os_tsd_set_direct(unsigned long slot, void* val) -{ -#if defined(__i386__) && defined(__PIC__) - __asm__("movl %1, %%gs:%0" : "=m" (*(void **)(slot * sizeof(void *))) : "rn" (val)); -#elif defined(__i386__) && !defined(__PIC__) - __asm__("movl %1, %%gs:%0" : "=m" (*(void **)(slot * sizeof(void *))) : "ri" (val)); -#elif defined(__x86_64__) - __asm__("movq %1, %%gs:%0" : "=m" (*(void **)(slot * sizeof(void *))) : "rn" (val)); -#endif - - return 0; -} - -#endif diff --git a/objc/objc-runtime/include/pthread/qos_private.h b/objc/objc-runtime/include/pthread/qos_private.h deleted file mode 100644 index 46763fa..0000000 --- a/objc/objc-runtime/include/pthread/qos_private.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2013-2014 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 _QOS_PRIVATE_H -#define _QOS_PRIVATE_H - -#include <pthread/qos.h> -#include <sys/qos_private.h> - -#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL -// allow __DARWIN_C_LEVEL to turn off the use of mach_port_t -#include <mach/port.h> -#endif - -// pthread_priority_t is an on opaque integer that is guaranteed to be ordered such that -// combations of QoS classes and relative priorities are ordered numerically, according to -// their combined priority. -typedef unsigned long pthread_priority_t; - -// masks for splitting the handling the contents of a pthread_priority_t, the mapping from -// qos_class_t to the class bits, however, is intentionally not exposed. -#define _PTHREAD_PRIORITY_FLAGS_MASK (~0xffffff) -#define _PTHREAD_PRIORITY_QOS_CLASS_MASK 0x00ffff00 -#define _PTHREAD_PRIORITY_QOS_CLASS_SHIFT (8ull) -#define _PTHREAD_PRIORITY_PRIORITY_MASK 0x000000ff -#define _PTHREAD_PRIORITY_PRIORITY_SHIFT (0) - -#define _PTHREAD_PRIORITY_OVERCOMMIT_FLAG 0x80000000 -#define _PTHREAD_PRIORITY_INHERIT_FLAG 0x40000000 -#define _PTHREAD_PRIORITY_ROOTQUEUE_FLAG 0x20000000 -#define _PTHREAD_PRIORITY_ENFORCE_FLAG 0x10000000 -#define _PTHREAD_PRIORITY_OVERRIDE_FLAG 0x08000000 - -// redeffed here to avoid leaving __QOS_ENUM defined in the public header -#define __QOS_ENUM(name, type, ...) enum { __VA_ARGS__ }; typedef type name##_t -#define __QOS_AVAILABLE_STARTING(x, y) - -#if defined(__has_feature) && defined(__has_extension) -#if __has_feature(objc_fixed_enum) || __has_extension(cxx_strong_enums) -#undef __QOS_ENUM -#define __QOS_ENUM(name, type, ...) typedef enum : type { __VA_ARGS__ } name##_t -#endif -#if __has_feature(enumerator_attributes) -#undef __QOS_AVAILABLE_STARTING -#define __QOS_AVAILABLE_STARTING __OSX_AVAILABLE_STARTING -#endif -#endif - -__QOS_ENUM(_pthread_set_flags, unsigned int, - _PTHREAD_SET_SELF_QOS_FLAG - __QOS_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) = 0x1, - _PTHREAD_SET_SELF_VOUCHER_FLAG - __QOS_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) = 0x2, - _PTHREAD_SET_SELF_FIXEDPRIORITY_FLAG - __QOS_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) = 0x4, -); - -#undef __QOS_ENUM -#undef __QOS_AVAILABLE_STARTING - -#ifndef KERNEL - -__BEGIN_DECLS - -/*! - * @function pthread_set_qos_class_np - * - * @abstract - * Sets the requested QOS class and relative priority of the current thread. - * - * @discussion - * The QOS class and relative priority represent an overall combination of - * system quality of service attributes on a thread. - * - * Subsequent calls to interfaces such as pthread_setschedparam() that are - * incompatible or in conflict with the QOS class system will unset the QOS - * class requested with this interface and pthread_get_qos_class_np() will - * return QOS_CLASS_UNSPECIFIED thereafter. A thread so modified is permanently - * opted-out of the QOS class system and calls to this function to request a QOS - * class for such a thread will fail and return EPERM. - * - * @param __pthread - * The current thread as returned by pthread_self(). - * EINVAL will be returned if any other thread is provided. - * - * @param __qos_class - * A QOS class value: - * - QOS_CLASS_USER_INTERACTIVE - * - QOS_CLASS_USER_INITIATED - * - QOS_CLASS_DEFAULT - * - QOS_CLASS_UTILITY - * - QOS_CLASS_BACKGROUND - * - QOS_CLASS_MAINTENANCE - * EINVAL will be returned if any other value is provided. - * - * @param __relative_priority - * A relative priority within the QOS class. This value is a negative offset - * from the maximum supported scheduler priority for the given class. - * EINVAL will be returned if the value is greater than zero or less than - * QOS_MIN_RELATIVE_PRIORITY. - * - * @return - * Zero if successful, othwerise an errno value. - */ -__OSX_AVAILABLE_BUT_DEPRECATED_MSG(__MAC_10_10, __MAC_10_10, __IPHONE_8_0, __IPHONE_8_0, \ - "Use pthread_set_qos_class_self_np() instead") -int -pthread_set_qos_class_np(pthread_t __pthread, - qos_class_t __qos_class, - int __relative_priority); - -/* Private interfaces for libdispatch to encode/decode specific values of pthread_priority_t. */ - -// Encode a class+priority pair into a pthread_priority_t, -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -pthread_priority_t -_pthread_qos_class_encode(qos_class_t qos_class, int relative_priority, unsigned long flags); - -// Decode a pthread_priority_t into a class+priority pair. -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -qos_class_t -_pthread_qos_class_decode(pthread_priority_t priority, int *relative_priority, unsigned long *flags); - -// Encode a legacy workqueue API priority into a pthread_priority_t -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -pthread_priority_t -_pthread_qos_class_encode_workqueue(int queue_priority, unsigned long flags); - -#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL -// Set QoS or voucher, or both, on pthread_self() -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -int -_pthread_set_properties_self(_pthread_set_flags_t flags, pthread_priority_t priority, mach_port_t voucher); - -// Set self to fixed priority without disturbing QoS or priority -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -int -pthread_set_fixedpriority_self(void); - -#endif - -__END_DECLS - -#endif // KERNEL - -#endif //_QOS_PRIVATE_H diff --git a/objc/objc-runtime/include/pthread/spinlock_private.h b/objc/objc-runtime/include/pthread/spinlock_private.h deleted file mode 100644 index 392c499..0000000 --- a/objc/objc-runtime/include/pthread/spinlock_private.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2003, 2013 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@ - */ -/* - * Copyright 1996 1995 by Open Software Foundation, Inc. 1997 1996 1995 1994 1993 1992 1991 - * All Rights Reserved - * - * Permission to use, copy, modify, and distribute this software and - * its documentation for any purpose and without fee is hereby granted, - * provided that the above copyright notice appears in all copies and - * that both the copyright notice and this permission notice appear in - * supporting documentation. - * - * OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE - * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE. - * - * IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR - * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT, - * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION - * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - */ -/* - * MkLinux - */ - -/* - * POSIX Threads - IEEE 1003.1c - */ - -#ifndef _POSIX_PTHREAD_SPINLOCK_H -#define _POSIX_PTHREAD_SPINLOCK_H - -#include <sys/cdefs.h> -#include <mach/mach.h> -#include <libkern/OSAtomic.h> - -//typedef volatile OSSpinLock pthread_lock_t; - -#define LOCK_INIT(l) ((l) = OS_SPINLOCK_INIT) -#define LOCK_INITIALIZER OS_SPINLOCK_INIT - -#define _DO_SPINLOCK_LOCK(v) OSSpinLockLock(v) -#define _DO_SPINLOCK_UNLOCK(v) OSSpinLockUnlock(v) - -#define TRY_LOCK(v) OSSpinLockTry((volatile OSSpinLock *)&(v)) -#define LOCK(v) OSSpinLockLock((volatile OSSpinLock *)&(v)) -#define UNLOCK(v) OSSpinLockUnlock((volatile OSSpinLock *)&(v)) - -extern void _spin_lock(pthread_lock_t *lockp) __deprecated_msg("Use OSSpinLockLock instead"); -extern int _spin_lock_try(pthread_lock_t *lockp) __deprecated_msg("Use OSSpinLockTry instead"); -extern void _spin_unlock(pthread_lock_t *lockp) __deprecated_msg("Use OSSpinLockUnlock instead"); - -extern void spin_lock(pthread_lock_t *lockp) __deprecated_msg("Use OSSpinLockLock instead"); -extern int spin_lock_try(pthread_lock_t *lockp) __deprecated_msg("Use OSSpinLockTry instead"); -extern void spin_unlock(pthread_lock_t *lockp) __deprecated_msg("Use OSSpinLockUnlock instead"); - -#endif /* _POSIX_PTHREAD_SPINLOCK_H */ diff --git a/objc/objc-runtime/include/pthread/tsd_private.h b/objc/objc-runtime/include/pthread/tsd_private.h deleted file mode 100644 index 43ebbba..0000000 --- a/objc/objc-runtime/include/pthread/tsd_private.h +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (c) 2003-2013 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@ - */ -/* - * Copyright 1996 1995 by Open Software Foundation, Inc. 1997 1996 1995 1994 1993 1992 1991 - * All Rights Reserved - * - * Permission to use, copy, modify, and distribute this software and - * its documentation for any purpose and without fee is hereby granted, - * provided that the above copyright notice appears in all copies and - * that both the copyright notice and this permission notice appear in - * supporting documentation. - * - * OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE - * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE. - * - * IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR - * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT, - * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION - * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ -/* - * MkLinux - */ - -#ifndef __PTHREAD_TSD_H__ -#define __PTHREAD_TSD_H__ - -#ifndef __ASSEMBLER__ - -#include <System/machine/cpu_capabilities.h> -#include <sys/cdefs.h> -#include <TargetConditionals.h> -#include <os/tsd.h> -#include <pthread/spinlock_private.h> - -#ifndef __TSD_MACH_THREAD_SELF -#define __TSD_MACH_THREAD_SELF 3 -#endif - -#ifndef __TSD_THREAD_QOS_CLASS -#define __TSD_THREAD_QOS_CLASS 4 -#endif - -/* Constant TSD slots for inline pthread_getspecific() usage. */ - -/* Keys 0 - 9 are for Libsyscall/libplatform usage */ -#define _PTHREAD_TSD_SLOT_PTHREAD_SELF __TSD_THREAD_SELF -#define _PTHREAD_TSD_SLOT_ERRNO __TSD_ERRNO -#define _PTHREAD_TSD_SLOT_MIG_REPLY __TSD_MIG_REPLY -#define _PTHREAD_TSD_SLOT_MACH_THREAD_SELF __TSD_MACH_THREAD_SELF -#define _PTHREAD_TSD_SLOT_PTHREAD_QOS_CLASS __TSD_THREAD_QOS_CLASS -//#define _PTHREAD_TSD_SLOT_SEMAPHORE_CACHE__TSD_SEMAPHORE_CACHE - -//#define _PTHREAD_TSD_RESERVED_SLOT_COUNT _PTHREAD_TSD_RESERVED_SLOT_COUNT - -/* Keys 10 - 29 are for Libc/Libsystem internal usage */ -/* used as __pthread_tsd_first + Num */ -#define __PTK_LIBC_LOCALE_KEY 10 -#define __PTK_LIBC_TTYNAME_KEY 11 -#define __PTK_LIBC_LOCALTIME_KEY 12 -#define __PTK_LIBC_GMTIME_KEY 13 -#define __PTK_LIBC_GDTOA_BIGINT_KEY 14 -#define __PTK_LIBC_PARSEFLOAT_KEY 15 -/* for usage by dyld */ -#define __PTK_LIBC_DYLD_Unwind_SjLj_Key 18 - -/* Keys 20-29 for libdispatch usage */ -#define __PTK_LIBDISPATCH_KEY0 20 -#define __PTK_LIBDISPATCH_KEY1 21 -#define __PTK_LIBDISPATCH_KEY2 22 -#define __PTK_LIBDISPATCH_KEY3 23 -#define __PTK_LIBDISPATCH_KEY4 24 -#define __PTK_LIBDISPATCH_KEY5 25 -#define __PTK_LIBDISPATCH_KEY6 26 -#define __PTK_LIBDISPATCH_KEY7 27 -#define __PTK_LIBDISPATCH_KEY8 28 -#define __PTK_LIBDISPATCH_KEY9 29 - -/* Keys 30-255 for Non Libsystem usage */ - -/* Keys 30-39 for Graphic frameworks usage */ -#define _PTHREAD_TSD_SLOT_OPENGL 30 /* backwards compat sake */ -#define __PTK_FRAMEWORK_OPENGL_KEY 30 -#define __PTK_FRAMEWORK_GRAPHICS_KEY1 31 -#define __PTK_FRAMEWORK_GRAPHICS_KEY2 32 -#define __PTK_FRAMEWORK_GRAPHICS_KEY3 33 -#define __PTK_FRAMEWORK_GRAPHICS_KEY4 34 -#define __PTK_FRAMEWORK_GRAPHICS_KEY5 35 -#define __PTK_FRAMEWORK_GRAPHICS_KEY6 36 -#define __PTK_FRAMEWORK_GRAPHICS_KEY7 37 -#define __PTK_FRAMEWORK_GRAPHICS_KEY8 38 -#define __PTK_FRAMEWORK_GRAPHICS_KEY9 39 - -/* Keys 40-49 for Objective-C runtime usage */ -#define __PTK_FRAMEWORK_OBJC_KEY0 40 -#define __PTK_FRAMEWORK_OBJC_KEY1 41 -#define __PTK_FRAMEWORK_OBJC_KEY2 42 -#define __PTK_FRAMEWORK_OBJC_KEY3 43 -#define __PTK_FRAMEWORK_OBJC_KEY4 44 -#define __PTK_FRAMEWORK_OBJC_KEY5 45 -#define __PTK_FRAMEWORK_OBJC_KEY6 46 -#define __PTK_FRAMEWORK_OBJC_KEY7 47 -#define __PTK_FRAMEWORK_OBJC_KEY8 48 -#define __PTK_FRAMEWORK_OBJC_KEY9 49 - -/* Keys 50-59 for Core Foundation usage */ -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY0 50 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY1 51 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY2 52 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY3 53 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY4 54 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY5 55 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY6 56 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY7 57 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY8 58 -#define __PTK_FRAMEWORK_COREFOUNDATION_KEY9 59 - -/* Keys 60-69 for Foundation usage */ -#define __PTK_FRAMEWORK_FOUNDATION_KEY0 60 -#define __PTK_FRAMEWORK_FOUNDATION_KEY1 61 -#define __PTK_FRAMEWORK_FOUNDATION_KEY2 62 -#define __PTK_FRAMEWORK_FOUNDATION_KEY3 63 -#define __PTK_FRAMEWORK_FOUNDATION_KEY4 64 -#define __PTK_FRAMEWORK_FOUNDATION_KEY5 65 -#define __PTK_FRAMEWORK_FOUNDATION_KEY6 66 -#define __PTK_FRAMEWORK_FOUNDATION_KEY7 67 -#define __PTK_FRAMEWORK_FOUNDATION_KEY8 68 -#define __PTK_FRAMEWORK_FOUNDATION_KEY9 69 - -/* Keys 70-79 for Core Animation/QuartzCore usage */ -#define __PTK_FRAMEWORK_QUARTZCORE_KEY0 70 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY1 71 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY2 72 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY3 73 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY4 74 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY5 75 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY6 76 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY7 77 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY8 78 -#define __PTK_FRAMEWORK_QUARTZCORE_KEY9 79 - - -/* Keys 80-89 for CoreData */ -#define __PTK_FRAMEWORK_COREDATA_KEY0 80 -#define __PTK_FRAMEWORK_COREDATA_KEY1 81 -#define __PTK_FRAMEWORK_COREDATA_KEY2 82 -#define __PTK_FRAMEWORK_COREDATA_KEY3 83 -#define __PTK_FRAMEWORK_COREDATA_KEY4 84 -#define __PTK_FRAMEWORK_COREDATA_KEY5 85 -#define __PTK_FRAMEWORK_COREDATA_KEY6 86 -#define __PTK_FRAMEWORK_COREDATA_KEY7 87 -#define __PTK_FRAMEWORK_COREDATA_KEY8 88 -#define __PTK_FRAMEWORK_COREDATA_KEY9 89 - -/* Keys 90-94 for JavaScriptCore Collection */ -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY0 90 -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY1 91 -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY2 92 -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY3 93 -#define __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY4 94 -/* Keys 95 for CoreText */ -#define __PTK_FRAMEWORK_CORETEXT_KEY0 95 - -/* Keys 110-119 for Garbage Collection */ -#define __PTK_FRAMEWORK_GC_KEY0 110 -#define __PTK_FRAMEWORK_GC_KEY1 111 -#define __PTK_FRAMEWORK_GC_KEY2 112 -#define __PTK_FRAMEWORK_GC_KEY3 113 -#define __PTK_FRAMEWORK_GC_KEY4 114 -#define __PTK_FRAMEWORK_GC_KEY5 115 -#define __PTK_FRAMEWORK_GC_KEY6 116 -#define __PTK_FRAMEWORK_GC_KEY7 117 -#define __PTK_FRAMEWORK_GC_KEY8 118 -#define __PTK_FRAMEWORK_GC_KEY9 119 - -/* Keys 210 - 229 are for libSystem usage within the iOS Simulator */ -/* They are offset from their corresponding libSystem keys by 200 */ -#define __PTK_LIBC_SIM_LOCALE_KEY 210 -#define __PTK_LIBC_SIM_TTYNAME_KEY 211 -#define __PTK_LIBC_SIM_LOCALTIME_KEY 212 -#define __PTK_LIBC_SIM_GMTIME_KEY 213 -#define __PTK_LIBC_SIM_GDTOA_BIGINT_KEY 214 -#define __PTK_LIBC_SIM_PARSEFLOAT_KEY 215 - -__BEGIN_DECLS - -extern void *pthread_getspecific(unsigned long); -extern int pthread_setspecific(unsigned long, const void *); -/* setup destructor function for static key as it is not created with pthread_key_create() */ -extern int pthread_key_init_np(int, void (*)(void *)); - -#if PTHREAD_LAYOUT_SPI - -/* SPI intended for CoreSymbolication only */ - -__OSX_AVAILABLE_STARTING(__MAC_10_10,__IPHONE_8_0) -extern const struct pthread_layout_offsets_s { - // always add new fields at the end - const uint16_t plo_version; - // either of the next two fields may be 0; use whichever is set - // bytes from pthread_t to base of tsd - const uint16_t plo_pthread_tsd_base_offset; - // bytes from pthread_t to a pointer to base of tsd - const uint16_t plo_pthread_tsd_base_address_offset; - const uint16_t plo_pthread_tsd_entry_size; -} pthread_layout_offsets; - -#endif // PTHREAD_LAYOUT_SPI -__END_DECLS - -#if TARGET_IPHONE_SIMULATOR - -__header_always_inline int -_pthread_has_direct_tsd(void) -{ - return 0; -} - -#define _pthread_getspecific_direct(key) pthread_getspecific((key)) -#define _pthread_setspecific_direct(key, val) pthread_setspecific((key), (val)) - -#else /* TARGET_IPHONE_SIMULATOR */ - -__header_always_inline int -_pthread_has_direct_tsd(void) -{ - return 1; -} - -/* To be used with static constant keys only */ -__header_always_inline void * -_pthread_getspecific_direct(unsigned long slot) -{ - return _os_tsd_get_direct(slot); -} - -/* To be used with static constant keys only */ -__header_always_inline int -_pthread_setspecific_direct(unsigned long slot, void * val) -{ - return _os_tsd_set_direct(slot, val); -} - -#endif /* TARGET_IPHONE_SIMULATOR */ - -#endif /* ! __ASSEMBLER__ */ -#endif /* __PTHREAD_TSD_H__ */ diff --git a/objc/objc-runtime/include/pthread/workqueue_private.h b/objc/objc-runtime/include/pthread/workqueue_private.h deleted file mode 100644 index 533103f..0000000 --- a/objc/objc-runtime/include/pthread/workqueue_private.h +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2007, 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 __PTHREAD_WORKQUEUE_H__ -#define __PTHREAD_WORKQUEUE_H__ - -#include <sys/cdefs.h> -#include <Availability.h> -#include <pthread/pthread.h> -#include <pthread/qos.h> -#ifndef _PTHREAD_BUILDING_PTHREAD_ -#include <pthread/qos_private.h> -#endif - -#define PTHREAD_WORKQUEUE_SPI_VERSION 20140730 - -/* Feature checking flags, returned by _pthread_workqueue_supported() - * - * Note: These bits should match the definition of PTHREAD_FEATURE_* - * bits defined in libpthread/kern/kern_internal.h */ - -#define WORKQ_FEATURE_DISPATCHFUNC 0x01 // pthread_workqueue_setdispatch_np is supported (or not) -#define WORKQ_FEATURE_FINEPRIO 0x02 // fine grained pthread workq priorities -#define WORKQ_FEATURE_MAINTENANCE 0x10 // QOS class maintenance - -/* Legacy dispatch priority bands */ - -#define WORKQ_NUM_PRIOQUEUE 4 - -#define WORKQ_HIGH_PRIOQUEUE 0 // high priority queue -#define WORKQ_DEFAULT_PRIOQUEUE 1 // default priority queue -#define WORKQ_LOW_PRIOQUEUE 2 // low priority queue -#define WORKQ_BG_PRIOQUEUE 3 // background priority queue -#define WORKQ_NON_INTERACTIVE_PRIOQUEUE 128 // libdispatch SPI level - -/* Legacy dispatch workqueue function flags */ -#define WORKQ_ADDTHREADS_OPTION_OVERCOMMIT 0x00000001 - -__BEGIN_DECLS - -// Legacy callback prototype, used with pthread_workqueue_setdispatch_np -typedef void (*pthread_workqueue_function_t)(int queue_priority, int options, void *ctxt); -// New callback prototype, used with pthread_workqueue_init -typedef void (*pthread_workqueue_function2_t)(pthread_priority_t priority); - -// Initialises the pthread workqueue subsystem, passing the new-style callback prototype, -// the dispatchoffset and an unused flags field. -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -int -_pthread_workqueue_init(pthread_workqueue_function2_t func, int offset, int flags); - -// Non-zero enables kill on current thread, zero disables it. -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2) -int -__pthread_workqueue_setkill(int); - -// Dispatch function to be called when new worker threads are created. -__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) -int -pthread_workqueue_setdispatch_np(pthread_workqueue_function_t worker_func); - -// Dispatch offset to be set in the kernel. -__OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0) -void -pthread_workqueue_setdispatchoffset_np(int offset); - -// Request additional worker threads. -__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) -int -pthread_workqueue_addthreads_np(int queue_priority, int options, int numthreads); - -// Retrieve the supported pthread feature set -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -int -_pthread_workqueue_supported(void); - -// Request worker threads (fine grained priority) -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -int -_pthread_workqueue_addthreads(int numthreads, pthread_priority_t priority); - -// Apply a QoS override without allocating userspace memory -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -int -_pthread_override_qos_class_start_direct(mach_port_t thread, pthread_priority_t priority); - -// Drop a corresponding QoS override made above. -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -int -_pthread_override_qos_class_end_direct(mach_port_t thread); - -// Apply a QoS override on a given workqueue thread. -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -int -_pthread_workqueue_override_start_direct(mach_port_t thread, pthread_priority_t priority); - -// Drop all QoS overrides on the current workqueue thread. -__OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0) -int -_pthread_workqueue_override_reset(void); - -// Apply a QoS override on a given thread (can be non-workqueue as well) with a resource/queue token -__OSX_AVAILABLE_STARTING(__MAC_10_10_2, __IPHONE_NA) -int -_pthread_workqueue_asynchronous_override_add(mach_port_t thread, pthread_priority_t priority, void *resource); - -// Reset overrides for the given resource for the current thread -__OSX_AVAILABLE_STARTING(__MAC_10_10_2, __IPHONE_NA) -int -_pthread_workqueue_asynchronous_override_reset_self(void *resource); - -// Reset overrides for all resources for the current thread -__OSX_AVAILABLE_STARTING(__MAC_10_10_2, __IPHONE_NA) -int -_pthread_workqueue_asynchronous_override_reset_all_self(void); - -__END_DECLS - -#endif // __PTHREAD_WORKQUEUE_H__ diff --git a/objc/objc-runtime/include/sys/qos_private.h b/objc/objc-runtime/include/sys/qos_private.h deleted file mode 100644 index 0a38926..0000000 --- a/objc/objc-runtime/include/sys/qos_private.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2014 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 _QOS_SYS_PRIVATE_H -#define _QOS_SYS_PRIVATE_H - -/*! - * @constant QOS_CLASS_MAINTENANCE - * @abstract A QOS class which indicates work performed by this thread was not - * initiated by the user and that the user may be unaware of the results. - * @discussion Such work is requested to run at a priority far below other work - * including significant I/O throttling. The use of this QOS class indicates - * the work should be run in the most energy and thermally-efficient manner - * possible, and may be deferred for a long time in order to preserve - * system responsiveness for the user. - * This is SPI for use by Spotlight and Time Machine only. - */ -#define QOS_CLASS_MAINTENANCE 0x05 - -#endif //_QOS_SYS_PRIVATE_H diff --git a/objc/objc-runtime/include/vproc_priv.h b/objc/objc-runtime/include/vproc_priv.h deleted file mode 100755 index 954b481..0000000 --- a/objc/objc-runtime/include/vproc_priv.h +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2006 Apple Computer, 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 __VPROC_PRIVATE_H__ -#define __VPROC_PRIVATE_H__ - -#include <Availability.h> -#include <sys/types.h> -#include <sys/cdefs.h> -#include <sys/syslog.h> -#include <sys/time.h> -#include <stdbool.h> -#include <launch.h> -#include <vproc.h> -#include <uuid/uuid.h> -#include <servers/bootstrap.h> - -#ifndef VPROC_HAS_TRANSACTIONS -#define VPROC_HAS_TRANSACTIONS 1 -#endif - -__BEGIN_DECLS - -#define VPROCMGR_SESSION_LOGINWINDOW "LoginWindow" -#define VPROCMGR_SESSION_BACKGROUND "Background" -#define VPROCMGR_SESSION_AQUA "Aqua" -#define VPROCMGR_SESSION_STANDARDIO "StandardIO" -#define VPROCMGR_SESSION_SYSTEM "System" - -#define XPC_DOMAIN_TYPE_SYSTEM "XPCSystem" -#define XPC_DOMAIN_TYPE_PERUSER "XPCPerUser" -#define XPC_DOMAIN_TYPE_PERSESSION "XPCPerSession" -#define XPC_DOMAIN_TYPE_PERAPPLICATION "XPCPerApplication" - -#pragma GCC visibility push(default) - -/* DO NOT use this. This is a hack for 'launchctl' */ -#define VPROC_MAGIC_UNLOAD_SIGNAL 0x4141504C - -typedef void (*_vproc_transaction_callout)(void); - -typedef enum { - VPROC_GSK_ZERO, - VPROC_GSK_LAST_EXIT_STATUS, - VPROC_GSK_GLOBAL_ON_DEMAND, - VPROC_GSK_MGR_UID, - VPROC_GSK_MGR_PID, - VPROC_GSK_IS_MANAGED, - VPROC_GSK_MGR_NAME, - VPROC_GSK_BASIC_KEEPALIVE, - VPROC_GSK_START_INTERVAL, - VPROC_GSK_IDLE_TIMEOUT, - VPROC_GSK_EXIT_TIMEOUT, - VPROC_GSK_ENVIRONMENT, - VPROC_GSK_ALLJOBS, - VPROC_GSK_GLOBAL_LOG_MASK, - VPROC_GSK_GLOBAL_UMASK, - VPROC_GSK_ABANDON_PROCESS_GROUP, - VPROC_GSK_TRANSACTIONS_ENABLED, - VPROC_GSK_WEIRD_BOOTSTRAP, - VPROC_GSK_WAITFORDEBUGGER, - VPROC_GSK_SECURITYSESSION, - VPROC_GSK_SHUTDOWN_DEBUGGING, - VPROC_GSK_VERBOSE_BOOT, - VPROC_GSK_PERUSER_SUSPEND, - VPROC_GSK_PERUSER_RESUME, - VPROC_GSK_JOB_OVERRIDES_DB, - VPROC_GSK_JOB_CACHE_DB, - VPROC_GSK_EMBEDDEDROOTEQUIVALENT, -} vproc_gsk_t; - -typedef unsigned int vproc_flags_t; -/* For _vproc_kickstart_by_label() -- instructs launchd to kickstart the job to stall before exec(2). */ -#define VPROCFLAG_STALL_JOB_EXEC 1 << 1 - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) -vproc_t -vprocmgr_lookup_vproc(const char *label); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) -vproc_t -vproc_retain(vproc_t vp); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) -void -vproc_release(vproc_t vp); - -__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_3_0) -vproc_err_t -vproc_swap_integer(vproc_t vp, vproc_gsk_t key, - int64_t *inval, int64_t *outval); - -__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_3_0) -vproc_err_t -vproc_swap_complex(vproc_t vp, vproc_gsk_t key, - launch_data_t inval, launch_data_t *outval); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_4_0) -vproc_err_t -vproc_swap_string(vproc_t vp, vproc_gsk_t key, - const char *instr, char **outstr); - -__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA) -vproc_err_t -_vproc_get_last_exit_status(int *wstatus); - -__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_3_0) -vproc_err_t -_vproc_set_global_on_demand(bool val); - -__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_3_0) -vproc_err_t -_vproc_send_signal_by_label(const char *label, int sig); - -__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_3_0) -vproc_err_t -_vproc_kickstart_by_label(const char *label, pid_t *out_pid, - mach_port_t *out_port_name, mach_port_t *out_obsrvr_port, - vproc_flags_t flags); - -/* _vprocmgr_log_drain() is specific to syslogd. It is not for general use. */ -typedef void (*_vprocmgr_log_drain_callback_t)(struct timeval *when, pid_t - from_pid, pid_t about_pid, uid_t sender_uid, gid_t sender_gid, int priority, - const char *from_name, const char *about_name, const char *session_name, - const char *msg); - -vproc_err_t -_vprocmgr_log_drain(vproc_t vp, pthread_mutex_t *optional_mutex_around_callback, - _vprocmgr_log_drain_callback_t func); - -__attribute__((format(printf, 2, 3))) -void -_vproc_log(int pri, const char *msg, ...); - -__attribute__((format(printf, 2, 3))) -void -_vproc_log_error(int pri, const char *msg, ...); - -__attribute__((format(printf, 3, 0))) -void -_vproc_logv(int pri, int err, const char *msg, va_list ap); - -/* One day, we'll be able to get rid of this... */ -vproc_err_t -_vprocmgr_move_subset_to_user(uid_t target_user, const char *session_type, - uint64_t flags); - -vproc_err_t -_vprocmgr_switch_to_session(const char *target_session, vproc_flags_t flags); - -vproc_err_t -_vprocmgr_detach_from_console(vproc_flags_t flags); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) -void -_vproc_standby_begin(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) -void -_vproc_standby_end(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) -size_t -_vproc_standby_count(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) -size_t -_vproc_standby_timeout(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) -kern_return_t -_vproc_transaction_count_for_pid(pid_t p, int32_t *count, bool *condemned); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) -bool -_vproc_pid_is_managed(pid_t p); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) -void -_vproc_transaction_try_exit(int status); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0) -void -_vproc_transaction_begin(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0) -void -_vproc_transaction_end(void); - -__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) -size_t -_vproc_transaction_count(void); - -int32_t * -_vproc_transaction_ptr(void); - -void -_vproc_transaction_set_callouts(_vproc_transaction_callout gone2zero, _vproc_transaction_callout gonenonzero); - -void -_vproc_transactions_enable(void); - -#pragma GCC visibility pop - -__END_DECLS - -#endif /* __VPROC_PRIVATE_H__ */ diff --git a/objc/objc-runtime/libobjc.order b/objc/objc-runtime/libobjc.order deleted file mode 100644 index 88206c1..0000000 --- a/objc/objc-runtime/libobjc.order +++ /dev/null @@ -1,359 +0,0 @@ -__objc_init -_environ_init -_tls_init -_lock_init -_recursive_mutex_init -_exception_init -_map_images -_map_images_nolock -__getObjcImageInfo -__hasObjcContents -__objc_appendHeader -_verify_gc_readiness -_gc_init -__objc_inform_on_crash -__objc_crashlog -_rtp_init -_gc_fixup_barrier_stubs -__objc_update_stubs_in_mach_header -_sel_init -_sel_lock -___sel_registerName -__objc_search_builtins -__ZNK8objc_opt13objc_selopt_t3getEPKc -__ZNK8objc_opt13objc_selopt_t4hashEPKc -_sel_unlock -_sel_registerName -_arr_init -__ZN4objc8DenseMapIP11objc_objectmLb1ENS_12DenseMapInfoIS2_EENS3_ImEEE4initEj -__read_images -__Z11initVtablesv -__Z17appendTrampolinesP22objc_trampoline_header -_gdb_objc_trampolines_changed -_crashlog_header_name -__getObjc2ClassList -_NXCreateMapTableFromZone -_NXCreateHashTable -_NXCreateHashTableFromZone -_NXHashGet -_NXHashInsert -__NXHashRehashToCapacity -_NXNextHashState -_freeBuckets -_NXNoEffectFree -_hashPrototype -_NXPtrHash -_isEqualPrototype -__Z13futureClassesv -_NXCountMapTable -__Z13addNamedClassP7class_tPKc -_NXMapGet -__mapStrHash -_NXMapInsert -__mapPtrHash -__Z10remapClassP7class_t -__Z15remappedClassesa -_NXMapMember -__NXMapMember -__mapStrIsEqual -__mapPtrIsEqual -__getObjc2ClassRefs -__getObjc2SuperRefs -_sel_preoptimizationValid -__getObjc2SelectorRefs -_sel_registerNameNoLock -___objc_sel_set_create -___objc_sel_set_add -___objc_sel_set_findBuckets -___objc_sel_set_get -__Z9protocolsv -__getObjc2ProtocolList -_NXMapKeyCopyingInsert -__NXMapRehash -__getObjc2ProtocolRefs -__Z13remapProtocolm -__getObjc2NonlazyClassList -__Z12realizeClassP7class_t -__Z11addSubclassP7class_tS0_ -__Z17attachMethodListsP7class_tPP13method_list_tiaPa -__Z15fixupMethodListP13method_list_ta -_memdup -__ZNSt3__113__stable_sortIRN8method_t16SortBySELAddressEN13method_list_t15method_iteratorEEEvT0_S6_T_NS_15iterator_traitsIS6_E1 -__Z9addMethodP7class_tP13objc_selectorPFP11objc_objectS3_S1_zEPKca -__Z23getMethodNoSuper_nolockP7class_tP13objc_selector -__ZN7class_t14setHasCustomRREv -__Z20unattachedCategoriesv -_NXMapRemove -__Z21attachCategoryMethodsP7class_tP13category_listPa -_objc_addRegisteredClass -_layout_bitmap_create -_set_bits -_layout_bitmap_free -__ZNSt3__116__insertion_sortIRN8method_t16SortBySELAddressEN13method_list_t15method_iteratorEEEvT0_S6_T_ -__Z17buildProtocolListP13category_listPK15protocol_list_tPS3_ -__Z17buildPropertyListPK15property_list_tP13category_lista -__ZNSt3__120get_temporary_bufferI8method_tEENS_4pairIPT_lEEl -__ZNSt3__118__stable_sort_moveIRN8method_t16SortBySELAddressEN13method_list_t15method_iteratorEEEvT0_S6_T_NS_15iterator_traitsI -__ZNSt3__122__merge_move_constructIRN8method_t16SortBySELAddressEN13method_list_t15method_iteratorES5_EEvT0_S6_T1_S7_PNS_15iter -__ZNSt3__119__merge_move_assignIRN8method_t16SortBySELAddressEPS1_S4_N13method_list_t15method_iteratorEEEvT0_S7_T1_S8_T2_T_ -_NXPtrIsEqual -__getObjc2CategoryList -__Z29addUnattachedCategoryForClassP10category_tP7class_tP12_header_info -__Z16remethodizeClassP7class_t -__Z11flushCachesP7class_t -_flush_cache -__class_getCache -_load_images -_load_images_nolock -_prepare_load_methods -__Z19schedule_class_loadP7class_t -_add_class_to_loadable_list -__class_getLoadMethod -__getObjc2NonlazyCategoryList -_call_load_methods -+[Protocol load] -_objc_lookUpClass -_look_up_class -_object_getClass -_protocol_copyMethodDescriptionList -_class_getClassMethod -__class_getMeta -_look_up_method -__cache_getMethod -__class_getMethod -_method_getTypeEncoding -_method_getImplementation -_method_getName -_class_addMethod -_class_getInstanceMethod -__Z12flushVtablesP7class_t -__Z12updateVtableP7class_ta -_class_replaceMethod -__Z25_method_setImplementationP7class_tP8method_tPFP11objc_objectS4_P13objc_selectorzE -_class_addProtocol -_class_conformsToProtocol -_objc_setExceptionPreprocessor -_objc_setExceptionMatcher -_objc_setUncaughtExceptionHandler -_objc_setForwardHandler -_objc_setEnumerationMutationHandler -_objc_collectingEnabled -_objc_getFutureClass -_objc_assign_strongCast_non_gc -_objc_getClass -__objc_insert_tagged_isa -_objc_msgSend_fixup -__objc_fixupMessageRef -_objc_msgSend -__class_lookupMethodAndLoadCache3 -_lookUpMethod -_prepareForMethodLookup -__class_initialize -__class_getNonMetaClass -__Z15getNonMetaClassP7class_t -__class_getSuperclass -__class_isInitialized -__class_isInitializing -__class_setInitializing -__fetchInitializingClassList -__objc_fetch_pthread_data -_lockForMethodLookup -__cache_getImp -__class_getMethodNoSuper_nolock -_log_and_fill_cache -__cache_fill -_unlockForMethodLookup -_objc_assign_global_non_gc -_class_setSuperclass -_class_setVersion -_objc_msgSend_vtable1 -__objc_rootAlloc -_class_getInstanceSize -__class_getInstanceSize -_class_createInstance -_object_getClassName -__class_getName -_object_getIndexedIvars -_objc_msgSend_vtable0 -__objc_rootAllocWithZone -__objc_rootInit -_objc_msgSend_vtable3 -_objc_assign_ivar_non_gc -__objc_rootRetain -__ZN4objc8DenseMapIP11objc_objectmLb1ENS_12DenseMapInfoIS2_EENS3_ImEEE16FindAndConstructERKS2_ -__ZNK4objc8DenseMapIP11objc_objectmLb1ENS_12DenseMapInfoIS2_EENS3_ImEEE15LookupBucketForERKS2_RPNSt3__14pairIS2_mEE -__ZN4objc8DenseMapIP11objc_objectmLb1ENS_12DenseMapInfoIS2_EENS3_ImEEE16InsertIntoBucketERKS2_RKmPNSt3__14pairIS2_mEE -__objc_rootRelease -__objc_rootReleaseWasZero -__ZN4objc8DenseMapIP11objc_objectmLb1ENS_12DenseMapInfoIS2_EENS3_ImEEE4findERKS2_ -__finishInitializing -__class_setInitialized -_NXFreeMapTable -_NXResetMapTable -__cache_malloc -__class_setCache -__class_setGrowCache -_objc_initializeClassPair -__Z33objc_initializeClassPair_internalP10objc_classPKcS0_S0_ -_objc_registerClassPair -_add_category_to_loadable_list -__category_getLoadMethod -__category_getClass -__class_isLoadable -_objc_msgSendSuper2 -__objc_autoreleasePoolPush -_objc_autoreleasePoolPush -__ZN12_GLOBAL__N_119AutoreleasePoolPageC1EPS0_ -__ZN12_GLOBAL__N_119AutoreleasePoolPage9fastcheckEb -_objc_destructInstance -_objc_clear_deallocating -__ZN4objc8DenseMapIP11objc_objectmLb1ENS_12DenseMapInfoIS2_EENS3_ImEEE5eraseERKS2_ -_objc_msgSend_vtable9 -__class_shouldGrowCache -__cache_collect_free -__cache_collect -_class_getSuperclass -_objc_msgSend_vtable2 -_objc_msgSend_vtable13 -_objc_msgSend_vtable14 -_objc_memmove_collectable -_class_respondsToSelector -__class_resolveMethod -__class_isMetaClass -__cache_addForwardEntry -__objc_rootDealloc -_object_dispose -_objc_msgSend_fixedup -_class_getName -_objc_atomicCompareAndSwapPtrBarrier -_objc_msgSend_vtable7 -__objc_rootAutorelease -__Z22_objc_rootAutorelease2P11objc_object -_objc_msgSend_vtable12 -_objc_msgSend_vtable11 -_objc_msgSend_vtable8 -_objc_msgSend_vtable15 -__objc_autoreleasePoolPop -__ZN12_GLOBAL__N_119AutoreleasePoolPage3popEPv -_objc_msgSend_vtable4 -_objc_msgSend_vtable10 -_objc_retain -_objc_atomicCompareAndSwapInstanceVariableBarrier -_objc_msgSendSuper2_fixup -_objc_msgSendSuper2_fixedup -__collecting_in_critical -__cache_free_block -_class_getVersion -_objc_finalizeOnMainThread -_class_getImageName -__objc_rootZone -__Z35_protocol_conformsToProtocol_nolockP10protocol_tS0_ -_objc_msgSend_vtable5 -_objc_sync_enter -_id2data -_fetch_cache -_objc_sync_exit -_gc_enforcer -_cache_region_calloc -_class_getMethodImplementation -_objc_msgSend_stret -__ZN4objc8DenseMapIP11objc_objectmLb1ENS_12DenseMapInfoIS2_EENS3_ImEEE4growEj -__objc_rootHash -_objc_assign_weak_non_gc -_objc_read_weak_non_gc -_sel_getName -_method_getArgumentType -_encoding_getArgumentType -_encoding_getArgumentInfo -_SkipFirstType -_class_isMetaClass -_objc_allocateClassPair -__calloc_class -_class_getInstanceVariable -__class_getVariable -__Z7getIvarP7class_tPKc -_object_setClass -__class_instancesHaveAssociatedObjects -_method_getNumberOfArguments -_encoding_getNumberOfArguments -_method_copyReturnType -_encoding_copyReturnType -_method_copyArgumentType -_encoding_copyArgumentType -__objc_rootRetainCount -_objc_getAssociatedObject_non_gc -__object_get_associative_reference -__ZN19AssociationsManagerC2Ev -__ZN19AssociationsManager12associationsEv -__ZNK23objc_references_support15ObjcPointerHashclEPv -_objc_release -_objc_removeAssociatedObjects -_objc_setProperty_non_gc -_objc_getProperty_non_gc -_objc_autoreleaseReturnValue -_objc_setAssociatedObject_non_gc -__object_set_associative_reference -__ZN9__gnu_cxx8hash_mapIPvPN23objc_references_support20ObjectAssociationMapENS2_15ObjcPointerHashENS2_16ObjcPointerEqualENS2_13 -__ZNSt3__13mapIPvN23objc_references_support15ObjcAssociationENS2_17ObjectPointerLessENS2_13ObjcAllocatorINS_4pairIKS1_S3_EEEEEi -__ZNSt3__13mapIPvN23objc_references_support15ObjcAssociationENS2_17ObjectPointerLessENS2_13ObjcAllocatorINS_4pairIKS1_S3_EEEEE1 -__ZNSt3__127__tree_balance_after_insertIPNS_16__tree_node_baseIPvEEEEvT_S5_ -__class_setInstancesHaveAssociatedObjects -_ivar_getTypeEncoding -_object_getIvar -_ivar_getOffset -__class_usesAutomaticRetainRelease -__objc_msgForward_internal -__objc_msgForward -_class_copyProtocolList -_protocol_getMethodDescription -__protocol_getMethod -__Z26_protocol_getMethod_nolockP10protocol_tP13objc_selectoraa -_method_getDescription -_ivar_getName -_objc_addExceptionHandler -_read_address -_read_sleb -_fetch_handler_list -_objc_removeExceptionHandler -_SubtypeUntil -_objc_collecting_enabled -_objc_msgSend_vtable6 -_objc_is_finalized -_class_copyPropertyList -_property_getName -_property_getAttributes -_objc_msgSendSuper2_stret -_object_setInstanceVariable -_object_setIvar -_objc_assign_ivar -__ZN12_GLOBAL__N_119AutoreleasePoolPage15autoreleaseSlowEP11objc_object -_objc_atomicCompareAndSwapPtr -_objc_atomicCompareAndSwapGlobalBarrier -_sel_getUid -__ZN12_GLOBAL__N_119AutoreleasePoolPage11tls_deallocEPv -__ZN12_GLOBAL__N_119AutoreleasePoolPage4killEv -__objc_constructOrFree -_object_cxxConstruct -_object_cxxConstructFromClass -__class_hasCxxStructors -_lookupMethodInClassAndLoadCache -__class_getMethodNoSuper -_object_cxxDestruct -_object_cxxDestructFromClass -_class_copyIvarList -__object_addExternalReference_rr -__objc_rootRetain_slow -__objc_rootReleaseWasZero_slow -_object_copy -__Z20_object_copyFromZoneP11objc_objectmPv -__objc_pthread_destroyspecific -__destroyInitializingClassList -__destroySyncCache -__destroyAltHandlerList -__object_remove_assocations -__ZNSt3__114__split_bufferIN23objc_references_support15ObjcAssociationERNS1_13ObjcAllocatorIS2_EEE9push_backERKS2_ -__ZNSt3__16vectorIN23objc_references_support15ObjcAssociationENS1_13ObjcAllocatorIS2_EEE26__swap_out_circular_bufferERNS_14__sp -__ZNSt3__112__hash_tableINS_4pairIPvPN23objc_references_support20ObjectAssociationMapEEEN9__gnu_cxx17__hash_map_hasherIS6_NS3_1 -__ZNSt3__114__split_bufferIN23objc_references_support15ObjcAssociationERNS1_13ObjcAllocatorIS2_EEE10push_frontERKS2_ -__ZNSt3__16__treeINS_4pairIPvN23objc_references_support15ObjcAssociationEEENS_19__map_value_compareIS2_S4_NS3_17ObjectPointerLe -__ZNSt3__113__tree_removeIPNS_16__tree_node_baseIPvEEEEvT_S5_ diff --git a/objc/objc-runtime/markgc.c b/objc/objc-runtime/markgc.c deleted file mode 100644 index d0473be..0000000 --- a/objc/objc-runtime/markgc.c +++ /dev/null @@ -1,604 +0,0 @@ -/* - * Copyright (c) 2007-2009 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 <stdlib.h> -#include <unistd.h> -#include <string.h> -#include <stdio.h> -#include <stdbool.h> -#include <fcntl.h> -#include <limits.h> -#include <sys/mman.h> -#include <sys/stat.h> -#include <sys/errno.h> -#include <mach-o/fat.h> -#include <mach-o/arch.h> -#include <mach-o/loader.h> - -// from "objc-private.h" -// masks for objc_image_info.flags -#define OBJC_IMAGE_SUPPORTS_GC (1<<1) - -// Some OS X SDKs don't define these. -#ifndef CPU_TYPE_ARM -#define CPU_TYPE_ARM ((cpu_type_t) 12) -#endif -#ifndef CPU_ARCH_ABI64 -#define CPU_ARCH_ABI64 0x01000000 /* 64 bit ABI */ -#endif -#ifndef CPU_TYPE_ARM64 -#define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64) -#endif - -// File abstraction taken from ld64/FileAbstraction.hpp -// and ld64/MachOFileAbstraction.hpp. - -#ifdef __OPTIMIZE__ -#define INLINE __attribute__((always_inline)) -#else -#define INLINE -#endif - -// -// This abstraction layer is for use with file formats that have 64-bit/32-bit and Big-Endian/Little-Endian variants -// -// For example: to make a utility that handles 32-bit little enidan files use: Pointer32<LittleEndian> -// -// -// get16() read a 16-bit number from an E endian struct -// set16() write a 16-bit number to an E endian struct -// get32() read a 32-bit number from an E endian struct -// set32() write a 32-bit number to an E endian struct -// get64() read a 64-bit number from an E endian struct -// set64() write a 64-bit number to an E endian struct -// -// getBits() read a bit field from an E endian struct (bitCount=number of bits in field, firstBit=bit index of field) -// setBits() write a bit field to an E endian struct (bitCount=number of bits in field, firstBit=bit index of field) -// -// getBitsRaw() read a bit field from a struct with native endianness -// setBitsRaw() write a bit field from a struct with native endianness -// - -class BigEndian -{ -public: - static uint16_t get16(const uint16_t& from) INLINE { return OSReadBigInt16(&from, 0); } - static void set16(uint16_t& into, uint16_t value) INLINE { OSWriteBigInt16(&into, 0, value); } - - static uint32_t get32(const uint32_t& from) INLINE { return OSReadBigInt32(&from, 0); } - static void set32(uint32_t& into, uint32_t value) INLINE { OSWriteBigInt32(&into, 0, value); } - - static uint64_t get64(const uint64_t& from) INLINE { return OSReadBigInt64(&from, 0); } - static void set64(uint64_t& into, uint64_t value) INLINE { OSWriteBigInt64(&into, 0, value); } - - static uint32_t getBits(const uint32_t& from, - uint8_t firstBit, uint8_t bitCount) INLINE { return getBitsRaw(get32(from), firstBit, bitCount); } - static void setBits(uint32_t& into, uint32_t value, - uint8_t firstBit, uint8_t bitCount) INLINE { uint32_t temp = get32(into); setBitsRaw(temp, value, firstBit, bitCount); set32(into, temp); } - - static uint32_t getBitsRaw(const uint32_t& from, - uint8_t firstBit, uint8_t bitCount) INLINE { return ((from >> (32-firstBit-bitCount)) & ((1<<bitCount)-1)); } - static void setBitsRaw(uint32_t& into, uint32_t value, - uint8_t firstBit, uint8_t bitCount) INLINE { uint32_t temp = into; - const uint32_t mask = ((1<<bitCount)-1); - temp &= ~(mask << (32-firstBit-bitCount)); - temp |= ((value & mask) << (32-firstBit-bitCount)); - into = temp; } - enum { little_endian = 0 }; -}; - - -class LittleEndian -{ -public: - static uint16_t get16(const uint16_t& from) INLINE { return OSReadLittleInt16(&from, 0); } - static void set16(uint16_t& into, uint16_t value) INLINE { OSWriteLittleInt16(&into, 0, value); } - - static uint32_t get32(const uint32_t& from) INLINE { return OSReadLittleInt32(&from, 0); } - static void set32(uint32_t& into, uint32_t value) INLINE { OSWriteLittleInt32(&into, 0, value); } - - static uint64_t get64(const uint64_t& from) INLINE { return OSReadLittleInt64(&from, 0); } - static void set64(uint64_t& into, uint64_t value) INLINE { OSWriteLittleInt64(&into, 0, value); } - - static uint32_t getBits(const uint32_t& from, - uint8_t firstBit, uint8_t bitCount) INLINE { return getBitsRaw(get32(from), firstBit, bitCount); } - static void setBits(uint32_t& into, uint32_t value, - uint8_t firstBit, uint8_t bitCount) INLINE { uint32_t temp = get32(into); setBitsRaw(temp, value, firstBit, bitCount); set32(into, temp); } - - static uint32_t getBitsRaw(const uint32_t& from, - uint8_t firstBit, uint8_t bitCount) INLINE { return ((from >> firstBit) & ((1<<bitCount)-1)); } - static void setBitsRaw(uint32_t& into, uint32_t value, - uint8_t firstBit, uint8_t bitCount) INLINE { uint32_t temp = into; - const uint32_t mask = ((1<<bitCount)-1); - temp &= ~(mask << firstBit); - temp |= ((value & mask) << firstBit); - into = temp; } - enum { little_endian = 1 }; -}; - -#if __BIG_ENDIAN__ -typedef BigEndian CurrentEndian; -typedef LittleEndian OtherEndian; -#elif __LITTLE_ENDIAN__ -typedef LittleEndian CurrentEndian; -typedef BigEndian OtherEndian; -#else -#error unknown endianness -#endif - - -template <typename _E> -class Pointer32 -{ -public: - typedef uint32_t uint_t; - typedef int32_t sint_t; - typedef _E E; - - static uint64_t getP(const uint_t& from) INLINE { return _E::get32(from); } - static void setP(uint_t& into, uint64_t value) INLINE { _E::set32(into, value); } -}; - - -template <typename _E> -class Pointer64 -{ -public: - typedef uint64_t uint_t; - typedef int64_t sint_t; - typedef _E E; - - static uint64_t getP(const uint_t& from) INLINE { return _E::get64(from); } - static void setP(uint_t& into, uint64_t value) INLINE { _E::set64(into, value); } -}; - - -// -// mach-o file header -// -template <typename P> struct macho_header_content {}; -template <> struct macho_header_content<Pointer32<BigEndian> > { mach_header fields; }; -template <> struct macho_header_content<Pointer64<BigEndian> > { mach_header_64 fields; }; -template <> struct macho_header_content<Pointer32<LittleEndian> > { mach_header fields; }; -template <> struct macho_header_content<Pointer64<LittleEndian> > { mach_header_64 fields; }; - -template <typename P> -class macho_header { -public: - uint32_t magic() const INLINE { return E::get32(header.fields.magic); } - void set_magic(uint32_t value) INLINE { E::set32(header.fields.magic, value); } - - uint32_t cputype() const INLINE { return E::get32(header.fields.cputype); } - void set_cputype(uint32_t value) INLINE { E::set32((uint32_t&)header.fields.cputype, value); } - - uint32_t cpusubtype() const INLINE { return E::get32(header.fields.cpusubtype); } - void set_cpusubtype(uint32_t value) INLINE { E::set32((uint32_t&)header.fields.cpusubtype, value); } - - uint32_t filetype() const INLINE { return E::get32(header.fields.filetype); } - void set_filetype(uint32_t value) INLINE { E::set32(header.fields.filetype, value); } - - uint32_t ncmds() const INLINE { return E::get32(header.fields.ncmds); } - void set_ncmds(uint32_t value) INLINE { E::set32(header.fields.ncmds, value); } - - uint32_t sizeofcmds() const INLINE { return E::get32(header.fields.sizeofcmds); } - void set_sizeofcmds(uint32_t value) INLINE { E::set32(header.fields.sizeofcmds, value); } - - uint32_t flags() const INLINE { return E::get32(header.fields.flags); } - void set_flags(uint32_t value) INLINE { E::set32(header.fields.flags, value); } - - uint32_t reserved() const INLINE { return E::get32(header.fields.reserved); } - void set_reserved(uint32_t value) INLINE { E::set32(header.fields.reserved, value); } - - typedef typename P::E E; -private: - macho_header_content<P> header; -}; - - -// -// mach-o load command -// -template <typename P> -class macho_load_command { -public: - uint32_t cmd() const INLINE { return E::get32(command.cmd); } - void set_cmd(uint32_t value) INLINE { E::set32(command.cmd, value); } - - uint32_t cmdsize() const INLINE { return E::get32(command.cmdsize); } - void set_cmdsize(uint32_t value) INLINE { E::set32(command.cmdsize, value); } - - typedef typename P::E E; -private: - load_command command; -}; - - - - -// -// mach-o segment load command -// -template <typename P> struct macho_segment_content {}; -template <> struct macho_segment_content<Pointer32<BigEndian> > { segment_command fields; enum { CMD = LC_SEGMENT }; }; -template <> struct macho_segment_content<Pointer64<BigEndian> > { segment_command_64 fields; enum { CMD = LC_SEGMENT_64 }; }; -template <> struct macho_segment_content<Pointer32<LittleEndian> > { segment_command fields; enum { CMD = LC_SEGMENT }; }; -template <> struct macho_segment_content<Pointer64<LittleEndian> > { segment_command_64 fields; enum { CMD = LC_SEGMENT_64 }; }; - -template <typename P> -class macho_segment_command { -public: - uint32_t cmd() const INLINE { return E::get32(segment.fields.cmd); } - void set_cmd(uint32_t value) INLINE { E::set32(segment.fields.cmd, value); } - - uint32_t cmdsize() const INLINE { return E::get32(segment.fields.cmdsize); } - void set_cmdsize(uint32_t value) INLINE { E::set32(segment.fields.cmdsize, value); } - - const char* segname() const INLINE { return segment.fields.segname; } - void set_segname(const char* value) INLINE { strncpy(segment.fields.segname, value, 16); } - - uint64_t vmaddr() const INLINE { return P::getP(segment.fields.vmaddr); } - void set_vmaddr(uint64_t value) INLINE { P::setP(segment.fields.vmaddr, value); } - - uint64_t vmsize() const INLINE { return P::getP(segment.fields.vmsize); } - void set_vmsize(uint64_t value) INLINE { P::setP(segment.fields.vmsize, value); } - - uint64_t fileoff() const INLINE { return P::getP(segment.fields.fileoff); } - void set_fileoff(uint64_t value) INLINE { P::setP(segment.fields.fileoff, value); } - - uint64_t filesize() const INLINE { return P::getP(segment.fields.filesize); } - void set_filesize(uint64_t value) INLINE { P::setP(segment.fields.filesize, value); } - - uint32_t maxprot() const INLINE { return E::get32(segment.fields.maxprot); } - void set_maxprot(uint32_t value) INLINE { E::set32((uint32_t&)segment.fields.maxprot, value); } - - uint32_t initprot() const INLINE { return E::get32(segment.fields.initprot); } - void set_initprot(uint32_t value) INLINE { E::set32((uint32_t&)segment.fields.initprot, value); } - - uint32_t nsects() const INLINE { return E::get32(segment.fields.nsects); } - void set_nsects(uint32_t value) INLINE { E::set32(segment.fields.nsects, value); } - - uint32_t flags() const INLINE { return E::get32(segment.fields.flags); } - void set_flags(uint32_t value) INLINE { E::set32(segment.fields.flags, value); } - - enum { - CMD = macho_segment_content<P>::CMD - }; - - typedef typename P::E E; -private: - macho_segment_content<P> segment; -}; - - -// -// mach-o section -// -template <typename P> struct macho_section_content {}; -template <> struct macho_section_content<Pointer32<BigEndian> > { section fields; }; -template <> struct macho_section_content<Pointer64<BigEndian> > { section_64 fields; }; -template <> struct macho_section_content<Pointer32<LittleEndian> > { section fields; }; -template <> struct macho_section_content<Pointer64<LittleEndian> > { section_64 fields; }; - -template <typename P> -class macho_section { -public: - const char* sectname() const INLINE { return section.fields.sectname; } - void set_sectname(const char* value) INLINE { strncpy(section.fields.sectname, value, 16); } - - const char* segname() const INLINE { return section.fields.segname; } - void set_segname(const char* value) INLINE { strncpy(section.fields.segname, value, 16); } - - uint64_t addr() const INLINE { return P::getP(section.fields.addr); } - void set_addr(uint64_t value) INLINE { P::setP(section.fields.addr, value); } - - uint64_t size() const INLINE { return P::getP(section.fields.size); } - void set_size(uint64_t value) INLINE { P::setP(section.fields.size, value); } - - uint32_t offset() const INLINE { return E::get32(section.fields.offset); } - void set_offset(uint32_t value) INLINE { E::set32(section.fields.offset, value); } - - uint32_t align() const INLINE { return E::get32(section.fields.align); } - void set_align(uint32_t value) INLINE { E::set32(section.fields.align, value); } - - uint32_t reloff() const INLINE { return E::get32(section.fields.reloff); } - void set_reloff(uint32_t value) INLINE { E::set32(section.fields.reloff, value); } - - uint32_t nreloc() const INLINE { return E::get32(section.fields.nreloc); } - void set_nreloc(uint32_t value) INLINE { E::set32(section.fields.nreloc, value); } - - uint32_t flags() const INLINE { return E::get32(section.fields.flags); } - void set_flags(uint32_t value) INLINE { E::set32(section.fields.flags, value); } - - uint32_t reserved1() const INLINE { return E::get32(section.fields.reserved1); } - void set_reserved1(uint32_t value) INLINE { E::set32(section.fields.reserved1, value); } - - uint32_t reserved2() const INLINE { return E::get32(section.fields.reserved2); } - void set_reserved2(uint32_t value) INLINE { E::set32(section.fields.reserved2, value); } - - typedef typename P::E E; -private: - macho_section_content<P> section; -}; - - - - -static bool debug = true; - -bool processFile(const char *filename); - -int main(int argc, const char *argv[]) { - for (int i = 1; i < argc; ++i) { - if (!processFile(argv[i])) return 1; - } - return 0; -} - -struct imageinfo { - uint32_t version; - uint32_t flags; -}; - - -// Segment and section names are 16 bytes and may be un-terminated. -bool segnameEquals(const char *lhs, const char *rhs) -{ - return 0 == strncmp(lhs, rhs, 16); -} - -bool segnameStartsWith(const char *segname, const char *prefix) -{ - return 0 == strncmp(segname, prefix, strlen(prefix)); -} - -bool sectnameEquals(const char *lhs, const char *rhs) -{ - return segnameEquals(lhs, rhs); -} - - -template <typename P> -void dosect(uint8_t *start, macho_section<P> *sect, bool isOldABI, bool isOSX) -{ - if (debug) printf("section %.16s from segment %.16s\n", - sect->sectname(), sect->segname()); - - if (isOSX) { - // Add "supports GC" flag to objc image info - if ((segnameStartsWith(sect->segname(), "__DATA") && - sectnameEquals(sect->sectname(), "__objc_imageinfo")) || - (segnameEquals(sect->segname(), "__OBJC") && - sectnameEquals(sect->sectname(), "__image_info"))) - { - imageinfo *ii = (imageinfo*)(start + sect->offset()); - P::E::set32(ii->flags, P::E::get32(ii->flags) | OBJC_IMAGE_SUPPORTS_GC); - if (debug) printf("added GC support flag\n"); - } - } - - if (isOldABI) { - // Keep init funcs because libSystem doesn't call _objc_init(). - } else { - // Strip S_MOD_INIT/TERM_FUNC_POINTERS. We don't want dyld to call - // our init funcs because it is too late, and we don't want anyone to - // call our term funcs ever. - if (segnameStartsWith(sect->segname(), "__DATA") && - sectnameEquals(sect->sectname(), "__mod_init_func")) - { - // section type 0 is S_REGULAR - sect->set_flags(sect->flags() & ~SECTION_TYPE); - sect->set_sectname("__objc_init_func"); - if (debug) printf("disabled __mod_init_func section\n"); - } - if (segnameStartsWith(sect->segname(), "__DATA") && - sectnameEquals(sect->sectname(), "__mod_term_func")) - { - // section type 0 is S_REGULAR - sect->set_flags(sect->flags() & ~SECTION_TYPE); - sect->set_sectname("__objc_term_func"); - if (debug) printf("disabled __mod_term_func section\n"); - } - } -} - -template <typename P> -void doseg(uint8_t *start, macho_segment_command<P> *seg, - bool isOldABI, bool isOSX) -{ - if (debug) printf("segment name: %.16s, nsects %u\n", - seg->segname(), seg->nsects()); - macho_section<P> *sect = (macho_section<P> *)(seg + 1); - for (uint32_t i = 0; i < seg->nsects(); ++i) { - dosect(start, §[i], isOldABI, isOSX); - } -} - - -template<typename P> -bool parse_macho(uint8_t *buffer) -{ - macho_header<P>* mh = (macho_header<P>*)buffer; - uint8_t *cmds; - - bool isOldABI = false; - bool isOSX = false; - cmds = (uint8_t *)(mh + 1); - for (uint32_t c = 0; c < mh->ncmds(); c++) { - macho_load_command<P>* cmd = (macho_load_command<P>*)cmds; - cmds += cmd->cmdsize(); - if (cmd->cmd() == LC_SEGMENT || cmd->cmd() == LC_SEGMENT_64) { - macho_segment_command<P>* seg = (macho_segment_command<P>*)cmd; - if (segnameEquals(seg->segname(), "__OBJC")) isOldABI = true; - } - else if (cmd->cmd() == LC_VERSION_MIN_MACOSX) { - isOSX = true; - } - } - - if (debug) printf("ABI=%s, OS=%s\n", - isOldABI ? "old" : "new", isOSX ? "osx" : "ios"); - - cmds = (uint8_t *)(mh + 1); - for (uint32_t c = 0; c < mh->ncmds(); c++) { - macho_load_command<P>* cmd = (macho_load_command<P>*)cmds; - cmds += cmd->cmdsize(); - if (cmd->cmd() == LC_SEGMENT || cmd->cmd() == LC_SEGMENT_64) { - doseg(buffer, (macho_segment_command<P>*)cmd, isOldABI, isOSX); - } - } - - return true; -} - - -bool parse_macho(uint8_t *buffer) -{ - uint32_t magic = *(uint32_t *)buffer; - - switch (magic) { - case MH_MAGIC_64: - return parse_macho<Pointer64<CurrentEndian>>(buffer); - case MH_MAGIC: - return parse_macho<Pointer32<CurrentEndian>>(buffer); - case MH_CIGAM_64: - return parse_macho<Pointer64<OtherEndian>>(buffer); - case MH_CIGAM: - return parse_macho<Pointer32<OtherEndian>>(buffer); - default: - printf("file is not mach-o (magic %x)\n", magic); - return false; - } -} - - -bool parse_fat(uint8_t *buffer, size_t size) -{ - uint32_t magic; - - if (size < sizeof(magic)) { - printf("file is too small\n"); - return false; - } - - magic = *(uint32_t *)buffer; - if (magic != FAT_MAGIC && magic != FAT_CIGAM) { - /* Not a fat file */ - return parse_macho(buffer); - } else { - struct fat_header *fh; - uint32_t fat_magic, fat_nfat_arch; - struct fat_arch *archs; - - if (size < sizeof(struct fat_header)) { - printf("file is too small\n"); - return false; - } - - fh = (struct fat_header *)buffer; - fat_magic = OSSwapBigToHostInt32(fh->magic); - fat_nfat_arch = OSSwapBigToHostInt32(fh->nfat_arch); - - if (size < (sizeof(struct fat_header) + fat_nfat_arch * sizeof(struct fat_arch))) { - printf("file is too small\n"); - return false; - } - - archs = (struct fat_arch *)(buffer + sizeof(struct fat_header)); - - /* Special case hidden CPU_TYPE_ARM64 */ - if (size >= (sizeof(struct fat_header) + (fat_nfat_arch + 1) * sizeof(struct fat_arch))) { - if (fat_nfat_arch > 0 - && OSSwapBigToHostInt32(archs[fat_nfat_arch].cputype) == CPU_TYPE_ARM64) { - fat_nfat_arch++; - } - } - /* End special case hidden CPU_TYPE_ARM64 */ - - if (debug) printf("%d fat architectures\n", - fat_nfat_arch); - - for (uint32_t i = 0; i < fat_nfat_arch; i++) { - uint32_t arch_cputype = OSSwapBigToHostInt32(archs[i].cputype); - uint32_t arch_cpusubtype = OSSwapBigToHostInt32(archs[i].cpusubtype); - uint32_t arch_offset = OSSwapBigToHostInt32(archs[i].offset); - uint32_t arch_size = OSSwapBigToHostInt32(archs[i].size); - - if (debug) printf("cputype %d cpusubtype %d\n", - arch_cputype, arch_cpusubtype); - - /* Check that slice data is after all fat headers and archs */ - if (arch_offset < (sizeof(struct fat_header) + fat_nfat_arch * sizeof(struct fat_arch))) { - printf("file is badly formed\n"); - return false; - } - - /* Check that the slice ends before the file does */ - if (arch_offset > size) { - printf("file is badly formed\n"); - return false; - } - - if (arch_size > size) { - printf("file is badly formed\n"); - return false; - } - - if (arch_offset > (size - arch_size)) { - printf("file is badly formed\n"); - return false; - } - - bool ok = parse_macho(buffer + arch_offset); - if (!ok) return false; - } - return true; - } -} - -bool processFile(const char *filename) -{ - if (debug) printf("file %s\n", filename); - int fd = open(filename, O_RDWR); - if (fd < 0) { - printf("open %s: %s\n", filename, strerror(errno)); - return false; - } - - struct stat st; - if (fstat(fd, &st) < 0) { - printf("fstat %s: %s\n", filename, strerror(errno)); - return false; - } - - void *buffer = mmap(NULL, (size_t)st.st_size, PROT_READ|PROT_WRITE, - MAP_FILE|MAP_SHARED, fd, 0); - if (buffer == MAP_FAILED) { - printf("mmap %s: %s\n", filename, strerror(errno)); - return false; - } - - bool result = parse_fat((uint8_t *)buffer, (size_t)st.st_size); - munmap(buffer, (size_t)st.st_size); - close(fd); - return result; -} diff --git a/objc/objc-runtime/markgc.cpp b/objc/objc-runtime/markgc.cpp deleted file mode 100644 index bbef255..0000000 --- a/objc/objc-runtime/markgc.cpp +++ /dev/null @@ -1,604 +0,0 @@ -/* - * Copyright (c) 2007-2009 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 <stdlib.h> -#include <unistd.h> -#include <string.h> -#include <stdio.h> -#include <stdbool.h> -#include <fcntl.h> -#include <limits.h> -#include <sys/mman.h> -#include <sys/stat.h> -#include <sys/errno.h> -#include <mach-o/fat.h> -#include <mach-o/arch.h> -#include <mach-o/loader.h> - -// from "objc-private.h" -// masks for objc_image_info.flags -#define OBJC_IMAGE_SUPPORTS_GC (1<<1) - -// Some OS X SDKs don't define these. -#ifndef CPU_TYPE_ARM -#define CPU_TYPE_ARM ((cpu_type_t) 12) -#endif -#ifndef CPU_ARCH_ABI64 -#define CPU_ARCH_ABI64 0x01000000 /* 64 bit ABI */ -#endif -#ifndef CPU_TYPE_ARM64 -#define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64) -#endif - -// File abstraction taken from ld64/FileAbstraction.hpp -// and ld64/MachOFileAbstraction.hpp. - -#ifdef __OPTIMIZE__ -#define INLINE __attribute__((always_inline)) -#else -#define INLINE -#endif - -// -// This abstraction layer is for use with file formats that have 64-bit/32-bit and Big-Endian/Little-Endian variants -// -// For example: to make a utility that handles 32-bit little enidan files use: Pointer32<LittleEndian> -// -// -// get16() read a 16-bit number from an E endian struct -// set16() write a 16-bit number to an E endian struct -// get32() read a 32-bit number from an E endian struct -// set32() write a 32-bit number to an E endian struct -// get64() read a 64-bit number from an E endian struct -// set64() write a 64-bit number to an E endian struct -// -// getBits() read a bit field from an E endian struct (bitCount=number of bits in field, firstBit=bit index of field) -// setBits() write a bit field to an E endian struct (bitCount=number of bits in field, firstBit=bit index of field) -// -// getBitsRaw() read a bit field from a struct with native endianness -// setBitsRaw() write a bit field from a struct with native endianness -// - -class BigEndian -{ -public: - static uint16_t get16(const uint16_t& from) INLINE { return OSReadBigInt16(&from, 0); } - static void set16(uint16_t& into, uint16_t value) INLINE { OSWriteBigInt16(&into, 0, value); } - - static uint32_t get32(const uint32_t& from) INLINE { return OSReadBigInt32(&from, 0); } - static void set32(uint32_t& into, uint32_t value) INLINE { OSWriteBigInt32(&into, 0, value); } - - static uint64_t get64(const uint64_t& from) INLINE { return OSReadBigInt64(&from, 0); } - static void set64(uint64_t& into, uint64_t value) INLINE { OSWriteBigInt64(&into, 0, value); } - - static uint32_t getBits(const uint32_t& from, - uint8_t firstBit, uint8_t bitCount) INLINE { return getBitsRaw(get32(from), firstBit, bitCount); } - static void setBits(uint32_t& into, uint32_t value, - uint8_t firstBit, uint8_t bitCount) INLINE { uint32_t temp = get32(into); setBitsRaw(temp, value, firstBit, bitCount); set32(into, temp); } - - static uint32_t getBitsRaw(const uint32_t& from, - uint8_t firstBit, uint8_t bitCount) INLINE { return ((from >> (32-firstBit-bitCount)) & ((1<<bitCount)-1)); } - static void setBitsRaw(uint32_t& into, uint32_t value, - uint8_t firstBit, uint8_t bitCount) INLINE { uint32_t temp = into; - const uint32_t mask = ((1<<bitCount)-1); - temp &= ~(mask << (32-firstBit-bitCount)); - temp |= ((value & mask) << (32-firstBit-bitCount)); - into = temp; } - enum { little_endian = 0 }; -}; - - -class LittleEndian -{ -public: - static uint16_t get16(const uint16_t& from) INLINE { return OSReadLittleInt16(&from, 0); } - static void set16(uint16_t& into, uint16_t value) INLINE { OSWriteLittleInt16(&into, 0, value); } - - static uint32_t get32(const uint32_t& from) INLINE { return OSReadLittleInt32(&from, 0); } - static void set32(uint32_t& into, uint32_t value) INLINE { OSWriteLittleInt32(&into, 0, value); } - - static uint64_t get64(const uint64_t& from) INLINE { return OSReadLittleInt64(&from, 0); } - static void set64(uint64_t& into, uint64_t value) INLINE { OSWriteLittleInt64(&into, 0, value); } - - static uint32_t getBits(const uint32_t& from, - uint8_t firstBit, uint8_t bitCount) INLINE { return getBitsRaw(get32(from), firstBit, bitCount); } - static void setBits(uint32_t& into, uint32_t value, - uint8_t firstBit, uint8_t bitCount) INLINE { uint32_t temp = get32(into); setBitsRaw(temp, value, firstBit, bitCount); set32(into, temp); } - - static uint32_t getBitsRaw(const uint32_t& from, - uint8_t firstBit, uint8_t bitCount) INLINE { return ((from >> firstBit) & ((1<<bitCount)-1)); } - static void setBitsRaw(uint32_t& into, uint32_t value, - uint8_t firstBit, uint8_t bitCount) INLINE { uint32_t temp = into; - const uint32_t mask = ((1<<bitCount)-1); - temp &= ~(mask << firstBit); - temp |= ((value & mask) << firstBit); - into = temp; } - enum { little_endian = 1 }; -}; - -#if __BIG_ENDIAN__ -typedef BigEndian CurrentEndian; -typedef LittleEndian OtherEndian; -#elif __LITTLE_ENDIAN__ -typedef LittleEndian CurrentEndian; -typedef BigEndian OtherEndian; -#else -#error unknown endianness -#endif - - -template <typename _E> -class Pointer32 -{ -public: - typedef uint32_t uint_t; - typedef int32_t sint_t; - typedef _E E; - - static uint64_t getP(const uint_t& from) INLINE { return _E::get32(from); } - static void setP(uint_t& into, uint64_t value) INLINE { _E::set32(into, value); } -}; - - -template <typename _E> -class Pointer64 -{ -public: - typedef uint64_t uint_t; - typedef int64_t sint_t; - typedef _E E; - - static uint64_t getP(const uint_t& from) INLINE { return _E::get64(from); } - static void setP(uint_t& into, uint64_t value) INLINE { _E::set64(into, value); } -}; - - -// -// mach-o file header -// -template <typename P> struct macho_header_content {}; -template <> struct macho_header_content<Pointer32<BigEndian> > { mach_header fields; }; -template <> struct macho_header_content<Pointer64<BigEndian> > { mach_header_64 fields; }; -template <> struct macho_header_content<Pointer32<LittleEndian> > { mach_header fields; }; -template <> struct macho_header_content<Pointer64<LittleEndian> > { mach_header_64 fields; }; - -template <typename P> -class macho_header { -public: - uint32_t magic() const INLINE { return E::get32(header.fields.magic); } - void set_magic(uint32_t value) INLINE { E::set32(header.fields.magic, value); } - - uint32_t cputype() const INLINE { return E::get32(header.fields.cputype); } - void set_cputype(uint32_t value) INLINE { E::set32((uint32_t&)header.fields.cputype, value); } - - uint32_t cpusubtype() const INLINE { return E::get32(header.fields.cpusubtype); } - void set_cpusubtype(uint32_t value) INLINE { E::set32((uint32_t&)header.fields.cpusubtype, value); } - - uint32_t filetype() const INLINE { return E::get32(header.fields.filetype); } - void set_filetype(uint32_t value) INLINE { E::set32(header.fields.filetype, value); } - - uint32_t ncmds() const INLINE { return E::get32(header.fields.ncmds); } - void set_ncmds(uint32_t value) INLINE { E::set32(header.fields.ncmds, value); } - - uint32_t sizeofcmds() const INLINE { return E::get32(header.fields.sizeofcmds); } - void set_sizeofcmds(uint32_t value) INLINE { E::set32(header.fields.sizeofcmds, value); } - - uint32_t flags() const INLINE { return E::get32(header.fields.flags); } - void set_flags(uint32_t value) INLINE { E::set32(header.fields.flags, value); } - - uint32_t reserved() const INLINE { return E::get32(header.fields.reserved); } - void set_reserved(uint32_t value) INLINE { E::set32(header.fields.reserved, value); } - - typedef typename P::E E; -private: - macho_header_content<P> header; -}; - - -// -// mach-o load command -// -template <typename P> -class macho_load_command { -public: - uint32_t cmd() const INLINE { return E::get32(command.cmd); } - void set_cmd(uint32_t value) INLINE { E::set32(command.cmd, value); } - - uint32_t cmdsize() const INLINE { return E::get32(command.cmdsize); } - void set_cmdsize(uint32_t value) INLINE { E::set32(command.cmdsize, value); } - - typedef typename P::E E; -private: - load_command command; -}; - - - - -// -// mach-o segment load command -// -template <typename P> struct macho_segment_content {}; -template <> struct macho_segment_content<Pointer32<BigEndian> > { segment_command fields; enum { CMD = LC_SEGMENT }; }; -template <> struct macho_segment_content<Pointer64<BigEndian> > { segment_command_64 fields; enum { CMD = LC_SEGMENT_64 }; }; -template <> struct macho_segment_content<Pointer32<LittleEndian> > { segment_command fields; enum { CMD = LC_SEGMENT }; }; -template <> struct macho_segment_content<Pointer64<LittleEndian> > { segment_command_64 fields; enum { CMD = LC_SEGMENT_64 }; }; - -template <typename P> -class macho_segment_command { -public: - uint32_t cmd() const INLINE { return E::get32(segment.fields.cmd); } - void set_cmd(uint32_t value) INLINE { E::set32(segment.fields.cmd, value); } - - uint32_t cmdsize() const INLINE { return E::get32(segment.fields.cmdsize); } - void set_cmdsize(uint32_t value) INLINE { E::set32(segment.fields.cmdsize, value); } - - const char* segname() const INLINE { return segment.fields.segname; } - void set_segname(const char* value) INLINE { strncpy(segment.fields.segname, value, 16); } - - uint64_t vmaddr() const INLINE { return P::getP(segment.fields.vmaddr); } - void set_vmaddr(uint64_t value) INLINE { P::setP(segment.fields.vmaddr, value); } - - uint64_t vmsize() const INLINE { return P::getP(segment.fields.vmsize); } - void set_vmsize(uint64_t value) INLINE { P::setP(segment.fields.vmsize, value); } - - uint64_t fileoff() const INLINE { return P::getP(segment.fields.fileoff); } - void set_fileoff(uint64_t value) INLINE { P::setP(segment.fields.fileoff, value); } - - uint64_t filesize() const INLINE { return P::getP(segment.fields.filesize); } - void set_filesize(uint64_t value) INLINE { P::setP(segment.fields.filesize, value); } - - uint32_t maxprot() const INLINE { return E::get32(segment.fields.maxprot); } - void set_maxprot(uint32_t value) INLINE { E::set32((uint32_t&)segment.fields.maxprot, value); } - - uint32_t initprot() const INLINE { return E::get32(segment.fields.initprot); } - void set_initprot(uint32_t value) INLINE { E::set32((uint32_t&)segment.fields.initprot, value); } - - uint32_t nsects() const INLINE { return E::get32(segment.fields.nsects); } - void set_nsects(uint32_t value) INLINE { E::set32(segment.fields.nsects, value); } - - uint32_t flags() const INLINE { return E::get32(segment.fields.flags); } - void set_flags(uint32_t value) INLINE { E::set32(segment.fields.flags, value); } - - enum { - CMD = macho_segment_content<P>::CMD - }; - - typedef typename P::E E; -private: - macho_segment_content<P> segment; -}; - - -// -// mach-o section -// -template <typename P> struct macho_section_content {}; -template <> struct macho_section_content<Pointer32<BigEndian> > { section fields; }; -template <> struct macho_section_content<Pointer64<BigEndian> > { section_64 fields; }; -template <> struct macho_section_content<Pointer32<LittleEndian> > { section fields; }; -template <> struct macho_section_content<Pointer64<LittleEndian> > { section_64 fields; }; - -template <typename P> -class macho_section { -public: - const char* sectname() const INLINE { return section.fields.sectname; } - void set_sectname(const char* value) INLINE { strncpy(section.fields.sectname, value, 16); } - - const char* segname() const INLINE { return section.fields.segname; } - void set_segname(const char* value) INLINE { strncpy(section.fields.segname, value, 16); } - - uint64_t addr() const INLINE { return P::getP(section.fields.addr); } - void set_addr(uint64_t value) INLINE { P::setP(section.fields.addr, value); } - - uint64_t size() const INLINE { return P::getP(section.fields.size); } - void set_size(uint64_t value) INLINE { P::setP(section.fields.size, value); } - - uint32_t offset() const INLINE { return E::get32(section.fields.offset); } - void set_offset(uint32_t value) INLINE { E::set32(section.fields.offset, value); } - - uint32_t align() const INLINE { return E::get32(section.fields.align); } - void set_align(uint32_t value) INLINE { E::set32(section.fields.align, value); } - - uint32_t reloff() const INLINE { return E::get32(section.fields.reloff); } - void set_reloff(uint32_t value) INLINE { E::set32(section.fields.reloff, value); } - - uint32_t nreloc() const INLINE { return E::get32(section.fields.nreloc); } - void set_nreloc(uint32_t value) INLINE { E::set32(section.fields.nreloc, value); } - - uint32_t flags() const INLINE { return E::get32(section.fields.flags); } - void set_flags(uint32_t value) INLINE { E::set32(section.fields.flags, value); } - - uint32_t reserved1() const INLINE { return E::get32(section.fields.reserved1); } - void set_reserved1(uint32_t value) INLINE { E::set32(section.fields.reserved1, value); } - - uint32_t reserved2() const INLINE { return E::get32(section.fields.reserved2); } - void set_reserved2(uint32_t value) INLINE { E::set32(section.fields.reserved2, value); } - - typedef typename P::E E; -private: - macho_section_content<P> section; -}; - - - - -static bool debug = true; - -bool processFile(const char *filename); - -int main(int argc, const char *argv[]) { - for (int i = 1; i < argc; ++i) { - if (!processFile(argv[i])) return 1; - } - return 0; -} - -struct imageinfo { - uint32_t version; - uint32_t flags; -}; - - -// Segment and section names are 16 bytes and may be un-terminated. -bool segnameEquals(const char *lhs, const char *rhs) -{ - return 0 == strncmp(lhs, rhs, 16); -} - -bool segnameStartsWith(const char *segname, const char *prefix) -{ - return 0 == strncmp(segname, prefix, strlen(prefix)); -} - -bool sectnameEquals(const char *lhs, const char *rhs) -{ - return segnameEquals(lhs, rhs); -} - - -template <typename P> -void dosect(uint8_t *start, macho_section<P> *sect, bool isOldABI, bool isOSX) -{ - if (debug) printf("section %.16s from segment %.16s\n", - sect->sectname(), sect->segname()); - - if (isOSX) { - // Add "supports GC" flag to objc image info - if ((segnameStartsWith(sect->segname(), "__DATA") && - sectnameEquals(sect->sectname(), "__objc_imageinfo")) || - (segnameEquals(sect->segname(), "__OBJC") && - sectnameEquals(sect->sectname(), "__image_info"))) - { - imageinfo *ii = (imageinfo*)(start + sect->offset()); - P::E::set32(ii->flags, P::E::get32(ii->flags) | OBJC_IMAGE_SUPPORTS_GC); - if (debug) printf("added GC support flag\n"); - } - } - - if (isOldABI) { - // Keep init funcs because libSystem doesn't call _objc_init(). - } else { - // Strip S_MOD_INIT/TERM_FUNC_POINTERS. We don't want dyld to call - // our init funcs because it is too late, and we don't want anyone to - // call our term funcs ever. - if (segnameStartsWith(sect->segname(), "__DATA") && - sectnameEquals(sect->sectname(), "__mod_init_func")) - { - // section type 0 is S_REGULAR - sect->set_flags(sect->flags() & ~SECTION_TYPE); - sect->set_sectname("__objc_init_func"); - if (debug) printf("disabled __mod_init_func section\n"); - } - if (segnameStartsWith(sect->segname(), "__DATA") && - sectnameEquals(sect->sectname(), "__mod_term_func")) - { - // section type 0 is S_REGULAR - sect->set_flags(sect->flags() & ~SECTION_TYPE); - sect->set_sectname("__objc_term_func"); - if (debug) printf("disabled __mod_term_func section\n"); - } - } -} - -template <typename P> -void doseg(uint8_t *start, macho_segment_command<P> *seg, - bool isOldABI, bool isOSX) -{ - if (debug) printf("segment name: %.16s, nsects %u\n", - seg->segname(), seg->nsects()); - macho_section<P> *sect = (macho_section<P> *)(seg + 1); - for (uint32_t i = 0; i < seg->nsects(); ++i) { - dosect(start, §[i], isOldABI, isOSX); - } -} - - -template<typename P> -bool parse_macho(uint8_t *buffer) -{ - macho_header<P>* mh = (macho_header<P>*)buffer; - uint8_t *cmds; - - bool isOldABI = false; - bool isOSX = false; - cmds = (uint8_t *)(mh + 1); - for (uint32_t c = 0; c < mh->ncmds(); c++) { - macho_load_command<P>* cmd = (macho_load_command<P>*)cmds; - cmds += cmd->cmdsize(); - if (cmd->cmd() == LC_SEGMENT || cmd->cmd() == LC_SEGMENT_64) { - macho_segment_command<P>* seg = (macho_segment_command<P>*)cmd; - if (segnameEquals(seg->segname(), "__OBJC")) isOldABI = true; - } - else if (cmd->cmd() == LC_VERSION_MIN_MACOSX) { - isOSX = true; - } - } - - if (debug) printf("ABI=%s, OS=%s\n", - isOldABI ? "old" : "new", isOSX ? "osx" : "ios"); - - cmds = (uint8_t *)(mh + 1); - for (uint32_t c = 0; c < mh->ncmds(); c++) { - macho_load_command<P>* cmd = (macho_load_command<P>*)cmds; - cmds += cmd->cmdsize(); - if (cmd->cmd() == LC_SEGMENT || cmd->cmd() == LC_SEGMENT_64) { - doseg(buffer, (macho_segment_command<P>*)cmd, isOldABI, isOSX); - } - } - - return true; -} - - -bool parse_macho(uint8_t *buffer) -{ - uint32_t magic = *(uint32_t *)buffer; - - switch (magic) { - case MH_MAGIC_64: - return parse_macho<Pointer64<CurrentEndian>>(buffer); - case MH_MAGIC: - return parse_macho<Pointer32<CurrentEndian>>(buffer); - case MH_CIGAM_64: - return parse_macho<Pointer64<OtherEndian>>(buffer); - case MH_CIGAM: - return parse_macho<Pointer32<OtherEndian>>(buffer); - default: - printf("file is not mach-o (magic %x)\n", magic); - return false; - } -} - - -bool parse_fat(uint8_t *buffer, size_t size) -{ - uint32_t magic; - - if (size < sizeof(magic)) { - printf("file is too small\n"); - return false; - } - - magic = *(uint32_t *)buffer; - if (magic != FAT_MAGIC && magic != FAT_CIGAM) { - /* Not a fat file */ - return parse_macho(buffer); - } else { - struct fat_header *fh; - uint32_t fat_magic, fat_nfat_arch; - struct fat_arch *archs; - - if (size < sizeof(struct fat_header)) { - printf("file is too small\n"); - return false; - } - - fh = (struct fat_header *)buffer; - fat_magic = OSSwapBigToHostInt32(fh->magic); - fat_nfat_arch = OSSwapBigToHostInt32(fh->nfat_arch); - - if (size < (sizeof(struct fat_header) + fat_nfat_arch * sizeof(struct fat_arch))) { - printf("file is too small\n"); - return false; - } - - archs = (struct fat_arch *)(buffer + sizeof(struct fat_header)); - - /* Special case hidden CPU_TYPE_ARM64 */ - if (size >= (sizeof(struct fat_header) + (fat_nfat_arch + 1) * sizeof(struct fat_arch))) { - if (fat_nfat_arch > 0 - && OSSwapBigToHostInt32(archs[fat_nfat_arch].cputype) == CPU_TYPE_ARM64) { - fat_nfat_arch++; - } - } - /* End special case hidden CPU_TYPE_ARM64 */ - - if (debug) printf("%d fat architectures\n", - fat_nfat_arch); - - for (uint32_t i = 0; i < fat_nfat_arch; i++) { - uint32_t arch_cputype = OSSwapBigToHostInt32(archs[i].cputype); - uint32_t arch_cpusubtype = OSSwapBigToHostInt32(archs[i].cpusubtype); - uint32_t arch_offset = OSSwapBigToHostInt32(archs[i].offset); - uint32_t arch_size = OSSwapBigToHostInt32(archs[i].size); - - if (debug) printf("cputype %d cpusubtype %d\n", - arch_cputype, arch_cpusubtype); - - /* Check that slice data is after all fat headers and archs */ - if (arch_offset < (sizeof(struct fat_header) + fat_nfat_arch * sizeof(struct fat_arch))) { - printf("file is badly formed\n"); - return false; - } - - /* Check that the slice ends before the file does */ - if (arch_offset > size) { - printf("file is badly formed\n"); - return false; - } - - if (arch_size > size) { - printf("file is badly formed\n"); - return false; - } - - if (arch_offset > (size - arch_size)) { - printf("file is badly formed\n"); - return false; - } - - bool ok = parse_macho(buffer + arch_offset); - if (!ok) return false; - } - return true; - } -} - -bool processFile(const char *filename) -{ - if (debug) printf("file %s\n", filename); - int fd = open(filename, O_RDWR); - if (fd < 0) { - printf("open %s: %s\n", filename, strerror(errno)); - return false; - } - - struct stat st; - if (fstat(fd, &st) < 0) { - printf("fstat %s: %s\n", filename, strerror(errno)); - return false; - } - - void *buffer = mmap(NULL, (size_t)st.st_size, PROT_READ|PROT_WRITE, - MAP_FILE|MAP_SHARED, fd, 0); - if (buffer == MAP_FAILED) { - printf("mmap %s: %s\n", filename, strerror(errno)); - return false; - } - - bool result = parse_fat((uint8_t *)buffer, (size_t)st.st_size); - munmap(buffer, (size_t)st.st_size); - close(fd); - return result; -} diff --git a/objc/objc-runtime/objc.sln b/objc/objc-runtime/objc.sln deleted file mode 100755 index ddfd6e0..0000000 --- a/objc/objc-runtime/objc.sln +++ /dev/null @@ -1,34 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual C++ Express 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "objc", "objc.vcproj", "{B3408263-0CF1-47BE-83CC-56070EFC9BC1}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "objcrt", "objcrt\objcrt.vcproj", "{E38C1996-8B3D-4050-A4B2-DC85957B047D}" - ProjectSection(ProjectDependencies) = postProject - {B3408263-0CF1-47BE-83CC-56070EFC9BC1} = {B3408263-0CF1-47BE-83CC-56070EFC9BC1} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - DebugDLL|Win32 = DebugDLL|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B3408263-0CF1-47BE-83CC-56070EFC9BC1}.Debug|Win32.ActiveCfg = Debug|Win32 - {B3408263-0CF1-47BE-83CC-56070EFC9BC1}.Debug|Win32.Build.0 = Debug|Win32 - {B3408263-0CF1-47BE-83CC-56070EFC9BC1}.DebugDLL|Win32.ActiveCfg = DebugDLL|Win32 - {B3408263-0CF1-47BE-83CC-56070EFC9BC1}.DebugDLL|Win32.Build.0 = DebugDLL|Win32 - {B3408263-0CF1-47BE-83CC-56070EFC9BC1}.Release|Win32.ActiveCfg = Release|Win32 - {B3408263-0CF1-47BE-83CC-56070EFC9BC1}.Release|Win32.Build.0 = Release|Win32 - {E38C1996-8B3D-4050-A4B2-DC85957B047D}.Debug|Win32.ActiveCfg = Debug|Win32 - {E38C1996-8B3D-4050-A4B2-DC85957B047D}.Debug|Win32.Build.0 = Debug|Win32 - {E38C1996-8B3D-4050-A4B2-DC85957B047D}.DebugDLL|Win32.ActiveCfg = Debug|Win32 - {E38C1996-8B3D-4050-A4B2-DC85957B047D}.DebugDLL|Win32.Build.0 = Debug|Win32 - {E38C1996-8B3D-4050-A4B2-DC85957B047D}.Release|Win32.ActiveCfg = Release|Win32 - {E38C1996-8B3D-4050-A4B2-DC85957B047D}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/objc/objc-runtime/objc.suo b/objc/objc-runtime/objc.suo deleted file mode 100755 index 7f8180c..0000000 Binary files a/objc/objc-runtime/objc.suo and /dev/null differ diff --git a/objc/objc-runtime/objc.vcproj b/objc/objc-runtime/objc.vcproj deleted file mode 100644 index 2c84662..0000000 --- a/objc/objc-runtime/objc.vcproj +++ /dev/null @@ -1,1088 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioProject - ProjectType="Visual C++" - Version="8.00" - Name="objc" - ProjectGUID="{B3408263-0CF1-47BE-83CC-56070EFC9BC1}" - RootNamespace="objc" - Keyword="Win32Proj" - > - <Platforms> - <Platform - Name="Win32" - /> - </Platforms> - <ToolFiles> - </ToolFiles> - <Configurations> - <Configuration - Name="Debug|Win32" - OutputDirectory="$(SolutionDir)$(ConfigurationName)" - IntermediateDirectory="$(ConfigurationName)" - ConfigurationType="2" - CharacterSet="1" - > - <Tool - Name="VCPreBuildEventTool" - Description="prebuild.bat..." - CommandLine="prebuild" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - /> - <Tool - Name="VCCLCompilerTool" - Optimization="0" - AdditionalIncludeDirectories=""$(ProjectDir)\runtime";"$(DSTROOT)\AppleInternal\include";"$(SRCROOT)\AppleInternal\include"" - PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;OBJC_EXPORTS;BUILDING_OBJC;__WIN32__;_CRT_SECURE_NO_DEPRECATE" - MinimalRebuild="true" - BasicRuntimeChecks="3" - RuntimeLibrary="3" - UsePrecompiledHeader="0" - WarningLevel="3" - Detect64BitPortabilityProblems="true" - DebugInformationFormat="4" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - AdditionalOptions="/dynamicbase" - OutputFile="$(OutDir)\$(ProjectName)_debug.dll" - LinkIncremental="2" - GenerateDebugInformation="true" - StripPrivateSymbols="$(TargetDir)$(TargetName).pdbstripped" - SubSystem="2" - OptimizeReferences="1" - EnableCOMDATFolding="0" - TargetMachine="1" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCWebDeploymentTool" - /> - <Tool - Name="VCPostBuildEventTool" - Description="Install" - CommandLine="xcopy /Y "$(TargetDir)$(TargetName).dll" "%DSTROOT%\AppleInternal\bin\" xcopy /Y "$(TargetDir)$(TargetName).exp" "%DSTROOT%\AppleInternal\bin\" xcopy /Y "$(TargetDir)$(TargetName).lib" "%DSTROOT%\AppleInternal\lib\" xcopy /Y "$(TargetDir)$(TargetName).pdb" "%DSTROOT%\AppleInternal\bin\" xcopy /Y "$(TargetDir)$(TargetName).pdbstripped" "$(TargetDir)$(TargetName).pdb" xcopy /Y "$(TargetDir)$(TargetName).pdb" "%DSTROOT%\AppleInternal\public\sym\" " - /> - </Configuration> - <Configuration - Name="Release|Win32" - OutputDirectory="$(SolutionDir)$(ConfigurationName)" - IntermediateDirectory="$(ConfigurationName)" - ConfigurationType="2" - CharacterSet="1" - WholeProgramOptimization="1" - > - <Tool - Name="VCPreBuildEventTool" - Description="prebuild.bat..." - CommandLine="prebuild" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - /> - <Tool - Name="VCCLCompilerTool" - AdditionalIncludeDirectories=""$(ProjectDir)\runtime";"$(DSTROOT)\AppleInternal\include";"$(SRCROOT)\AppleInternal\include"" - PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;OBJC_EXPORTS;BUILDING_OBJC;__WIN32__;_CRT_SECURE_NO_DEPRECATE" - RuntimeLibrary="2" - UsePrecompiledHeader="0" - WarningLevel="3" - Detect64BitPortabilityProblems="true" - DebugInformationFormat="3" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - AdditionalOptions="/dynamicbase" - LinkIncremental="1" - GenerateDebugInformation="true" - StripPrivateSymbols="$(TargetDir)$(TargetName).pdbstripped" - SubSystem="2" - OptimizeReferences="1" - EnableCOMDATFolding="2" - TargetMachine="1" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCWebDeploymentTool" - /> - <Tool - Name="VCPostBuildEventTool" - Description="Install" - CommandLine="xcopy /Y "$(TargetDir)$(TargetName).dll" "%DSTROOT%\AppleInternal\bin\" xcopy /Y "$(TargetDir)$(TargetName).exp" "%DSTROOT%\AppleInternal\bin\" xcopy /Y "$(TargetDir)$(TargetName).lib" "%DSTROOT%\AppleInternal\lib\" xcopy /Y "$(TargetDir)$(TargetName).pdb" "%DSTROOT%\AppleInternal\bin\" xcopy /Y "$(TargetDir)$(TargetName).pdbstripped" "$(TargetDir)$(TargetName).pdb" xcopy /Y "$(TargetDir)$(TargetName).pdb" "%DSTROOT%\AppleInternal\public\sym\" " - /> - </Configuration> - <Configuration - Name="DebugDLL|Win32" - OutputDirectory="$(SolutionDir)$(ConfigurationName)" - IntermediateDirectory="$(ConfigurationName)" - ConfigurationType="2" - CharacterSet="1" - > - <Tool - Name="VCPreBuildEventTool" - Description="prebuild.bat..." - CommandLine="prebuild" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - /> - <Tool - Name="VCCLCompilerTool" - Optimization="0" - AdditionalIncludeDirectories=""$(ProjectDir)\runtime";"$(DSTROOT)\AppleInternal\include";"$(SRCROOT)\AppleInternal\include"" - PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;OBJC_EXPORTS;BUILDING_OBJC;__WIN32__;_CRT_SECURE_NO_DEPRECATE" - MinimalRebuild="true" - BasicRuntimeChecks="3" - RuntimeLibrary="3" - UsePrecompiledHeader="0" - WarningLevel="3" - Detect64BitPortabilityProblems="true" - DebugInformationFormat="4" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - AdditionalOptions="/dynamicbase" - OutputFile="$(OutDir)\$(ProjectName)_debug.dll" - LinkIncremental="2" - GenerateDebugInformation="true" - StripPrivateSymbols="$(TargetDir)$(TargetName).pdbstripped" - SubSystem="2" - OptimizeReferences="1" - EnableCOMDATFolding="0" - TargetMachine="1" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCWebDeploymentTool" - /> - <Tool - Name="VCPostBuildEventTool" - Description="Install" - CommandLine="xcopy /Y "$(TargetDir)$(TargetName).dll" "%DSTROOT%\AppleInternal\bin\" xcopy /Y "$(TargetDir)$(TargetName).exp" "%DSTROOT%\AppleInternal\bin\" xcopy /Y "$(TargetDir)$(TargetName).lib" "%DSTROOT%\AppleInternal\lib\" xcopy /Y "$(TargetDir)$(TargetName).pdb" "%DSTROOT%\AppleInternal\bin\" xcopy /Y "$(TargetDir)$(TargetName).pdbstripped" "$(TargetDir)$(TargetName).pdb" xcopy /Y "$(TargetDir)$(TargetName).pdb" "%DSTROOT%\AppleInternal\public\sym\" " - /> - </Configuration> - </Configurations> - <References> - </References> - <Files> - <Filter - Name="Source Files" - Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx" - UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" - > - <File - RelativePath=".\runtime\hashtable2.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\maptable.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-cache.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-class-old.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-class.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-errors.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-exception.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-file-old.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-file.mm" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-initialize.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-layout.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-load.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-loadmethod.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-lockdebug.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\Messengers.subproj\objc-msg-win32.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-os.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-references.mm" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-runtime-new.mm" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-runtime-old.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-runtime.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-sel-set.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-sel.mm" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-sync.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\runtime\objc-typeencoding.m" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCCLCompilerTool" - CompileAs="1" - /> - </FileConfiguration> - </File> - </Filter> - <Filter - Name="Header Files" - Filter="h;hpp;hxx;hm;inl;inc;xsd" - UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" - > - <File - RelativePath=".\runtime\error.h" - > - </File> - <File - RelativePath=".\runtime\hashtable.h" - > - </File> - <File - RelativePath=".\runtime\hashtable2.h" - > - </File> - <File - RelativePath=".\runtime\maptable.h" - > - </File> - <File - RelativePath=".\runtime\message.h" - > - </File> - <File - RelativePath=".\runtime\objc-api.h" - > - </File> - <File - RelativePath=".\runtime\objc-auto.h" - > - </File> - <File - RelativePath=".\runtime\objc-class.h" - > - </File> - <File - RelativePath=".\runtime\objc-config.h" - > - </File> - <File - RelativePath=".\runtime\objc-exception.h" - > - </File> - <File - RelativePath=".\runtime\objc-file-old.h" - > - </File> - <File - RelativePath=".\runtime\objc-file.h" - > - </File> - <File - RelativePath=".\runtime\objc-initialize.h" - > - </File> - <File - RelativePath=".\runtime\objc-load.h" - > - </File> - <File - RelativePath=".\runtime\objc-loadmethod.h" - > - </File> - <File - RelativePath=".\runtime\objc-os.h" - > - </File> - <File - RelativePath=".\runtime\objc-private.h" - > - </File> - <File - RelativePath=".\runtime\objc-references.h" - > - </File> - <File - RelativePath=".\runtime\objc-runtime-new.h" - > - </File> - <File - RelativePath=".\runtime\objc-runtime.h" - > - </File> - <File - RelativePath=".\runtime\objc-sel-set.h" - > - </File> - <File - RelativePath=".\runtime\objc-sel-table.h" - > - </File> - <File - RelativePath=".\runtime\objc-sync.h" - > - </File> - <File - RelativePath=".\runtime\objc.h" - > - </File> - <File - RelativePath=".\runtime\objcrt.h" - > - </File> - <File - RelativePath=".\runtime\Protocol.h" - > - </File> - <File - RelativePath=".\runtime\runtime.h" - > - </File> - </Filter> - <Filter - Name="Resource Files" - Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav" - UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}" - > - <File - RelativePath=".\version.rc" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCResourceCompilerTool" - AdditionalIncludeDirectories="$(OBJROOT)" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCResourceCompilerTool" - AdditionalIncludeDirectories="$(OBJROOT)" - /> - </FileConfiguration> - <FileConfiguration - Name="DebugDLL|Win32" - > - <Tool - Name="VCResourceCompilerTool" - AdditionalIncludeDirectories="$(OBJROOT)" - /> - </FileConfiguration> - </File> - </Filter> - </Files> - <Globals> - </Globals> -</VisualStudioProject> diff --git a/objc/objc-runtime/objc.xcodeproj/project.pbxproj b/objc/objc-runtime/objc.xcodeproj/project.pbxproj deleted file mode 100755 index 5c45b22..0000000 --- a/objc/objc-runtime/objc.xcodeproj/project.pbxproj +++ /dev/null @@ -1,1347 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 00396A861C81654B00667CB8 /* libobjc.A.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = D2AAC0630554660B00DB518D /* libobjc.A.dylib */; }; - 305B27561C7D9E96005AC125 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 305B27551C7D9E96005AC125 /* main.m */; }; - 307ED08F1C78839C000D10DC /* objc-accessors.mm in Sources */ = {isa = PBXBuildFile; fileRef = 307ED08E1C78839C000D10DC /* objc-accessors.mm */; }; - 307ED0911C7883B3000D10DC /* objc-accessors.h in Headers */ = {isa = PBXBuildFile; fileRef = 307ED0901C7883B3000D10DC /* objc-accessors.h */; }; - 3082F17A1BCF4C4500104AE9 /* Object.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3082F1791BCF4C4500104AE9 /* Object.mm */; }; - 3082F1831BCF4C7000104AE9 /* objc-runtime-old.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3082F17B1BCF4C7000104AE9 /* objc-runtime-old.mm */; }; - 3082F1841BCF4C7000104AE9 /* objc-auto.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3082F17C1BCF4C7000104AE9 /* objc-auto.mm */; }; - 3082F1851BCF4C7000104AE9 /* objc-cache-old.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3082F17D1BCF4C7000104AE9 /* objc-cache-old.mm */; }; - 3082F1861BCF4C7000104AE9 /* objc-class-old.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3082F17E1BCF4C7000104AE9 /* objc-class-old.mm */; }; - 3082F1871BCF4C7000104AE9 /* a1a2-blocktramps-arm64.s in Sources */ = {isa = PBXBuildFile; fileRef = 3082F17F1BCF4C7000104AE9 /* a1a2-blocktramps-arm64.s */; }; - 3082F1881BCF4C7000104AE9 /* objc-sel-old.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3082F1801BCF4C7000104AE9 /* objc-sel-old.mm */; }; - 3082F1891BCF4C7000104AE9 /* objc-auto-dump.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3082F1811BCF4C7000104AE9 /* objc-auto-dump.mm */; }; - 3082F18A1BCF4C7000104AE9 /* objc-file-old.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3082F1821BCF4C7000104AE9 /* objc-file-old.mm */; }; - 393CEAC00DC69E3E000B69DE /* objc-references.mm in Sources */ = {isa = PBXBuildFile; fileRef = 393CEABF0DC69E3E000B69DE /* objc-references.mm */; }; - 393CEAC60DC69E67000B69DE /* objc-references.h in Headers */ = {isa = PBXBuildFile; fileRef = 393CEAC50DC69E67000B69DE /* objc-references.h */; }; - 399BC72E1224831B007FBDF0 /* objc-externalref.mm in Sources */ = {isa = PBXBuildFile; fileRef = 399BC72D1224831B007FBDF0 /* objc-externalref.mm */; }; - 39ABD72312F0B61800D1054C /* objc-weak.h in Headers */ = {isa = PBXBuildFile; fileRef = 39ABD71F12F0B61800D1054C /* objc-weak.h */; }; - 39ABD72412F0B61800D1054C /* objc-weak.mm in Sources */ = {isa = PBXBuildFile; fileRef = 39ABD72012F0B61800D1054C /* objc-weak.mm */; }; - 39ABD72512F0B61800D1054C /* objc-weak.h in Headers */ = {isa = PBXBuildFile; fileRef = 39ABD71F12F0B61800D1054C /* objc-weak.h */; }; - 39ABD72612F0B61800D1054C /* objc-weak.mm in Sources */ = {isa = PBXBuildFile; fileRef = 39ABD72012F0B61800D1054C /* objc-weak.mm */; }; - 722437721D0C74E6008A731A /* XXObject.m in Sources */ = {isa = PBXBuildFile; fileRef = 722437711D0C74E6008A731A /* XXObject.m */; }; - 830F2A740D737FB800392440 /* objc-msg-arm.s in Sources */ = {isa = PBXBuildFile; fileRef = 830F2A690D737FB800392440 /* objc-msg-arm.s */; }; - 830F2A750D737FB900392440 /* objc-msg-i386.s in Sources */ = {isa = PBXBuildFile; fileRef = 830F2A6A0D737FB800392440 /* objc-msg-i386.s */; }; - 830F2A7D0D737FBB00392440 /* objc-msg-x86_64.s in Sources */ = {isa = PBXBuildFile; fileRef = 830F2A720D737FB800392440 /* objc-msg-x86_64.s */; }; - 830F2A980D738DC200392440 /* hashtable.h in Headers */ = {isa = PBXBuildFile; fileRef = 830F2A970D738DC200392440 /* hashtable.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83112ED40F00599600A5FBAF /* objc-internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 83112ED30F00599600A5FBAF /* objc-internal.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 831C85D50E10CF850066E64C /* objc-os.h in Headers */ = {isa = PBXBuildFile; fileRef = 831C85D30E10CF850066E64C /* objc-os.h */; }; - 831C85D60E10CF850066E64C /* objc-os.mm in Sources */ = {isa = PBXBuildFile; fileRef = 831C85D40E10CF850066E64C /* objc-os.mm */; }; - 834266D80E665A8B002E4DA2 /* objc-gdb.h in Headers */ = {isa = PBXBuildFile; fileRef = 834266D70E665A8B002E4DA2 /* objc-gdb.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 834EC0A411614167009B2563 /* objc-abi.h in Headers */ = {isa = PBXBuildFile; fileRef = 834EC0A311614167009B2563 /* objc-abi.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 83725F4A14CA5BFA0014370E /* objc-opt.mm in Sources */ = {isa = PBXBuildFile; fileRef = 83725F4914CA5BFA0014370E /* objc-opt.mm */; }; - 83725F4C14CA5C210014370E /* objc-opt.mm in Sources */ = {isa = PBXBuildFile; fileRef = 83725F4914CA5BFA0014370E /* objc-opt.mm */; }; - 8383A3A3122600E9009290B8 /* a1a2-blocktramps-arm.s in Sources */ = {isa = PBXBuildFile; fileRef = 8383A3A1122600E9009290B8 /* a1a2-blocktramps-arm.s */; }; - 8383A3A4122600E9009290B8 /* a2a3-blocktramps-arm.s in Sources */ = {isa = PBXBuildFile; fileRef = 8383A3A2122600E9009290B8 /* a2a3-blocktramps-arm.s */; }; - 8383A3AC122600FB009290B8 /* a1a2-blocktramps-arm.s in Sources */ = {isa = PBXBuildFile; fileRef = 8383A3A1122600E9009290B8 /* a1a2-blocktramps-arm.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3AD122600FB009290B8 /* a2a3-blocktramps-arm.s in Sources */ = {isa = PBXBuildFile; fileRef = 8383A3A2122600E9009290B8 /* a2a3-blocktramps-arm.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3AE122600FB009290B8 /* hashtable2.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485B80D6D687300CEA253 /* hashtable2.mm */; }; - 8383A3AF122600FB009290B8 /* maptable.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485BC0D6D687300CEA253 /* maptable.mm */; }; - 8383A3B3122600FB009290B8 /* objc-block-trampolines.mm in Sources */ = {isa = PBXBuildFile; fileRef = E8923DA0116AB2820071B552 /* objc-block-trampolines.mm */; }; - 8383A3B4122600FB009290B8 /* objc-cache.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485CB0D6D68A200CEA253 /* objc-cache.mm */; }; - 8383A3B6122600FB009290B8 /* objc-class.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485CE0D6D68A200CEA253 /* objc-class.mm */; }; - 8383A3B7122600FB009290B8 /* objc-errors.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D00D6D68A200CEA253 /* objc-errors.mm */; }; - 8383A3B8122600FB009290B8 /* objc-exception.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D20D6D68A200CEA253 /* objc-exception.mm */; settings = {COMPILER_FLAGS = "-fexceptions"; }; }; - 8383A3B9122600FB009290B8 /* objc-file.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D30D6D68A200CEA253 /* objc-file.mm */; }; - 8383A3BB122600FB009290B8 /* objc-initialize.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D50D6D68A200CEA253 /* objc-initialize.mm */; }; - 8383A3BC122600FB009290B8 /* objc-layout.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D60D6D68A200CEA253 /* objc-layout.mm */; }; - 8383A3BD122600FB009290B8 /* objc-load.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D80D6D68A200CEA253 /* objc-load.mm */; }; - 8383A3BE122600FB009290B8 /* objc-loadmethod.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485DA0D6D68A200CEA253 /* objc-loadmethod.mm */; }; - 8383A3BF122600FB009290B8 /* objc-lockdebug.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485DB0D6D68A200CEA253 /* objc-lockdebug.mm */; }; - 8383A3C0122600FB009290B8 /* objc-os.mm in Sources */ = {isa = PBXBuildFile; fileRef = 831C85D40E10CF850066E64C /* objc-os.mm */; }; - 8383A3C1122600FB009290B8 /* objc-references.mm in Sources */ = {isa = PBXBuildFile; fileRef = 393CEABF0DC69E3E000B69DE /* objc-references.mm */; }; - 8383A3C3122600FB009290B8 /* objc-runtime-new.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485E10D6D68A200CEA253 /* objc-runtime-new.mm */; }; - 8383A3C5122600FB009290B8 /* objc-runtime.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485E40D6D68A200CEA253 /* objc-runtime.mm */; }; - 8383A3C6122600FB009290B8 /* objc-sel-set.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485E60D6D68A200CEA253 /* objc-sel-set.mm */; }; - 8383A3C7122600FB009290B8 /* objc-sel-table.s in Sources */ = {isa = PBXBuildFile; fileRef = 83EB007A121C9EC200B92C16 /* objc-sel-table.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3C8122600FB009290B8 /* objc-sel.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485E80D6D68A200CEA253 /* objc-sel.mm */; }; - 8383A3C9122600FB009290B8 /* objc-sync.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485EA0D6D68A200CEA253 /* objc-sync.mm */; }; - 8383A3CA122600FB009290B8 /* objc-typeencoding.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485EB0D6D68A200CEA253 /* objc-typeencoding.mm */; }; - 8383A3CB122600FB009290B8 /* a1a2-blocktramps-i386.s in Sources */ = {isa = PBXBuildFile; fileRef = E8923D9C116AB2820071B552 /* a1a2-blocktramps-i386.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3CC122600FB009290B8 /* a1a2-blocktramps-x86_64.s in Sources */ = {isa = PBXBuildFile; fileRef = E8923D9D116AB2820071B552 /* a1a2-blocktramps-x86_64.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3CD122600FB009290B8 /* a2a3-blocktramps-i386.s in Sources */ = {isa = PBXBuildFile; fileRef = E8923D9E116AB2820071B552 /* a2a3-blocktramps-i386.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3CE122600FB009290B8 /* a2a3-blocktramps-x86_64.s in Sources */ = {isa = PBXBuildFile; fileRef = E8923D9F116AB2820071B552 /* a2a3-blocktramps-x86_64.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3D0122600FB009290B8 /* objc-msg-arm.s in Sources */ = {isa = PBXBuildFile; fileRef = 830F2A690D737FB800392440 /* objc-msg-arm.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3D1122600FB009290B8 /* objc-msg-i386.s in Sources */ = {isa = PBXBuildFile; fileRef = 830F2A6A0D737FB800392440 /* objc-msg-i386.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3D2122600FB009290B8 /* objc-msg-simulator-i386.s in Sources */ = {isa = PBXBuildFile; fileRef = 83B1A8BC0FF1AC0D0019EA5B /* objc-msg-simulator-i386.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3D3122600FB009290B8 /* objc-msg-x86_64.s in Sources */ = {isa = PBXBuildFile; fileRef = 830F2A720D737FB800392440 /* objc-msg-x86_64.s */; settings = {COMPILER_FLAGS = " -Qunused-arguments"; }; }; - 8383A3D4122600FB009290B8 /* objc-probes.d in Sources */ = {isa = PBXBuildFile; fileRef = 87BB4E900EC39633005D08E1 /* objc-probes.d */; }; - 8383A3DC1226291C009290B8 /* objc-externalref.mm in Sources */ = {isa = PBXBuildFile; fileRef = 399BC72D1224831B007FBDF0 /* objc-externalref.mm */; }; - 838485BF0D6D687300CEA253 /* hashtable2.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485B70D6D687300CEA253 /* hashtable2.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838485C00D6D687300CEA253 /* hashtable2.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485B80D6D687300CEA253 /* hashtable2.mm */; }; - 838485C30D6D687300CEA253 /* maptable.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485BB0D6D687300CEA253 /* maptable.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 838485C40D6D687300CEA253 /* maptable.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485BC0D6D687300CEA253 /* maptable.mm */; }; - 838485EF0D6D68A200CEA253 /* objc-api.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485C80D6D68A200CEA253 /* objc-api.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838485F00D6D68A200CEA253 /* objc-auto.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485C90D6D68A200CEA253 /* objc-auto.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838485F20D6D68A200CEA253 /* objc-cache.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485CB0D6D68A200CEA253 /* objc-cache.mm */; }; - 838485F40D6D68A200CEA253 /* objc-class.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485CD0D6D68A200CEA253 /* objc-class.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838485F50D6D68A200CEA253 /* objc-class.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485CE0D6D68A200CEA253 /* objc-class.mm */; }; - 838485F60D6D68A200CEA253 /* objc-config.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485CF0D6D68A200CEA253 /* objc-config.h */; }; - 838485F70D6D68A200CEA253 /* objc-errors.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D00D6D68A200CEA253 /* objc-errors.mm */; }; - 838485F80D6D68A200CEA253 /* objc-exception.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485D10D6D68A200CEA253 /* objc-exception.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838485F90D6D68A200CEA253 /* objc-exception.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D20D6D68A200CEA253 /* objc-exception.mm */; settings = {COMPILER_FLAGS = "-fexceptions"; }; }; - 838485FA0D6D68A200CEA253 /* objc-file.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D30D6D68A200CEA253 /* objc-file.mm */; }; - 838485FB0D6D68A200CEA253 /* objc-initialize.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485D40D6D68A200CEA253 /* objc-initialize.h */; }; - 838485FC0D6D68A200CEA253 /* objc-initialize.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D50D6D68A200CEA253 /* objc-initialize.mm */; }; - 838485FD0D6D68A200CEA253 /* objc-layout.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D60D6D68A200CEA253 /* objc-layout.mm */; }; - 838485FE0D6D68A200CEA253 /* objc-load.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485D70D6D68A200CEA253 /* objc-load.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838485FF0D6D68A200CEA253 /* objc-load.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485D80D6D68A200CEA253 /* objc-load.mm */; }; - 838486000D6D68A200CEA253 /* objc-loadmethod.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485D90D6D68A200CEA253 /* objc-loadmethod.h */; }; - 838486010D6D68A200CEA253 /* objc-loadmethod.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485DA0D6D68A200CEA253 /* objc-loadmethod.mm */; }; - 838486020D6D68A200CEA253 /* objc-lockdebug.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485DB0D6D68A200CEA253 /* objc-lockdebug.mm */; }; - 838486030D6D68A200CEA253 /* objc-private.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485DC0D6D68A200CEA253 /* objc-private.h */; }; - 838486070D6D68A200CEA253 /* objc-runtime-new.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485E00D6D68A200CEA253 /* objc-runtime-new.h */; }; - 838486080D6D68A200CEA253 /* objc-runtime-new.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485E10D6D68A200CEA253 /* objc-runtime-new.mm */; }; - 8384860A0D6D68A200CEA253 /* objc-runtime.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485E30D6D68A200CEA253 /* objc-runtime.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8384860B0D6D68A200CEA253 /* objc-runtime.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485E40D6D68A200CEA253 /* objc-runtime.mm */; }; - 8384860C0D6D68A200CEA253 /* objc-sel-set.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485E50D6D68A200CEA253 /* objc-sel-set.h */; }; - 8384860D0D6D68A200CEA253 /* objc-sel-set.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485E60D6D68A200CEA253 /* objc-sel-set.mm */; }; - 8384860F0D6D68A200CEA253 /* objc-sel.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485E80D6D68A200CEA253 /* objc-sel.mm */; }; - 838486100D6D68A200CEA253 /* objc-sync.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485E90D6D68A200CEA253 /* objc-sync.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838486110D6D68A200CEA253 /* objc-sync.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485EA0D6D68A200CEA253 /* objc-sync.mm */; }; - 838486120D6D68A200CEA253 /* objc-typeencoding.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838485EB0D6D68A200CEA253 /* objc-typeencoding.mm */; }; - 838486130D6D68A200CEA253 /* objc.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485EC0D6D68A200CEA253 /* objc.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838486140D6D68A200CEA253 /* Object.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485ED0D6D68A200CEA253 /* Object.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8384861E0D6D68A800CEA253 /* Protocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 838486180D6D68A800CEA253 /* Protocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8384861F0D6D68A800CEA253 /* Protocol.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838486190D6D68A800CEA253 /* Protocol.mm */; }; - 838486200D6D68A800CEA253 /* runtime.h in Headers */ = {isa = PBXBuildFile; fileRef = 8384861A0D6D68A800CEA253 /* runtime.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838486250D6D68F000CEA253 /* List.m in Sources */ = {isa = PBXBuildFile; fileRef = 838486230D6D68F000CEA253 /* List.m */; }; - 838486260D6D68F000CEA253 /* List.h in Headers */ = {isa = PBXBuildFile; fileRef = 838486240D6D68F000CEA253 /* List.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 838486280D6D6A2400CEA253 /* message.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485BD0D6D687300CEA253 /* message.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83B1A8BE0FF1AC0D0019EA5B /* objc-msg-simulator-i386.s in Sources */ = {isa = PBXBuildFile; fileRef = 83B1A8BC0FF1AC0D0019EA5B /* objc-msg-simulator-i386.s */; }; - 83BE02E80FCCB24D00661494 /* objc-file-old.h in Headers */ = {isa = PBXBuildFile; fileRef = 83BE02E50FCCB24D00661494 /* objc-file-old.h */; }; - 83BE02E90FCCB24D00661494 /* objc-file.h in Headers */ = {isa = PBXBuildFile; fileRef = 83BE02E60FCCB24D00661494 /* objc-file.h */; }; - 83BE02EA0FCCB24D00661494 /* objc-runtime-old.h in Headers */ = {isa = PBXBuildFile; fileRef = 83BE02E70FCCB24D00661494 /* objc-runtime-old.h */; }; - 83E50CDB0FF19E8200D74C19 /* hashtable2.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485B70D6D687300CEA253 /* hashtable2.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CDC0FF19E8200D74C19 /* maptable.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485BB0D6D687300CEA253 /* maptable.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 83E50CDD0FF19E8200D74C19 /* objc-api.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485C80D6D68A200CEA253 /* objc-api.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CDE0FF19E8200D74C19 /* objc-auto.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485C90D6D68A200CEA253 /* objc-auto.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CDF0FF19E8200D74C19 /* objc-auto-dump.h in Headers */ = {isa = PBXBuildFile; fileRef = BC07A00B0EF72D360014EC61 /* objc-auto-dump.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 83E50CE00FF19E8200D74C19 /* objc-class.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485CD0D6D68A200CEA253 /* objc-class.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CE10FF19E8200D74C19 /* objc-config.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485CF0D6D68A200CEA253 /* objc-config.h */; }; - 83E50CE20FF19E8200D74C19 /* objc-exception.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485D10D6D68A200CEA253 /* objc-exception.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CE30FF19E8200D74C19 /* objc-initialize.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485D40D6D68A200CEA253 /* objc-initialize.h */; }; - 83E50CE40FF19E8200D74C19 /* objc-load.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485D70D6D68A200CEA253 /* objc-load.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CE50FF19E8200D74C19 /* objc-loadmethod.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485D90D6D68A200CEA253 /* objc-loadmethod.h */; }; - 83E50CE60FF19E8200D74C19 /* objc-private.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485DC0D6D68A200CEA253 /* objc-private.h */; }; - 83E50CE80FF19E8200D74C19 /* objc-runtime-new.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485E00D6D68A200CEA253 /* objc-runtime-new.h */; }; - 83E50CE90FF19E8200D74C19 /* objc-runtime.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485E30D6D68A200CEA253 /* objc-runtime.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CEB0FF19E8200D74C19 /* objc-sel-set.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485E50D6D68A200CEA253 /* objc-sel-set.h */; }; - 83E50CEC0FF19E8200D74C19 /* objc-sync.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485E90D6D68A200CEA253 /* objc-sync.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CED0FF19E8200D74C19 /* objc.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485EC0D6D68A200CEA253 /* objc.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CEE0FF19E8200D74C19 /* Object.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485ED0D6D68A200CEA253 /* Object.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CEF0FF19E8200D74C19 /* Protocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 838486180D6D68A800CEA253 /* Protocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CF00FF19E8200D74C19 /* runtime.h in Headers */ = {isa = PBXBuildFile; fileRef = 8384861A0D6D68A800CEA253 /* runtime.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CF10FF19E8200D74C19 /* List.h in Headers */ = {isa = PBXBuildFile; fileRef = 838486240D6D68F000CEA253 /* List.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CF20FF19E8200D74C19 /* message.h in Headers */ = {isa = PBXBuildFile; fileRef = 838485BD0D6D687300CEA253 /* message.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CF40FF19E8200D74C19 /* hashtable.h in Headers */ = {isa = PBXBuildFile; fileRef = 830F2A970D738DC200392440 /* hashtable.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 83E50CF50FF19E8200D74C19 /* objc-references.h in Headers */ = {isa = PBXBuildFile; fileRef = 393CEAC50DC69E67000B69DE /* objc-references.h */; }; - 83E50CF60FF19E8200D74C19 /* objc-os.h in Headers */ = {isa = PBXBuildFile; fileRef = 831C85D30E10CF850066E64C /* objc-os.h */; }; - 83E50CF70FF19E8200D74C19 /* objc-gdb.h in Headers */ = {isa = PBXBuildFile; fileRef = 834266D70E665A8B002E4DA2 /* objc-gdb.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 83E50CF80FF19E8200D74C19 /* objc-internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 83112ED30F00599600A5FBAF /* objc-internal.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 83E50D140FF19E8200D74C19 /* Protocol.mm in Sources */ = {isa = PBXBuildFile; fileRef = 838486190D6D68A800CEA253 /* Protocol.mm */; }; - 83E50D150FF19E8200D74C19 /* List.m in Sources */ = {isa = PBXBuildFile; fileRef = 838486230D6D68F000CEA253 /* List.m */; }; - 83E57595121E892100295464 /* objc-abi.h in Headers */ = {isa = PBXBuildFile; fileRef = 834EC0A311614167009B2563 /* objc-abi.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 83E57596121E896200295464 /* objc-file-old.h in Headers */ = {isa = PBXBuildFile; fileRef = 83BE02E50FCCB24D00661494 /* objc-file-old.h */; }; - 83E57597121E8A0A00295464 /* objc-runtime-old.h in Headers */ = {isa = PBXBuildFile; fileRef = 83BE02E70FCCB24D00661494 /* objc-runtime-old.h */; }; - 83E57598121E8A1600295464 /* objc-file.h in Headers */ = {isa = PBXBuildFile; fileRef = 83BE02E60FCCB24D00661494 /* objc-file.h */; }; - 83EB007B121C9EC200B92C16 /* objc-sel-table.s in Sources */ = {isa = PBXBuildFile; fileRef = 83EB007A121C9EC200B92C16 /* objc-sel-table.s */; }; - 87BB4EA70EC39854005D08E1 /* objc-probes.d in Sources */ = {isa = PBXBuildFile; fileRef = 87BB4E900EC39633005D08E1 /* objc-probes.d */; }; - 9672F7EE14D5F488007CEC96 /* NSObject.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9672F7ED14D5F488007CEC96 /* NSObject.mm */; }; - 9672F7EF14D5F488007CEC96 /* NSObject.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9672F7ED14D5F488007CEC96 /* NSObject.mm */; }; - BC07A00C0EF72D360014EC61 /* objc-auto-dump.h in Headers */ = {isa = PBXBuildFile; fileRef = BC07A00B0EF72D360014EC61 /* objc-auto-dump.h */; settings = {ATTRIBUTES = (Private, ); }; }; - E8923DA1116AB2820071B552 /* a1a2-blocktramps-i386.s in Sources */ = {isa = PBXBuildFile; fileRef = E8923D9C116AB2820071B552 /* a1a2-blocktramps-i386.s */; }; - E8923DA2116AB2820071B552 /* a1a2-blocktramps-x86_64.s in Sources */ = {isa = PBXBuildFile; fileRef = E8923D9D116AB2820071B552 /* a1a2-blocktramps-x86_64.s */; }; - E8923DA3116AB2820071B552 /* a2a3-blocktramps-i386.s in Sources */ = {isa = PBXBuildFile; fileRef = E8923D9E116AB2820071B552 /* a2a3-blocktramps-i386.s */; }; - E8923DA4116AB2820071B552 /* a2a3-blocktramps-x86_64.s in Sources */ = {isa = PBXBuildFile; fileRef = E8923D9F116AB2820071B552 /* a2a3-blocktramps-x86_64.s */; }; - E8923DA5116AB2820071B552 /* objc-block-trampolines.mm in Sources */ = {isa = PBXBuildFile; fileRef = E8923DA0116AB2820071B552 /* objc-block-trampolines.mm */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 305B275A1C7DA178005AC125 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */; - proxyType = 1; - remoteGlobalIDString = D2AAC0620554660B00DB518D; - remoteInfo = objc; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 305B27511C7D9E96005AC125 /* CopyFiles */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = /usr/share/man/man1/; - dstSubfolderSpec = 0; - files = ( - ); - runOnlyForDeploymentPostprocessing = 1; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 305B27531C7D9E96005AC125 /* debug-objc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "debug-objc"; sourceTree = BUILT_PRODUCTS_DIR; }; - 305B27551C7D9E96005AC125 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; - 307ED08E1C78839C000D10DC /* objc-accessors.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-accessors.mm"; path = "runtime/objc-accessors.mm"; sourceTree = "<group>"; }; - 307ED0901C7883B3000D10DC /* objc-accessors.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-accessors.h"; path = "runtime/objc-accessors.h"; sourceTree = "<group>"; }; - 3082F1791BCF4C4500104AE9 /* Object.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = Object.mm; path = runtime/Object.mm; sourceTree = "<group>"; }; - 3082F17B1BCF4C7000104AE9 /* objc-runtime-old.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-runtime-old.mm"; path = "runtime/objc-runtime-old.mm"; sourceTree = "<group>"; }; - 3082F17C1BCF4C7000104AE9 /* objc-auto.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-auto.mm"; path = "runtime/objc-auto.mm"; sourceTree = "<group>"; }; - 3082F17D1BCF4C7000104AE9 /* objc-cache-old.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-cache-old.mm"; path = "runtime/objc-cache-old.mm"; sourceTree = "<group>"; }; - 3082F17E1BCF4C7000104AE9 /* objc-class-old.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-class-old.mm"; path = "runtime/objc-class-old.mm"; sourceTree = "<group>"; }; - 3082F17F1BCF4C7000104AE9 /* a1a2-blocktramps-arm64.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "a1a2-blocktramps-arm64.s"; path = "runtime/a1a2-blocktramps-arm64.s"; sourceTree = "<group>"; }; - 3082F1801BCF4C7000104AE9 /* objc-sel-old.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-sel-old.mm"; path = "runtime/objc-sel-old.mm"; sourceTree = "<group>"; }; - 3082F1811BCF4C7000104AE9 /* objc-auto-dump.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-auto-dump.mm"; path = "runtime/objc-auto-dump.mm"; sourceTree = "<group>"; }; - 3082F1821BCF4C7000104AE9 /* objc-file-old.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-file-old.mm"; path = "runtime/objc-file-old.mm"; sourceTree = "<group>"; }; - 393CEABF0DC69E3E000B69DE /* objc-references.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-references.mm"; path = "runtime/objc-references.mm"; sourceTree = "<group>"; }; - 393CEAC50DC69E67000B69DE /* objc-references.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-references.h"; path = "runtime/objc-references.h"; sourceTree = "<group>"; }; - 399BC72D1224831B007FBDF0 /* objc-externalref.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-externalref.mm"; path = "runtime/objc-externalref.mm"; sourceTree = "<group>"; }; - 39ABD71F12F0B61800D1054C /* objc-weak.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-weak.h"; path = "runtime/objc-weak.h"; sourceTree = "<group>"; }; - 39ABD72012F0B61800D1054C /* objc-weak.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-weak.mm"; path = "runtime/objc-weak.mm"; sourceTree = "<group>"; }; - 513A034019B4B13100448729 /* auto_zone.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = auto_zone.h; sourceTree = "<group>"; }; - 513A034119B4B13100448729 /* Block_private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Block_private.h; sourceTree = "<group>"; }; - 513A034219B4B13100448729 /* CrashReporterClient.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CrashReporterClient.h; sourceTree = "<group>"; }; - 513A034419B4B13100448729 /* benchmark.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = benchmark.h; sourceTree = "<group>"; }; - 513A034519B4B13100448729 /* private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = private.h; sourceTree = "<group>"; }; - 513A034619B4B13100448729 /* queue_private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = queue_private.h; sourceTree = "<group>"; }; - 513A034719B4B13100448729 /* source_private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = source_private.h; sourceTree = "<group>"; }; - 513A034919B4B13100448729 /* OSCrossEndian.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = OSCrossEndian.h; sourceTree = "<group>"; }; - 513A034B19B4B13100448729 /* clock_reply_server.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = clock_reply_server.h; sourceTree = "<group>"; }; - 513A034C19B4B13100448729 /* exc_server.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = exc_server.h; sourceTree = "<group>"; }; - 513A034D19B4B13100448729 /* mach_exc_server.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = mach_exc_server.h; sourceTree = "<group>"; }; - 513A034E19B4B13100448729 /* notify_server.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = notify_server.h; sourceTree = "<group>"; }; - 513A035019B4B13100448729 /* dyld_priv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = dyld_priv.h; sourceTree = "<group>"; }; - 513A035219B4B13100448729 /* asm.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = asm.h; sourceTree = "<group>"; }; - 513A035319B4B13100448729 /* ast.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ast.h; sourceTree = "<group>"; }; - 513A035419B4B13100448729 /* ast_types.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ast_types.h; sourceTree = "<group>"; }; - 513A035519B4B13100448729 /* commpage.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = commpage.h; sourceTree = "<group>"; }; - 513A035619B4B13100448729 /* cpu_affinity.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = cpu_affinity.h; sourceTree = "<group>"; }; - 513A035719B4B13100448729 /* cpu_capabilities.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = cpu_capabilities.h; sourceTree = "<group>"; }; - 513A035819B4B13100448729 /* cpu_data.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = cpu_data.h; sourceTree = "<group>"; }; - 513A035919B4B13100448729 /* cpu_number.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = cpu_number.h; sourceTree = "<group>"; }; - 513A035A19B4B13100448729 /* db_machdep.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = db_machdep.h; sourceTree = "<group>"; }; - 513A035B19B4B13100448729 /* endian.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = endian.h; sourceTree = "<group>"; }; - 513A035C19B4B13100448729 /* io_map_entries.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = io_map_entries.h; sourceTree = "<group>"; }; - 513A035D19B4B13100448729 /* lock.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = lock.h; sourceTree = "<group>"; }; - 513A035E19B4B13100448729 /* locks.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = locks.h; sourceTree = "<group>"; }; - 513A035F19B4B13100448729 /* machine_cpu.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = machine_cpu.h; sourceTree = "<group>"; }; - 513A036019B4B13100448729 /* machine_routines.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = machine_routines.h; sourceTree = "<group>"; }; - 513A036119B4B13100448729 /* machine_rpc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = machine_rpc.h; sourceTree = "<group>"; }; - 513A036219B4B13100448729 /* machlimits.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = machlimits.h; sourceTree = "<group>"; }; - 513A036319B4B13100448729 /* machparam.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = machparam.h; sourceTree = "<group>"; }; - 513A036419B4B13100448729 /* Makefile */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = "<group>"; }; - 513A036519B4B13100448729 /* pmap.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = pmap.h; sourceTree = "<group>"; }; - 513A036619B4B13100448729 /* sched_param.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = sched_param.h; sourceTree = "<group>"; }; - 513A036719B4B13100448729 /* setjmp.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = setjmp.h; sourceTree = "<group>"; }; - 513A036819B4B13100448729 /* simple_lock.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = simple_lock.h; sourceTree = "<group>"; }; - 513A036919B4B13100448729 /* task.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = task.h; sourceTree = "<group>"; }; - 513A036A19B4B13100448729 /* thread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = thread.h; sourceTree = "<group>"; }; - 513A036B19B4B13100448729 /* timer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = timer.h; sourceTree = "<group>"; }; - 513A036C19B4B13100448729 /* trap.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = trap.h; sourceTree = "<group>"; }; - 513A036D19B4B13100448729 /* vm_tuning.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = vm_tuning.h; sourceTree = "<group>"; }; - 513A036E19B4B13100448729 /* xpr.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = xpr.h; sourceTree = "<group>"; }; - 513A036F19B4B13100448729 /* objc-shared-cache.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "objc-shared-cache.h"; sourceTree = "<group>"; }; - 513A037219B4B13100448729 /* cpu_capabilities.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = cpu_capabilities.h; sourceTree = "<group>"; }; - 513A037419B4B13100448729 /* cpu_capabilities.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = cpu_capabilities.h; sourceTree = "<group>"; }; - 513A037619B4B13100448729 /* cpu_capabilities.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = cpu_capabilities.h; sourceTree = "<group>"; }; - 513A037719B4B13100448729 /* pthread_machdep.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = pthread_machdep.h; sourceTree = "<group>"; }; - 513A037819B4B13100448729 /* vproc_priv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = vproc_priv.h; sourceTree = "<group>"; }; - 722437701D0C74E6008A731A /* XXObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XXObject.h; sourceTree = "<group>"; }; - 722437711D0C74E6008A731A /* XXObject.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = XXObject.m; sourceTree = "<group>"; }; - 830F2A690D737FB800392440 /* objc-msg-arm.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "objc-msg-arm.s"; path = "runtime/Messengers.subproj/objc-msg-arm.s"; sourceTree = "<group>"; }; - 830F2A6A0D737FB800392440 /* objc-msg-i386.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "objc-msg-i386.s"; path = "runtime/Messengers.subproj/objc-msg-i386.s"; sourceTree = "<group>"; }; - 830F2A720D737FB800392440 /* objc-msg-x86_64.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "objc-msg-x86_64.s"; path = "runtime/Messengers.subproj/objc-msg-x86_64.s"; sourceTree = "<group>"; tabWidth = 8; usesTabs = 1; }; - 830F2A970D738DC200392440 /* hashtable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = hashtable.h; path = runtime/hashtable.h; sourceTree = "<group>"; }; - 830F2AA50D7394C200392440 /* markgc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = markgc.c; sourceTree = "<group>"; }; - 83112ED30F00599600A5FBAF /* objc-internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-internal.h"; path = "runtime/objc-internal.h"; sourceTree = "<group>"; }; - 831C85D30E10CF850066E64C /* objc-os.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-os.h"; path = "runtime/objc-os.h"; sourceTree = "<group>"; }; - 831C85D40E10CF850066E64C /* objc-os.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-os.mm"; path = "runtime/objc-os.mm"; sourceTree = "<group>"; }; - 834266D70E665A8B002E4DA2 /* objc-gdb.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-gdb.h"; path = "runtime/objc-gdb.h"; sourceTree = "<group>"; }; - 834EC0A311614167009B2563 /* objc-abi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-abi.h"; path = "runtime/objc-abi.h"; sourceTree = "<group>"; }; - 83725F4914CA5BFA0014370E /* objc-opt.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-opt.mm"; path = "runtime/objc-opt.mm"; sourceTree = "<group>"; }; - 8383A3A1122600E9009290B8 /* a1a2-blocktramps-arm.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "a1a2-blocktramps-arm.s"; path = "runtime/a1a2-blocktramps-arm.s"; sourceTree = "<group>"; }; - 8383A3A2122600E9009290B8 /* a2a3-blocktramps-arm.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "a2a3-blocktramps-arm.s"; path = "runtime/a2a3-blocktramps-arm.s"; sourceTree = "<group>"; }; - 838485B30D6D682B00CEA253 /* libobjc.order */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = libobjc.order; sourceTree = "<group>"; }; - 838485B40D6D683300CEA253 /* APPLE_LICENSE */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = APPLE_LICENSE; sourceTree = "<group>"; }; - 838485B50D6D683300CEA253 /* ReleaseNotes.rtf */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; path = ReleaseNotes.rtf; sourceTree = "<group>"; }; - 838485B70D6D687300CEA253 /* hashtable2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = hashtable2.h; path = runtime/hashtable2.h; sourceTree = "<group>"; }; - 838485B80D6D687300CEA253 /* hashtable2.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = hashtable2.mm; path = runtime/hashtable2.mm; sourceTree = "<group>"; }; - 838485BB0D6D687300CEA253 /* maptable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = maptable.h; path = runtime/maptable.h; sourceTree = "<group>"; }; - 838485BC0D6D687300CEA253 /* maptable.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = maptable.mm; path = runtime/maptable.mm; sourceTree = "<group>"; }; - 838485BD0D6D687300CEA253 /* message.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = message.h; path = runtime/message.h; sourceTree = "<group>"; }; - 838485C80D6D68A200CEA253 /* objc-api.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-api.h"; path = "runtime/objc-api.h"; sourceTree = "<group>"; }; - 838485C90D6D68A200CEA253 /* objc-auto.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-auto.h"; path = "runtime/objc-auto.h"; sourceTree = "<group>"; }; - 838485CB0D6D68A200CEA253 /* objc-cache.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-cache.mm"; path = "runtime/objc-cache.mm"; sourceTree = "<group>"; }; - 838485CD0D6D68A200CEA253 /* objc-class.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-class.h"; path = "runtime/objc-class.h"; sourceTree = "<group>"; }; - 838485CE0D6D68A200CEA253 /* objc-class.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-class.mm"; path = "runtime/objc-class.mm"; sourceTree = "<group>"; }; - 838485CF0D6D68A200CEA253 /* objc-config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-config.h"; path = "runtime/objc-config.h"; sourceTree = "<group>"; }; - 838485D00D6D68A200CEA253 /* objc-errors.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-errors.mm"; path = "runtime/objc-errors.mm"; sourceTree = "<group>"; }; - 838485D10D6D68A200CEA253 /* objc-exception.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-exception.h"; path = "runtime/objc-exception.h"; sourceTree = "<group>"; }; - 838485D20D6D68A200CEA253 /* objc-exception.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-exception.mm"; path = "runtime/objc-exception.mm"; sourceTree = "<group>"; }; - 838485D30D6D68A200CEA253 /* objc-file.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-file.mm"; path = "runtime/objc-file.mm"; sourceTree = "<group>"; }; - 838485D40D6D68A200CEA253 /* objc-initialize.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-initialize.h"; path = "runtime/objc-initialize.h"; sourceTree = "<group>"; }; - 838485D50D6D68A200CEA253 /* objc-initialize.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-initialize.mm"; path = "runtime/objc-initialize.mm"; sourceTree = "<group>"; }; - 838485D60D6D68A200CEA253 /* objc-layout.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-layout.mm"; path = "runtime/objc-layout.mm"; sourceTree = "<group>"; }; - 838485D70D6D68A200CEA253 /* objc-load.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-load.h"; path = "runtime/objc-load.h"; sourceTree = "<group>"; }; - 838485D80D6D68A200CEA253 /* objc-load.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-load.mm"; path = "runtime/objc-load.mm"; sourceTree = "<group>"; }; - 838485D90D6D68A200CEA253 /* objc-loadmethod.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-loadmethod.h"; path = "runtime/objc-loadmethod.h"; sourceTree = "<group>"; }; - 838485DA0D6D68A200CEA253 /* objc-loadmethod.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-loadmethod.mm"; path = "runtime/objc-loadmethod.mm"; sourceTree = "<group>"; }; - 838485DB0D6D68A200CEA253 /* objc-lockdebug.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-lockdebug.mm"; path = "runtime/objc-lockdebug.mm"; sourceTree = "<group>"; }; - 838485DC0D6D68A200CEA253 /* objc-private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-private.h"; path = "runtime/objc-private.h"; sourceTree = "<group>"; }; - 838485E00D6D68A200CEA253 /* objc-runtime-new.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-runtime-new.h"; path = "runtime/objc-runtime-new.h"; sourceTree = "<group>"; }; - 838485E10D6D68A200CEA253 /* objc-runtime-new.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-runtime-new.mm"; path = "runtime/objc-runtime-new.mm"; sourceTree = "<group>"; }; - 838485E30D6D68A200CEA253 /* objc-runtime.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-runtime.h"; path = "runtime/objc-runtime.h"; sourceTree = "<group>"; }; - 838485E40D6D68A200CEA253 /* objc-runtime.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-runtime.mm"; path = "runtime/objc-runtime.mm"; sourceTree = "<group>"; }; - 838485E50D6D68A200CEA253 /* objc-sel-set.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-sel-set.h"; path = "runtime/objc-sel-set.h"; sourceTree = "<group>"; }; - 838485E60D6D68A200CEA253 /* objc-sel-set.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-sel-set.mm"; path = "runtime/objc-sel-set.mm"; sourceTree = "<group>"; }; - 838485E80D6D68A200CEA253 /* objc-sel.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-sel.mm"; path = "runtime/objc-sel.mm"; sourceTree = "<group>"; }; - 838485E90D6D68A200CEA253 /* objc-sync.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-sync.h"; path = "runtime/objc-sync.h"; sourceTree = "<group>"; }; - 838485EA0D6D68A200CEA253 /* objc-sync.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-sync.mm"; path = "runtime/objc-sync.mm"; sourceTree = "<group>"; }; - 838485EB0D6D68A200CEA253 /* objc-typeencoding.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-typeencoding.mm"; path = "runtime/objc-typeencoding.mm"; sourceTree = "<group>"; }; - 838485EC0D6D68A200CEA253 /* objc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = objc.h; path = runtime/objc.h; sourceTree = "<group>"; }; - 838485ED0D6D68A200CEA253 /* Object.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Object.h; path = runtime/Object.h; sourceTree = "<group>"; }; - 838486180D6D68A800CEA253 /* Protocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Protocol.h; path = runtime/Protocol.h; sourceTree = "<group>"; }; - 838486190D6D68A800CEA253 /* Protocol.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = Protocol.mm; path = runtime/Protocol.mm; sourceTree = "<group>"; }; - 8384861A0D6D68A800CEA253 /* runtime.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = runtime.h; path = runtime/runtime.h; sourceTree = "<group>"; }; - 838486230D6D68F000CEA253 /* List.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = List.m; path = runtime/OldClasses.subproj/List.m; sourceTree = "<group>"; }; - 838486240D6D68F000CEA253 /* List.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = List.h; path = runtime/OldClasses.subproj/List.h; sourceTree = "<group>"; }; - 83B1A8BC0FF1AC0D0019EA5B /* objc-msg-simulator-i386.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "objc-msg-simulator-i386.s"; path = "runtime/Messengers.subproj/objc-msg-simulator-i386.s"; sourceTree = "<group>"; }; - 83BE02E50FCCB24D00661494 /* objc-file-old.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-file-old.h"; path = "runtime/objc-file-old.h"; sourceTree = "<group>"; }; - 83BE02E60FCCB24D00661494 /* objc-file.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-file.h"; path = "runtime/objc-file.h"; sourceTree = "<group>"; }; - 83BE02E70FCCB24D00661494 /* objc-runtime-old.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-runtime-old.h"; path = "runtime/objc-runtime-old.h"; sourceTree = "<group>"; }; - 83E50D2A0FF19E8200D74C19 /* libobjc.A.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libobjc.A.dylib; sourceTree = BUILT_PRODUCTS_DIR; }; - 83E50D2B0FF19E9E00D74C19 /* IndigoSDK.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = IndigoSDK.xcconfig; path = AppleInternal/XcodeConfig/IndigoSDK.xcconfig; sourceTree = DEVELOPER_DIR; }; - 83EB007A121C9EC200B92C16 /* objc-sel-table.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "objc-sel-table.s"; path = "runtime/objc-sel-table.s"; sourceTree = "<group>"; }; - 87BB4E900EC39633005D08E1 /* objc-probes.d */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.dtrace; name = "objc-probes.d"; path = "runtime/objc-probes.d"; sourceTree = "<group>"; }; - 9672F7ED14D5F488007CEC96 /* NSObject.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = NSObject.mm; path = runtime/NSObject.mm; sourceTree = "<group>"; }; - BC07A00B0EF72D360014EC61 /* objc-auto-dump.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "objc-auto-dump.h"; path = "runtime/objc-auto-dump.h"; sourceTree = "<group>"; }; - D2AAC0630554660B00DB518D /* libobjc.A.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libobjc.A.dylib; sourceTree = BUILT_PRODUCTS_DIR; }; - E8923D9C116AB2820071B552 /* a1a2-blocktramps-i386.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "a1a2-blocktramps-i386.s"; path = "runtime/a1a2-blocktramps-i386.s"; sourceTree = "<group>"; }; - E8923D9D116AB2820071B552 /* a1a2-blocktramps-x86_64.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "a1a2-blocktramps-x86_64.s"; path = "runtime/a1a2-blocktramps-x86_64.s"; sourceTree = "<group>"; }; - E8923D9E116AB2820071B552 /* a2a3-blocktramps-i386.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "a2a3-blocktramps-i386.s"; path = "runtime/a2a3-blocktramps-i386.s"; sourceTree = "<group>"; }; - E8923D9F116AB2820071B552 /* a2a3-blocktramps-x86_64.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "a2a3-blocktramps-x86_64.s"; path = "runtime/a2a3-blocktramps-x86_64.s"; sourceTree = "<group>"; }; - E8923DA0116AB2820071B552 /* objc-block-trampolines.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "objc-block-trampolines.mm"; path = "runtime/objc-block-trampolines.mm"; sourceTree = "<group>"; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 305B27501C7D9E96005AC125 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 00396A861C81654B00667CB8 /* libobjc.A.dylib in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 83E50D240FF19E8200D74C19 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - D289988505E68E00004EDB86 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 08FB7794FE84155DC02AAC07 /* objc */ = { - isa = PBXGroup; - children = ( - 513A033F19B4B13000448729 /* include */, - 838485C60D6D687700CEA253 /* Public Headers */, - 838485C70D6D688200CEA253 /* Private Headers */, - 8384862A0D6D6ABC00CEA253 /* Project Headers */, - 838486220D6D68E300CEA253 /* Obsolete Headers */, - 838486270D6D690F00CEA253 /* Obsolete Source */, - 08FB7795FE84155DC02AAC07 /* Source */, - 838485B20D6D67F900CEA253 /* Other */, - 305B27541C7D9E96005AC125 /* debug-objc */, - 1AB674ADFE9D54B511CA2CBB /* Products */, - ); - name = objc; - sourceTree = "<group>"; - }; - 08FB7795FE84155DC02AAC07 /* Source */ = { - isa = PBXGroup; - children = ( - 8383A3A1122600E9009290B8 /* a1a2-blocktramps-arm.s */, - 8383A3A2122600E9009290B8 /* a2a3-blocktramps-arm.s */, - 838485B80D6D687300CEA253 /* hashtable2.mm */, - 838485BC0D6D687300CEA253 /* maptable.mm */, - 9672F7ED14D5F488007CEC96 /* NSObject.mm */, - 838486190D6D68A800CEA253 /* Protocol.mm */, - 307ED08E1C78839C000D10DC /* objc-accessors.mm */, - 39ABD72012F0B61800D1054C /* objc-weak.mm */, - E8923DA0116AB2820071B552 /* objc-block-trampolines.mm */, - 838485CB0D6D68A200CEA253 /* objc-cache.mm */, - 838485CE0D6D68A200CEA253 /* objc-class.mm */, - 838485D00D6D68A200CEA253 /* objc-errors.mm */, - 838485D20D6D68A200CEA253 /* objc-exception.mm */, - 399BC72D1224831B007FBDF0 /* objc-externalref.mm */, - 838485D30D6D68A200CEA253 /* objc-file.mm */, - 838485D50D6D68A200CEA253 /* objc-initialize.mm */, - 838485D60D6D68A200CEA253 /* objc-layout.mm */, - 838485D80D6D68A200CEA253 /* objc-load.mm */, - 838485DA0D6D68A200CEA253 /* objc-loadmethod.mm */, - 838485DB0D6D68A200CEA253 /* objc-lockdebug.mm */, - 83725F4914CA5BFA0014370E /* objc-opt.mm */, - 831C85D40E10CF850066E64C /* objc-os.mm */, - 393CEABF0DC69E3E000B69DE /* objc-references.mm */, - 838485E10D6D68A200CEA253 /* objc-runtime-new.mm */, - 838485E40D6D68A200CEA253 /* objc-runtime.mm */, - 838485E60D6D68A200CEA253 /* objc-sel-set.mm */, - 83EB007A121C9EC200B92C16 /* objc-sel-table.s */, - 838485E80D6D68A200CEA253 /* objc-sel.mm */, - 838485EA0D6D68A200CEA253 /* objc-sync.mm */, - 838485EB0D6D68A200CEA253 /* objc-typeencoding.mm */, - E8923D9C116AB2820071B552 /* a1a2-blocktramps-i386.s */, - E8923D9D116AB2820071B552 /* a1a2-blocktramps-x86_64.s */, - E8923D9E116AB2820071B552 /* a2a3-blocktramps-i386.s */, - 830F2A690D737FB800392440 /* objc-msg-arm.s */, - E8923D9F116AB2820071B552 /* a2a3-blocktramps-x86_64.s */, - 830F2A6A0D737FB800392440 /* objc-msg-i386.s */, - 83B1A8BC0FF1AC0D0019EA5B /* objc-msg-simulator-i386.s */, - 830F2A720D737FB800392440 /* objc-msg-x86_64.s */, - 3082F17B1BCF4C7000104AE9 /* objc-runtime-old.mm */, - 3082F17C1BCF4C7000104AE9 /* objc-auto.mm */, - 3082F17D1BCF4C7000104AE9 /* objc-cache-old.mm */, - 3082F17E1BCF4C7000104AE9 /* objc-class-old.mm */, - 3082F17F1BCF4C7000104AE9 /* a1a2-blocktramps-arm64.s */, - 3082F1801BCF4C7000104AE9 /* objc-sel-old.mm */, - 3082F1811BCF4C7000104AE9 /* objc-auto-dump.mm */, - 3082F1821BCF4C7000104AE9 /* objc-file-old.mm */, - 87BB4E900EC39633005D08E1 /* objc-probes.d */, - ); - name = Source; - sourceTree = "<group>"; - }; - 1AB674ADFE9D54B511CA2CBB /* Products */ = { - isa = PBXGroup; - children = ( - D2AAC0630554660B00DB518D /* libobjc.A.dylib */, - 83E50D2A0FF19E8200D74C19 /* libobjc.A.dylib */, - 305B27531C7D9E96005AC125 /* debug-objc */, - ); - name = Products; - sourceTree = "<group>"; - }; - 305B27541C7D9E96005AC125 /* debug-objc */ = { - isa = PBXGroup; - children = ( - 305B27551C7D9E96005AC125 /* main.m */, - 722437701D0C74E6008A731A /* XXObject.h */, - 722437711D0C74E6008A731A /* XXObject.m */, - ); - path = "debug-objc"; - sourceTree = "<group>"; - }; - 513A033F19B4B13000448729 /* include */ = { - isa = PBXGroup; - children = ( - 513A034019B4B13100448729 /* auto_zone.h */, - 513A034119B4B13100448729 /* Block_private.h */, - 513A034219B4B13100448729 /* CrashReporterClient.h */, - 513A036F19B4B13100448729 /* objc-shared-cache.h */, - 513A037819B4B13100448729 /* vproc_priv.h */, - 513A034319B4B13100448729 /* dispatch */, - 513A034819B4B13100448729 /* libkern */, - 513A034A19B4B13100448729 /* mach */, - 513A034F19B4B13100448729 /* mach-o */, - 513A035119B4B13100448729 /* machine */, - 513A037019B4B13100448729 /* System */, - ); - path = include; - sourceTree = "<group>"; - }; - 513A034319B4B13100448729 /* dispatch */ = { - isa = PBXGroup; - children = ( - 513A034419B4B13100448729 /* benchmark.h */, - 513A034519B4B13100448729 /* private.h */, - 513A034619B4B13100448729 /* queue_private.h */, - 513A034719B4B13100448729 /* source_private.h */, - ); - path = dispatch; - sourceTree = "<group>"; - }; - 513A034819B4B13100448729 /* libkern */ = { - isa = PBXGroup; - children = ( - 513A034919B4B13100448729 /* OSCrossEndian.h */, - ); - path = libkern; - sourceTree = "<group>"; - }; - 513A034A19B4B13100448729 /* mach */ = { - isa = PBXGroup; - children = ( - 513A034B19B4B13100448729 /* clock_reply_server.h */, - 513A034C19B4B13100448729 /* exc_server.h */, - 513A034D19B4B13100448729 /* mach_exc_server.h */, - 513A034E19B4B13100448729 /* notify_server.h */, - ); - path = mach; - sourceTree = "<group>"; - }; - 513A034F19B4B13100448729 /* mach-o */ = { - isa = PBXGroup; - children = ( - 513A035019B4B13100448729 /* dyld_priv.h */, - ); - path = "mach-o"; - sourceTree = "<group>"; - }; - 513A035119B4B13100448729 /* machine */ = { - isa = PBXGroup; - children = ( - 513A035219B4B13100448729 /* asm.h */, - 513A035319B4B13100448729 /* ast.h */, - 513A035419B4B13100448729 /* ast_types.h */, - 513A035519B4B13100448729 /* commpage.h */, - 513A035619B4B13100448729 /* cpu_affinity.h */, - 513A035719B4B13100448729 /* cpu_capabilities.h */, - 513A035819B4B13100448729 /* cpu_data.h */, - 513A035919B4B13100448729 /* cpu_number.h */, - 513A035A19B4B13100448729 /* db_machdep.h */, - 513A035B19B4B13100448729 /* endian.h */, - 513A035C19B4B13100448729 /* io_map_entries.h */, - 513A035D19B4B13100448729 /* lock.h */, - 513A035E19B4B13100448729 /* locks.h */, - 513A035F19B4B13100448729 /* machine_cpu.h */, - 513A036019B4B13100448729 /* machine_routines.h */, - 513A036119B4B13100448729 /* machine_rpc.h */, - 513A036219B4B13100448729 /* machlimits.h */, - 513A036319B4B13100448729 /* machparam.h */, - 513A036419B4B13100448729 /* Makefile */, - 513A036519B4B13100448729 /* pmap.h */, - 513A036619B4B13100448729 /* sched_param.h */, - 513A036719B4B13100448729 /* setjmp.h */, - 513A036819B4B13100448729 /* simple_lock.h */, - 513A036919B4B13100448729 /* task.h */, - 513A036A19B4B13100448729 /* thread.h */, - 513A036B19B4B13100448729 /* timer.h */, - 513A036C19B4B13100448729 /* trap.h */, - 513A036D19B4B13100448729 /* vm_tuning.h */, - 513A036E19B4B13100448729 /* xpr.h */, - ); - path = machine; - sourceTree = "<group>"; - }; - 513A037019B4B13100448729 /* System */ = { - isa = PBXGroup; - children = ( - 513A037119B4B13100448729 /* i386 */, - 513A037319B4B13100448729 /* machine */, - 513A037519B4B13100448729 /* ppc */, - 513A037719B4B13100448729 /* pthread_machdep.h */, - ); - path = System; - sourceTree = "<group>"; - }; - 513A037119B4B13100448729 /* i386 */ = { - isa = PBXGroup; - children = ( - 513A037219B4B13100448729 /* cpu_capabilities.h */, - ); - path = i386; - sourceTree = "<group>"; - }; - 513A037319B4B13100448729 /* machine */ = { - isa = PBXGroup; - children = ( - 513A037419B4B13100448729 /* cpu_capabilities.h */, - ); - path = machine; - sourceTree = "<group>"; - }; - 513A037519B4B13100448729 /* ppc */ = { - isa = PBXGroup; - children = ( - 513A037619B4B13100448729 /* cpu_capabilities.h */, - ); - path = ppc; - sourceTree = "<group>"; - }; - 838485B20D6D67F900CEA253 /* Other */ = { - isa = PBXGroup; - children = ( - 830F2AA50D7394C200392440 /* markgc.c */, - 838485B40D6D683300CEA253 /* APPLE_LICENSE */, - 838485B50D6D683300CEA253 /* ReleaseNotes.rtf */, - 838485B30D6D682B00CEA253 /* libobjc.order */, - 83E50D2B0FF19E9E00D74C19 /* IndigoSDK.xcconfig */, - ); - name = Other; - sourceTree = "<group>"; - }; - 838485C60D6D687700CEA253 /* Public Headers */ = { - isa = PBXGroup; - children = ( - 838485BD0D6D687300CEA253 /* message.h */, - 838485C80D6D68A200CEA253 /* objc-api.h */, - 838485C90D6D68A200CEA253 /* objc-auto.h */, - 838485D10D6D68A200CEA253 /* objc-exception.h */, - 838485E90D6D68A200CEA253 /* objc-sync.h */, - 838485EC0D6D68A200CEA253 /* objc.h */, - 8384861A0D6D68A800CEA253 /* runtime.h */, - ); - name = "Public Headers"; - sourceTree = "<group>"; - }; - 838485C70D6D688200CEA253 /* Private Headers */ = { - isa = PBXGroup; - children = ( - 83112ED30F00599600A5FBAF /* objc-internal.h */, - 834EC0A311614167009B2563 /* objc-abi.h */, - 838485BB0D6D687300CEA253 /* maptable.h */, - BC07A00B0EF72D360014EC61 /* objc-auto-dump.h */, - 834266D70E665A8B002E4DA2 /* objc-gdb.h */, - ); - name = "Private Headers"; - sourceTree = "<group>"; - }; - 838486220D6D68E300CEA253 /* Obsolete Headers */ = { - isa = PBXGroup; - children = ( - 830F2A970D738DC200392440 /* hashtable.h */, - 838485B70D6D687300CEA253 /* hashtable2.h */, - 838485CD0D6D68A200CEA253 /* objc-class.h */, - 838485D70D6D68A200CEA253 /* objc-load.h */, - 838485E30D6D68A200CEA253 /* objc-runtime.h */, - 838486240D6D68F000CEA253 /* List.h */, - 838485ED0D6D68A200CEA253 /* Object.h */, - 838486180D6D68A800CEA253 /* Protocol.h */, - ); - name = "Obsolete Headers"; - sourceTree = "<group>"; - }; - 838486270D6D690F00CEA253 /* Obsolete Source */ = { - isa = PBXGroup; - children = ( - 838486230D6D68F000CEA253 /* List.m */, - 3082F1791BCF4C4500104AE9 /* Object.mm */, - ); - name = "Obsolete Source"; - sourceTree = "<group>"; - }; - 8384862A0D6D6ABC00CEA253 /* Project Headers */ = { - isa = PBXGroup; - children = ( - 307ED0901C7883B3000D10DC /* objc-accessors.h */, - 838485CF0D6D68A200CEA253 /* objc-config.h */, - 83BE02E60FCCB24D00661494 /* objc-file.h */, - 83BE02E50FCCB24D00661494 /* objc-file-old.h */, - 838485D40D6D68A200CEA253 /* objc-initialize.h */, - 838485D90D6D68A200CEA253 /* objc-loadmethod.h */, - 831C85D30E10CF850066E64C /* objc-os.h */, - 838485DC0D6D68A200CEA253 /* objc-private.h */, - 393CEAC50DC69E67000B69DE /* objc-references.h */, - 838485E00D6D68A200CEA253 /* objc-runtime-new.h */, - 83BE02E70FCCB24D00661494 /* objc-runtime-old.h */, - 838485E50D6D68A200CEA253 /* objc-sel-set.h */, - 39ABD71F12F0B61800D1054C /* objc-weak.h */, - ); - name = "Project Headers"; - sourceTree = "<group>"; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 83E50CDA0FF19E8200D74C19 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 83E50CF40FF19E8200D74C19 /* hashtable.h in Headers */, - 83E50CDB0FF19E8200D74C19 /* hashtable2.h in Headers */, - 83E50CF10FF19E8200D74C19 /* List.h in Headers */, - 83E50CDC0FF19E8200D74C19 /* maptable.h in Headers */, - 83E50CF20FF19E8200D74C19 /* message.h in Headers */, - 83E57595121E892100295464 /* objc-abi.h in Headers */, - 83E50CDD0FF19E8200D74C19 /* objc-api.h in Headers */, - 83E50CDE0FF19E8200D74C19 /* objc-auto.h in Headers */, - 83E50CDF0FF19E8200D74C19 /* objc-auto-dump.h in Headers */, - 83E50CE00FF19E8200D74C19 /* objc-class.h in Headers */, - 83E50CE10FF19E8200D74C19 /* objc-config.h in Headers */, - 83E50CE20FF19E8200D74C19 /* objc-exception.h in Headers */, - 83E57596121E896200295464 /* objc-file-old.h in Headers */, - 83E57598121E8A1600295464 /* objc-file.h in Headers */, - 83E50CF70FF19E8200D74C19 /* objc-gdb.h in Headers */, - 83E50CE30FF19E8200D74C19 /* objc-initialize.h in Headers */, - 83E50CF80FF19E8200D74C19 /* objc-internal.h in Headers */, - 83E50CE40FF19E8200D74C19 /* objc-load.h in Headers */, - 83E50CE50FF19E8200D74C19 /* objc-loadmethod.h in Headers */, - 83E50CF60FF19E8200D74C19 /* objc-os.h in Headers */, - 83E50CE60FF19E8200D74C19 /* objc-private.h in Headers */, - 83E50CF50FF19E8200D74C19 /* objc-references.h in Headers */, - 83E50CE80FF19E8200D74C19 /* objc-runtime-new.h in Headers */, - 83E57597121E8A0A00295464 /* objc-runtime-old.h in Headers */, - 83E50CE90FF19E8200D74C19 /* objc-runtime.h in Headers */, - 83E50CEB0FF19E8200D74C19 /* objc-sel-set.h in Headers */, - 83E50CEC0FF19E8200D74C19 /* objc-sync.h in Headers */, - 83E50CED0FF19E8200D74C19 /* objc.h in Headers */, - 83E50CEE0FF19E8200D74C19 /* Object.h in Headers */, - 83E50CEF0FF19E8200D74C19 /* Protocol.h in Headers */, - 83E50CF00FF19E8200D74C19 /* runtime.h in Headers */, - 39ABD72512F0B61800D1054C /* objc-weak.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - D2AAC0600554660B00DB518D /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 830F2A980D738DC200392440 /* hashtable.h in Headers */, - 838485BF0D6D687300CEA253 /* hashtable2.h in Headers */, - 838486260D6D68F000CEA253 /* List.h in Headers */, - 838485C30D6D687300CEA253 /* maptable.h in Headers */, - 838486280D6D6A2400CEA253 /* message.h in Headers */, - 834EC0A411614167009B2563 /* objc-abi.h in Headers */, - 838485EF0D6D68A200CEA253 /* objc-api.h in Headers */, - BC07A00C0EF72D360014EC61 /* objc-auto-dump.h in Headers */, - 838485F00D6D68A200CEA253 /* objc-auto.h in Headers */, - 838485F40D6D68A200CEA253 /* objc-class.h in Headers */, - 838485F60D6D68A200CEA253 /* objc-config.h in Headers */, - 838485F80D6D68A200CEA253 /* objc-exception.h in Headers */, - 83BE02E80FCCB24D00661494 /* objc-file-old.h in Headers */, - 83BE02E90FCCB24D00661494 /* objc-file.h in Headers */, - 834266D80E665A8B002E4DA2 /* objc-gdb.h in Headers */, - 838485FB0D6D68A200CEA253 /* objc-initialize.h in Headers */, - 83112ED40F00599600A5FBAF /* objc-internal.h in Headers */, - 838485FE0D6D68A200CEA253 /* objc-load.h in Headers */, - 838486000D6D68A200CEA253 /* objc-loadmethod.h in Headers */, - 831C85D50E10CF850066E64C /* objc-os.h in Headers */, - 838486030D6D68A200CEA253 /* objc-private.h in Headers */, - 393CEAC60DC69E67000B69DE /* objc-references.h in Headers */, - 838486070D6D68A200CEA253 /* objc-runtime-new.h in Headers */, - 83BE02EA0FCCB24D00661494 /* objc-runtime-old.h in Headers */, - 307ED0911C7883B3000D10DC /* objc-accessors.h in Headers */, - 8384860A0D6D68A200CEA253 /* objc-runtime.h in Headers */, - 8384860C0D6D68A200CEA253 /* objc-sel-set.h in Headers */, - 838486100D6D68A200CEA253 /* objc-sync.h in Headers */, - 838486130D6D68A200CEA253 /* objc.h in Headers */, - 838486140D6D68A200CEA253 /* Object.h in Headers */, - 8384861E0D6D68A800CEA253 /* Protocol.h in Headers */, - 838486200D6D68A800CEA253 /* runtime.h in Headers */, - 39ABD72312F0B61800D1054C /* objc-weak.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - 305B27521C7D9E96005AC125 /* debug-objc */ = { - isa = PBXNativeTarget; - buildConfigurationList = 305B27571C7D9E96005AC125 /* Build configuration list for PBXNativeTarget "debug-objc" */; - buildPhases = ( - 305B274F1C7D9E96005AC125 /* Sources */, - 305B27501C7D9E96005AC125 /* Frameworks */, - 305B27511C7D9E96005AC125 /* CopyFiles */, - ); - buildRules = ( - ); - dependencies = ( - 305B275B1C7DA178005AC125 /* PBXTargetDependency */, - ); - name = "debug-objc"; - productName = "debug-objc"; - productReference = 305B27531C7D9E96005AC125 /* debug-objc */; - productType = "com.apple.product-type.tool"; - }; - 83E50CD70FF19E8200D74C19 /* objc-simulator */ = { - isa = PBXNativeTarget; - buildConfigurationList = 83E50D270FF19E8200D74C19 /* Build configuration list for PBXNativeTarget "objc-simulator" */; - buildPhases = ( - 83E50CDA0FF19E8200D74C19 /* Headers */, - 83E50CFC0FF19E8200D74C19 /* Sources */, - 83E50D240FF19E8200D74C19 /* Frameworks */, - 83E50D260FF19E8200D74C19 /* Run Script (symlink) */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = "objc-simulator"; - productName = objc; - productReference = 83E50D2A0FF19E8200D74C19 /* libobjc.A.dylib */; - productType = "com.apple.product-type.library.dynamic"; - }; - D2AAC0620554660B00DB518D /* objc */ = { - isa = PBXNativeTarget; - buildConfigurationList = 1DEB914A08733D8E0010E9CD /* Build configuration list for PBXNativeTarget "objc" */; - buildPhases = ( - D2AAC0600554660B00DB518D /* Headers */, - D2AAC0610554660B00DB518D /* Sources */, - D289988505E68E00004EDB86 /* Frameworks */, - 830F2AB60D739AB600392440 /* Run Script (markgc) */, - 830F2AFA0D73BC5800392440 /* Run Script (symlink) */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = objc; - productName = objc; - productReference = D2AAC0630554660B00DB518D /* libobjc.A.dylib */; - productType = "com.apple.product-type.library.dynamic"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 08FB7793FE84155DC02AAC07 /* Project object */ = { - isa = PBXProject; - attributes = { - BuildIndependentTargetsInParallel = NO; - LastUpgradeCheck = 0700; - TargetAttributes = { - 305B27521C7D9E96005AC125 = { - CreatedOnToolsVersion = 7.2.1; - }; - }; - }; - buildConfigurationList = 1DEB914E08733D8E0010E9CD /* Build configuration list for PBXProject "objc" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 1; - knownRegions = ( - English, - Japanese, - French, - German, - ); - mainGroup = 08FB7794FE84155DC02AAC07 /* objc */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - D2AAC0620554660B00DB518D /* objc */, - 83E50CD70FF19E8200D74C19 /* objc-simulator */, - 305B27521C7D9E96005AC125 /* debug-objc */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXShellScriptBuildPhase section */ - 830F2AB60D739AB600392440 /* Run Script (markgc) */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - comments = "Set the GC-supported bit in libobjc itself.\n\nlibobjc cannot be built with -fobjc-gc, because it needs more precise control over write-barrier use.\n\nThis is done on all architectures and platforms, even though some don't actually support GC. In those cases, a program that actually tries to use GC will fail with link errors."; - files = ( - ); - inputPaths = ( - ); - name = "Run Script (markgc)"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "set -x\n/usr/bin/xcrun -toolchain XcodeDefault -sdk macosx clang++ -Wall -mmacosx-version-min=10.9 -arch x86_64 -std=c++11 \"${SRCROOT}/markgc.cpp\" -o \"${BUILT_PRODUCTS_DIR}/markgc\"\n\"${BUILT_PRODUCTS_DIR}/markgc\" \"${BUILT_PRODUCTS_DIR}/libobjc.A.dylib\""; - }; - 830F2AFA0D73BC5800392440 /* Run Script (symlink) */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 8; - files = ( - ); - inputPaths = ( - ); - name = "Run Script (symlink)"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 1; - shellPath = /bin/sh; - shellScript = "cd \"${INSTALL_DIR}\"\n/bin/ln -s libobjc.A.dylib libobjc.dylib\n"; - }; - 83E50D260FF19E8200D74C19 /* Run Script (symlink) */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 8; - files = ( - ); - inputPaths = ( - ); - name = "Run Script (symlink)"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 1; - shellPath = /bin/sh; - shellScript = "cd \"${INSTALL_DIR}\"\n/bin/ln -s libobjc.A.dylib libobjc.dylib\n"; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 305B274F1C7D9E96005AC125 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 722437721D0C74E6008A731A /* XXObject.m in Sources */, - 305B27561C7D9E96005AC125 /* main.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 83E50CFC0FF19E8200D74C19 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 83E50D140FF19E8200D74C19 /* Protocol.mm in Sources */, - 83E50D150FF19E8200D74C19 /* List.m in Sources */, - 8383A3AC122600FB009290B8 /* a1a2-blocktramps-arm.s in Sources */, - 8383A3AD122600FB009290B8 /* a2a3-blocktramps-arm.s in Sources */, - 8383A3AE122600FB009290B8 /* hashtable2.mm in Sources */, - 8383A3AF122600FB009290B8 /* maptable.mm in Sources */, - 8383A3B3122600FB009290B8 /* objc-block-trampolines.mm in Sources */, - 8383A3B4122600FB009290B8 /* objc-cache.mm in Sources */, - 8383A3B6122600FB009290B8 /* objc-class.mm in Sources */, - 8383A3B7122600FB009290B8 /* objc-errors.mm in Sources */, - 8383A3B8122600FB009290B8 /* objc-exception.mm in Sources */, - 8383A3B9122600FB009290B8 /* objc-file.mm in Sources */, - 8383A3BB122600FB009290B8 /* objc-initialize.mm in Sources */, - 8383A3BC122600FB009290B8 /* objc-layout.mm in Sources */, - 8383A3BD122600FB009290B8 /* objc-load.mm in Sources */, - 8383A3BE122600FB009290B8 /* objc-loadmethod.mm in Sources */, - 8383A3BF122600FB009290B8 /* objc-lockdebug.mm in Sources */, - 8383A3C0122600FB009290B8 /* objc-os.mm in Sources */, - 8383A3C1122600FB009290B8 /* objc-references.mm in Sources */, - 8383A3C3122600FB009290B8 /* objc-runtime-new.mm in Sources */, - 8383A3C5122600FB009290B8 /* objc-runtime.mm in Sources */, - 8383A3C6122600FB009290B8 /* objc-sel-set.mm in Sources */, - 8383A3C7122600FB009290B8 /* objc-sel-table.s in Sources */, - 8383A3C8122600FB009290B8 /* objc-sel.mm in Sources */, - 8383A3C9122600FB009290B8 /* objc-sync.mm in Sources */, - 8383A3CA122600FB009290B8 /* objc-typeencoding.mm in Sources */, - 8383A3CB122600FB009290B8 /* a1a2-blocktramps-i386.s in Sources */, - 8383A3CC122600FB009290B8 /* a1a2-blocktramps-x86_64.s in Sources */, - 8383A3CD122600FB009290B8 /* a2a3-blocktramps-i386.s in Sources */, - 8383A3CE122600FB009290B8 /* a2a3-blocktramps-x86_64.s in Sources */, - 8383A3D0122600FB009290B8 /* objc-msg-arm.s in Sources */, - 8383A3D1122600FB009290B8 /* objc-msg-i386.s in Sources */, - 8383A3D2122600FB009290B8 /* objc-msg-simulator-i386.s in Sources */, - 8383A3D3122600FB009290B8 /* objc-msg-x86_64.s in Sources */, - 8383A3D4122600FB009290B8 /* objc-probes.d in Sources */, - 8383A3DC1226291C009290B8 /* objc-externalref.mm in Sources */, - 39ABD72612F0B61800D1054C /* objc-weak.mm in Sources */, - 9672F7EF14D5F488007CEC96 /* NSObject.mm in Sources */, - 83725F4C14CA5C210014370E /* objc-opt.mm in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - D2AAC0610554660B00DB518D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 3082F17A1BCF4C4500104AE9 /* Object.mm in Sources */, - 838485C00D6D687300CEA253 /* hashtable2.mm in Sources */, - 3082F1861BCF4C7000104AE9 /* objc-class-old.mm in Sources */, - 838485C40D6D687300CEA253 /* maptable.mm in Sources */, - 838485F20D6D68A200CEA253 /* objc-cache.mm in Sources */, - 838485F50D6D68A200CEA253 /* objc-class.mm in Sources */, - 838485F70D6D68A200CEA253 /* objc-errors.mm in Sources */, - 838485F90D6D68A200CEA253 /* objc-exception.mm in Sources */, - 838485FA0D6D68A200CEA253 /* objc-file.mm in Sources */, - 838485FC0D6D68A200CEA253 /* objc-initialize.mm in Sources */, - 838485FD0D6D68A200CEA253 /* objc-layout.mm in Sources */, - 838485FF0D6D68A200CEA253 /* objc-load.mm in Sources */, - 838486010D6D68A200CEA253 /* objc-loadmethod.mm in Sources */, - 838486020D6D68A200CEA253 /* objc-lockdebug.mm in Sources */, - 838486080D6D68A200CEA253 /* objc-runtime-new.mm in Sources */, - 8384860B0D6D68A200CEA253 /* objc-runtime.mm in Sources */, - 3082F1891BCF4C7000104AE9 /* objc-auto-dump.mm in Sources */, - 8384860D0D6D68A200CEA253 /* objc-sel-set.mm in Sources */, - 3082F1831BCF4C7000104AE9 /* objc-runtime-old.mm in Sources */, - 8384860F0D6D68A200CEA253 /* objc-sel.mm in Sources */, - 838486110D6D68A200CEA253 /* objc-sync.mm in Sources */, - 838486120D6D68A200CEA253 /* objc-typeencoding.mm in Sources */, - 307ED08F1C78839C000D10DC /* objc-accessors.mm in Sources */, - 3082F1851BCF4C7000104AE9 /* objc-cache-old.mm in Sources */, - 8384861F0D6D68A800CEA253 /* Protocol.mm in Sources */, - 838486250D6D68F000CEA253 /* List.m in Sources */, - 830F2A740D737FB800392440 /* objc-msg-arm.s in Sources */, - 830F2A750D737FB900392440 /* objc-msg-i386.s in Sources */, - 830F2A7D0D737FBB00392440 /* objc-msg-x86_64.s in Sources */, - 393CEAC00DC69E3E000B69DE /* objc-references.mm in Sources */, - 831C85D60E10CF850066E64C /* objc-os.mm in Sources */, - 87BB4EA70EC39854005D08E1 /* objc-probes.d in Sources */, - E8923DA1116AB2820071B552 /* a1a2-blocktramps-i386.s in Sources */, - E8923DA2116AB2820071B552 /* a1a2-blocktramps-x86_64.s in Sources */, - E8923DA3116AB2820071B552 /* a2a3-blocktramps-i386.s in Sources */, - 3082F1841BCF4C7000104AE9 /* objc-auto.mm in Sources */, - E8923DA4116AB2820071B552 /* a2a3-blocktramps-x86_64.s in Sources */, - E8923DA5116AB2820071B552 /* objc-block-trampolines.mm in Sources */, - 83B1A8BE0FF1AC0D0019EA5B /* objc-msg-simulator-i386.s in Sources */, - 3082F1881BCF4C7000104AE9 /* objc-sel-old.mm in Sources */, - 83EB007B121C9EC200B92C16 /* objc-sel-table.s in Sources */, - 8383A3A3122600E9009290B8 /* a1a2-blocktramps-arm.s in Sources */, - 8383A3A4122600E9009290B8 /* a2a3-blocktramps-arm.s in Sources */, - 399BC72E1224831B007FBDF0 /* objc-externalref.mm in Sources */, - 3082F1871BCF4C7000104AE9 /* a1a2-blocktramps-arm64.s in Sources */, - 39ABD72412F0B61800D1054C /* objc-weak.mm in Sources */, - 9672F7EE14D5F488007CEC96 /* NSObject.mm in Sources */, - 3082F18A1BCF4C7000104AE9 /* objc-file-old.mm in Sources */, - 83725F4A14CA5BFA0014370E /* objc-opt.mm in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 305B275B1C7DA178005AC125 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = D2AAC0620554660B00DB518D /* objc */; - targetProxy = 305B275A1C7DA178005AC125 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 1DEB914B08733D8E0010E9CD /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - COMBINE_HIDPI_IMAGES = YES; - COPY_PHASE_STRIP = NO; - DYLIB_CURRENT_VERSION = 228; - EXECUTABLE_PREFIX = lib; - GCC_CW_ASM_SYNTAX = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_MODEL_TUNING = G5; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "OS_OBJECT_USE_OBJC=0", - LIBC_NO_LIBCRASHREPORTERCLIENT, - ); - GCC_THREADSAFE_STATICS = NO; - GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; - HEADER_SEARCH_PATHS = ( - "$(DSTROOT)/usr/include/**", - "$(DSTROOT)/usr/local/include/**", - "$(CONFIGURATION_BUILD_DIR)/usr/include/**", - "$(CONFIGURATION_BUILD_DIR)/usr/local/include/**", - "$(SRCROOT)/include", - ); - INSTALL_PATH = /usr/lib; - MACH_O_TYPE = mh_dylib; - ORDER_FILE = libobjc.order; - OTHER_CFLAGS = ( - "-fdollars-in-identifiers", - "$(OTHER_CFLAGS)", - ); - "OTHER_LDFLAGS[sdk=iphoneos*][arch=*]" = "-lc++abi"; - "OTHER_LDFLAGS[sdk=iphonesimulator*][arch=*]" = "-l_BUILD_objc-simulator_TARGET_INSTEAD"; - "OTHER_LDFLAGS[sdk=macosx*]" = ( - "-lauto", - "-lc++abi", - ); - PRIVATE_HEADERS_FOLDER_PATH = /usr/local/include/objc; - PRODUCT_NAME = objc.A; - PUBLIC_HEADERS_FOLDER_PATH = /usr/include/objc; - UNEXPORTED_SYMBOLS_FILE = unexported_symbols; - }; - name = Debug; - }; - 1DEB914C08733D8E0010E9CD /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - COMBINE_HIDPI_IMAGES = YES; - DYLIB_CURRENT_VERSION = 228; - EXECUTABLE_PREFIX = lib; - GCC_CW_ASM_SYNTAX = NO; - GCC_PREPROCESSOR_DEFINITIONS = ( - "OS_OBJECT_USE_OBJC=0", - "NDEBUG=1", - LIBC_NO_LIBCRASHREPORTERCLIENT, - ); - GCC_THREADSAFE_STATICS = NO; - GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; - HEADER_SEARCH_PATHS = ( - "$(DSTROOT)/usr/include/**", - "$(DSTROOT)/usr/local/include/**", - "$(CONFIGURATION_BUILD_DIR)/usr/include/**", - "$(CONFIGURATION_BUILD_DIR)/usr/local/include/**", - "$(SRCROOT)/include/**", - ); - INSTALL_PATH = /usr/lib; - MACH_O_TYPE = mh_dylib; - ORDER_FILE = libobjc.order; - OTHER_CFLAGS = ( - "-fdollars-in-identifiers", - "$(OTHER_CFLAGS)", - ); - "OTHER_LDFLAGS[sdk=iphoneos*][arch=*]" = "-lc++abi"; - "OTHER_LDFLAGS[sdk=iphonesimulator*][arch=*]" = "-l_BUILD_objc-simulator_TARGET_INSTEAD"; - "OTHER_LDFLAGS[sdk=macosx*]" = ( - "-lauto", - "-lc++abi", - ); - PRIVATE_HEADERS_FOLDER_PATH = /usr/local/include/objc; - PRODUCT_NAME = objc.A; - PUBLIC_HEADERS_FOLDER_PATH = /usr/include/objc; - UNEXPORTED_SYMBOLS_FILE = unexported_symbols; - }; - name = Release; - }; - 1DEB914F08733D8E0010E9CD /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_CXX_LIBRARY = "libc++"; - "CLANG_CXX_LIBRARY[sdk=iphoneos*]" = "libstdc++"; - "CLANG_CXX_LIBRARY[sdk=iphonesimulator*]" = "libstdc++"; - CLANG_LINK_OBJC_RUNTIME = NO; - CLANG_OBJC_RUNTIME = NO; - 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; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_ENABLE_CPP_EXCEPTIONS = NO; - GCC_ENABLE_CPP_RTTI = NO; - GCC_INLINES_ARE_PRIVATE_EXTERN = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = "OS_OBJECT_USE_OBJC=0"; - GCC_STRICT_ALIASING = YES; - GCC_SYMBOLS_PRIVATE_EXTERN = YES; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_NEWLINE = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_SHADOW = YES; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = dynamic; - STRIP_STYLE = all; - VALID_ARCHS = x86_64; - WARNING_CFLAGS = ( - "-Wall", - "-Wextra", - "-Wstrict-aliasing=2", - "-Wstrict-overflow=4", - "-Wno-unused-parameter", - "-Wno-deprecated-objc-isa-usage", - ); - }; - name = Debug; - }; - 1DEB915008733D8E0010E9CD /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_CXX_LIBRARY = "libc++"; - "CLANG_CXX_LIBRARY[sdk=iphoneos*]" = "libstdc++"; - "CLANG_CXX_LIBRARY[sdk=iphonesimulator*]" = "libstdc++"; - CLANG_LINK_OBJC_RUNTIME = NO; - CLANG_OBJC_RUNTIME = NO; - 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; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_ENABLE_CPP_EXCEPTIONS = NO; - GCC_ENABLE_CPP_RTTI = NO; - GCC_INLINES_ARE_PRIVATE_EXTERN = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREPROCESSOR_DEFINITIONS = ( - "OS_OBJECT_USE_OBJC=0", - "NDEBUG=1", - ); - GCC_STRICT_ALIASING = YES; - GCC_SYMBOLS_PRIVATE_EXTERN = YES; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_NEWLINE = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_SHADOW = YES; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - "OTHER_CFLAGS[arch=i386]" = "-momit-leaf-frame-pointer"; - "OTHER_CFLAGS[arch=x86_64]" = "-momit-leaf-frame-pointer"; - SDKROOT = macosx; - STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = dynamic; - STRIP_STYLE = all; - VALID_ARCHS = x86_64; - WARNING_CFLAGS = ( - "-Wall", - "-Wextra", - "-Wstrict-aliasing=2", - "-Wstrict-overflow=4", - "-Wno-unused-parameter", - "-Wno-deprecated-objc-isa-usage", - ); - }; - name = Release; - }; - 305B27581C7D9E96005AC125 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - MACOSX_DEPLOYMENT_TARGET = 10.11; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Debug; - }; - 305B27591C7D9E96005AC125 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - ENABLE_NS_ASSERTIONS = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - MACOSX_DEPLOYMENT_TARGET = 10.11; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Release; - }; - 83E50D280FF19E8200D74C19 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 83E50D2B0FF19E9E00D74C19 /* IndigoSDK.xcconfig */; - buildSettings = { - COMBINE_HIDPI_IMAGES = YES; - COPY_PHASE_STRIP = NO; - DYLIB_CURRENT_VERSION = 227; - EXECUTABLE_PREFIX = lib; - GCC_CW_ASM_SYNTAX = NO; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_THREADSAFE_STATICS = NO; - GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; - HEADER_SEARCH_PATHS = ( - "$(DSTROOT)/$(INDIGO_INSTALL_PATH_PREFIX)/usr/include/**", - "$(DSTROOT)/$(INDIGO_INSTALL_PATH_PREFIX)/usr/local/include/**", - "$(CONFIGURATION_BUILD_DIR)/$(INDIGO_INSTALL_PATH_PREFIX)/usr/include/**", - "$(CONFIGURATION_BUILD_DIR)/$(INDIGO_INSTALL_PATH_PREFIX)/usr/local/include/**", - ); - INSTALL_PATH = "$(INDIGO_INSTALL_PATH_PREFIX)/usr/lib"; - LD_DYLIB_INSTALL_NAME_mh_dylib = "/usr/lib/$(EXECUTABLE_PATH)"; - OTHER_CFLAGS = ( - "-fobjc-legacy-dispatch", - "-fobjc-abi-version=2", - "-fdollars-in-identifiers", - ); - OTHER_LDFLAGS = "-lc++abi"; - PRIVATE_HEADERS_FOLDER_PATH = "$(INDIGO_INSTALL_PATH_PREFIX)/usr/local/include/objc"; - PRODUCT_NAME = objc.A; - PUBLIC_HEADERS_FOLDER_PATH = "$(INDIGO_INSTALL_PATH_PREFIX)/usr/include/objc"; - UNEXPORTED_SYMBOLS_FILE = unexported_symbols; - }; - name = Debug; - }; - 83E50D290FF19E8200D74C19 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 83E50D2B0FF19E9E00D74C19 /* IndigoSDK.xcconfig */; - buildSettings = { - COMBINE_HIDPI_IMAGES = YES; - DYLIB_CURRENT_VERSION = 227; - EXECUTABLE_PREFIX = lib; - GCC_CW_ASM_SYNTAX = NO; - GCC_THREADSAFE_STATICS = NO; - GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; - HEADER_SEARCH_PATHS = ( - "$(DSTROOT)/$(INDIGO_INSTALL_PATH_PREFIX)/usr/include/**", - "$(DSTROOT)/$(INDIGO_INSTALL_PATH_PREFIX)/usr/local/include/**", - "$(CONFIGURATION_BUILD_DIR)/$(INDIGO_INSTALL_PATH_PREFIX)/usr/include/**", - "$(CONFIGURATION_BUILD_DIR)/$(INDIGO_INSTALL_PATH_PREFIX)/usr/local/include/**", - ); - INSTALL_PATH = "$(INDIGO_INSTALL_PATH_PREFIX)/usr/lib"; - LD_DYLIB_INSTALL_NAME_mh_dylib = "/usr/lib/$(EXECUTABLE_PATH)"; - OTHER_CFLAGS = ( - "-fobjc-legacy-dispatch", - "-fobjc-abi-version=2", - "-fdollars-in-identifiers", - ); - OTHER_LDFLAGS = "-lc++abi"; - PRIVATE_HEADERS_FOLDER_PATH = "$(INDIGO_INSTALL_PATH_PREFIX)/usr/local/include/objc"; - PRODUCT_NAME = objc.A; - PUBLIC_HEADERS_FOLDER_PATH = "$(INDIGO_INSTALL_PATH_PREFIX)/usr/include/objc"; - UNEXPORTED_SYMBOLS_FILE = unexported_symbols; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1DEB914A08733D8E0010E9CD /* Build configuration list for PBXNativeTarget "objc" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1DEB914B08733D8E0010E9CD /* Debug */, - 1DEB914C08733D8E0010E9CD /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Debug; - }; - 1DEB914E08733D8E0010E9CD /* Build configuration list for PBXProject "objc" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1DEB914F08733D8E0010E9CD /* Debug */, - 1DEB915008733D8E0010E9CD /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Debug; - }; - 305B27571C7D9E96005AC125 /* Build configuration list for PBXNativeTarget "debug-objc" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 305B27581C7D9E96005AC125 /* Debug */, - 305B27591C7D9E96005AC125 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Debug; - }; - 83E50D270FF19E8200D74C19 /* Build configuration list for PBXNativeTarget "objc-simulator" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 83E50D280FF19E8200D74C19 /* Debug */, - 83E50D290FF19E8200D74C19 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Debug; - }; -/* End XCConfigurationList section */ - }; - rootObject = 08FB7793FE84155DC02AAC07 /* Project object */; -} diff --git a/objc/objc-runtime/objc.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/objc/objc-runtime/objc.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100755 index fafe8e5..0000000 --- a/objc/objc-runtime/objc.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<Workspace - version = "1.0"> - <FileRef - location = "self:objc.xcodeproj"> - </FileRef> -</Workspace> diff --git a/objc/objc-runtime/objc.xcodeproj/project.xcworkspace/xcshareddata/objc.xccheckout b/objc/objc-runtime/objc.xcodeproj/project.xcworkspace/xcshareddata/objc.xccheckout deleted file mode 100644 index 28bb83a..0000000 --- a/objc/objc-runtime/objc.xcodeproj/project.xcworkspace/xcshareddata/objc.xccheckout +++ /dev/null @@ -1,41 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>IDESourceControlProjectFavoriteDictionaryKey</key> - <false/> - <key>IDESourceControlProjectIdentifier</key> - <string>898E84ED-C968-4FB3-97DF-DF58CD759D2E</string> - <key>IDESourceControlProjectName</key> - <string>objc</string> - <key>IDESourceControlProjectOriginsDictionary</key> - <dict> - <key>041A75B833F290D5C1BA7698A88C3F3E9FE4354D</key> - <string>https://github.com/RetVal/objc4-532.2.git</string> - </dict> - <key>IDESourceControlProjectPath</key> - <string>objc.xcodeproj</string> - <key>IDESourceControlProjectRelativeInstallPathDictionary</key> - <dict> - <key>041A75B833F290D5C1BA7698A88C3F3E9FE4354D</key> - <string>../..</string> - </dict> - <key>IDESourceControlProjectURL</key> - <string>https://github.com/RetVal/objc4-532.2.git</string> - <key>IDESourceControlProjectVersion</key> - <integer>111</integer> - <key>IDESourceControlProjectWCCIdentifier</key> - <string>041A75B833F290D5C1BA7698A88C3F3E9FE4354D</string> - <key>IDESourceControlProjectWCConfigurations</key> - <array> - <dict> - <key>IDESourceControlRepositoryExtensionIdentifierKey</key> - <string>public.vcs.git</string> - <key>IDESourceControlWCCIdentifierKey</key> - <string>041A75B833F290D5C1BA7698A88C3F3E9FE4354D</string> - <key>IDESourceControlWCCName</key> - <string>objc4-532.2</string> - </dict> - </array> -</dict> -</plist> diff --git a/objc/objc-runtime/objc.xcodeproj/project.xcworkspace/xcuserdata/Draveness.xcuserdatad/UserInterfaceState.xcuserstate b/objc/objc-runtime/objc.xcodeproj/project.xcworkspace/xcuserdata/Draveness.xcuserdatad/UserInterfaceState.xcuserstate deleted file mode 100644 index 037d013..0000000 Binary files a/objc/objc-runtime/objc.xcodeproj/project.xcworkspace/xcuserdata/Draveness.xcuserdatad/UserInterfaceState.xcuserstate and /dev/null differ diff --git a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist deleted file mode 100644 index 3f5e808..0000000 --- a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist +++ /dev/null @@ -1,323 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<Bucket - type = "1" - version = "2.0"> - <Breakpoints> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "Yes" - ignoreCount = "0" - continueAfterRunningActions = "No" - filePath = "runtime/NSObject.mm" - timestampString = "484979361.526003" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "965" - endingLineNumber = "965" - landmarkName = "pop(void *token)" - landmarkType = "5"> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "Yes" - ignoreCount = "0" - continueAfterRunningActions = "No" - filePath = "runtime/NSObject.mm" - timestampString = "487355582.365353" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "402" - endingLineNumber = "402" - landmarkName = "objc_initWeak(id *location, id newObj)" - landmarkType = "7"> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - filePath = "debug-objc/main.m" - timestampString = "490416764.655418" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "16" - endingLineNumber = "16" - landmarkName = "main()" - landmarkType = "7"> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - filePath = "runtime/NSObject.mm" - timestampString = "490416853.81163" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1658" - endingLineNumber = "1658" - landmarkName = "callAlloc(Class cls, bool checkNil, bool allocWithZone=false)" - landmarkType = "7"> - <Locations> - <Location - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - symbolName = "_objc_rootAlloc" - moduleName = "libobjc.A.dylib" - usesParentBreakpointCondition = "Yes" - urlString = "file:///Users/apple/Desktop/objc-runtime/runtime/NSObject.mm" - timestampString = "490416929.198721" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1658" - endingLineNumber = "1658" - offsetFromSymbolStart = "235"> - </Location> - <Location - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - symbolName = "objc_alloc" - moduleName = "libobjc.A.dylib" - usesParentBreakpointCondition = "Yes" - urlString = "file:///Users/apple/Desktop/objc-runtime/runtime/NSObject.mm" - timestampString = "490416929.198956" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1658" - endingLineNumber = "1658" - offsetFromSymbolStart = "235"> - </Location> - <Location - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - symbolName = "objc_allocWithZone" - moduleName = "libobjc.A.dylib" - usesParentBreakpointCondition = "Yes" - urlString = "file:///Users/apple/Desktop/objc-runtime/runtime/NSObject.mm" - timestampString = "490416929.199293" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1658" - endingLineNumber = "1658" - offsetFromSymbolStart = "235"> - </Location> - <Location - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - symbolName = "+[NSObject new]" - moduleName = "libobjc.A.dylib" - usesParentBreakpointCondition = "Yes" - urlString = "file:///Users/apple/Desktop/objc-runtime/runtime/NSObject.mm" - timestampString = "490416929.199622" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1658" - endingLineNumber = "1658" - offsetFromSymbolStart = "239"> - </Location> - </Locations> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - filePath = "runtime/NSObject.mm" - timestampString = "490416923.095083" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1667" - endingLineNumber = "1667" - landmarkName = "callAlloc(Class cls, bool checkNil, bool allocWithZone=false)" - landmarkType = "7"> - <Locations> - <Location - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - symbolName = "_objc_rootAlloc" - moduleName = "libobjc.A.dylib" - usesParentBreakpointCondition = "Yes" - urlString = "file:///Users/apple/Desktop/objc-runtime/runtime/NSObject.mm" - timestampString = "490417145.853159" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1667" - endingLineNumber = "1667" - offsetFromSymbolStart = "329"> - </Location> - <Location - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - symbolName = "objc_alloc" - moduleName = "libobjc.A.dylib" - usesParentBreakpointCondition = "Yes" - urlString = "file:///Users/apple/Desktop/objc-runtime/runtime/NSObject.mm" - timestampString = "490417145.85342" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1667" - endingLineNumber = "1667" - offsetFromSymbolStart = "329"> - </Location> - <Location - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - symbolName = "objc_allocWithZone" - moduleName = "libobjc.A.dylib" - usesParentBreakpointCondition = "Yes" - urlString = "file:///Users/apple/Desktop/objc-runtime/runtime/NSObject.mm" - timestampString = "490417145.853972" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1667" - endingLineNumber = "1667" - offsetFromSymbolStart = "329"> - </Location> - <Location - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - symbolName = "+[NSObject new]" - moduleName = "libobjc.A.dylib" - usesParentBreakpointCondition = "Yes" - urlString = "file:///Users/apple/Desktop/objc-runtime/runtime/NSObject.mm" - timestampString = "490417145.855297" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1667" - endingLineNumber = "1667" - offsetFromSymbolStart = "333"> - </Location> - </Locations> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - filePath = "runtime/NSObject.mm" - timestampString = "490417136.650317" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "2217" - endingLineNumber = "2217" - landmarkName = "-init" - landmarkType = "5"> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - filePath = "runtime/objc-runtime-new.mm" - timestampString = "490796911.329176" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "929" - endingLineNumber = "929" - landmarkName = "getClass(const char *name)" - landmarkType = "7"> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "No" - filePath = "debug-objc/main.m" - timestampString = "490796921.810572" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "17" - endingLineNumber = "17" - landmarkName = "main()" - landmarkType = "7"> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "No" - ignoreCount = "0" - continueAfterRunningActions = "Yes" - filePath = "runtime/objc-runtime-new.mm" - timestampString = "490982055.091344" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1855" - endingLineNumber = "1855" - landmarkName = "realizeClass(Class cls)" - landmarkType = "7"> - <Actions> - <BreakpointActionProxy - ActionExtensionID = "Xcode.BreakpointAction.DebuggerCommand"> - <ActionContent - consoleCommand = "po (void *)cls"> - </ActionContent> - </BreakpointActionProxy> - </Actions> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "Yes" - ignoreCount = "0" - continueAfterRunningActions = "Yes" - filePath = "runtime/objc-runtime-new.mm" - timestampString = "490982161.70803" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "1953" - endingLineNumber = "1953" - landmarkName = "realizeClass(Class cls)" - landmarkType = "7"> - <Actions> - <BreakpointActionProxy - ActionExtensionID = "Xcode.BreakpointAction.DebuggerCommand"> - <ActionContent - consoleCommand = "po (void *)cls"> - </ActionContent> - </BreakpointActionProxy> - </Actions> - </BreakpointContent> - </BreakpointProxy> - <BreakpointProxy - BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> - <BreakpointContent - shouldBeEnabled = "Yes" - ignoreCount = "0" - continueAfterRunningActions = "No" - filePath = "debug-objc/main.m" - timestampString = "490984549.658754" - startingColumnNumber = "9223372036854775807" - endingColumnNumber = "9223372036854775807" - startingLineNumber = "19" - endingLineNumber = "19" - landmarkName = "main()" - landmarkType = "7"> - </BreakpointContent> - </BreakpointProxy> - </Breakpoints> -</Bucket> diff --git a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/call-method.xcscheme b/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/call-method.xcscheme deleted file mode 100644 index f50b356..0000000 --- a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/call-method.xcscheme +++ /dev/null @@ -1,91 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<Scheme - LastUpgradeVersion = "0730" - version = "1.3"> - <BuildAction - parallelizeBuildables = "YES" - buildImplicitDependencies = "YES"> - <BuildActionEntries> - <BuildActionEntry - buildForTesting = "YES" - buildForRunning = "YES" - buildForProfiling = "YES" - buildForArchiving = "YES" - buildForAnalyzing = "YES"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72A15AD51CCCA22E00DCF938" - BuildableName = "call-method" - BlueprintName = "call-method" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildActionEntry> - </BuildActionEntries> - </BuildAction> - <TestAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - shouldUseLaunchSchemeArgsEnv = "YES"> - <Testables> - </Testables> - <MacroExpansion> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72A15AD51CCCA22E00DCF938" - BuildableName = "call-method" - BlueprintName = "call-method" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </MacroExpansion> - <AdditionalOptions> - </AdditionalOptions> - </TestAction> - <LaunchAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - launchStyle = "0" - useCustomWorkingDirectory = "NO" - ignoresPersistentStateOnLaunch = "NO" - debugDocumentVersioning = "YES" - debugServiceExtension = "internal" - allowLocationSimulation = "YES"> - <BuildableProductRunnable - runnableDebuggingMode = "0"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72A15AD51CCCA22E00DCF938" - BuildableName = "call-method" - BlueprintName = "call-method" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildableProductRunnable> - <AdditionalOptions> - </AdditionalOptions> - </LaunchAction> - <ProfileAction - buildConfiguration = "Release" - shouldUseLaunchSchemeArgsEnv = "YES" - savedToolIdentifier = "" - useCustomWorkingDirectory = "NO" - debugDocumentVersioning = "YES"> - <BuildableProductRunnable - runnableDebuggingMode = "0"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72A15AD51CCCA22E00DCF938" - BuildableName = "call-method" - BlueprintName = "call-method" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildableProductRunnable> - </ProfileAction> - <AnalyzeAction - buildConfiguration = "Debug"> - </AnalyzeAction> - <ArchiveAction - buildConfiguration = "Release" - revealArchiveInOrganizer = "YES"> - </ArchiveAction> -</Scheme> diff --git a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/debug-objc.xcscheme b/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/debug-objc.xcscheme deleted file mode 100644 index 302cb36..0000000 --- a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/debug-objc.xcscheme +++ /dev/null @@ -1,91 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<Scheme - LastUpgradeVersion = "0730" - version = "1.3"> - <BuildAction - parallelizeBuildables = "YES" - buildImplicitDependencies = "YES"> - <BuildActionEntries> - <BuildActionEntry - buildForTesting = "YES" - buildForRunning = "YES" - buildForProfiling = "YES" - buildForArchiving = "YES" - buildForAnalyzing = "YES"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "305B27521C7D9E96005AC125" - BuildableName = "debug-objc" - BlueprintName = "debug-objc" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildActionEntry> - </BuildActionEntries> - </BuildAction> - <TestAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - shouldUseLaunchSchemeArgsEnv = "YES"> - <Testables> - </Testables> - <MacroExpansion> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "305B27521C7D9E96005AC125" - BuildableName = "debug-objc" - BlueprintName = "debug-objc" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </MacroExpansion> - <AdditionalOptions> - </AdditionalOptions> - </TestAction> - <LaunchAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - launchStyle = "0" - useCustomWorkingDirectory = "NO" - ignoresPersistentStateOnLaunch = "NO" - debugDocumentVersioning = "YES" - debugServiceExtension = "internal" - allowLocationSimulation = "YES"> - <BuildableProductRunnable - runnableDebuggingMode = "0"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "305B27521C7D9E96005AC125" - BuildableName = "debug-objc" - BlueprintName = "debug-objc" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildableProductRunnable> - <AdditionalOptions> - </AdditionalOptions> - </LaunchAction> - <ProfileAction - buildConfiguration = "Release" - shouldUseLaunchSchemeArgsEnv = "YES" - savedToolIdentifier = "" - useCustomWorkingDirectory = "NO" - debugDocumentVersioning = "YES"> - <BuildableProductRunnable - runnableDebuggingMode = "0"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "305B27521C7D9E96005AC125" - BuildableName = "debug-objc" - BlueprintName = "debug-objc" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildableProductRunnable> - </ProfileAction> - <AnalyzeAction - buildConfiguration = "Debug"> - </AnalyzeAction> - <ArchiveAction - buildConfiguration = "Release" - revealArchiveInOrganizer = "YES"> - </ArchiveAction> -</Scheme> diff --git a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/isa.xcscheme b/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/isa.xcscheme deleted file mode 100644 index 773d35e..0000000 --- a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/isa.xcscheme +++ /dev/null @@ -1,91 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<Scheme - LastUpgradeVersion = "0730" - version = "1.3"> - <BuildAction - parallelizeBuildables = "YES" - buildImplicitDependencies = "YES"> - <BuildActionEntries> - <BuildActionEntry - buildForTesting = "YES" - buildForRunning = "YES" - buildForProfiling = "YES" - buildForArchiving = "YES" - buildForAnalyzing = "YES"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72E4B4211CC9D7090088B2D9" - BuildableName = "isa" - BlueprintName = "isa" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildActionEntry> - </BuildActionEntries> - </BuildAction> - <TestAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - shouldUseLaunchSchemeArgsEnv = "YES"> - <Testables> - </Testables> - <MacroExpansion> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72E4B4211CC9D7090088B2D9" - BuildableName = "isa" - BlueprintName = "isa" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </MacroExpansion> - <AdditionalOptions> - </AdditionalOptions> - </TestAction> - <LaunchAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - launchStyle = "0" - useCustomWorkingDirectory = "NO" - ignoresPersistentStateOnLaunch = "NO" - debugDocumentVersioning = "YES" - debugServiceExtension = "internal" - allowLocationSimulation = "YES"> - <BuildableProductRunnable - runnableDebuggingMode = "0"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72E4B4211CC9D7090088B2D9" - BuildableName = "isa" - BlueprintName = "isa" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildableProductRunnable> - <AdditionalOptions> - </AdditionalOptions> - </LaunchAction> - <ProfileAction - buildConfiguration = "Release" - shouldUseLaunchSchemeArgsEnv = "YES" - savedToolIdentifier = "" - useCustomWorkingDirectory = "NO" - debugDocumentVersioning = "YES"> - <BuildableProductRunnable - runnableDebuggingMode = "0"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72E4B4211CC9D7090088B2D9" - BuildableName = "isa" - BlueprintName = "isa" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildableProductRunnable> - </ProfileAction> - <AnalyzeAction - buildConfiguration = "Debug"> - </AnalyzeAction> - <ArchiveAction - buildConfiguration = "Release" - revealArchiveInOrganizer = "YES"> - </ArchiveAction> -</Scheme> diff --git a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/method.xcscheme b/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/method.xcscheme deleted file mode 100644 index 6dbc439..0000000 --- a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/method.xcscheme +++ /dev/null @@ -1,91 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<Scheme - LastUpgradeVersion = "0730" - version = "1.3"> - <BuildAction - parallelizeBuildables = "YES" - buildImplicitDependencies = "YES"> - <BuildActionEntries> - <BuildActionEntry - buildForTesting = "YES" - buildForRunning = "YES" - buildForProfiling = "YES" - buildForArchiving = "YES" - buildForAnalyzing = "YES"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72E4B42D1CC9D78C0088B2D9" - BuildableName = "method" - BlueprintName = "method" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildActionEntry> - </BuildActionEntries> - </BuildAction> - <TestAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - shouldUseLaunchSchemeArgsEnv = "YES"> - <Testables> - </Testables> - <MacroExpansion> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72E4B42D1CC9D78C0088B2D9" - BuildableName = "method" - BlueprintName = "method" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </MacroExpansion> - <AdditionalOptions> - </AdditionalOptions> - </TestAction> - <LaunchAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - launchStyle = "0" - useCustomWorkingDirectory = "NO" - ignoresPersistentStateOnLaunch = "NO" - debugDocumentVersioning = "YES" - debugServiceExtension = "internal" - allowLocationSimulation = "YES"> - <BuildableProductRunnable - runnableDebuggingMode = "0"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72E4B42D1CC9D78C0088B2D9" - BuildableName = "method" - BlueprintName = "method" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildableProductRunnable> - <AdditionalOptions> - </AdditionalOptions> - </LaunchAction> - <ProfileAction - buildConfiguration = "Release" - shouldUseLaunchSchemeArgsEnv = "YES" - savedToolIdentifier = "" - useCustomWorkingDirectory = "NO" - debugDocumentVersioning = "YES"> - <BuildableProductRunnable - runnableDebuggingMode = "0"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "72E4B42D1CC9D78C0088B2D9" - BuildableName = "method" - BlueprintName = "method" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildableProductRunnable> - </ProfileAction> - <AnalyzeAction - buildConfiguration = "Debug"> - </AnalyzeAction> - <ArchiveAction - buildConfiguration = "Release" - revealArchiveInOrganizer = "YES"> - </ArchiveAction> -</Scheme> diff --git a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/objc-simulator.xcscheme b/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/objc-simulator.xcscheme deleted file mode 100644 index 1fd12b8..0000000 --- a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/objc-simulator.xcscheme +++ /dev/null @@ -1,80 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<Scheme - LastUpgradeVersion = "0730" - version = "1.3"> - <BuildAction - parallelizeBuildables = "YES" - buildImplicitDependencies = "YES"> - <BuildActionEntries> - <BuildActionEntry - buildForTesting = "YES" - buildForRunning = "YES" - buildForProfiling = "YES" - buildForArchiving = "YES" - buildForAnalyzing = "YES"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "83E50CD70FF19E8200D74C19" - BuildableName = "libobjc.A.dylib" - BlueprintName = "objc-simulator" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildActionEntry> - </BuildActionEntries> - </BuildAction> - <TestAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - shouldUseLaunchSchemeArgsEnv = "YES"> - <Testables> - </Testables> - <AdditionalOptions> - </AdditionalOptions> - </TestAction> - <LaunchAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - launchStyle = "0" - useCustomWorkingDirectory = "NO" - ignoresPersistentStateOnLaunch = "NO" - debugDocumentVersioning = "YES" - debugServiceExtension = "internal" - allowLocationSimulation = "YES"> - <MacroExpansion> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "83E50CD70FF19E8200D74C19" - BuildableName = "libobjc.A.dylib" - BlueprintName = "objc-simulator" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </MacroExpansion> - <AdditionalOptions> - </AdditionalOptions> - </LaunchAction> - <ProfileAction - buildConfiguration = "Release" - shouldUseLaunchSchemeArgsEnv = "YES" - savedToolIdentifier = "" - useCustomWorkingDirectory = "NO" - debugDocumentVersioning = "YES"> - <MacroExpansion> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "83E50CD70FF19E8200D74C19" - BuildableName = "libobjc.A.dylib" - BlueprintName = "objc-simulator" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </MacroExpansion> - </ProfileAction> - <AnalyzeAction - buildConfiguration = "Debug"> - </AnalyzeAction> - <ArchiveAction - buildConfiguration = "Release" - revealArchiveInOrganizer = "YES"> - </ArchiveAction> -</Scheme> diff --git a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/objc.xcscheme b/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/objc.xcscheme deleted file mode 100644 index 0753bec..0000000 --- a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/objc.xcscheme +++ /dev/null @@ -1,80 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<Scheme - LastUpgradeVersion = "0730" - version = "1.3"> - <BuildAction - parallelizeBuildables = "YES" - buildImplicitDependencies = "YES"> - <BuildActionEntries> - <BuildActionEntry - buildForTesting = "YES" - buildForRunning = "YES" - buildForProfiling = "YES" - buildForArchiving = "YES" - buildForAnalyzing = "YES"> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "D2AAC0620554660B00DB518D" - BuildableName = "libobjc.A.dylib" - BlueprintName = "objc" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </BuildActionEntry> - </BuildActionEntries> - </BuildAction> - <TestAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - shouldUseLaunchSchemeArgsEnv = "YES"> - <Testables> - </Testables> - <AdditionalOptions> - </AdditionalOptions> - </TestAction> - <LaunchAction - buildConfiguration = "Debug" - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - launchStyle = "0" - useCustomWorkingDirectory = "NO" - ignoresPersistentStateOnLaunch = "NO" - debugDocumentVersioning = "YES" - debugServiceExtension = "internal" - allowLocationSimulation = "YES"> - <MacroExpansion> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "D2AAC0620554660B00DB518D" - BuildableName = "libobjc.A.dylib" - BlueprintName = "objc" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </MacroExpansion> - <AdditionalOptions> - </AdditionalOptions> - </LaunchAction> - <ProfileAction - buildConfiguration = "Release" - shouldUseLaunchSchemeArgsEnv = "YES" - savedToolIdentifier = "" - useCustomWorkingDirectory = "NO" - debugDocumentVersioning = "YES"> - <MacroExpansion> - <BuildableReference - BuildableIdentifier = "primary" - BlueprintIdentifier = "D2AAC0620554660B00DB518D" - BuildableName = "libobjc.A.dylib" - BlueprintName = "objc" - ReferencedContainer = "container:objc.xcodeproj"> - </BuildableReference> - </MacroExpansion> - </ProfileAction> - <AnalyzeAction - buildConfiguration = "Debug"> - </AnalyzeAction> - <ArchiveAction - buildConfiguration = "Release" - revealArchiveInOrganizer = "YES"> - </ArchiveAction> -</Scheme> diff --git a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/xcschememanagement.plist b/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/xcschememanagement.plist deleted file mode 100644 index 4a8b73d..0000000 --- a/objc/objc-runtime/objc.xcodeproj/xcuserdata/Draveness.xcuserdatad/xcschemes/xcschememanagement.plist +++ /dev/null @@ -1,72 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>SchemeUserState</key> - <dict> - <key>call-method.xcscheme</key> - <dict> - <key>orderHint</key> - <integer>5</integer> - </dict> - <key>debug-objc.xcscheme</key> - <dict> - <key>orderHint</key> - <integer>2</integer> - </dict> - <key>isa.xcscheme</key> - <dict> - <key>orderHint</key> - <integer>3</integer> - </dict> - <key>method.xcscheme</key> - <dict> - <key>orderHint</key> - <integer>4</integer> - </dict> - <key>objc-simulator.xcscheme</key> - <dict> - <key>orderHint</key> - <integer>1</integer> - </dict> - <key>objc.xcscheme</key> - <dict> - <key>orderHint</key> - <integer>0</integer> - </dict> - </dict> - <key>SuppressBuildableAutocreation</key> - <dict> - <key>305B27521C7D9E96005AC125</key> - <dict> - <key>primary</key> - <true/> - </dict> - <key>72A15AD51CCCA22E00DCF938</key> - <dict> - <key>primary</key> - <true/> - </dict> - <key>72E4B4211CC9D7090088B2D9</key> - <dict> - <key>primary</key> - <true/> - </dict> - <key>72E4B42D1CC9D78C0088B2D9</key> - <dict> - <key>primary</key> - <true/> - </dict> - <key>83E50CD70FF19E8200D74C19</key> - <dict> - <key>primary</key> - <true/> - </dict> - <key>D2AAC0620554660B00DB518D</key> - <dict> - <key>primary</key> - <true/> - </dict> - </dict> -</dict> -</plist> diff --git a/objc/objc-runtime/objc/objc-abi.h b/objc/objc-runtime/objc/objc-abi.h deleted file mode 100755 index b770259..0000000 --- a/objc/objc-runtime/objc/objc-abi.h +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2009 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 _OBJC_ABI_H -#define _OBJC_ABI_H - -/* - * WARNING DANGER HAZARD BEWARE EEK - * - * Everything in this file is for Apple Internal use only. - * These will change in arbitrary OS updates and in unpredictable ways. - * When your program breaks, you get to keep both pieces. - */ - -/* - * objc-abi.h: Declarations for functions used by compiler codegen. - */ - -#include <malloc/malloc.h> -#include <objc/objc.h> -#include <objc/runtime.h> -#include <objc/message.h> - -/* Runtime startup. */ - -// Old static initializer. Used by old crt1.o and old bug workarounds. -OBJC_EXPORT void _objcInit(void) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - - -/* Properties */ - -// Read or write an object property. Not all object properties use these. -OBJC_EXPORT id objc_getProperty(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -OBJC_EXPORT void objc_setProperty_atomic(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; -OBJC_EXPORT void objc_setProperty_nonatomic(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; -OBJC_EXPORT void objc_setProperty_atomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; -OBJC_EXPORT void objc_setProperty_nonatomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; - - -// Read or write a non-object property. Not all uses are C structs, -// and not all C struct properties use this. -OBJC_EXPORT void objc_copyStruct(void *dest, const void *src, ptrdiff_t size, BOOL atomic, BOOL hasStrong) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -// Perform a copy of a C++ object using striped locks. Used by non-POD C++ typed atomic properties. -OBJC_EXPORT void objc_copyCppObjectAtomic(void *dest, const void *src, void (*copyHelper) (void *dest, const void *source)) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); - -/* Classes. */ -#if __OBJC2__ -OBJC_EXPORT IMP _objc_empty_vtable - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -#endif -OBJC_EXPORT struct objc_cache _objc_empty_cache - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - - -/* Messages */ - -#if __OBJC2__ -// objc_msgSendSuper2() takes the current search class, not its superclass. -OBJC_EXPORT id objc_msgSendSuper2(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_msgSendSuper2_stret(struct objc_super *super, SEL op,...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -// objc_msgSend_noarg() may be faster for methods with no additional arguments. -OBJC_EXPORT id objc_msgSend_noarg(id self, SEL _cmd) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#endif - -#if __OBJC2__ -// Debug messengers. Messengers used by the compiler have a debug flavor that -// may perform extra sanity checking. -// Old objc_msgSendSuper() does not have a debug version; this is OBJC2 only. -// *_fixup() do not have debug versions; use non-fixup only for debug mode. -OBJC_EXPORT id objc_msgSend_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT id objc_msgSendSuper2_debug(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT void objc_msgSend_stret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT void objc_msgSendSuper2_stret_debug(struct objc_super *super, SEL op,...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -# if defined(__i386__) -OBJC_EXPORT double objc_msgSend_fpret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# elif defined(__x86_64__) -OBJC_EXPORT long double objc_msgSend_fpret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# if __STDC_VERSION__ >= 199901L -OBJC_EXPORT _Complex long double objc_msgSend_fp2ret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# else -OBJC_EXPORT void objc_msgSend_fp2ret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# endif -# endif - -#endif - -#if __OBJC2__ && defined(__x86_64__) -// objc_msgSend_fixup() is used for vtable-dispatchable call sites. -OBJC_EXPORT id objc_msgSend_fixup(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT void objc_msgSend_stret_fixup(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT id objc_msgSendSuper2_fixup(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT void objc_msgSendSuper2_stret_fixup(struct objc_super *super, SEL op,...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT long double objc_msgSend_fpret_fixup(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -# if __STDC_VERSION__ >= 199901L -OBJC_EXPORT _Complex long double objc_msgSend_fp2ret_fixup(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -# else -OBJC_EXPORT void objc_msgSend_fp2ret_fixup(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -# endif -#endif - -/* C++-compatible exception handling. */ -#if __OBJC2__ - -// fixme these conflict with C++ compiler's internal definitions -#if !defined(__cplusplus) - -// Vtable for C++ exception typeinfo for Objective-C types. -OBJC_EXPORT const void *objc_ehtype_vtable[] - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -// C++ exception typeinfo for type `id`. -OBJC_EXPORT struct objc_typeinfo OBJC_EHTYPE_id - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -#endif - -// Exception personality function for Objective-C and Objective-C++ code. -struct _Unwind_Exception; -struct _Unwind_Context; -OBJC_EXPORT int -__objc_personality_v0(int version, - int actions, - uint64_t exceptionClass, - struct _Unwind_Exception *exceptionObject, - struct _Unwind_Context *context) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -#endif - -/* ARR */ - -OBJC_EXPORT id objc_retainBlock(id) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -#endif diff --git a/objc/objc-runtime/objcrt/objcrt.vcproj b/objc/objc-runtime/objcrt/objcrt.vcproj deleted file mode 100755 index 22b5919..0000000 --- a/objc/objc-runtime/objcrt/objcrt.vcproj +++ /dev/null @@ -1,95 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioProject - ProjectType="Visual C++" - Version="8.00" - Name="objcrt" - ProjectGUID="{E38C1996-8B3D-4050-A4B2-DC85957B047D}" - RootNamespace="objcrt" - > - <Platforms> - <Platform - Name="Win32" - /> - </Platforms> - <ToolFiles> - </ToolFiles> - <Configurations> - <Configuration - Name="Debug|Win32" - OutputDirectory="$(SolutionDir)$(ConfigurationName)" - IntermediateDirectory="$(ConfigurationName)" - ConfigurationType="10" - CharacterSet="2" - > - <Tool - Name="VCPreBuildEventTool" - CommandLine="cl /nologo /c /MDd /D_DEBUG /Od /Zl /DYNAMICBASE /GS /I"%DSTROOT%\AppleInternal\include" /I"%SRCROOT%\AppleInternal\include" /I"$(ProjectDir)\runtime" /D"_WINDOWS" /Dnil=0 ..\runtime\objcrt.c /Fo"$(OutDir)\objcrt_debug.obj" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCMIDLTool" - /> - <Tool - Name="VCPostBuildEventTool" - CommandLine="xcopy /Y "$(OutDir)\objcrt_debug.obj" "%DSTROOT%\AppleInternal\lib"" - /> - </Configuration> - <Configuration - Name="Release|Win32" - OutputDirectory="$(SolutionDir)$(ConfigurationName)" - IntermediateDirectory="$(ConfigurationName)" - ConfigurationType="10" - CharacterSet="2" - WholeProgramOptimization="1" - > - <Tool - Name="VCPreBuildEventTool" - CommandLine="cl /nologo /c /MD /O1 /Zi /MP2 /DYNAMICBASE /GS /I"%DSTROOT%\AppleInternal\include" /I"%SRCROOT%\AppleInternal\include" /I"$(ProjectDir)\..\runtime" /D"_WINDOWS" /Dnil=0 ..\runtime\objcrt.c /Fo"$(OutDir)\objcrt.obj" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCMIDLTool" - /> - <Tool - Name="VCPostBuildEventTool" - CommandLine="xcopy /Y "$(OutDir)\objcrt.obj" "%DSTROOT%\AppleInternal\lib"" - /> - </Configuration> - </Configurations> - <References> - </References> - <Files> - <Filter - Name="Source Files" - Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx" - UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" - > - <File - RelativePath="..\runtime\objcrt.c" - > - </File> - </Filter> - <Filter - Name="Header Files" - Filter="h;hpp;hxx;hm;inl;inc;xsd" - UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" - > - <File - RelativePath="..\runtime\objcrt.h" - > - </File> - </Filter> - <Filter - Name="Resource Files" - Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav" - UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}" - > - </Filter> - </Files> - <Globals> - </Globals> -</VisualStudioProject> diff --git a/objc/objc-runtime/prebuild.bat b/objc/objc-runtime/prebuild.bat deleted file mode 100755 index 70c55b0..0000000 --- a/objc/objc-runtime/prebuild.bat +++ /dev/null @@ -1,15 +0,0 @@ -@echo off - -echo prebuild: installing headers -xcopy /Y "%ProjectDir%runtime\objc.h" "%DSTROOT%\AppleInternal\include\objc\" -xcopy /Y "%ProjectDir%runtime\objc-api.h" "%DSTROOT%\AppleInternal\include\objc\" -xcopy /Y "%ProjectDir%runtime\objc-auto.h" "%DSTROOT%\AppleInternal\include\objc\" -xcopy /Y "%ProjectDir%runtime\objc-exception.h" "%DSTROOT%\AppleInternal\include\objc\" -xcopy /Y "%ProjectDir%runtime\message.h" "%DSTROOT%\AppleInternal\include\objc\" -xcopy /Y "%ProjectDir%runtime\runtime.h" "%DSTROOT%\AppleInternal\include\objc\" -xcopy /Y "%ProjectDir%runtime\hashtable.h" "%DSTROOT%\AppleInternal\include\objc\" -xcopy /Y "%ProjectDir%runtime\hashtable2.h" "%DSTROOT%\AppleInternal\include\objc\" -xcopy /Y "%ProjectDir%runtime\maptable.h" "%DSTROOT%\AppleInternal\include\objc\" - -echo prebuild: setting version -version diff --git a/objc/objc-runtime/runtests.sh b/objc/objc-runtime/runtests.sh deleted file mode 100755 index dc0f6f8..0000000 --- a/objc/objc-runtime/runtests.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh -# Simple script to run the libclosure tests -# Note: to build the testing root, the makefile will ask to authenticate with sudo -# Use the RootsDirectory environment variable to direct the build to somewhere other than /tmp/ - -RootsDirectory=${RootsDirectory:-/tmp/} -StartingDir="$PWD" -ObjcDir="`dirname $0`" -TestsDir="test/" -cd "$ObjcDir" -# <rdar://problem/6456031> ER: option to not require extra privileges (-nosudo or somesuch) -Buildit="/Network/Servers/xs1/release/bin/buildit -rootsDirectory ${RootsDirectory} -arch i386 -arch x86_64 -project objc4 ." -echo Sudoing for buildit: -sudo $Buildit -XIT=$? -if [[ $XIT == 0 ]]; then - cd "$TestsDir" - #ObjcRootPath="$RootsDirectory/objc4.roots/objc4~dst/usr/lib/libobjc.A.dylib" - #ObjcRootHeaders="$RootsDirectory/objc4.roots/objc4~dst/usr/include/" - #make HALT=YES OBJC_LIB="$ObjcRootPath" OTHER_CFLAGS="-isystem $ObjcRootHeaders" - perl test.pl ARCHS=x86_64 OBJC_ROOT="$RootsDirectory/objc4.roots/" - XIT=`expr $XIT \| $?` - perl test.pl ARCHS=i386 OBJC_ROOT="$RootsDirectory/objc4.roots/" - XIT=`expr $XIT \| $?` - perl test.pl ARCHS=x86_64 GUARDMALLOC=YES OBJC_ROOT="$RootsDirectory/objc4.roots/" - XIT=`expr $XIT \| $?` - perl test.pl ARCHS=i386 GUARDMALLOC=YES OBJC_ROOT="$RootsDirectory/objc4.roots/" - XIT=`expr $XIT \| $?` - perl test.pl clean -fi -cd "$StartingDir" -exit $XIT \ No newline at end of file diff --git a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-arm.s b/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-arm.s deleted file mode 100644 index 142e285..0000000 --- a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-arm.s +++ /dev/null @@ -1,778 +0,0 @@ -/* - * @APPLE_LICENSE_HEADER_START@ - * - * Copyright (c) 1999-2007 Apple Computer, Inc. All Rights Reserved. - * - * 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@ - */ -/******************************************************************** - * - * objc-msg-arm.s - ARM code to support objc messaging - * - ********************************************************************/ - -#ifdef __arm__ - -#include <arm/arch.h> - -#ifndef _ARM_ARCH_7 -# error requires armv7 -#endif - -// Set FP=1 on architectures that pass parameters in floating-point registers -#if __ARM_ARCH_7K__ -# define FP 1 -#else -# define FP 0 -#endif - -#if FP - -# if !__ARM_NEON__ -# error sorry -# endif - -# define FP_RETURN_ZERO \ - vmov.i32 q0, #0 ; \ - vmov.i32 q1, #0 ; \ - vmov.i32 q2, #0 ; \ - vmov.i32 q3, #0 - -# define FP_SAVE \ - vpush {q0-q3} - -# define FP_RESTORE \ - vpop {q0-q3} - -#else - -# define FP_RETURN_ZERO -# define FP_SAVE -# define FP_RESTORE - -#endif - -.syntax unified - -#define MI_EXTERN(var) \ - .non_lazy_symbol_pointer ;\ -L ## var ## $$non_lazy_ptr: ;\ - .indirect_symbol var ;\ - .long 0 - -#define MI_GET_EXTERN(reg,var) \ - movw reg, :lower16:(L##var##$$non_lazy_ptr-4f-4) ;\ - movt reg, :upper16:(L##var##$$non_lazy_ptr-4f-4) ;\ -4: add reg, pc ;\ - ldr reg, [reg] - -#define MI_CALL_EXTERNAL(var) \ - MI_GET_EXTERN(r12,var) ;\ - blx r12 - - -#define MI_GET_ADDRESS(reg,var) \ - movw reg, :lower16:(var-4f-4) ;\ - movt reg, :upper16:(var-4f-4) ;\ -4: add reg, pc ;\ - - -MI_EXTERN(__class_lookupMethodAndLoadCache3) -MI_EXTERN(___objc_error) - - -.data - -// _objc_entryPoints and _objc_exitPoints are used by method dispatch -// caching code to figure out whether any threads are actively -// in the cache for dispatching. The labels surround the asm code -// that do cache lookups. The tables are zero-terminated. - -.align 2 -.private_extern _objc_entryPoints -_objc_entryPoints: - .long _cache_getImp - .long _objc_msgSend - .long _objc_msgSend_stret - .long _objc_msgSendSuper - .long _objc_msgSendSuper_stret - .long _objc_msgSendSuper2 - .long _objc_msgSendSuper2_stret - .long 0 - -.private_extern _objc_exitPoints -_objc_exitPoints: - .long LGetImpExit - .long LMsgSendExit - .long LMsgSendStretExit - .long LMsgSendSuperExit - .long LMsgSendSuperStretExit - .long LMsgSendSuper2Exit - .long LMsgSendSuper2StretExit - .long 0 - - -/******************************************************************** -* List every exit insn from every messenger for debugger use. -* Format: -* ( -* 1 word instruction's address -* 1 word type (ENTER or FAST_EXIT or SLOW_EXIT or NIL_EXIT) -* ) -* 1 word zero -* -* ENTER is the start of a dispatcher -* FAST_EXIT is method dispatch -* SLOW_EXIT is uncached method lookup -* NIL_EXIT is returning zero from a message sent to nil -* These must match objc-gdb.h. -********************************************************************/ - -#define ENTER 1 -#define FAST_EXIT 2 -#define SLOW_EXIT 3 -#define NIL_EXIT 4 - -.section __DATA,__objc_msg_break -.globl _gdb_objc_messenger_breakpoints -_gdb_objc_messenger_breakpoints: -// contents populated by the macros below - -.macro MESSENGER_START -4: - .section __DATA,__objc_msg_break - .long 4b - .long ENTER - .text -.endmacro -.macro MESSENGER_END_FAST -4: - .section __DATA,__objc_msg_break - .long 4b - .long FAST_EXIT - .text -.endmacro -.macro MESSENGER_END_SLOW -4: - .section __DATA,__objc_msg_break - .long 4b - .long SLOW_EXIT - .text -.endmacro -.macro MESSENGER_END_NIL -4: - .section __DATA,__objc_msg_break - .long 4b - .long NIL_EXIT - .text -.endmacro - - -/******************************************************************** - * Names for relative labels - * DO NOT USE THESE LABELS ELSEWHERE - * Reserved labels: 8: 9: - ********************************************************************/ -#define LCacheMiss 8 -#define LCacheMiss_f 8f -#define LCacheMiss_b 8b -#define LNilReceiver 9 -#define LNilReceiver_f 9f -#define LNilReceiver_b 9b - - -/******************************************************************** - * Macro parameters - ********************************************************************/ - -#define NORMAL 0 -#define FPRET 1 -#define FP2RET 2 -#define GETIMP 3 -#define STRET 4 -#define SUPER 5 -#define SUPER2 6 -#define SUPER_STRET 7 -#define SUPER2_STRET 8 - - -/******************************************************************** - * - * Structure definitions. - * - ********************************************************************/ - -/* objc_super parameter to sendSuper */ -#define RECEIVER 0 -#define CLASS 4 - -/* Selected field offsets in class structure */ -#define ISA 0 -#define SUPERCLASS 4 -#define CACHE 8 -#define CACHE_MASK 12 - -/* Selected field offsets in method structure */ -#define METHOD_NAME 0 -#define METHOD_TYPES 4 -#define METHOD_IMP 8 - - -////////////////////////////////////////////////////////////////////// -// -// ENTRY functionName -// -// Assembly directives to begin an exported function. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro ENTRY /* name */ - .text - .thumb - .align 5 - .globl _$0 - .thumb_func -_$0: -.endmacro - -.macro STATIC_ENTRY /*name*/ - .text - .thumb - .align 5 - .private_extern _$0 - .thumb_func -_$0: -.endmacro - - -////////////////////////////////////////////////////////////////////// -// -// END_ENTRY functionName -// -// Assembly directives to end an exported function. Just a placeholder, -// a close-parenthesis for ENTRY, until it is needed for something. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro END_ENTRY /* name */ -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// CacheLookup return-type -// -// Locate the implementation for a selector in a class's method cache. -// -// Takes: -// $0 = NORMAL, STRET, SUPER, SUPER_STRET, SUPER2, SUPER2_STRET, GETIMP -// r0 or r1 (STRET) = receiver -// r1 or r2 (STRET) = selector -// r9 = class to search in -// -// On exit: r9 and r12 clobbered -// (found) calls or returns IMP, eq/ne/r9 set for forwarding -// (not found) jumps to LCacheMiss -// -///////////////////////////////////////////////////////////////////// - -.macro CacheHit - -.if $0 == GETIMP - ldr r0, [r9, #4] // r0 = bucket->imp - MI_GET_ADDRESS(r1, __objc_msgSend_uncached_impcache) - teq r0, r1 - it eq - moveq r0, #0 // don't return msgSend_uncached - bx lr // return imp -.elseif $0 == NORMAL - ldr r12, [r9, #4] // r12 = bucket->imp - // eq already set for nonstret forward - MESSENGER_END_FAST - bx r12 // call imp -.elseif $0 == STRET - ldr r12, [r9, #4] // r12 = bucket->imp - movs r9, #1 // r9=1, Z=0 for stret forwarding - MESSENGER_END_FAST - bx r12 // call imp -.elseif $0 == SUPER - ldr r12, [r9, #4] // r12 = bucket->imp - ldr r9, [r0, #CLASS] // r9 = class to search for forwarding - ldr r0, [r0, #RECEIVER] // fetch real receiver - tst r12, r12 // set ne for forwarding (r12!=0) - MESSENGER_END_FAST - bx r12 // call imp -.elseif $0 == SUPER2 - ldr r12, [r9, #4] // r12 = bucket->imp - ldr r9, [r0, #CLASS] - ldr r9, [r9, #SUPERCLASS] // r9 = class to search for forwarding - ldr r0, [r0, #RECEIVER] // fetch real receiver - tst r12, r12 // set ne for forwarding (r12!=0) - MESSENGER_END_FAST - bx r12 // call imp -.elseif $0 == SUPER_STRET - ldr r12, [r9, #4] // r12 = bucket->imp - ldr r9, [r1, #CLASS] // r9 = class to search for forwarding - orr r9, r9, #1 // r9 = class|1 for super_stret forward - ldr r1, [r1, #RECEIVER] // fetch real receiver - tst r12, r12 // set ne for forwarding (r12!=0) - MESSENGER_END_FAST - bx r12 // call imp -.elseif $0 == SUPER2_STRET - ldr r12, [r9, #4] // r12 = bucket->imp - ldr r9, [r1, #CLASS] // r9 = class to search for forwarding - ldr r9, [r9, #SUPERCLASS] // r9 = class to search for forwarding - orr r9, r9, #1 // r9 = class|1 for super_stret forward - ldr r1, [r1, #RECEIVER] // fetch real receiver - tst r12, r12 // set ne for forwarding (r12!=0) - MESSENGER_END_FAST - bx r12 // call imp -.else -.abort oops -.endif - -.endmacro - -.macro CacheLookup - - ldrh r12, [r9, #CACHE_MASK] // r12 = mask - ldr r9, [r9, #CACHE] // r9 = buckets -.if $0 == STRET || $0 == SUPER_STRET - and r12, r12, r2 // r12 = index = SEL & mask -.else - and r12, r12, r1 // r12 = index = SEL & mask -.endif - add r9, r9, r12, LSL #3 // r9 = bucket = buckets+index*8 - ldr r12, [r9] // r12 = bucket->sel -2: -.if $0 == STRET || $0 == SUPER_STRET - teq r12, r2 -.else - teq r12, r1 -.endif - bne 1f - CacheHit $0 -1: - cmp r12, #1 - blo LCacheMiss_f // if (bucket->sel == 0) cache miss - it eq // if (bucket->sel == 1) cache wrap - ldreq r9, [r9, #4] // bucket->imp is before first bucket - ldr r12, [r9, #8]! // r12 = (++bucket)->sel - b 2b - -.endmacro - - -/******************************************************************** - * IMP cache_getImp(Class cls, SEL sel) - * - * On entry: r0 = class whose cache is to be searched - * r1 = selector to search for - * - * If found, returns method implementation. - * If not found, returns NULL. - ********************************************************************/ - - STATIC_ENTRY cache_getImp - - mov r9, r0 - CacheLookup GETIMP // returns IMP on success - -LCacheMiss: - mov r0, #0 // return nil if cache miss - bx lr - -LGetImpExit: - END_ENTRY cache_getImp - - -/******************************************************************** - * - * id objc_msgSend(id self, SEL _cmd,...); - * - ********************************************************************/ - - ENTRY objc_msgSend - MESSENGER_START - - cbz r0, LNilReceiver_f - - ldr r9, [r0] // r9 = self->isa - CacheLookup NORMAL - // calls IMP or LCacheMiss - -LCacheMiss: - MESSENGER_END_SLOW - ldr r9, [r0, #ISA] // class = receiver->isa - b __objc_msgSend_uncached - -LNilReceiver: - // r0 is already zero - mov r1, #0 - mov r2, #0 - mov r3, #0 - FP_RETURN_ZERO - MESSENGER_END_NIL - bx lr - -LMsgSendExit: - END_ENTRY objc_msgSend - - -/******************************************************************** - * id objc_msgSend_noarg(id self, SEL op) - * - * On entry: r0 is the message receiver, - * r1 is the selector - ********************************************************************/ - - ENTRY objc_msgSend_noarg - b _objc_msgSend - END_ENTRY objc_msgSend_noarg - - -/******************************************************************** - * void objc_msgSend_stret(void *st_addr, id self, SEL op, ...); - * - * objc_msgSend_stret is the struct-return form of msgSend. - * The ABI calls for r0 to be used as the address of the structure - * being returned, with the parameters in the succeeding registers. - * - * On entry: r0 is the address where the structure is returned, - * r1 is the message receiver, - * r2 is the selector - ********************************************************************/ - - ENTRY objc_msgSend_stret - MESSENGER_START - - cbz r1, LNilReceiver_f - - ldr r9, [r1] // r9 = self->isa - CacheLookup STRET - // calls IMP or LCacheMiss - -LCacheMiss: - MESSENGER_END_SLOW - ldr r9, [r1] // r9 = self->isa - b __objc_msgSend_stret_uncached - -LNilReceiver: - MESSENGER_END_NIL - bx lr - -LMsgSendStretExit: - END_ENTRY objc_msgSend_stret - - -/******************************************************************** - * id objc_msgSendSuper(struct objc_super *super, SEL op, ...) - * - * struct objc_super { - * id receiver; - * Class cls; // the class to search - * } - ********************************************************************/ - - ENTRY objc_msgSendSuper - MESSENGER_START - - ldr r9, [r0, #CLASS] // r9 = struct super->class - CacheLookup SUPER - // calls IMP or LCacheMiss - -LCacheMiss: - MESSENGER_END_SLOW - ldr r9, [r0, #CLASS] // r9 = struct super->class - ldr r0, [r0, #RECEIVER] // load real receiver - b __objc_msgSend_uncached - -LMsgSendSuperExit: - END_ENTRY objc_msgSendSuper - - -/******************************************************************** - * id objc_msgSendSuper2(struct objc_super *super, SEL op, ...) - * - * struct objc_super { - * id receiver; - * Class cls; // SUBCLASS of the class to search - * } - ********************************************************************/ - - ENTRY objc_msgSendSuper2 - MESSENGER_START - - ldr r9, [r0, #CLASS] // class = struct super->class - ldr r9, [r9, #SUPERCLASS] // class = class->superclass - CacheLookup SUPER2 - // calls IMP or LCacheMiss - -LCacheMiss: - MESSENGER_END_SLOW - ldr r9, [r0, #CLASS] // class = struct super->class - ldr r9, [r9, #SUPERCLASS] // class = class->superclass - ldr r0, [r0, #RECEIVER] // load real receiver - b __objc_msgSend_uncached - -LMsgSendSuper2Exit: - END_ENTRY objc_msgSendSuper2 - - -/******************************************************************** - * void objc_msgSendSuper_stret(void *st_addr, objc_super *self, SEL op, ...); - * - * objc_msgSendSuper_stret is the struct-return form of msgSendSuper. - * The ABI calls for r0 to be used as the address of the structure - * being returned, with the parameters in the succeeding registers. - * - * On entry: r0 is the address where the structure is returned, - * r1 is the address of the objc_super structure, - * r2 is the selector - ********************************************************************/ - - ENTRY objc_msgSendSuper_stret - MESSENGER_START - - ldr r9, [r1, #CLASS] // r9 = struct super->class - CacheLookup SUPER_STRET - // calls IMP or LCacheMiss - -LCacheMiss: - MESSENGER_END_SLOW - ldr r9, [r1, #CLASS] // r9 = struct super->class - ldr r1, [r1, #RECEIVER] // load real receiver - b __objc_msgSend_stret_uncached - -LMsgSendSuperStretExit: - END_ENTRY objc_msgSendSuper_stret - - -/******************************************************************** - * id objc_msgSendSuper2_stret - ********************************************************************/ - - ENTRY objc_msgSendSuper2_stret - MESSENGER_START - - ldr r9, [r1, #CLASS] // class = struct super->class - ldr r9, [r9, #SUPERCLASS] // class = class->superclass - CacheLookup SUPER2_STRET - -LCacheMiss: - MESSENGER_END_SLOW - ldr r9, [r1, #CLASS] // class = struct super->class - ldr r9, [r9, #SUPERCLASS] // class = class->superclass - ldr r1, [r1, #RECEIVER] // load real receiver - b __objc_msgSend_stret_uncached - -LMsgSendSuper2StretExit: - END_ENTRY objc_msgSendSuper2_stret - - -/******************************************************************** - * - * _objc_msgSend_uncached_impcache - * Used to erase method cache entries in-place by - * bouncing them to the uncached lookup. - * - * _objc_msgSend_uncached - * _objc_msgSend_stret_uncached - * The uncached lookup. - * - ********************************************************************/ - - STATIC_ENTRY _objc_msgSend_uncached_impcache - // Method cache version - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band Z is 0 (EQ) for normal, 1 (NE) for stret and/or super - // Out-of-band r9 is 1 for stret, cls for super, cls|1 for super_stret - // Note objc_msgForward_impcache uses the same parameters - - MESSENGER_START - nop - MESSENGER_END_SLOW - - ite eq - ldreq r9, [r0] // normal: r9 = class = self->isa - tstne r9, #1 // low bit clear? - beq __objc_msgSend_uncached // super: r9 is already the class - // stret or super_stret - eors r9, r9, #1 // clear low bit - it eq // r9 now zero? - ldreq r9, [r1] // stret: r9 = class = self->isa - // super_stret: r9 is already the class - b __objc_msgSend_stret_uncached - - END_ENTRY _objc_msgSend_uncached_impcache - - - STATIC_ENTRY _objc_msgSend_uncached - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band r9 is the class to search - - stmfd sp!, {r0-r3,r7,lr} - add r7, sp, #16 - sub sp, #8 // align stack - FP_SAVE - // receiver already in r0 - // selector already in r1 - mov r2, r9 // class to search - - MI_CALL_EXTERNAL(__class_lookupMethodAndLoadCache3) - mov r12, r0 // r12 = IMP - - movs r9, #0 // r9=0, Z=1 for nonstret forwarding - FP_RESTORE - add sp, #8 // align stack - ldmfd sp!, {r0-r3,r7,lr} - bx r12 - - END_ENTRY _objc_msgSend_uncached - - - STATIC_ENTRY _objc_msgSend_stret_uncached - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band r9 is the class to search - - stmfd sp!, {r0-r3,r7,lr} - add r7, sp, #16 - sub sp, #8 // align stack - FP_SAVE - - mov r0, r1 // receiver - mov r1, r2 // selector - mov r2, r9 // class to search - - MI_CALL_EXTERNAL(__class_lookupMethodAndLoadCache3) - mov r12, r0 // r12 = IMP - - movs r9, #1 // r9=1, Z=0 for stret forwarding - FP_RESTORE - add sp, #8 // align stack - ldmfd sp!, {r0-r3,r7,lr} - bx r12 - - END_ENTRY _objc_msgSend_stret_uncached - - -/******************************************************************** -* -* id _objc_msgForward(id self, SEL _cmd,...); -* -* _objc_msgForward and _objc_msgForward_stret are the externally-callable -* functions returned by things like method_getImplementation(). -* _objc_msgForward_impcache is the function pointer actually stored in -* method caches. -* -********************************************************************/ - - MI_EXTERN(__objc_forward_handler) - MI_EXTERN(__objc_forward_stret_handler) - - STATIC_ENTRY _objc_msgForward_impcache - // Method cache version - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band Z is 0 (EQ) for normal, 1 (NE) for stret and/or super - // Out-of-band r9 is 1 for stret, cls for super, cls|1 for super_stret - // Note _objc_msgSend_uncached_impcache uses the same parameters - - MESSENGER_START - nop - MESSENGER_END_SLOW - - it ne - tstne r9, #1 - beq __objc_msgForward - b __objc_msgForward_stret - - END_ENTRY _objc_msgForward_impcache - - - ENTRY _objc_msgForward - // Non-stret version - - MI_GET_EXTERN(r12, __objc_forward_handler) - ldr r12, [r12] - bx r12 - - END_ENTRY _objc_msgForward - - - ENTRY _objc_msgForward_stret - // Struct-return version - - MI_GET_EXTERN(r12, __objc_forward_stret_handler) - ldr r12, [r12] - bx r12 - - END_ENTRY _objc_msgForward_stret - - - ENTRY objc_msgSend_debug - b _objc_msgSend - END_ENTRY objc_msgSend_debug - - ENTRY objc_msgSendSuper2_debug - b _objc_msgSendSuper2 - END_ENTRY objc_msgSendSuper2_debug - - ENTRY objc_msgSend_stret_debug - b _objc_msgSend_stret - END_ENTRY objc_msgSend_stret_debug - - ENTRY objc_msgSendSuper2_stret_debug - b _objc_msgSendSuper2_stret - END_ENTRY objc_msgSendSuper2_stret_debug - - - ENTRY method_invoke - // r1 is method triplet instead of SEL - ldr r12, [r1, #METHOD_IMP] - ldr r1, [r1, #METHOD_NAME] - bx r12 - END_ENTRY method_invoke - - - ENTRY method_invoke_stret - // r2 is method triplet instead of SEL - ldr r12, [r2, #METHOD_IMP] - ldr r2, [r2, #METHOD_NAME] - bx r12 - END_ENTRY method_invoke_stret - - - STATIC_ENTRY _objc_ignored_method - - // self is already in a0 - bx lr - - END_ENTRY _objc_ignored_method - - -.section __DATA,__objc_msg_break -.long 0 -.long 0 - -#endif diff --git a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-arm64.s b/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-arm64.s deleted file mode 100755 index d2391e2..0000000 --- a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-arm64.s +++ /dev/null @@ -1,472 +0,0 @@ -/* - * @APPLE_LICENSE_HEADER_START@ - * - * Copyright (c) 2011 Apple Inc. All Rights Reserved. - * - * 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@ - */ -/******************************************************************** - * - * objc-msg-arm64.s - ARM64 code to support objc messaging - * - ********************************************************************/ - -#ifdef __arm64__ - -#include <arm/arch.h> - - -.data - -// _objc_entryPoints and _objc_exitPoints are used by method dispatch -// caching code to figure out whether any threads are actively -// in the cache for dispatching. The labels surround the asm code -// that do cache lookups. The tables are zero-terminated. - -.align 4 -.private_extern _objc_entryPoints -_objc_entryPoints: - .quad _cache_getImp - .quad _objc_msgSend - .quad _objc_msgSendSuper - .quad _objc_msgSendSuper2 - .quad 0 - -.private_extern _objc_exitPoints -_objc_exitPoints: - .quad LExit_cache_getImp - .quad LExit_objc_msgSend - .quad LExit_objc_msgSendSuper - .quad LExit_objc_msgSendSuper2 - .quad 0 - - -/******************************************************************** -* List every exit insn from every messenger for debugger use. -* Format: -* ( -* 1 word instruction's address -* 1 word type (ENTER or FAST_EXIT or SLOW_EXIT or NIL_EXIT) -* ) -* 1 word zero -* -* ENTER is the start of a dispatcher -* FAST_EXIT is method dispatch -* SLOW_EXIT is uncached method lookup -* NIL_EXIT is returning zero from a message sent to nil -* These must match objc-gdb.h. -********************************************************************/ - -#define ENTER 1 -#define FAST_EXIT 2 -#define SLOW_EXIT 3 -#define NIL_EXIT 4 - -.section __DATA,__objc_msg_break -.globl _gdb_objc_messenger_breakpoints -_gdb_objc_messenger_breakpoints: -// contents populated by the macros below - -.macro MESSENGER_START -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad ENTER - .text -.endmacro -.macro MESSENGER_END_FAST -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad FAST_EXIT - .text -.endmacro -.macro MESSENGER_END_SLOW -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad SLOW_EXIT - .text -.endmacro -.macro MESSENGER_END_NIL -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad NIL_EXIT - .text -.endmacro - - -/* objc_super parameter to sendSuper */ -#define RECEIVER 0 -#define CLASS 8 - -/* Selected field offsets in class structure */ -#define SUPERCLASS 8 -#define CACHE 16 - -/* Selected field offsets in isa field */ -#define ISA_MASK 0x00000001fffffff8 - -/* Selected field offsets in method structure */ -#define METHOD_NAME 0 -#define METHOD_TYPES 8 -#define METHOD_IMP 16 - - -/******************************************************************** - * ENTRY functionName - * STATIC_ENTRY functionName - * END_ENTRY functionName - ********************************************************************/ - -.macro ENTRY /* name */ - .text - .align 5 - .globl $0 -$0: -.endmacro - -.macro STATIC_ENTRY /*name*/ - .text - .align 5 - .private_extern $0 -$0: -.endmacro - -.macro END_ENTRY /* name */ -LExit$0: -.endmacro - - -/******************************************************************** - * - * CacheLookup NORMAL|GETIMP - * - * Locate the implementation for a selector in a class method cache. - * - * Takes: - * x1 = selector - * x9 = class to be searched - * - * Kills: - * x10,x11,x12, x16,x17 - * - * On exit: (found) exits CacheLookup - * with x9 = class, x17 = IMP - * (not found) jumps to LCacheMiss - * - ********************************************************************/ - -#define NORMAL 0 -#define GETIMP 1 - -.macro CacheHit - MESSENGER_END_FAST -.if $0 == NORMAL - br x17 // call imp -.else - b LGetImpHit -.endif -.endmacro - -.macro CheckMiss -.if $0 == NORMAL // miss if bucket->cls == 0 - cbz x16, __objc_msgSend_uncached_impcache -.else - cbz x16, LGetImpMiss -.endif -.endmacro - -.macro JumpMiss -.if $0 == NORMAL - b __objc_msgSend_uncached_impcache -.else - b LGetImpMiss -.endif -.endmacro - -.macro CacheLookup - // x1 = SEL, x9 = isa - ldp x10, x11, [x9, #CACHE] // x10 = buckets, x11 = occupied|mask - and w12, w1, w11 // x12 = _cmd & mask - add x12, x10, x12, LSL #4 // x12 = buckets + ((_cmd & mask)<<4) - - ldp x16, x17, [x12] // {x16, x17} = *bucket -1: cmp x16, x1 // if (bucket->sel != _cmd) - b.ne 2f // scan more - CacheHit $0 // call or return imp - -2: // not hit: x12 = not-hit bucket - CheckMiss $0 // miss if bucket->cls == 0 - cmp x12, x10 // wrap if bucket == buckets - b.eq 3f - ldp x16, x17, [x12, #-16]! // {x16, x17} = *--bucket - b 1b // loop - -3: // wrap: x12 = first bucket, w11 = mask - add x12, x12, w11, UXTW #4 // x12 = buckets+(mask<<4) - - // Clone scanning loop to miss instead of hang when cache is corrupt. - // The slow path may detect any corruption and halt later. - - ldp x16, x17, [x12] // {x16, x17} = *bucket -1: cmp x16, x1 // if (bucket->sel != _cmd) - b.ne 2f // scan more - CacheHit $0 // call or return imp - -2: // not hit: x12 = not-hit bucket - CheckMiss $0 // miss if bucket->cls == 0 - cmp x12, x10 // wrap if bucket == buckets - b.eq 3f - ldp x16, x17, [x12, #-16]! // {x16, x17} = *--bucket - b 1b // loop - -3: // double wrap - JumpMiss $0 - -.endmacro - - - .data - .align 3 - .globl _objc_debug_taggedpointer_classes -_objc_debug_taggedpointer_classes: - .fill 16, 8, 0 - - ENTRY _objc_msgSend - MESSENGER_START - - cmp x0, #0 // nil check and tagged pointer check - b.le LNilOrTagged // (MSB tagged pointer looks negative) - ldr x13, [x0] // x13 = isa - and x9, x13, #ISA_MASK // x9 = class -LGetIsaDone: - CacheLookup NORMAL // calls imp or objc_msgSend_uncached - -LNilOrTagged: - b.eq LReturnZero // nil check - - // tagged - adrp x10, _objc_debug_taggedpointer_classes@PAGE - add x10, x10, _objc_debug_taggedpointer_classes@PAGEOFF - ubfx x11, x0, #60, #4 - ldr x9, [x10, x11, LSL #3] - b LGetIsaDone - -LReturnZero: - // x0 is already zero - mov x1, #0 - movi d0, #0 - movi d1, #0 - movi d2, #0 - movi d3, #0 - MESSENGER_END_NIL - ret - - END_ENTRY _objc_msgSend - - - ENTRY _objc_msgSendSuper - MESSENGER_START - - ldr x9, [x0, #CLASS] // load class to search - ldr x0, [x0, #RECEIVER] // load real receiver - CacheLookup NORMAL // calls imp or objc_msgSend_uncached - - END_ENTRY _objc_msgSendSuper - - - ENTRY _objc_msgSendSuper2 - MESSENGER_START - - ldr x9, [x0, #CLASS] - ldr x9, [x9, #SUPERCLASS] // load class to search - ldr x0, [x0, #RECEIVER] // load real receiver - CacheLookup NORMAL - - END_ENTRY _objc_msgSendSuper2 - - - ENTRY _objc_msgSend_noarg - b _objc_msgSend - END_ENTRY _objc_msgSend_noarg - - - STATIC_ENTRY __objc_msgSend_uncached_impcache - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band x9 is the class to search - - MESSENGER_START - - // push frame - stp fp, lr, [sp, #-16]! - mov fp, sp - - MESSENGER_END_SLOW - - // save parameter registers: x0..x8, q0..q7 - sub sp, sp, #(10*8 + 8*16) - stp q0, q1, [sp, #(0*16)] - stp q2, q3, [sp, #(2*16)] - stp q4, q5, [sp, #(4*16)] - stp q6, q7, [sp, #(6*16)] - stp x0, x1, [sp, #(8*16+0*8)] - stp x2, x3, [sp, #(8*16+2*8)] - stp x4, x5, [sp, #(8*16+4*8)] - stp x6, x7, [sp, #(8*16+6*8)] - str x8, [sp, #(8*16+8*8)] - - // receiver and selector already in x0 and x1 - mov x2, x9 - bl __class_lookupMethodAndLoadCache3 - - // imp in x0 - mov x17, x0 - - // restore registers and return - ldp q0, q1, [sp, #(0*16)] - ldp q2, q3, [sp, #(2*16)] - ldp q4, q5, [sp, #(4*16)] - ldp q6, q7, [sp, #(6*16)] - ldp x0, x1, [sp, #(8*16+0*8)] - ldp x2, x3, [sp, #(8*16+2*8)] - ldp x4, x5, [sp, #(8*16+4*8)] - ldp x6, x7, [sp, #(8*16+6*8)] - ldr x8, [sp, #(8*16+8*8)] - - mov sp, fp - ldp fp, lr, [sp], #16 - - br x17 - - END_ENTRY __objc_msgSend_uncached_impcache - - -.section __LD,__compact_unwind,regular,debug - .quad _objc_msgSend - .set LUnwind_objc_msgSend, LExit_objc_msgSend-_objc_msgSend - .long LUnwind_objc_msgSend - .long 0x02000000 // no frame, no SP adjustment - .quad 0 // no personality - .quad 0 // no LSDA - -.section __LD,__compact_unwind,regular,debug - .quad _objc_msgSendSuper - .set LUnwind_objc_msgSendSuper, LExit_objc_msgSendSuper-_objc_msgSendSuper - .long LUnwind_objc_msgSendSuper - .long 0x02000000 // no frame, no SP adjustment - .quad 0 // no personality - .quad 0 // no LSDA - -.section __LD,__compact_unwind,regular,debug - .quad _objc_msgSendSuper2 - .set LUnwind_objc_msgSendSuper2, LExit_objc_msgSendSuper2-_objc_msgSendSuper2 - .long LUnwind_objc_msgSendSuper2 - .long 0x02000000 // no frame, no SP adjustment - .quad 0 // no personality - .quad 0 // no LSDA - -.section __LD,__compact_unwind,regular,debug - .quad __objc_msgSend_uncached_impcache - .set LUnwind__objc_msgSend_uncached_impcache, LExit__objc_msgSend_uncached_impcache-__objc_msgSend_uncached_impcache - .long LUnwind__objc_msgSend_uncached_impcache - .long 0x04000000 // frame, no non-volatile registers saved - .quad 0 // no personality - .quad 0 // no LSDA - - - STATIC_ENTRY _cache_getImp - - and x9, x0, #ISA_MASK - CacheLookup GETIMP - -LGetImpHit: - // imp in x17 - // don't return msgSend_uncached - adrp x16, __objc_msgSend_uncached_impcache@PAGE - add x16, x16, __objc_msgSend_uncached_impcache@PAGEOFF - cmp x16, x17 - csel x0, x17, xzr, ne // if imp!=uncached then imp else 0 - ret - -LGetImpMiss: - mov x0, #0 - ret - - END_ENTRY _cache_getImp - - -/******************************************************************** -* -* id _objc_msgForward(id self, SEL _cmd,...); -* -* _objc_msgForward is the externally-callable -* function returned by things like method_getImplementation(). -* _objc_msgForward_impcache is the function pointer actually stored in -* method caches. -* -********************************************************************/ - - STATIC_ENTRY __objc_msgForward_impcache - - MESSENGER_START - nop - MESSENGER_END_SLOW - - // No stret specialization. - b __objc_msgForward - - END_ENTRY __objc_msgForward_impcache - - - ENTRY __objc_msgForward - - adrp x17, __objc_forward_handler@PAGE - ldr x17, [x17, __objc_forward_handler@PAGEOFF] - br x17 - - END_ENTRY __objc_msgForward - - - ENTRY _objc_msgSend_debug - b _objc_msgSend - END_ENTRY _objc_msgSend_debug - - ENTRY _objc_msgSendSuper2_debug - b _objc_msgSendSuper2 - END_ENTRY _objc_msgSendSuper2_debug - - - ENTRY _method_invoke - // x1 is method triplet instead of SEL - ldr x17, [x1, #METHOD_IMP] - ldr x1, [x1, #METHOD_NAME] - br x17 - END_ENTRY _method_invoke - - - STATIC_ENTRY __objc_ignored_method - - // self is already in x0 - ret - - END_ENTRY __objc_ignored_method - -#endif diff --git a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-i386.s b/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-i386.s deleted file mode 100644 index 48f95f8..0000000 --- a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-i386.s +++ /dev/null @@ -1,1187 +0,0 @@ -/* - * 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@ - */ - -#include <TargetConditionals.h> -#if defined(__i386__) && !TARGET_IPHONE_SIMULATOR - -/******************************************************************** - ******************************************************************** - ** - ** objc-msg-i386.s - i386 code to support objc messaging. - ** - ******************************************************************** - ********************************************************************/ - -// for kIgnore -#include "objc-config.h" - - -/******************************************************************** -* Data used by the ObjC runtime. -* -********************************************************************/ - -.data - -// _objc_entryPoints and _objc_exitPoints are used by objc -// to get the critical regions for which method caches -// cannot be garbage collected. - -.align 2 -.private_extern _objc_entryPoints -_objc_entryPoints: - .long __cache_getImp - .long __cache_getMethod - .long _objc_msgSend - .long _objc_msgSend_fpret - .long _objc_msgSend_stret - .long _objc_msgSendSuper - .long _objc_msgSendSuper_stret - .long 0 - -.private_extern _objc_exitPoints -_objc_exitPoints: - .long LGetImpExit - .long LGetMethodExit - .long LMsgSendExit - .long LMsgSendFpretExit - .long LMsgSendStretExit - .long LMsgSendSuperExit - .long LMsgSendSuperStretExit - .long 0 - - -/******************************************************************** -* List every exit insn from every messenger for debugger use. -* Format: -* ( -* 1 word instruction's address -* 1 word type (ENTER or FAST_EXIT or SLOW_EXIT or NIL_EXIT) -* ) -* 1 word zero -* -* ENTER is the start of a dispatcher -* FAST_EXIT is method dispatch -* SLOW_EXIT is uncached method lookup -* NIL_EXIT is returning zero from a message sent to nil -* These must match objc-gdb.h. -********************************************************************/ - -#define ENTER 1 -#define FAST_EXIT 2 -#define SLOW_EXIT 3 -#define NIL_EXIT 4 - -.section __DATA,__objc_msg_break -.globl _gdb_objc_messenger_breakpoints -_gdb_objc_messenger_breakpoints: -// contents populated by the macros below - -.macro MESSENGER_START -4: - .section __DATA,__objc_msg_break - .long 4b - .long ENTER - .text -.endmacro -.macro MESSENGER_END_FAST -4: - .section __DATA,__objc_msg_break - .long 4b - .long FAST_EXIT - .text -.endmacro -.macro MESSENGER_END_SLOW -4: - .section __DATA,__objc_msg_break - .long 4b - .long SLOW_EXIT - .text -.endmacro -.macro MESSENGER_END_NIL -4: - .section __DATA,__objc_msg_break - .long 4b - .long NIL_EXIT - .text -.endmacro - - -/******************************************************************** - * - * Common offsets. - * - ********************************************************************/ - - self = 4 - super = 4 - selector = 8 - marg_size = 12 - marg_list = 16 - first_arg = 12 - - struct_addr = 4 - - self_stret = 8 - super_stret = 8 - selector_stret = 12 - marg_size_stret = 16 - marg_list_stret = 20 - - -/******************************************************************** - * - * Structure definitions. - * - ********************************************************************/ - -// objc_super parameter to sendSuper - receiver = 0 - class = 4 - -// Selected field offsets in class structure - isa = 0 - cache = 32 - -// Method descriptor - method_name = 0 - method_imp = 8 - -// Cache header - mask = 0 - occupied = 4 - buckets = 8 // variable length array - -#if defined(OBJC_INSTRUMENTED) -// Cache instrumentation data, follows buckets - hitCount = 0 - hitProbes = hitCount + 4 - maxHitProbes = hitProbes + 4 - missCount = maxHitProbes + 4 - missProbes = missCount + 4 - maxMissProbes = missProbes + 4 - flushCount = maxMissProbes + 4 - flushedEntries = flushCount + 4 - -// Buckets in CacheHitHistogram and CacheMissHistogram - CACHE_HISTOGRAM_SIZE = 512 -#endif - - -////////////////////////////////////////////////////////////////////// -// -// ENTRY functionName -// -// Assembly directives to begin an exported function. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro ENTRY - .text - .globl $0 - .align 4, 0x90 -$0: -.endmacro - -.macro STATIC_ENTRY - .text - .private_extern $0 - .align 4, 0x90 -$0: -.endmacro - -////////////////////////////////////////////////////////////////////// -// -// END_ENTRY functionName -// -// Assembly directives to end an exported function. Just a placeholder, -// a close-parenthesis for ENTRY, until it is needed for something. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro END_ENTRY -.endmacro - -////////////////////////////////////////////////////////////////////// -// -// CALL_MCOUNTER -// -// Calls mcount() profiling routine. Must be called immediately on -// function entry, before any prologue executes. -// -////////////////////////////////////////////////////////////////////// - -.macro CALL_MCOUNTER -#ifdef PROFILE - // Current stack contents: ret - pushl %ebp - movl %esp,%ebp - subl $$8,%esp - // Current stack contents: ret, ebp, pad, pad - call mcount - movl %ebp,%esp - popl %ebp -#endif -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// -// CacheLookup WORD_RETURN | STRUCT_RETURN, MSG_SEND | MSG_SENDSUPER | CACHE_GET, cacheMissLabel -// -// Locate the implementation for a selector in a class method cache. -// -// Takes: WORD_RETURN (first parameter is at sp+4) -// STRUCT_RETURN (struct address is at sp+4, first parameter at sp+8) -// MSG_SEND (first parameter is receiver) -// MSG_SENDSUPER (first parameter is address of objc_super structure) -// CACHE_GET (first parameter is class; return method triplet) -// selector in %ecx -// class to search in %edx -// -// cacheMissLabel = label to branch to iff method is not cached -// -// On exit: (found) MSG_SEND and MSG_SENDSUPER: return imp in eax -// (found) CACHE_GET: return method triplet in eax -// (not found) jumps to cacheMissLabel -// -///////////////////////////////////////////////////////////////////// - - -// Values to specify to method lookup macros whether the return type of -// the method is word or structure. -WORD_RETURN = 0 -STRUCT_RETURN = 1 - -// Values to specify to method lookup macros whether the first argument -// is an object/class reference or a 'objc_super' structure. -MSG_SEND = 0 // first argument is receiver, search the isa -MSG_SENDSUPER = 1 // first argument is objc_super, search the class -CACHE_GET = 2 // first argument is class, search that class - -.macro CacheLookup - -// load variables and save caller registers. - - pushl %edi // save scratch register - movl cache(%edx), %edi // cache = class->cache - pushl %esi // save scratch register - -#if defined(OBJC_INSTRUMENTED) - pushl %ebx // save non-volatile register - pushl %eax // save cache pointer - xorl %ebx, %ebx // probeCount = 0 -#endif - movl mask(%edi), %esi // mask = cache->mask - movl %ecx, %edx // index = selector - shrl $$2, %edx // index = selector >> 2 - -// search the receiver's cache -// ecx = selector -// edi = cache -// esi = mask -// edx = index -// eax = method (soon) -LMsgSendProbeCache_$0_$1_$2: -#if defined(OBJC_INSTRUMENTED) - addl $$1, %ebx // probeCount += 1 -#endif - andl %esi, %edx // index &= mask - movl buckets(%edi, %edx, 4), %eax // meth = cache->buckets[index] - - testl %eax, %eax // check for end of bucket - je LMsgSendCacheMiss_$0_$1_$2 // go to cache miss code - cmpl method_name(%eax), %ecx // check for method name match - je LMsgSendCacheHit_$0_$1_$2 // go handle cache hit - addl $$1, %edx // bump index ... - jmp LMsgSendProbeCache_$0_$1_$2 // ... and loop - -// not found in cache: restore state and go to callers handler -LMsgSendCacheMiss_$0_$1_$2: -#if defined(OBJC_INSTRUMENTED) - popl %edx // retrieve cache pointer - movl mask(%edx), %esi // mask = cache->mask - testl %esi, %esi // a mask of zero is only for the... - je LMsgSendMissInstrumentDone_$0_$1_$2 // ... emptyCache, do not record anything - - // locate and update the CacheInstrumentation structure - addl $$1, %esi // entryCount = mask + 1 - shll $$2, %esi // tableSize = entryCount * sizeof(entry) - addl $buckets, %esi // offset = buckets + tableSize - addl %edx, %esi // cacheData = &cache->buckets[mask+1] - - movl missCount(%esi), %edi // - addl $$1, %edi // - movl %edi, missCount(%esi) // cacheData->missCount += 1 - movl missProbes(%esi), %edi // - addl %ebx, %edi // - movl %edi, missProbes(%esi) // cacheData->missProbes += probeCount - movl maxMissProbes(%esi), %edi// if (cacheData->maxMissProbes < probeCount) - cmpl %ebx, %edi // - jge LMsgSendMaxMissProbeOK_$0_$1_$2 // - movl %ebx, maxMissProbes(%esi)// cacheData->maxMissProbes = probeCount -LMsgSendMaxMissProbeOK_$0_$1_$2: - - // update cache miss probe histogram - cmpl $CACHE_HISTOGRAM_SIZE, %ebx // pin probeCount to max index - jl LMsgSendMissHistoIndexSet_$0_$1_$2 - movl $(CACHE_HISTOGRAM_SIZE-1), %ebx -LMsgSendMissHistoIndexSet_$0_$1_$2: - LEA_STATIC_DATA %esi, _CacheMissHistogram, EXTERNAL_SYMBOL - shll $$2, %ebx // convert probeCount to histogram index - addl %ebx, %esi // calculate &CacheMissHistogram[probeCount<<2] - movl 0(%esi), %edi // get current tally - addl $$1, %edi // - movl %edi, 0(%esi) // tally += 1 -LMsgSendMissInstrumentDone_$0_$1_$2: - popl %ebx // restore non-volatile register -#endif - -.if $0 == WORD_RETURN // Regular word return -.if $1 == MSG_SEND // MSG_SEND - popl %esi // restore callers register - popl %edi // restore callers register - movl self(%esp), %edx // get messaged object - movl isa(%edx), %eax // get objects class -.elseif $1 == MSG_SENDSUPER // MSG_SENDSUPER - // replace "super" arg with "receiver" - movl super+8(%esp), %edi // get super structure - movl receiver(%edi), %edx // get messaged object - movl %edx, super+8(%esp) // make it the first argument - movl class(%edi), %eax // get messaged class - popl %esi // restore callers register - popl %edi // restore callers register -.else // CACHE_GET - popl %esi // restore callers register - popl %edi // restore callers register -.endif -.else // Struct return -.if $1 == MSG_SEND // MSG_SEND (stret) - popl %esi // restore callers register - popl %edi // restore callers register - movl self_stret(%esp), %edx // get messaged object - movl isa(%edx), %eax // get objects class -.elseif $1 == MSG_SENDSUPER // MSG_SENDSUPER (stret) - // replace "super" arg with "receiver" - movl super_stret+8(%esp), %edi// get super structure - movl receiver(%edi), %edx // get messaged object - movl %edx, super_stret+8(%esp)// make it the first argument - movl class(%edi), %eax // get messaged class - popl %esi // restore callers register - popl %edi // restore callers register -.else // CACHE_GET - !! This should not happen. -.endif -.endif - - // edx = receiver - // ecx = selector - // eax = class - jmp $2 // go to callers handler - -// eax points to matching cache entry - .align 4, 0x90 -LMsgSendCacheHit_$0_$1_$2: -#if defined(OBJC_INSTRUMENTED) - popl %edx // retrieve cache pointer - movl mask(%edx), %esi // mask = cache->mask - testl %esi, %esi // a mask of zero is only for the... - je LMsgSendHitInstrumentDone_$0_$1_$2 // ... emptyCache, do not record anything - - // locate and update the CacheInstrumentation structure - addl $$1, %esi // entryCount = mask + 1 - shll $$2, %esi // tableSize = entryCount * sizeof(entry) - addl $buckets, %esi // offset = buckets + tableSize - addl %edx, %esi // cacheData = &cache->buckets[mask+1] - - movl hitCount(%esi), %edi - addl $$1, %edi - movl %edi, hitCount(%esi) // cacheData->hitCount += 1 - movl hitProbes(%esi), %edi - addl %ebx, %edi - movl %edi, hitProbes(%esi) // cacheData->hitProbes += probeCount - movl maxHitProbes(%esi), %edi// if (cacheData->maxHitProbes < probeCount) - cmpl %ebx, %edi - jge LMsgSendMaxHitProbeOK_$0_$1_$2 - movl %ebx, maxHitProbes(%esi)// cacheData->maxHitProbes = probeCount -LMsgSendMaxHitProbeOK_$0_$1_$2: - - // update cache hit probe histogram - cmpl $CACHE_HISTOGRAM_SIZE, %ebx // pin probeCount to max index - jl LMsgSendHitHistoIndexSet_$0_$1_$2 - movl $(CACHE_HISTOGRAM_SIZE-1), %ebx -LMsgSendHitHistoIndexSet_$0_$1_$2: - LEA_STATIC_DATA %esi, _CacheHitHistogram, EXTERNAL_SYMBOL - shll $$2, %ebx // convert probeCount to histogram index - addl %ebx, %esi // calculate &CacheHitHistogram[probeCount<<2] - movl 0(%esi), %edi // get current tally - addl $$1, %edi // - movl %edi, 0(%esi) // tally += 1 -LMsgSendHitInstrumentDone_$0_$1_$2: - popl %ebx // restore non-volatile register -#endif - -// load implementation address, restore state, and we're done -.if $1 == CACHE_GET - // method triplet is already in eax -.else - movl method_imp(%eax), %eax // imp = method->method_imp -.endif - -.if $0 == WORD_RETURN // Regular word return -.if $1 == MSG_SENDSUPER // MSG_SENDSUPER - // replace "super" arg with "self" - movl super+8(%esp), %edi - movl receiver(%edi), %esi - movl %esi, super+8(%esp) -.endif -.else // Struct return -.if $1 == MSG_SENDSUPER // MSG_SENDSUPER (stret) - // replace "super" arg with "self" - movl super_stret+8(%esp), %edi - movl receiver(%edi), %esi - movl %esi, super_stret+8(%esp) -.endif -.endif - - // restore caller registers - popl %esi - popl %edi -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// MethodTableLookup WORD_RETURN | STRUCT_RETURN, MSG_SEND | MSG_SENDSUPER -// -// Takes: WORD_RETURN (first parameter is at sp+4) -// STRUCT_RETURN (struct address is at sp+4, first parameter at sp+8) -// MSG_SEND (first parameter is receiver) -// MSG_SENDSUPER (first parameter is address of objc_super structure) -// -// edx = receiver -// ecx = selector -// eax = class -// (all set by CacheLookup's miss case) -// -// Stack must be at 0xXXXXXXXc on entrance. -// -// On exit: esp unchanged -// imp in eax -// -///////////////////////////////////////////////////////////////////// - -.macro MethodTableLookup - MESSENGER_END_SLOW - - // stack has return address and nothing else - subl $$(12+5*16), %esp - - movdqa %xmm3, 4*16(%esp) - movdqa %xmm2, 3*16(%esp) - movdqa %xmm1, 2*16(%esp) - movdqa %xmm0, 1*16(%esp) - - movl %eax, 8(%esp) // class - movl %ecx, 4(%esp) // selector - movl %edx, 0(%esp) // receiver - call __class_lookupMethodAndLoadCache3 - - movdqa 4*16(%esp), %xmm3 - movdqa 3*16(%esp), %xmm2 - movdqa 2*16(%esp), %xmm1 - movdqa 1*16(%esp), %xmm0 - - addl $$(12+5*16), %esp // pop parameters -.endmacro - - -/******************************************************************** - * Method _cache_getMethod(Class cls, SEL sel, IMP msgForward_internal_imp) - * - * If found, returns method triplet pointer. - * If not found, returns NULL. - * - * NOTE: _cache_getMethod never returns any cache entry whose implementation - * is _objc_msgForward_impcache. It returns 1 instead. This prevents thread- - * safety and memory management bugs in _class_lookupMethodAndLoadCache. - * See _class_lookupMethodAndLoadCache for details. - * - * _objc_msgForward_impcache is passed as a parameter because it's more - * efficient to do the (PIC) lookup once in the caller than repeatedly here. - ********************************************************************/ - - STATIC_ENTRY __cache_getMethod - -// load the class and selector - movl selector(%esp), %ecx - movl self(%esp), %edx - -// do lookup - CacheLookup WORD_RETURN, CACHE_GET, LGetMethodMiss - -// cache hit, method triplet in %eax - movl first_arg(%esp), %ecx // check for _objc_msgForward_impcache - cmpl method_imp(%eax), %ecx // if (imp==_objc_msgForward_impcache) - je 1f // return (Method)1 - ret // else return method triplet address -1: movl $1, %eax - ret - -LGetMethodMiss: -// cache miss, return nil - xorl %eax, %eax // zero %eax - ret - -LGetMethodExit: - END_ENTRY __cache_getMethod - - -/******************************************************************** - * IMP _cache_getImp(Class cls, SEL sel) - * - * If found, returns method implementation. - * If not found, returns NULL. - ********************************************************************/ - - STATIC_ENTRY __cache_getImp - -// load the class and selector - movl selector(%esp), %ecx - movl self(%esp), %edx - -// do lookup - CacheLookup WORD_RETURN, CACHE_GET, LGetImpMiss - -// cache hit, method triplet in %eax - movl method_imp(%eax), %eax // return method imp - ret - -LGetImpMiss: -// cache miss, return nil - xorl %eax, %eax // zero %eax - ret - -LGetImpExit: - END_ENTRY __cache_getImp - - -/******************************************************************** - * - * id objc_msgSend(id self, SEL _cmd,...); - * - ********************************************************************/ - - ENTRY _objc_msgSend - MESSENGER_START - CALL_MCOUNTER - -// load receiver and selector - movl selector(%esp), %ecx - movl self(%esp), %eax - -// check whether selector is ignored - cmpl $ kIgnore, %ecx - je LMsgSendDone // return self from %eax - -// check whether receiver is nil - testl %eax, %eax - je LMsgSendNilSelf - -// receiver (in %eax) is non-nil: search the cache -LMsgSendReceiverOk: - movl isa(%eax), %edx // class = self->isa - CacheLookup WORD_RETURN, MSG_SEND, LMsgSendCacheMiss - xor %edx, %edx // set nonstret for msgForward_internal - MESSENGER_END_FAST - jmp *%eax - -// cache miss: go search the method lists -LMsgSendCacheMiss: - MethodTableLookup WORD_RETURN, MSG_SEND - xor %edx, %edx // set nonstret for msgForward_internal - jmp *%eax // goto *imp - -// message sent to nil: redirect to nil receiver, if any -LMsgSendNilSelf: - // %eax is already zero - movl $0,%edx - xorps %xmm0, %xmm0 -LMsgSendDone: - MESSENGER_END_NIL - ret - -// guaranteed non-nil entry point (disabled for now) -// .globl _objc_msgSendNonNil -// _objc_msgSendNonNil: -// movl self(%esp), %eax -// jmp LMsgSendReceiverOk - -LMsgSendExit: - END_ENTRY _objc_msgSend - -/******************************************************************** - * - * id objc_msgSendSuper(struct objc_super *super, SEL _cmd,...); - * - * struct objc_super { - * id receiver; - * Class class; - * }; - ********************************************************************/ - - ENTRY _objc_msgSendSuper - MESSENGER_START - CALL_MCOUNTER - -// load selector and class to search - movl super(%esp), %eax // struct objc_super - movl selector(%esp), %ecx - movl class(%eax), %edx // struct objc_super->class - -// check whether selector is ignored - cmpl $ kIgnore, %ecx - je LMsgSendSuperIgnored // return self from %eax - -// search the cache (class in %edx) - CacheLookup WORD_RETURN, MSG_SENDSUPER, LMsgSendSuperCacheMiss - xor %edx, %edx // set nonstret for msgForward_internal - MESSENGER_END_FAST - jmp *%eax // goto *imp - -// cache miss: go search the method lists -LMsgSendSuperCacheMiss: - MethodTableLookup WORD_RETURN, MSG_SENDSUPER - xor %edx, %edx // set nonstret for msgForward_internal - jmp *%eax // goto *imp - -// ignored selector: return self -LMsgSendSuperIgnored: - movl super(%esp), %eax - movl receiver(%eax), %eax - MESSENGER_END_NIL - ret - -LMsgSendSuperExit: - END_ENTRY _objc_msgSendSuper - -/******************************************************************** - * id objc_msgSendv(id self, SEL _cmd, unsigned size, marg_list frame); - * - * On entry: - * (sp+4) is the message receiver, - * (sp+8) is the selector, - * (sp+12) is the size of the marg_list, in bytes, - * (sp+16) is the address of the marg_list - * - ********************************************************************/ - - ENTRY _objc_msgSendv - -#if defined(KERNEL) - trap // _objc_msgSendv is not for the kernel -#else - pushl %ebp - movl %esp, %ebp - // stack is currently aligned assuming no extra arguments - movl (marg_list+4)(%ebp), %edx - addl $8, %edx // skip self & selector - movl (marg_size+4)(%ebp), %ecx - subl $8, %ecx // skip self & selector - shrl $2, %ecx - je LMsgSendvArgsOK - - // %esp = %esp - (16 - ((numVariableArguments & 3) << 2)) - movl %ecx, %eax // 16-byte align stack - andl $3, %eax - shll $2, %eax - subl $16, %esp - addl %eax, %esp - -LMsgSendvArgLoop: - decl %ecx - movl 0(%edx, %ecx, 4), %eax - pushl %eax - jg LMsgSendvArgLoop - -LMsgSendvArgsOK: - movl (selector+4)(%ebp), %ecx - pushl %ecx - movl (self+4)(%ebp),%ecx - pushl %ecx - call _objc_msgSend - movl %ebp,%esp - popl %ebp - - ret -#endif - END_ENTRY _objc_msgSendv - -/******************************************************************** - * - * double objc_msgSend_fpret(id self, SEL _cmd,...); - * - ********************************************************************/ - - ENTRY _objc_msgSend_fpret - MESSENGER_START - CALL_MCOUNTER - -// load receiver and selector - movl selector(%esp), %ecx - movl self(%esp), %eax - -// check whether selector is ignored - cmpl $ kIgnore, %ecx - je LMsgSendFpretDone // return self from %eax - -// check whether receiver is nil - testl %eax, %eax - je LMsgSendFpretNilSelf - -// receiver (in %eax) is non-nil: search the cache -LMsgSendFpretReceiverOk: - movl isa(%eax), %edx // class = self->isa - CacheLookup WORD_RETURN, MSG_SEND, LMsgSendFpretCacheMiss - xor %edx, %edx // set nonstret for msgForward_internal - MESSENGER_END_FAST - jmp *%eax // goto *imp - -// cache miss: go search the method lists -LMsgSendFpretCacheMiss: - MethodTableLookup WORD_RETURN, MSG_SEND - xor %edx, %edx // set nonstret for msgForward_internal - jmp *%eax // goto *imp - -// message sent to nil: redirect to nil receiver, if any -LMsgSendFpretNilSelf: - // %eax is already zero - fldz -LMsgSendFpretDone: - MESSENGER_END_NIL - ret - -LMsgSendFpretExit: - END_ENTRY _objc_msgSend_fpret - -/******************************************************************** - * double objc_msgSendv_fpret(id self, SEL _cmd, unsigned size, marg_list frame); - * - * On entry: - * (sp+4) is the message receiver, - * (sp+8) is the selector, - * (sp+12) is the size of the marg_list, in bytes, - * (sp+16) is the address of the marg_list - * - ********************************************************************/ - - ENTRY _objc_msgSendv_fpret - -#if defined(KERNEL) - trap // _objc_msgSendv is not for the kernel -#else - pushl %ebp - movl %esp, %ebp - // stack is currently aligned assuming no extra arguments - movl (marg_list+4)(%ebp), %edx - addl $8, %edx // skip self & selector - movl (marg_size+4)(%ebp), %ecx - subl $8, %ecx // skip self & selector - shrl $2, %ecx - je LMsgSendvFpretArgsOK - - // %esp = %esp - (16 - ((numVariableArguments & 3) << 2)) - movl %ecx, %eax // 16-byte align stack - andl $3, %eax - shll $2, %eax - subl $16, %esp - addl %eax, %esp - -LMsgSendvFpretArgLoop: - decl %ecx - movl 0(%edx, %ecx, 4), %eax - pushl %eax - jg LMsgSendvFpretArgLoop - -LMsgSendvFpretArgsOK: - movl (selector+4)(%ebp), %ecx - pushl %ecx - movl (self+4)(%ebp),%ecx - pushl %ecx - call _objc_msgSend_fpret - movl %ebp,%esp - popl %ebp - - ret -#endif - END_ENTRY _objc_msgSendv_fpret - -/******************************************************************** - * - * void objc_msgSend_stret(void *st_addr , id self, SEL _cmd, ...); - * - * - * objc_msgSend_stret is the struct-return form of msgSend. - * The ABI calls for (sp+4) to be used as the address of the structure - * being returned, with the parameters in the succeeding locations. - * - * On entry: (sp+4)is the address where the structure is returned, - * (sp+8) is the message receiver, - * (sp+12) is the selector - ********************************************************************/ - - ENTRY _objc_msgSend_stret - MESSENGER_START - CALL_MCOUNTER - -// load receiver and selector - movl self_stret(%esp), %eax - movl (selector_stret)(%esp), %ecx - -// check whether receiver is nil - testl %eax, %eax - je LMsgSendStretNilSelf - -// receiver (in %eax) is non-nil: search the cache -LMsgSendStretReceiverOk: - movl isa(%eax), %edx // class = self->isa - CacheLookup STRUCT_RETURN, MSG_SEND, LMsgSendStretCacheMiss - movl $1, %edx // set stret for objc_msgForward - MESSENGER_END_FAST - jmp *%eax // goto *imp - -// cache miss: go search the method lists -LMsgSendStretCacheMiss: - MethodTableLookup STRUCT_RETURN, MSG_SEND - movl $1, %edx // set stret for objc_msgForward - jmp *%eax // goto *imp - -// message sent to nil: redirect to nil receiver, if any -LMsgSendStretNilSelf: - MESSENGER_END_NIL - ret $4 // pop struct return address (#2995932) - -// guaranteed non-nil entry point (disabled for now) -// .globl _objc_msgSendNonNil_stret -// _objc_msgSendNonNil_stret: -// CALL_MCOUNTER -// movl self_stret(%esp), %eax -// jmp LMsgSendStretReceiverOk - -LMsgSendStretExit: - END_ENTRY _objc_msgSend_stret - -/******************************************************************** - * - * void objc_msgSendSuper_stret(void *st_addr, struct objc_super *super, SEL _cmd, ...); - * - * struct objc_super { - * id receiver; - * Class class; - * }; - * - * objc_msgSendSuper_stret is the struct-return form of msgSendSuper. - * The ABI calls for (sp+4) to be used as the address of the structure - * being returned, with the parameters in the succeeding registers. - * - * On entry: (sp+4)is the address where the structure is returned, - * (sp+8) is the address of the objc_super structure, - * (sp+12) is the selector - * - ********************************************************************/ - - ENTRY _objc_msgSendSuper_stret - MESSENGER_START - CALL_MCOUNTER - -// load selector and class to search - movl super_stret(%esp), %eax // struct objc_super - movl (selector_stret)(%esp), %ecx // get selector - movl class(%eax), %edx // struct objc_super->class - -// search the cache (class in %edx) - CacheLookup STRUCT_RETURN, MSG_SENDSUPER, LMsgSendSuperStretCacheMiss - movl $1, %edx // set stret for objc_msgForward - MESSENGER_END_FAST - jmp *%eax // goto *imp - -// cache miss: go search the method lists -LMsgSendSuperStretCacheMiss: - MethodTableLookup STRUCT_RETURN, MSG_SENDSUPER - movl $1, %edx // set stret for objc_msgForward - jmp *%eax // goto *imp - -LMsgSendSuperStretExit: - END_ENTRY _objc_msgSendSuper_stret - - -/******************************************************************** - * void objc_msgSendv_stret(void *st_addr, id self, SEL _cmd, unsigned size, marg_list frame); - * - * objc_msgSendv_stret is the struct-return form of msgSendv. - * This function does not use the struct-return ABI; instead, the - * structure return address is passed as a normal parameter. - * - * On entry: (sp+4) is the address in which the returned struct is put, - * (sp+8) is the message receiver, - * (sp+12) is the selector, - * (sp+16) is the size of the marg_list, in bytes, - * (sp+20) is the address of the marg_list - * - ********************************************************************/ - - ENTRY _objc_msgSendv_stret - -#if defined(KERNEL) - trap // _objc_msgSendv_stret is not for the kernel -#else - pushl %ebp - movl %esp, %ebp - subl $12, %esp // align stack assuming no extra arguments - movl (marg_list_stret+4)(%ebp), %edx - addl $8, %edx // skip self & selector - movl (marg_size_stret+4)(%ebp), %ecx - subl $5, %ecx // skip self & selector - shrl $2, %ecx - jle LMsgSendvStretArgsOK - - // %esp = %esp - (16 - ((numVariableArguments & 3) << 2)) - movl %ecx, %eax // 16-byte align stack - andl $3, %eax - shll $2, %eax - subl $16, %esp - addl %eax, %esp - -LMsgSendvStretArgLoop: - decl %ecx - movl 0(%edx, %ecx, 4), %eax - pushl %eax - jg LMsgSendvStretArgLoop - -LMsgSendvStretArgsOK: - movl (selector_stret+4)(%ebp), %ecx - pushl %ecx - movl (self_stret+4)(%ebp),%ecx - pushl %ecx - movl (struct_addr+4)(%ebp),%ecx - pushl %ecx - call _objc_msgSend_stret - movl %ebp,%esp - popl %ebp - - ret -#endif - END_ENTRY _objc_msgSendv_stret - - -/******************************************************************** - * - * id _objc_msgForward(id self, SEL _cmd,...); - * - ********************************************************************/ - -// _FwdSel is @selector(forward::), set up in map_images(). -// ALWAYS dereference _FwdSel to get to "forward::" !! - .data - .align 2 - .private_extern _FwdSel -_FwdSel: .long 0 - - .cstring - .align 2 -LUnkSelStr: .ascii "Does not recognize selector %s (while forwarding %s)\0" - - .non_lazy_symbol_pointer -L_forward_handler: - .indirect_symbol __objc_forward_handler - .long 0 -L_forward_stret_handler: - .indirect_symbol __objc_forward_stret_handler - .long 0 - - STATIC_ENTRY __objc_msgForward_impcache - // Method cache version - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band register %edx is nonzero for stret, zero otherwise - - MESSENGER_START - nop - MESSENGER_END_SLOW - - // Check return type (stret or not) - testl %edx, %edx - jnz __objc_msgForward_stret - jmp __objc_msgForward - - END_ENTRY _objc_msgForward_impcache - - - ENTRY __objc_msgForward - // Non-struct return version - - // Get PIC base into %edx - call L__objc_msgForward$pic_base -L__objc_msgForward$pic_base: - popl %edx - - // Call user handler, if any - movl L_forward_handler-L__objc_msgForward$pic_base(%edx),%ecx - movl (%ecx), %ecx - testl %ecx, %ecx // if not NULL - je 1f // skip to default handler - jmp *%ecx // call __objc_forward_handler -1: - // No user handler - // Push stack frame - pushl %ebp - movl %esp, %ebp - - // Die if forwarding "forward::" - movl (selector+4)(%ebp), %eax - movl _FwdSel-L__objc_msgForward$pic_base(%edx),%ecx - cmpl %ecx, %eax - je LMsgForwardError - - // Call [receiver forward:sel :margs] - subl $8, %esp // 16-byte align the stack - leal (self+4)(%ebp), %ecx - pushl %ecx // &margs - pushl %eax // sel - movl _FwdSel-L__objc_msgForward$pic_base(%edx),%ecx - pushl %ecx // forward:: - pushl (self+4)(%ebp) // receiver - - call _objc_msgSend - - movl %ebp, %esp - popl %ebp - ret - -LMsgForwardError: - // Call __objc_error(receiver, "unknown selector %s %s", "forward::", forwardedSel) - subl $8, %esp // 16-byte align the stack - pushl (selector+4+4)(%ebp) // the forwarded selector - movl _FwdSel-L__objc_msgForward$pic_base(%edx),%eax - pushl %eax - leal LUnkSelStr-L__objc_msgForward$pic_base(%edx),%eax - pushl %eax - pushl (self+4)(%ebp) - call ___objc_error // never returns - - END_ENTRY __objc_msgForward - - - ENTRY __objc_msgForward_stret - // Struct return version - - // Get PIC base into %edx - call L__objc_msgForwardStret$pic_base -L__objc_msgForwardStret$pic_base: - popl %edx - - // Call user handler, if any - movl L_forward_stret_handler-L__objc_msgForwardStret$pic_base(%edx), %ecx - movl (%ecx), %ecx - testl %ecx, %ecx // if not NULL - je 1f // skip to default handler - jmp *%ecx // call __objc_forward_stret_handler -1: - // No user handler - // Push stack frame - pushl %ebp - movl %esp, %ebp - - // Die if forwarding "forward::" - movl (selector_stret+4)(%ebp), %eax - movl _FwdSel-L__objc_msgForwardStret$pic_base(%edx), %ecx - cmpl %ecx, %eax - je LMsgForwardStretError - - // Call [receiver forward:sel :margs] - subl $8, %esp // 16-byte align the stack - leal (self_stret+4)(%ebp), %ecx - pushl %ecx // &margs - pushl %eax // sel - movl _FwdSel-L__objc_msgForwardStret$pic_base(%edx),%ecx - pushl %ecx // forward:: - pushl (self_stret+4)(%ebp) // receiver - - call _objc_msgSend - - movl %ebp, %esp - popl %ebp - ret $4 // pop struct return address (#2995932) - -LMsgForwardStretError: - // Call __objc_error(receiver, "unknown selector %s %s", "forward::", forwardedSelector) - subl $8, %esp // 16-byte align the stack - pushl (selector_stret+4+4)(%ebp) // the forwarded selector - leal _FwdSel-L__objc_msgForwardStret$pic_base(%edx),%eax - pushl %eax - leal LUnkSelStr-L__objc_msgForwardStret$pic_base(%edx),%eax - pushl %eax - pushl (self_stret+4)(%ebp) - call ___objc_error // never returns - - END_ENTRY __objc_msgForward_stret - - - ENTRY _method_invoke - - movl selector(%esp), %ecx - movl method_name(%ecx), %edx - movl method_imp(%ecx), %eax - movl %edx, selector(%esp) - jmp *%eax - - END_ENTRY _method_invoke - - - ENTRY _method_invoke_stret - - movl selector_stret(%esp), %ecx - movl method_name(%ecx), %edx - movl method_imp(%ecx), %eax - movl %edx, selector_stret(%esp) - jmp *%eax - - END_ENTRY _method_invoke_stret - - - STATIC_ENTRY __objc_ignored_method - - movl self(%esp), %eax - ret - - END_ENTRY __objc_ignored_method - - -.section __DATA,__objc_msg_break -.long 0 -.long 0 - -#endif diff --git a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-simulator-i386.s b/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-simulator-i386.s deleted file mode 100644 index 12cc010..0000000 --- a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-simulator-i386.s +++ /dev/null @@ -1,856 +0,0 @@ -/* - * Copyright (c) 1999-2009 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 <TargetConditionals.h> -#if defined(__i386__) && TARGET_IPHONE_SIMULATOR - -#include "objc-config.h" - -.data - -// _objc_entryPoints and _objc_exitPoints are used by objc -// to get the critical regions for which method caches -// cannot be garbage collected. - -.align 2 -.private_extern _objc_entryPoints -_objc_entryPoints: - .long _cache_getImp - .long _objc_msgSend - .long _objc_msgSend_fpret - .long _objc_msgSend_stret - .long _objc_msgSendSuper - .long _objc_msgSendSuper2 - .long _objc_msgSendSuper_stret - .long _objc_msgSendSuper2_stret - .long 0 - -.private_extern _objc_exitPoints -_objc_exitPoints: - .long LGetImpExit - .long LMsgSendExit - .long LMsgSendFpretExit - .long LMsgSendStretExit - .long LMsgSendSuperExit - .long LMsgSendSuper2Exit - .long LMsgSendSuperStretExit - .long LMsgSendSuper2StretExit - .long 0 - - -/******************************************************************** -* List every exit insn from every messenger for debugger use. -* Format: -* ( -* 1 word instruction's address -* 1 word type (ENTER or FAST_EXIT or SLOW_EXIT or NIL_EXIT) -* ) -* 1 word zero -* -* ENTER is the start of a dispatcher -* FAST_EXIT is method dispatch -* SLOW_EXIT is uncached method lookup -* NIL_EXIT is returning zero from a message sent to nil -* These must match objc-gdb.h. -********************************************************************/ - -#define ENTER 1 -#define FAST_EXIT 2 -#define SLOW_EXIT 3 -#define NIL_EXIT 4 - -.section __DATA,__objc_msg_break -.globl _gdb_objc_messenger_breakpoints -_gdb_objc_messenger_breakpoints: -// contents populated by the macros below - -.macro MESSENGER_START -4: - .section __DATA,__objc_msg_break - .long 4b - .long ENTER - .text -.endmacro -.macro MESSENGER_END_FAST -4: - .section __DATA,__objc_msg_break - .long 4b - .long FAST_EXIT - .text -.endmacro -.macro MESSENGER_END_SLOW -4: - .section __DATA,__objc_msg_break - .long 4b - .long SLOW_EXIT - .text -.endmacro -.macro MESSENGER_END_NIL -4: - .section __DATA,__objc_msg_break - .long 4b - .long NIL_EXIT - .text -.endmacro - - -/******************************************************************** - * Names for relative labels - * DO NOT USE THESE LABELS ELSEWHERE - * Reserved labels: 5: 6: 7: 8: 9: - ********************************************************************/ -#define LCacheMiss 5 -#define LCacheMiss_f 5f -#define LCacheMiss_b 5b -#define LNilTestDone 6 -#define LNilTestDone_f 6f -#define LNilTestDone_b 6b -#define LNilTestSlow 7 -#define LNilTestSlow_f 7f -#define LNilTestSlow_b 7b -#define LGetIsaDone 8 -#define LGetIsaDone_f 8f -#define LGetIsaDone_b 8b -#define LGetIsaSlow 9 -#define LGetIsaSlow_f 9f -#define LGetIsaSlow_b 9b - -/******************************************************************** - * Macro parameters - ********************************************************************/ - -#define NORMAL 0 -#define FPRET 1 -#define GETIMP 3 -#define STRET 4 -#define SUPER 5 -#define SUPER_STRET 6 - - -/******************************************************************** - * - * Structure definitions. - * - ********************************************************************/ - -// Offsets from %esp -#define self 4 -#define super 4 -#define selector 8 -#define marg_size 12 -#define marg_list 16 -#define first_arg 12 - -#define struct_addr 4 - -#define self_stret 8 -#define super_stret 8 -#define selector_stret 12 -#define marg_size_stret 16 -#define marg_list_stret 20 - -// objc_super parameter to sendSuper -#define receiver 0 -#define class 4 - -// Selected field offsets in class structure -#define isa 0 -#define superclass 4 - -// Method descriptor -#define method_name 0 -#define method_imp 8 - - -////////////////////////////////////////////////////////////////////// -// -// ENTRY functionName -// -// Assembly directives to begin an exported function. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro ENTRY - .text - .globl $0 - .align 2, 0x90 -$0: - .cfi_startproc -.endmacro - -.macro STATIC_ENTRY - .text - .private_extern $0 - .align 4, 0x90 -$0: - .cfi_startproc -.endmacro - -////////////////////////////////////////////////////////////////////// -// -// END_ENTRY functionName -// -// Assembly directives to end an exported function. Just a placeholder, -// a close-parenthesis for ENTRY, until it is needed for something. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro END_ENTRY - .cfi_endproc -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// CacheLookup return-type -// -// Locate the implementation for a selector in a class method cache. -// -// Takes: -// $0 = NORMAL, FPRET, STRET, SUPER, SUPER_STRET, GETIMP -// ecx = selector to search for -// edx = class to search -// -// On exit: ecx clobbered -// (found) calls or returns IMP in eax, eq/ne set for forwarding -// (not found) jumps to LCacheMiss, class still in edx -// -///////////////////////////////////////////////////////////////////// - -.macro CacheHit - - // CacheHit must always be preceded by a not-taken `jne` instruction - // in case the imp is _objc_msgForward_impcache. - -.if $0 == GETIMP - movl 4(%eax), %eax // return imp - call 4f -4: pop %edx - leal __objc_msgSend_uncached_impcache-4b(%edx), %edx - cmpl %edx, %eax - jne 4f - xor %eax, %eax // don't return msgSend_uncached -4: ret -.elseif $0 == NORMAL || $0 == FPRET - // eq already set for forwarding by `jne` - MESSENGER_END_FAST - jmp *4(%eax) // call imp -.elseif $0 == STRET - test %eax, %eax // set ne for stret forwarding - MESSENGER_END_FAST - jmp *4(%eax) // call imp -.elseif $0 == SUPER - // replace "super" arg with "receiver" - movl super(%esp), %ecx // get super structure - movl receiver(%ecx), %ecx // get messaged object - movl %ecx, super(%esp) // make it the first argument - cmp %eax, %eax // set eq for non-stret forwarding - MESSENGER_END_FAST - jmp *4(%eax) // call imp -.elseif $0 == SUPER_STRET - // replace "super" arg with "receiver" - movl super_stret(%esp), %ecx // get super structure - movl receiver(%ecx), %ecx // get messaged object - movl %ecx, super_stret(%esp) // make it the first argument - test %eax, %eax // set ne for stret forwarding - MESSENGER_END_FAST - jmp *4(%eax) // call imp -.else -.abort oops -.endif - -.endmacro - - -.macro CacheLookup - - movzwl 12(%edx), %eax // eax = mask - andl %ecx, %eax // eax = SEL & mask - shll $$3, %eax // eax = offset = (SEL & mask) * 8 - addl 8(%edx), %eax // eax = bucket = cache->buckets+offset - cmpl (%eax), %ecx // if (bucket->sel != SEL) - jne 1f // scan more - // The `jne` above sets flags for CacheHit - CacheHit $0 // call or return imp - -1: - // loop - cmpl $$1, (%eax) - jbe 3f // if (bucket->sel <= 1) wrap or miss - - addl $$8, %eax // bucket++ -2: - cmpl (%eax), %ecx // if (bucket->sel != sel) - jne 1b // scan more - // The `jne` above sets flags for CacheHit - CacheHit $0 // call or return imp - -3: - // wrap or miss - jb LCacheMiss_f // if (bucket->sel < 1) cache miss - // wrap - movl 4(%eax), %eax // bucket->imp is really first bucket - jmp 2f - - // Clone scanning loop to miss instead of hang when cache is corrupt. - // The slow path may detect any corruption and halt later. - -1: - // loop - cmpq $$1, (%eax) - jbe 3f // if (bucket->sel <= 1) wrap or miss - - addl $$8, %eax // bucket++ -2: - cmpl (%eax), %ecx // if (bucket->sel != sel) - jne 1b // scan more - // The `jne` above sets flags for CacheHit - CacheHit $0 // call or return imp - -3: - // double wrap or miss - jmp LCacheMiss_f - -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// MethodTableLookup -// -// Takes: -// $0 = NORMAL, FPRET, STRET, SUPER, SUPER_STRET -// eax = receiver -// ecx = selector -// edx = class to search -// -// On exit: calls IMP, eq/ne set for forwarding -// -///////////////////////////////////////////////////////////////////// - -.macro MethodTableLookup - MESSENGER_END_SLOW - pushl %ebp - .cfi_def_cfa_offset 8 - .cfi_offset ebp, -8 - - movl %esp, %ebp - .cfi_def_cfa_register ebp - - subl $$(8+5*16), %esp - - movdqa %xmm3, 4*16(%esp) - movdqa %xmm2, 3*16(%esp) - movdqa %xmm1, 2*16(%esp) - movdqa %xmm0, 1*16(%esp) - - movl %edx, 8(%esp) // class - movl %ecx, 4(%esp) // selector - movl %eax, 0(%esp) // receiver - call __class_lookupMethodAndLoadCache3 - - // imp in eax - - movdqa 4*16(%esp), %xmm3 - movdqa 3*16(%esp), %xmm2 - movdqa 2*16(%esp), %xmm1 - movdqa 1*16(%esp), %xmm0 - - leave - .cfi_def_cfa esp, 4 - .cfi_same_value ebp - -.if $0 == SUPER - // replace "super" arg with "receiver" - movl super(%esp), %ecx // get super structure - movl receiver(%ecx), %ecx // get messaged object - movl %ecx, super(%esp) // make it the first argument -.elseif $0 == SUPER_STRET - // replace "super" arg with "receiver" - movl super_stret(%esp), %ecx // get super structure - movl receiver(%ecx), %ecx // get messaged object - movl %ecx, super_stret(%esp) // make it the first argument -.endif - -.if $0 == STRET || $0 == SUPER_STRET - // set ne (stret) for forwarding; eax != 0 - test %eax, %eax - jmp *%eax // call imp -.else - // set eq (non-stret) for forwarding - cmp %eax, %eax - jmp *%eax // call imp -.endif - -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// NilTest return-type -// -// Takes: $0 = NORMAL or FPRET or STRET -// eax = receiver -// -// On exit: Loads non-nil receiver in eax and self(esp) or self_stret(esp), -// or returns zero. -// -// NilTestSupport return-type -// -// Takes: $0 = NORMAL or FPRET or STRET -// eax = receiver -// -// On exit: Loads non-nil receiver in eax and self(esp) or self_stret(esp), -// or returns zero. -// -///////////////////////////////////////////////////////////////////// - -.macro NilTest - testl %eax, %eax - jz LNilTestSlow_f -LNilTestDone: -.endmacro - -.macro NilTestSupport - .align 3 -LNilTestSlow: - -.if $0 == FPRET - fldz - MESSENGER_END_NIL - ret -.elseif $0 == STRET - MESSENGER_END_NIL - ret $$4 -.elseif $0 == NORMAL - // eax is already zero - xorl %edx, %edx - xorps %xmm0, %xmm0 - xorps %xmm1, %xmm1 - MESSENGER_END_NIL - ret -.endif -.endmacro - - -/******************************************************************** - * IMP _cache_getImp(Class cls, SEL sel) - * - * If found, returns method implementation. - * If not found, returns NULL. - ********************************************************************/ - - STATIC_ENTRY _cache_getImp - -// load the class and selector - movl selector(%esp), %ecx - movl self(%esp), %edx - - CacheLookup GETIMP // returns IMP on success - -LCacheMiss: -// cache miss, return nil - xorl %eax, %eax - ret - -LGetImpExit: - END_ENTRY _cache_getImp - - -/******************************************************************** - * - * id objc_msgSend(id self, SEL _cmd,...); - * - ********************************************************************/ - - ENTRY _objc_msgSend - MESSENGER_START - - movl selector(%esp), %ecx - movl self(%esp), %eax - - NilTest NORMAL - - movl isa(%eax), %edx // class = self->isa - CacheLookup NORMAL // calls IMP on success - - NilTestSupport NORMAL - -LCacheMiss: - // isa still in edx - movl selector(%esp), %ecx - movl self(%esp), %eax - MethodTableLookup NORMAL // calls IMP - -LMsgSendExit: - END_ENTRY _objc_msgSend - - -/******************************************************************** - * - * id objc_msgSendSuper(struct objc_super *super, SEL _cmd,...); - * - * struct objc_super { - * id receiver; - * Class class; - * }; - ********************************************************************/ - - ENTRY _objc_msgSendSuper - MESSENGER_START - - movl selector(%esp), %ecx - movl super(%esp), %eax // struct objc_super - movl class(%eax), %edx // struct objc_super->class - CacheLookup SUPER // calls IMP on success - -LCacheMiss: - // class still in edx - movl selector(%esp), %ecx - movl super(%esp), %eax - movl receiver(%eax), %eax - MethodTableLookup SUPER // calls IMP - -LMsgSendSuperExit: - END_ENTRY _objc_msgSendSuper - - - ENTRY _objc_msgSendSuper2 - MESSENGER_START - - movl selector(%esp), %ecx - movl super(%esp), %eax // struct objc_super - movl class(%eax), %eax // struct objc_super->class - mov superclass(%eax), %edx // edx = objc_super->class->super_class - CacheLookup SUPER // calls IMP on success - -LCacheMiss: - // class still in edx - movl selector(%esp), %ecx - movl super(%esp), %eax - movl receiver(%eax), %eax - MethodTableLookup SUPER // calls IMP - -LMsgSendSuper2Exit: - END_ENTRY _objc_msgSendSuper2 - - -/******************************************************************** - * - * double objc_msgSend_fpret(id self, SEL _cmd,...); - * - ********************************************************************/ - - ENTRY _objc_msgSend_fpret - MESSENGER_START - - movl selector(%esp), %ecx - movl self(%esp), %eax - - NilTest FPRET - - movl isa(%eax), %edx // class = self->isa - CacheLookup FPRET // calls IMP on success - - NilTestSupport FPRET - -LCacheMiss: - // class still in edx - movl selector(%esp), %ecx - movl self(%esp), %eax - MethodTableLookup FPRET // calls IMP - -LMsgSendFpretExit: - END_ENTRY _objc_msgSend_fpret - - -/******************************************************************** - * - * void objc_msgSend_stret(void *st_addr , id self, SEL _cmd, ...); - * - * - * objc_msgSend_stret is the struct-return form of msgSend. - * The ABI calls for (sp+4) to be used as the address of the structure - * being returned, with the parameters in the succeeding locations. - * - * On entry: (sp+4)is the address where the structure is returned, - * (sp+8) is the message receiver, - * (sp+12) is the selector - ********************************************************************/ - - ENTRY _objc_msgSend_stret - MESSENGER_START - - movl selector_stret(%esp), %ecx - movl self_stret(%esp), %eax - - NilTest STRET - - movl isa(%eax), %edx // class = self->isa - CacheLookup STRET // calls IMP on success - - NilTestSupport STRET - -LCacheMiss: - // class still in edx - movl selector_stret(%esp), %ecx - movl self_stret(%esp), %eax - MethodTableLookup STRET // calls IMP - -LMsgSendStretExit: - END_ENTRY _objc_msgSend_stret - - -/******************************************************************** - * - * void objc_msgSendSuper_stret(void *st_addr, struct objc_super *super, SEL _cmd, ...); - * - * struct objc_super { - * id receiver; - * Class class; - * }; - * - * objc_msgSendSuper_stret is the struct-return form of msgSendSuper. - * The ABI calls for (sp+4) to be used as the address of the structure - * being returned, with the parameters in the succeeding registers. - * - * On entry: (sp+4)is the address where the structure is returned, - * (sp+8) is the address of the objc_super structure, - * (sp+12) is the selector - * - ********************************************************************/ - - ENTRY _objc_msgSendSuper_stret - MESSENGER_START - - movl selector_stret(%esp), %ecx - movl super_stret(%esp), %eax // struct objc_super - movl class(%eax), %edx // struct objc_super->class - CacheLookup SUPER_STRET // calls IMP on success - -LCacheMiss: - // class still in edx - movl selector_stret(%esp), %ecx - movl super_stret(%esp), %eax - movl receiver(%eax), %eax - MethodTableLookup SUPER_STRET // calls IMP - -LMsgSendSuperStretExit: - END_ENTRY _objc_msgSendSuper_stret - - - ENTRY _objc_msgSendSuper2_stret - MESSENGER_START - - movl selector_stret(%esp), %ecx - movl super_stret(%esp), %eax // struct objc_super - movl class(%eax), %eax // struct objc_super->class - mov superclass(%eax), %edx // edx = objc_super->class->super_class - CacheLookup SUPER_STRET // calls IMP on success - -// cache miss: go search the method lists -LCacheMiss: - // class still in edx - movl selector_stret(%esp), %ecx - movl super_stret(%esp), %eax - movl receiver(%eax), %eax - MethodTableLookup SUPER_STRET // calls IMP - -LMsgSendSuper2StretExit: - END_ENTRY _objc_msgSendSuper2_stret - - -/******************************************************************** - * - * _objc_msgSend_uncached_impcache - * _objc_msgSend_uncached - * _objc_msgSend_stret_uncached - * - * Used to erase method cache entries in-place by - * bouncing them to the uncached lookup. - * - ********************************************************************/ - - STATIC_ENTRY __objc_msgSend_uncached_impcache - // Method cache version - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band condition register is NE for stret, EQ otherwise. - // Out-of-band edx is the searched class - - MESSENGER_START - nop - MESSENGER_END_SLOW - - jne __objc_msgSend_stret_uncached - jmp __objc_msgSend_uncached - - END_ENTRY __objc_msgSend_uncached_impcache - - - STATIC_ENTRY __objc_msgSend_uncached - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band edx is the searched class - - // edx is already the class to search - movl selector(%esp), %ecx - MethodTableLookup NORMAL // calls IMP - - END_ENTRY __objc_msgSend_uncached - - - STATIC_ENTRY __objc_msgSend_stret_uncached - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band edx is the searched class - - // edx is already the class to search - movl selector_stret(%esp), %ecx - MethodTableLookup STRET // calls IMP - - END_ENTRY __objc_msgSend_stret_uncached - - - -/******************************************************************** -* -* id _objc_msgForward(id self, SEL _cmd,...); -* -* _objc_msgForward and _objc_msgForward_stret are the externally-callable -* functions returned by things like method_getImplementation(). -* _objc_msgForward_impcache is the function pointer actually stored in -* method caches. -* -********************************************************************/ - - .non_lazy_symbol_pointer -L_forward_handler: - .indirect_symbol __objc_forward_handler - .long 0 -L_forward_stret_handler: - .indirect_symbol __objc_forward_stret_handler - .long 0 - - STATIC_ENTRY __objc_msgForward_impcache - // Method cache version - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band condition register is NE for stret, EQ otherwise. - - MESSENGER_START - nop - MESSENGER_END_SLOW - - jne __objc_msgForward_stret - jmp __objc_msgForward - - END_ENTRY _objc_msgForward_impcache - - - ENTRY __objc_msgForward - // Non-struct return version - - call 1f -1: popl %edx - movl L_forward_handler-1b(%edx), %edx - jmp *(%edx) - - END_ENTRY __objc_msgForward - - - ENTRY __objc_msgForward_stret - // Struct return version - - call 1f -1: popl %edx - movl L_forward_stret_handler-1b(%edx), %edx - jmp *(%edx) - - END_ENTRY __objc_msgForward_stret - - - ENTRY _objc_msgSend_debug - jmp _objc_msgSend - END_ENTRY _objc_msgSend_debug - - ENTRY _objc_msgSendSuper2_debug - jmp _objc_msgSendSuper2 - END_ENTRY _objc_msgSendSuper2_debug - - ENTRY _objc_msgSend_stret_debug - jmp _objc_msgSend_stret - END_ENTRY _objc_msgSend_stret_debug - - ENTRY _objc_msgSendSuper2_stret_debug - jmp _objc_msgSendSuper2_stret - END_ENTRY _objc_msgSendSuper2_stret_debug - - ENTRY _objc_msgSend_fpret_debug - jmp _objc_msgSend_fpret - END_ENTRY _objc_msgSend_fpret_debug - - - ENTRY _objc_msgSend_noarg - jmp _objc_msgSend - END_ENTRY _objc_msgSend_noarg - - - ENTRY _method_invoke - - movl selector(%esp), %ecx - movl method_name(%ecx), %edx - movl method_imp(%ecx), %eax - movl %edx, selector(%esp) - jmp *%eax - - END_ENTRY _method_invoke - - - ENTRY _method_invoke_stret - - movl selector_stret(%esp), %ecx - movl method_name(%ecx), %edx - movl method_imp(%ecx), %eax - movl %edx, selector_stret(%esp) - jmp *%eax - - END_ENTRY _method_invoke_stret - -#if DEBUG - STATIC_ENTRY __objc_ignored_method - - movl self(%esp), %eax - ret - - END_ENTRY __objc_ignored_method -#endif - - -.section __DATA,__objc_msg_break -.long 0 -.long 0 - -#endif diff --git a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-simulator-x86_64.s b/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-simulator-x86_64.s deleted file mode 100644 index 6237c27..0000000 --- a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-simulator-x86_64.s +++ /dev/null @@ -1,1067 +0,0 @@ -/* - * 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@ - */ - -#include <TargetConditionals.h> -#if __x86_64__ && TARGET_IPHONE_SIMULATOR - -/******************************************************************** - ******************************************************************** - ** - ** objc-msg-x86_64.s - x86-64 code to support objc messaging. - ** - ******************************************************************** - ********************************************************************/ - -.data - -// _objc_entryPoints and _objc_exitPoints are used by objc -// to get the critical regions for which method caches -// cannot be garbage collected. - -.align 4 -.private_extern _objc_entryPoints -_objc_entryPoints: - .quad _cache_getImp - .quad _objc_msgSend - .quad _objc_msgSend_fpret - .quad _objc_msgSend_fp2ret - .quad _objc_msgSend_stret - .quad _objc_msgSendSuper - .quad _objc_msgSendSuper_stret - .quad _objc_msgSendSuper2 - .quad _objc_msgSendSuper2_stret - .quad 0 - -.private_extern _objc_exitPoints -_objc_exitPoints: - .quad LExit_cache_getImp - .quad LExit_objc_msgSend - .quad LExit_objc_msgSend_fpret - .quad LExit_objc_msgSend_fp2ret - .quad LExit_objc_msgSend_stret - .quad LExit_objc_msgSendSuper - .quad LExit_objc_msgSendSuper_stret - .quad LExit_objc_msgSendSuper2 - .quad LExit_objc_msgSendSuper2_stret - .quad 0 - - -/******************************************************************** -* List every exit insn from every messenger for debugger use. -* Format: -* ( -* 1 word instruction's address -* 1 word type (ENTER or FAST_EXIT or SLOW_EXIT or NIL_EXIT) -* ) -* 1 word zero -* -* ENTER is the start of a dispatcher -* FAST_EXIT is method dispatch -* SLOW_EXIT is uncached method lookup -* NIL_EXIT is returning zero from a message sent to nil -* These must match objc-gdb.h. -********************************************************************/ - -#define ENTER 1 -#define FAST_EXIT 2 -#define SLOW_EXIT 3 -#define NIL_EXIT 4 - -.section __DATA,__objc_msg_break -.globl _gdb_objc_messenger_breakpoints -_gdb_objc_messenger_breakpoints: -// contents populated by the macros below - -.macro MESSENGER_START -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad ENTER - .text -.endmacro -.macro MESSENGER_END_FAST -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad FAST_EXIT - .text -.endmacro -.macro MESSENGER_END_SLOW -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad SLOW_EXIT - .text -.endmacro -.macro MESSENGER_END_NIL -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad NIL_EXIT - .text -.endmacro - - -/******************************************************************** - * Recommended multi-byte NOP instructions - * (Intel 64 and IA-32 Architectures Software Developer's Manual Volume 2B) - ********************************************************************/ -#define nop1 .byte 0x90 -#define nop2 .byte 0x66,0x90 -#define nop3 .byte 0x0F,0x1F,0x00 -#define nop4 .byte 0x0F,0x1F,0x40,0x00 -#define nop5 .byte 0x0F,0x1F,0x44,0x00,0x00 -#define nop6 .byte 0x66,0x0F,0x1F,0x44,0x00,0x00 -#define nop7 .byte 0x0F,0x1F,0x80,0x00,0x00,0x00,0x00 -#define nop8 .byte 0x0F,0x1F,0x84,0x00,0x00,0x00,0x00,0x00 -#define nop9 .byte 0x66,0x0F,0x1F,0x84,0x00,0x00,0x00,0x00,0x00 - - -/******************************************************************** - * Names for parameter registers. - ********************************************************************/ - -#define a1 rdi -#define a1d edi -#define a1b dil -#define a2 rsi -#define a2d esi -#define a2b sil -#define a3 rdx -#define a3d edx -#define a4 rcx -#define a4d ecx -#define a5 r8 -#define a5d r8d -#define a6 r9 -#define a6d r9d - - -/******************************************************************** - * Names for relative labels - * DO NOT USE THESE LABELS ELSEWHERE - * Reserved labels: 6: 7: 8: 9: - ********************************************************************/ -#define LCacheMiss 6 -#define LCacheMiss_f 6f -#define LCacheMiss_b 6b -#define LGetIsaDone 7 -#define LGetIsaDone_f 7f -#define LGetIsaDone_b 7b -#define LNilOrTagged 8 -#define LNilOrTagged_f 8f -#define LNilOrTagged_b 8b -#define LNil 9 -#define LNil_f 9f -#define LNil_b 9b - -/******************************************************************** - * Macro parameters - ********************************************************************/ - -#define NORMAL 0 -#define FPRET 1 -#define FP2RET 2 -#define GETIMP 3 -#define STRET 4 -#define SUPER 5 -#define SUPER_STRET 6 -#define SUPER2 7 -#define SUPER2_STRET 8 - - -/******************************************************************** - * - * Structure definitions. - * - ********************************************************************/ - -// objc_super parameter to sendSuper -#define receiver 0 -#define class 8 - -// Selected field offsets in class structure -// #define isa 0 USE GetIsa INSTEAD - -// Method descriptor -#define method_name 0 -#define method_imp 16 - - -////////////////////////////////////////////////////////////////////// -// -// ENTRY functionName -// -// Assembly directives to begin an exported function. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro ENTRY - .text - .globl $0 - .align 6, 0x90 -$0: - .cfi_startproc -.endmacro - -.macro STATIC_ENTRY - .text - .private_extern $0 - .align 2, 0x90 -$0: - .cfi_startproc -.endmacro - -////////////////////////////////////////////////////////////////////// -// -// END_ENTRY functionName -// -// Assembly directives to end an exported function. Just a placeholder, -// a close-parenthesis for ENTRY, until it is needed for something. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro END_ENTRY - .cfi_endproc -LExit$0: -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// SaveRegisters -// -// Pushes a stack frame and saves all registers that might contain -// parameter values. -// -// On entry: -// stack = ret -// -// On exit: -// %rsp is 16-byte aligned -// -///////////////////////////////////////////////////////////////////// - -.macro SaveRegisters - - push %rbp - .cfi_def_cfa_offset 16 - .cfi_offset rbp, -16 - - mov %rsp, %rbp - .cfi_def_cfa_register rbp - - sub $$0x80+8, %rsp // +8 for alignment - - movdqa %xmm0, -0x80(%rbp) - push %rax // might be xmm parameter count - movdqa %xmm1, -0x70(%rbp) - push %a1 - movdqa %xmm2, -0x60(%rbp) - push %a2 - movdqa %xmm3, -0x50(%rbp) - push %a3 - movdqa %xmm4, -0x40(%rbp) - push %a4 - movdqa %xmm5, -0x30(%rbp) - push %a5 - movdqa %xmm6, -0x20(%rbp) - push %a6 - movdqa %xmm7, -0x10(%rbp) - -.endmacro - -///////////////////////////////////////////////////////////////////// -// -// RestoreRegisters -// -// Pops a stack frame pushed by SaveRegisters -// -// On entry: -// %rbp unchanged since SaveRegisters -// -// On exit: -// stack = ret -// -///////////////////////////////////////////////////////////////////// - -.macro RestoreRegisters - - movdqa -0x80(%rbp), %xmm0 - pop %a6 - movdqa -0x70(%rbp), %xmm1 - pop %a5 - movdqa -0x60(%rbp), %xmm2 - pop %a4 - movdqa -0x50(%rbp), %xmm3 - pop %a3 - movdqa -0x40(%rbp), %xmm4 - pop %a2 - movdqa -0x30(%rbp), %xmm5 - pop %a1 - movdqa -0x20(%rbp), %xmm6 - pop %rax - movdqa -0x10(%rbp), %xmm7 - - leave - .cfi_def_cfa rsp, 8 - .cfi_same_value rbp - -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// CacheLookup return-type, caller -// -// Locate the implementation for a class in a selector's method cache. -// -// Takes: -// $0 = NORMAL, FPRET, FP2RET, STRET, SUPER, SUPER_STRET, SUPER2, SUPER2_STRET, GETIMP -// a2 or a3 (STRET) = selector a.k.a. cache -// r11 = class to search -// -// On exit: r10 clobbered -// (found) calls or returns IMP, eq/ne/r11 set for forwarding -// (not found) jumps to LCacheMiss, class still in r11 -// -///////////////////////////////////////////////////////////////////// - -.macro CacheHit - - // CacheHit must always be preceded by a not-taken `jne` instruction - // in order to set the correct flags for _objc_msgForward_impcache. - - // r10 = found bucket - -.if $0 == GETIMP - movq 8(%r10), %rax // return imp - leaq __objc_msgSend_uncached_impcache(%rip), %r11 - cmpq %rax, %r11 - jne 4f - xorl %eax, %eax // don't return msgSend_uncached -4: ret -.elseif $0 == NORMAL || $0 == FPRET || $0 == FP2RET - // eq already set for forwarding by `jne` - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == SUPER - movq receiver(%a1), %a1 // load real receiver - cmp %r10, %r10 // set eq for non-stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == SUPER2 - movq receiver(%a1), %a1 // load real receiver - cmp %r10, %r10 // set eq for non-stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == STRET - test %r10, %r10 // set ne for stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == SUPER_STRET - movq receiver(%a2), %a2 // load real receiver - test %r10, %r10 // set ne for stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == SUPER2_STRET - movq receiver(%a2), %a2 // load real receiver - test %r10, %r10 // set ne for stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp -.else -.abort oops -.endif - -.endmacro - - -.macro CacheLookup -.if $0 != STRET && $0 != SUPER_STRET && $0 != SUPER2_STRET - movq %a2, %r10 // r10 = _cmd -.else - movq %a3, %r10 // r10 = _cmd -.endif - andl 24(%r11), %r10d // r10 = _cmd & class->cache.mask - shlq $$4, %r10 // r10 = offset = (_cmd & mask)<<4 - addq 16(%r11), %r10 // r10 = class->cache.buckets + offset - -.if $0 != STRET && $0 != SUPER_STRET && $0 != SUPER2_STRET - cmpq (%r10), %a2 // if (bucket->sel != _cmd) -.else - cmpq (%r10), %a3 // if (bucket->sel != _cmd) -.endif - jne 1f // scan more - // CacheHit must always be preceded by a not-taken `jne` instruction - CacheHit $0 // call or return imp - -1: - // loop - cmpq $$1, (%r10) - jbe 3f // if (bucket->sel <= 1) wrap or miss - - addq $$16, %r10 // bucket++ -2: -.if $0 != STRET && $0 != SUPER_STRET && $0 != SUPER2_STRET - cmpq (%r10), %a2 // if (bucket->sel != _cmd) -.else - cmpq (%r10), %a3 // if (bucket->sel != _cmd) -.endif - jne 1b // scan more - // CacheHit must always be preceded by a not-taken `jne` instruction - CacheHit $0 // call or return imp - -3: - // wrap or miss - jb LCacheMiss_f // if (bucket->sel < 1) cache miss - // wrap - movq 8(%r10), %r10 // bucket->imp is really first bucket - jmp 2f - - // Clone scanning loop to miss instead of hang when cache is corrupt. - // The slow path may detect any corruption and halt later. - -1: - // loop - cmpq $$1, (%r10) - jbe 3f // if (bucket->sel <= 1) wrap or miss - - addq $$16, %r10 // bucket++ -2: -.if $0 != STRET && $0 != SUPER_STRET && $0 != SUPER2_STRET - cmpq (%r10), %a2 // if (bucket->sel != _cmd) -.else - cmpq (%r10), %a3 // if (bucket->sel != _cmd) -.endif - jne 1b // scan more - // CacheHit must always be preceded by a not-taken `jne` instruction - CacheHit $0 // call or return imp - -3: - // double wrap or miss - jmp LCacheMiss_f - -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// MethodTableLookup classRegister, selectorRegister -// -// Takes: $0 = class to search (a1 or a2 or r10 ONLY) -// $1 = selector to search for (a2 or a3 ONLY) -// r11 = class to search -// -// On exit: imp in %r11 -// -///////////////////////////////////////////////////////////////////// -.macro MethodTableLookup - - MESSENGER_END_SLOW - - SaveRegisters - - // _class_lookupMethodAndLoadCache3(receiver, selector, class) - - movq $0, %a1 - movq $1, %a2 - movq %r11, %a3 - call __class_lookupMethodAndLoadCache3 - - // IMP is now in %rax - movq %rax, %r11 - - RestoreRegisters - -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// GetIsaCheckNil return-type -// GetIsaSupport return-type -// -// Sets r11 = receiver->isa. -// Looks up the real class if receiver is a tagged pointer object. -// Returns zero if obj is nil. -// -// Takes: $0 = NORMAL or FPRET or FP2RET or STRET -// a1 or a2 (STRET) = receiver -// -// On exit: r11 = receiver->isa -// r10 is clobbered -// -///////////////////////////////////////////////////////////////////// - -.macro GetIsaCheckNil -.if $0 == SUPER || $0 == SUPER_STRET - error super dispatch does not test for nil -.endif - -.if $0 != STRET - testq %a1, %a1 -.else - testq %a2, %a2 -.endif - jle LNilOrTagged_f // MSB tagged pointer looks negative - -.if $0 != STRET - movq (%a1), %r11 // r11 = isa -.else - movq (%a2), %r11 // r11 = isa -.endif - -LGetIsaDone: -.endmacro - - -.macro GetIsaSupport - .align 3 -LNilOrTagged: - jz LNil_f // flags set by NilOrTaggedTest - - // tagged - - leaq _objc_debug_taggedpointer_classes(%rip), %r11 -.if $0 != STRET - movq %a1, %r10 -.else - movq %a2, %r10 -.endif - shrq $$60, %r10 - movq (%r11, %r10, 8), %r11 // read isa from table - jmp LGetIsaDone_b - -LNil: - // nil - -.if $0 == FPRET - fldz -.elseif $0 == FP2RET - fldz - fldz -.endif -.if $0 == STRET - movq %rdi, %rax -.else - xorl %eax, %eax - xorl %edx, %edx - xorps %xmm0, %xmm0 - xorps %xmm1, %xmm1 -.endif - MESSENGER_END_NIL - ret -.endmacro - - -/******************************************************************** - * IMP cache_getImp(Class cls, SEL sel) - * - * On entry: a1 = class whose cache is to be searched - * a2 = selector to search for - * - * If found, returns method implementation. - * If not found, returns NULL. - ********************************************************************/ - - STATIC_ENTRY _cache_getImp - -// do lookup - movq %a1, %r11 // move class to r11 for CacheLookup - CacheLookup GETIMP // returns IMP on success - -LCacheMiss: -// cache miss, return nil - xorl %eax, %eax - ret - -LGetImpExit: - END_ENTRY _cache_getImp - - -/******************************************************************** - * - * id objc_msgSend(id self, SEL _cmd,...); - * - ********************************************************************/ - - .data - .align 3 - .globl _objc_debug_taggedpointer_classes -_objc_debug_taggedpointer_classes: - .fill 16, 8, 0 - - ENTRY _objc_msgSend - MESSENGER_START - - GetIsaCheckNil NORMAL // r11 = self->isa, or return zero - CacheLookup NORMAL // calls IMP on success - - GetIsaSupport NORMAL - -// cache miss: go search the method lists -LCacheMiss: - // isa still in r11 - MethodTableLookup %a1, %a2 // r11 = IMP - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSend - - - ENTRY _objc_msgSend_fixup - int3 - END_ENTRY _objc_msgSend_fixup - - - STATIC_ENTRY _objc_msgSend_fixedup - // Load _cmd from the message_ref - movq 8(%a2), %a2 - jmp _objc_msgSend - END_ENTRY _objc_msgSend_fixedup - - -/******************************************************************** - * - * id objc_msgSendSuper(struct objc_super *super, SEL _cmd,...); - * - * struct objc_super { - * id receiver; - * Class class; - * }; - ********************************************************************/ - - ENTRY _objc_msgSendSuper - MESSENGER_START - -// search the cache (objc_super in %a1) - movq class(%a1), %r11 // class = objc_super->class - CacheLookup SUPER // calls IMP on success - -// cache miss: go search the method lists -LCacheMiss: - // class still in r11 - movq receiver(%a1), %r10 - MethodTableLookup %r10, %a2 // r11 = IMP - movq receiver(%a1), %a1 // load real receiver - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSendSuper - - -/******************************************************************** - * id objc_msgSendSuper2 - ********************************************************************/ - - ENTRY _objc_msgSendSuper2 - MESSENGER_START - - // objc_super->class is superclass of class to search - -// search the cache (objc_super in %a1) - movq class(%a1), %r11 // cls = objc_super->class - movq 8(%r11), %r11 // cls = class->superclass - CacheLookup SUPER2 // calls IMP on success - -// cache miss: go search the method lists -LCacheMiss: - // superclass still in r11 - movq receiver(%a1), %r10 - MethodTableLookup %r10, %a2 // r11 = IMP - movq receiver(%a1), %a1 // load real receiver - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSendSuper2 - - - ENTRY _objc_msgSendSuper2_fixup - int3 - END_ENTRY _objc_msgSendSuper2_fixup - - - STATIC_ENTRY _objc_msgSendSuper2_fixedup - // Load _cmd from the message_ref - movq 8(%a2), %a2 - jmp _objc_msgSendSuper2 - END_ENTRY _objc_msgSendSuper2_fixedup - - -/******************************************************************** - * - * double objc_msgSend_fpret(id self, SEL _cmd,...); - * Used for `long double` return only. `float` and `double` use objc_msgSend. - * - ********************************************************************/ - - ENTRY _objc_msgSend_fpret - MESSENGER_START - - GetIsaCheckNil FPRET // r11 = self->isa, or return zero - CacheLookup FPRET // calls IMP on success - - GetIsaSupport FPRET - -// cache miss: go search the method lists -LCacheMiss: - // isa still in r11 - MethodTableLookup %a1, %a2 // r11 = IMP - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSend_fpret - - - ENTRY _objc_msgSend_fpret_fixup - int3 - END_ENTRY _objc_msgSend_fpret_fixup - - - STATIC_ENTRY _objc_msgSend_fpret_fixedup - // Load _cmd from the message_ref - movq 8(%a2), %a2 - jmp _objc_msgSend_fpret - END_ENTRY _objc_msgSend_fpret_fixedup - - -/******************************************************************** - * - * double objc_msgSend_fp2ret(id self, SEL _cmd,...); - * Used for `complex long double` return only. - * - ********************************************************************/ - - ENTRY _objc_msgSend_fp2ret - MESSENGER_START - - GetIsaCheckNil FP2RET // r11 = self->isa, or return zero - CacheLookup FP2RET // calls IMP on success - - GetIsaSupport FP2RET - -// cache miss: go search the method lists -LCacheMiss: - // isa still in r11 - MethodTableLookup %a1, %a2 // r11 = IMP - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSend_fp2ret - - - ENTRY _objc_msgSend_fp2ret_fixup - int3 - END_ENTRY _objc_msgSend_fp2ret_fixup - - - STATIC_ENTRY _objc_msgSend_fp2ret_fixedup - // Load _cmd from the message_ref - movq 8(%a2), %a2 - jmp _objc_msgSend_fp2ret - END_ENTRY _objc_msgSend_fp2ret_fixedup - - -/******************************************************************** - * - * void objc_msgSend_stret(void *st_addr, id self, SEL _cmd, ...); - * - * objc_msgSend_stret is the struct-return form of msgSend. - * The ABI calls for %a1 to be used as the address of the structure - * being returned, with the parameters in the succeeding locations. - * - * On entry: %a1 is the address where the structure is returned, - * %a2 is the message receiver, - * %a3 is the selector - ********************************************************************/ - - ENTRY _objc_msgSend_stret - MESSENGER_START - - GetIsaCheckNil STRET // r11 = self->isa, or return zero - CacheLookup STRET // calls IMP on success - - GetIsaSupport STRET - -// cache miss: go search the method lists -LCacheMiss: - // isa still in r11 - MethodTableLookup %a2, %a3 // r11 = IMP - test %r11, %r11 // set ne (stret) for forward; r11!=0 - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSend_stret - - - ENTRY _objc_msgSend_stret_fixup - int3 - END_ENTRY _objc_msgSend_stret_fixup - - - STATIC_ENTRY _objc_msgSend_stret_fixedup - // Load _cmd from the message_ref - movq 8(%a3), %a3 - jmp _objc_msgSend_stret - END_ENTRY _objc_msgSend_stret_fixedup - - -/******************************************************************** - * - * void objc_msgSendSuper_stret(void *st_addr, struct objc_super *super, SEL _cmd, ...); - * - * struct objc_super { - * id receiver; - * Class class; - * }; - * - * objc_msgSendSuper_stret is the struct-return form of msgSendSuper. - * The ABI calls for (sp+4) to be used as the address of the structure - * being returned, with the parameters in the succeeding registers. - * - * On entry: %a1 is the address where the structure is returned, - * %a2 is the address of the objc_super structure, - * %a3 is the selector - * - ********************************************************************/ - - ENTRY _objc_msgSendSuper_stret - MESSENGER_START - -// search the cache (objc_super in %a2) - movq class(%a2), %r11 // class = objc_super->class - CacheLookup SUPER_STRET // calls IMP on success - -// cache miss: go search the method lists -LCacheMiss: - // class still in r11 - movq receiver(%a2), %r10 - MethodTableLookup %r10, %a3 // r11 = IMP - movq receiver(%a2), %a2 // load real receiver - test %r11, %r11 // set ne (stret) for forward; r11!=0 - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSendSuper_stret - - -/******************************************************************** - * id objc_msgSendSuper2_stret - ********************************************************************/ - - ENTRY _objc_msgSendSuper2_stret - MESSENGER_START - -// search the cache (objc_super in %a2) - movq class(%a2), %r11 // class = objc_super->class - movq 8(%r11), %r11 // class = class->superclass - CacheLookup SUPER2_STRET // calls IMP on success - -// cache miss: go search the method lists -LCacheMiss: - // superclass still in r11 - movq receiver(%a2), %r10 - MethodTableLookup %r10, %a3 // r11 = IMP - movq receiver(%a2), %a2 // load real receiver - test %r11, %r11 // set ne (stret) for forward; r11!=0 - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSendSuper2_stret - - - ENTRY _objc_msgSendSuper2_stret_fixup - int3 - END_ENTRY _objc_msgSendSuper2_stret_fixup - - - STATIC_ENTRY _objc_msgSendSuper2_stret_fixedup - // Load _cmd from the message_ref - movq 8(%a3), %a3 - jmp _objc_msgSendSuper2_stret - END_ENTRY _objc_msgSendSuper2_stret_fixedup - - -/******************************************************************** - * - * _objc_msgSend_uncached_impcache - * _objc_msgSend_uncached - * _objc_msgSend_stret_uncached - * - * Used to erase method cache entries in-place by - * bouncing them to the uncached lookup. - * - ********************************************************************/ - - STATIC_ENTRY __objc_msgSend_uncached_impcache - // Method cache version - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band condition register is NE for stret, EQ otherwise. - // Out-of-band r11 is the searched class - - MESSENGER_START - nop - MESSENGER_END_SLOW - - jne __objc_msgSend_stret_uncached - jmp __objc_msgSend_uncached - - END_ENTRY __objc_msgSend_uncached_impcache - - - STATIC_ENTRY __objc_msgSend_uncached - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band r11 is the searched class - - // r11 is already the class to search - MethodTableLookup %a1, %a2 // r11 = IMP - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY __objc_msgSend_uncached - - - STATIC_ENTRY __objc_msgSend_stret_uncached - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band r11 is the searched class - - // r11 is already the class to search - MethodTableLookup %a2, %a3 // r11 = IMP - test %r11, %r11 // set ne (stret) for forward; r11!=0 - jmp *%r11 // goto *imp - - END_ENTRY __objc_msgSend_stret_uncached - - -/******************************************************************** -* -* id _objc_msgForward(id self, SEL _cmd,...); -* -* _objc_msgForward and _objc_msgForward_stret are the externally-callable -* functions returned by things like method_getImplementation(). -* _objc_msgForward_impcache is the function pointer actually stored in -* method caches. -* -********************************************************************/ - - STATIC_ENTRY __objc_msgForward_impcache - // Method cache version - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band condition register is NE for stret, EQ otherwise. - - MESSENGER_START - nop - MESSENGER_END_SLOW - - jne __objc_msgForward_stret - jmp __objc_msgForward - - END_ENTRY __objc_msgForward_impcache - - - ENTRY __objc_msgForward - // Non-stret version - - movq __objc_forward_handler(%rip), %r11 - jmp *%r11 - - END_ENTRY __objc_msgForward - - - ENTRY __objc_msgForward_stret - // Struct-return version - - movq __objc_forward_stret_handler(%rip), %r11 - jmp *%r11 - - END_ENTRY __objc_msgForward_stret - - - ENTRY _objc_msgSend_debug - jmp _objc_msgSend - END_ENTRY _objc_msgSend_debug - - ENTRY _objc_msgSendSuper2_debug - jmp _objc_msgSendSuper2 - END_ENTRY _objc_msgSendSuper2_debug - - ENTRY _objc_msgSend_stret_debug - jmp _objc_msgSend_stret - END_ENTRY _objc_msgSend_stret_debug - - ENTRY _objc_msgSendSuper2_stret_debug - jmp _objc_msgSendSuper2_stret - END_ENTRY _objc_msgSendSuper2_stret_debug - - ENTRY _objc_msgSend_fpret_debug - jmp _objc_msgSend_fpret - END_ENTRY _objc_msgSend_fpret_debug - - ENTRY _objc_msgSend_fp2ret_debug - jmp _objc_msgSend_fp2ret - END_ENTRY _objc_msgSend_fp2ret_debug - - - ENTRY _objc_msgSend_noarg - jmp _objc_msgSend - END_ENTRY _objc_msgSend_noarg - - - ENTRY _method_invoke - - movq method_imp(%a2), %r11 - movq method_name(%a2), %a2 - jmp *%r11 - - END_ENTRY _method_invoke - - - ENTRY _method_invoke_stret - - movq method_imp(%a3), %r11 - movq method_name(%a3), %a3 - jmp *%r11 - - END_ENTRY _method_invoke_stret - - - STATIC_ENTRY __objc_ignored_method - - movq %a1, %rax - ret - - END_ENTRY __objc_ignored_method - - -.section __DATA,__objc_msg_break -.quad 0 -.quad 0 - -#endif diff --git a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-win32.m b/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-win32.m deleted file mode 100644 index 014daa8..0000000 --- a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-win32.m +++ /dev/null @@ -1,551 +0,0 @@ -#include "objc-private.h" - -// out-of-band parameter to objc_msgForward -#define kFwdMsgSend 1 -#define kFwdMsgSendStret 0 - -// objc_msgSend parameters -#define SELF 8[ebp] -#define SUPER 8[ebp] -#define SELECTOR 12[ebp] -#define FIRST_ARG 16[ebp] - -// objc_msgSend_stret parameters -#define STRUCT_ADDR 8[ebp] -#define SELF_STRET 12[ebp] -#define SUPER_STRET 12[ebp] -#define SELECTOR_STRET 16[ebp] - -// objc_super parameter to sendSuper -#define super_receiver 0 -#define super_class 4 - -// struct objc_class fields -#define isa 0 -#define cache 32 - -// struct objc_method fields -#define method_name 0 -#define method_imp 8 - -// struct objc_cache fields -#define mask 0 -#define occupied 4 -#define buckets 8 - -void *_objc_forward_handler = NULL; -void *_objc_forward_stret_handler = NULL; - -__declspec(naked) Method _cache_getMethod(Class cls, SEL sel, IMP objc_msgForward_imp) -{ - __asm { - push ebp - mov ebp, esp - - mov ecx, SELECTOR - mov edx, SELF - -// CacheLookup WORD_RETURN, CACHE_GET - push edi - mov edi, cache[edx] - - push esi - mov esi, mask[edi] - mov edx, ecx - shr edx, 2 -SCAN: - and edx, esi - mov eax, buckets[edi][edx*4] - test eax, eax - je MISS - cmp ecx, method_name[eax] - je HIT - add edx, 1 - jmp SCAN - -MISS: - xor eax, eax - pop esi - pop edi - leave - ret - -HIT: - mov ecx, FIRST_ARG - cmp ecx, method_imp[eax] - je MISS - pop esi - pop edi - leave - ret - } -} - -__declspec(naked) IMP _cache_getImp(Class cls, SEL sel) -{ - __asm { - push ebp - mov ebp, esp - - mov ecx, SELECTOR - mov edx, SELF - -// CacheLookup WORD_RETURN, CACHE_GET - push edi - mov edi, cache[edx] - - push esi - mov esi, mask[edi] - mov edx, ecx - shr edx, 2 -SCAN: - and edx, esi - mov eax, buckets[edi][edx*4] - test eax, eax - je MISS - cmp ecx, method_name[eax] - je HIT - add edx, 1 - jmp SCAN - -MISS: - pop esi - pop edi - xor eax, eax - leave - ret - -HIT: - pop esi - pop edi - mov eax, method_imp[eax] - leave - ret - } -} - - -OBJC_EXPORT __declspec(naked) id objc_msgSend(id a, SEL b, ...) -{ - __asm { - push ebp - mov ebp, esp - - // load receiver and selector - mov ecx, SELECTOR - mov eax, SELF - -#if SUPPORT_GC - // check whether selector is ignored -#error oops -#endif - - // check whether receiver is nil - test eax, eax - je NIL - - // receiver (in eax) is non-nil: search the cache - mov edx, isa[eax] - - // CacheLookup WORD_RETURN, MSG_SEND - push edi - mov edi, cache[edx] - push esi - mov esi, mask[edi] - mov edx, ecx - shr edx, 2 -SCAN: - and edx, esi - mov eax, buckets[edi][edx*4] - test eax, eax - je MISS - cmp ecx, method_name[eax] - je HIT - add edx, 1 - jmp SCAN - -HIT: - mov eax, method_imp[eax] - pop esi - pop edi - mov edx, kFwdMsgSend - leave - jmp eax - - // cache miss: search method lists -MISS: - pop esi - pop edi - mov edx, SELF - mov eax, isa[edx] - - // MethodTableLookup WORD_RETURN, MSG_SEND - push eax - push ecx - push edx - call _class_lookupMethodAndLoadCache3 - - mov edx, kFwdMsgSend - leave - jmp eax - - // message send to nil: return zero -NIL: - // eax is already zero - mov edx, 0 - leave - ret - } -} - - -OBJC_EXPORT __declspec(naked) double objc_msgSend_fpret(id a, SEL b, ...) -{ - __asm { - push ebp - mov ebp, esp - - // load receiver and selector - mov ecx, SELECTOR - mov eax, SELF - -#if SUPPORT_GC - // check whether selector is ignored -#error oops -#endif - - // check whether receiver is nil - test eax, eax - je NIL - - // receiver (in eax) is non-nil: search the cache - mov edx, isa[eax] - - // CacheLookup WORD_RETURN, MSG_SEND - push edi - mov edi, cache[edx] - push esi - mov esi, mask[edi] - mov edx, ecx - shr edx, 2 -SCAN: - and edx, esi - mov eax, buckets[edi][edx*4] - test eax, eax - je MISS - cmp ecx, method_name[eax] - je HIT - add edx, 1 - jmp SCAN - -HIT: - mov eax, method_imp[eax] - pop esi - pop edi - mov edx, kFwdMsgSend - leave - jmp eax - - // cache miss: search method lists -MISS: - pop esi - pop edi - mov edx, SELF - mov eax, isa[edx] - - // MethodTableLookup WORD_RETURN, MSG_SEND - push eax - push ecx - push edx - call _class_lookupMethodAndLoadCache3 - - mov edx, kFwdMsgSend - leave - jmp eax - - // message send to nil: return zero -NIL: - fldz - leave - ret - } -} - - -OBJC_EXPORT __declspec(naked) id objc_msgSendSuper(struct objc_super *a, SEL b, ...) -{ - __asm { - push ebp - mov ebp, esp - - // load class and selector - mov eax, SUPER - mov ecx, SELECTOR - mov edx, super_class[eax] - -#if SUPPORT_GC - // check whether selector is ignored -#error oops -#endif - - // search the cache (class in edx) - // CacheLookup WORD_RETURN, MSG_SENDSUPER - push edi - mov edi, cache[edx] - push esi - mov esi, mask[edi] - mov edx, ecx - shr edx, 2 -SCAN: - and edx, esi - mov eax, buckets[edi][edx*4] - test eax, eax - je MISS - cmp ecx, method_name[eax] - je HIT - add edx, 1 - jmp SCAN - -HIT: - mov eax, method_imp[eax] - pop esi - pop edi - mov edx, SUPER - mov edx, super_receiver[edx] - mov SUPER, edx - mov edx, kFwdMsgSend - leave - jmp eax - - // cache miss: search method lists -MISS: - - pop esi - pop edi - mov eax, SUPER - mov edx, super_receiver[eax] - mov SUPER, edx - mov eax, super_class[eax] - - // MethodTableLookup WORD_RETURN, MSG_SENDSUPER - push eax - push ecx - push edx - call _class_lookupMethodAndLoadCache3 - - mov edx, kFwdMsgSend - leave - jmp eax - } -} - - -OBJC_EXPORT __declspec(naked) void objc_msgSend_stret(void) -{ - __asm { - push ebp - mov ebp, esp - - // load receiver and selector - mov ecx, SELECTOR_STRET - mov eax, SELF_STRET - -#if SUPPORT_GC - // check whether selector is ignored -#error oops -#endif - - // check whether receiver is nil - test eax, eax - je NIL - - // receiver (in eax) is non-nil: search the cache - mov edx, isa[eax] - - // CacheLookup WORD_RETURN, MSG_SEND - push edi - mov edi, cache[edx] - push esi - mov esi, mask[edi] - mov edx, ecx - shr edx, 2 -SCAN: - and edx, esi - mov eax, buckets[edi][edx*4] - test eax, eax - je MISS - cmp ecx, method_name[eax] - je HIT - add edx, 1 - jmp SCAN - -HIT: - mov eax, method_imp[eax] - pop esi - pop edi - mov edx, kFwdMsgSendStret - leave - jmp eax - - // cache miss: search method lists -MISS: - pop esi - pop edi - mov edx, SELF_STRET - mov eax, isa[edx] - - // MethodTableLookup WORD_RETURN, MSG_SEND - push eax - push ecx - push edx - call _class_lookupMethodAndLoadCache3 - - mov edx, kFwdMsgSendStret - leave - jmp eax - - // message send to nil: return zero -NIL: - // eax is already zero - mov edx, 0 - leave - ret - } -} - - -OBJC_EXPORT __declspec(naked) id objc_msgSendSuper_stret(struct objc_super *a, SEL b, ...) -{ - __asm { - push ebp - mov ebp, esp - - // load class and selector - mov eax, SUPER_STRET - mov ecx, SELECTOR_STRET - mov edx, super_class[eax] - -#if SUPPORT_GC - // check whether selector is ignored -#error oops -#endif - - // search the cache (class in edx) - // CacheLookup WORD_RETURN, MSG_SENDSUPER - push edi - mov edi, cache[edx] - push esi - mov esi, mask[edi] - mov edx, ecx - shr edx, 2 -SCAN: - and edx, esi - mov eax, buckets[edi][edx*4] - test eax, eax - je MISS - cmp ecx, method_name[eax] - je HIT - add edx, 1 - jmp SCAN - -HIT: - mov eax, method_imp[eax] - pop esi - pop edi - mov edx, SUPER_STRET - mov edx, super_receiver[edx] - mov SUPER_STRET, edx - mov edx, kFwdMsgSendStret - leave - jmp eax - - // cache miss: search method lists -MISS: - - pop esi - pop edi - mov eax, SUPER_STRET - mov edx, super_receiver[eax] - mov SUPER_STRET, edx - mov eax, super_class[eax] - - // MethodTableLookup WORD_RETURN, MSG_SENDSUPER - push eax - push ecx - push edx - call _class_lookupMethodAndLoadCache3 - - mov edx, kFwdMsgSendStret - leave - jmp eax - } -} - - -OBJC_EXPORT __declspec(naked) id _objc_msgForward(id a, SEL b, ...) -{ - __asm { - mov ecx, _objc_forward_handler - jmp ecx - } -} - -OBJC_EXPORT __declspec(naked) id _objc_msgForward_stret(id a, SEL b, ...) -{ - __asm { - mov ecx, _objc_forward_stret_handler - jmp ecx - } -} - - -__declspec(naked) id _objc_msgForward_cached(id a, SEL b, ...) -{ - __asm { - cmp edx, kFwdMsgSendStret - je STRET - jmp _objc_msgForward -STRET: - jmp _objc_msgForward_stret - } -} - - -OBJC_EXPORT __declspec(naked) void method_invoke(void) -{ - __asm { - push ebp - mov ebp, esp - - mov ecx, SELECTOR - mov edx, method_name[ecx] - mov eax, method_imp[ecx] - mov SELECTOR, edx - - leave - jmp eax - } -} - - -OBJC_EXPORT __declspec(naked) void method_invoke_stret(void) -{ - __asm { - push ebp - mov ebp, esp - - mov ecx, SELECTOR_STRET - mov edx, method_name[ecx] - mov eax, method_imp[ecx] - mov SELECTOR_STRET, edx - - leave - jmp eax - } -} - - -__declspec(naked) id _objc_ignored_method(id obj, SEL sel) -{ - return obj; -} diff --git a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-x86_64.s b/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-x86_64.s deleted file mode 100644 index 50d7e0b..0000000 --- a/objc/objc-runtime/runtime/Messengers.subproj/objc-msg-x86_64.s +++ /dev/null @@ -1,1183 +0,0 @@ -/* - * 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@ - */ - -#include <TargetConditionals.h> -#if __x86_64__ && !TARGET_IPHONE_SIMULATOR - -/******************************************************************** - ******************************************************************** - ** - ** objc-msg-x86_64.s - x86-64 code to support objc messaging. - ** - ******************************************************************** - ********************************************************************/ - -/******************************************************************** -* Data used by the ObjC runtime. -* -********************************************************************/ - -.data - -// _objc_entryPoints and _objc_exitPoints are used by objc -// to get the critical regions for which method caches -// cannot be garbage collected. - -.align 4 -.private_extern _objc_entryPoints -_objc_entryPoints: - .quad _cache_getImp - .quad _objc_msgSend - .quad _objc_msgSend_fpret - .quad _objc_msgSend_fp2ret - .quad _objc_msgSend_stret - .quad _objc_msgSendSuper - .quad _objc_msgSendSuper_stret - .quad _objc_msgSendSuper2 - .quad _objc_msgSendSuper2_stret - .quad 0 - -.private_extern _objc_exitPoints -_objc_exitPoints: - .quad LExit_cache_getImp - .quad LExit_objc_msgSend - .quad LExit_objc_msgSend_fpret - .quad LExit_objc_msgSend_fp2ret - .quad LExit_objc_msgSend_stret - .quad LExit_objc_msgSendSuper - .quad LExit_objc_msgSendSuper_stret - .quad LExit_objc_msgSendSuper2 - .quad LExit_objc_msgSendSuper2_stret - .quad 0 - - -/******************************************************************** -* List every exit insn from every messenger for debugger use. -* Format: -* ( -* 1 word instruction's address -* 1 word type (ENTER or FAST_EXIT or SLOW_EXIT or NIL_EXIT) -* ) -* 1 word zero -* -* ENTER is the start of a dispatcher -* FAST_EXIT is method dispatch -* SLOW_EXIT is uncached method lookup -* NIL_EXIT is returning zero from a message sent to nil -* These must match objc-gdb.h. -********************************************************************/ - -#define ENTER 1 -#define FAST_EXIT 2 -#define SLOW_EXIT 3 -#define NIL_EXIT 4 - -.section __DATA,__objc_msg_break -.globl _gdb_objc_messenger_breakpoints -_gdb_objc_messenger_breakpoints: -// contents populated by the macros below - -.macro MESSENGER_START -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad ENTER - .text -.endmacro -.macro MESSENGER_END_FAST -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad FAST_EXIT - .text -.endmacro -.macro MESSENGER_END_SLOW -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad SLOW_EXIT - .text -.endmacro -.macro MESSENGER_END_NIL -4: - .section __DATA,__objc_msg_break - .quad 4b - .quad NIL_EXIT - .text -.endmacro - - -/******************************************************************** - * Recommended multi-byte NOP instructions - * (Intel 64 and IA-32 Architectures Software Developer's Manual Volume 2B) - ********************************************************************/ -#define nop1 .byte 0x90 -#define nop2 .byte 0x66,0x90 -#define nop3 .byte 0x0F,0x1F,0x00 -#define nop4 .byte 0x0F,0x1F,0x40,0x00 -#define nop5 .byte 0x0F,0x1F,0x44,0x00,0x00 -#define nop6 .byte 0x66,0x0F,0x1F,0x44,0x00,0x00 -#define nop7 .byte 0x0F,0x1F,0x80,0x00,0x00,0x00,0x00 -#define nop8 .byte 0x0F,0x1F,0x84,0x00,0x00,0x00,0x00,0x00 -#define nop9 .byte 0x66,0x0F,0x1F,0x84,0x00,0x00,0x00,0x00,0x00 - - -/******************************************************************** - * Harmless branch prefix hint for instruction alignment - ********************************************************************/ - -#define PN .byte 0x2e - - -/******************************************************************** - * Names for parameter registers. - ********************************************************************/ - -#define a1 rdi -#define a1d edi -#define a1b dil -#define a2 rsi -#define a2d esi -#define a2b sil -#define a3 rdx -#define a3d edx -#define a4 rcx -#define a4d ecx -#define a5 r8 -#define a5d r8d -#define a6 r9 -#define a6d r9d - - -/******************************************************************** - * Names for relative labels - * DO NOT USE THESE LABELS ELSEWHERE - * Reserved labels: 6: 7: 8: 9: - ********************************************************************/ -#define LCacheMiss 6 -#define LCacheMiss_f 6f -#define LCacheMiss_b 6b -#define LNilTestSlow 7 -#define LNilTestSlow_f 7f -#define LNilTestSlow_b 7b -#define LGetIsaDone 8 -#define LGetIsaDone_f 8f -#define LGetIsaDone_b 8b -#define LGetIsaSlow 9 -#define LGetIsaSlow_f 9f -#define LGetIsaSlow_b 9b - -/******************************************************************** - * Macro parameters - ********************************************************************/ - -#define NORMAL 0 -#define FPRET 1 -#define FP2RET 2 -#define GETIMP 3 -#define STRET 4 -#define SUPER 5 -#define SUPER_STRET 6 -#define SUPER2 7 -#define SUPER2_STRET 8 - - -/******************************************************************** - * - * Structure definitions. - * - ********************************************************************/ - -// objc_super parameter to sendSuper -#define receiver 0 -#define class 8 - -// Selected field offsets in class structure -// #define isa 0 USE GetIsa INSTEAD - -// Method descriptor -#define method_name 0 -#define method_imp 16 - -// typedef struct { -// uint128_t floatingPointArgs[8]; // xmm0..xmm7 -// long linkageArea[4]; // r10, rax, ebp, ret -// long registerArgs[6]; // a1..a6 -// long stackArgs[0]; // variable-size -// } *marg_list; -#define FP_AREA 0 -#define LINK_AREA (FP_AREA+8*16) -#define REG_AREA (LINK_AREA+4*8) -#define STACK_AREA (REG_AREA+6*8) - - -////////////////////////////////////////////////////////////////////// -// -// ENTRY functionName -// -// Assembly directives to begin an exported function. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro ENTRY - .text - .globl $0 - .align 6, 0x90 -$0: - .cfi_startproc -.endmacro - -.macro STATIC_ENTRY - .text - .private_extern $0 - .align 2, 0x90 -$0: - .cfi_startproc -.endmacro - -////////////////////////////////////////////////////////////////////// -// -// END_ENTRY functionName -// -// Assembly directives to end an exported function. Just a placeholder, -// a close-parenthesis for ENTRY, until it is needed for something. -// -// Takes: functionName - name of the exported function -////////////////////////////////////////////////////////////////////// - -.macro END_ENTRY - .cfi_endproc -LExit$0: -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// SaveRegisters -// -// Pushes a stack frame and saves all registers that might contain -// parameter values. -// -// On entry: -// stack = ret -// -// On exit: -// %rsp is 16-byte aligned -// -///////////////////////////////////////////////////////////////////// - -.macro SaveRegisters - - push %rbp - .cfi_def_cfa_offset 16 - .cfi_offset rbp, -16 - - mov %rsp, %rbp - .cfi_def_cfa_register rbp - - sub $$0x80+8, %rsp // +8 for alignment - - movdqa %xmm0, -0x80(%rbp) - push %rax // might be xmm parameter count - movdqa %xmm1, -0x70(%rbp) - push %a1 - movdqa %xmm2, -0x60(%rbp) - push %a2 - movdqa %xmm3, -0x50(%rbp) - push %a3 - movdqa %xmm4, -0x40(%rbp) - push %a4 - movdqa %xmm5, -0x30(%rbp) - push %a5 - movdqa %xmm6, -0x20(%rbp) - push %a6 - movdqa %xmm7, -0x10(%rbp) - -.endmacro - -///////////////////////////////////////////////////////////////////// -// -// RestoreRegisters -// -// Pops a stack frame pushed by SaveRegisters -// -// On entry: -// %rbp unchanged since SaveRegisters -// -// On exit: -// stack = ret -// -///////////////////////////////////////////////////////////////////// - -.macro RestoreRegisters - - movdqa -0x80(%rbp), %xmm0 - pop %a6 - movdqa -0x70(%rbp), %xmm1 - pop %a5 - movdqa -0x60(%rbp), %xmm2 - pop %a4 - movdqa -0x50(%rbp), %xmm3 - pop %a3 - movdqa -0x40(%rbp), %xmm4 - pop %a2 - movdqa -0x30(%rbp), %xmm5 - pop %a1 - movdqa -0x20(%rbp), %xmm6 - pop %rax - movdqa -0x10(%rbp), %xmm7 - - leave - .cfi_def_cfa rsp, 8 - .cfi_same_value rbp - -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// CacheLookup return-type, caller -// -// Locate the implementation for a class in a selector's method cache. -// -// Takes: -// $0 = NORMAL, FPRET, FP2RET, STRET, SUPER, SUPER_STRET, SUPER2, SUPER2_STRET, GETIMP -// a2 or a3 (STRET) = selector a.k.a. cache -// r11 = class to search -// -// On exit: r10 clobbered -// (found) calls or returns IMP, eq/ne/r11 set for forwarding -// (not found) jumps to LCacheMiss, class still in r11 -// -///////////////////////////////////////////////////////////////////// - -.macro CacheHit - - // CacheHit must always be preceded by a not-taken `jne` instruction - // in order to set the correct flags for _objc_msgForward_impcache. - - // r10 = found bucket - -.if $0 == GETIMP - movq 8(%r10), %rax // return imp - leaq __objc_msgSend_uncached_impcache(%rip), %r11 - cmpq %rax, %r11 - jne 4f - xorl %eax, %eax // don't return msgSend_uncached -4: ret -.elseif $0 == NORMAL || $0 == FPRET || $0 == FP2RET - // eq already set for forwarding by `jne` - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == SUPER - movq receiver(%a1), %a1 // load real receiver - cmp %r10, %r10 // set eq for non-stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == SUPER2 - movq receiver(%a1), %a1 // load real receiver - cmp %r10, %r10 // set eq for non-stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == STRET - test %r10, %r10 // set ne for stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == SUPER_STRET - movq receiver(%a2), %a2 // load real receiver - test %r10, %r10 // set ne for stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp - -.elseif $0 == SUPER2_STRET - movq receiver(%a2), %a2 // load real receiver - test %r10, %r10 // set ne for stret forwarding - MESSENGER_END_FAST - jmp *8(%r10) // call imp -.else -.abort oops -.endif - -.endmacro - - -.macro CacheLookup -.if $0 != STRET && $0 != SUPER_STRET && $0 != SUPER2_STRET - movq %a2, %r10 // r10 = _cmd -.else - movq %a3, %r10 // r10 = _cmd -.endif - andl 24(%r11), %r10d // r10 = _cmd & class->cache.mask - shlq $$4, %r10 // r10 = offset = (_cmd & mask)<<4 - addq 16(%r11), %r10 // r10 = class->cache.buckets + offset - -.if $0 != STRET && $0 != SUPER_STRET && $0 != SUPER2_STRET - cmpq (%r10), %a2 // if (bucket->sel != _cmd) -.else - cmpq (%r10), %a3 // if (bucket->sel != _cmd) -.endif - jne 1f // scan more - // CacheHit must always be preceded by a not-taken `jne` instruction - CacheHit $0 // call or return imp - -1: - // loop - cmpq $$1, (%r10) - jbe 3f // if (bucket->sel <= 1) wrap or miss - - addq $$16, %r10 // bucket++ -2: -.if $0 != STRET && $0 != SUPER_STRET && $0 != SUPER2_STRET - cmpq (%r10), %a2 // if (bucket->sel != _cmd) -.else - cmpq (%r10), %a3 // if (bucket->sel != _cmd) -.endif - jne 1b // scan more - // CacheHit must always be preceded by a not-taken `jne` instruction - CacheHit $0 // call or return imp - -3: - // wrap or miss - jb LCacheMiss_f // if (bucket->sel < 1) cache miss - // wrap - movq 8(%r10), %r10 // bucket->imp is really first bucket - jmp 2f - - // Clone scanning loop to miss instead of hang when cache is corrupt. - // The slow path may detect any corruption and halt later. - -1: - // loop - cmpq $$1, (%r10) - jbe 3f // if (bucket->sel <= 1) wrap or miss - - addq $$16, %r10 // bucket++ -2: -.if $0 != STRET && $0 != SUPER_STRET && $0 != SUPER2_STRET - cmpq (%r10), %a2 // if (bucket->sel != _cmd) -.else - cmpq (%r10), %a3 // if (bucket->sel != _cmd) -.endif - jne 1b // scan more - // CacheHit must always be preceded by a not-taken `jne` instruction - CacheHit $0 // call or return imp - -3: - // double wrap or miss - jmp LCacheMiss_f - -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// MethodTableLookup classRegister, selectorRegister -// -// Takes: $0 = class to search (a1 or a2 or r10 ONLY) -// $1 = selector to search for (a2 or a3 ONLY) -// r11 = class to search -// -// On exit: imp in %r11 -// -///////////////////////////////////////////////////////////////////// -.macro MethodTableLookup - - MESSENGER_END_SLOW - - SaveRegisters - - // _class_lookupMethodAndLoadCache3(receiver, selector, class) - - movq $0, %a1 - movq $1, %a2 - movq %r11, %a3 - call __class_lookupMethodAndLoadCache3 - - // IMP is now in %rax - movq %rax, %r11 - - RestoreRegisters - -.endmacro - -///////////////////////////////////////////////////////////////////// -// -// GetIsaFast return-type -// GetIsaSupport return-type -// -// Sets r11 = obj->isa. Consults the tagged isa table if necessary. -// -// Takes: $0 = NORMAL or FPRET or FP2RET or STRET -// a1 or a2 (STRET) = receiver -// -// On exit: r11 = receiver->isa -// r10 is clobbered -// -///////////////////////////////////////////////////////////////////// - -.macro GetIsaFast -.if $0 != STRET - testb $$1, %a1b - PN - jnz LGetIsaSlow_f - movq $$0x00007ffffffffff8, %r11 - andq (%a1), %r11 -.else - testb $$1, %a2b - PN - jnz LGetIsaSlow_f - movq $$0x00007ffffffffff8, %r11 - andq (%a2), %r11 -.endif -LGetIsaDone: -.endmacro - -.macro GetIsaSupport2 -LGetIsaSlow: - leaq _objc_debug_taggedpointer_classes(%rip), %r11 -.if $0 != STRET - movl %a1d, %r10d -.else - movl %a2d, %r10d -.endif - andl $$0xF, %r10d - movq (%r11, %r10, 8), %r11 // read isa from table -.endmacro - -.macro GetIsaSupport - GetIsaSupport2 $0 - jmp LGetIsaDone_b -.endmacro - -.macro GetIsa - GetIsaFast $0 - jmp LGetIsaDone_f - GetIsaSupport2 $0 -LGetIsaDone: -.endmacro - - -///////////////////////////////////////////////////////////////////// -// -// NilTest return-type -// -// Takes: $0 = NORMAL or FPRET or FP2RET or STRET -// %a1 or %a2 (STRET) = receiver -// -// On exit: Loads non-nil receiver in %a1 or %a2 (STRET), or returns zero. -// -// NilTestSupport return-type -// -// Takes: $0 = NORMAL or FPRET or FP2RET or STRET -// %a1 or %a2 (STRET) = receiver -// -// On exit: Loads non-nil receiver in %a1 or %a2 (STRET), or returns zero. -// -///////////////////////////////////////////////////////////////////// - -.macro NilTest -.if $0 == SUPER || $0 == SUPER_STRET - error super dispatch does not test for nil -.endif - -.if $0 != STRET - testq %a1, %a1 -.else - testq %a2, %a2 -.endif - PN - jz LNilTestSlow_f -.endmacro - -.macro NilTestSupport - .align 3 -LNilTestSlow: -.if $0 == FPRET - fldz -.elseif $0 == FP2RET - fldz - fldz -.endif -.if $0 == STRET - movq %rdi, %rax -.else - xorl %eax, %eax - xorl %edx, %edx - xorps %xmm0, %xmm0 - xorps %xmm1, %xmm1 -.endif - MESSENGER_END_NIL - ret -.endmacro - - -/******************************************************************** - * IMP cache_getImp(Class cls, SEL sel) - * - * On entry: a1 = class whose cache is to be searched - * a2 = selector to search for - * - * If found, returns method implementation. - * If not found, returns NULL. - ********************************************************************/ - - STATIC_ENTRY _cache_getImp - -// do lookup - movq %a1, %r11 // move class to r11 for CacheLookup - CacheLookup GETIMP // returns IMP on success - -LCacheMiss: -// cache miss, return nil - xorl %eax, %eax - ret - -LGetImpExit: - END_ENTRY _cache_getImp - - -/******************************************************************** - * - * id objc_msgSend(id self, SEL _cmd,...); - * - ********************************************************************/ - - .data - .align 3 - .globl _objc_debug_taggedpointer_classes -_objc_debug_taggedpointer_classes: - .fill 16, 8, 0 - - ENTRY _objc_msgSend - MESSENGER_START - - NilTest NORMAL - - GetIsaFast NORMAL // r11 = self->isa - CacheLookup NORMAL // calls IMP on success - - NilTestSupport NORMAL - - GetIsaSupport NORMAL - -// cache miss: go search the method lists -LCacheMiss: - // isa still in r11 - MethodTableLookup %a1, %a2 // r11 = IMP - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSend - - - ENTRY _objc_msgSend_fixup - int3 - END_ENTRY _objc_msgSend_fixup - - - STATIC_ENTRY _objc_msgSend_fixedup - // Load _cmd from the message_ref - movq 8(%a2), %a2 - jmp _objc_msgSend - END_ENTRY _objc_msgSend_fixedup - - -/******************************************************************** - * - * id objc_msgSendSuper(struct objc_super *super, SEL _cmd,...); - * - * struct objc_super { - * id receiver; - * Class class; - * }; - ********************************************************************/ - - ENTRY _objc_msgSendSuper - MESSENGER_START - -// search the cache (objc_super in %a1) - movq class(%a1), %r11 // class = objc_super->class - CacheLookup SUPER // calls IMP on success - -// cache miss: go search the method lists -LCacheMiss: - // class still in r11 - movq receiver(%a1), %r10 - MethodTableLookup %r10, %a2 // r11 = IMP - movq receiver(%a1), %a1 // load real receiver - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSendSuper - - -/******************************************************************** - * id objc_msgSendSuper2 - ********************************************************************/ - - ENTRY _objc_msgSendSuper2 - MESSENGER_START - - // objc_super->class is superclass of class to search - -// search the cache (objc_super in %a1) - movq class(%a1), %r11 // cls = objc_super->class - movq 8(%r11), %r11 // cls = class->superclass - CacheLookup SUPER2 // calls IMP on success - -// cache miss: go search the method lists -LCacheMiss: - // superclass still in r11 - movq receiver(%a1), %r10 - MethodTableLookup %r10, %a2 // r11 = IMP - movq receiver(%a1), %a1 // load real receiver - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSendSuper2 - - - ENTRY _objc_msgSendSuper2_fixup - int3 - END_ENTRY _objc_msgSendSuper2_fixup - - - STATIC_ENTRY _objc_msgSendSuper2_fixedup - // Load _cmd from the message_ref - movq 8(%a2), %a2 - jmp _objc_msgSendSuper2 - END_ENTRY _objc_msgSendSuper2_fixedup - - -/******************************************************************** - * - * double objc_msgSend_fpret(id self, SEL _cmd,...); - * Used for `long double` return only. `float` and `double` use objc_msgSend. - * - ********************************************************************/ - - ENTRY _objc_msgSend_fpret - MESSENGER_START - - NilTest FPRET - - GetIsaFast FPRET // r11 = self->isa - CacheLookup FPRET // calls IMP on success - - NilTestSupport FPRET - - GetIsaSupport FPRET - -// cache miss: go search the method lists -LCacheMiss: - // isa still in r11 - MethodTableLookup %a1, %a2 // r11 = IMP - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSend_fpret - - - ENTRY _objc_msgSend_fpret_fixup - int3 - END_ENTRY _objc_msgSend_fpret_fixup - - - STATIC_ENTRY _objc_msgSend_fpret_fixedup - // Load _cmd from the message_ref - movq 8(%a2), %a2 - jmp _objc_msgSend_fpret - END_ENTRY _objc_msgSend_fpret_fixedup - - -/******************************************************************** - * - * double objc_msgSend_fp2ret(id self, SEL _cmd,...); - * Used for `complex long double` return only. - * - ********************************************************************/ - - ENTRY _objc_msgSend_fp2ret - MESSENGER_START - - NilTest FP2RET - - GetIsaFast FP2RET // r11 = self->isa - CacheLookup FP2RET // calls IMP on success - - NilTestSupport FP2RET - - GetIsaSupport FP2RET - -// cache miss: go search the method lists -LCacheMiss: - // isa still in r11 - MethodTableLookup %a1, %a2 // r11 = IMP - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSend_fp2ret - - - ENTRY _objc_msgSend_fp2ret_fixup - int3 - END_ENTRY _objc_msgSend_fp2ret_fixup - - - STATIC_ENTRY _objc_msgSend_fp2ret_fixedup - // Load _cmd from the message_ref - movq 8(%a2), %a2 - jmp _objc_msgSend_fp2ret - END_ENTRY _objc_msgSend_fp2ret_fixedup - - -/******************************************************************** - * - * void objc_msgSend_stret(void *st_addr, id self, SEL _cmd, ...); - * - * objc_msgSend_stret is the struct-return form of msgSend. - * The ABI calls for %a1 to be used as the address of the structure - * being returned, with the parameters in the succeeding locations. - * - * On entry: %a1 is the address where the structure is returned, - * %a2 is the message receiver, - * %a3 is the selector - ********************************************************************/ - - ENTRY _objc_msgSend_stret - MESSENGER_START - - NilTest STRET - - GetIsaFast STRET // r11 = self->isa - CacheLookup STRET // calls IMP on success - - NilTestSupport STRET - - GetIsaSupport STRET - -// cache miss: go search the method lists -LCacheMiss: - // isa still in r11 - MethodTableLookup %a2, %a3 // r11 = IMP - test %r11, %r11 // set ne (stret) for forward; r11!=0 - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSend_stret - - - ENTRY _objc_msgSend_stret_fixup - int3 - END_ENTRY _objc_msgSend_stret_fixup - - - STATIC_ENTRY _objc_msgSend_stret_fixedup - // Load _cmd from the message_ref - movq 8(%a3), %a3 - jmp _objc_msgSend_stret - END_ENTRY _objc_msgSend_stret_fixedup - - -/******************************************************************** - * - * void objc_msgSendSuper_stret(void *st_addr, struct objc_super *super, SEL _cmd, ...); - * - * struct objc_super { - * id receiver; - * Class class; - * }; - * - * objc_msgSendSuper_stret is the struct-return form of msgSendSuper. - * The ABI calls for (sp+4) to be used as the address of the structure - * being returned, with the parameters in the succeeding registers. - * - * On entry: %a1 is the address where the structure is returned, - * %a2 is the address of the objc_super structure, - * %a3 is the selector - * - ********************************************************************/ - - ENTRY _objc_msgSendSuper_stret - MESSENGER_START - -// search the cache (objc_super in %a2) - movq class(%a2), %r11 // class = objc_super->class - CacheLookup SUPER_STRET // calls IMP on success - -// cache miss: go search the method lists -LCacheMiss: - // class still in r11 - movq receiver(%a2), %r10 - MethodTableLookup %r10, %a3 // r11 = IMP - movq receiver(%a2), %a2 // load real receiver - test %r11, %r11 // set ne (stret) for forward; r11!=0 - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSendSuper_stret - - -/******************************************************************** - * id objc_msgSendSuper2_stret - ********************************************************************/ - - ENTRY _objc_msgSendSuper2_stret - MESSENGER_START - -// search the cache (objc_super in %a2) - movq class(%a2), %r11 // class = objc_super->class - movq 8(%r11), %r11 // class = class->superclass - CacheLookup SUPER2_STRET // calls IMP on success - -// cache miss: go search the method lists -LCacheMiss: - // superclass still in r11 - movq receiver(%a2), %r10 - MethodTableLookup %r10, %a3 // r11 = IMP - movq receiver(%a2), %a2 // load real receiver - test %r11, %r11 // set ne (stret) for forward; r11!=0 - jmp *%r11 // goto *imp - - END_ENTRY _objc_msgSendSuper2_stret - - - ENTRY _objc_msgSendSuper2_stret_fixup - int3 - END_ENTRY _objc_msgSendSuper2_stret_fixup - - - STATIC_ENTRY _objc_msgSendSuper2_stret_fixedup - // Load _cmd from the message_ref - movq 8(%a3), %a3 - jmp _objc_msgSendSuper2_stret - END_ENTRY _objc_msgSendSuper2_stret_fixedup - - -/******************************************************************** - * - * _objc_msgSend_uncached_impcache - * _objc_msgSend_uncached - * _objc_msgSend_stret_uncached - * - * Used to erase method cache entries in-place by - * bouncing them to the uncached lookup. - * - ********************************************************************/ - - STATIC_ENTRY __objc_msgSend_uncached_impcache - // Method cache version - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band condition register is NE for stret, EQ otherwise. - // Out-of-band r11 is the searched class - - MESSENGER_START - nop - MESSENGER_END_SLOW - - jne __objc_msgSend_stret_uncached - jmp __objc_msgSend_uncached - - END_ENTRY __objc_msgSend_uncached_impcache - - - STATIC_ENTRY __objc_msgSend_uncached - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band r11 is the searched class - - // r11 is already the class to search - MethodTableLookup %a1, %a2 // r11 = IMP - cmp %r11, %r11 // set eq (nonstret) for forwarding - jmp *%r11 // goto *imp - - END_ENTRY __objc_msgSend_uncached - - - STATIC_ENTRY __objc_msgSend_stret_uncached - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band r11 is the searched class - - // r11 is already the class to search - MethodTableLookup %a2, %a3 // r11 = IMP - test %r11, %r11 // set ne (stret) for forward; r11!=0 - jmp *%r11 // goto *imp - - END_ENTRY __objc_msgSend_stret_uncached - - -/******************************************************************** -* -* id _objc_msgForward(id self, SEL _cmd,...); -* -* _objc_msgForward and _objc_msgForward_stret are the externally-callable -* functions returned by things like method_getImplementation(). -* _objc_msgForward_impcache is the function pointer actually stored in -* method caches. -* -********************************************************************/ - - STATIC_ENTRY __objc_msgForward_impcache - // Method cache version - - // THIS IS NOT A CALLABLE C FUNCTION - // Out-of-band condition register is NE for stret, EQ otherwise. - - MESSENGER_START - nop - MESSENGER_END_SLOW - - jne __objc_msgForward_stret - jmp __objc_msgForward - - END_ENTRY __objc_msgForward_impcache - - - ENTRY __objc_msgForward - // Non-stret version - - movq __objc_forward_handler(%rip), %r11 - jmp *%r11 - - END_ENTRY __objc_msgForward - - - ENTRY __objc_msgForward_stret - // Struct-return version - - movq __objc_forward_stret_handler(%rip), %r11 - jmp *%r11 - - END_ENTRY __objc_msgForward_stret - - - ENTRY _objc_msgSend_debug - jmp _objc_msgSend - END_ENTRY _objc_msgSend_debug - - ENTRY _objc_msgSendSuper2_debug - jmp _objc_msgSendSuper2 - END_ENTRY _objc_msgSendSuper2_debug - - ENTRY _objc_msgSend_stret_debug - jmp _objc_msgSend_stret - END_ENTRY _objc_msgSend_stret_debug - - ENTRY _objc_msgSendSuper2_stret_debug - jmp _objc_msgSendSuper2_stret - END_ENTRY _objc_msgSendSuper2_stret_debug - - ENTRY _objc_msgSend_fpret_debug - jmp _objc_msgSend_fpret - END_ENTRY _objc_msgSend_fpret_debug - - ENTRY _objc_msgSend_fp2ret_debug - jmp _objc_msgSend_fp2ret - END_ENTRY _objc_msgSend_fp2ret_debug - - - ENTRY _objc_msgSend_noarg - jmp _objc_msgSend - END_ENTRY _objc_msgSend_noarg - - - ENTRY _method_invoke - - movq method_imp(%a2), %r11 - movq method_name(%a2), %a2 - jmp *%r11 - - END_ENTRY _method_invoke - - - ENTRY _method_invoke_stret - - movq method_imp(%a3), %r11 - movq method_name(%a3), %a3 - jmp *%r11 - - END_ENTRY _method_invoke_stret - - - STATIC_ENTRY __objc_ignored_method - - movq %a1, %rax - ret - - END_ENTRY __objc_ignored_method - - -.section __DATA,__objc_msg_break -.quad 0 -.quad 0 - - - // Workaround for Skype evil (rdar://19715989) - - .text - .align 4 - .private_extern _map_images - .private_extern _map_2_images - .private_extern _hax -_hax: - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop -_map_images: - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - nop - jmp _map_2_images - -#endif diff --git a/objc/objc-runtime/runtime/NSObjCRuntime.h b/objc/objc-runtime/runtime/NSObjCRuntime.h deleted file mode 100644 index d111e0e..0000000 --- a/objc/objc-runtime/runtime/NSObjCRuntime.h +++ /dev/null @@ -1,33 +0,0 @@ -/* NSObjCRuntime.h - Copyright (c) 1994-2012, Apple Inc. All rights reserved. -*/ - -#ifndef _OBJC_NSOBJCRUNTIME_H_ -#define _OBJC_NSOBJCRUNTIME_H_ - -#include <TargetConditionals.h> -#include <objc/objc.h> - -#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 -typedef long NSInteger; -typedef unsigned long NSUInteger; -#else -typedef int NSInteger; -typedef unsigned int NSUInteger; -#endif - -#define NSIntegerMax LONG_MAX -#define NSIntegerMin LONG_MIN -#define NSUIntegerMax ULONG_MAX - -#define NSINTEGER_DEFINED 1 - -#ifndef NS_DESIGNATED_INITIALIZER -#if __has_attribute(objc_designated_initializer) -#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) -#else -#define NS_DESIGNATED_INITIALIZER -#endif -#endif - -#endif diff --git a/objc/objc-runtime/runtime/NSObject.h b/objc/objc-runtime/runtime/NSObject.h deleted file mode 100644 index efce452..0000000 --- a/objc/objc-runtime/runtime/NSObject.h +++ /dev/null @@ -1,109 +0,0 @@ -/* NSObject.h - Copyright (c) 1994-2012, Apple Inc. All rights reserved. -*/ - -#ifndef _OBJC_NSOBJECT_H_ -#define _OBJC_NSOBJECT_H_ - -#if __OBJC__ - -#include <objc/objc.h> -#include <objc/NSObjCRuntime.h> - -@class NSString, NSMethodSignature, NSInvocation; - -@protocol NSObject - -- (BOOL)isEqual:(id)object; -@property (readonly) NSUInteger hash; - -@property (readonly) Class superclass; -- (Class)class OBJC_SWIFT_UNAVAILABLE("use 'anObject.dynamicType' instead"); -- (instancetype)self; - -- (id)performSelector:(SEL)aSelector; -- (id)performSelector:(SEL)aSelector withObject:(id)object; -- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2; - -- (BOOL)isProxy; - -- (BOOL)isKindOfClass:(Class)aClass; -- (BOOL)isMemberOfClass:(Class)aClass; -- (BOOL)conformsToProtocol:(Protocol *)aProtocol; - -- (BOOL)respondsToSelector:(SEL)aSelector; - -- (instancetype)retain OBJC_ARC_UNAVAILABLE; -- (oneway void)release OBJC_ARC_UNAVAILABLE; -- (instancetype)autorelease OBJC_ARC_UNAVAILABLE; -- (NSUInteger)retainCount OBJC_ARC_UNAVAILABLE; - -- (struct _NSZone *)zone OBJC_ARC_UNAVAILABLE; - -@property (readonly, copy) NSString *description; -@optional -@property (readonly, copy) NSString *debugDescription; - -@end - - -__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) -OBJC_ROOT_CLASS -OBJC_EXPORT -@interface NSObject <NSObject> { - Class isa OBJC_ISA_AVAILABILITY; -} - -+ (void)load; - -+ (void)initialize; -- (instancetype)init -#if NS_ENFORCE_NSOBJECT_DESIGNATED_INITIALIZER - NS_DESIGNATED_INITIALIZER -#endif - ; - -+ (instancetype)new OBJC_SWIFT_UNAVAILABLE("use object initializers instead"); -+ (instancetype)allocWithZone:(struct _NSZone *)zone OBJC_SWIFT_UNAVAILABLE("use object initializers instead"); -+ (instancetype)alloc OBJC_SWIFT_UNAVAILABLE("use object initializers instead"); -- (void)dealloc OBJC_SWIFT_UNAVAILABLE("use 'deinit' to define a de-initializer"); - -- (void)finalize; - -- (id)copy; -- (id)mutableCopy; - -+ (id)copyWithZone:(struct _NSZone *)zone OBJC_ARC_UNAVAILABLE; -+ (id)mutableCopyWithZone:(struct _NSZone *)zone OBJC_ARC_UNAVAILABLE; - -+ (BOOL)instancesRespondToSelector:(SEL)aSelector; -+ (BOOL)conformsToProtocol:(Protocol *)protocol; -- (IMP)methodForSelector:(SEL)aSelector; -+ (IMP)instanceMethodForSelector:(SEL)aSelector; -- (void)doesNotRecognizeSelector:(SEL)aSelector; - -- (id)forwardingTargetForSelector:(SEL)aSelector __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -- (void)forwardInvocation:(NSInvocation *)anInvocation OBJC_SWIFT_UNAVAILABLE(""); -- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector OBJC_SWIFT_UNAVAILABLE(""); - -+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector OBJC_SWIFT_UNAVAILABLE(""); - -- (BOOL)allowsWeakReference UNAVAILABLE_ATTRIBUTE; -- (BOOL)retainWeakReference UNAVAILABLE_ATTRIBUTE; - -+ (BOOL)isSubclassOfClass:(Class)aClass; - -+ (BOOL)resolveClassMethod:(SEL)sel __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -+ (BOOL)resolveInstanceMethod:(SEL)sel __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -+ (NSUInteger)hash; -+ (Class)superclass; -+ (Class)class OBJC_SWIFT_UNAVAILABLE("use 'aClass.self' instead"); -+ (NSString *)description; -+ (NSString *)debugDescription; - -@end - -#endif - -#endif diff --git a/objc/objc-runtime/runtime/NSObject.mm b/objc/objc-runtime/runtime/NSObject.mm deleted file mode 100644 index c964cb8..0000000 --- a/objc/objc-runtime/runtime/NSObject.mm +++ /dev/null @@ -1,2272 +0,0 @@ -/* - * Copyright (c) 2010-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 "objc-private.h" -#include "NSObject.h" - -#include "objc-weak.h" -#include "llvm-DenseMap.h" -#include "NSObject.h" - -#include <malloc/malloc.h> -#include <stdint.h> -#include <stdbool.h> -#include <mach/mach.h> -#include <mach-o/dyld.h> -#include <mach-o/nlist.h> -#include <sys/types.h> -#include <sys/mman.h> -#include <libkern/OSAtomic.h> -#include <Block.h> -#include <map> -#include <execinfo.h> - -@interface NSInvocation -- (SEL)selector; -@end - - -#if TARGET_OS_MAC - -// NSObject used to be in Foundation/CoreFoundation. - -#define SYMBOL_ELSEWHERE_IN_3(sym, vers, n) \ - OBJC_EXPORT const char elsewhere_ ##n __asm__("$ld$hide$os" #vers "$" #sym); const char elsewhere_ ##n = 0 -#define SYMBOL_ELSEWHERE_IN_2(sym, vers, n) \ - SYMBOL_ELSEWHERE_IN_3(sym, vers, n) -#define SYMBOL_ELSEWHERE_IN(sym, vers) \ - SYMBOL_ELSEWHERE_IN_2(sym, vers, __COUNTER__) - -#if __OBJC2__ -# define NSOBJECT_ELSEWHERE_IN(vers) \ - SYMBOL_ELSEWHERE_IN(_OBJC_CLASS_$_NSObject, vers); \ - SYMBOL_ELSEWHERE_IN(_OBJC_METACLASS_$_NSObject, vers); \ - SYMBOL_ELSEWHERE_IN(_OBJC_IVAR_$_NSObject.isa, vers) -#else -# define NSOBJECT_ELSEWHERE_IN(vers) \ - SYMBOL_ELSEWHERE_IN(.objc_class_name_NSObject, vers) -#endif - -#if TARGET_OS_IOS - NSOBJECT_ELSEWHERE_IN(5.1); - NSOBJECT_ELSEWHERE_IN(5.0); - NSOBJECT_ELSEWHERE_IN(4.3); - NSOBJECT_ELSEWHERE_IN(4.2); - NSOBJECT_ELSEWHERE_IN(4.1); - NSOBJECT_ELSEWHERE_IN(4.0); - NSOBJECT_ELSEWHERE_IN(3.2); - NSOBJECT_ELSEWHERE_IN(3.1); - NSOBJECT_ELSEWHERE_IN(3.0); - NSOBJECT_ELSEWHERE_IN(2.2); - NSOBJECT_ELSEWHERE_IN(2.1); - NSOBJECT_ELSEWHERE_IN(2.0); -#elif TARGET_OS_MAC && !TARGET_OS_IPHONE - NSOBJECT_ELSEWHERE_IN(10.7); - NSOBJECT_ELSEWHERE_IN(10.6); - NSOBJECT_ELSEWHERE_IN(10.5); - NSOBJECT_ELSEWHERE_IN(10.4); - NSOBJECT_ELSEWHERE_IN(10.3); - NSOBJECT_ELSEWHERE_IN(10.2); - NSOBJECT_ELSEWHERE_IN(10.1); - NSOBJECT_ELSEWHERE_IN(10.0); -#else - // NSObject has always been in libobjc on these platforms. -#endif - -// TARGET_OS_MAC -#endif - - -/*********************************************************************** -* Weak ivar support -**********************************************************************/ - -static id defaultBadAllocHandler(Class cls) -{ - _objc_fatal("attempt to allocate object of class '%s' failed", - cls->nameForLogging()); -} - -static id(*badAllocHandler)(Class) = &defaultBadAllocHandler; - -static id callBadAllocHandler(Class cls) -{ - // fixme add re-entrancy protection in case allocation fails inside handler - return (*badAllocHandler)(cls); -} - -void _objc_setBadAllocHandler(id(*newHandler)(Class)) -{ - badAllocHandler = newHandler; -} - - -namespace { - -// The order of these bits is important. -#define SIDE_TABLE_WEAKLY_REFERENCED (1UL<<0) -#define SIDE_TABLE_DEALLOCATING (1UL<<1) // MSB-ward of weak bit -#define SIDE_TABLE_RC_ONE (1UL<<2) // MSB-ward of deallocating bit -#define SIDE_TABLE_RC_PINNED (1UL<<(WORD_BITS-1)) - -#define SIDE_TABLE_RC_SHIFT 2 -#define SIDE_TABLE_FLAG_MASK (SIDE_TABLE_RC_ONE-1) - -// RefcountMap disguises its pointers because we -// don't want the table to act as a root for `leaks`. -typedef objc::DenseMap<DisguisedPtr<objc_object>,size_t,true> RefcountMap; - -struct SideTable { - spinlock_t slock; - RefcountMap refcnts; - weak_table_t weak_table; - - SideTable() { - memset(&weak_table, 0, sizeof(weak_table)); - } - - ~SideTable() { - _objc_fatal("Do not delete SideTable."); - } - - void lock() { slock.lock(); } - void unlock() { slock.unlock(); } - bool trylock() { return slock.trylock(); } - - // Address-ordered lock discipline for a pair of side tables. - - template<bool HaveOld, bool HaveNew> - static void lockTwo(SideTable *lock1, SideTable *lock2); - template<bool HaveOld, bool HaveNew> - static void unlockTwo(SideTable *lock1, SideTable *lock2); -}; - - -template<> -void SideTable::lockTwo<true, true>(SideTable *lock1, SideTable *lock2) { - spinlock_t::lockTwo(&lock1->slock, &lock2->slock); -} - -template<> -void SideTable::lockTwo<true, false>(SideTable *lock1, SideTable *) { - lock1->lock(); -} - -template<> -void SideTable::lockTwo<false, true>(SideTable *, SideTable *lock2) { - lock2->lock(); -} - -template<> -void SideTable::unlockTwo<true, true>(SideTable *lock1, SideTable *lock2) { - spinlock_t::unlockTwo(&lock1->slock, &lock2->slock); -} - -template<> -void SideTable::unlockTwo<true, false>(SideTable *lock1, SideTable *) { - lock1->unlock(); -} - -template<> -void SideTable::unlockTwo<false, true>(SideTable *, SideTable *lock2) { - lock2->unlock(); -} - - - -// We cannot use a C++ static initializer to initialize SideTables because -// libc calls us before our C++ initializers run. We also don't want a global -// pointer to this struct because of the extra indirection. -// Do it the hard way. -alignas(sizeof(StripedMap<SideTable>)) static uint8_t - SideTableBuf[sizeof(StripedMap<SideTable>)]; - -static void SideTableInit() { - new (SideTableBuf) StripedMap<SideTable>(); -} - -static StripedMap<SideTable>& SideTables() { - return *reinterpret_cast<StripedMap<SideTable>*>(SideTableBuf); -} - -// anonymous namespace -}; - - -// -// The -fobjc-arc flag causes the compiler to issue calls to objc_{retain/release/autorelease/retain_block} -// - -id objc_retainBlock(id x) { - return (id)_Block_copy(x); -} - -// -// The following SHOULD be called by the compiler directly, but the request hasn't been made yet :-) -// - -BOOL objc_should_deallocate(id object) { - return YES; -} - -id -objc_retain_autorelease(id obj) -{ - return objc_autorelease(objc_retain(obj)); -} - - -void -objc_storeStrong(id *location, id obj) -{ - id prev = *location; - if (obj == prev) { - return; - } - objc_retain(obj); - *location = obj; - objc_release(prev); -} - - -// Update a weak variable. -// If HaveOld is true, the variable has an existing value -// that needs to be cleaned up. This value might be nil. -// If HaveNew is true, there is a new value that needs to be -// assigned into the variable. This value might be nil. -// If CrashIfDeallocating is true, the process is halted if newObj is -// deallocating or newObj's class does not support weak references. -// If CrashIfDeallocating is false, nil is stored instead. -template <bool HaveOld, bool HaveNew, bool CrashIfDeallocating> -static id -storeWeak(id *location, objc_object *newObj) -{ - assert(HaveOld || HaveNew); - if (!HaveNew) assert(newObj == nil); - - Class previouslyInitializedClass = nil; - id oldObj; - SideTable *oldTable; - SideTable *newTable; - - // Acquire locks for old and new values. - // Order by lock address to prevent lock ordering problems. - // Retry if the old value changes underneath us. - retry: - if (HaveOld) { - oldObj = *location; - oldTable = &SideTables()[oldObj]; - } else { - oldTable = nil; - } - if (HaveNew) { - newTable = &SideTables()[newObj]; - } else { - newTable = nil; - } - - SideTable::lockTwo<HaveOld, HaveNew>(oldTable, newTable); - - if (HaveOld && *location != oldObj) { - SideTable::unlockTwo<HaveOld, HaveNew>(oldTable, newTable); - goto retry; - } - - // Prevent a deadlock between the weak reference machinery - // and the +initialize machinery by ensuring that no - // weakly-referenced object has an un-+initialized isa. - if (HaveNew && newObj) { - Class cls = newObj->getIsa(); - if (cls != previouslyInitializedClass && - !((objc_class *)cls)->isInitialized()) - { - SideTable::unlockTwo<HaveOld, HaveNew>(oldTable, newTable); - _class_initialize(_class_getNonMetaClass(cls, (id)newObj)); - - // If this class is finished with +initialize then we're good. - // If this class is still running +initialize on this thread - // (i.e. +initialize called storeWeak on an instance of itself) - // then we may proceed but it will appear initializing and - // not yet initialized to the check above. - // Instead set previouslyInitializedClass to recognize it on retry. - previouslyInitializedClass = cls; - - goto retry; - } - } - - // Clean up old value, if any. - if (HaveOld) { - weak_unregister_no_lock(&oldTable->weak_table, oldObj, location); - } - - // Assign new value, if any. - if (HaveNew) { - newObj = (objc_object *)weak_register_no_lock(&newTable->weak_table, - (id)newObj, location, - CrashIfDeallocating); - // weak_register_no_lock returns nil if weak store should be rejected - - // Set is-weakly-referenced bit in refcount table. - if (newObj && !newObj->isTaggedPointer()) { - newObj->setWeaklyReferenced_nolock(); - } - - // Do not set *location anywhere else. That would introduce a race. - *location = (id)newObj; - } - else { - // No new value. The storage is not changed. - } - - SideTable::unlockTwo<HaveOld, HaveNew>(oldTable, newTable); - - return (id)newObj; -} - - -/** - * This function stores a new value into a __weak variable. It would - * be used anywhere a __weak variable is the target of an assignment. - * - * @param location The address of the weak pointer itself - * @param newObj The new object this weak ptr should now point to - * - * @return \e newObj - */ -id -objc_storeWeak(id *location, id newObj) -{ - return storeWeak<true/*old*/, true/*new*/, true/*crash*/> - (location, (objc_object *)newObj); -} - - -/** - * This function stores a new value into a __weak variable. - * If the new object is deallocating or the new object's class - * does not support weak references, stores nil instead. - * - * @param location The address of the weak pointer itself - * @param newObj The new object this weak ptr should now point to - * - * @return The value stored (either the new object or nil) - */ -id -objc_storeWeakOrNil(id *location, id newObj) -{ - return storeWeak<true/*old*/, true/*new*/, false/*crash*/> - (location, (objc_object *)newObj); -} - - -/** - * Initialize a fresh weak pointer to some object location. - * It would be used for code like: - * - * (The nil case) - * __weak id weakPtr; - * (The non-nil case) - * NSObject *o = ...; - * __weak id weakPtr = o; - * - * This function IS NOT thread-safe with respect to concurrent - * modifications to the weak variable. (Concurrent weak clear is safe.) - * - * @param location Address of __weak ptr. - * @param newObj Object ptr. - */ -id -objc_initWeak(id *location, id newObj) -{ - if (!newObj) { - *location = nil; - return nil; - } - - return storeWeak<false/*old*/, true/*new*/, true/*crash*/> - (location, (objc_object*)newObj); -} - -id -objc_initWeakOrNil(id *location, id newObj) -{ - if (!newObj) { - *location = nil; - return nil; - } - - return storeWeak<false/*old*/, true/*new*/, false/*crash*/> - (location, (objc_object*)newObj); -} - - -/** - * Destroys the relationship between a weak pointer - * and the object it is referencing in the internal weak - * table. If the weak pointer is not referencing anything, - * there is no need to edit the weak table. - * - * This function IS NOT thread-safe with respect to concurrent - * modifications to the weak variable. (Concurrent weak clear is safe.) - * - * @param location The weak pointer address. - */ -void -objc_destroyWeak(id *location) -{ - (void)storeWeak<true/*old*/, false/*new*/, false/*crash*/> - (location, nil); -} - - -id -objc_loadWeakRetained(id *location) -{ - id result; - - SideTable *table; - - retry: - result = *location; - if (!result) return nil; - - table = &SideTables()[result]; - - table->lock(); - if (*location != result) { - table->unlock(); - goto retry; - } - - result = weak_read_no_lock(&table->weak_table, location); - - table->unlock(); - return result; -} - -/** - * This loads the object referenced by a weak pointer and returns it, after - * retaining and autoreleasing the object to ensure that it stays alive - * long enough for the caller to use it. This function would be used - * anywhere a __weak variable is used in an expression. - * - * @param location The weak pointer address - * - * @return The object pointed to by \e location, or \c nil if \e location is \c nil. - */ -id -objc_loadWeak(id *location) -{ - if (!*location) return nil; - return objc_autorelease(objc_loadWeakRetained(location)); -} - - -/** - * This function copies a weak pointer from one location to another, - * when the destination doesn't already contain a weak pointer. It - * would be used for code like: - * - * __weak id src = ...; - * __weak id dst = src; - * - * This function IS NOT thread-safe with respect to concurrent - * modifications to the destination variable. (Concurrent weak clear is safe.) - * - * @param dst The destination variable. - * @param src The source variable. - */ -void -objc_copyWeak(id *dst, id *src) -{ - id obj = objc_loadWeakRetained(src); - objc_initWeak(dst, obj); - objc_release(obj); -} - -/** - * Move a weak pointer from one location to another. - * Before the move, the destination must be uninitialized. - * After the move, the source is nil. - * - * This function IS NOT thread-safe with respect to concurrent - * modifications to either weak variable. (Concurrent weak clear is safe.) - * - */ -void -objc_moveWeak(id *dst, id *src) -{ - objc_copyWeak(dst, src); - objc_destroyWeak(src); - *src = nil; -} - - -/*********************************************************************** - Autorelease pool implementation - - A thread's autorelease pool is a stack of pointers. - Each pointer is either an object to release, or POOL_SENTINEL which is - an autorelease pool boundary. - A pool token is a pointer to the POOL_SENTINEL for that pool. When - the pool is popped, every object hotter than the sentinel is released. - The stack is divided into a doubly-linked list of pages. Pages are added - and deleted as necessary. - Thread-local storage points to the hot page, where newly autoreleased - objects are stored. -**********************************************************************/ - -BREAKPOINT_FUNCTION(void objc_autoreleaseNoPool(id obj)); - -namespace { - -struct magic_t { - static const uint32_t M0 = 0xA1A1A1A1; -# define M1 "AUTORELEASE!" - static const size_t M1_len = 12; - uint32_t m[4]; - - magic_t() { - assert(M1_len == strlen(M1)); - assert(M1_len == 3 * sizeof(m[1])); - - m[0] = M0; - strncpy((char *)&m[1], M1, M1_len); - } - - ~magic_t() { - m[0] = m[1] = m[2] = m[3] = 0; - } - - bool check() const { - return (m[0] == M0 && 0 == strncmp((char *)&m[1], M1, M1_len)); - } - - bool fastcheck() const { -#if DEBUG - return check(); -#else - return (m[0] == M0); -#endif - } - -# undef M1 -}; - - -// Set this to 1 to mprotect() autorelease pool contents -#define PROTECT_AUTORELEASEPOOL 0 - -class AutoreleasePoolPage -{ - -#define POOL_SENTINEL nil - static pthread_key_t const key = AUTORELEASE_POOL_KEY; - static uint8_t const SCRIBBLE = 0xA3; // 0xA3A3A3A3 after releasing - static size_t const SIZE = -#if PROTECT_AUTORELEASEPOOL - PAGE_MAX_SIZE; // must be multiple of vm page size -#else - PAGE_MAX_SIZE; // size and alignment, power of 2 -#endif - static size_t const COUNT = SIZE / sizeof(id); - - magic_t const magic; - id *next; - pthread_t const thread; - AutoreleasePoolPage * const parent; - AutoreleasePoolPage *child; - uint32_t const depth; - uint32_t hiwat; - - // SIZE-sizeof(*this) bytes of contents follow - - static void * operator new(size_t size) { - return malloc_zone_memalign(malloc_default_zone(), SIZE, SIZE); - } - static void operator delete(void * p) { - return free(p); - } - - inline void protect() { -#if PROTECT_AUTORELEASEPOOL - mprotect(this, SIZE, PROT_READ); - check(); -#endif - } - - inline void unprotect() { -#if PROTECT_AUTORELEASEPOOL - check(); - mprotect(this, SIZE, PROT_READ | PROT_WRITE); -#endif - } - - AutoreleasePoolPage(AutoreleasePoolPage *newParent) - : magic(), next(begin()), thread(pthread_self()), - parent(newParent), child(nil), - depth(parent ? 1+parent->depth : 0), - hiwat(parent ? parent->hiwat : 0) - { - if (parent) { - parent->check(); - assert(!parent->child); - parent->unprotect(); - parent->child = this; - parent->protect(); - } - protect(); - } - - ~AutoreleasePoolPage() - { - check(); - unprotect(); - assert(empty()); - - // Not recursive: we don't want to blow out the stack - // if a thread accumulates a stupendous amount of garbage - assert(!child); - } - - - void busted(bool die = true) - { - magic_t right; - (die ? _objc_fatal : _objc_inform) - ("autorelease pool page %p corrupted\n" - " magic 0x%08x 0x%08x 0x%08x 0x%08x\n" - " should be 0x%08x 0x%08x 0x%08x 0x%08x\n" - " pthread %p\n" - " should be %p\n", - this, - magic.m[0], magic.m[1], magic.m[2], magic.m[3], - right.m[0], right.m[1], right.m[2], right.m[3], - this->thread, pthread_self()); - } - - void check(bool die = true) - { - if (!magic.check() || !pthread_equal(thread, pthread_self())) { - busted(die); - } - } - - void fastcheck(bool die = true) - { - if (! magic.fastcheck()) { - busted(die); - } - } - - - id * begin() { - return (id *) ((uint8_t *)this+sizeof(*this)); - } - - id * end() { - return (id *) ((uint8_t *)this+SIZE); - } - - bool empty() { - return next == begin(); - } - - bool full() { - return next == end(); - } - - bool lessThanHalfFull() { - return (next - begin() < (end() - begin()) / 2); - } - - id *add(id obj) - { - assert(!full()); - unprotect(); - id *ret = next; // faster than `return next-1` because of aliasing - *next++ = obj; - protect(); - return ret; - } - - void releaseAll() - { - releaseUntil(begin()); - } - - void releaseUntil(id *stop) - { - // Not recursive: we don't want to blow out the stack - // if a thread accumulates a stupendous amount of garbage - - while (this->next != stop) { - // Restart from hotPage() every time, in case -release - // autoreleased more objects - AutoreleasePoolPage *page = hotPage(); - - // fixme I think this `while` can be `if`, but I can't prove it - while (page->empty()) { - page = page->parent; - setHotPage(page); - } - - page->unprotect(); - id obj = *--page->next; - memset((void*)page->next, SCRIBBLE, sizeof(*page->next)); - page->protect(); - - if (obj != POOL_SENTINEL) { - objc_release(obj); - } - } - - setHotPage(this); - -#if DEBUG - // we expect any children to be completely empty - for (AutoreleasePoolPage *page = child; page; page = page->child) { - assert(page->empty()); - } -#endif - } - - void kill() - { - // Not recursive: we don't want to blow out the stack - // if a thread accumulates a stupendous amount of garbage - AutoreleasePoolPage *page = this; - while (page->child) page = page->child; - - AutoreleasePoolPage *deathptr; - do { - deathptr = page; - page = page->parent; - if (page) { - page->unprotect(); - page->child = nil; - page->protect(); - } - delete deathptr; - } while (deathptr != this); - } - - static void tls_dealloc(void *p) - { - // reinstate TLS value while we work - setHotPage((AutoreleasePoolPage *)p); - - if (AutoreleasePoolPage *page = coldPage()) { - if (!page->empty()) pop(page->begin()); // pop all of the pools - if (DebugMissingPools || DebugPoolAllocation) { - // pop() killed the pages already - } else { - page->kill(); // free all of the pages - } - } - - // clear TLS value so TLS destruction doesn't loop - setHotPage(nil); - } - - static AutoreleasePoolPage *pageForPointer(const void *p) - { - return pageForPointer((uintptr_t)p); - } - - static AutoreleasePoolPage *pageForPointer(uintptr_t p) - { - AutoreleasePoolPage *result; - uintptr_t offset = p % SIZE; - - assert(offset >= sizeof(AutoreleasePoolPage)); - - result = (AutoreleasePoolPage *)(p - offset); - result->fastcheck(); - - return result; - } - - - static inline AutoreleasePoolPage *hotPage() - { - AutoreleasePoolPage *result = (AutoreleasePoolPage *) - tls_get_direct(key); - if (result) result->fastcheck(); - return result; - } - - static inline void setHotPage(AutoreleasePoolPage *page) - { - if (page) page->fastcheck(); - tls_set_direct(key, (void *)page); - } - - static inline AutoreleasePoolPage *coldPage() - { - AutoreleasePoolPage *result = hotPage(); - if (result) { - while (result->parent) { - result = result->parent; - result->fastcheck(); - } - } - return result; - } - - - static inline id *autoreleaseFast(id obj) - { - AutoreleasePoolPage *page = hotPage(); - if (page && !page->full()) { - return page->add(obj); - } else if (page) { - return autoreleaseFullPage(obj, page); - } else { - return autoreleaseNoPage(obj); - } - } - - static __attribute__((noinline)) - id *autoreleaseFullPage(id obj, AutoreleasePoolPage *page) - { - // The hot page is full. - // Step to the next non-full page, adding a new page if necessary. - // Then add the object to that page. - assert(page == hotPage()); - assert(page->full() || DebugPoolAllocation); - - do { - if (page->child) page = page->child; - else page = new AutoreleasePoolPage(page); - } while (page->full()); - - setHotPage(page); - return page->add(obj); - } - - static __attribute__((noinline)) - id *autoreleaseNoPage(id obj) - { - // No pool in place. - assert(!hotPage()); - - if (obj != POOL_SENTINEL && DebugMissingPools) { - // We are pushing an object with no pool in place, - // and no-pool debugging was requested by environment. - _objc_inform("MISSING POOLS: Object %p of class %s " - "autoreleased with no pool in place - " - "just leaking - break on " - "objc_autoreleaseNoPool() to debug", - (void*)obj, object_getClassName(obj)); - objc_autoreleaseNoPool(obj); - return nil; - } - - // Install the first page. - AutoreleasePoolPage *page = new AutoreleasePoolPage(nil); - setHotPage(page); - - // Push an autorelease pool boundary if it wasn't already requested. - if (obj != POOL_SENTINEL) { - page->add(POOL_SENTINEL); - } - - // Push the requested object. - return page->add(obj); - } - - - static __attribute__((noinline)) - id *autoreleaseNewPage(id obj) - { - AutoreleasePoolPage *page = hotPage(); - if (page) return autoreleaseFullPage(obj, page); - else return autoreleaseNoPage(obj); - } - -public: - static inline id autorelease(id obj) - { - assert(obj); - assert(!obj->isTaggedPointer()); - id *dest __unused = autoreleaseFast(obj); - assert(!dest || *dest == obj); - return obj; - } - - - static inline void *push() - { - id *dest; - if (DebugPoolAllocation) { - // Each autorelease pool starts on a new pool page. - dest = autoreleaseNewPage(POOL_SENTINEL); - } else { - dest = autoreleaseFast(POOL_SENTINEL); - } - assert(*dest == POOL_SENTINEL); - return dest; - } - - static inline void pop(void *token) - { - AutoreleasePoolPage *page; - id *stop; - - page = pageForPointer(token); - stop = (id *)token; - if (DebugPoolAllocation && *stop != POOL_SENTINEL) { - // This check is not valid with DebugPoolAllocation off - // after an autorelease with a pool page but no pool in place. - _objc_fatal("invalid or prematurely-freed autorelease pool %p; ", - token); - } - - if (PrintPoolHiwat) printHiwat(); - - page->releaseUntil(stop); - - // memory: delete empty children - if (DebugPoolAllocation && page->empty()) { - // special case: delete everything during page-per-pool debugging - AutoreleasePoolPage *parent = page->parent; - page->kill(); - setHotPage(parent); - } else if (DebugMissingPools && page->empty() && !page->parent) { - // special case: delete everything for pop(top) - // when debugging missing autorelease pools - page->kill(); - setHotPage(nil); - } - else if (page->child) { - // hysteresis: keep one empty child if page is more than half full - if (page->lessThanHalfFull()) { - page->child->kill(); - } - else if (page->child->child) { - page->child->child->kill(); - } - } - } - - static void init() - { - int r __unused = pthread_key_init_np(AutoreleasePoolPage::key, - AutoreleasePoolPage::tls_dealloc); - assert(r == 0); - } - - void print() - { - _objc_inform("[%p] ................ PAGE %s %s %s", this, - full() ? "(full)" : "", - this == hotPage() ? "(hot)" : "", - this == coldPage() ? "(cold)" : ""); - check(false); - for (id *p = begin(); p < next; p++) { - if (*p == POOL_SENTINEL) { - _objc_inform("[%p] ################ POOL %p", p, p); - } else { - _objc_inform("[%p] %#16lx %s", - p, (unsigned long)*p, object_getClassName(*p)); - } - } - } - - static void printAll() - { - _objc_inform("##############"); - _objc_inform("AUTORELEASE POOLS for thread %p", pthread_self()); - - AutoreleasePoolPage *page; - ptrdiff_t objects = 0; - for (page = coldPage(); page; page = page->child) { - objects += page->next - page->begin(); - } - _objc_inform("%llu releases pending.", (unsigned long long)objects); - - for (page = coldPage(); page; page = page->child) { - page->print(); - } - - _objc_inform("##############"); - } - - static void printHiwat() - { - // Check and propagate high water mark - // Ignore high water marks under 256 to suppress noise. - AutoreleasePoolPage *p = hotPage(); - uint32_t mark = p->depth*COUNT + (uint32_t)(p->next - p->begin()); - if (mark > p->hiwat && mark > 256) { - for( ; p; p = p->parent) { - p->unprotect(); - p->hiwat = mark; - p->protect(); - } - - _objc_inform("POOL HIGHWATER: new high water mark of %u " - "pending autoreleases for thread %p:", - mark, pthread_self()); - - void *stack[128]; - int count = backtrace(stack, sizeof(stack)/sizeof(stack[0])); - char **sym = backtrace_symbols(stack, count); - for (int i = 0; i < count; i++) { - _objc_inform("POOL HIGHWATER: %s", sym[i]); - } - free(sym); - } - } - -#undef POOL_SENTINEL -}; - -// anonymous namespace -}; - - -/*********************************************************************** -* Slow paths for inline control -**********************************************************************/ - -#if SUPPORT_NONPOINTER_ISA - -NEVER_INLINE id -objc_object::rootRetain_overflow(bool tryRetain) -{ - return rootRetain(tryRetain, true); -} - - -NEVER_INLINE bool -objc_object::rootRelease_underflow(bool performDealloc) -{ - return rootRelease(performDealloc, true); -} - - -// Slow path of clearDeallocating() -// for objects with indexed isa -// that were ever weakly referenced -// or whose retain count ever overflowed to the side table. -NEVER_INLINE void -objc_object::clearDeallocating_slow() -{ - assert(isa.indexed && (isa.weakly_referenced || isa.has_sidetable_rc)); - - SideTable& table = SideTables()[this]; - table.lock(); - if (isa.weakly_referenced) { - weak_clear_no_lock(&table.weak_table, (id)this); - } - if (isa.has_sidetable_rc) { - table.refcnts.erase(this); - } - table.unlock(); -} - -#endif - -__attribute__((noinline,used)) -id -objc_object::rootAutorelease2() -{ - assert(!isTaggedPointer()); - return AutoreleasePoolPage::autorelease((id)this); -} - - -BREAKPOINT_FUNCTION( - void objc_overrelease_during_dealloc_error(void) -); - - -NEVER_INLINE -bool -objc_object::overrelease_error() -{ - _objc_inform_now_and_on_crash("%s object %p overreleased while already deallocating; break on objc_overrelease_during_dealloc_error to debug", object_getClassName((id)this), this); - objc_overrelease_during_dealloc_error(); - return false; // allow rootRelease() to tail-call this -} - - -/*********************************************************************** -* Retain count operations for side table. -**********************************************************************/ - - -#if DEBUG -// Used to assert that an object is not present in the side table. -bool -objc_object::sidetable_present() -{ - bool result = false; - SideTable& table = SideTables()[this]; - - table.lock(); - - RefcountMap::iterator it = table.refcnts.find(this); - if (it != table.refcnts.end()) result = true; - - if (weak_is_registered_no_lock(&table.weak_table, (id)this)) result = true; - - table.unlock(); - - return result; -} -#endif - -#if SUPPORT_NONPOINTER_ISA - -void -objc_object::sidetable_lock() -{ - SideTable& table = SideTables()[this]; - table.lock(); -} - -void -objc_object::sidetable_unlock() -{ - SideTable& table = SideTables()[this]; - table.unlock(); -} - - -// Move the entire retain count to the side table, -// as well as isDeallocating and weaklyReferenced. -void -objc_object::sidetable_moveExtraRC_nolock(size_t extra_rc, - bool isDeallocating, - bool weaklyReferenced) -{ - assert(!isa.indexed); // should already be changed to not-indexed - SideTable& table = SideTables()[this]; - - size_t& refcntStorage = table.refcnts[this]; - size_t oldRefcnt = refcntStorage; - // not deallocating - that was in the isa - assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0); - assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0); - - uintptr_t carry; - size_t refcnt = addc(oldRefcnt, extra_rc << SIDE_TABLE_RC_SHIFT, 0, &carry); - if (carry) refcnt = SIDE_TABLE_RC_PINNED; - if (isDeallocating) refcnt |= SIDE_TABLE_DEALLOCATING; - if (weaklyReferenced) refcnt |= SIDE_TABLE_WEAKLY_REFERENCED; - - refcntStorage = refcnt; -} - - -// Move some retain counts to the side table from the isa field. -// Returns true if the object is now pinned. -bool -objc_object::sidetable_addExtraRC_nolock(size_t delta_rc) -{ - assert(isa.indexed); - SideTable& table = SideTables()[this]; - - size_t& refcntStorage = table.refcnts[this]; - size_t oldRefcnt = refcntStorage; - // isa-side bits should not be set here - assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0); - assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0); - - if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true; - - uintptr_t carry; - size_t newRefcnt = - addc(oldRefcnt, delta_rc << SIDE_TABLE_RC_SHIFT, 0, &carry); - if (carry) { - refcntStorage = - SIDE_TABLE_RC_PINNED | (oldRefcnt & SIDE_TABLE_FLAG_MASK); - return true; - } - else { - refcntStorage = newRefcnt; - return false; - } -} - - -// Move some retain counts from the side table to the isa field. -// Returns the actual count subtracted, which may be less than the request. -size_t -objc_object::sidetable_subExtraRC_nolock(size_t delta_rc) -{ - assert(isa.indexed); - SideTable& table = SideTables()[this]; - - RefcountMap::iterator it = table.refcnts.find(this); - if (it == table.refcnts.end() || it->second == 0) { - // Side table retain count is zero. Can't borrow. - return 0; - } - size_t oldRefcnt = it->second; - - // isa-side bits should not be set here - assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0); - assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0); - - size_t newRefcnt = oldRefcnt - (delta_rc << SIDE_TABLE_RC_SHIFT); - assert(oldRefcnt > newRefcnt); // shouldn't underflow - it->second = newRefcnt; - return delta_rc; -} - - -size_t -objc_object::sidetable_getExtraRC_nolock() -{ - assert(isa.indexed); - SideTable& table = SideTables()[this]; - RefcountMap::iterator it = table.refcnts.find(this); - if (it == table.refcnts.end()) return 0; - else return it->second >> SIDE_TABLE_RC_SHIFT; -} - - -// SUPPORT_NONPOINTER_ISA -#endif - - -__attribute__((used,noinline,nothrow)) -id -objc_object::sidetable_retain_slow(SideTable& table) -{ -#if SUPPORT_NONPOINTER_ISA - assert(!isa.indexed); -#endif - - table.lock(); - size_t& refcntStorage = table.refcnts[this]; - if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) { - refcntStorage += SIDE_TABLE_RC_ONE; - } - table.unlock(); - - return (id)this; -} - - -id -objc_object::sidetable_retain() -{ -#if SUPPORT_NONPOINTER_ISA - assert(!isa.indexed); -#endif - SideTable& table = SideTables()[this]; - - if (table.trylock()) { - size_t& refcntStorage = table.refcnts[this]; - if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) { - refcntStorage += SIDE_TABLE_RC_ONE; - } - table.unlock(); - return (id)this; - } - return sidetable_retain_slow(table); -} - - -bool -objc_object::sidetable_tryRetain() -{ -#if SUPPORT_NONPOINTER_ISA - assert(!isa.indexed); -#endif - SideTable& table = SideTables()[this]; - - // NO SPINLOCK HERE - // _objc_rootTryRetain() is called exclusively by _objc_loadWeak(), - // which already acquired the lock on our behalf. - - // fixme can't do this efficiently with os_lock_handoff_s - // if (table.slock == 0) { - // _objc_fatal("Do not call -_tryRetain."); - // } - - bool result = true; - RefcountMap::iterator it = table.refcnts.find(this); - if (it == table.refcnts.end()) { - table.refcnts[this] = SIDE_TABLE_RC_ONE; - } else if (it->second & SIDE_TABLE_DEALLOCATING) { - result = false; - } else if (! (it->second & SIDE_TABLE_RC_PINNED)) { - it->second += SIDE_TABLE_RC_ONE; - } - - return result; -} - - -uintptr_t -objc_object::sidetable_retainCount() -{ - SideTable& table = SideTables()[this]; - - size_t refcnt_result = 1; - - table.lock(); - RefcountMap::iterator it = table.refcnts.find(this); - if (it != table.refcnts.end()) { - // this is valid for SIDE_TABLE_RC_PINNED too - refcnt_result += it->second >> SIDE_TABLE_RC_SHIFT; - } - table.unlock(); - return refcnt_result; -} - - -bool -objc_object::sidetable_isDeallocating() -{ - SideTable& table = SideTables()[this]; - - // NO SPINLOCK HERE - // _objc_rootIsDeallocating() is called exclusively by _objc_storeWeak(), - // which already acquired the lock on our behalf. - - - // fixme can't do this efficiently with os_lock_handoff_s - // if (table.slock == 0) { - // _objc_fatal("Do not call -_isDeallocating."); - // } - - RefcountMap::iterator it = table.refcnts.find(this); - return (it != table.refcnts.end()) && (it->second & SIDE_TABLE_DEALLOCATING); -} - - -bool -objc_object::sidetable_isWeaklyReferenced() -{ - bool result = false; - - SideTable& table = SideTables()[this]; - table.lock(); - - RefcountMap::iterator it = table.refcnts.find(this); - if (it != table.refcnts.end()) { - result = it->second & SIDE_TABLE_WEAKLY_REFERENCED; - } - - table.unlock(); - - return result; -} - - -void -objc_object::sidetable_setWeaklyReferenced_nolock() -{ -#if SUPPORT_NONPOINTER_ISA - assert(!isa.indexed); -#endif - - SideTable& table = SideTables()[this]; - - table.refcnts[this] |= SIDE_TABLE_WEAKLY_REFERENCED; -} - - -// rdar://20206767 -// return uintptr_t instead of bool so that the various raw-isa -// -release paths all return zero in eax -__attribute__((used,noinline,nothrow)) -uintptr_t -objc_object::sidetable_release_slow(SideTable& table, bool performDealloc) -{ -#if SUPPORT_NONPOINTER_ISA - assert(!isa.indexed); -#endif - bool do_dealloc = false; - - table.lock(); - RefcountMap::iterator it = table.refcnts.find(this); - if (it == table.refcnts.end()) { - do_dealloc = true; - table.refcnts[this] = SIDE_TABLE_DEALLOCATING; - } else if (it->second < SIDE_TABLE_DEALLOCATING) { - // SIDE_TABLE_WEAKLY_REFERENCED may be set. Don't change it. - do_dealloc = true; - it->second |= SIDE_TABLE_DEALLOCATING; - } else if (! (it->second & SIDE_TABLE_RC_PINNED)) { - it->second -= SIDE_TABLE_RC_ONE; - } - table.unlock(); - if (do_dealloc && performDealloc) { - ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc); - } - return do_dealloc; -} - - -// rdar://20206767 -// return uintptr_t instead of bool so that the various raw-isa -// -release paths all return zero in eax -uintptr_t -objc_object::sidetable_release(bool performDealloc) -{ -#if SUPPORT_NONPOINTER_ISA - assert(!isa.indexed); -#endif - SideTable& table = SideTables()[this]; - - bool do_dealloc = false; - - if (table.trylock()) { - RefcountMap::iterator it = table.refcnts.find(this); - if (it == table.refcnts.end()) { - do_dealloc = true; - table.refcnts[this] = SIDE_TABLE_DEALLOCATING; - } else if (it->second < SIDE_TABLE_DEALLOCATING) { - // SIDE_TABLE_WEAKLY_REFERENCED may be set. Don't change it. - do_dealloc = true; - it->second |= SIDE_TABLE_DEALLOCATING; - } else if (! (it->second & SIDE_TABLE_RC_PINNED)) { - it->second -= SIDE_TABLE_RC_ONE; - } - table.unlock(); - if (do_dealloc && performDealloc) { - ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc); - } - return do_dealloc; - } - - return sidetable_release_slow(table, performDealloc); -} - - -void -objc_object::sidetable_clearDeallocating() -{ - SideTable& table = SideTables()[this]; - - // clear any weak table items - // clear extra retain count and deallocating bit - // (fixme warn or abort if extra retain count == 0 ?) - table.lock(); - RefcountMap::iterator it = table.refcnts.find(this); - if (it != table.refcnts.end()) { - if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) { - weak_clear_no_lock(&table.weak_table, (id)this); - } - table.refcnts.erase(it); - } - table.unlock(); -} - - -/*********************************************************************** -* Optimized retain/release/autorelease entrypoints -**********************************************************************/ - - -#if __OBJC2__ - -__attribute__((aligned(16))) -id -objc_retain(id obj) -{ - if (!obj) return obj; - if (obj->isTaggedPointer()) return obj; - return obj->retain(); -} - - -__attribute__((aligned(16))) -void -objc_release(id obj) -{ - if (!obj) return; - if (obj->isTaggedPointer()) return; - return obj->release(); -} - - -__attribute__((aligned(16))) -id -objc_autorelease(id obj) -{ - if (!obj) return obj; - if (obj->isTaggedPointer()) return obj; - return obj->autorelease(); -} - - -// OBJC2 -#else -// not OBJC2 - - -id objc_retain(id obj) { return [obj retain]; } -void objc_release(id obj) { [obj release]; } -id objc_autorelease(id obj) { return [obj autorelease]; } - - -#endif - - -/*********************************************************************** -* Basic operations for root class implementations a.k.a. _objc_root*() -**********************************************************************/ - -bool -_objc_rootTryRetain(id obj) -{ - assert(obj); - - return obj->rootTryRetain(); -} - -bool -_objc_rootIsDeallocating(id obj) -{ - assert(obj); - - return obj->rootIsDeallocating(); -} - - -void -objc_clear_deallocating(id obj) -{ - assert(obj); - assert(!UseGC); - - if (obj->isTaggedPointer()) return; - obj->clearDeallocating(); -} - - -bool -_objc_rootReleaseWasZero(id obj) -{ - assert(obj); - - return obj->rootReleaseShouldDealloc(); -} - - -id -_objc_rootAutorelease(id obj) -{ - assert(obj); - // assert(!UseGC); - if (UseGC) return obj; // fixme CF calls this when GC is on - - return obj->rootAutorelease(); -} - -uintptr_t -_objc_rootRetainCount(id obj) -{ - assert(obj); - - return obj->rootRetainCount(); -} - - -id -_objc_rootRetain(id obj) -{ - assert(obj); - - return obj->rootRetain(); -} - -void -_objc_rootRelease(id obj) -{ - assert(obj); - - obj->rootRelease(); -} - - -id -_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone) -{ - id obj; - -#if __OBJC2__ - // allocWithZone under __OBJC2__ ignores the zone parameter - (void)zone; - obj = class_createInstance(cls, 0); -#else - if (!zone || UseGC) { - obj = class_createInstance(cls, 0); - } - else { - obj = class_createInstanceFromZone(cls, 0, zone); - } -#endif - - if (!obj) obj = callBadAllocHandler(cls); - return obj; -} - - -// Call [cls alloc] or [cls allocWithZone:nil], with appropriate -// shortcutting optimizations. -static ALWAYS_INLINE id -callAlloc(Class cls, bool checkNil, bool allocWithZone=false) -{ - if (checkNil && !cls) return nil; - -#if __OBJC2__ - if (! cls->ISA()->hasCustomAWZ()) { - // No alloc/allocWithZone implementation. Go straight to the allocator. - // fixme store hasCustomAWZ in the non-meta class and - // add it to canAllocFast's summary - if (cls->canAllocFast()) { - // No ctors, raw isa, etc. Go straight to the metal. - bool dtor = cls->hasCxxDtor(); - id obj = (id)calloc(1, cls->bits.fastInstanceSize()); - if (!obj) return callBadAllocHandler(cls); - obj->initInstanceIsa(cls, dtor); - return obj; - } - else { - // Has ctor or raw isa or something. Use the slower path. - id obj = class_createInstance(cls, 0); - if (!obj) return callBadAllocHandler(cls); - return obj; - } - } -#endif - - // No shortcuts available. - if (allocWithZone) return [cls allocWithZone:nil]; - return [cls alloc]; -} - - -// Base class implementation of +alloc. cls is not nil. -// Calls [cls allocWithZone:nil]. -id -_objc_rootAlloc(Class cls) -{ - return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/); -} - -// Calls [cls alloc]. -id -objc_alloc(Class cls) -{ - return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/); -} - -// Calls [cls allocWithZone:nil]. -id -objc_allocWithZone(Class cls) -{ - return callAlloc(cls, true/*checkNil*/, true/*allocWithZone*/); -} - - -void -_objc_rootDealloc(id obj) -{ - assert(obj); - - obj->rootDealloc(); -} - -void -_objc_rootFinalize(id obj __unused) -{ - assert(obj); - assert(UseGC); - - if (UseGC) { - return; - } - _objc_fatal("_objc_rootFinalize called with garbage collection off"); -} - - -id -_objc_rootInit(id obj) -{ - // In practice, it will be hard to rely on this function. - // Many classes do not properly chain -init calls. - return obj; -} - - -malloc_zone_t * -_objc_rootZone(id obj) -{ - (void)obj; - if (gc_zone) { - return gc_zone; - } -#if __OBJC2__ - // allocWithZone under __OBJC2__ ignores the zone parameter - return malloc_default_zone(); -#else - malloc_zone_t *rval = malloc_zone_from_ptr(obj); - return rval ? rval : malloc_default_zone(); -#endif -} - -uintptr_t -_objc_rootHash(id obj) -{ - if (UseGC) { - return _object_getExternalHash(obj); - } - return (uintptr_t)obj; -} - -void * -objc_autoreleasePoolPush(void) -{ - if (UseGC) return nil; - return AutoreleasePoolPage::push(); -} - -void -objc_autoreleasePoolPop(void *ctxt) -{ - if (UseGC) return; - AutoreleasePoolPage::pop(ctxt); -} - - -void * -_objc_autoreleasePoolPush(void) -{ - return objc_autoreleasePoolPush(); -} - -void -_objc_autoreleasePoolPop(void *ctxt) -{ - objc_autoreleasePoolPop(ctxt); -} - -void -_objc_autoreleasePoolPrint(void) -{ - if (UseGC) return; - AutoreleasePoolPage::printAll(); -} - - -// Same as objc_release but suitable for tail-calling -// if you need the value back and don't want to push a frame before this point. -__attribute__((noinline)) -static id -objc_releaseAndReturn(id obj) -{ - objc_release(obj); - return obj; -} - -// Same as objc_retainAutorelease but suitable for tail-calling -// if you don't want to push a frame before this point. -__attribute__((noinline)) -static id -objc_retainAutoreleaseAndReturn(id obj) -{ - return objc_retainAutorelease(obj); -} - - -// Prepare a value at +1 for return through a +0 autoreleasing convention. -id -objc_autoreleaseReturnValue(id obj) -{ - if (prepareOptimizedReturn(ReturnAtPlus1)) return obj; - - return objc_autorelease(obj); -} - -// Prepare a value at +0 for return through a +0 autoreleasing convention. -id -objc_retainAutoreleaseReturnValue(id obj) -{ - if (prepareOptimizedReturn(ReturnAtPlus0)) return obj; - - // not objc_autoreleaseReturnValue(objc_retain(obj)) - // because we don't need another optimization attempt - return objc_retainAutoreleaseAndReturn(obj); -} - -// Accept a value returned through a +0 autoreleasing convention for use at +1. -id -objc_retainAutoreleasedReturnValue(id obj) -{ - if (acceptOptimizedReturn() == ReturnAtPlus1) return obj; - - return objc_retain(obj); -} - -// Accept a value returned through a +0 autoreleasing convention for use at +0. -id -objc_unsafeClaimAutoreleasedReturnValue(id obj) -{ - if (acceptOptimizedReturn() == ReturnAtPlus0) return obj; - - return objc_releaseAndReturn(obj); -} - -id -objc_retainAutorelease(id obj) -{ - return objc_autorelease(objc_retain(obj)); -} - -void -_objc_deallocOnMainThreadHelper(void *context) -{ - id obj = (id)context; - [obj dealloc]; -} - -#undef objc_retainedObject -#undef objc_unretainedObject -#undef objc_unretainedPointer - -// convert objc_objectptr_t to id, callee must take ownership. -id objc_retainedObject(objc_objectptr_t pointer) { return (id)pointer; } - -// convert objc_objectptr_t to id, without ownership transfer. -id objc_unretainedObject(objc_objectptr_t pointer) { return (id)pointer; } - -// convert id to objc_objectptr_t, no ownership transfer. -objc_objectptr_t objc_unretainedPointer(id object) { return object; } - - -void arr_init(void) -{ - AutoreleasePoolPage::init(); - SideTableInit(); -} - -@implementation NSObject - -+ (void)load { - if (UseGC) gc_init2(); -} - -+ (void)initialize { -} - -+ (id)self { - return (id)self; -} - -- (id)self { - return self; -} - -+ (Class)class { - return self; -} - -- (Class)class { - return object_getClass(self); -} - -+ (Class)superclass { - return self->superclass; -} - -- (Class)superclass { - return [self class]->superclass; -} - -+ (BOOL)isMemberOfClass:(Class)cls { - return object_getClass((id)self) == cls; -} - -- (BOOL)isMemberOfClass:(Class)cls { - return [self class] == cls; -} - -+ (BOOL)isKindOfClass:(Class)cls { - for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) { - if (tcls == cls) return YES; - } - return NO; -} - -- (BOOL)isKindOfClass:(Class)cls { - for (Class tcls = [self class]; tcls; tcls = tcls->superclass) { - if (tcls == cls) return YES; - } - return NO; -} - -+ (BOOL)isSubclassOfClass:(Class)cls { - for (Class tcls = self; tcls; tcls = tcls->superclass) { - if (tcls == cls) return YES; - } - return NO; -} - -+ (BOOL)isAncestorOfObject:(NSObject *)obj { - for (Class tcls = [obj class]; tcls; tcls = tcls->superclass) { - if (tcls == self) return YES; - } - return NO; -} - -+ (BOOL)instancesRespondToSelector:(SEL)sel { - if (!sel) return NO; - return class_respondsToSelector(self, sel); -} - -+ (BOOL)respondsToSelector:(SEL)sel { - if (!sel) return NO; - return class_respondsToSelector_inst(object_getClass(self), sel, self); -} - -- (BOOL)respondsToSelector:(SEL)sel { - if (!sel) return NO; - return class_respondsToSelector_inst([self class], sel, self); -} - -+ (BOOL)conformsToProtocol:(Protocol *)protocol { - if (!protocol) return NO; - for (Class tcls = self; tcls; tcls = tcls->superclass) { - if (class_conformsToProtocol(tcls, protocol)) return YES; - } - return NO; -} - -- (BOOL)conformsToProtocol:(Protocol *)protocol { - if (!protocol) return NO; - for (Class tcls = [self class]; tcls; tcls = tcls->superclass) { - if (class_conformsToProtocol(tcls, protocol)) return YES; - } - return NO; -} - -+ (NSUInteger)hash { - return _objc_rootHash(self); -} - -- (NSUInteger)hash { - return _objc_rootHash(self); -} - -+ (BOOL)isEqual:(id)obj { - return obj == (id)self; -} - -- (BOOL)isEqual:(id)obj { - return obj == self; -} - - -+ (BOOL)isFault { - return NO; -} - -- (BOOL)isFault { - return NO; -} - -+ (BOOL)isProxy { - return NO; -} - -- (BOOL)isProxy { - return NO; -} - - -+ (IMP)instanceMethodForSelector:(SEL)sel { - if (!sel) [self doesNotRecognizeSelector:sel]; - return class_getMethodImplementation(self, sel); -} - -+ (IMP)methodForSelector:(SEL)sel { - if (!sel) [self doesNotRecognizeSelector:sel]; - return object_getMethodImplementation((id)self, sel); -} - -- (IMP)methodForSelector:(SEL)sel { - if (!sel) [self doesNotRecognizeSelector:sel]; - return object_getMethodImplementation(self, sel); -} - -+ (BOOL)resolveClassMethod:(SEL)sel { - return NO; -} - -+ (BOOL)resolveInstanceMethod:(SEL)sel { - return NO; -} - -// Replaced by CF (throws an NSException) -+ (void)doesNotRecognizeSelector:(SEL)sel { - _objc_fatal("+[%s %s]: unrecognized selector sent to instance %p", - class_getName(self), sel_getName(sel), self); -} - -// Replaced by CF (throws an NSException) -- (void)doesNotRecognizeSelector:(SEL)sel { - _objc_fatal("-[%s %s]: unrecognized selector sent to instance %p", - object_getClassName(self), sel_getName(sel), self); -} - - -+ (id)performSelector:(SEL)sel { - if (!sel) [self doesNotRecognizeSelector:sel]; - return ((id(*)(id, SEL))objc_msgSend)((id)self, sel); -} - -+ (id)performSelector:(SEL)sel withObject:(id)obj { - if (!sel) [self doesNotRecognizeSelector:sel]; - return ((id(*)(id, SEL, id))objc_msgSend)((id)self, sel, obj); -} - -+ (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 { - if (!sel) [self doesNotRecognizeSelector:sel]; - return ((id(*)(id, SEL, id, id))objc_msgSend)((id)self, sel, obj1, obj2); -} - -- (id)performSelector:(SEL)sel { - if (!sel) [self doesNotRecognizeSelector:sel]; - return ((id(*)(id, SEL))objc_msgSend)(self, sel); -} - -- (id)performSelector:(SEL)sel withObject:(id)obj { - if (!sel) [self doesNotRecognizeSelector:sel]; - return ((id(*)(id, SEL, id))objc_msgSend)(self, sel, obj); -} - -- (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 { - if (!sel) [self doesNotRecognizeSelector:sel]; - return ((id(*)(id, SEL, id, id))objc_msgSend)(self, sel, obj1, obj2); -} - - -// Replaced by CF (returns an NSMethodSignature) -+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)sel { - _objc_fatal("+[NSObject instanceMethodSignatureForSelector:] " - "not available without CoreFoundation"); -} - -// Replaced by CF (returns an NSMethodSignature) -+ (NSMethodSignature *)methodSignatureForSelector:(SEL)sel { - _objc_fatal("+[NSObject methodSignatureForSelector:] " - "not available without CoreFoundation"); -} - -// Replaced by CF (returns an NSMethodSignature) -- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel { - _objc_fatal("-[NSObject methodSignatureForSelector:] " - "not available without CoreFoundation"); -} - -+ (void)forwardInvocation:(NSInvocation *)invocation { - [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)]; -} - -- (void)forwardInvocation:(NSInvocation *)invocation { - [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)]; -} - -+ (id)forwardingTargetForSelector:(SEL)sel { - return nil; -} - -- (id)forwardingTargetForSelector:(SEL)sel { - return nil; -} - - -// Replaced by CF (returns an NSString) -+ (NSString *)description { - return nil; -} - -// Replaced by CF (returns an NSString) -- (NSString *)description { - return nil; -} - -+ (NSString *)debugDescription { - return [self description]; -} - -- (NSString *)debugDescription { - return [self description]; -} - - -+ (id)new { - return [callAlloc(self, false/*checkNil*/) init]; -} - -+ (id)retain { - return (id)self; -} - -// Replaced by ObjectAlloc -- (id)retain { - return ((id)self)->rootRetain(); -} - - -+ (BOOL)_tryRetain { - return YES; -} - -// Replaced by ObjectAlloc -- (BOOL)_tryRetain { - return ((id)self)->rootTryRetain(); -} - -+ (BOOL)_isDeallocating { - return NO; -} - -- (BOOL)_isDeallocating { - return ((id)self)->rootIsDeallocating(); -} - -+ (BOOL)allowsWeakReference { - return YES; -} - -+ (BOOL)retainWeakReference { - return YES; -} - -- (BOOL)allowsWeakReference { - return ! [self _isDeallocating]; -} - -- (BOOL)retainWeakReference { - return [self _tryRetain]; -} - -+ (oneway void)release { -} - -// Replaced by ObjectAlloc -- (oneway void)release { - ((id)self)->rootRelease(); -} - -+ (id)autorelease { - return (id)self; -} - -// Replaced by ObjectAlloc -- (id)autorelease { - return ((id)self)->rootAutorelease(); -} - -+ (NSUInteger)retainCount { - return ULONG_MAX; -} - -- (NSUInteger)retainCount { - return ((id)self)->rootRetainCount(); -} - -+ (id)alloc { - return _objc_rootAlloc(self); -} - -// Replaced by ObjectAlloc -+ (id)allocWithZone:(struct _NSZone *)zone { - return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone); -} - -// Replaced by CF (throws an NSException) -+ (id)init { - return (id)self; -} - -- (id)init { - return _objc_rootInit(self); -} - -// Replaced by CF (throws an NSException) -+ (void)dealloc { -} - - -// Replaced by NSZombies -- (void)dealloc { - _objc_rootDealloc(self); -} - -// Replaced by CF (throws an NSException) -+ (void)finalize { -} - -- (void)finalize { - _objc_rootFinalize(self); -} - -+ (struct _NSZone *)zone { - return (struct _NSZone *)_objc_rootZone(self); -} - -- (struct _NSZone *)zone { - return (struct _NSZone *)_objc_rootZone(self); -} - -+ (id)copy { - return (id)self; -} - -+ (id)copyWithZone:(struct _NSZone *)zone { - return (id)self; -} - -- (id)copy { - return [(id)self copyWithZone:nil]; -} - -+ (id)mutableCopy { - return (id)self; -} - -+ (id)mutableCopyWithZone:(struct _NSZone *)zone { - return (id)self; -} - -- (id)mutableCopy { - return [(id)self mutableCopyWithZone:nil]; -} - -@end - - diff --git a/objc/objc-runtime/runtime/Object.h b/objc/objc-runtime/runtime/Object.h deleted file mode 100644 index dd8838d..0000000 --- a/objc/objc-runtime/runtime/Object.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 1999-2003, 2005-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@ - */ -/* - Object.h - Copyright 1988-1996 NeXT Software, Inc. - - DEFINED AS: A common class - HEADER FILES: <objc/Object.h> - -*/ - -#ifndef _OBJC_OBJECT_H_ -#define _OBJC_OBJECT_H_ - -#include <stdarg.h> -#include <objc/objc-runtime.h> - -#if __OBJC__ && !__OBJC2__ - -__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_NA) -OBJC_ROOT_CLASS -@interface Object -{ - Class isa; /* A pointer to the instance's class structure */ -} - -/* Initializing classes and instances */ - -+ (id)initialize; -- (id)init; - -/* Creating, copying, and freeing instances */ - -+ (id)new; -+ (id)free; -- (id)free; -+ (id)alloc; -- (id)copy; -+ (id)allocFromZone:(void *)zone; -- (id)copyFromZone:(void *)zone; -- (void *)zone; - -/* Identifying classes */ - -+ (id)class; -+ (id)superclass; -+ (const char *) name; -- (id)class; -- (id)superclass; -- (const char *) name; - -/* Identifying and comparing instances */ - -- (id)self; -- (unsigned int) hash; -- (BOOL) isEqual:anObject; - -/* Testing inheritance relationships */ - -- (BOOL) isKindOf: aClassObject; -- (BOOL) isMemberOf: aClassObject; -- (BOOL) isKindOfClassNamed: (const char *)aClassName; -- (BOOL) isMemberOfClassNamed: (const char *)aClassName; - -/* Testing class functionality */ - -+ (BOOL) instancesRespondTo:(SEL)aSelector; -- (BOOL) respondsTo:(SEL)aSelector; - -/* Testing protocol conformance */ - -- (BOOL) conformsTo: (Protocol *)aProtocolObject; -+ (BOOL) conformsTo: (Protocol *)aProtocolObject; - -/* Obtaining method descriptors from protocols */ - -- (struct objc_method_description *) descriptionForMethod:(SEL)aSel; -+ (struct objc_method_description *) descriptionForInstanceMethod:(SEL)aSel; - -/* Obtaining method handles */ - -- (IMP) methodFor:(SEL)aSelector; -+ (IMP) instanceMethodFor:(SEL)aSelector; - -/* Sending messages determined at run time */ - -- (id)perform:(SEL)aSelector; -- (id)perform:(SEL)aSelector with:anObject; -- (id)perform:(SEL)aSelector with:object1 with:object2; - -/* Posing */ - -+ (id)poseAs: aClassObject; - -/* Enforcing intentions */ - -- (id)subclassResponsibility:(SEL)aSelector; -- (id)notImplemented:(SEL)aSelector; - -/* Error handling */ - -- (id)doesNotRecognize:(SEL)aSelector; -- (id)error:(const char *)aString, ...; - -/* Debugging */ - -- (void) printForDebugger:(void *)stream; - -/* Archiving */ - -- (id)awake; -- (id)write:(void *)stream; -- (id)read:(void *)stream; -+ (int) version; -+ (id)setVersion: (int) aVersion; - -/* Forwarding */ - -- (id)forward: (SEL)sel : (marg_list)args; -- (id)performv: (SEL)sel : (marg_list)args; - -@end - -/* Abstract Protocol for Archiving */ - -@interface Object (Archiving) - -- (id)startArchiving: (void *)stream; -- (id)finishUnarchiving; - -@end - -/* Abstract Protocol for Dynamic Loading */ - -@interface Object (DynamicLoading) - -//+ finishLoading:(headerType *)header; -struct mach_header; -+ (id)finishLoading:(struct mach_header *)header; -+ (id)startUnloading; - -@end - -#endif - -#endif /* _OBJC_OBJECT_H_ */ diff --git a/objc/objc-runtime/runtime/Object.mm b/objc/objc-runtime/runtime/Object.mm deleted file mode 100644 index c4981cf..0000000 --- a/objc/objc-runtime/runtime/Object.mm +++ /dev/null @@ -1,558 +0,0 @@ -/* - * 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@ - */ -/* - Object.m - Copyright 1988-1996 NeXT Software, Inc. -*/ - -#include "objc-private.h" - -#undef id -#undef Class - -typedef struct objc_class *Class; -typedef struct objc_object *id; - -#if __OBJC2__ - -__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_NA) -OBJC_ROOT_CLASS -@interface Object { - Class isa; -} -@end - -@implementation Object - -+ (id)initialize -{ - return self; -} - -+ (id)class -{ - return self; -} - --(id) retain -{ - return _objc_rootRetain(self); -} - --(void) release -{ - _objc_rootRelease(self); -} - --(id) autorelease -{ - return _objc_rootAutorelease(self); -} - -+(id) retain -{ - return self; -} - -+(void) release -{ -} - -+(id) autorelease -{ - return self; -} - - -@end - - -// __OBJC2__ -#else -// not __OBJC2__ - -#include <stdlib.h> -#include <stdarg.h> -#include <string.h> -#include <malloc/malloc.h> - -#include "Object.h" -#include "Protocol.h" -#include "objc-runtime.h" -#include "objc-auto.h" - - -// Error Messages -static const char - _errShouldHaveImp[] = "should have implemented the '%s' method.", - _errShouldNotImp[] = "should NOT have implemented the '%s' method.", - _errLeftUndone[] = "method '%s' not implemented", - _errBadSel[] = "method %s given invalid selector %s", - _errDoesntRecognize[] = "does not recognize selector %c%s"; - - -@implementation Object - - -+ (id)initialize -{ - return self; -} - -- (id)awake -{ - return self; -} - -+ (id)poseAs: aFactory -{ - return class_poseAs(self, aFactory); -} - -+ (id)new -{ - id newObject = (*_alloc)((Class)self, 0); - Class metaClass = self->ISA(); - if (class_getVersion(metaClass) > 1) - return [newObject init]; - else - return newObject; -} - -+ (id)alloc -{ - return (*_zoneAlloc)((Class)self, 0, malloc_default_zone()); -} - -+ (id)allocFromZone:(void *) z -{ - return (*_zoneAlloc)((Class)self, 0, z); -} - -- (id)init -{ - return self; -} - -- (const char *)name -{ - return class_getName(isa); -} - -+ (const char *)name -{ - return class_getName((Class)self); -} - -- (unsigned)hash -{ - return (unsigned)(((uintptr_t)self) >> 2); -} - -- (BOOL)isEqual:anObject -{ - return anObject == self; -} - -- (id)free -{ - return (*_dealloc)(self); -} - -+ (id)free -{ - return nil; -} - -- (id)self -{ - return self; -} - - --(id)class -{ - return (id)isa; -} - -+ (id)class -{ - return self; -} - -- (void *)zone -{ - void *z = malloc_zone_from_ptr(self); - return z ? z : malloc_default_zone(); -} - -+ (id)superclass -{ - return self->superclass; -} - -- (id)superclass -{ - return isa->superclass; -} - -+ (int) version -{ - return class_getVersion((Class)self); -} - -+ (id)setVersion: (int) aVersion -{ - class_setVersion((Class)self, aVersion); - return self; -} - -- (BOOL)isKindOf:aClass -{ - Class cls; - for (cls = isa; cls; cls = cls->superclass) - if (cls == (Class)aClass) - return YES; - return NO; -} - -- (BOOL)isMemberOf:aClass -{ - return isa == (Class)aClass; -} - -- (BOOL)isKindOfClassNamed:(const char *)aClassName -{ - Class cls; - for (cls = isa; cls; cls = cls->superclass) - if (strcmp(aClassName, class_getName(cls)) == 0) - return YES; - return NO; -} - -- (BOOL)isMemberOfClassNamed:(const char *)aClassName -{ - return strcmp(aClassName, class_getName(isa)) == 0; -} - -+ (BOOL)instancesRespondTo:(SEL)aSelector -{ - return class_respondsToMethod((Class)self, aSelector); -} - -- (BOOL)respondsTo:(SEL)aSelector -{ - return class_respondsToMethod(isa, aSelector); -} - -- (id)copy -{ - return [self copyFromZone: [self zone]]; -} - -- (id)copyFromZone:(void *)z -{ - return (*_zoneCopy)(self, 0, z); -} - -- (IMP)methodFor:(SEL)aSelector -{ - return class_lookupMethod(isa, aSelector); -} - -+ (IMP)instanceMethodFor:(SEL)aSelector -{ - return class_lookupMethod(self, aSelector); -} - -- (id)perform:(SEL)aSelector -{ - if (aSelector) - return ((id(*)(id, SEL))objc_msgSend)(self, aSelector); - else - return [self error:_errBadSel, sel_getName(_cmd), aSelector]; -} - -- (id)perform:(SEL)aSelector with:anObject -{ - if (aSelector) - return ((id(*)(id, SEL, id))objc_msgSend)(self, aSelector, anObject); - else - return [self error:_errBadSel, sel_getName(_cmd), aSelector]; -} - -- (id)perform:(SEL)aSelector with:obj1 with:obj2 -{ - if (aSelector) - return ((id(*)(id, SEL, id, id))objc_msgSend)(self, aSelector, obj1, obj2); - else - return [self error:_errBadSel, sel_getName(_cmd), aSelector]; -} - -- (id)subclassResponsibility:(SEL)aSelector -{ - return [self error:_errShouldHaveImp, sel_getName(aSelector)]; -} - -- (id)notImplemented:(SEL)aSelector -{ - return [self error:_errLeftUndone, sel_getName(aSelector)]; -} - -- (id)doesNotRecognize:(SEL)aMessage -{ - return [self error:_errDoesntRecognize, - class_isMetaClass(isa) ? '+' : '-', sel_getName(aMessage)]; -} - -- (id)error:(const char *)aCStr, ... -{ - va_list ap; - va_start(ap,aCStr); - (*_error)(self, aCStr, ap); - _objc_error (self, aCStr, ap); /* In case (*_error)() returns. */ - va_end(ap); - return nil; -} - -- (void) printForDebugger:(void *)stream -{ -} - -- (id)write:(void *) stream -{ - return self; -} - -- (id)read:(void *) stream -{ - return self; -} - -- (id)forward: (SEL) sel : (marg_list) args -{ - return [self doesNotRecognize: sel]; -} - -/* this method is not part of the published API */ - -- (unsigned)methodArgSize:(SEL)sel -{ - Method method = class_getInstanceMethod((Class)isa, sel); - if (! method) return 0; - return method_getSizeOfArguments(method); -} - -- (id)performv: (SEL) sel : (marg_list) args -{ - unsigned size; - - // Messages to nil object always return nil - if (! self) return nil; - - // Calculate size of the marg_list from the method's - // signature. This looks for the method in self - // and its superclasses. - size = [self methodArgSize: sel]; - - // If neither self nor its superclasses implement - // it, forward the message because self might know - // someone who does. This is a "chained" forward... - if (! size) return [self forward: sel: args]; - - // Message self with the specified selector and arguments - return objc_msgSendv (self, sel, size, args); -} - -/* Testing protocol conformance */ - -- (BOOL) conformsTo: (Protocol *)aProtocolObj -{ - return [(id)isa conformsTo:aProtocolObj]; -} - -+ (BOOL) conformsTo: (Protocol *)aProtocolObj -{ - Class cls; - for (cls = self; cls; cls = cls->superclass) - { - if (class_conformsToProtocol(cls, aProtocolObj)) return YES; - } - return NO; -} - - -/* Looking up information for a method */ - -- (struct objc_method_description *) descriptionForMethod:(SEL)aSelector -{ - Class cls; - struct objc_method_description *m; - - /* Look in the protocols first. */ - for (cls = isa; cls; cls = cls->superclass) - { - if (cls->ISA()->version >= 3) - { - struct objc_protocol_list *protocols = - (struct objc_protocol_list *)cls->protocols; - - while (protocols) - { - int i; - - for (i = 0; i < protocols->count; i++) - { - Protocol *p = protocols->list[i]; - - if (class_isMetaClass(cls)) - m = [p descriptionForClassMethod:aSelector]; - else - m = [p descriptionForInstanceMethod:aSelector]; - - if (m) { - return m; - } - } - - if (cls->ISA()->version <= 4) - break; - - protocols = protocols->next; - } - } - } - - /* Then try the class implementations. */ - for (cls = isa; cls; cls = cls->superclass) { - void *iterator = 0; - int i; - struct objc_method_list *mlist; - while ( (mlist = class_nextMethodList( cls, &iterator )) ) { - for (i = 0; i < mlist->method_count; i++) - if (mlist->method_list[i].method_name == aSelector) { - m = (struct objc_method_description *)&mlist->method_list[i]; - return m; - } - } - } - return 0; -} - -+ (struct objc_method_description *) descriptionForInstanceMethod:(SEL)aSelector -{ - Class cls; - - /* Look in the protocols first. */ - for (cls = self; cls; cls = cls->superclass) - { - if (cls->ISA()->version >= 3) - { - struct objc_protocol_list *protocols = - (struct objc_protocol_list *)cls->protocols; - - while (protocols) - { - int i; - - for (i = 0; i < protocols->count; i++) - { - Protocol *p = protocols->list[i]; - struct objc_method_description *m; - - if ((m = [p descriptionForInstanceMethod:aSelector])) - return m; - } - - if (cls->ISA()->version <= 4) - break; - - protocols = protocols->next; - } - } - } - - /* Then try the class implementations. */ - for (cls = self; cls; cls = cls->superclass) { - void *iterator = 0; - int i; - struct objc_method_list *mlist; - while ( (mlist = class_nextMethodList( cls, &iterator )) ) { - for (i = 0; i < mlist->method_count; i++) - if (mlist->method_list[i].method_name == aSelector) { - struct objc_method_description *m; - m = (struct objc_method_description *)&mlist->method_list[i]; - return m; - } - } - } - return 0; -} - - -/* Obsolete methods (for binary compatibility only). */ - -+ (id)superClass -{ - return [self superclass]; -} - -- (id)superClass -{ - return [self superclass]; -} - -- (BOOL)isKindOfGivenName:(const char *)aClassName -{ - return [self isKindOfClassNamed: aClassName]; -} - -- (BOOL)isMemberOfGivenName:(const char *)aClassName -{ - return [self isMemberOfClassNamed: aClassName]; -} - -- (struct objc_method_description *) methodDescFor:(SEL)aSelector -{ - return [self descriptionForMethod: aSelector]; -} - -+ (struct objc_method_description *) instanceMethodDescFor:(SEL)aSelector -{ - return [self descriptionForInstanceMethod: aSelector]; -} - -- (id)findClass:(const char *)aClassName -{ - return objc_lookUpClass(aClassName); -} - -- (id)shouldNotImplement:(SEL)aSelector -{ - return [self error:_errShouldNotImp, sel_getName(aSelector)]; -} - - -@end - -#endif diff --git a/objc/objc-runtime/runtime/OldClasses.subproj/List.h b/objc/objc-runtime/runtime/OldClasses.subproj/List.h deleted file mode 100644 index 993cf2c..0000000 --- a/objc/objc-runtime/runtime/OldClasses.subproj/List.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 1999-2002, 2005-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@ - */ -/* - List.h - Copyright 1988-1996 NeXT Software, Inc. - - DEFINED AS: A common class - HEADER FILES: objc/List.h - -*/ - -#ifndef _OBJC_LIST_H_ -#define _OBJC_LIST_H_ - -#if __OBJC__ && !__OBJC2__ && !__cplusplus - -#include <objc/Object.h> -#include <Availability.h> - -DEPRECATED_ATTRIBUTE -@interface List : Object -{ -@public - id *dataPtr DEPRECATED_ATTRIBUTE; /* data of the List object */ - unsigned numElements DEPRECATED_ATTRIBUTE; /* Actual number of elements */ - unsigned maxElements DEPRECATED_ATTRIBUTE; /* Total allocated elements */ -} - -/* Creating, freeing */ - -- (id)free DEPRECATED_ATTRIBUTE; -- (id)freeObjects DEPRECATED_ATTRIBUTE; -- (id)copyFromZone:(void *)z DEPRECATED_ATTRIBUTE; - -/* Initializing */ - -- (id)init DEPRECATED_ATTRIBUTE; -- (id)initCount:(unsigned)numSlots DEPRECATED_ATTRIBUTE; - -/* Comparing two lists */ - -- (BOOL)isEqual: anObject DEPRECATED_ATTRIBUTE; - -/* Managing the storage capacity */ - -- (unsigned)capacity DEPRECATED_ATTRIBUTE; -- (id)setAvailableCapacity:(unsigned)numSlots DEPRECATED_ATTRIBUTE; - -/* Manipulating objects by index */ - -- (unsigned)count DEPRECATED_ATTRIBUTE; -- (id)objectAt:(unsigned)index DEPRECATED_ATTRIBUTE; -- (id)lastObject DEPRECATED_ATTRIBUTE; -- (id)addObject:anObject DEPRECATED_ATTRIBUTE; -- (id)insertObject:anObject at:(unsigned)index DEPRECATED_ATTRIBUTE; -- (id)removeObjectAt:(unsigned)index DEPRECATED_ATTRIBUTE; -- (id)removeLastObject DEPRECATED_ATTRIBUTE; -- (id)replaceObjectAt:(unsigned)index with:newObject DEPRECATED_ATTRIBUTE; -- (id)appendList: (List *)otherList DEPRECATED_ATTRIBUTE; - -/* Manipulating objects by id */ - -- (unsigned)indexOf:anObject DEPRECATED_ATTRIBUTE; -- (id)addObjectIfAbsent:anObject DEPRECATED_ATTRIBUTE; -- (id)removeObject:anObject DEPRECATED_ATTRIBUTE; -- (id)replaceObject:anObject with:newObject DEPRECATED_ATTRIBUTE; - -/* Emptying the list */ - -- (id)empty DEPRECATED_ATTRIBUTE; - -/* Sending messages to elements of the list */ - -- (id)makeObjectsPerform:(SEL)aSelector DEPRECATED_ATTRIBUTE; -- (id)makeObjectsPerform:(SEL)aSelector with:anObject DEPRECATED_ATTRIBUTE; - -/* - * The following new... methods are now obsolete. They remain in this - * interface file for backward compatibility only. Use Object's alloc method - * and the init... methods defined in this class instead. - */ - -+ (id)new DEPRECATED_ATTRIBUTE; -+ (id)newCount:(unsigned)numSlots DEPRECATED_ATTRIBUTE; - -@end - -typedef struct { - @defs(List); -} NXListId DEPRECATED_ATTRIBUTE; - -#define NX_ADDRESS(x) (((NXListId *)(x))->dataPtr) - -#define NX_NOT_IN_LIST 0xffffffff - -#endif - -#endif /* _OBJC_LIST_H_ */ diff --git a/objc/objc-runtime/runtime/OldClasses.subproj/List.m b/objc/objc-runtime/runtime/OldClasses.subproj/List.m deleted file mode 100644 index a46849c..0000000 --- a/objc/objc-runtime/runtime/OldClasses.subproj/List.m +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (c) 1999-2001, 2005-2006 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@ - */ -/* - List.m - Copyright 1988-1996 NeXT Software, Inc. - Written by: Bryan Yamamoto - Responsibility: Bertrand Serlet -*/ - -#ifndef __OBJC2__ - -#include <stdlib.h> -#include <stdio.h> -#include <string.h> - -#include <objc/List.h> - -#define DATASIZE(count) ((count) * sizeof(id)) - -@implementation List - -+ (id)initialize -{ - [self setVersion: 1]; - return self; -} - -- (id)initCount:(unsigned)numSlots -{ - maxElements = numSlots; - if (maxElements) - dataPtr = (id *)malloc(DATASIZE(maxElements)); - return self; -} - -+ (id)newCount:(unsigned)numSlots -{ - return [[self alloc] initCount:numSlots]; -} - -+ (id)new -{ - return [self newCount:0]; -} - -- (id)init -{ - return [self initCount:0]; -} - -- (id)free -{ - free(dataPtr); - return [super free]; -} - -- (id)freeObjects -{ - id element; - while ((element = [self removeLastObject])) - [element free]; - return self; -} - -- (id)copyFromZone:(void *)z -{ - List *new = [[[self class] alloc] initCount: numElements]; - new->numElements = numElements; - bcopy ((const char*)dataPtr, (char*)new->dataPtr, DATASIZE(numElements)); - return new; -} - -- (BOOL) isEqual: anObject -{ - List *other; - if (! [anObject isKindOf: [self class]]) return NO; - other = (List *) anObject; - return (numElements == other->numElements) - && (bcmp ((const char*)dataPtr, (const char*)other->dataPtr, DATASIZE(numElements)) == 0); -} - -- (unsigned)capacity -{ - return maxElements; -} - -- (unsigned)count -{ - return numElements; -} - -- (id)objectAt:(unsigned)index -{ - if (index >= numElements) - return nil; - return dataPtr[index]; -} - -- (unsigned)indexOf:anObject -{ - register id *this = dataPtr; - register id *last = this + numElements; - while (this < last) { - if (*this == anObject) - return this - dataPtr; - this++; - } - return NX_NOT_IN_LIST; -} - -- (id)lastObject -{ - if (! numElements) - return nil; - return dataPtr[numElements - 1]; -} - -- (id)setAvailableCapacity:(unsigned)numSlots -{ - volatile id *tempDataPtr; - if (numSlots < numElements) return nil; - tempDataPtr = (id *) realloc (dataPtr, DATASIZE(numSlots)); - dataPtr = (id *)tempDataPtr; - maxElements = numSlots; - return self; -} - -- (id)insertObject:anObject at:(unsigned)index -{ - register id *this, *last, *prev; - if (! anObject) return nil; - if (index > numElements) - return nil; - if ((numElements + 1) > maxElements) { - volatile id *tempDataPtr; - /* we double the capacity, also a good size for malloc */ - maxElements += maxElements + 1; - tempDataPtr = (id *) realloc (dataPtr, DATASIZE(maxElements)); - dataPtr = (id*)tempDataPtr; - } - this = dataPtr + numElements; - prev = this - 1; - last = dataPtr + index; - while (this > last) - *this-- = *prev--; - *last = anObject; - numElements++; - return self; -} - -- (id)addObject:anObject -{ - return [self insertObject:anObject at:numElements]; - -} - - -- (id)addObjectIfAbsent:anObject -{ - register id *this, *last; - if (! anObject) return nil; - this = dataPtr; - last = dataPtr + numElements; - while (this < last) { - if (*this == anObject) - return self; - this++; - } - return [self insertObject:anObject at:numElements]; - -} - - -- (id)removeObjectAt:(unsigned)index -{ - register id *this, *last, *next; - id retval; - if (index >= numElements) - return nil; - this = dataPtr + index; - last = dataPtr + numElements; - next = this + 1; - retval = *this; - while (next < last) - *this++ = *next++; - numElements--; - return retval; -} - -- (id)removeObject:anObject -{ - register id *this, *last; - this = dataPtr; - last = dataPtr + numElements; - while (this < last) { - if (*this == anObject) - return [self removeObjectAt:this - dataPtr]; - this++; - } - return nil; -} - -- (id)removeLastObject -{ - if (! numElements) - return nil; - return [self removeObjectAt: numElements - 1]; -} - -- (id)empty -{ - numElements = 0; - return self; -} - -- (id)replaceObject:anObject with:newObject -{ - register id *this, *last; - if (! newObject) - return nil; - this = dataPtr; - last = dataPtr + numElements; - while (this < last) { - if (*this == anObject) { - *this = newObject; - return anObject; - } - this++; - } - return nil; -} - -- (id)replaceObjectAt:(unsigned)index with:newObject -{ - register id *this; - id retval; - if (! newObject) - return nil; - if (index >= numElements) - return nil; - this = dataPtr + index; - retval = *this; - *this = newObject; - return retval; -} - -- (id)makeObjectsPerform:(SEL)aSelector -{ - unsigned count = numElements; - while (count--) - [dataPtr[count] perform: aSelector]; - return self; -} - -- (id)makeObjectsPerform:(SEL)aSelector with:anObject -{ - unsigned count = numElements; - while (count--) - [dataPtr[count] perform: aSelector with: anObject]; - return self; -} - --(id)appendList: (List *)otherList -{ - unsigned i, count; - - for (i = 0, count = [otherList count]; i < count; i++) - [self addObject: [otherList objectAt: i]]; - return self; -} - -@end - -#endif diff --git a/objc/objc-runtime/runtime/Protocol.h b/objc/objc-runtime/runtime/Protocol.h deleted file mode 100644 index 0e78850..0000000 --- a/objc/objc-runtime/runtime/Protocol.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 1999-2003, 2006-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@ - */ -/* - Protocol.h - Copyright 1991-1996 NeXT Software, Inc. -*/ - -#ifndef _OBJC_PROTOCOL_H_ -#define _OBJC_PROTOCOL_H_ - -#if !__OBJC__ - -// typedef Protocol is here: -#include <objc/runtime.h> - - -#elif __OBJC2__ - -#include <objc/NSObject.h> - -// All methods of class Protocol are unavailable. -// Use the functions in objc/runtime.h instead. - -__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) -@interface Protocol : NSObject -@end - - -#else - -#include <objc/Object.h> - -__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) -@interface Protocol : Object -{ -@private - char *protocol_name OBJC2_UNAVAILABLE; - struct objc_protocol_list *protocol_list OBJC2_UNAVAILABLE; - struct objc_method_description_list *instance_methods OBJC2_UNAVAILABLE; - struct objc_method_description_list *class_methods OBJC2_UNAVAILABLE; -} - -/* Obtaining attributes intrinsic to the protocol */ - -- (const char *)name OBJC2_UNAVAILABLE; - -/* Testing protocol conformance */ - -- (BOOL) conformsTo: (Protocol *)aProtocolObject OBJC2_UNAVAILABLE; - -/* Looking up information specific to a protocol */ - -- (struct objc_method_description *) descriptionForInstanceMethod:(SEL)aSel - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); -- (struct objc_method_description *) descriptionForClassMethod:(SEL)aSel - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); - -@end - -#endif - -#endif /* _OBJC_PROTOCOL_H_ */ diff --git a/objc/objc-runtime/runtime/Protocol.mm b/objc/objc-runtime/runtime/Protocol.mm deleted file mode 100644 index 137eac9..0000000 --- a/objc/objc-runtime/runtime/Protocol.mm +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 1999-2001, 2005-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@ - */ -/* - Protocol.h - Copyright 1991-1996 NeXT Software, Inc. -*/ - -#include "objc-private.h" - -#undef id -#undef Class - -#include <stdlib.h> -#include <string.h> -#include <mach-o/dyld.h> -#include <mach-o/ldsyms.h> - -#include "Protocol.h" - -#if __OBJC2__ -@interface __IncompleteProtocol : NSObject @end -@implementation __IncompleteProtocol -// fixme hack - make __IncompleteProtocol a non-lazy class -+ (void) load { } -@end -#endif - -@implementation Protocol - -#if __OBJC2__ -// fixme hack - make Protocol a non-lazy class -+ (void) load { } -#endif - - -- (BOOL) conformsTo: (Protocol *)aProtocolObj -{ - return protocol_conformsToProtocol(self, aProtocolObj); -} - -- (struct objc_method_description *) descriptionForInstanceMethod:(SEL)aSel -{ -#if !__OBJC2__ - return lookup_protocol_method((struct old_protocol *)self, aSel, - YES/*required*/, YES/*instance*/, - YES/*recursive*/); -#else - return method_getDescription(protocol_getMethod((struct protocol_t *)self, - aSel, YES, YES, YES)); -#endif -} - -- (struct objc_method_description *) descriptionForClassMethod:(SEL)aSel -{ -#if !__OBJC2__ - return lookup_protocol_method((struct old_protocol *)self, aSel, - YES/*required*/, NO/*instance*/, - YES/*recursive*/); -#else - return method_getDescription(protocol_getMethod((struct protocol_t *)self, - aSel, YES, NO, YES)); -#endif -} - -- (const char *)name -{ - return protocol_getName(self); -} - -- (BOOL)isEqual:other -{ -#if __OBJC2__ - // check isKindOf: - Class cls; - Class protoClass = objc_getClass("Protocol"); - for (cls = object_getClass(other); cls; cls = cls->superclass) { - if (cls == protoClass) break; - } - if (!cls) return NO; - // check equality - return protocol_isEqual(self, other); -#else - return [other isKindOf:[Protocol class]] && [self conformsTo: other] && [other conformsTo: self]; -#endif -} - -#if __OBJC2__ -- (NSUInteger)hash -{ - return 23; -} -#else -- (unsigned)hash -{ - return 23; -} -#endif - -@end diff --git a/objc/objc-runtime/runtime/a1a2-blocktramps-arm.s b/objc/objc-runtime/runtime/a1a2-blocktramps-arm.s deleted file mode 100644 index 9e54078..0000000 --- a/objc/objc-runtime/runtime/a1a2-blocktramps-arm.s +++ /dev/null @@ -1,148 +0,0 @@ -#if __arm__ - -#include <arm/arch.h> -#include <mach/vm_param.h> - -.syntax unified - -.text - - .private_extern __a1a2_tramphead - .private_extern __a1a2_firsttramp - .private_extern __a1a2_trampend - -// Trampoline machinery assumes the trampolines are Thumb function pointers -#if !__thumb2__ -# error sorry -#endif - -.thumb -.thumb_func __a1a2_tramphead -.thumb_func __a1a2_firsttramp -.thumb_func __a1a2_trampend - -.align PAGE_MAX_SHIFT -__a1a2_tramphead: - /* - r0 == self - r12 == pc of trampoline's first instruction + PC bias - lr == original return address - */ - - mov r1, r0 // _cmd = self - - // Trampoline's data is one page before the trampoline text. - // Also correct PC bias of 4 bytes. - sub r12, #PAGE_MAX_SIZE - ldr r0, [r12, #-4] // self = block object - ldr pc, [r0, #12] // tail call block->invoke - // not reached - - // Align trampolines to 8 bytes -.align 3 - -.macro TrampolineEntry - mov r12, pc - b __a1a2_tramphead -.align 3 -.endmacro - -.macro TrampolineEntryX16 - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry -.endmacro - -.macro TrampolineEntryX256 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 -.endmacro - -.private_extern __a1a2_firsttramp -__a1a2_firsttramp: - // 2048-2 trampolines to fill 16K page - TrampolineEntryX256 - TrampolineEntryX256 - TrampolineEntryX256 - TrampolineEntryX256 - - TrampolineEntryX256 - TrampolineEntryX256 - TrampolineEntryX256 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - // TrampolineEntry - // TrampolineEntry - -.private_extern __a1a2_trampend -__a1a2_trampend: - -#endif diff --git a/objc/objc-runtime/runtime/a1a2-blocktramps-arm64.s b/objc/objc-runtime/runtime/a1a2-blocktramps-arm64.s deleted file mode 100644 index 139df99..0000000 --- a/objc/objc-runtime/runtime/a1a2-blocktramps-arm64.s +++ /dev/null @@ -1,134 +0,0 @@ -#if __arm64__ - -#include <mach/vm_param.h> - -.text - - .private_extern __a1a2_tramphead - .private_extern __a1a2_firsttramp - .private_extern __a1a2_trampend - -.align PAGE_MAX_SHIFT -__a1a2_tramphead: -L_a1a2_tramphead: - /* - x0 == self - x17 == address of called trampoline's data (1 page before its code) - lr == original return address - */ - - mov x1, x0 // _cmd = self - ldr x0, [x17] // self = block object - ldr x16, [x0, #16] // tail call block->invoke - br x16 - - // pad up to TrampolineBlockPagePair header size - nop - nop - -.macro TrampolineEntry - // load address of trampoline data (one page before this instruction) - adr x17, -PAGE_MAX_SIZE - b L_a1a2_tramphead -.endmacro - -.macro TrampolineEntryX16 - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry -.endmacro - -.macro TrampolineEntryX256 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 -.endmacro - -.align 3 -.private_extern __a1a2_firsttramp -__a1a2_firsttramp: - // 2048-3 trampolines to fill 16K page - TrampolineEntryX256 - TrampolineEntryX256 - TrampolineEntryX256 - TrampolineEntryX256 - - TrampolineEntryX256 - TrampolineEntryX256 - TrampolineEntryX256 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - // TrampolineEntry - // TrampolineEntry - // TrampolineEntry - -.private_extern __a1a2_trampend -__a1a2_trampend: - -#endif diff --git a/objc/objc-runtime/runtime/a1a2-blocktramps-i386.s b/objc/objc-runtime/runtime/a1a2-blocktramps-i386.s deleted file mode 100755 index e4579c0..0000000 --- a/objc/objc-runtime/runtime/a1a2-blocktramps-i386.s +++ /dev/null @@ -1,566 +0,0 @@ -/* - * 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@ - */ - -#ifdef __i386__ - -#include <mach/vm_param.h> - -.text - .private_extern __a1a2_tramphead - .private_extern __a1a2_firsttramp - .private_extern __a1a2_nexttramp - .private_extern __a1a2_trampend - -.align PAGE_SHIFT -__a1a2_tramphead: - popl %eax - andl $0xFFFFFFF8, %eax - subl $ PAGE_SIZE, %eax - movl 4(%esp), %ecx // self -> ecx - movl %ecx, 8(%esp) // ecx -> _cmd - movl (%eax), %ecx // blockPtr -> ecx - movl %ecx, 4(%esp) // ecx -> self - jmp *12(%ecx) // tail to block->invoke - -.macro TrampolineEntry - call __a1a2_tramphead - nop - nop - nop -.endmacro - -.align 5 -__a1a2_firsttramp: - TrampolineEntry -__a1a2_nexttramp: // used to calculate size of each trampoline - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - -__a1a2_trampend: - -#endif diff --git a/objc/objc-runtime/runtime/a1a2-blocktramps-x86_64.s b/objc/objc-runtime/runtime/a1a2-blocktramps-x86_64.s deleted file mode 100755 index 696eb59..0000000 --- a/objc/objc-runtime/runtime/a1a2-blocktramps-x86_64.s +++ /dev/null @@ -1,564 +0,0 @@ -/* - * 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@ - */ - -#ifdef __x86_64__ - -#include <mach/vm_param.h> - - .text - .private_extern __a1a2_tramphead - .private_extern __a1a2_firsttramp - .private_extern __a1a2_nexttramp - .private_extern __a1a2_trampend - -.align PAGE_SHIFT -__a1a2_tramphead: - popq %r10 - andq $0xFFFFFFFFFFFFFFF8, %r10 - subq $ PAGE_SIZE, %r10 - movq %rdi, %rsi // arg1 -> arg2 - movq (%r10), %rdi // block -> arg1 - jmp *16(%rdi) - -.macro TrampolineEntry - callq __a1a2_tramphead - nop - nop - nop -.endmacro - -.align 5 -__a1a2_firsttramp: - TrampolineEntry -__a1a2_nexttramp: - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - -__a1a2_trampend: - -#endif diff --git a/objc/objc-runtime/runtime/a2a3-blocktramps-arm.s b/objc/objc-runtime/runtime/a2a3-blocktramps-arm.s deleted file mode 100644 index ac0ce72..0000000 --- a/objc/objc-runtime/runtime/a2a3-blocktramps-arm.s +++ /dev/null @@ -1,148 +0,0 @@ -#if __arm__ - -#include <arm/arch.h> -#include <mach/vm_param.h> - -.syntax unified - -.text - - .private_extern __a2a3_tramphead - .private_extern __a2a3_firsttramp - .private_extern __a2a3_trampend - -// Trampoline machinery assumes the trampolines are Thumb function pointers -#if !__thumb2__ -# error sorry -#endif - -.thumb -.thumb_func __a2a3_tramphead -.thumb_func __a2a3_firsttramp -.thumb_func __a2a3_trampend - -.align PAGE_MAX_SHIFT -__a2a3_tramphead: - /* - r1 == self - r12 == pc of trampoline's first instruction + PC bias - lr == original return address - */ - - mov r2, r1 // _cmd = self - - // Trampoline's data is one page before the trampoline text. - // Also correct PC bias of 4 bytes. - sub r12, #PAGE_MAX_SIZE - ldr r1, [r12, #-4] // self = block object - ldr pc, [r1, #12] // tail call block->invoke - // not reached - - // Align trampolines to 8 bytes -.align 3 - -.macro TrampolineEntry - mov r12, pc - b __a2a3_tramphead -.align 3 -.endmacro - -.macro TrampolineEntryX16 - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry -.endmacro - -.macro TrampolineEntryX256 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 -.endmacro - -.private_extern __a2a3_firsttramp -__a2a3_firsttramp: - // 2048-2 trampolines to fill 16K page - TrampolineEntryX256 - TrampolineEntryX256 - TrampolineEntryX256 - TrampolineEntryX256 - - TrampolineEntryX256 - TrampolineEntryX256 - TrampolineEntryX256 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntryX16 - TrampolineEntryX16 - TrampolineEntryX16 - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - - TrampolineEntry - TrampolineEntry - // TrampolineEntry - // TrampolineEntry - -.private_extern __a2a3_trampend -__a2a3_trampend: - -#endif diff --git a/objc/objc-runtime/runtime/a2a3-blocktramps-i386.s b/objc/objc-runtime/runtime/a2a3-blocktramps-i386.s deleted file mode 100755 index d9932f6..0000000 --- a/objc/objc-runtime/runtime/a2a3-blocktramps-i386.s +++ /dev/null @@ -1,566 +0,0 @@ -/* - * 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@ - */ - -#ifdef __i386__ - -#include <mach/vm_param.h> - -.text - .private_extern __a2a3_tramphead - .private_extern __a2a3_firsttramp - .private_extern __a2a3_nexttramp - .private_extern __a2a3_trampend - -.align PAGE_SHIFT -__a2a3_tramphead: - popl %eax - andl $0xFFFFFFF8, %eax - subl $ PAGE_SIZE, %eax - movl 8(%esp), %ecx // self -> ecx - movl %ecx, 12(%esp) // ecx -> _cmd - movl (%eax), %ecx // blockPtr -> ecx - movl %ecx, 8(%esp) // ecx -> self - jmp *12(%ecx) // tail to block->invoke - -.macro TrampolineEntry - call __a2a3_tramphead - nop - nop - nop -.endmacro - -.align 5 -__a2a3_firsttramp: - TrampolineEntry -__a2a3_nexttramp: - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - -__a2a3_trampend: - -#endif diff --git a/objc/objc-runtime/runtime/a2a3-blocktramps-x86_64.s b/objc/objc-runtime/runtime/a2a3-blocktramps-x86_64.s deleted file mode 100755 index 4904ac4..0000000 --- a/objc/objc-runtime/runtime/a2a3-blocktramps-x86_64.s +++ /dev/null @@ -1,565 +0,0 @@ -/* - * 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@ - */ - -#ifdef __x86_64__ - -#include <mach/vm_param.h> - - .text - .private_extern __a2a3_tramphead - .private_extern __a2a3_firsttramp - .private_extern __a2a3_nexttramp - .private_extern __a2a3_trampend - -.align PAGE_SHIFT -__a2a3_tramphead: - popq %r10 - andq $0xFFFFFFFFFFFFFFF8, %r10 - subq $ PAGE_SIZE, %r10 - // %rdi -- first arg -- is address of return value's space. Don't mess with it. - movq %rsi, %rdx // arg2 -> arg3 - movq (%r10), %rsi // block -> arg2 - jmp *16(%rsi) - -.macro TrampolineEntry - callq __a2a3_tramphead - nop - nop - nop -.endmacro - -.align 5 -__a2a3_firsttramp: - TrampolineEntry -__a2a3_nexttramp: - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - TrampolineEntry - -__a2a3_trampend: - -#endif diff --git a/objc/objc-runtime/runtime/hashtable.h b/objc/objc-runtime/runtime/hashtable.h deleted file mode 100644 index 7f62780..0000000 --- a/objc/objc-runtime/runtime/hashtable.h +++ /dev/null @@ -1,2 +0,0 @@ -#include <objc/hashtable2.h> - diff --git a/objc/objc-runtime/runtime/hashtable2.h b/objc/objc-runtime/runtime/hashtable2.h deleted file mode 100644 index c6612b8..0000000 --- a/objc/objc-runtime/runtime/hashtable2.h +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 1999-2006 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@ - */ -/* - hashtable2.h - Scalable hash table. - Copyright 1989-1996 NeXT Software, Inc. - */ - -#ifndef _OBJC_LITTLE_HASHTABLE_H_ -#define _OBJC_LITTLE_HASHTABLE_H_ - -#ifndef _OBJC_PRIVATE_H_ -# define OBJC_HASH_AVAILABILITY __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_1, __IPHONE_NA,__IPHONE_NA); -#else -# define OBJC_HASH_AVAILABILITY -#endif - -#include <objc/objc.h> -#include <stdint.h> -#include <TargetConditionals.h> - -__BEGIN_DECLS - -/************************************************************************* - * Hash tables of arbitrary data - *************************************************************************/ - -/* This module allows hashing of arbitrary data. Such data must be pointers or integers, and client is responsible for allocating/deallocating this data. A deallocation call-back is provided. - The objective C class HashTable is preferred when dealing with (key, values) associations because it is easier to use in that situation. - As well-behaved scalable data structures, hash tables double in size when they start becoming full, thus guaranteeing both average constant time access and linear size. */ - -typedef struct { - uintptr_t (*hash)(const void *info, const void *data); - int (*isEqual)(const void *info, const void *data1, const void *data2); - void (*free)(const void *info, void *data); - int style; /* reserved for future expansion; currently 0 */ -} NXHashTablePrototype; - -/* the info argument allows a certain generality, such as freeing according to some owner information */ -/* invariants assumed by the implementation: - 1 - data1 = data2 => hash(data1) = hash(data2) - when data varies over time, hash(data) must remain invariant - e.g. if data hashes over a string key, the string must not be changed - 2- isEqual (data1, data2) => data1= data2 - */ - -typedef struct { - const NXHashTablePrototype *prototype OBJC_HASH_AVAILABILITY; - unsigned count OBJC_HASH_AVAILABILITY; - unsigned nbBuckets OBJC_HASH_AVAILABILITY; - void *buckets OBJC_HASH_AVAILABILITY; - const void *info OBJC_HASH_AVAILABILITY; -} NXHashTable OBJC_HASH_AVAILABILITY; -/* private data structure; may change */ - -OBJC_EXPORT NXHashTable *NXCreateHashTableFromZone (NXHashTablePrototype prototype, unsigned capacity, const void *info, void *z) OBJC_HASH_AVAILABILITY; -OBJC_EXPORT NXHashTable *NXCreateHashTable (NXHashTablePrototype prototype, unsigned capacity, const void *info) OBJC_HASH_AVAILABILITY; -/* if hash is 0, pointer hash is assumed */ -/* if isEqual is 0, pointer equality is assumed */ -/* if free is 0, elements are not freed */ -/* capacity is only a hint; 0 creates a small table */ -/* info allows call backs to be very general */ - -OBJC_EXPORT void NXFreeHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* calls free for each data, and recovers table */ - -OBJC_EXPORT void NXEmptyHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* does not deallocate table nor data; keeps current capacity */ - -OBJC_EXPORT void NXResetHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* frees each entry; keeps current capacity */ - -OBJC_EXPORT BOOL NXCompareHashTables (NXHashTable *table1, NXHashTable *table2) OBJC_HASH_AVAILABILITY; -/* Returns YES if the two sets are equal (each member of table1 in table2, and table have same size) */ - -OBJC_EXPORT NXHashTable *NXCopyHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* makes a fresh table, copying data pointers, not data itself. */ - -OBJC_EXPORT unsigned NXCountHashTable (NXHashTable *table) OBJC_HASH_AVAILABILITY; -/* current number of data in table */ - -OBJC_EXPORT int NXHashMember (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* returns non-0 iff data is present in table. - Example of use when the hashed data is a struct containing the key, - and when the callee only has a key: - MyStruct pseudo; - pseudo.key = myKey; - return NXHashMember (myTable, &pseudo) - */ - -OBJC_EXPORT void *NXHashGet (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* return original table data or NULL. - Example of use when the hashed data is a struct containing the key, - and when the callee only has a key: - MyStruct pseudo; - MyStruct *original; - pseudo.key = myKey; - original = NXHashGet (myTable, &pseudo) - */ - -OBJC_EXPORT void *NXHashInsert (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* previous data or NULL is returned. */ - -OBJC_EXPORT void *NXHashInsertIfAbsent (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* If data already in table, returns the one in table - else adds argument to table and returns argument. */ - -OBJC_EXPORT void *NXHashRemove (NXHashTable *table, const void *data) OBJC_HASH_AVAILABILITY; -/* previous data or NULL is returned */ - -/* Iteration over all elements of a table consists in setting up an iteration state and then to progress until all entries have been visited. An example of use for counting elements in a table is: - unsigned count = 0; - MyData *data; - NXHashState state = NXInitHashState(table); - while (NXNextHashState(table, &state, &data)) { - count++; - } - */ - -typedef struct {int i; int j;} NXHashState OBJC_HASH_AVAILABILITY; -/* callers should not rely on actual contents of the struct */ - -OBJC_EXPORT NXHashState NXInitHashState(NXHashTable *table) OBJC_HASH_AVAILABILITY; - -OBJC_EXPORT int NXNextHashState(NXHashTable *table, NXHashState *state, void **data) OBJC_HASH_AVAILABILITY; -/* returns 0 when all elements have been visited */ - -/************************************************************************* - * Conveniences for writing hash, isEqual and free functions - * and common prototypes - *************************************************************************/ - -OBJC_EXPORT uintptr_t NXPtrHash(const void *info, const void *data) OBJC_HASH_AVAILABILITY; -/* scrambles the address bits; info unused */ -OBJC_EXPORT uintptr_t NXStrHash(const void *info, const void *data) OBJC_HASH_AVAILABILITY; -/* string hashing; info unused */ -OBJC_EXPORT int NXPtrIsEqual(const void *info, const void *data1, const void *data2) OBJC_HASH_AVAILABILITY; -/* pointer comparison; info unused */ -OBJC_EXPORT int NXStrIsEqual(const void *info, const void *data1, const void *data2) OBJC_HASH_AVAILABILITY; -/* string comparison; NULL ok; info unused */ -OBJC_EXPORT void NXNoEffectFree(const void *info, void *data) OBJC_HASH_AVAILABILITY; -/* no effect; info unused */ -OBJC_EXPORT void NXReallyFree(const void *info, void *data) OBJC_HASH_AVAILABILITY; -/* frees it; info unused */ - -/* The two following prototypes are useful for manipulating set of pointers or set of strings; For them free is defined as NXNoEffectFree */ -OBJC_EXPORT const NXHashTablePrototype NXPtrPrototype OBJC_HASH_AVAILABILITY; -/* prototype when data is a pointer (void *) */ -OBJC_EXPORT const NXHashTablePrototype NXStrPrototype OBJC_HASH_AVAILABILITY; -/* prototype when data is a string (char *) */ - -/* following prototypes help describe mappings where the key is the first element of a struct and is either a pointer or a string. - For example NXStrStructKeyPrototype can be used to hash pointers to Example, where Example is: - typedef struct { - char *key; - int data1; - ... - } Example - - For the following prototypes, free is defined as NXReallyFree. - */ -OBJC_EXPORT const NXHashTablePrototype NXPtrStructKeyPrototype OBJC_HASH_AVAILABILITY; -OBJC_EXPORT const NXHashTablePrototype NXStrStructKeyPrototype OBJC_HASH_AVAILABILITY; - - -#if !__OBJC2__ && !TARGET_OS_WIN32 - -/************************************************************************* - * Unique strings and buffers - *************************************************************************/ - -/* Unique strings allows C users to enjoy the benefits of Lisp's atoms: - A unique string is a string that is allocated once for all (never de-allocated) and that has only one representant (thus allowing comparison with == instead of strcmp). A unique string should never be modified (and in fact some memory protection is done to ensure that). In order to more explicitly insist on the fact that the string has been uniqued, a synonym of (const char *) has been added, NXAtom. */ - -typedef const char *NXAtom OBJC_HASH_AVAILABILITY; - -OBJC_EXPORT NXAtom NXUniqueString(const char *buffer) OBJC_HASH_AVAILABILITY; -/* assumes that buffer is \0 terminated, and returns - a previously created string or a new string that is a copy of buffer. - If NULL is passed returns NULL. - Returned string should never be modified. To ensure this invariant, - allocations are made in a special read only zone. */ - -OBJC_EXPORT NXAtom NXUniqueStringWithLength(const char *buffer, int length) OBJC_HASH_AVAILABILITY; -/* assumes that buffer is a non NULL buffer of at least - length characters. Returns a previously created string or - a new string that is a copy of buffer. - If buffer contains \0, string will be truncated. - As for NXUniqueString, returned string should never be modified. */ - -OBJC_EXPORT NXAtom NXUniqueStringNoCopy(const char *string) OBJC_HASH_AVAILABILITY; -/* If there is already a unique string equal to string, returns the original. - Otherwise, string is entered in the table, without making a copy. Argument should then never be modified. */ - -OBJC_EXPORT char *NXCopyStringBuffer(const char *buffer) OBJC_HASH_AVAILABILITY; -/* given a buffer, allocates a new string copy of buffer. - Buffer should be \0 terminated; returned string is \0 terminated. */ - -OBJC_EXPORT char *NXCopyStringBufferFromZone(const char *buffer, void *z) OBJC_HASH_AVAILABILITY; -/* given a buffer, allocates a new string copy of buffer. - Buffer should be \0 terminated; returned string is \0 terminated. */ - -#endif - -__END_DECLS - -#endif /* _OBJC_LITTLE_HASHTABLE_H_ */ diff --git a/objc/objc-runtime/runtime/hashtable2.mm b/objc/objc-runtime/runtime/hashtable2.mm deleted file mode 100644 index fdaded9..0000000 --- a/objc/objc-runtime/runtime/hashtable2.mm +++ /dev/null @@ -1,646 +0,0 @@ -/* - * Copyright (c) 1999-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@ - */ -/* - hashtable2.m - Copyright 1989-1996 NeXT Software, Inc. - Created by Bertrand Serlet, Feb 89 - */ - -#include "objc-private.h" -#include "hashtable2.h" - -/* In order to improve efficiency, buckets contain a pointer to an array or directly the data when the array size is 1 */ -typedef union { - const void *one; - const void **many; -} oneOrMany; -/* an optimization consists of storing directly data when count = 1 */ - -typedef struct { - unsigned count; - oneOrMany elements; -} HashBucket; -/* private data structure; may change */ - -/************************************************************************* - * - * Macros and utilities - * - *************************************************************************/ - -#define PTRSIZE sizeof(void *) - -#if !SUPPORT_ZONES -# define DEFAULT_ZONE NULL -# define ZONE_FROM_PTR(p) NULL -# define ALLOCTABLE(z) ((NXHashTable *) malloc (sizeof (NXHashTable))) -# define ALLOCBUCKETS(z,nb)((HashBucket *) calloc (nb, sizeof (HashBucket))) -/* Return interior pointer so a table of classes doesn't look like objects */ -# define ALLOCPAIRS(z,nb) (1+(const void **) calloc (nb+1, sizeof (void *))) -# define FREEPAIRS(p) (free((void*)(-1+p))) -#else -# define DEFAULT_ZONE malloc_default_zone() -# define ZONE_FROM_PTR(p) malloc_zone_from_ptr(p) -# define ALLOCTABLE(z) ((NXHashTable *) malloc_zone_malloc ((malloc_zone_t *)z,sizeof (NXHashTable))) -# define ALLOCBUCKETS(z,nb)((HashBucket *) malloc_zone_calloc ((malloc_zone_t *)z, nb, sizeof (HashBucket))) -/* Return interior pointer so a table of classes doesn't look like objects */ -# define ALLOCPAIRS(z,nb) (1+(const void **) malloc_zone_calloc ((malloc_zone_t *)z, nb+1, sizeof (void *))) -# define FREEPAIRS(p) (free((void*)(-1+p))) -#endif - -#if !SUPPORT_MOD -/* nbBuckets must be a power of 2 */ -# define BUCKETOF(table, data) (((HashBucket *)table->buckets)+((*table->prototype->hash)(table->info, data) & (table->nbBuckets-1))) -# define GOOD_CAPACITY(c) (c <= 1 ? 1 : 1 << (log2u (c-1)+1)) -# define MORE_CAPACITY(b) (b*2) -#else -/* iff necessary this modulo can be optimized since the nbBuckets is of the form 2**n-1 */ -# define BUCKETOF(table, data) (((HashBucket *)table->buckets)+((*table->prototype->hash)(table->info, data) % table->nbBuckets)) -# define GOOD_CAPACITY(c) (exp2m1u (log2u (c)+1)) -# define MORE_CAPACITY(b) (b*2+1) -#endif - -#define ISEQUAL(table, data1, data2) ((data1 == data2) || (*table->prototype->isEqual)(table->info, data1, data2)) -/* beware of double evaluation */ - -/************************************************************************* - * - * Global data and bootstrap - * - *************************************************************************/ - -static int isEqualPrototype (const void *info, const void *data1, const void *data2) { - NXHashTablePrototype *proto1 = (NXHashTablePrototype *) data1; - NXHashTablePrototype *proto2 = (NXHashTablePrototype *) data2; - - return (proto1->hash == proto2->hash) && (proto1->isEqual == proto2->isEqual) && (proto1->free == proto2->free) && (proto1->style == proto2->style); -}; - -static uintptr_t hashPrototype (const void *info, const void *data) { - NXHashTablePrototype *proto = (NXHashTablePrototype *) data; - - return NXPtrHash(info, (void*)proto->hash) ^ NXPtrHash(info, (void*)proto->isEqual) ^ NXPtrHash(info, (void*)proto->free) ^ (uintptr_t) proto->style; -}; - -void NXNoEffectFree (const void *info, void *data) {}; - -static NXHashTablePrototype protoPrototype = { - hashPrototype, isEqualPrototype, NXNoEffectFree, 0 -}; - -static NXHashTable *prototypes = NULL; -/* table of all prototypes */ - -static void bootstrap (void) { - free(malloc(8)); - prototypes = ALLOCTABLE (DEFAULT_ZONE); - prototypes->prototype = &protoPrototype; - prototypes->count = 1; - prototypes->nbBuckets = 1; /* has to be 1 so that the right bucket is 0 */ - prototypes->buckets = ALLOCBUCKETS(DEFAULT_ZONE, 1); - prototypes->info = NULL; - ((HashBucket *) prototypes->buckets)[0].count = 1; - ((HashBucket *) prototypes->buckets)[0].elements.one = &protoPrototype; -}; - -int NXPtrIsEqual (const void *info, const void *data1, const void *data2) { - return data1 == data2; -}; - -/************************************************************************* - * - * On z'y va - * - *************************************************************************/ - -NXHashTable *NXCreateHashTable (NXHashTablePrototype prototype, unsigned capacity, const void *info) { - return NXCreateHashTableFromZone(prototype, capacity, info, DEFAULT_ZONE); -} - -NXHashTable *NXCreateHashTableFromZone (NXHashTablePrototype prototype, unsigned capacity, const void *info, void *z) { - NXHashTable *table; - NXHashTablePrototype *proto; - - table = ALLOCTABLE(z); - if (! prototypes) bootstrap (); - if (! prototype.hash) prototype.hash = NXPtrHash; - if (! prototype.isEqual) prototype.isEqual = NXPtrIsEqual; - if (! prototype.free) prototype.free = NXNoEffectFree; - if (prototype.style) { - _objc_inform ("*** NXCreateHashTable: invalid style\n"); - return NULL; - }; - proto = (NXHashTablePrototype *)NXHashGet (prototypes, &prototype); - if (! proto) { - proto - = (NXHashTablePrototype *) malloc(sizeof (NXHashTablePrototype)); - bcopy ((const char*)&prototype, (char*)proto, sizeof (NXHashTablePrototype)); - (void) NXHashInsert (prototypes, proto); - proto = (NXHashTablePrototype *)NXHashGet (prototypes, &prototype); - if (! proto) { - _objc_inform ("*** NXCreateHashTable: bug\n"); - return NULL; - }; - }; - table->prototype = proto; table->count = 0; table->info = info; - table->nbBuckets = GOOD_CAPACITY(capacity); - table->buckets = ALLOCBUCKETS(z, table->nbBuckets); - return table; -} - -static void freeBucketPairs (void (*freeProc)(const void *info, void *data), HashBucket bucket, const void *info) { - unsigned j = bucket.count; - const void **pairs; - - if (j == 1) { - (*freeProc) (info, (void *) bucket.elements.one); - return; - }; - pairs = bucket.elements.many; - while (j--) { - (*freeProc) (info, (void *) *pairs); - pairs ++; - }; - FREEPAIRS (bucket.elements.many); -}; - -static void freeBuckets (NXHashTable *table, int freeObjects) { - unsigned i = table->nbBuckets; - HashBucket *buckets = (HashBucket *) table->buckets; - - while (i--) { - if (buckets->count) { - freeBucketPairs ((freeObjects) ? table->prototype->free : NXNoEffectFree, *buckets, table->info); - buckets->count = 0; - buckets->elements.one = NULL; - }; - buckets++; - }; -}; - -void NXFreeHashTable (NXHashTable *table) { - freeBuckets (table, YES); - free (table->buckets); - free (table); -}; - -void NXEmptyHashTable (NXHashTable *table) { - freeBuckets (table, NO); - table->count = 0; -} - -void NXResetHashTable (NXHashTable *table) { - freeBuckets (table, YES); - table->count = 0; -} - -BOOL NXCompareHashTables (NXHashTable *table1, NXHashTable *table2) { - if (table1 == table2) return YES; - if (NXCountHashTable (table1) != NXCountHashTable (table2)) return NO; - else { - void *data; - NXHashState state = NXInitHashState (table1); - while (NXNextHashState (table1, &state, &data)) { - if (! NXHashMember (table2, data)) return NO; - } - return YES; - } -} - -NXHashTable *NXCopyHashTable (NXHashTable *table) { - NXHashTable *newt; - NXHashState state = NXInitHashState (table); - void *data; - __unused void *z = ZONE_FROM_PTR(table); - - newt = ALLOCTABLE(z); - newt->prototype = table->prototype; newt->count = 0; - newt->info = table->info; - newt->nbBuckets = table->nbBuckets; - newt->buckets = ALLOCBUCKETS(z, newt->nbBuckets); - while (NXNextHashState (table, &state, &data)) - NXHashInsert (newt, data); - return newt; -} - -unsigned NXCountHashTable (NXHashTable *table) { - return table->count; -} - -int NXHashMember (NXHashTable *table, const void *data) { - HashBucket *bucket = BUCKETOF(table, data); - unsigned j = bucket->count; - const void **pairs; - - if (! j) return 0; - if (j == 1) { - return ISEQUAL(table, data, bucket->elements.one); - }; - pairs = bucket->elements.many; - while (j--) { - /* we don't cache isEqual because lists are short */ - if (ISEQUAL(table, data, *pairs)) return 1; - pairs ++; - }; - return 0; -} - -void *NXHashGet (NXHashTable *table, const void *data) { - HashBucket *bucket = BUCKETOF(table, data); - unsigned j = bucket->count; - const void **pairs; - - if (! j) return NULL; - if (j == 1) { - return ISEQUAL(table, data, bucket->elements.one) - ? (void *) bucket->elements.one : NULL; - }; - pairs = bucket->elements.many; - while (j--) { - /* we don't cache isEqual because lists are short */ - if (ISEQUAL(table, data, *pairs)) return (void *) *pairs; - pairs ++; - }; - return NULL; -} - -unsigned _NXHashCapacity (NXHashTable *table) { - return table->nbBuckets; -} - -void _NXHashRehashToCapacity (NXHashTable *table, unsigned newCapacity) { - /* Rehash: we create a pseudo table pointing really to the old guys, - extend self, copy the old pairs, and free the pseudo table */ - NXHashTable *old; - NXHashState state; - void *aux; - __unused void *z = ZONE_FROM_PTR(table); - - old = ALLOCTABLE(z); - old->prototype = table->prototype; old->count = table->count; - old->nbBuckets = table->nbBuckets; old->buckets = table->buckets; - table->nbBuckets = newCapacity; - table->count = 0; table->buckets = ALLOCBUCKETS(z, table->nbBuckets); - state = NXInitHashState (old); - while (NXNextHashState (old, &state, &aux)) - (void) NXHashInsert (table, aux); - freeBuckets (old, NO); - if (old->count != table->count) - _objc_inform("*** hashtable: count differs after rehashing; probably indicates a broken invariant: there are x and y such as isEqual(x, y) is TRUE but hash(x) != hash (y)\n"); - free (old->buckets); - free (old); -} - -static void _NXHashRehash (NXHashTable *table) { - _NXHashRehashToCapacity (table, MORE_CAPACITY(table->nbBuckets)); -} - -void *NXHashInsert (NXHashTable *table, const void *data) { - HashBucket *bucket = BUCKETOF(table, data); - unsigned j = bucket->count; - const void **pairs; - const void **newt; - __unused void *z = ZONE_FROM_PTR(table); - - if (! j) { - bucket->count++; bucket->elements.one = data; - table->count++; - return NULL; - }; - if (j == 1) { - if (ISEQUAL(table, data, bucket->elements.one)) { - const void *old = bucket->elements.one; - bucket->elements.one = data; - return (void *) old; - }; - newt = ALLOCPAIRS(z, 2); - newt[1] = bucket->elements.one; - *newt = data; - bucket->count++; bucket->elements.many = newt; - table->count++; - if (table->count > table->nbBuckets) _NXHashRehash (table); - return NULL; - }; - pairs = bucket->elements.many; - while (j--) { - /* we don't cache isEqual because lists are short */ - if (ISEQUAL(table, data, *pairs)) { - const void *old = *pairs; - *pairs = data; - return (void *) old; - }; - pairs ++; - }; - /* we enlarge this bucket; and put new data in front */ - newt = ALLOCPAIRS(z, bucket->count+1); - if (bucket->count) bcopy ((const char*)bucket->elements.many, (char*)(newt+1), bucket->count * PTRSIZE); - *newt = data; - FREEPAIRS (bucket->elements.many); - bucket->count++; bucket->elements.many = newt; - table->count++; - if (table->count > table->nbBuckets) _NXHashRehash (table); - return NULL; -} - -void *NXHashInsertIfAbsent (NXHashTable *table, const void *data) { - HashBucket *bucket = BUCKETOF(table, data); - unsigned j = bucket->count; - const void **pairs; - const void **newt; - __unused void *z = ZONE_FROM_PTR(table); - - if (! j) { - bucket->count++; bucket->elements.one = data; - table->count++; - return (void *) data; - }; - if (j == 1) { - if (ISEQUAL(table, data, bucket->elements.one)) - return (void *) bucket->elements.one; - newt = ALLOCPAIRS(z, 2); - newt[1] = bucket->elements.one; - *newt = data; - bucket->count++; bucket->elements.many = newt; - table->count++; - if (table->count > table->nbBuckets) _NXHashRehash (table); - return (void *) data; - }; - pairs = bucket->elements.many; - while (j--) { - /* we don't cache isEqual because lists are short */ - if (ISEQUAL(table, data, *pairs)) - return (void *) *pairs; - pairs ++; - }; - /* we enlarge this bucket; and put new data in front */ - newt = ALLOCPAIRS(z, bucket->count+1); - if (bucket->count) bcopy ((const char*)bucket->elements.many, (char*)(newt+1), bucket->count * PTRSIZE); - *newt = data; - FREEPAIRS (bucket->elements.many); - bucket->count++; bucket->elements.many = newt; - table->count++; - if (table->count > table->nbBuckets) _NXHashRehash (table); - return (void *) data; -} - -void *NXHashRemove (NXHashTable *table, const void *data) { - HashBucket *bucket = BUCKETOF(table, data); - unsigned j = bucket->count; - const void **pairs; - const void **newt; - __unused void *z = ZONE_FROM_PTR(table); - - if (! j) return NULL; - if (j == 1) { - if (! ISEQUAL(table, data, bucket->elements.one)) return NULL; - data = bucket->elements.one; - table->count--; bucket->count--; bucket->elements.one = NULL; - return (void *) data; - }; - pairs = bucket->elements.many; - if (j == 2) { - if (ISEQUAL(table, data, pairs[0])) { - bucket->elements.one = pairs[1]; data = pairs[0]; - } - else if (ISEQUAL(table, data, pairs[1])) { - bucket->elements.one = pairs[0]; data = pairs[1]; - } - else return NULL; - FREEPAIRS (pairs); - table->count--; bucket->count--; - return (void *) data; - }; - while (j--) { - if (ISEQUAL(table, data, *pairs)) { - data = *pairs; - /* we shrink this bucket */ - newt = (bucket->count-1) - ? ALLOCPAIRS(z, bucket->count-1) : NULL; - if (bucket->count-1 != j) - bcopy ((const char*)bucket->elements.many, (char*)newt, PTRSIZE*(bucket->count-j-1)); - if (j) - bcopy ((const char*)(bucket->elements.many + bucket->count-j), (char*)(newt+bucket->count-j-1), PTRSIZE*j); - FREEPAIRS (bucket->elements.many); - table->count--; bucket->count--; bucket->elements.many = newt; - return (void *) data; - }; - pairs ++; - }; - return NULL; -} - -NXHashState NXInitHashState (NXHashTable *table) { - NXHashState state; - - state.i = table->nbBuckets; - state.j = 0; - return state; -}; - -int NXNextHashState (NXHashTable *table, NXHashState *state, void **data) { - HashBucket *buckets = (HashBucket *) table->buckets; - - while (state->j == 0) { - if (state->i == 0) return NO; - state->i--; state->j = buckets[state->i].count; - } - state->j--; - buckets += state->i; - *data = (void *) ((buckets->count == 1) - ? buckets->elements.one : buckets->elements.many[state->j]); - return YES; -}; - -/************************************************************************* - * - * Conveniences - * - *************************************************************************/ - -uintptr_t NXPtrHash (const void *info, const void *data) { - return (((uintptr_t) data) >> 16) ^ ((uintptr_t) data); -}; - -uintptr_t NXStrHash (const void *info, const void *data) { - uintptr_t hash = 0; - unsigned char *s = (unsigned char *) data; - /* unsigned to avoid a sign-extend */ - /* unroll the loop */ - if (s) for (; ; ) { - if (*s == '\0') break; - hash ^= (uintptr_t) *s++; - if (*s == '\0') break; - hash ^= (uintptr_t) *s++ << 8; - if (*s == '\0') break; - hash ^= (uintptr_t) *s++ << 16; - if (*s == '\0') break; - hash ^= (uintptr_t) *s++ << 24; - } - return hash; -}; - -int NXStrIsEqual (const void *info, const void *data1, const void *data2) { - if (data1 == data2) return YES; - if (! data1) return ! strlen ((char *) data2); - if (! data2) return ! strlen ((char *) data1); - if (((char *) data1)[0] != ((char *) data2)[0]) return NO; - return (strcmp ((char *) data1, (char *) data2)) ? NO : YES; -}; - -void NXReallyFree (const void *info, void *data) { - free (data); -}; - -/* All the following functions are really private, made non-static only for the benefit of shlibs */ -static uintptr_t hashPtrStructKey (const void *info, const void *data) { - return NXPtrHash(info, *((void **) data)); -}; - -static int isEqualPtrStructKey (const void *info, const void *data1, const void *data2) { - return NXPtrIsEqual (info, *((void **) data1), *((void **) data2)); -}; - -static uintptr_t hashStrStructKey (const void *info, const void *data) { - return NXStrHash(info, *((char **) data)); -}; - -static int isEqualStrStructKey (const void *info, const void *data1, const void *data2) { - return NXStrIsEqual (info, *((char **) data1), *((char **) data2)); -}; - -const NXHashTablePrototype NXPtrPrototype = { - NXPtrHash, NXPtrIsEqual, NXNoEffectFree, 0 -}; - -const NXHashTablePrototype NXStrPrototype = { - NXStrHash, NXStrIsEqual, NXNoEffectFree, 0 -}; - -const NXHashTablePrototype NXPtrStructKeyPrototype = { - hashPtrStructKey, isEqualPtrStructKey, NXReallyFree, 0 -}; - -const NXHashTablePrototype NXStrStructKeyPrototype = { - hashStrStructKey, isEqualStrStructKey, NXReallyFree, 0 -}; - -/************************************************************************* - * - * Unique strings - * - *************************************************************************/ - -#if !__OBJC2__ && !TARGET_OS_WIN32 - -/* the implementation could be made faster at the expense of memory if the size of the strings were kept around */ -static NXHashTable *uniqueStrings = NULL; - -/* this is based on most apps using a few K of strings, and an average string size of 15 using sqrt(2*dataAlloced*perChunkOverhead) */ -#define CHUNK_SIZE 360 - -static int accessUniqueString = 0; - -static char *z = NULL; -static size_t zSize = 0; -static mutex_t uniquerLock; - -static const char *CopyIntoReadOnly (const char *str) { - size_t len = strlen (str) + 1; - char *result; - - if (len > CHUNK_SIZE/2) { /* dont let big strings waste space */ - result = (char *)malloc (len); - bcopy (str, result, len); - return result; - } - - mutex_locker_t lock(uniquerLock); - if (zSize < len) { - zSize = CHUNK_SIZE *((len + CHUNK_SIZE - 1) / CHUNK_SIZE); - /* not enough room, we try to allocate. If no room left, too bad */ - z = (char *)malloc (zSize); - }; - - result = z; - bcopy (str, result, len); - z += len; - zSize -= len; - return result; -}; - -NXAtom NXUniqueString (const char *buffer) { - const char *previous; - - if (! buffer) return buffer; - accessUniqueString++; - if (! uniqueStrings) - uniqueStrings = NXCreateHashTable (NXStrPrototype, 0, NULL); - previous = (const char *) NXHashGet (uniqueStrings, buffer); - if (previous) return previous; - previous = CopyIntoReadOnly (buffer); - if (NXHashInsert (uniqueStrings, previous)) { - _objc_inform ("*** NXUniqueString: invariant broken\n"); - return NULL; - }; - return previous; -}; - -NXAtom NXUniqueStringNoCopy (const char *string) { - accessUniqueString++; - if (! uniqueStrings) - uniqueStrings = NXCreateHashTable (NXStrPrototype, 0, NULL); - return (const char *) NXHashInsertIfAbsent (uniqueStrings, string); -}; - -#define BUF_SIZE 256 - -NXAtom NXUniqueStringWithLength (const char *buffer, int length) { - NXAtom atom; - char *nullTermStr; - char stackBuf[BUF_SIZE]; - - if (length+1 > BUF_SIZE) - nullTermStr = (char *)malloc (length+1); - else - nullTermStr = stackBuf; - bcopy (buffer, nullTermStr, length); - nullTermStr[length] = '\0'; - atom = NXUniqueString (nullTermStr); - if (length+1 > BUF_SIZE) - free (nullTermStr); - return atom; -}; - -char *NXCopyStringBufferFromZone (const char *str, void *zone) { -#if !SUPPORT_ZONES - return strdup(str); -#else - return strcpy ((char *) malloc_zone_malloc((malloc_zone_t *)zone, strlen (str) + 1), str); -#endif -}; - -char *NXCopyStringBuffer (const char *str) { - return strdup(str); -}; - -#endif diff --git a/objc/objc-runtime/runtime/llvm-AlignOf.h b/objc/objc-runtime/runtime/llvm-AlignOf.h deleted file mode 100644 index cad2422..0000000 --- a/objc/objc-runtime/runtime/llvm-AlignOf.h +++ /dev/null @@ -1,171 +0,0 @@ -//===--- AlignOf.h - Portable calculation of type alignment -----*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the AlignOf function that computes alignments for -// arbitrary types. -// -//===----------------------------------------------------------------------===// - -// Taken from llvmCore-3425.0.31. - -#ifndef LLVM_SUPPORT_ALIGNOF_H -#define LLVM_SUPPORT_ALIGNOF_H - -#include <cstddef> - -namespace objc { - -template <typename T> -struct AlignmentCalcImpl { - char x; - T t; -private: - AlignmentCalcImpl() {} // Never instantiate. -}; - -/// AlignOf - A templated class that contains an enum value representing -/// the alignment of the template argument. For example, -/// AlignOf<int>::Alignment represents the alignment of type "int". The -/// alignment calculated is the minimum alignment, and not necessarily -/// the "desired" alignment returned by GCC's __alignof__ (for example). Note -/// that because the alignment is an enum value, it can be used as a -/// compile-time constant (e.g., for template instantiation). -template <typename T> -struct AlignOf { - enum { Alignment = - static_cast<unsigned int>(sizeof(AlignmentCalcImpl<T>) - sizeof(T)) }; - - enum { Alignment_GreaterEqual_2Bytes = Alignment >= 2 ? 1 : 0 }; - enum { Alignment_GreaterEqual_4Bytes = Alignment >= 4 ? 1 : 0 }; - enum { Alignment_GreaterEqual_8Bytes = Alignment >= 8 ? 1 : 0 }; - enum { Alignment_GreaterEqual_16Bytes = Alignment >= 16 ? 1 : 0 }; - - enum { Alignment_LessEqual_2Bytes = Alignment <= 2 ? 1 : 0 }; - enum { Alignment_LessEqual_4Bytes = Alignment <= 4 ? 1 : 0 }; - enum { Alignment_LessEqual_8Bytes = Alignment <= 8 ? 1 : 0 }; - enum { Alignment_LessEqual_16Bytes = Alignment <= 16 ? 1 : 0 }; - -}; - -/// alignOf - A templated function that returns the minimum alignment of -/// of a type. This provides no extra functionality beyond the AlignOf -/// class besides some cosmetic cleanliness. Example usage: -/// alignOf<int>() returns the alignment of an int. -template <typename T> -inline unsigned alignOf() { return AlignOf<T>::Alignment; } - - -/// \brief Helper for building an aligned character array type. -/// -/// This template is used to explicitly build up a collection of aligned -/// character types. We have to build these up using a macro and explicit -/// specialization to cope with old versions of MSVC and GCC where only an -/// integer literal can be used to specify an alignment constraint. Once built -/// up here, we can then begin to indirect between these using normal C++ -/// template parameters. -template <size_t Alignment> struct AlignedCharArrayImpl; - -// MSVC requires special handling here. -#ifndef _MSC_VER - -#if __has_feature(cxx_alignas) -#define LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \ - template <> struct AlignedCharArrayImpl<x> { \ - char aligned alignas(x); \ - } -#elif defined(__GNUC__) -#define LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \ - template <> struct AlignedCharArrayImpl<x> { \ - char aligned __attribute__((aligned(x))); \ - } -#else -# error No supported align as directive. -#endif - -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(16); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(32); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(64); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(128); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(512); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1024); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2048); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4096); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8192); - -#undef LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT - -#else // _MSC_VER - -// We provide special variations of this template for the most common -// alignments because __declspec(align(...)) doesn't actually work when it is -// a member of a by-value function argument in MSVC, even if the alignment -// request is something reasonably like 8-byte or 16-byte. -template <> struct AlignedCharArrayImpl<1> { char aligned; }; -template <> struct AlignedCharArrayImpl<2> { short aligned; }; -template <> struct AlignedCharArrayImpl<4> { int aligned; }; -template <> struct AlignedCharArrayImpl<8> { double aligned; }; - -#define LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \ - template <> struct AlignedCharArrayImpl<x> { \ - __declspec(align(x)) char aligned; \ - } -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(16); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(32); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(64); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(128); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(512); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1024); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2048); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4096); -LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8192); -// Any larger and MSVC complains. -#undef LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT - -#endif // _MSC_VER - -/// \brief This union template exposes a suitably aligned and sized character -/// array member which can hold elements of any of up to four types. -/// -/// These types may be arrays, structs, or any other types. The goal is to -/// produce a union type containing a character array which, when used, forms -/// storage suitable to placement new any of these types over. Support for more -/// than four types can be added at the cost of more boiler plate. -template <typename T1, - typename T2 = char, typename T3 = char, typename T4 = char> -union AlignedCharArrayUnion { -private: - class AlignerImpl { - T1 t1; T2 t2; T3 t3; T4 t4; - - AlignerImpl(); // Never defined or instantiated. - }; - union SizerImpl { - char arr1[sizeof(T1)], arr2[sizeof(T2)], arr3[sizeof(T3)], arr4[sizeof(T4)]; - }; - -public: - /// \brief The character array buffer for use by clients. - /// - /// No other member of this union should be referenced. The exist purely to - /// constrain the layout of this character array. - char buffer[sizeof(SizerImpl)]; - -private: - // Tests seem to indicate that both Clang and GCC will properly register the - // alignment of a struct containing an aligned member, and this alignment - // should carry over to the character array in the union. - AlignedCharArrayImpl<AlignOf<AlignerImpl>::Alignment> nonce_member; -}; - -} // end namespace objc -#endif diff --git a/objc/objc-runtime/runtime/llvm-DenseMap.h b/objc/objc-runtime/runtime/llvm-DenseMap.h deleted file mode 100644 index 6fe1382..0000000 --- a/objc/objc-runtime/runtime/llvm-DenseMap.h +++ /dev/null @@ -1,1097 +0,0 @@ -//===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the DenseMap class. -// -//===----------------------------------------------------------------------===// - -// Taken from llvmCore-3425.0.31. - -#ifndef LLVM_ADT_DENSEMAP_H -#define LLVM_ADT_DENSEMAP_H - -#include "llvm-type_traits.h" -#include "llvm-MathExtras.h" -#include "llvm-AlignOf.h" -#include "llvm-DenseMapInfo.h" -#include <algorithm> -#include <iterator> -#include <new> -#include <utility> -#include <cassert> -#include <climits> -#include <cstddef> -#include <cstring> -#include <TargetConditionals.h> - -#include "objc-private.h" - -// From llvm/Support/Compiler.h -#define LLVM_USE_RVALUE_REFERENCES 1 -#define llvm_move(value) (::std::move(value)) - -#define MIN_BUCKETS 4 -#define MIN_COMPACT 1024 - - -namespace objc { - -template<typename KeyT, typename ValueT, - typename KeyInfoT = DenseMapInfo<KeyT>, - bool IsConst = false> -class DenseMapIterator; - -// ZeroValuesArePurgeable=true is used by the refcount table. -// A key/value pair with value==0 is not required to be stored -// in the refcount table; it could correctly be erased instead. -// For performance, we do keep zero values in the table when the -// true refcount decreases to 1: this makes any future retain faster. -// For memory size, we allow rehashes and table insertions to -// remove a zero value as if it were a tombstone. - -template<typename DerivedT, - typename KeyT, typename ValueT, typename KeyInfoT, - bool ZeroValuesArePurgeable = false> -class DenseMapBase { -protected: - typedef std::pair<KeyT, ValueT> BucketT; - -public: - typedef KeyT key_type; - typedef ValueT mapped_type; - typedef BucketT value_type; - - typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator; - typedef DenseMapIterator<KeyT, ValueT, - KeyInfoT, true> const_iterator; - inline iterator begin() { - // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets(). - return empty() ? end() : iterator(getBuckets(), getBucketsEnd()); - } - inline iterator end() { - return iterator(getBucketsEnd(), getBucketsEnd(), true); - } - inline const_iterator begin() const { - return empty() ? end() : const_iterator(getBuckets(), getBucketsEnd()); - } - inline const_iterator end() const { - return const_iterator(getBucketsEnd(), getBucketsEnd(), true); - } - - bool empty() const { return getNumEntries() == 0; } - unsigned size() const { return getNumEntries(); } - - /// Grow the densemap so that it has at least Size buckets. Does not shrink - void resize(size_t Size) { - if (Size > getNumBuckets()) - grow(Size); - } - - void clear() { - if (getNumEntries() == 0 && getNumTombstones() == 0) return; - - // If the capacity of the array is huge, and the # elements used is small, - // shrink the array. - if (getNumEntries() * 4 < getNumBuckets() && - getNumBuckets() > MIN_BUCKETS) { - shrink_and_clear(); - return; - } - - const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey(); - for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) { - if (!KeyInfoT::isEqual(P->first, EmptyKey)) { - if (!KeyInfoT::isEqual(P->first, TombstoneKey)) { - P->second.~ValueT(); - decrementNumEntries(); - } - P->first = EmptyKey; - } - } - assert(getNumEntries() == 0 && "Node count imbalance!"); - setNumTombstones(0); - } - - /// count - Return true if the specified key is in the map. - bool count(const KeyT &Val) const { - const BucketT *TheBucket; - return LookupBucketFor(Val, TheBucket); - } - - iterator find(const KeyT &Val) { - BucketT *TheBucket; - if (LookupBucketFor(Val, TheBucket)) - return iterator(TheBucket, getBucketsEnd(), true); - return end(); - } - const_iterator find(const KeyT &Val) const { - const BucketT *TheBucket; - if (LookupBucketFor(Val, TheBucket)) - return const_iterator(TheBucket, getBucketsEnd(), true); - return end(); - } - - /// Alternate version of find() which allows a different, and possibly - /// less expensive, key type. - /// The DenseMapInfo is responsible for supplying methods - /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key - /// type used. - template<class LookupKeyT> - iterator find_as(const LookupKeyT &Val) { - BucketT *TheBucket; - if (LookupBucketFor(Val, TheBucket)) - return iterator(TheBucket, getBucketsEnd(), true); - return end(); - } - template<class LookupKeyT> - const_iterator find_as(const LookupKeyT &Val) const { - const BucketT *TheBucket; - if (LookupBucketFor(Val, TheBucket)) - return const_iterator(TheBucket, getBucketsEnd(), true); - return end(); - } - - /// lookup - Return the entry for the specified key, or a default - /// constructed value if no such entry exists. - ValueT lookup(const KeyT &Val) const { - const BucketT *TheBucket; - if (LookupBucketFor(Val, TheBucket)) - return TheBucket->second; - return ValueT(); - } - - // Inserts key,value pair into the map if the key isn't already in the map. - // If the key is already in the map, it returns false and doesn't update the - // value. - std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) { - BucketT *TheBucket; - if (LookupBucketFor(KV.first, TheBucket)) - return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), - false); // Already in map. - - // Otherwise, insert the new element. - TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket); - return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), true); - } - - /// insert - Range insertion of pairs. - template<typename InputIt> - void insert(InputIt I, InputIt E) { - for (; I != E; ++I) - insert(*I); - } - - // Clear if empty. - // Shrink if at least 15/16 empty and larger than MIN_COMPACT. - void compact() { - if (getNumEntries() == 0) { - shrink_and_clear(); - } - else if (getNumBuckets() / 16 > getNumEntries() && - getNumBuckets() > MIN_COMPACT) - { - grow(getNumEntries() * 2); - } - } - - bool erase(const KeyT &Val) { - BucketT *TheBucket; - if (!LookupBucketFor(Val, TheBucket)) - return false; // not in map. - - TheBucket->second.~ValueT(); - TheBucket->first = getTombstoneKey(); - decrementNumEntries(); - incrementNumTombstones(); - compact(); - return true; - } - void erase(iterator I) { - BucketT *TheBucket = &*I; - TheBucket->second.~ValueT(); - TheBucket->first = getTombstoneKey(); - decrementNumEntries(); - incrementNumTombstones(); - compact(); - } - - value_type& FindAndConstruct(const KeyT &Key) { - BucketT *TheBucket; - if (LookupBucketFor(Key, TheBucket)) - return *TheBucket; - - return *InsertIntoBucket(Key, ValueT(), TheBucket); - } - - ValueT &operator[](const KeyT &Key) { - return FindAndConstruct(Key).second; - } - -#if LLVM_USE_RVALUE_REFERENCES - value_type& FindAndConstruct(KeyT &&Key) { - BucketT *TheBucket; - if (LookupBucketFor(Key, TheBucket)) - return *TheBucket; - - return *InsertIntoBucket(Key, ValueT(), TheBucket); - } - - ValueT &operator[](KeyT &&Key) { - return FindAndConstruct(Key).second; - } -#endif - - /// isPointerIntoBucketsArray - Return true if the specified pointer points - /// somewhere into the DenseMap's array of buckets (i.e. either to a key or - /// value in the DenseMap). - bool isPointerIntoBucketsArray(const void *Ptr) const { - return Ptr >= getBuckets() && Ptr < getBucketsEnd(); - } - - /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets - /// array. In conjunction with the previous method, this can be used to - /// determine whether an insertion caused the DenseMap to reallocate. - const void *getPointerIntoBucketsArray() const { return getBuckets(); } - -protected: - DenseMapBase() {} - - void destroyAll() { - if (getNumBuckets() == 0) // Nothing to do. - return; - - const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey(); - for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) { - if (!KeyInfoT::isEqual(P->first, EmptyKey) && - !KeyInfoT::isEqual(P->first, TombstoneKey)) - P->second.~ValueT(); - P->first.~KeyT(); - } - -#ifndef NDEBUG - memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets()); -#endif - } - - void initEmpty() { - setNumEntries(0); - setNumTombstones(0); - - assert((getNumBuckets() & (getNumBuckets()-1)) == 0 && - "# initial buckets must be a power of two!"); - const KeyT EmptyKey = getEmptyKey(); - for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B) - new (&B->first) KeyT(EmptyKey); - } - - void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) { - initEmpty(); - - // Insert all the old elements. - const KeyT EmptyKey = getEmptyKey(); - const KeyT TombstoneKey = getTombstoneKey(); - for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) { - if (!KeyInfoT::isEqual(B->first, EmptyKey) && - !KeyInfoT::isEqual(B->first, TombstoneKey) && - !(ZeroValuesArePurgeable && B->second == 0)) { - // Insert the key/value into the new table. - BucketT *DestBucket; - bool FoundVal = LookupBucketFor(B->first, DestBucket); - (void)FoundVal; // silence warning. - assert(!FoundVal && "Key already in new map?"); - DestBucket->first = llvm_move(B->first); - new (&DestBucket->second) ValueT(llvm_move(B->second)); - incrementNumEntries(); - - // Free the value. - B->second.~ValueT(); - } - B->first.~KeyT(); - } - -#ifndef NDEBUG - if (OldBucketsBegin != OldBucketsEnd) - memset((void*)OldBucketsBegin, 0x5a, - sizeof(BucketT) * (OldBucketsEnd - OldBucketsBegin)); -#endif - } - - template <typename OtherBaseT> - void copyFrom(const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT>& other) { - assert(getNumBuckets() == other.getNumBuckets()); - - setNumEntries(other.getNumEntries()); - setNumTombstones(other.getNumTombstones()); - - if (isPodLike<KeyT>::value && isPodLike<ValueT>::value) - memcpy(getBuckets(), other.getBuckets(), - getNumBuckets() * sizeof(BucketT)); - else - for (size_t i = 0; i < getNumBuckets(); ++i) { - new (&getBuckets()[i].first) KeyT(other.getBuckets()[i].first); - if (!KeyInfoT::isEqual(getBuckets()[i].first, getEmptyKey()) && - !KeyInfoT::isEqual(getBuckets()[i].first, getTombstoneKey())) - new (&getBuckets()[i].second) ValueT(other.getBuckets()[i].second); - } - } - - void swap(DenseMapBase& RHS) { - std::swap(getNumEntries(), RHS.getNumEntries()); - std::swap(getNumTombstones(), RHS.getNumTombstones()); - } - - static unsigned getHashValue(const KeyT &Val) { - return KeyInfoT::getHashValue(Val); - } - template<typename LookupKeyT> - static unsigned getHashValue(const LookupKeyT &Val) { - return KeyInfoT::getHashValue(Val); - } - static const KeyT getEmptyKey() { - return KeyInfoT::getEmptyKey(); - } - static const KeyT getTombstoneKey() { - return KeyInfoT::getTombstoneKey(); - } - -private: - unsigned getNumEntries() const { - return static_cast<const DerivedT *>(this)->getNumEntries(); - } - void setNumEntries(unsigned Num) { - static_cast<DerivedT *>(this)->setNumEntries(Num); - } - void incrementNumEntries() { - setNumEntries(getNumEntries() + 1); - } - void decrementNumEntries() { - setNumEntries(getNumEntries() - 1); - } - unsigned getNumTombstones() const { - return static_cast<const DerivedT *>(this)->getNumTombstones(); - } - void setNumTombstones(unsigned Num) { - static_cast<DerivedT *>(this)->setNumTombstones(Num); - } - void incrementNumTombstones() { - setNumTombstones(getNumTombstones() + 1); - } - void decrementNumTombstones() { - setNumTombstones(getNumTombstones() - 1); - } - const BucketT *getBuckets() const { - return static_cast<const DerivedT *>(this)->getBuckets(); - } - BucketT *getBuckets() { - return static_cast<DerivedT *>(this)->getBuckets(); - } - unsigned getNumBuckets() const { - return static_cast<const DerivedT *>(this)->getNumBuckets(); - } - BucketT *getBucketsEnd() { - return getBuckets() + getNumBuckets(); - } - const BucketT *getBucketsEnd() const { - return getBuckets() + getNumBuckets(); - } - - void grow(unsigned AtLeast) { - static_cast<DerivedT *>(this)->grow(AtLeast); - } - - void shrink_and_clear() { - static_cast<DerivedT *>(this)->shrink_and_clear(); - } - - - BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value, - BucketT *TheBucket) { - TheBucket = InsertIntoBucketImpl(Key, TheBucket); - - TheBucket->first = Key; - new (&TheBucket->second) ValueT(Value); - return TheBucket; - } - -#if LLVM_USE_RVALUE_REFERENCES - BucketT *InsertIntoBucket(const KeyT &Key, ValueT &&Value, - BucketT *TheBucket) { - TheBucket = InsertIntoBucketImpl(Key, TheBucket); - - TheBucket->first = Key; - new (&TheBucket->second) ValueT(std::move(Value)); - return TheBucket; - } - - BucketT *InsertIntoBucket(KeyT &&Key, ValueT &&Value, BucketT *TheBucket) { - TheBucket = InsertIntoBucketImpl(Key, TheBucket); - - TheBucket->first = std::move(Key); - new (&TheBucket->second) ValueT(std::move(Value)); - return TheBucket; - } -#endif - - BucketT *InsertIntoBucketImpl(const KeyT &Key, BucketT *TheBucket) { - // If the load of the hash table is more than 3/4, grow the table. - // If fewer than 1/8 of the buckets are empty (meaning that many are - // filled with tombstones), rehash the table without growing. - // - // The later case is tricky. For example, if we had one empty bucket with - // tons of tombstones, failing lookups (e.g. for insertion) would have to - // probe almost the entire table until it found the empty bucket. If the - // table completely filled with tombstones, no lookup would ever succeed, - // causing infinite loops in lookup. - unsigned NewNumEntries = getNumEntries() + 1; - unsigned NumBuckets = getNumBuckets(); - if (NewNumEntries*4 >= NumBuckets*3) { - this->grow(NumBuckets * 2); - LookupBucketFor(Key, TheBucket); - NumBuckets = getNumBuckets(); - } - if (NumBuckets-(NewNumEntries+getNumTombstones()) <= NumBuckets/8) { - this->grow(NumBuckets); - LookupBucketFor(Key, TheBucket); - } - assert(TheBucket); - - // Only update the state after we've grown our bucket space appropriately - // so that when growing buckets we have self-consistent entry count. - // If we are writing over a tombstone or zero value, remember this. - if (KeyInfoT::isEqual(TheBucket->first, getEmptyKey())) { - // Replacing an empty bucket. - incrementNumEntries(); - } - else if (KeyInfoT::isEqual(TheBucket->first, getTombstoneKey())) { - // Replacing a tombstone. - incrementNumEntries(); - decrementNumTombstones(); - } - else if (ZeroValuesArePurgeable && TheBucket->second == 0) { - // Purging a zero. No accounting changes. - TheBucket->second.~ValueT(); - } else { - // Updating an existing entry. No accounting changes. - } - - return TheBucket; - } - - /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in - /// FoundBucket. If the bucket contains the key and a value, this returns - /// true, otherwise it returns a bucket with an empty marker or tombstone - /// or zero value and returns false. - template<typename LookupKeyT> - bool LookupBucketFor(const LookupKeyT &Val, - const BucketT *&FoundBucket) const { - const BucketT *BucketsPtr = getBuckets(); - const unsigned NumBuckets = getNumBuckets(); - - if (NumBuckets == 0) { - FoundBucket = 0; - return false; - } - - // FoundTombstone - Keep track of whether we find a tombstone or zero value while probing. - const BucketT *FoundTombstone = 0; - const KeyT EmptyKey = getEmptyKey(); - const KeyT TombstoneKey = getTombstoneKey(); - assert(!KeyInfoT::isEqual(Val, EmptyKey) && - !KeyInfoT::isEqual(Val, TombstoneKey) && - "Empty/Tombstone value shouldn't be inserted into map!"); - - unsigned BucketNo = getHashValue(Val) & (NumBuckets-1); - unsigned ProbeAmt = 1; - while (1) { - const BucketT *ThisBucket = BucketsPtr + BucketNo; - // Found Val's bucket? If so, return it. - if (KeyInfoT::isEqual(Val, ThisBucket->first)) { - FoundBucket = ThisBucket; - return true; - } - - // If we found an empty bucket, the key doesn't exist in the set. - // Insert it and return the default value. - if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) { - // If we've already seen a tombstone while probing, fill it in instead - // of the empty bucket we eventually probed to. - if (FoundTombstone) ThisBucket = FoundTombstone; - FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket; - return false; - } - - // If this is a tombstone, remember it. If Val ends up not in the map, we - // prefer to return it than something that would require more probing. - // Ditto for zero values. - if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone) - FoundTombstone = ThisBucket; // Remember the first tombstone found. - if (ZeroValuesArePurgeable && - ThisBucket->second == 0 && !FoundTombstone) - FoundTombstone = ThisBucket; - - // Otherwise, it's a hash collision or a tombstone, continue quadratic - // probing. - if (ProbeAmt > NumBuckets) { - // No empty buckets in table. Die. - _objc_fatal("Hash table corrupted. This is probably a memory error " - "somewhere. (table at %p, buckets at %p (%zu bytes), " - "%u buckets, %u entries, %u tombstones, " - "data %p %p %p %p)", - this, BucketsPtr, malloc_size(BucketsPtr), - NumBuckets, getNumEntries(), getNumTombstones(), - ((void**)BucketsPtr)[0], ((void**)BucketsPtr)[1], - ((void**)BucketsPtr)[2], ((void**)BucketsPtr)[3]); - } - BucketNo += ProbeAmt++; - BucketNo&= (NumBuckets-1); - } - } - - template <typename LookupKeyT> - bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) { - const BucketT *ConstFoundBucket; - bool Result = const_cast<const DenseMapBase *>(this) - ->LookupBucketFor(Val, ConstFoundBucket); - FoundBucket = const_cast<BucketT *>(ConstFoundBucket); - return Result; - } - -public: - /// Return the approximate size (in bytes) of the actual map. - /// This is just the raw memory used by DenseMap. - /// If entries are pointers to objects, the size of the referenced objects - /// are not included. - size_t getMemorySize() const { - return getNumBuckets() * sizeof(BucketT); - } -}; - -template<typename KeyT, typename ValueT, - bool ZeroValuesArePurgeable = false, - typename KeyInfoT = DenseMapInfo<KeyT> > -class DenseMap - : public DenseMapBase<DenseMap<KeyT, ValueT, ZeroValuesArePurgeable, KeyInfoT>, - KeyT, ValueT, KeyInfoT, ZeroValuesArePurgeable> { - // Lift some types from the dependent base class into this class for - // simplicity of referring to them. - typedef DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, ZeroValuesArePurgeable> BaseT; - typedef typename BaseT::BucketT BucketT; - friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, ZeroValuesArePurgeable>; - - BucketT *Buckets; - unsigned NumEntries; - unsigned NumTombstones; - unsigned NumBuckets; - -public: - explicit DenseMap(unsigned NumInitBuckets = 0) { - init(NumInitBuckets); - } - - DenseMap(const DenseMap &other) { - init(0); - copyFrom(other); - } - -#if LLVM_USE_RVALUE_REFERENCES - DenseMap(DenseMap &&other) { - init(0); - swap(other); - } -#endif - - template<typename InputIt> - DenseMap(const InputIt &I, const InputIt &E) { - init(NextPowerOf2(std::distance(I, E))); - this->insert(I, E); - } - - ~DenseMap() { - this->destroyAll(); - operator delete(Buckets); - } - - void swap(DenseMap& RHS) { - std::swap(Buckets, RHS.Buckets); - std::swap(NumEntries, RHS.NumEntries); - std::swap(NumTombstones, RHS.NumTombstones); - std::swap(NumBuckets, RHS.NumBuckets); - } - - DenseMap& operator=(const DenseMap& other) { - copyFrom(other); - return *this; - } - -#if LLVM_USE_RVALUE_REFERENCES - DenseMap& operator=(DenseMap &&other) { - this->destroyAll(); - operator delete(Buckets); - init(0); - swap(other); - return *this; - } -#endif - - void copyFrom(const DenseMap& other) { - this->destroyAll(); - operator delete(Buckets); - if (allocateBuckets(other.NumBuckets)) { - this->BaseT::copyFrom(other); - } else { - NumEntries = 0; - NumTombstones = 0; - } - } - - void init(unsigned InitBuckets) { - if (allocateBuckets(InitBuckets)) { - this->BaseT::initEmpty(); - } else { - NumEntries = 0; - NumTombstones = 0; - } - } - - void grow(unsigned AtLeast) { - unsigned OldNumBuckets = NumBuckets; - BucketT *OldBuckets = Buckets; - - allocateBuckets(std::max<unsigned>(MIN_BUCKETS, NextPowerOf2(AtLeast))); - assert(Buckets); - if (!OldBuckets) { - this->BaseT::initEmpty(); - return; - } - - this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets); - - // Free the old table. - operator delete(OldBuckets); - } - - void shrink_and_clear() { - unsigned OldNumEntries = NumEntries; - this->destroyAll(); - - // Reduce the number of buckets. - unsigned NewNumBuckets = 0; - if (OldNumEntries) - NewNumBuckets = std::max(MIN_BUCKETS, 1 << (Log2_32_Ceil(OldNumEntries) + 1)); - if (NewNumBuckets == NumBuckets) { - this->BaseT::initEmpty(); - return; - } - - operator delete(Buckets); - init(NewNumBuckets); - } - -private: - unsigned getNumEntries() const { - return NumEntries; - } - void setNumEntries(unsigned Num) { - NumEntries = Num; - } - - unsigned getNumTombstones() const { - return NumTombstones; - } - void setNumTombstones(unsigned Num) { - NumTombstones = Num; - } - - BucketT *getBuckets() const { - return Buckets; - } - - unsigned getNumBuckets() const { - return NumBuckets; - } - - bool allocateBuckets(unsigned Num) { - NumBuckets = Num; - if (NumBuckets == 0) { - Buckets = 0; - return false; - } - - Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets)); - return true; - } -}; - -template<typename KeyT, typename ValueT, - unsigned InlineBuckets = 4, - bool ZeroValuesArePurgeable = false, - typename KeyInfoT = DenseMapInfo<KeyT> > -class SmallDenseMap - : public DenseMapBase<SmallDenseMap<KeyT, ValueT, InlineBuckets, ZeroValuesArePurgeable, KeyInfoT>, - KeyT, ValueT, KeyInfoT, ZeroValuesArePurgeable> { - // Lift some types from the dependent base class into this class for - // simplicity of referring to them. - typedef DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, ZeroValuesArePurgeable> BaseT; - typedef typename BaseT::BucketT BucketT; - friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, ZeroValuesArePurgeable>; - - unsigned Small : 1; - unsigned NumEntries : 31; - unsigned NumTombstones; - - struct LargeRep { - BucketT *Buckets; - unsigned NumBuckets; - }; - - /// A "union" of an inline bucket array and the struct representing - /// a large bucket. This union will be discriminated by the 'Small' bit. - AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage; - -public: - explicit SmallDenseMap(unsigned NumInitBuckets = 0) { - init(NumInitBuckets); - } - - SmallDenseMap(const SmallDenseMap &other) { - init(0); - copyFrom(other); - } - -#if LLVM_USE_RVALUE_REFERENCES - SmallDenseMap(SmallDenseMap &&other) { - init(0); - swap(other); - } -#endif - - template<typename InputIt> - SmallDenseMap(const InputIt &I, const InputIt &E) { - init(NextPowerOf2(std::distance(I, E))); - this->insert(I, E); - } - - ~SmallDenseMap() { - this->destroyAll(); - deallocateBuckets(); - } - - void swap(SmallDenseMap& RHS) { - unsigned TmpNumEntries = RHS.NumEntries; - RHS.NumEntries = NumEntries; - NumEntries = TmpNumEntries; - std::swap(NumTombstones, RHS.NumTombstones); - - const KeyT EmptyKey = this->getEmptyKey(); - const KeyT TombstoneKey = this->getTombstoneKey(); - if (Small && RHS.Small) { - // If we're swapping inline bucket arrays, we have to cope with some of - // the tricky bits of DenseMap's storage system: the buckets are not - // fully initialized. Thus we swap every key, but we may have - // a one-directional move of the value. - for (unsigned i = 0, e = InlineBuckets; i != e; ++i) { - BucketT *LHSB = &getInlineBuckets()[i], - *RHSB = &RHS.getInlineBuckets()[i]; - bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->first, EmptyKey) && - !KeyInfoT::isEqual(LHSB->first, TombstoneKey)); - bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->first, EmptyKey) && - !KeyInfoT::isEqual(RHSB->first, TombstoneKey)); - if (hasLHSValue && hasRHSValue) { - // Swap together if we can... - std::swap(*LHSB, *RHSB); - continue; - } - // Swap separately and handle any assymetry. - std::swap(LHSB->first, RHSB->first); - if (hasLHSValue) { - new (&RHSB->second) ValueT(llvm_move(LHSB->second)); - LHSB->second.~ValueT(); - } else if (hasRHSValue) { - new (&LHSB->second) ValueT(llvm_move(RHSB->second)); - RHSB->second.~ValueT(); - } - } - return; - } - if (!Small && !RHS.Small) { - std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets); - std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets); - return; - } - - SmallDenseMap &SmallSide = Small ? *this : RHS; - SmallDenseMap &LargeSide = Small ? RHS : *this; - - // First stash the large side's rep and move the small side across. - LargeRep TmpRep = llvm_move(*LargeSide.getLargeRep()); - LargeSide.getLargeRep()->~LargeRep(); - LargeSide.Small = true; - // This is similar to the standard move-from-old-buckets, but the bucket - // count hasn't actually rotated in this case. So we have to carefully - // move construct the keys and values into their new locations, but there - // is no need to re-hash things. - for (unsigned i = 0, e = InlineBuckets; i != e; ++i) { - BucketT *NewB = &LargeSide.getInlineBuckets()[i], - *OldB = &SmallSide.getInlineBuckets()[i]; - new (&NewB->first) KeyT(llvm_move(OldB->first)); - OldB->first.~KeyT(); - if (!KeyInfoT::isEqual(NewB->first, EmptyKey) && - !KeyInfoT::isEqual(NewB->first, TombstoneKey)) { - new (&NewB->second) ValueT(llvm_move(OldB->second)); - OldB->second.~ValueT(); - } - } - - // The hard part of moving the small buckets across is done, just move - // the TmpRep into its new home. - SmallSide.Small = false; - new (SmallSide.getLargeRep()) LargeRep(llvm_move(TmpRep)); - } - - SmallDenseMap& operator=(const SmallDenseMap& other) { - copyFrom(other); - return *this; - } - -#if LLVM_USE_RVALUE_REFERENCES - SmallDenseMap& operator=(SmallDenseMap &&other) { - this->destroyAll(); - deallocateBuckets(); - init(0); - swap(other); - return *this; - } -#endif - - void copyFrom(const SmallDenseMap& other) { - this->destroyAll(); - deallocateBuckets(); - Small = true; - if (other.getNumBuckets() > InlineBuckets) { - Small = false; - allocateBuckets(other.getNumBuckets()); - } - this->BaseT::copyFrom(other); - } - - void init(unsigned InitBuckets) { - Small = true; - if (InitBuckets > InlineBuckets) { - Small = false; - new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets)); - } - this->BaseT::initEmpty(); - } - - void grow(unsigned AtLeast) { - if (AtLeast > InlineBuckets) - AtLeast = std::max<unsigned>(MIN_BUCKETS, NextPowerOf2(AtLeast)); - - if (Small) { - if (AtLeast <= InlineBuckets) - return; // Nothing to do. - - // First move the inline buckets into a temporary storage. - AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage; - BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer); - BucketT *TmpEnd = TmpBegin; - - // Loop over the buckets, moving non-empty, non-tombstones into the - // temporary storage. Have the loop move the TmpEnd forward as it goes. - const KeyT EmptyKey = this->getEmptyKey(); - const KeyT TombstoneKey = this->getTombstoneKey(); - for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) { - if (!KeyInfoT::isEqual(P->first, EmptyKey) && - !KeyInfoT::isEqual(P->first, TombstoneKey)) { - assert(size_t(TmpEnd - TmpBegin) < InlineBuckets && - "Too many inline buckets!"); - new (&TmpEnd->first) KeyT(llvm_move(P->first)); - new (&TmpEnd->second) ValueT(llvm_move(P->second)); - ++TmpEnd; - P->second.~ValueT(); - } - P->first.~KeyT(); - } - - // Now make this map use the large rep, and move all the entries back - // into it. - Small = false; - new (getLargeRep()) LargeRep(allocateBuckets(AtLeast)); - this->moveFromOldBuckets(TmpBegin, TmpEnd); - return; - } - - LargeRep OldRep = llvm_move(*getLargeRep()); - getLargeRep()->~LargeRep(); - if (AtLeast <= InlineBuckets) { - Small = true; - } else { - new (getLargeRep()) LargeRep(allocateBuckets(AtLeast)); - } - - this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets); - - // Free the old table. - operator delete(OldRep.Buckets); - } - - void shrink_and_clear() { - unsigned OldSize = this->size(); - this->destroyAll(); - - // Reduce the number of buckets. - unsigned NewNumBuckets = 0; - if (OldSize) { - NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1); - if (NewNumBuckets > InlineBuckets && NewNumBuckets < MIN_BUCKETS) - NewNumBuckets = MIN_BUCKETS; - } - if ((Small && NewNumBuckets <= InlineBuckets) || - (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) { - this->BaseT::initEmpty(); - return; - } - - deallocateBuckets(); - init(NewNumBuckets); - } - -private: - unsigned getNumEntries() const { - return NumEntries; - } - void setNumEntries(unsigned Num) { - assert(Num < INT_MAX && "Cannot support more than INT_MAX entries"); - NumEntries = Num; - } - - unsigned getNumTombstones() const { - return NumTombstones; - } - void setNumTombstones(unsigned Num) { - NumTombstones = Num; - } - - const BucketT *getInlineBuckets() const { - assert(Small); - // Note that this cast does not violate aliasing rules as we assert that - // the memory's dynamic type is the small, inline bucket buffer, and the - // 'storage.buffer' static type is 'char *'. - return reinterpret_cast<const BucketT *>(storage.buffer); - } - BucketT *getInlineBuckets() { - return const_cast<BucketT *>( - const_cast<const SmallDenseMap *>(this)->getInlineBuckets()); - } - const LargeRep *getLargeRep() const { - assert(!Small); - // Note, same rule about aliasing as with getInlineBuckets. - return reinterpret_cast<const LargeRep *>(storage.buffer); - } - LargeRep *getLargeRep() { - return const_cast<LargeRep *>( - const_cast<const SmallDenseMap *>(this)->getLargeRep()); - } - - const BucketT *getBuckets() const { - return Small ? getInlineBuckets() : getLargeRep()->Buckets; - } - BucketT *getBuckets() { - return const_cast<BucketT *>( - const_cast<const SmallDenseMap *>(this)->getBuckets()); - } - unsigned getNumBuckets() const { - return Small ? InlineBuckets : getLargeRep()->NumBuckets; - } - - void deallocateBuckets() { - if (Small) - return; - - operator delete(getLargeRep()->Buckets); - getLargeRep()->~LargeRep(); - } - - LargeRep allocateBuckets(unsigned Num) { - assert(Num > InlineBuckets && "Must allocate more buckets than are inline"); - LargeRep Rep = { - static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num -}; - return Rep; - } -}; - -template<typename KeyT, typename ValueT, - typename KeyInfoT, bool IsConst> -class DenseMapIterator { - typedef std::pair<KeyT, ValueT> Bucket; - typedef DenseMapIterator<KeyT, ValueT, - KeyInfoT, true> ConstIterator; - friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, true>; -public: - typedef ptrdiff_t difference_type; - typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type; - typedef value_type *pointer; - typedef value_type &reference; - typedef std::forward_iterator_tag iterator_category; -private: - pointer Ptr, End; -public: - DenseMapIterator() : Ptr(0), End(0) {} - - DenseMapIterator(pointer Pos, pointer E, bool NoAdvance = false) - : Ptr(Pos), End(E) { - if (!NoAdvance) AdvancePastEmptyBuckets(); - } - - // If IsConst is true this is a converting constructor from iterator to - // const_iterator and the default copy constructor is used. - // Otherwise this is a copy constructor for iterator. - DenseMapIterator(const DenseMapIterator<KeyT, ValueT, - KeyInfoT, false>& I) - : Ptr(I.Ptr), End(I.End) {} - - reference operator*() const { - return *Ptr; - } - pointer operator->() const { - return Ptr; - } - - bool operator==(const ConstIterator &RHS) const { - return Ptr == RHS.operator->(); - } - bool operator!=(const ConstIterator &RHS) const { - return Ptr != RHS.operator->(); - } - - inline DenseMapIterator& operator++() { // Preincrement - ++Ptr; - AdvancePastEmptyBuckets(); - return *this; - } - DenseMapIterator operator++(int) { // Postincrement - DenseMapIterator tmp = *this; ++*this; return tmp; - } - -private: - void AdvancePastEmptyBuckets() { - const KeyT Empty = KeyInfoT::getEmptyKey(); - const KeyT Tombstone = KeyInfoT::getTombstoneKey(); - - while (Ptr != End && - (KeyInfoT::isEqual(Ptr->first, Empty) || - KeyInfoT::isEqual(Ptr->first, Tombstone))) - ++Ptr; - } -}; - -} // end namespace objc - -#endif diff --git a/objc/objc-runtime/runtime/llvm-DenseMapInfo.h b/objc/objc-runtime/runtime/llvm-DenseMapInfo.h deleted file mode 100644 index 5ed0e62..0000000 --- a/objc/objc-runtime/runtime/llvm-DenseMapInfo.h +++ /dev/null @@ -1,200 +0,0 @@ -//===- llvm/ADT/DenseMapInfo.h - Type traits for DenseMap -------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines DenseMapInfo traits for DenseMap. -// -//===----------------------------------------------------------------------===// - -// Taken from llvmCore-3425.0.31. - -#ifndef LLVM_ADT_DENSEMAPINFO_H -#define LLVM_ADT_DENSEMAPINFO_H - -#include "objc-private.h" -#include "llvm-type_traits.h" - -namespace objc { - -template<typename T> -struct DenseMapInfo { - //static inline T getEmptyKey(); - //static inline T getTombstoneKey(); - //static unsigned getHashValue(const T &Val); - //static bool isEqual(const T &LHS, const T &RHS); -}; - -// Provide DenseMapInfo for all pointers. -template<typename T> -struct DenseMapInfo<T*> { - static inline T* getEmptyKey() { - uintptr_t Val = static_cast<uintptr_t>(-1); - return reinterpret_cast<T*>(Val); - } - static inline T* getTombstoneKey() { - uintptr_t Val = static_cast<uintptr_t>(-2); - return reinterpret_cast<T*>(Val); - } - static unsigned getHashValue(const T *PtrVal) { - return ptr_hash((uintptr_t)PtrVal); - } - static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; } -}; - -// Provide DenseMapInfo for disguised pointers. -template<typename T> -struct DenseMapInfo<DisguisedPtr<T> > { - static inline DisguisedPtr<T> getEmptyKey() { - return DisguisedPtr<T>((T*)(uintptr_t)-1); - } - static inline DisguisedPtr<T> getTombstoneKey() { - return DisguisedPtr<T>((T*)(uintptr_t)-2); - } - static unsigned getHashValue(const T *PtrVal) { - return ptr_hash((uintptr_t)PtrVal); - } - static bool isEqual(const DisguisedPtr<T> &LHS, const DisguisedPtr<T> &RHS) { - return LHS == RHS; - } -}; - -// Provide DenseMapInfo for cstrings. -template<> struct DenseMapInfo<const char*> { - static inline const char* getEmptyKey() { - return reinterpret_cast<const char *>((intptr_t)-1); - } - static inline const char* getTombstoneKey() { - return reinterpret_cast<const char *>((intptr_t)-2); - } - static unsigned getHashValue(const char* const &Val) { - return _objc_strhash(Val); - } - static bool isEqual(const char* const &LHS, const char* const &RHS) { - return 0 == strcmp(LHS, RHS); - } -}; - -// Provide DenseMapInfo for chars. -template<> struct DenseMapInfo<char> { - static inline char getEmptyKey() { return ~0; } - static inline char getTombstoneKey() { return ~0 - 1; } - static unsigned getHashValue(const char& Val) { return Val * 37U; } - static bool isEqual(const char &LHS, const char &RHS) { - return LHS == RHS; - } -}; - -// Provide DenseMapInfo for unsigned ints. -template<> struct DenseMapInfo<unsigned> { - static inline unsigned getEmptyKey() { return ~0U; } - static inline unsigned getTombstoneKey() { return ~0U - 1; } - static unsigned getHashValue(const unsigned& Val) { return Val * 37U; } - static bool isEqual(const unsigned& LHS, const unsigned& RHS) { - return LHS == RHS; - } -}; - -// Provide DenseMapInfo for unsigned longs. -template<> struct DenseMapInfo<unsigned long> { - static inline unsigned long getEmptyKey() { return ~0UL; } - static inline unsigned long getTombstoneKey() { return ~0UL - 1L; } - static unsigned getHashValue(const unsigned long& Val) { - return (unsigned)(Val * 37UL); - } - static bool isEqual(const unsigned long& LHS, const unsigned long& RHS) { - return LHS == RHS; - } -}; - -// Provide DenseMapInfo for unsigned long longs. -template<> struct DenseMapInfo<unsigned long long> { - static inline unsigned long long getEmptyKey() { return ~0ULL; } - static inline unsigned long long getTombstoneKey() { return ~0ULL - 1ULL; } - static unsigned getHashValue(const unsigned long long& Val) { - return (unsigned)(Val * 37ULL); - } - static bool isEqual(const unsigned long long& LHS, - const unsigned long long& RHS) { - return LHS == RHS; - } -}; - -// Provide DenseMapInfo for ints. -template<> struct DenseMapInfo<int> { - static inline int getEmptyKey() { return 0x7fffffff; } - static inline int getTombstoneKey() { return -0x7fffffff - 1; } - static unsigned getHashValue(const int& Val) { return (unsigned)(Val * 37U); } - static bool isEqual(const int& LHS, const int& RHS) { - return LHS == RHS; - } -}; - -// Provide DenseMapInfo for longs. -template<> struct DenseMapInfo<long> { - static inline long getEmptyKey() { - return (1UL << (sizeof(long) * 8 - 1)) - 1UL; - } - static inline long getTombstoneKey() { return getEmptyKey() - 1L; } - static unsigned getHashValue(const long& Val) { - return (unsigned)(Val * 37UL); - } - static bool isEqual(const long& LHS, const long& RHS) { - return LHS == RHS; - } -}; - -// Provide DenseMapInfo for long longs. -template<> struct DenseMapInfo<long long> { - static inline long long getEmptyKey() { return 0x7fffffffffffffffLL; } - static inline long long getTombstoneKey() { return -0x7fffffffffffffffLL-1; } - static unsigned getHashValue(const long long& Val) { - return (unsigned)(Val * 37ULL); - } - static bool isEqual(const long long& LHS, - const long long& RHS) { - return LHS == RHS; - } -}; - -// Provide DenseMapInfo for all pairs whose members have info. -template<typename T, typename U> -struct DenseMapInfo<std::pair<T, U> > { - typedef std::pair<T, U> Pair; - typedef DenseMapInfo<T> FirstInfo; - typedef DenseMapInfo<U> SecondInfo; - - static inline Pair getEmptyKey() { - return std::make_pair(FirstInfo::getEmptyKey(), - SecondInfo::getEmptyKey()); - } - static inline Pair getTombstoneKey() { - return std::make_pair(FirstInfo::getTombstoneKey(), - SecondInfo::getTombstoneKey()); - } - static unsigned getHashValue(const Pair& PairVal) { - uint64_t key = (uint64_t)FirstInfo::getHashValue(PairVal.first) << 32 - | (uint64_t)SecondInfo::getHashValue(PairVal.second); - key += ~(key << 32); - key ^= (key >> 22); - key += ~(key << 13); - key ^= (key >> 8); - key += (key << 3); - key ^= (key >> 15); - key += ~(key << 27); - key ^= (key >> 31); - return (unsigned)key; - } - static bool isEqual(const Pair &LHS, const Pair &RHS) { - return FirstInfo::isEqual(LHS.first, RHS.first) && - SecondInfo::isEqual(LHS.second, RHS.second); - } -}; - -} // end namespace objc - -#endif diff --git a/objc/objc-runtime/runtime/llvm-MathExtras.h b/objc/objc-runtime/runtime/llvm-MathExtras.h deleted file mode 100644 index 7baad41..0000000 --- a/objc/objc-runtime/runtime/llvm-MathExtras.h +++ /dev/null @@ -1,480 +0,0 @@ -//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file contains some functions that are useful for math stuff. -// -//===----------------------------------------------------------------------===// - -// Taken from llvmCore-3425.0.31. - -#ifndef LLVM_SUPPORT_MATHEXTRAS_H -#define LLVM_SUPPORT_MATHEXTRAS_H - -namespace objc { - -// NOTE: The following support functions use the _32/_64 extensions instead of -// type overloading so that signed and unsigned integers can be used without -// ambiguity. - -/// Hi_32 - This function returns the high 32 bits of a 64 bit value. -inline uint32_t Hi_32(uint64_t Value) { - return static_cast<uint32_t>(Value >> 32); -} - -/// Lo_32 - This function returns the low 32 bits of a 64 bit value. -inline uint32_t Lo_32(uint64_t Value) { - return static_cast<uint32_t>(Value); -} - -/// isInt - Checks if an integer fits into the given bit width. -template<unsigned N> -inline bool isInt(int64_t x) { - return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1))); -} -// Template specializations to get better code for common cases. -template<> -inline bool isInt<8>(int64_t x) { - return static_cast<int8_t>(x) == x; -} -template<> -inline bool isInt<16>(int64_t x) { - return static_cast<int16_t>(x) == x; -} -template<> -inline bool isInt<32>(int64_t x) { - return static_cast<int32_t>(x) == x; -} - -/// isShiftedInt<N,S> - Checks if a signed integer is an N bit number shifted -/// left by S. -template<unsigned N, unsigned S> -inline bool isShiftedInt(int64_t x) { - return isInt<N+S>(x) && (x % (1<<S) == 0); -} - -/// isUInt - Checks if an unsigned integer fits into the given bit width. -template<unsigned N> -inline bool isUInt(uint64_t x) { - return N >= 64 || x < (UINT64_C(1)<<N); -} -// Template specializations to get better code for common cases. -template<> -inline bool isUInt<8>(uint64_t x) { - return static_cast<uint8_t>(x) == x; -} -template<> -inline bool isUInt<16>(uint64_t x) { - return static_cast<uint16_t>(x) == x; -} -template<> -inline bool isUInt<32>(uint64_t x) { - return static_cast<uint32_t>(x) == x; -} - -/// isShiftedUInt<N,S> - Checks if a unsigned integer is an N bit number shifted -/// left by S. -template<unsigned N, unsigned S> -inline bool isShiftedUInt(uint64_t x) { - return isUInt<N+S>(x) && (x % (1<<S) == 0); -} - -/// isUIntN - Checks if an unsigned integer fits into the given (dynamic) -/// bit width. -inline bool isUIntN(unsigned N, uint64_t x) { - return x == (x & (~0ULL >> (64 - N))); -} - -/// isIntN - Checks if an signed integer fits into the given (dynamic) -/// bit width. -inline bool isIntN(unsigned N, int64_t x) { - return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1))); -} - -/// isMask_32 - This function returns true if the argument is a sequence of ones -/// starting at the least significant bit with the remainder zero (32 bit -/// version). Ex. isMask_32(0x0000FFFFU) == true. -inline bool isMask_32(uint32_t Value) { - return Value && ((Value + 1) & Value) == 0; -} - -/// isMask_64 - This function returns true if the argument is a sequence of ones -/// starting at the least significant bit with the remainder zero (64 bit -/// version). -inline bool isMask_64(uint64_t Value) { - return Value && ((Value + 1) & Value) == 0; -} - -/// isShiftedMask_32 - This function returns true if the argument contains a -/// sequence of ones with the remainder zero (32 bit version.) -/// Ex. isShiftedMask_32(0x0000FF00U) == true. -inline bool isShiftedMask_32(uint32_t Value) { - return isMask_32((Value - 1) | Value); -} - -/// isShiftedMask_64 - This function returns true if the argument contains a -/// sequence of ones with the remainder zero (64 bit version.) -inline bool isShiftedMask_64(uint64_t Value) { - return isMask_64((Value - 1) | Value); -} - -/// isPowerOf2_32 - This function returns true if the argument is a power of -/// two > 0. Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.) -inline bool isPowerOf2_32(uint32_t Value) { - return Value && !(Value & (Value - 1)); -} - -/// isPowerOf2_64 - This function returns true if the argument is a power of two -/// > 0 (64 bit edition.) -inline bool isPowerOf2_64(uint64_t Value) { - return Value && !(Value & (Value - int64_t(1L))); -} - -/// CountLeadingZeros_32 - this function performs the platform optimal form of -/// counting the number of zeros from the most significant bit to the first one -/// bit. Ex. CountLeadingZeros_32(0x00F000FF) == 8. -/// Returns 32 if the word is zero. -inline unsigned CountLeadingZeros_32(uint32_t Value) { - unsigned Count; // result -#if __GNUC__ >= 4 - // PowerPC is defined for __builtin_clz(0) -#if !defined(__ppc__) && !defined(__ppc64__) - if (!Value) return 32; -#endif - Count = __builtin_clz(Value); -#else - if (!Value) return 32; - Count = 0; - // bisection method for count leading zeros - for (unsigned Shift = 32 >> 1; Shift; Shift >>= 1) { - uint32_t Tmp = Value >> Shift; - if (Tmp) { - Value = Tmp; - } else { - Count |= Shift; - } - } -#endif - return Count; -} - -/// CountLeadingOnes_32 - this function performs the operation of -/// counting the number of ones from the most significant bit to the first zero -/// bit. Ex. CountLeadingOnes_32(0xFF0FFF00) == 8. -/// Returns 32 if the word is all ones. -inline unsigned CountLeadingOnes_32(uint32_t Value) { - return CountLeadingZeros_32(~Value); -} - -/// CountLeadingZeros_64 - This function performs the platform optimal form -/// of counting the number of zeros from the most significant bit to the first -/// one bit (64 bit edition.) -/// Returns 64 if the word is zero. -inline unsigned CountLeadingZeros_64(uint64_t Value) { - unsigned Count; // result -#if __GNUC__ >= 4 - // PowerPC is defined for __builtin_clzll(0) -#if !defined(__ppc__) && !defined(__ppc64__) - if (!Value) return 64; -#endif - Count = __builtin_clzll(Value); -#else - if (sizeof(long) == sizeof(int64_t)) { - if (!Value) return 64; - Count = 0; - // bisection method for count leading zeros - for (unsigned Shift = 64 >> 1; Shift; Shift >>= 1) { - uint64_t Tmp = Value >> Shift; - if (Tmp) { - Value = Tmp; - } else { - Count |= Shift; - } - } - } else { - // get hi portion - uint32_t Hi = Hi_32(Value); - - // if some bits in hi portion - if (Hi) { - // leading zeros in hi portion plus all bits in lo portion - Count = CountLeadingZeros_32(Hi); - } else { - // get lo portion - uint32_t Lo = Lo_32(Value); - // same as 32 bit value - Count = CountLeadingZeros_32(Lo)+32; - } - } -#endif - return Count; -} - -/// CountLeadingOnes_64 - This function performs the operation -/// of counting the number of ones from the most significant bit to the first -/// zero bit (64 bit edition.) -/// Returns 64 if the word is all ones. -inline unsigned CountLeadingOnes_64(uint64_t Value) { - return CountLeadingZeros_64(~Value); -} - -/// CountTrailingZeros_32 - this function performs the platform optimal form of -/// counting the number of zeros from the least significant bit to the first one -/// bit. Ex. CountTrailingZeros_32(0xFF00FF00) == 8. -/// Returns 32 if the word is zero. -inline unsigned CountTrailingZeros_32(uint32_t Value) { -#if __GNUC__ >= 4 - return Value ? __builtin_ctz(Value) : 32; -#else - static const unsigned Mod37BitPosition[] = { - 32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, - 4, 7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, - 5, 20, 8, 19, 18 - }; - return Mod37BitPosition[(-Value & Value) % 37]; -#endif -} - -/// CountTrailingOnes_32 - this function performs the operation of -/// counting the number of ones from the least significant bit to the first zero -/// bit. Ex. CountTrailingOnes_32(0x00FF00FF) == 8. -/// Returns 32 if the word is all ones. -inline unsigned CountTrailingOnes_32(uint32_t Value) { - return CountTrailingZeros_32(~Value); -} - -/// CountTrailingZeros_64 - This function performs the platform optimal form -/// of counting the number of zeros from the least significant bit to the first -/// one bit (64 bit edition.) -/// Returns 64 if the word is zero. -inline unsigned CountTrailingZeros_64(uint64_t Value) { -#if __GNUC__ >= 4 - return Value ? __builtin_ctzll(Value) : 64; -#else - static const unsigned Mod67Position[] = { - 64, 0, 1, 39, 2, 15, 40, 23, 3, 12, 16, 59, 41, 19, 24, 54, - 4, 64, 13, 10, 17, 62, 60, 28, 42, 30, 20, 51, 25, 44, 55, - 47, 5, 32, 65, 38, 14, 22, 11, 58, 18, 53, 63, 9, 61, 27, - 29, 50, 43, 46, 31, 37, 21, 57, 52, 8, 26, 49, 45, 36, 56, - 7, 48, 35, 6, 34, 33, 0 - }; - return Mod67Position[(-Value & Value) % 67]; -#endif -} - -/// CountTrailingOnes_64 - This function performs the operation -/// of counting the number of ones from the least significant bit to the first -/// zero bit (64 bit edition.) -/// Returns 64 if the word is all ones. -inline unsigned CountTrailingOnes_64(uint64_t Value) { - return CountTrailingZeros_64(~Value); -} - -/// CountPopulation_32 - this function counts the number of set bits in a value. -/// Ex. CountPopulation(0xF000F000) = 8 -/// Returns 0 if the word is zero. -inline unsigned CountPopulation_32(uint32_t Value) { -#if __GNUC__ >= 4 - return __builtin_popcount(Value); -#else - uint32_t v = Value - ((Value >> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >> 2) & 0x33333333); - return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; -#endif -} - -/// CountPopulation_64 - this function counts the number of set bits in a value, -/// (64 bit edition.) -inline unsigned CountPopulation_64(uint64_t Value) { -#if __GNUC__ >= 4 - return __builtin_popcountll(Value); -#else - uint64_t v = Value - ((Value >> 1) & 0x5555555555555555ULL); - v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL); - v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL; - return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56); -#endif -} - -/// Log2_32 - This function returns the floor log base 2 of the specified value, -/// -1 if the value is zero. (32 bit edition.) -/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2 -inline unsigned Log2_32(uint32_t Value) { - return 31 - CountLeadingZeros_32(Value); -} - -/// Log2_64 - This function returns the floor log base 2 of the specified value, -/// -1 if the value is zero. (64 bit edition.) -inline unsigned Log2_64(uint64_t Value) { - return 63 - CountLeadingZeros_64(Value); -} - -/// Log2_32_Ceil - This function returns the ceil log base 2 of the specified -/// value, 32 if the value is zero. (32 bit edition). -/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3 -inline unsigned Log2_32_Ceil(uint32_t Value) { - return 32-CountLeadingZeros_32(Value-1); -} - -/// Log2_64_Ceil - This function returns the ceil log base 2 of the specified -/// value, 64 if the value is zero. (64 bit edition.) -inline unsigned Log2_64_Ceil(uint64_t Value) { - return 64-CountLeadingZeros_64(Value-1); -} - -/// GreatestCommonDivisor64 - Return the greatest common divisor of the two -/// values using Euclid's algorithm. -inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) { - while (B) { - uint64_t T = B; - B = A % B; - A = T; - } - return A; -} - -/// BitsToDouble - This function takes a 64-bit integer and returns the bit -/// equivalent double. -inline double BitsToDouble(uint64_t Bits) { - union { - uint64_t L; - double D; - } T; - T.L = Bits; - return T.D; -} - -/// BitsToFloat - This function takes a 32-bit integer and returns the bit -/// equivalent float. -inline float BitsToFloat(uint32_t Bits) { - union { - uint32_t I; - float F; - } T; - T.I = Bits; - return T.F; -} - -/// DoubleToBits - This function takes a double and returns the bit -/// equivalent 64-bit integer. Note that copying doubles around -/// changes the bits of NaNs on some hosts, notably x86, so this -/// routine cannot be used if these bits are needed. -inline uint64_t DoubleToBits(double Double) { - union { - uint64_t L; - double D; - } T; - T.D = Double; - return T.L; -} - -/// FloatToBits - This function takes a float and returns the bit -/// equivalent 32-bit integer. Note that copying floats around -/// changes the bits of NaNs on some hosts, notably x86, so this -/// routine cannot be used if these bits are needed. -inline uint32_t FloatToBits(float Float) { - union { - uint32_t I; - float F; - } T; - T.F = Float; - return T.I; -} - -/// Platform-independent wrappers for the C99 isnan() function. -int IsNAN(float f); -int IsNAN(double d); - -/// Platform-independent wrappers for the C99 isinf() function. -int IsInf(float f); -int IsInf(double d); - -/// MinAlign - A and B are either alignments or offsets. Return the minimum -/// alignment that may be assumed after adding the two together. -inline uint64_t MinAlign(uint64_t A, uint64_t B) { - // The largest power of 2 that divides both A and B. - return (A | B) & -(A | B); -} - -/// NextPowerOf2 - Returns the next power of two (in 64-bits) -/// that is strictly greater than A. Returns zero on overflow. -inline uint64_t NextPowerOf2(uint64_t A) { - A |= (A >> 1); - A |= (A >> 2); - A |= (A >> 4); - A |= (A >> 8); - A |= (A >> 16); - A |= (A >> 32); - return A + 1; -} - -/// NextPowerOf2 - Returns the next power of two (in 32-bits) -/// that is strictly greater than A. Returns zero on overflow. -inline uint32_t NextPowerOf2(uint32_t A) { - A |= (A >> 1); - A |= (A >> 2); - A |= (A >> 4); - A |= (A >> 8); - A |= (A >> 16); - return A + 1; -} - -/// Returns the next integer (mod 2**64) that is greater than or equal to -/// \p Value and is a multiple of \p Align. \p Align must be non-zero. -/// -/// Examples: -/// \code -/// RoundUpToAlignment(5, 8) = 8 -/// RoundUpToAlignment(17, 8) = 24 -/// RoundUpToAlignment(~0LL, 8) = 0 -/// \endcode -inline uint64_t RoundUpToAlignment(uint64_t Value, uint64_t Align) { - return ((Value + Align - 1) / Align) * Align; -} - -/// Returns the offset to the next integer (mod 2**64) that is greater than -/// or equal to \p Value and is a multiple of \p Align. \p Align must be -/// non-zero. -inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) { - return RoundUpToAlignment(Value, Align) - Value; -} - -/// abs64 - absolute value of a 64-bit int. Not all environments support -/// "abs" on whatever their name for the 64-bit int type is. The absolute -/// value of the largest negative number is undefined, as with "abs". -inline int64_t abs64(int64_t x) { - return (x < 0) ? -x : x; -} - -/// SignExtend32 - Sign extend B-bit number x to 32-bit int. -/// Usage int32_t r = SignExtend32<5>(x); -template <unsigned B> inline int32_t SignExtend32(uint32_t x) { - return int32_t(x << (32 - B)) >> (32 - B); -} - -/// \brief Sign extend number in the bottom B bits of X to a 32-bit int. -/// Requires 0 < B <= 32. -inline int32_t SignExtend32(uint32_t X, unsigned B) { - return int32_t(X << (32 - B)) >> (32 - B); -} - -/// SignExtend64 - Sign extend B-bit number x to 64-bit int. -/// Usage int64_t r = SignExtend64<5>(x); -template <unsigned B> inline int64_t SignExtend64(uint64_t x) { - return int64_t(x << (64 - B)) >> (64 - B); -} - -/// \brief Sign extend number in the bottom B bits of X to a 64-bit int. -/// Requires 0 < B <= 64. -inline int64_t SignExtend64(uint64_t X, unsigned B) { - return int64_t(X << (64 - B)) >> (64 - B); -} - -} // End llvm namespace - -#endif diff --git a/objc/objc-runtime/runtime/llvm-type_traits.h b/objc/objc-runtime/runtime/llvm-type_traits.h deleted file mode 100644 index bbe38d4..0000000 --- a/objc/objc-runtime/runtime/llvm-type_traits.h +++ /dev/null @@ -1,221 +0,0 @@ -//===- llvm/Support/type_traits.h - Simplfied type traits -------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file provides a template class that determines if a type is a class or -// not. The basic mechanism, based on using the pointer to member function of -// a zero argument to a function was "boosted" from the boost type_traits -// library. See http://www.boost.org/ for all the gory details. -// -//===----------------------------------------------------------------------===// - -// Taken from llvmCore-3425.0.31. - -#ifndef LLVM_SUPPORT_TYPE_TRAITS_H -#define LLVM_SUPPORT_TYPE_TRAITS_H - -#include <cstddef> -#include <utility> - -#ifndef __has_feature -#define LLVM_DEFINED_HAS_FEATURE -#define __has_feature(x) 0 -#endif - -// This is actually the conforming implementation which works with abstract -// classes. However, enough compilers have trouble with it that most will use -// the one in boost/type_traits/object_traits.hpp. This implementation actually -// works with VC7.0, but other interactions seem to fail when we use it. - -namespace objc { - -namespace dont_use -{ - // These two functions should never be used. They are helpers to - // the is_class template below. They cannot be located inside - // is_class because doing so causes at least GCC to think that - // the value of the "value" enumerator is not constant. Placing - // them out here (for some strange reason) allows the sizeof - // operator against them to magically be constant. This is - // important to make the is_class<T>::value idiom zero cost. it - // evaluates to a constant 1 or 0 depending on whether the - // parameter T is a class or not (respectively). - template<typename T> char is_class_helper(void(T::*)()); - template<typename T> double is_class_helper(...); -} - -template <typename T> -struct is_class -{ - // is_class<> metafunction due to Paul Mensonides (leavings@attbi.com). For - // more details: - // http://groups.google.com/groups?hl=en&selm=000001c1cc83%24e154d5e0%247772e50c%40c161550a&rnum=1 -public: - static const bool value = - sizeof(char) == sizeof(dont_use::is_class_helper<T>(0)); -}; - - -/// isPodLike - This is a type trait that is used to determine whether a given -/// type can be copied around with memcpy instead of running ctors etc. -template <typename T> -struct isPodLike { -#if __has_feature(is_trivially_copyable) - // If the compiler supports the is_trivially_copyable trait use it, as it - // matches the definition of isPodLike closely. - static const bool value = __is_trivially_copyable(T); -#else - // If we don't know anything else, we can (at least) assume that all non-class - // types are PODs. - static const bool value = !is_class<T>::value; -#endif -}; - -// std::pair's are pod-like if their elements are. -template<typename T, typename U> -struct isPodLike<std::pair<T, U> > { - static const bool value = isPodLike<T>::value && isPodLike<U>::value; -}; - - -template <class T, T v> -struct integral_constant { - typedef T value_type; - static const value_type value = v; - typedef integral_constant<T,v> type; - operator value_type() { return value; } -}; - -typedef integral_constant<bool, true> true_type; -typedef integral_constant<bool, false> false_type; - -/// \brief Metafunction that determines whether the two given types are -/// equivalent. -template<typename T, typename U> struct is_same : public false_type {}; -template<typename T> struct is_same<T, T> : public true_type {}; - -/// \brief Metafunction that removes const qualification from a type. -template <typename T> struct remove_const { typedef T type; }; -template <typename T> struct remove_const<const T> { typedef T type; }; - -/// \brief Metafunction that removes volatile qualification from a type. -template <typename T> struct remove_volatile { typedef T type; }; -template <typename T> struct remove_volatile<volatile T> { typedef T type; }; - -/// \brief Metafunction that removes both const and volatile qualification from -/// a type. -template <typename T> struct remove_cv { - typedef typename remove_const<typename remove_volatile<T>::type>::type type; -}; - -/// \brief Helper to implement is_integral metafunction. -template <typename T> struct is_integral_impl : false_type {}; -template <> struct is_integral_impl< bool> : true_type {}; -template <> struct is_integral_impl< char> : true_type {}; -template <> struct is_integral_impl< signed char> : true_type {}; -template <> struct is_integral_impl<unsigned char> : true_type {}; -template <> struct is_integral_impl< wchar_t> : true_type {}; -template <> struct is_integral_impl< short> : true_type {}; -template <> struct is_integral_impl<unsigned short> : true_type {}; -template <> struct is_integral_impl< int> : true_type {}; -template <> struct is_integral_impl<unsigned int> : true_type {}; -template <> struct is_integral_impl< long> : true_type {}; -template <> struct is_integral_impl<unsigned long> : true_type {}; -template <> struct is_integral_impl< long long> : true_type {}; -template <> struct is_integral_impl<unsigned long long> : true_type {}; - -/// \brief Metafunction that determines whether the given type is an integral -/// type. -template <typename T> -struct is_integral : is_integral_impl<T> {}; - -/// \brief Metafunction to remove reference from a type. -template <typename T> struct remove_reference { typedef T type; }; -template <typename T> struct remove_reference<T&> { typedef T type; }; - -/// \brief Metafunction that determines whether the given type is a pointer -/// type. -template <typename T> struct is_pointer : false_type {}; -template <typename T> struct is_pointer<T*> : true_type {}; -template <typename T> struct is_pointer<T* const> : true_type {}; -template <typename T> struct is_pointer<T* volatile> : true_type {}; -template <typename T> struct is_pointer<T* const volatile> : true_type {}; - -/// \brief Metafunction that determines whether the given type is either an -/// integral type or an enumeration type. -/// -/// Note that this accepts potentially more integral types than we whitelist -/// above for is_integral because it is based on merely being convertible -/// implicitly to an integral type. -template <typename T> class is_integral_or_enum { - // Provide an overload which can be called with anything implicitly - // convertible to an unsigned long long. This should catch integer types and - // enumeration types at least. We blacklist classes with conversion operators - // below. - static double check_int_convertible(unsigned long long); - static char check_int_convertible(...); - - typedef typename remove_reference<T>::type UnderlyingT; - static UnderlyingT &nonce_instance; - -public: - static const bool - value = (!is_class<UnderlyingT>::value && !is_pointer<UnderlyingT>::value && - !is_same<UnderlyingT, float>::value && - !is_same<UnderlyingT, double>::value && - sizeof(char) != sizeof(check_int_convertible(nonce_instance))); -}; - -// enable_if_c - Enable/disable a template based on a metafunction -template<bool Cond, typename T = void> -struct enable_if_c { - typedef T type; -}; - -template<typename T> struct enable_if_c<false, T> { }; - -// enable_if - Enable/disable a template based on a metafunction -template<typename Cond, typename T = void> -struct enable_if : public enable_if_c<Cond::value, T> { }; - -namespace dont_use { - template<typename Base> char base_of_helper(const volatile Base*); - template<typename Base> double base_of_helper(...); -} - -/// is_base_of - Metafunction to determine whether one type is a base class of -/// (or identical to) another type. -template<typename Base, typename Derived> -struct is_base_of { - static const bool value - = is_class<Base>::value && is_class<Derived>::value && - sizeof(char) == sizeof(dont_use::base_of_helper<Base>((Derived*)0)); -}; - -// remove_pointer - Metafunction to turn Foo* into Foo. Defined in -// C++0x [meta.trans.ptr]. -template <typename T> struct remove_pointer { typedef T type; }; -template <typename T> struct remove_pointer<T*> { typedef T type; }; -template <typename T> struct remove_pointer<T*const> { typedef T type; }; -template <typename T> struct remove_pointer<T*volatile> { typedef T type; }; -template <typename T> struct remove_pointer<T*const volatile> { - typedef T type; }; - -template <bool, typename T, typename F> -struct conditional { typedef T type; }; - -template <typename T, typename F> -struct conditional<false, T, F> { typedef F type; }; - -} - -#ifdef LLVM_DEFINED_HAS_FEATURE -#undef __has_feature -#endif - -#endif diff --git a/objc/objc-runtime/runtime/maptable.h b/objc/objc-runtime/runtime/maptable.h deleted file mode 100644 index bc2a635..0000000 --- a/objc/objc-runtime/runtime/maptable.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 1999-2003, 2006-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@ - */ -/* maptable.h - Scalable hash table of mappings. - Bertrand, August 1990 - Copyright 1990-1996 NeXT Software, Inc. -*/ - -#ifndef _OBJC_MAPTABLE_H_ -#define _OBJC_MAPTABLE_H_ - -#ifndef _OBJC_PRIVATE_H_ -# define OBJC_MAP_AVAILABILITY __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_1, __IPHONE_NA,__IPHONE_NA); -#else -# define OBJC_MAP_AVAILABILITY -#endif - -#include <objc/objc.h> - -__BEGIN_DECLS - -/*************** Definitions ***************/ - - /* This module allows hashing of arbitrary associations [key -> value]. Keys and values must be pointers or integers, and client is responsible for allocating/deallocating this data. A deallocation call-back is provided. - NX_MAPNOTAKEY (-1) is used internally as a marker, and therefore keys must always be different from -1. - As well-behaved scalable data structures, hash tables double in size when they start becoming full, thus guaranteeing both average constant time access and linear size. */ - -typedef struct _NXMapTable { - /* private data structure; may change */ - const struct _NXMapTablePrototype *prototype; - unsigned count; - unsigned nbBucketsMinusOne; - void *buckets; -} NXMapTable OBJC_MAP_AVAILABILITY; - -typedef struct _NXMapTablePrototype { - unsigned (*hash)(NXMapTable *, const void *key); - int (*isEqual)(NXMapTable *, const void *key1, const void *key2); - void (*free)(NXMapTable *, void *key, void *value); - int style; /* reserved for future expansion; currently 0 */ -} NXMapTablePrototype OBJC_MAP_AVAILABILITY; - - /* invariants assumed by the implementation: - A - key != -1 - B - key1 == key2 => hash(key1) == hash(key2) - when key varies over time, hash(key) must remain invariant - e.g. if string key, the string must not be changed - C - isEqual(key1, key2) => key1 == key2 - */ - -#define NX_MAPNOTAKEY ((void *)(-1)) - -/*************** Functions ***************/ - -OBJC_EXPORT NXMapTable *NXCreateMapTableFromZone(NXMapTablePrototype prototype, unsigned capacity, void *z) OBJC_MAP_AVAILABILITY; -OBJC_EXPORT NXMapTable *NXCreateMapTable(NXMapTablePrototype prototype, unsigned capacity) OBJC_MAP_AVAILABILITY; - /* capacity is only a hint; 0 creates a small table */ - -OBJC_EXPORT void NXFreeMapTable(NXMapTable *table) OBJC_MAP_AVAILABILITY; - /* call free for each pair, and recovers table */ - -OBJC_EXPORT void NXResetMapTable(NXMapTable *table) OBJC_MAP_AVAILABILITY; - /* free each pair; keep current capacity */ - -OBJC_EXPORT BOOL NXCompareMapTables(NXMapTable *table1, NXMapTable *table2) OBJC_MAP_AVAILABILITY; - /* Returns YES if the two sets are equal (each member of table1 in table2, and table have same size) */ - -OBJC_EXPORT unsigned NXCountMapTable(NXMapTable *table) OBJC_MAP_AVAILABILITY; - /* current number of data in table */ - -OBJC_EXPORT void *NXMapMember(NXMapTable *table, const void *key, void **value) OBJC_MAP_AVAILABILITY; - /* return original table key or NX_MAPNOTAKEY. If key is found, value is set */ - -OBJC_EXPORT void *NXMapGet(NXMapTable *table, const void *key) OBJC_MAP_AVAILABILITY; - /* return original corresponding value or NULL. When NULL need be stored as value, NXMapMember can be used to test for presence */ - -OBJC_EXPORT void *NXMapInsert(NXMapTable *table, const void *key, const void *value) OBJC_MAP_AVAILABILITY; - /* override preexisting pair; Return previous value or NULL. */ - -OBJC_EXPORT void *NXMapRemove(NXMapTable *table, const void *key) OBJC_MAP_AVAILABILITY; - /* previous value or NULL is returned */ - -/* Iteration over all elements of a table consists in setting up an iteration state and then to progress until all entries have been visited. An example of use for counting elements in a table is: - unsigned count = 0; - const MyKey *key; - const MyValue *value; - NXMapState state = NXInitMapState(table); - while(NXNextMapState(table, &state, &key, &value)) { - count++; - } -*/ - -typedef struct {int index;} NXMapState OBJC_MAP_AVAILABILITY; - /* callers should not rely on actual contents of the struct */ - -OBJC_EXPORT NXMapState NXInitMapState(NXMapTable *table) OBJC_MAP_AVAILABILITY; - -OBJC_EXPORT int NXNextMapState(NXMapTable *table, NXMapState *state, const void **key, const void **value) OBJC_MAP_AVAILABILITY; - /* returns 0 when all elements have been visited */ - -/*************** Conveniences ***************/ - -OBJC_EXPORT const NXMapTablePrototype NXPtrValueMapPrototype OBJC_MAP_AVAILABILITY; - /* hashing is pointer/integer hashing; - isEqual is identity; - free is no-op. */ -OBJC_EXPORT const NXMapTablePrototype NXStrValueMapPrototype OBJC_MAP_AVAILABILITY; - /* hashing is string hashing; - isEqual is strcmp; - free is no-op. */ -OBJC_EXPORT const NXMapTablePrototype NXObjectMapPrototype OBJC2_UNAVAILABLE; - /* for objects; uses methods: hash, isEqual:, free, all for key. */ - -__END_DECLS - -#endif /* _OBJC_MAPTABLE_H_ */ diff --git a/objc/objc-runtime/runtime/maptable.mm b/objc/objc-runtime/runtime/maptable.mm deleted file mode 100644 index 4d9bb32..0000000 --- a/objc/objc-runtime/runtime/maptable.mm +++ /dev/null @@ -1,452 +0,0 @@ -/* - * Copyright (c) 1999-2003, 2005-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@ - */ -/* maptable.m - Copyright 1990-1996 NeXT Software, Inc. - Created by Bertrand Serlet, August 1990 - */ - - -#include <string.h> -#include <stdlib.h> -#include <stdio.h> - -#include "objc-private.h" -#include "maptable.h" -#include "hashtable2.h" - - -/****** Macros and utilities ****************************/ - -#if defined(DEBUG) -#define INLINE -#else -#define INLINE inline -#endif - -typedef struct _MapPair { - const void *key; - const void *value; -} MapPair; - -static INLINE unsigned xorHash(unsigned hash) { - unsigned xored = (hash & 0xffff) ^ (hash >> 16); - return ((xored * 65521) + hash); -} - -static INLINE unsigned bucketOf(NXMapTable *table, const void *key) { - unsigned hash = (table->prototype->hash)(table, key); - return hash & table->nbBucketsMinusOne; -} - -static INLINE int isEqual(NXMapTable *table, const void *key1, const void *key2) { - return (key1 == key2) ? 1 : (table->prototype->isEqual)(table, key1, key2); -} - -static INLINE unsigned nextIndex(NXMapTable *table, unsigned index) { - return (index + 1) & table->nbBucketsMinusOne; -} - -static INLINE void *allocBuckets(void *z, unsigned nb) { - MapPair *pairs = 1+(MapPair *)malloc_zone_malloc((malloc_zone_t *)z, ((nb+1) * sizeof(MapPair))); - MapPair *pair = pairs; - while (nb--) { pair->key = NX_MAPNOTAKEY; pair->value = NULL; pair++; } - return pairs; -} - -static INLINE void freeBuckets(void *p) { - free(-1+(MapPair *)p); -} - -/***** Global data and bootstrap **********************/ - -static int isEqualPrototype (const void *info, const void *data1, const void *data2) { - NXHashTablePrototype *proto1 = (NXHashTablePrototype *) data1; - NXHashTablePrototype *proto2 = (NXHashTablePrototype *) data2; - - return (proto1->hash == proto2->hash) && (proto1->isEqual == proto2->isEqual) && (proto1->free == proto2->free) && (proto1->style == proto2->style); -}; - -static uintptr_t hashPrototype (const void *info, const void *data) { - NXHashTablePrototype *proto = (NXHashTablePrototype *) data; - - return NXPtrHash(info, (void*)proto->hash) ^ NXPtrHash(info, (void*)proto->isEqual) ^ NXPtrHash(info, (void*)proto->free) ^ (uintptr_t) proto->style; -}; - -static NXHashTablePrototype protoPrototype = { - hashPrototype, isEqualPrototype, NXNoEffectFree, 0 -}; - -static NXHashTable *prototypes = NULL; -/* table of all prototypes */ - -/**** Fundamentals Operations **************/ - -NXMapTable *NXCreateMapTableFromZone(NXMapTablePrototype prototype, unsigned capacity, void *z) { - NXMapTable *table = (NXMapTable *)malloc_zone_malloc((malloc_zone_t *)z, sizeof(NXMapTable)); - NXMapTablePrototype *proto; - if (! prototypes) prototypes = NXCreateHashTable(protoPrototype, 0, NULL); - if (! prototype.hash || ! prototype.isEqual || ! prototype.free || prototype.style) { - _objc_inform("*** NXCreateMapTable: invalid creation parameters\n"); - return NULL; - } - proto = (NXMapTablePrototype *)NXHashGet(prototypes, &prototype); - if (! proto) { - proto = (NXMapTablePrototype *)malloc(sizeof(NXMapTablePrototype)); - *proto = prototype; - (void)NXHashInsert(prototypes, proto); - } - table->prototype = proto; table->count = 0; - table->nbBucketsMinusOne = exp2u(log2u(capacity)+1) - 1; - table->buckets = allocBuckets(z, table->nbBucketsMinusOne + 1); - return table; -} - -NXMapTable *NXCreateMapTable(NXMapTablePrototype prototype, unsigned capacity) { - return NXCreateMapTableFromZone(prototype, capacity, malloc_default_zone()); -} - -void NXFreeMapTable(NXMapTable *table) { - NXResetMapTable(table); - freeBuckets(table->buckets); - free(table); -} - -void NXResetMapTable(NXMapTable *table) { - MapPair *pairs = (MapPair *)table->buckets; - void (*freeProc)(struct _NXMapTable *, void *, void *) = table->prototype->free; - unsigned index = table->nbBucketsMinusOne + 1; - while (index--) { - if (pairs->key != NX_MAPNOTAKEY) { - freeProc(table, (void *)pairs->key, (void *)pairs->value); - pairs->key = NX_MAPNOTAKEY; pairs->value = NULL; - } - pairs++; - } - table->count = 0; -} - -BOOL NXCompareMapTables(NXMapTable *table1, NXMapTable *table2) { - if (table1 == table2) return YES; - if (table1->count != table2->count) return NO; - else { - const void *key; - const void *value; - NXMapState state = NXInitMapState(table1); - while (NXNextMapState(table1, &state, &key, &value)) { - if (NXMapMember(table2, key, (void**)&value) == NX_MAPNOTAKEY) return NO; - } - return YES; - } -} - -unsigned NXCountMapTable(NXMapTable *table) { return table->count; } - -static INLINE void *_NXMapMember(NXMapTable *table, const void *key, void **value) { - MapPair *pairs = (MapPair *)table->buckets; - unsigned index = bucketOf(table, key); - MapPair *pair = pairs + index; - if (pair->key == NX_MAPNOTAKEY) return NX_MAPNOTAKEY; - if (isEqual(table, pair->key, key)) { - *value = (void *)pair->value; - return (void *)pair->key; - } else { - unsigned index2 = index; - while ((index2 = nextIndex(table, index2)) != index) { - pair = pairs + index2; - if (pair->key == NX_MAPNOTAKEY) return NX_MAPNOTAKEY; - if (isEqual(table, pair->key, key)) { - *value = (void *)pair->value; - return (void *)pair->key; - } - } - return NX_MAPNOTAKEY; - } -} - -void *NXMapMember(NXMapTable *table, const void *key, void **value) { - return _NXMapMember(table, key, value); -} - -void *NXMapGet(NXMapTable *table, const void *key) { - void *value; - return (_NXMapMember(table, key, &value) != NX_MAPNOTAKEY) ? value : NULL; -} - -static void _NXMapRehash(NXMapTable *table) { - MapPair *pairs = (MapPair *)table->buckets; - MapPair *pair = pairs; - unsigned numBuckets = table->nbBucketsMinusOne + 1; - unsigned index = numBuckets; - unsigned oldCount = table->count; - - table->nbBucketsMinusOne = 2 * numBuckets - 1; - table->count = 0; - table->buckets = allocBuckets(malloc_zone_from_ptr(table), table->nbBucketsMinusOne + 1); - while (index--) { - if (pair->key != NX_MAPNOTAKEY) { - (void)NXMapInsert(table, pair->key, pair->value); - } - pair++; - } - if (oldCount != table->count) - _objc_inform("*** maptable: count differs after rehashing; probably indicates a broken invariant: there are x and y such as isEqual(x, y) is TRUE but hash(x) != hash (y)\n"); - freeBuckets(pairs); -} - -void *NXMapInsert(NXMapTable *table, const void *key, const void *value) { - MapPair *pairs = (MapPair *)table->buckets; - unsigned index = bucketOf(table, key); - MapPair *pair = pairs + index; - if (key == NX_MAPNOTAKEY) { - _objc_inform("*** NXMapInsert: invalid key: -1\n"); - return NULL; - } - - unsigned numBuckets = table->nbBucketsMinusOne + 1; - - if (pair->key == NX_MAPNOTAKEY) { - pair->key = key; pair->value = value; - table->count++; - if (table->count * 4 > numBuckets * 3) _NXMapRehash(table); - return NULL; - } - - if (isEqual(table, pair->key, key)) { - const void *old = pair->value; - if (old != value) pair->value = value;/* avoid writing unless needed! */ - return (void *)old; - } else if (table->count == numBuckets) { - /* no room: rehash and retry */ - _NXMapRehash(table); - return NXMapInsert(table, key, value); - } else { - unsigned index2 = index; - while ((index2 = nextIndex(table, index2)) != index) { - pair = pairs + index2; - if (pair->key == NX_MAPNOTAKEY) { - pair->key = key; pair->value = value; - table->count++; - if (table->count * 4 > numBuckets * 3) _NXMapRehash(table); - return NULL; - } - if (isEqual(table, pair->key, key)) { - const void *old = pair->value; - if (old != value) pair->value = value;/* avoid writing unless needed! */ - return (void *)old; - } - } - /* no room: can't happen! */ - _objc_inform("**** NXMapInsert: bug\n"); - return NULL; - } -} - -static int mapRemove = 0; - -void *NXMapRemove(NXMapTable *table, const void *key) { - MapPair *pairs = (MapPair *)table->buckets; - unsigned index = bucketOf(table, key); - MapPair *pair = pairs + index; - unsigned chain = 1; /* number of non-nil pairs in a row */ - int found = 0; - const void *old = NULL; - if (pair->key == NX_MAPNOTAKEY) return NULL; - mapRemove ++; - /* compute chain */ - { - unsigned index2 = index; - if (isEqual(table, pair->key, key)) {found ++; old = pair->value; } - while ((index2 = nextIndex(table, index2)) != index) { - pair = pairs + index2; - if (pair->key == NX_MAPNOTAKEY) break; - if (isEqual(table, pair->key, key)) {found ++; old = pair->value; } - chain++; - } - } - if (! found) return NULL; - if (found != 1) _objc_inform("**** NXMapRemove: incorrect table\n"); - /* remove then reinsert */ - { - MapPair buffer[16]; - MapPair *aux = (chain > 16) ? (MapPair *)malloc(sizeof(MapPair)*(chain-1)) : buffer; - unsigned auxnb = 0; - int nb = chain; - unsigned index2 = index; - while (nb--) { - pair = pairs + index2; - if (! isEqual(table, pair->key, key)) aux[auxnb++] = *pair; - pair->key = NX_MAPNOTAKEY; pair->value = NULL; - index2 = nextIndex(table, index2); - } - table->count -= chain; - if (auxnb != chain-1) _objc_inform("**** NXMapRemove: bug\n"); - while (auxnb--) NXMapInsert(table, aux[auxnb].key, aux[auxnb].value); - if (chain > 16) free(aux); - } - return (void *)old; -} - -NXMapState NXInitMapState(NXMapTable *table) { - NXMapState state; - state.index = table->nbBucketsMinusOne + 1; - return state; -} - -int NXNextMapState(NXMapTable *table, NXMapState *state, const void **key, const void **value) { - MapPair *pairs = (MapPair *)table->buckets; - while (state->index--) { - MapPair *pair = pairs + state->index; - if (pair->key != NX_MAPNOTAKEY) { - *key = pair->key; *value = pair->value; - return YES; - } - } - return NO; -} - - -/*********************************************************************** - * NXMapKeyCopyingInsert - * Like NXMapInsert, but strdups the key if necessary. - * Used to prevent stale pointers when bundles are unloaded. - **********************************************************************/ -void *NXMapKeyCopyingInsert(NXMapTable *table, const void *key, const void *value) -{ - void *realKey; - void *realValue = NULL; - - if ((realKey = NXMapMember(table, key, &realValue)) != NX_MAPNOTAKEY) { - // key DOES exist in table - use table's key for insertion - } else { - // key DOES NOT exist in table - copy the new key before insertion - realKey = (void *)strdup((char *)key); - } - return NXMapInsert(table, realKey, value); -} - - -/*********************************************************************** - * NXMapKeyFreeingRemove - * Like NXMapRemove, but frees the existing key if necessary. - * Used to prevent stale pointers when bundles are unloaded. - **********************************************************************/ -void *NXMapKeyFreeingRemove(NXMapTable *table, const void *key) -{ - void *realKey; - void *realValue = NULL; - - if ((realKey = NXMapMember(table, key, &realValue)) != NX_MAPNOTAKEY) { - // key DOES exist in table - remove pair and free key - realValue = NXMapRemove(table, realKey); - free(realKey); // the key from the table, not necessarily the one given - return realValue; - } else { - // key DOES NOT exist in table - nothing to do - return NULL; - } -} - - -/**** Conveniences *************************************/ - -static unsigned _mapPtrHash(NXMapTable *table, const void *key) { -#ifdef __LP64__ - return (unsigned)(((uintptr_t)key) >> 3); -#else - return ((uintptr_t)key) >> 2; -#endif -} - -static unsigned _mapStrHash(NXMapTable *table, const void *key) { - unsigned hash = 0; - unsigned char *s = (unsigned char *)key; - /* unsigned to avoid a sign-extend */ - /* unroll the loop */ - if (s) for (; ; ) { - if (*s == '\0') break; - hash ^= *s++; - if (*s == '\0') break; - hash ^= *s++ << 8; - if (*s == '\0') break; - hash ^= *s++ << 16; - if (*s == '\0') break; - hash ^= *s++ << 24; - } - return xorHash(hash); -} - -static int _mapPtrIsEqual(NXMapTable *table, const void *key1, const void *key2) { - return key1 == key2; -} - -static int _mapStrIsEqual(NXMapTable *table, const void *key1, const void *key2) { - if (key1 == key2) return YES; - if (! key1) return ! strlen ((char *) key2); - if (! key2) return ! strlen ((char *) key1); - if (((char *) key1)[0] != ((char *) key2)[0]) return NO; - return (strcmp((char *) key1, (char *) key2)) ? NO : YES; -} - -static void _mapNoFree(NXMapTable *table, void *key, void *value) {} - -const NXMapTablePrototype NXPtrValueMapPrototype = { - _mapPtrHash, _mapPtrIsEqual, _mapNoFree, 0 -}; - -const NXMapTablePrototype NXStrValueMapPrototype = { - _mapStrHash, _mapStrIsEqual, _mapNoFree, 0 -}; - - -#if !__OBJC2__ && !TARGET_OS_WIN32 - -/* This only works with class Object, which is unavailable. */ - -/* Method prototypes */ -@interface DoesNotExist -+ (id)class; -+ (id)initialize; -- (id)description; -- (const char *)UTF8String; -- (unsigned long)hash; -- (BOOL)isEqual:(id)object; -- (void)free; -@end - -static unsigned _mapObjectHash(NXMapTable *table, const void *key) { - return [(id)key hash]; -} - -static int _mapObjectIsEqual(NXMapTable *table, const void *key1, const void *key2) { - return [(id)key1 isEqual:(id)key2]; -} - -static void _mapObjectFree(NXMapTable *table, void *key, void *value) { - [(id)key free]; -} - -const NXMapTablePrototype NXObjectMapPrototype = { - _mapObjectHash, _mapObjectIsEqual, _mapObjectFree, 0 -}; - -#endif diff --git a/objc/objc-runtime/runtime/message.h b/objc/objc-runtime/runtime/message.h deleted file mode 100644 index 9f2a1c6..0000000 --- a/objc/objc-runtime/runtime/message.h +++ /dev/null @@ -1,333 +0,0 @@ -/* - * 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@ - */ - -#ifndef _OBJC_MESSAGE_H -#define _OBJC_MESSAGE_H - -#pragma GCC system_header - -#include <objc/objc.h> -#include <objc/runtime.h> - -#pragma GCC system_header - -#ifndef OBJC_SUPER -#define OBJC_SUPER - -/// Specifies the superclass of an instance. -struct objc_super { - /// Specifies an instance of a class. - __unsafe_unretained id receiver; - - /// Specifies the particular superclass of the instance to message. -#if !defined(__cplusplus) && !__OBJC2__ - /* For compatibility with old objc-runtime.h header */ - __unsafe_unretained Class class; -#else - __unsafe_unretained Class super_class; -#endif - /* super_class is the first class to search */ -}; -#endif - - -/* Basic Messaging Primitives - * - * On some architectures, use objc_msgSend_stret for some struct return types. - * On some architectures, use objc_msgSend_fpret for some float return types. - * On some architectures, use objc_msgSend_fp2ret for some float return types. - * - * These functions must be cast to an appropriate function pointer type - * before being called. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES -OBJC_EXPORT void objc_msgSend(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -OBJC_EXPORT void objc_msgSendSuper(void /* struct objc_super *super, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -#else -/** - * Sends a message with a simple return value to an instance of a class. - * - * @param self A pointer to the instance of the class that is to receive the message. - * @param op The selector of the method that handles the message. - * @param ... - * A variable argument list containing the arguments to the method. - * - * @return The return value of the method. - * - * @note When it encounters a method call, the compiler generates a call to one of the - * functions \c objc_msgSend, \c objc_msgSend_stret, \c objc_msgSendSuper, or \c objc_msgSendSuper_stret. - * Messages sent to an object’s superclass (using the \c super keyword) are sent using \c objc_msgSendSuper; - * other messages are sent using \c objc_msgSend. Methods that have data structures as return values - * are sent using \c objc_msgSendSuper_stret and \c objc_msgSend_stret. - */ -OBJC_EXPORT id objc_msgSend(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -/** - * Sends a message with a simple return value to the superclass of an instance of a class. - * - * @param super A pointer to an \c objc_super data structure. Pass values identifying the - * context the message was sent to, including the instance of the class that is to receive the - * message and the superclass at which to start searching for the method implementation. - * @param op A pointer of type SEL. Pass the selector of the method that will handle the message. - * @param ... - * A variable argument list containing the arguments to the method. - * - * @return The return value of the method identified by \e op. - * - * @see objc_msgSend - */ -OBJC_EXPORT id objc_msgSendSuper(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -#endif - - -/* Struct-returning Messaging Primitives - * - * Use these functions to call methods that return structs on the stack. - * On some architectures, some structures are returned in registers. - * Consult your local function call ABI documentation for details. - * - * These functions must be cast to an appropriate function pointer type - * before being called. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES -OBJC_EXPORT void objc_msgSend_stret(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -OBJC_EXPORT void objc_msgSendSuper_stret(void /* struct objc_super *super, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -#else -/** - * Sends a message with a data-structure return value to an instance of a class. - * - * @see objc_msgSend - */ -OBJC_EXPORT void objc_msgSend_stret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; - -/** - * Sends a message with a data-structure return value to the superclass of an instance of a class. - * - * @see objc_msgSendSuper - */ -OBJC_EXPORT void objc_msgSendSuper_stret(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -#endif - - -/* Floating-point-returning Messaging Primitives - * - * Use these functions to call methods that return floating-point values - * on the stack. - * Consult your local function call ABI documentation for details. - * - * arm: objc_msgSend_fpret not used - * i386: objc_msgSend_fpret used for `float`, `double`, `long double`. - * x86-64: objc_msgSend_fpret used for `long double`. - * - * arm: objc_msgSend_fp2ret not used - * i386: objc_msgSend_fp2ret not used - * x86-64: objc_msgSend_fp2ret used for `_Complex long double`. - * - * These functions must be cast to an appropriate function pointer type - * before being called. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES - -# if defined(__i386__) - -OBJC_EXPORT void objc_msgSend_fpret(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0); - -# elif defined(__x86_64__) - -OBJC_EXPORT void objc_msgSend_fpret(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_msgSend_fp2ret(void /* id self, SEL op, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -# endif - -// !OBJC_OLD_DISPATCH_PROTOTYPES -#else -// OBJC_OLD_DISPATCH_PROTOTYPES -# if defined(__i386__) - -/** - * Sends a message with a floating-point return value to an instance of a class. - * - * @see objc_msgSend - * @note On the i386 platform, the ABI for functions returning a floating-point value is - * incompatible with that for functions returning an integral type. On the i386 platform, therefore, - * you must use \c objc_msgSend_fpret for functions returning non-integral type. For \c float or - * \c long \c double return types, cast the function to an appropriate function pointer type first. - */ -OBJC_EXPORT double objc_msgSend_fpret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0); - -/* Use objc_msgSendSuper() for fp-returning messages to super. */ -/* See also objc_msgSendv_fpret() below. */ - -# elif defined(__x86_64__) -/** - * Sends a message with a floating-point return value to an instance of a class. - * - * @see objc_msgSend - */ -OBJC_EXPORT long double objc_msgSend_fpret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -# if __STDC_VERSION__ >= 199901L -OBJC_EXPORT _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -# else -OBJC_EXPORT void objc_msgSend_fp2ret(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -# endif - -/* Use objc_msgSendSuper() for fp-returning messages to super. */ -/* See also objc_msgSendv_fpret() below. */ - -# endif - -// OBJC_OLD_DISPATCH_PROTOTYPES -#endif - - -/* Direct Method Invocation Primitives - * Use these functions to call the implementation of a given Method. - * This is faster than calling method_getImplementation() and method_getName(). - * - * The receiver must not be nil. - * - * These functions must be cast to an appropriate function pointer type - * before being called. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES -OBJC_EXPORT void method_invoke(void /* id receiver, Method m, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void method_invoke_stret(void /* id receiver, Method m, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -#else -OBJC_EXPORT id method_invoke(id receiver, Method m, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void method_invoke_stret(id receiver, Method m, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; -#endif - - -/* Message Forwarding Primitives - * Use these functions to forward a message as if the receiver did not - * respond to it. - * - * The receiver must not be nil. - * - * class_getMethodImplementation() may return (IMP)_objc_msgForward. - * class_getMethodImplementation_stret() may return (IMP)_objc_msgForward_stret - * - * These functions must be cast to an appropriate function pointer type - * before being called. - * - * Before Mac OS X 10.6, _objc_msgForward must not be called directly - * but may be compared to other IMP values. - */ -#if !OBJC_OLD_DISPATCH_PROTOTYPES -OBJC_EXPORT void _objc_msgForward(void /* id receiver, SEL sel, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -OBJC_EXPORT void _objc_msgForward_stret(void /* id receiver, SEL sel, ... */ ) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) - OBJC_ARM64_UNAVAILABLE; -#else -OBJC_EXPORT id _objc_msgForward(id receiver, SEL sel, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -OBJC_EXPORT void _objc_msgForward_stret(id receiver, SEL sel, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) - OBJC_ARM64_UNAVAILABLE; -#endif - - -/* Variable-argument Messaging Primitives - * - * Use these functions to call methods with a list of arguments, such - * as the one passed to forward:: . - * - * The contents of the argument list are architecture-specific. - * Consult your local function call ABI documentation for details. - * - * These functions must be cast to an appropriate function pointer type - * before being called, except for objc_msgSendv_stret() which must not - * be cast to a struct-returning type. - */ - -typedef void* marg_list; - -OBJC_EXPORT id objc_msgSendv(id self, SEL op, size_t arg_size, marg_list arg_frame) OBJC2_UNAVAILABLE; -OBJC_EXPORT void objc_msgSendv_stret(void *stretAddr, id self, SEL op, size_t arg_size, marg_list arg_frame) OBJC2_UNAVAILABLE; -/* Note that objc_msgSendv_stret() does not return a structure type, - * and should not be cast to do so. This is unlike objc_msgSend_stret() - * and objc_msgSendSuper_stret(). - */ -#if defined(__i386__) -OBJC_EXPORT double objc_msgSendv_fpret(id self, SEL op, unsigned arg_size, marg_list arg_frame) OBJC2_UNAVAILABLE; -#endif - - -/* The following marg_list macros are of marginal utility. They - * are included for compatibility with the old objc-class.h header. */ - -#if !__OBJC2__ - -#define marg_prearg_size 0 - -#define marg_malloc(margs, method) \ - do { \ - margs = (marg_list *)malloc (marg_prearg_size + ((7 + method_getSizeOfArguments(method)) & ~7)); \ - } while (0) - -#define marg_free(margs) \ - do { \ - free(margs); \ - } while (0) - -#define marg_adjustedOffset(method, offset) \ - (marg_prearg_size + offset) - -#define marg_getRef(margs, offset, type) \ - ( (type *)((char *)margs + marg_adjustedOffset(method,offset) ) ) - -#define marg_getValue(margs, offset, type) \ - ( *marg_getRef(margs, offset, type) ) - -#define marg_setValue(margs, offset, type, value) \ - ( marg_getValue(margs, offset, type) = (value) ) - -#endif - -#endif diff --git a/objc/objc-runtime/runtime/objc-abi.h b/objc/objc-runtime/runtime/objc-abi.h deleted file mode 100644 index fb325ef..0000000 --- a/objc/objc-runtime/runtime/objc-abi.h +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (c) 2009 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 _OBJC_ABI_H -#define _OBJC_ABI_H - -/* - * WARNING DANGER HAZARD BEWARE EEK - * - * Everything in this file is for Apple Internal use only. - * These will change in arbitrary OS updates and in unpredictable ways. - * When your program breaks, you get to keep both pieces. - */ - -/* - * objc-abi.h: Declarations for functions used by compiler codegen. - */ - -#include <malloc/malloc.h> -#include <objc/objc.h> -#include <objc/runtime.h> -#include <objc/message.h> - -/* Runtime startup. */ - -// Old static initializer. Used by old crt1.o and old bug workarounds. -OBJC_EXPORT void _objcInit(void) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/* Images */ - -// Description of an Objective-C image. -// __DATA,__objc_imageinfo stores one of these. -typedef struct objc_image_info { - uint32_t version; // currently 0 - uint32_t flags; -} objc_image_info; - -// Values for objc_image_info.flags -#define OBJC_IMAGE_IS_REPLACEMENT (1<<0) -#define OBJC_IMAGE_SUPPORTS_GC (1<<1) -#define OBJC_IMAGE_REQUIRES_GC (1<<2) -#define OBJC_IMAGE_OPTIMIZED_BY_DYLD (1<<3) -#define OBJC_IMAGE_SUPPORTS_COMPACTION (1<<4) // might be re-assignable - - -/* Properties */ - -// Read or write an object property. Not all object properties use these. -OBJC_EXPORT id objc_getProperty(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -OBJC_EXPORT void objc_setProperty_atomic(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; -OBJC_EXPORT void objc_setProperty_nonatomic(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; -OBJC_EXPORT void objc_setProperty_atomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; -OBJC_EXPORT void objc_setProperty_nonatomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0) - OBJC_GC_UNAVAILABLE; - - -// Read or write a non-object property. Not all uses are C structs, -// and not all C struct properties use this. -OBJC_EXPORT void objc_copyStruct(void *dest, const void *src, ptrdiff_t size, BOOL atomic, BOOL hasStrong) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -// Perform a copy of a C++ object using striped locks. Used by non-POD C++ typed atomic properties. -OBJC_EXPORT void objc_copyCppObjectAtomic(void *dest, const void *src, void (*copyHelper) (void *dest, const void *source)) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); - -/* Classes. */ -#if __OBJC2__ -OBJC_EXPORT IMP _objc_empty_vtable - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -#endif -OBJC_EXPORT struct objc_cache _objc_empty_cache - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - - -/* Messages */ - -#if __OBJC2__ -// objc_msgSendSuper2() takes the current search class, not its superclass. -OBJC_EXPORT id objc_msgSendSuper2(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0); -OBJC_EXPORT void objc_msgSendSuper2_stret(struct objc_super *super, SEL op,...) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; - -// objc_msgSend_noarg() may be faster for methods with no additional arguments. -OBJC_EXPORT id objc_msgSend_noarg(id self, SEL _cmd) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#endif - -#if __OBJC2__ -// Debug messengers. Messengers used by the compiler have a debug flavor that -// may perform extra sanity checking. -// Old objc_msgSendSuper() does not have a debug version; this is OBJC2 only. -// *_fixup() do not have debug versions; use non-fixup only for debug mode. -OBJC_EXPORT id objc_msgSend_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT id objc_msgSendSuper2_debug(struct objc_super *super, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT void objc_msgSend_stret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0) - OBJC_ARM64_UNAVAILABLE; -OBJC_EXPORT void objc_msgSendSuper2_stret_debug(struct objc_super *super, SEL op,...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0) - OBJC_ARM64_UNAVAILABLE; - -# if defined(__i386__) -OBJC_EXPORT double objc_msgSend_fpret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# elif defined(__x86_64__) -OBJC_EXPORT long double objc_msgSend_fpret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# if __STDC_VERSION__ >= 199901L -OBJC_EXPORT _Complex long double objc_msgSend_fp2ret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# else -OBJC_EXPORT void objc_msgSend_fp2ret_debug(id self, SEL op, ...) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -# endif -# endif - -#endif - -#if defined(__x86_64__) && TARGET_OS_MAC && !TARGET_IPHONE_SIMULATOR -// objc_msgSend_fixup() is used for vtable-dispatchable call sites. -OBJC_EXPORT void objc_msgSend_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSend_stret_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSendSuper2_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSendSuper2_stret_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSend_fpret_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -OBJC_EXPORT void objc_msgSend_fp2ret_fixup(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5, __MAC_10_8, __IPHONE_NA, __IPHONE_NA); -#endif - -/* C++-compatible exception handling. */ -#if __OBJC2__ - -// fixme these conflict with C++ compiler's internal definitions -#if !defined(__cplusplus) - -// Vtable for C++ exception typeinfo for Objective-C types. -OBJC_EXPORT const void *objc_ehtype_vtable[] - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -// C++ exception typeinfo for type `id`. -OBJC_EXPORT struct objc_typeinfo OBJC_EHTYPE_id - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -#endif - -// Exception personality function for Objective-C and Objective-C++ code. -struct _Unwind_Exception; -struct _Unwind_Context; -OBJC_EXPORT int -__objc_personality_v0(int version, - int actions, - uint64_t exceptionClass, - struct _Unwind_Exception *exceptionObject, - struct _Unwind_Context *context) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -#endif - -/* ARR */ - -OBJC_EXPORT id objc_retainBlock(id) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -#endif diff --git a/objc/objc-runtime/runtime/objc-accessors.h b/objc/objc-runtime/runtime/objc-accessors.h deleted file mode 100644 index 8b2f5f1..0000000 --- a/objc/objc-runtime/runtime/objc-accessors.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2006-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@ - */ - -#ifndef _OBJC_ACCESSORS_H_ -#define _OBJC_ACCESSORS_H_ - -#include <objc/objc.h> -#include <stddef.h> - -__BEGIN_DECLS - -#if SUPPORT_GC - -extern void objc_setProperty_non_gc(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy); -extern id objc_getProperty_non_gc(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic); - -extern void objc_setProperty_gc(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy); -extern id objc_getProperty_gc(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic); - -#endif - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/runtime/objc-accessors.mm b/objc/objc-runtime/runtime/objc-accessors.mm deleted file mode 100644 index 67d9846..0000000 --- a/objc/objc-runtime/runtime/objc-accessors.mm +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -#include <string.h> -#include <stddef.h> - -#include <libkern/OSAtomic.h> - -#include "objc-private.h" -#include "objc-auto.h" -#include "runtime.h" -#include "objc-accessors.h" - -// stub interface declarations to make compiler happy. - -@interface __NSCopyable -- (id)copyWithZone:(void *)zone; -@end - -@interface __NSMutableCopyable -- (id)mutableCopyWithZone:(void *)zone; -@end - -static StripedMap<spinlock_t> PropertyLocks; - -#define MUTABLE_COPY 2 - -id objc_getProperty_non_gc(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) { - if (offset == 0) { - return object_getClass(self); - } - - // Retain release world - id *slot = (id*) ((char*)self + offset); - if (!atomic) return *slot; - - // Atomic retain release world - spinlock_t& slotlock = PropertyLocks[slot]; - slotlock.lock(); - id value = objc_retain(*slot); - slotlock.unlock(); - - // for performance, we (safely) issue the autorelease OUTSIDE of the spinlock. - return objc_autoreleaseReturnValue(value); -} - - -static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy) __attribute__((always_inline)); - -static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy) -{ - if (offset == 0) { - object_setClass(self, newValue); - return; - } - - id oldValue; - id *slot = (id*) ((char*)self + offset); - - if (copy) { - newValue = [newValue copyWithZone:nil]; - } else if (mutableCopy) { - newValue = [newValue mutableCopyWithZone:nil]; - } else { - if (*slot == newValue) return; - newValue = objc_retain(newValue); - } - - if (!atomic) { - oldValue = *slot; - *slot = newValue; - } else { - spinlock_t& slotlock = PropertyLocks[slot]; - slotlock.lock(); - oldValue = *slot; - *slot = newValue; - slotlock.unlock(); - } - - objc_release(oldValue); -} - -void objc_setProperty_non_gc(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy) -{ - bool copy = (shouldCopy && shouldCopy != MUTABLE_COPY); - bool mutableCopy = (shouldCopy == MUTABLE_COPY); - reallySetProperty(self, _cmd, newValue, offset, atomic, copy, mutableCopy); -} - -void objc_setProperty_atomic(id self, SEL _cmd, id newValue, ptrdiff_t offset) -{ - reallySetProperty(self, _cmd, newValue, offset, true, false, false); -} - -void objc_setProperty_nonatomic(id self, SEL _cmd, id newValue, ptrdiff_t offset) -{ - reallySetProperty(self, _cmd, newValue, offset, false, false, false); -} - - -void objc_setProperty_atomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset) -{ - reallySetProperty(self, _cmd, newValue, offset, true, true, false); -} - -void objc_setProperty_nonatomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset) -{ - reallySetProperty(self, _cmd, newValue, offset, false, true, false); -} - - -#if SUPPORT_GC - -id objc_getProperty_gc(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) { - return *(id*) ((char*)self + offset); -} - -void objc_setProperty_gc(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy) { - if (shouldCopy) { - newValue = (shouldCopy == MUTABLE_COPY ? [newValue mutableCopyWithZone:nil] : [newValue copyWithZone:nil]); - } - objc_assign_ivar(newValue, self, offset); -} - -// objc_getProperty and objc_setProperty are resolver functions in objc-auto.mm - -#else - -id -objc_getProperty(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) -{ - return objc_getProperty_non_gc(self, _cmd, offset, atomic); -} - -void -objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, - BOOL atomic, signed char shouldCopy) -{ - objc_setProperty_non_gc(self, _cmd, offset, newValue, atomic, shouldCopy); -} - -#endif - - -// This entry point was designed wrong. When used as a getter, src needs to be locked so that -// if simultaneously used for a setter then there would be contention on src. -// So we need two locks - one of which will be contended. -void objc_copyStruct(void *dest, const void *src, ptrdiff_t size, BOOL atomic, BOOL hasStrong) { - static StripedMap<spinlock_t> StructLocks; - spinlock_t *srcLock = nil; - spinlock_t *dstLock = nil; - if (atomic) { - srcLock = &StructLocks[src]; - dstLock = &StructLocks[dest]; - spinlock_t::lockTwo(srcLock, dstLock); - } -#if SUPPORT_GC - if (UseGC && hasStrong) { - auto_zone_write_barrier_memmove(gc_zone, dest, src, size); - } else -#endif - { - memmove(dest, src, size); - } - if (atomic) { - spinlock_t::unlockTwo(srcLock, dstLock); - } -} - -void objc_copyCppObjectAtomic(void *dest, const void *src, void (*copyHelper) (void *dest, const void *source)) { - static StripedMap<spinlock_t> CppObjectLocks; - spinlock_t *srcLock = &CppObjectLocks[src]; - spinlock_t *dstLock = &CppObjectLocks[dest]; - spinlock_t::lockTwo(srcLock, dstLock); - - // let C++ code perform the actual copy. - copyHelper(dest, src); - - spinlock_t::unlockTwo(srcLock, dstLock); -} diff --git a/objc/objc-runtime/runtime/objc-api.h b/objc/objc-runtime/runtime/objc-api.h deleted file mode 100644 index dcc83f9..0000000 --- a/objc/objc-runtime/runtime/objc-api.h +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (c) 1999-2006 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@ - */ -// Copyright 1988-1996 NeXT Software, Inc. - -#ifndef _OBJC_OBJC_API_H_ -#define _OBJC_OBJC_API_H_ - -#include <Availability.h> -#include <AvailabilityMacros.h> -#include <TargetConditionals.h> - -#ifndef __has_feature -# define __has_feature(x) 0 -#endif - -#ifndef __has_extension -# define __has_extension __has_feature -#endif - -#ifndef __has_attribute -# define __has_attribute(x) 0 -#endif - - -/* - * OBJC_API_VERSION 0 or undef: Tiger and earlier API only - * OBJC_API_VERSION 2: Leopard and later API available - */ -#if !defined(OBJC_API_VERSION) -# if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_5 -# define OBJC_API_VERSION 0 -# else -# define OBJC_API_VERSION 2 -# endif -#endif - - -/* - * OBJC_NO_GC 1: GC is not supported - * OBJC_NO_GC undef: GC is supported - * - * OBJC_NO_GC_API undef: Libraries must export any symbols that - * dual-mode code may links to. - * OBJC_NO_GC_API 1: Libraries need not export GC-related symbols. - */ -#if TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 - /* GC is unsupported. GC API symbols are not exported. */ -# define OBJC_NO_GC 1 -# define OBJC_NO_GC_API 1 -#elif TARGET_OS_MAC && __x86_64h__ - /* GC is unsupported. GC API symbols are exported. */ -# define OBJC_NO_GC 1 -# undef OBJC_NO_GC_API -#else - /* GC is supported. */ -# undef OBJC_NO_GC -# undef OBJC_GC_API -#endif - - -/* NS_ENFORCE_NSOBJECT_DESIGNATED_INITIALIZER == 1 - * marks -[NSObject init] as a designated initializer. */ -#if !defined(NS_ENFORCE_NSOBJECT_DESIGNATED_INITIALIZER) -# define NS_ENFORCE_NSOBJECT_DESIGNATED_INITIALIZER 1 -#endif - - -/* OBJC_OLD_DISPATCH_PROTOTYPES == 0 enforces the rule that the dispatch - * functions must be cast to an appropriate function pointer type. */ -#if !defined(OBJC_OLD_DISPATCH_PROTOTYPES) -# define OBJC_OLD_DISPATCH_PROTOTYPES 1 -#endif - - -/* OBJC_ISA_AVAILABILITY: `isa` will be deprecated or unavailable - * in the future */ -#if !defined(OBJC_ISA_AVAILABILITY) -# if __OBJC2__ -# define OBJC_ISA_AVAILABILITY __attribute__((deprecated)) -# else -# define OBJC_ISA_AVAILABILITY /* still available */ -# endif -#endif - - -/* OBJC2_UNAVAILABLE: unavailable in objc 2.0, deprecated in Leopard */ -#if !defined(OBJC2_UNAVAILABLE) -# if __OBJC2__ -# define OBJC2_UNAVAILABLE UNAVAILABLE_ATTRIBUTE -# else - /* plain C code also falls here, but this is close enough */ -# define OBJC2_UNAVAILABLE __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0) -# endif -#endif - -/* OBJC_ARC_UNAVAILABLE: unavailable with -fobjc-arc */ -#if !defined(OBJC_ARC_UNAVAILABLE) -# if __has_feature(objc_arc) -# if __has_extension(attribute_unavailable_with_message) -# define OBJC_ARC_UNAVAILABLE __attribute__((unavailable("not available in automatic reference counting mode"))) -# else -# define OBJC_ARC_UNAVAILABLE __attribute__((unavailable)) -# endif -# else -# define OBJC_ARC_UNAVAILABLE -# endif -#endif - -/* OBJC_SWIFT_UNAVAILABLE: unavailable in Swift */ -#if !defined(OBJC_SWIFT_UNAVAILABLE) -# if __has_feature(attribute_availability_swift) -# define OBJC_SWIFT_UNAVAILABLE(_msg) __attribute__((availability(swift, unavailable, message=_msg))) -# else -# define OBJC_SWIFT_UNAVAILABLE(_msg) -# endif -#endif - -/* OBJC_ARM64_UNAVAILABLE: unavailable on arm64 (i.e. stret dispatch) */ -#if !defined(OBJC_ARM64_UNAVAILABLE) -# if defined(__arm64__) -# define OBJC_ARM64_UNAVAILABLE __attribute__((unavailable("not available in arm64"))) -# else -# define OBJC_ARM64_UNAVAILABLE -# endif -#endif - -/* OBJC_GC_UNAVAILABLE: unavailable with -fobjc-gc or -fobjc-gc-only */ -#if !defined(OBJC_GC_UNAVAILABLE) -# if __OBJC_GC__ -# if __has_extension(attribute_unavailable_with_message) -# define OBJC_GC_UNAVAILABLE __attribute__((unavailable("not available in garbage collecting mode"))) -# else -# define OBJC_GC_UNAVAILABLE __attribute__((unavailable)) -# endif -# else -# define OBJC_GC_UNAVAILABLE -# endif -#endif - -#if !defined(OBJC_EXTERN) -# if defined(__cplusplus) -# define OBJC_EXTERN extern "C" -# else -# define OBJC_EXTERN extern -# endif -#endif - -#if !defined(OBJC_VISIBLE) -# if TARGET_OS_WIN32 -# if defined(BUILDING_OBJC) -# define OBJC_VISIBLE __declspec(dllexport) -# else -# define OBJC_VISIBLE __declspec(dllimport) -# endif -# else -# define OBJC_VISIBLE __attribute__((visibility("default"))) -# endif -#endif - -#if !defined(OBJC_EXPORT) -# define OBJC_EXPORT OBJC_EXTERN OBJC_VISIBLE -#endif - -#if !defined(OBJC_IMPORT) -# define OBJC_IMPORT extern -#endif - -#if !defined(OBJC_ROOT_CLASS) -# if __has_attribute(objc_root_class) -# define OBJC_ROOT_CLASS __attribute__((objc_root_class)) -# else -# define OBJC_ROOT_CLASS -# endif -#endif - -#ifndef __DARWIN_NULL -#define __DARWIN_NULL NULL -#endif - -#if !defined(OBJC_INLINE) -# define OBJC_INLINE __inline -#endif - -// Declares an enum type or option bits type as appropriate for each language. -#if (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || (!__cplusplus && __has_feature(objc_fixed_enum)) -#define OBJC_ENUM(_type, _name) enum _name : _type _name; enum _name : _type -#if (__cplusplus) -#define OBJC_OPTIONS(_type, _name) _type _name; enum : _type -#else -#define OBJC_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type -#endif -#else -#define OBJC_ENUM(_type, _name) _type _name; enum -#define OBJC_OPTIONS(_type, _name) _type _name; enum -#endif - -#endif diff --git a/objc/objc-runtime/runtime/objc-auto-dump.h b/objc/objc-runtime/runtime/objc-auto-dump.h deleted file mode 100644 index d58e0c0..0000000 --- a/objc/objc-runtime/runtime/objc-auto-dump.h +++ /dev/null @@ -1,55 +0,0 @@ -// -// objc-auto-dump.h -// objc -// The raw dump file format -// See objc-gdb.h for the primitive. -// -// Created by Blaine Garst on 12/8/08. -// Copyright 2008 Apple, Inc. All rights reserved. -// -#ifndef _OBJC_AUTO_DUMP_H_ -#define _OBJC_AUTO_DUMP_H_ - -/* - * Raw file format definitions - */ - -// must be unique in first letter... -// RAW FORMAT -#define HEADER "dumpster" -#define THREAD 't' -#define LOCAL 'l' -#define NODE 'n' -#define REGISTER 'r' -#define ROOT 'g' -#define WEAK 'w' -#define CLASS 'c' -#define END 'e' - -#define SixtyFour 1 -#define Little 2 - -/* - -Raw format, not that anyone should really care. Most programs should use the cooked file reader. - -<rawfile := <header> <arch> <middle>* <end> -<header> := 'd' 'u' 'm' 'p' 's' 't' 'e' 'r' ; the HEADER string -<arch> := SixtyFour? + Little? ; architecture -<middle> := <thread> | <root> | <node> | <weak> | <class> -<thread> := <register> <stack> <local>* ; the triple -<register> := 'r' longLength [bytes] ; the register bank -<stack> := 't' longLength [bytes] ; the stack -<local> := 'l' [long] ; a thread local node -<root> := 'g' longAddress longValue -<node> := 'n' longAddress longSize intLayout longRefcount longIsa? -<weak> := 'w' longAddress longValue -<class> := 'c' longAddress <name> <strongLayout> <weakLayout> -<name> := intLength [bytes] ; no null byte -<strongLayout> := intLength [bytes] ; including 0 byte at end -<weakLayout> := intLength [bytes] ; including 0 byte at end -<end> := 'e' - - */ - -#endif diff --git a/objc/objc-runtime/runtime/objc-auto-dump.mm b/objc/objc-runtime/runtime/objc-auto-dump.mm deleted file mode 100644 index 9746daa..0000000 --- a/objc/objc-runtime/runtime/objc-auto-dump.mm +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -#include "objc-config.h" - -#if SUPPORT_GC - -#include "objc-private.h" -#include "objc-auto-dump.h" - -#include <auto_zone.h> -#include <objc/objc.h> -#include <objc/runtime.h> -#include <strings.h> - -/* - * Utilities - */ - -static char myType() { - char type = 0; - if (sizeof(void *) == 8) type |= SixtyFour; -#if __LITTLE_ENDIAN__ - type |= Little; -#endif - return type; -} - -/* - * Sigh, a mutable set. - */ - -typedef struct { - long *items; - long count; - long capacity; -} pointer_set_t; - -static pointer_set_t *new_pointer_set() { - pointer_set_t *result = (pointer_set_t *)malloc(sizeof(pointer_set_t)); - result->items = (long *)calloc(64, sizeof(long)); - result->count = 0; - result->capacity = 63; // last valid ptr, also mask - return result; -} - -static void pointer_set_grow(pointer_set_t *set); - -static void pointer_set_add(pointer_set_t *set, long ptr) { - long hash = ptr & set->capacity; - while (1) { - if (!set->items[hash]) { - set->items[hash] = ptr; - ++set->count; - if (set->count*3 > set->capacity*2) - pointer_set_grow(set); - return; - } - if (set->items[hash] == ptr) return; - hash = (hash + 1) & set->capacity; - } -} - -static void pointer_set_grow(pointer_set_t *set) { - long oldCapacity = set->capacity; - long *oldItems = set->items; - long i; - set->count = 0; - set->capacity = 2*(oldCapacity+1)-1; - set->items = (long *)calloc(2*(oldCapacity+1), sizeof(long)); - for (i = 0; i < oldCapacity; ++i) - if (oldItems[i]) pointer_set_add(set, oldItems[i]); - free(oldItems); -} - -static void pointer_set_iterate(pointer_set_t *set, void (^block)(long item)) { - long i; - for (i = 0; i < set->capacity; ++i) - if (set->items[i]) block(set->items[i]); -} - -static void pointer_set_dispose(pointer_set_t *set) { - free(set->items); - free(set); -} - -/* - Quickly dump heap to a named file in a pretty raw format. - */ -bool _objc_dumpHeap(auto_zone_t *zone, const char *filename) { - // just write interesting info to disk - int fd = secure_open(filename, O_WRONLY|O_CREAT, geteuid()); - if (fd < 0) return NO; - FILE *fp = fdopen(fd, "w"); - if (fp == NULL) { - return NO; - } - - fwrite(HEADER, strlen(HEADER), 1, fp); - char type2 = myType(); - fwrite(&type2, 1, 1, fp); - - // for each thread... - - // do registers first - auto_zone_register_dump dump_registers = ^(const void *base, unsigned long byte_size) { - char type = REGISTER; - fwrite(&type, 1, 1, fp); - //fwrite(REGISTER, strlen(REGISTER), 1, fp); - fwrite(&byte_size, sizeof(byte_size), 1, fp); - fwrite(base, byte_size, 1, fp); - }; - - // then stacks - auto_zone_stack_dump dump_stack = ^(const void *base, unsigned long byte_size) { - char type = THREAD; - fwrite(&type, 1, 1, fp); - //fwrite(THREAD, strlen(THREAD), 1, fp); - fwrite(&byte_size, sizeof(byte_size), 1, fp); - fwrite(base, byte_size, 1, fp); - }; - - // then locals - void (^dump_local)(const void *, unsigned long, unsigned int, unsigned long) = - ^(const void *address, unsigned long size, unsigned int layout, unsigned long refcount) { - // just write the value - rely on it showing up again as a node later - char type = LOCAL; - fwrite(&type, 1, 1, fp); - fwrite(&address, sizeof(address), 1, fp); - }; - - - - // roots - auto_zone_root_dump dump_root = ^(const void **address) { - char type = ROOT; - fwrite(&type, 1, 1, fp); - // write the address so that we can catch misregistered globals - fwrite(&address, sizeof(address), 1, fp); - // write content, even (?) if zero - fwrite(address, sizeof(*address), 1, fp); - }; - - // the nodes - pointer_set_t *classes = new_pointer_set(); - auto_zone_node_dump dump_node = ^(const void *address, unsigned long size, unsigned int layout, unsigned long refcount) { - char type = NODE; - fwrite(&type, 1, 1, fp); - fwrite(&address, sizeof(address), 1, fp); - fwrite(&size, sizeof(size), 1, fp); - fwrite(&layout, sizeof(layout), 1, fp); - fwrite(&refcount, sizeof(refcount), 1, fp); - if ((layout & AUTO_UNSCANNED) != AUTO_UNSCANNED) { - // now the nodes unfiltered content - fwrite(address, size, 1, fp); - } - if ((layout & AUTO_OBJECT) == AUTO_OBJECT) { - long theClass = *(long *)address; - if (theClass) pointer_set_add(classes, theClass); - } - }; - - // weak - auto_zone_weak_dump dump_weak = ^(const void **address, const void *item) { - char type = WEAK; - fwrite(&type, 1, 1, fp); - fwrite(&address, sizeof(address), 1, fp); - fwrite(&item, sizeof(item), 1, fp); - }; - - auto_zone_dump(zone, dump_stack, dump_registers, dump_local, dump_root, dump_node, dump_weak); - - pointer_set_iterate(classes, ^(long cls) { - char type = CLASS; - fwrite(&type, 1, 1, fp); - fwrite(&cls, sizeof(cls), 1, fp); // write address so that we can map it from node isa's - // classname (for grins) - const char *className = class_getName((Class)cls); - unsigned int length = (int)strlen(className); - fwrite(&length, sizeof(length), 1, fp); // n - fwrite(className, length, 1, fp); // n bytes - // strong layout - const uint8_t *layout = class_getIvarLayout((Class)cls); - length = layout ? (int)strlen((char *)layout)+1 : 0; // format is <skipnibble><count nibble> ending with <0><0> - fwrite(&length, sizeof(length), 1, fp); // n - fwrite(layout, length, 1, fp); // n bytes - // weak layout - layout = class_getWeakIvarLayout((Class)cls); - length = layout ? (int)strlen((char *)layout)+1 : 0; // format is <skipnibble><count nibble> ending with <0><0> - fwrite(&length, sizeof(length), 1, fp); // n - fwrite(layout, length, 1, fp); // n bytes - }); - - { - // end - char type = END; - fwrite(&type, 1, 1, fp); - fclose(fp); - pointer_set_dispose(classes); - } - return YES; -} - -#endif diff --git a/objc/objc-runtime/runtime/objc-auto.h b/objc/objc-runtime/runtime/objc-auto.h deleted file mode 100644 index 8c755a4..0000000 --- a/objc/objc-runtime/runtime/objc-auto.h +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Copyright (c) 2004-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@ - */ - -#ifndef _OBJC_AUTO_H_ -#define _OBJC_AUTO_H_ - -#pragma GCC system_header - -#include <objc/objc.h> -#include <malloc/malloc.h> -#include <stdint.h> -#include <stddef.h> -#include <string.h> -#include <Availability.h> -#include <TargetConditionals.h> - -#if !TARGET_OS_WIN32 -#include <sys/types.h> -#include <libkern/OSAtomic.h> -#else -# define WINVER 0x0501 // target Windows XP and later -# define _WIN32_WINNT 0x0501 // target Windows XP and later -# define WIN32_LEAN_AND_MEAN -// workaround: windef.h typedefs BOOL as int -# define BOOL WINBOOL -# include <windows.h> -# undef BOOL -#endif - - -/* objc_collect() options */ -enum { - // choose one - OBJC_RATIO_COLLECTION = (0 << 0), // run "ratio" generational collections, then a full - OBJC_GENERATIONAL_COLLECTION = (1 << 0), // run fast incremental collection - OBJC_FULL_COLLECTION = (2 << 0), // run full collection. - OBJC_EXHAUSTIVE_COLLECTION = (3 << 0), // run full collections until memory available stops improving - - OBJC_COLLECT_IF_NEEDED = (1 << 3), // run collection only if needed (allocation threshold exceeded) - OBJC_WAIT_UNTIL_DONE = (1 << 4), // wait (when possible) for collection to end before returning (when collector is running on dedicated thread) -}; - -/* objc_clear_stack() options */ -enum { - OBJC_CLEAR_RESIDENT_STACK = (1 << 0) -}; - -#ifndef OBJC_NO_GC - - -/* GC declarations */ - -/* Collection utilities */ - -OBJC_EXPORT void objc_collect(unsigned long options) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA); -OBJC_EXPORT BOOL objc_collectingEnabled(void) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT malloc_zone_t *objc_collectableZone(void) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/* GC configuration */ - -/* Tells collector to wait until specified bytes have been allocated before trying to collect again. */ -OBJC_EXPORT void objc_setCollectionThreshold(size_t threshold) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - -/* Tells collector to run a full collection for every ratio generational collections. */ -OBJC_EXPORT void objc_setCollectionRatio(size_t ratio) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - -// -// GC-safe compare-and-swap -// - -/* Atomic update, with write barrier. */ -OBJC_EXPORT BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; -/* "Barrier" version also includes memory barrier. */ -OBJC_EXPORT BOOL objc_atomicCompareAndSwapPtrBarrier(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; - -// atomic update of a global variable -OBJC_EXPORT BOOL objc_atomicCompareAndSwapGlobal(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; -OBJC_EXPORT BOOL objc_atomicCompareAndSwapGlobalBarrier(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; -// atomic update of an instance variable -OBJC_EXPORT BOOL objc_atomicCompareAndSwapInstanceVariable(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; -OBJC_EXPORT BOOL objc_atomicCompareAndSwapInstanceVariableBarrier(id predicate, id replacement, volatile id *objectLocation) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA) OBJC_ARC_UNAVAILABLE; - - -// -// Read and write barriers -// - -OBJC_EXPORT id objc_assign_strongCast(id val, id *dest) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); -OBJC_EXPORT id objc_assign_global(id val, id *dest) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); -OBJC_EXPORT id objc_assign_threadlocal(id val, id *dest) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -OBJC_EXPORT id objc_assign_ivar(id value, id dest, ptrdiff_t offset) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); -OBJC_EXPORT void *objc_memmove_collectable(void *dst, const void *src, size_t size) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); - -OBJC_EXPORT id objc_read_weak(id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT id objc_assign_weak(id value, id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - - -// -// Thread management -// - -/* Register the calling thread with the garbage collector. */ -OBJC_EXPORT void objc_registerThreadWithCollector(void) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA); - -/* Unregisters the calling thread with the garbage collector. - Unregistration also happens automatically at thread exit. */ -OBJC_EXPORT void objc_unregisterThreadWithCollector(void) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA); - -/* To be called from code which must only execute on a registered thread. */ -/* If the calling thread is unregistered then an error message is emitted and the thread is implicitly registered. */ -OBJC_EXPORT void objc_assertRegisteredThreadWithCollector(void) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_NA); - -/* Erases any stale references in unused parts of the stack. */ -OBJC_EXPORT void objc_clear_stack(unsigned long options) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - - -// -// Finalization -// - -/* Returns true if object has been scheduled for finalization. Can be used to avoid operations that may lead to resurrection, which are fatal. */ -OBJC_EXPORT BOOL objc_is_finalized(void *ptr) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); - -// Deprcated. Tells runtime to issue finalize calls on the main thread only. -OBJC_EXPORT void objc_finalizeOnMainThread(Class cls) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); - - -// -// Deprecated names. -// - -/* Deprecated. Use objc_collectingEnabled() instead. */ -OBJC_EXPORT BOOL objc_collecting_enabled(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -/* Deprecated. Use objc_setCollectionThreshold() instead. */ -OBJC_EXPORT void objc_set_collection_threshold(size_t threshold) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -/* Deprecated. Use objc_setCollectionRatio() instead. */ -OBJC_EXPORT void objc_set_collection_ratio(size_t ratio) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -/* Deprecated. Use objc_startCollectorThread() instead. */ -OBJC_EXPORT void objc_start_collector_thread(void) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -/* Deprecated. No replacement. Formerly told the collector to run using a dedicated background thread. */ -OBJC_EXPORT void objc_startCollectorThread(void) -__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_7, __IPHONE_NA,__IPHONE_NA); - - -/* Deprecated. Use class_createInstance() instead. */ -OBJC_EXPORT id objc_allocate_object(Class cls, int extra) -__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4,__MAC_10_4, __IPHONE_NA,__IPHONE_NA); - - -/* !defined(OBJC_NO_GC) */ -#else -/* defined(OBJC_NO_GC) */ - - -/* Non-GC declarations */ - -static OBJC_INLINE void objc_collect(unsigned long options __unused) { } -static OBJC_INLINE BOOL objc_collectingEnabled(void) { return NO; } -#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && !TARGET_IPHONE_SIMULATOR -static OBJC_INLINE malloc_zone_t *objc_collectableZone(void) { return nil; } -#endif -static OBJC_INLINE void objc_setCollectionThreshold(size_t threshold __unused) { } -static OBJC_INLINE void objc_setCollectionRatio(size_t ratio __unused) { } -static OBJC_INLINE void objc_startCollectorThread(void) { } - -#if __has_feature(objc_arc) - -/* Covers for GC memory operations are unavailable in ARC */ - -#else - -#if TARGET_OS_WIN32 -static OBJC_INLINE BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) - { void *original = InterlockedCompareExchangePointer((void * volatile *)objectLocation, (void *)replacement, (void *)predicate); return (original == predicate); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapPtrBarrier(id predicate, id replacement, volatile id *objectLocation) - { void *original = InterlockedCompareExchangePointer((void * volatile *)objectLocation, (void *)replacement, (void *)predicate); return (original == predicate); } -#else -static OBJC_INLINE BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) - { return OSAtomicCompareAndSwapPtr((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapPtrBarrier(id predicate, id replacement, volatile id *objectLocation) - { return OSAtomicCompareAndSwapPtrBarrier((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); } -#endif - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapGlobal(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtr(predicate, replacement, objectLocation); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapGlobalBarrier(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtrBarrier(predicate, replacement, objectLocation); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapInstanceVariable(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtr(predicate, replacement, objectLocation); } - -static OBJC_INLINE BOOL objc_atomicCompareAndSwapInstanceVariableBarrier(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtrBarrier(predicate, replacement, objectLocation); } - - -static OBJC_INLINE id objc_assign_strongCast(id val, id *dest) - { return (*dest = val); } - -static OBJC_INLINE id objc_assign_global(id val, id *dest) - { return (*dest = val); } - -static OBJC_INLINE id objc_assign_threadlocal(id val, id *dest) - { return (*dest = val); } - -static OBJC_INLINE id objc_assign_ivar(id val, id dest, ptrdiff_t offset) - { return (*(id*)((char *)dest+offset) = val); } - -static OBJC_INLINE id objc_read_weak(id *location) - { return *location; } - -static OBJC_INLINE id objc_assign_weak(id value, id *location) - { return (*location = value); } - -/* MRC */ -#endif - -static OBJC_INLINE void *objc_memmove_collectable(void *dst, const void *src, size_t size) - { return memmove(dst, src, size); } - -static OBJC_INLINE void objc_finalizeOnMainThread(Class cls __unused) { } -static OBJC_INLINE BOOL objc_is_finalized(void *ptr __unused) { return NO; } -static OBJC_INLINE void objc_clear_stack(unsigned long options __unused) { } - -static OBJC_INLINE BOOL objc_collecting_enabled(void) { return NO; } -static OBJC_INLINE void objc_set_collection_threshold(size_t threshold __unused) { } -static OBJC_INLINE void objc_set_collection_ratio(size_t ratio __unused) { } -static OBJC_INLINE void objc_start_collector_thread(void) { } - -#if __has_feature(objc_arc) -extern id objc_allocate_object(Class cls, int extra) UNAVAILABLE_ATTRIBUTE; -#else -OBJC_EXPORT id class_createInstance(Class cls, size_t extraBytes) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); -static OBJC_INLINE id objc_allocate_object(Class cls, int extra) - { return class_createInstance(cls, extra); } -#endif - -static OBJC_INLINE void objc_registerThreadWithCollector() { } -static OBJC_INLINE void objc_unregisterThreadWithCollector() { } -static OBJC_INLINE void objc_assertRegisteredThreadWithCollector() { } - -/* defined(OBJC_NO_GC) */ -#endif - - -#if TARGET_OS_EMBEDDED -enum { - OBJC_GENERATIONAL = (1 << 0) -}; -static OBJC_INLINE void objc_collect_if_needed(unsigned long options) __attribute__((deprecated)); -static OBJC_INLINE void objc_collect_if_needed(unsigned long options __unused) { } -#endif - -#endif diff --git a/objc/objc-runtime/runtime/objc-auto.mm b/objc/objc-runtime/runtime/objc-auto.mm deleted file mode 100644 index 2030cc8..0000000 --- a/objc/objc-runtime/runtime/objc-auto.mm +++ /dev/null @@ -1,1430 +0,0 @@ -/* - * Copyright (c) 2004-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@ - */ - -#include "objc-private.h" - - -#if OBJC_NO_GC && OBJC_NO_GC_API - -// No GC and no GC symbols needed. We're done here. - -#elif OBJC_NO_GC && !OBJC_NO_GC_API - -// No GC but we do need to export GC symbols. -// These are mostly the same as the OBJC_NO_GC inline versions in objc-auto.h. - -OBJC_EXPORT void objc_collect(unsigned long options __unused) { } -OBJC_EXPORT BOOL objc_collectingEnabled(void) { return NO; } -OBJC_EXPORT void objc_setCollectionThreshold(size_t threshold __unused) { } -OBJC_EXPORT void objc_setCollectionRatio(size_t ratio __unused) { } -OBJC_EXPORT void objc_startCollectorThread(void) { } - -#if TARGET_OS_WIN32 -OBJC_EXPORT BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) - { void *original = InterlockedCompareExchangePointer((void * volatile *)objectLocation, (void *)replacement, (void *)predicate); return (original == predicate); } - -OBJC_EXPORT BOOL objc_atomicCompareAndSwapPtrBarrier(id predicate, id replacement, volatile id *objectLocation) - { void *original = InterlockedCompareExchangePointer((void * volatile *)objectLocation, (void *)replacement, (void *)predicate); return (original == predicate); } -#else -OBJC_EXPORT BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) - { return OSAtomicCompareAndSwapPtr((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); } - -OBJC_EXPORT BOOL objc_atomicCompareAndSwapPtrBarrier(id predicate, id replacement, volatile id *objectLocation) - { return OSAtomicCompareAndSwapPtrBarrier((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); } -#endif - -OBJC_EXPORT BOOL objc_atomicCompareAndSwapGlobal(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtr(predicate, replacement, objectLocation); } - -OBJC_EXPORT BOOL objc_atomicCompareAndSwapGlobalBarrier(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtrBarrier(predicate, replacement, objectLocation); } - -OBJC_EXPORT BOOL objc_atomicCompareAndSwapInstanceVariable(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtr(predicate, replacement, objectLocation); } - -OBJC_EXPORT BOOL objc_atomicCompareAndSwapInstanceVariableBarrier(id predicate, id replacement, volatile id *objectLocation) - { return objc_atomicCompareAndSwapPtrBarrier(predicate, replacement, objectLocation); } - - -OBJC_EXPORT id objc_assign_strongCast(id val, id *dest) - { return (*dest = val); } - -OBJC_EXPORT id objc_assign_global(id val, id *dest) - { return (*dest = val); } - -OBJC_EXPORT id objc_assign_threadlocal(id val, id *dest) - { return (*dest = val); } - -OBJC_EXPORT id objc_assign_ivar(id val, id dest, ptrdiff_t offset) - { return (*(id*)((char *)dest+offset) = val); } - -OBJC_EXPORT id objc_read_weak(id *location) - { return *location; } - -OBJC_EXPORT id objc_assign_weak(id value, id *location) - { return (*location = value); } - -OBJC_EXPORT void *objc_memmove_collectable(void *dst, const void *src, size_t size) - { return memmove(dst, src, size); } - -OBJC_EXPORT void objc_finalizeOnMainThread(Class cls __unused) { } -OBJC_EXPORT BOOL objc_is_finalized(void *ptr __unused) { return NO; } -OBJC_EXPORT void objc_clear_stack(unsigned long options __unused) { } - -OBJC_EXPORT BOOL objc_collecting_enabled(void) { return NO; } -OBJC_EXPORT void objc_set_collection_threshold(size_t threshold __unused) { } -OBJC_EXPORT void objc_set_collection_ratio(size_t ratio __unused) { } -OBJC_EXPORT void objc_start_collector_thread(void) { } - -OBJC_EXPORT id objc_allocate_object(Class cls, int extra) - { return class_createInstance(cls, extra); } - -OBJC_EXPORT void objc_registerThreadWithCollector() { } -OBJC_EXPORT void objc_unregisterThreadWithCollector() { } -OBJC_EXPORT void objc_assertRegisteredThreadWithCollector() { } - -OBJC_EXPORT malloc_zone_t* objc_collect_init(int(*callback)() __unused) { return nil; } -OBJC_EXPORT void* objc_collectableZone() { return nil; } - -OBJC_EXPORT BOOL objc_isAuto(id object __unused) { return NO; } -OBJC_EXPORT BOOL objc_dumpHeap(char *filename __unused, unsigned long length __unused) - { return NO; } - -// OBJC_NO_GC && !OBJC_NO_GC_API -#else -// !OBJC_NO_GC - -// Garbage collection. - -#include <stdint.h> -#include <stdbool.h> -#include <fcntl.h> -#include <dlfcn.h> -#include <mach/mach.h> -#include <mach-o/dyld.h> -#include <mach-o/nlist.h> -#include <sys/types.h> -#include <sys/mman.h> -#include <libkern/OSAtomic.h> -#include <auto_zone.h> - -#include <Block_private.h> -#include <dispatch/private.h> - -#include "objc-private.h" -#include "objc-config.h" -#include "objc-accessors.h" -#include "objc-auto.h" -#include "objc-references.h" -#include "maptable.h" -#include "message.h" -#include "objc-gdb.h" - -#if DEBUG && !__OBJC2__ -#include "objc-exception.h" -#endif - - -static auto_zone_t *gc_zone_init(void); -static void gc_block_init(void); -static void registeredClassTableInit(void); -static bool objc_isRegisteredClass(Class candidate); - -int8_t UseGC = -1; -static bool WantsMainThreadFinalization = NO; - -auto_zone_t *gc_zone = nil; - - -/* Method prototypes */ -@interface DoesNotExist -- (const char *)UTF8String; -- (id)description; -@end - - -/*********************************************************************** -* Break-on-error functions -**********************************************************************/ - -BREAKPOINT_FUNCTION( - void objc_assign_ivar_error(id base, ptrdiff_t offset) -); - -BREAKPOINT_FUNCTION( - void objc_assign_global_error(id value, id *slot) -); - -BREAKPOINT_FUNCTION( - void objc_exception_during_finalize_error(void) -); - -/*********************************************************************** -* Utility exports -* Called by various libraries. -**********************************************************************/ - -OBJC_EXPORT void objc_set_collection_threshold(size_t threshold) { // Old naming - if (UseGC) { - auto_collection_parameters(gc_zone)->collection_threshold = threshold; - } -} - -OBJC_EXPORT void objc_setCollectionThreshold(size_t threshold) { - if (UseGC) { - auto_collection_parameters(gc_zone)->collection_threshold = threshold; - } -} - -void objc_setCollectionRatio(size_t ratio) { - if (UseGC) { - auto_collection_parameters(gc_zone)->full_vs_gen_frequency = ratio; - } -} - -void objc_set_collection_ratio(size_t ratio) { // old naming - if (UseGC) { - auto_collection_parameters(gc_zone)->full_vs_gen_frequency = ratio; - } -} - -void objc_finalizeOnMainThread(Class cls) { - if (UseGC) { - WantsMainThreadFinalization = YES; - cls->setShouldFinalizeOnMainThread(); - } -} - -// stack based data structure queued if/when there is main-thread-only finalization work TBD -typedef struct BatchFinalizeBlock { - auto_zone_foreach_object_t foreach; - auto_zone_cursor_t cursor; - size_t cursor_size; - volatile bool finished; - volatile bool started; - struct BatchFinalizeBlock *next; -} BatchFinalizeBlock_t; - -// The Main Thread Finalization Work Queue Head -static struct { - pthread_mutex_t mutex; - pthread_cond_t condition; - BatchFinalizeBlock_t *head; - BatchFinalizeBlock_t *tail; -} MainThreadWorkQ; - - -void objc_startCollectorThread(void) { -} - -void objc_start_collector_thread(void) { -} - -static void batchFinalizeOnMainThread(void); - -void objc_collect(unsigned long options) { - if (!UseGC) return; - bool onMainThread = pthread_main_np(); - - // while we're here, sneak off and do some finalization work (if any) - if (onMainThread) batchFinalizeOnMainThread(); - // now on with our normally scheduled programming - auto_zone_options_t amode = AUTO_ZONE_COLLECT_NO_OPTIONS; - if (!(options & OBJC_COLLECT_IF_NEEDED)) { - switch (options & 0x3) { - case OBJC_RATIO_COLLECTION: amode = AUTO_ZONE_COLLECT_RATIO_COLLECTION; break; - case OBJC_GENERATIONAL_COLLECTION: amode = AUTO_ZONE_COLLECT_GENERATIONAL_COLLECTION; break; - case OBJC_FULL_COLLECTION: amode = AUTO_ZONE_COLLECT_FULL_COLLECTION; break; - case OBJC_EXHAUSTIVE_COLLECTION: amode = AUTO_ZONE_COLLECT_EXHAUSTIVE_COLLECTION; break; - } - amode |= AUTO_ZONE_COLLECT_COALESCE; - amode |= AUTO_ZONE_COLLECT_LOCAL_COLLECTION; - } - if (options & OBJC_WAIT_UNTIL_DONE) { - __block bool done = NO; - // If executing on the main thread, use the main thread work queue condition to block, - // so main thread finalization can complete. Otherwise, use a thread-local condition. - pthread_mutex_t localMutex = PTHREAD_MUTEX_INITIALIZER, *mutex = &localMutex; - pthread_cond_t localCondition = PTHREAD_COND_INITIALIZER, *condition = &localCondition; - if (onMainThread) { - mutex = &MainThreadWorkQ.mutex; - condition = &MainThreadWorkQ.condition; - } - pthread_mutex_lock(mutex); - auto_zone_collect_and_notify(gc_zone, amode, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - pthread_mutex_lock(mutex); - done = YES; - pthread_cond_signal(condition); - pthread_mutex_unlock(mutex); - }); - while (!done) { - pthread_cond_wait(condition, mutex); - if (onMainThread && MainThreadWorkQ.head) { - pthread_mutex_unlock(mutex); - batchFinalizeOnMainThread(); - pthread_mutex_lock(mutex); - } - } - pthread_mutex_unlock(mutex); - } else { - auto_zone_collect(gc_zone, amode); - } -} - - -// USED BY CF & ONE OTHER -BOOL objc_isAuto(id object) -{ - return UseGC && auto_zone_is_valid_pointer(gc_zone, object) != 0; -} - - -BOOL objc_collectingEnabled(void) -{ - return UseGC; -} - -BOOL objc_collecting_enabled(void) // Old naming -{ - return UseGC; -} - -malloc_zone_t *objc_collectableZone(void) { - return gc_zone; -} - -BOOL objc_dumpHeap(char *filenamebuffer, unsigned long length) { - static int counter = 0; - ++counter; - char buffer[1024]; - sprintf(buffer, OBJC_HEAP_DUMP_FILENAME_FORMAT, getpid(), counter); - if (!_objc_dumpHeap(gc_zone, buffer)) return NO; - if (filenamebuffer) { - unsigned long blen = strlen(buffer); - if (blen < length) - strncpy(filenamebuffer, buffer, blen+1); - else if (length > 0) - filenamebuffer[0] = 0; // give some answer - } - return YES; -} - - -/*********************************************************************** -* Memory management. -* Called by CF and Foundation. -**********************************************************************/ - -// Allocate an object in the GC zone, with the given number of extra bytes. -id objc_allocate_object(Class cls, int extra) -{ - return class_createInstance(cls, extra); -} - - -/*********************************************************************** -* Write barrier implementations, optimized for when GC is known to be on -* Called by the write barrier exports only. -* These implementations assume GC is on. The exported function must -* either perform the check itself or be conditionally stomped at -* startup time. -**********************************************************************/ - -id objc_assign_strongCast_gc(id value, id *slot) { - if (!auto_zone_set_write_barrier(gc_zone, (void*)slot, value)) { // stores & returns true if slot points into GC allocated memory - auto_zone_root_write_barrier(gc_zone, slot, value); // always stores - } - return value; -} - -id objc_assign_global_gc(id value, id *slot) { - // use explicit root registration. - if (value && auto_zone_is_valid_pointer(gc_zone, value)) { - if (auto_zone_is_finalized(gc_zone, value)) { - _objc_inform("GC: storing an already collected object %p into global memory at %p, break on objc_assign_global_error to debug\n", (void*)value, slot); - objc_assign_global_error(value, slot); - } - auto_zone_add_root(gc_zone, slot, value); - } - else - *slot = value; - - return value; -} - -id objc_assign_threadlocal_gc(id value, id *slot) -{ - if (value && auto_zone_is_valid_pointer(gc_zone, value)) { - auto_zone_add_root(gc_zone, slot, value); - } - else { - *slot = value; - } - - return value; -} - -id objc_assign_ivar_gc(id value, id base, ptrdiff_t offset) -{ - id *slot = (id*) ((char *)base + offset); - - if (value) { - if (!auto_zone_set_write_barrier(gc_zone, (char *)base + offset, value)) { - _objc_inform("GC: %p + %tu isn't in the auto_zone, break on objc_assign_ivar_error to debug.\n", (void*)base, offset); - objc_assign_ivar_error(base, offset); - } - } - else - *slot = value; - - return value; -} - -id objc_assign_strongCast_non_gc(id value, id *slot) { - return (*slot = value); -} - -id objc_assign_global_non_gc(id value, id *slot) { - return (*slot = value); -} - -id objc_assign_threadlocal_non_gc(id value, id *slot) { - return (*slot = value); -} - -id objc_assign_ivar_non_gc(id value, id base, ptrdiff_t offset) { - id *slot = (id*) ((char *)base + offset); - return (*slot = value); -} - - -/*********************************************************************** -* Non-trivial write barriers -**********************************************************************/ - -void *objc_memmove_collectable(void *dst, const void *src, size_t size) -{ - if (UseGC) { - return auto_zone_write_barrier_memmove(gc_zone, dst, src, size); - } else { - return memmove(dst, src, size); - } -} - -BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) { - const BOOL issueMemoryBarrier = NO; - if (UseGC) - return auto_zone_atomicCompareAndSwapPtr(gc_zone, (void *)predicate, (void *)replacement, (void * volatile *)objectLocation, issueMemoryBarrier); - else - return OSAtomicCompareAndSwapPtr((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); -} - -BOOL objc_atomicCompareAndSwapPtrBarrier(id predicate, id replacement, volatile id *objectLocation) { - const BOOL issueMemoryBarrier = YES; - if (UseGC) - return auto_zone_atomicCompareAndSwapPtr(gc_zone, (void *)predicate, (void *)replacement, (void * volatile *)objectLocation, issueMemoryBarrier); - else - return OSAtomicCompareAndSwapPtrBarrier((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); -} - -BOOL objc_atomicCompareAndSwapGlobal(id predicate, id replacement, volatile id *objectLocation) { - const BOOL isGlobal = YES; - const BOOL issueMemoryBarrier = NO; - if (UseGC) - return auto_zone_atomicCompareAndSwap(gc_zone, (void *)predicate, (void *)replacement, (void * volatile *)objectLocation, isGlobal, issueMemoryBarrier); - else - return OSAtomicCompareAndSwapPtr((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); -} - -BOOL objc_atomicCompareAndSwapGlobalBarrier(id predicate, id replacement, volatile id *objectLocation) { - const BOOL isGlobal = YES; - const BOOL issueMemoryBarrier = YES; - if (UseGC) - return auto_zone_atomicCompareAndSwap(gc_zone, (void *)predicate, (void *)replacement, (void * volatile *)objectLocation, isGlobal, issueMemoryBarrier); - else - return OSAtomicCompareAndSwapPtrBarrier((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); -} - -BOOL objc_atomicCompareAndSwapInstanceVariable(id predicate, id replacement, volatile id *objectLocation) { - const BOOL isGlobal = NO; - const BOOL issueMemoryBarrier = NO; - if (UseGC) - return auto_zone_atomicCompareAndSwap(gc_zone, (void *)predicate, (void *)replacement, (void * volatile *)objectLocation, isGlobal, issueMemoryBarrier); - else - return OSAtomicCompareAndSwapPtr((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); -} - -BOOL objc_atomicCompareAndSwapInstanceVariableBarrier(id predicate, id replacement, volatile id *objectLocation) { - const BOOL isGlobal = NO; - const BOOL issueMemoryBarrier = YES; - if (UseGC) - return auto_zone_atomicCompareAndSwap(gc_zone, (void *)predicate, (void *)replacement, (void * volatile *)objectLocation, isGlobal, issueMemoryBarrier); - else - return OSAtomicCompareAndSwapPtrBarrier((void *)predicate, (void *)replacement, (void * volatile *)objectLocation); -} - - -/*********************************************************************** -* Weak ivar support -**********************************************************************/ - -id objc_read_weak_gc(id *location) { - id result = *location; - if (result) { - result = (id)auto_read_weak_reference(gc_zone, (void **)location); - } - return result; -} - -id objc_read_weak_non_gc(id *location) { - return *location; -} - -id objc_assign_weak_gc(id value, id *location) { - auto_assign_weak_reference(gc_zone, value, (const void **)location, nil); - return value; -} - -id objc_assign_weak_non_gc(id value, id *location) { - return (*location = value); -} - - -void gc_fixup_weakreferences(id newObject, id oldObject) { - // fix up weak references if any. - const unsigned char *weakLayout = (const unsigned char *)class_getWeakIvarLayout(newObject->ISA()); - if (weakLayout) { - void **newPtr = (void **)newObject, **oldPtr = (void **)oldObject; - unsigned char byte; - while ((byte = *weakLayout++)) { - unsigned skips = (byte >> 4); - unsigned weaks = (byte & 0x0F); - newPtr += skips, oldPtr += skips; - while (weaks--) { - *newPtr = nil; - auto_assign_weak_reference(gc_zone, auto_read_weak_reference(gc_zone, oldPtr), (const void **)newPtr, nil); - ++newPtr, ++oldPtr; - } - } - } -} - - -/*********************************************************************** -* dyld resolver functions for basic GC write barriers -* dyld calls the resolver function to bind the symbol. -* We return the GC or non-GC variant as appropriate. -**********************************************************************/ - -#define GC_RESOLVER(name) \ - OBJC_EXPORT void *name##_resolver(void) __asm__("_" #name); \ - void *name##_resolver(void) \ - { \ - __asm__(".symbol_resolver _" #name); \ - if (UseGC) return (void*)name##_gc; \ - else return (void*)name##_non_gc; \ - } - -GC_RESOLVER(objc_assign_ivar) -GC_RESOLVER(objc_assign_strongCast) -GC_RESOLVER(objc_assign_global) -GC_RESOLVER(objc_assign_threadlocal) -GC_RESOLVER(objc_read_weak) -GC_RESOLVER(objc_assign_weak) -GC_RESOLVER(objc_getProperty) -GC_RESOLVER(objc_setProperty) -GC_RESOLVER(objc_getAssociatedObject) -GC_RESOLVER(objc_setAssociatedObject) -GC_RESOLVER(_object_addExternalReference) -GC_RESOLVER(_object_readExternalReference) -GC_RESOLVER(_object_removeExternalReference) - - -/*********************************************************************** -* Testing tools -* Used to isolate resurrection of garbage objects during finalization. -**********************************************************************/ -BOOL objc_is_finalized(void *ptr) { - if (ptr != nil && UseGC) { - return auto_zone_is_finalized(gc_zone, ptr); - } - return NO; -} - - -/*********************************************************************** -* Stack clearing. -* Used by top-level thread loops to reduce false pointers from the stack. -**********************************************************************/ -void objc_clear_stack(unsigned long options) { - if (!UseGC) return; - auto_zone_clear_stack(gc_zone, 0); -} - - -/*********************************************************************** -* Finalization support -**********************************************************************/ - -// Finalizer crash debugging -static void *finalizing_object; - -// finalize a single object without fuss -// When there are no main-thread-only classes this is used directly -// Otherwise, it is used indirectly by smarter code that knows main-thread-affinity requirements -static void finalizeOneObject(void *obj, void *ignored) { - id object = (id)obj; - finalizing_object = obj; - - Class cls = object->ISA(); - CRSetCrashLogMessage2(class_getName(cls)); - - /// call -finalize method. - ((void(*)(id, SEL))objc_msgSend)(object, @selector(finalize)); - - // Call C++ destructors. - // This would be objc_destructInstance() but for performance. - if (cls->hasCxxDtor()) { - object_cxxDestruct(object); - } - - finalizing_object = nil; - CRSetCrashLogMessage2(nil); -} - -// finalize object only if it is a main-thread-only object. -// Called only from the main thread. -static void finalizeOneMainThreadOnlyObject(void *obj, void *arg) { - id object = (id)obj; - Class cls = object->ISA(); - if (cls == nil) { - _objc_fatal("object with nil ISA passed to finalizeOneMainThreadOnlyObject: %p\n", obj); - } - if (cls->shouldFinalizeOnMainThread()) { - finalizeOneObject(obj, nil); - } -} - -// finalize one object only if it is not a main-thread-only object -// called from any other thread than the main thread -// Important: if a main-thread-only object is passed, return that fact in the needsMain argument -static void finalizeOneAnywhereObject(void *obj, void *needsMain) { - id object = (id)obj; - Class cls = object->ISA(); - bool *needsMainThreadWork = (bool *)needsMain; - if (cls == nil) { - _objc_fatal("object with nil ISA passed to finalizeOneAnywhereObject: %p\n", obj); - } - if (!cls->shouldFinalizeOnMainThread()) { - finalizeOneObject(obj, nil); - } - else { - *needsMainThreadWork = true; - } -} - - -// Utility workhorse. -// Set up the expensive @try block and ask the collector to hand the next object to -// our finalizeAnObject function. -// Track and return a boolean that records whether or not any main thread work is necessary. -// (When we know that there are no main thread only objects then the boolean isn't even computed) -static bool batchFinalize(auto_zone_t *zone, - auto_zone_foreach_object_t foreach, - auto_zone_cursor_t cursor, - size_t cursor_size, - void (*finalizeAnObject)(void *, void*)) -{ -#if DEBUG && !__OBJC2__ - // debug: don't call try/catch before exception handlers are installed - objc_exception_functions_t table = {}; - objc_exception_get_functions(&table); - assert(table.throw_exc); -#endif - - bool needsMainThreadWork = false; - for (;;) { - @try { - foreach(cursor, finalizeAnObject, &needsMainThreadWork); - // non-exceptional return means finalization is complete. - break; - } - @catch (id exception) { - // whoops, note exception, then restart at cursor's position - _objc_inform("GC: -finalize resulted in an exception (%p) being thrown, break on objc_exception_during_finalize_error to debug\n\t%s", exception, (const char*)[[exception description] UTF8String]); - objc_exception_during_finalize_error(); - } - @catch (...) { - // whoops, note exception, then restart at cursor's position - _objc_inform("GC: -finalize resulted in an exception being thrown, break on objc_exception_during_finalize_error to debug"); - objc_exception_during_finalize_error(); - } - } - return needsMainThreadWork; -} - -// Called on main thread-only. -// Pick up work from global queue. -// called parasitically by anyone requesting a collection -// called explicitly when there is known to be main thread only finalization work -// In both cases we are on the main thread -// Guard against recursion by something called from a finalizer -static void batchFinalizeOnMainThread() { - pthread_mutex_lock(&MainThreadWorkQ.mutex); - if (!MainThreadWorkQ.head || MainThreadWorkQ.head->started) { - // No work or we're already here - pthread_mutex_unlock(&MainThreadWorkQ.mutex); - return; - } - while (MainThreadWorkQ.head) { - BatchFinalizeBlock_t *bfb = MainThreadWorkQ.head; - bfb->started = YES; - pthread_mutex_unlock(&MainThreadWorkQ.mutex); - - batchFinalize(gc_zone, bfb->foreach, bfb->cursor, bfb->cursor_size, finalizeOneMainThreadOnlyObject); - // signal the collector thread(s) that finalization has finished. - pthread_mutex_lock(&MainThreadWorkQ.mutex); - bfb->finished = YES; - pthread_cond_broadcast(&MainThreadWorkQ.condition); - MainThreadWorkQ.head = bfb->next; - } - MainThreadWorkQ.tail = nil; - pthread_mutex_unlock(&MainThreadWorkQ.mutex); -} - - -// Knowing that we possibly have main thread only work to do, first process everything -// that is not main-thread-only. If we discover main thread only work, queue a work block -// to the main thread that will do just the main thread only work. Wait for it. -// Called from a non main thread. -static void batchFinalizeOnTwoThreads(auto_zone_t *zone, - auto_zone_foreach_object_t foreach, - auto_zone_cursor_t cursor, - size_t cursor_size) -{ - // First, lets get rid of everything we can on this thread, then ask main thread to help if needed - char cursor_copy[cursor_size]; - memcpy(cursor_copy, cursor, cursor_size); - bool needsMainThreadFinalization = batchFinalize(zone, foreach, (auto_zone_cursor_t)cursor_copy, cursor_size, finalizeOneAnywhereObject); - - if (! needsMainThreadFinalization) - return; // no help needed - - // set up the control block. Either our ping of main thread with _callOnMainThread will get to it, or - // an objc_collect(if_needed) will get to it. Either way, this block will be processed on the main thread. - BatchFinalizeBlock_t bfb; - bfb.foreach = foreach; - bfb.cursor = cursor; - bfb.cursor_size = cursor_size; - bfb.started = NO; - bfb.finished = NO; - bfb.next = nil; - pthread_mutex_lock(&MainThreadWorkQ.mutex); - if (MainThreadWorkQ.tail) { - - // link to end so that ordering of finalization is preserved. - MainThreadWorkQ.tail->next = &bfb; - MainThreadWorkQ.tail = &bfb; - } - else { - MainThreadWorkQ.head = &bfb; - MainThreadWorkQ.tail = &bfb; - } - pthread_mutex_unlock(&MainThreadWorkQ.mutex); - - //printf("----->asking main thread to finalize\n"); - dispatch_async(dispatch_get_main_queue(), ^{ batchFinalizeOnMainThread(); }); - - // wait for the main thread to finish finalizing instances of classes marked CLS_FINALIZE_ON_MAIN_THREAD. - pthread_mutex_lock(&MainThreadWorkQ.mutex); - while (!bfb.finished) { - // the main thread might be blocked waiting for a synchronous collection to complete, so wake it here - pthread_cond_signal(&MainThreadWorkQ.condition); - pthread_cond_wait(&MainThreadWorkQ.condition, &MainThreadWorkQ.mutex); - } - pthread_mutex_unlock(&MainThreadWorkQ.mutex); - //printf("<------ main thread finalize done\n"); - -} - - - -// collector calls this with garbage ready -// thread collectors, too, so this needs to be thread-safe -static void BatchInvalidate(auto_zone_t *zone, - auto_zone_foreach_object_t foreach, - auto_zone_cursor_t cursor, - size_t cursor_size) -{ - if (pthread_main_np() || !WantsMainThreadFinalization) { - // Collect all objects. We're either pre-multithreaded on main thread or we're on the collector thread - // but no main-thread-only objects have been allocated. - batchFinalize(zone, foreach, cursor, cursor_size, finalizeOneObject); - } - else { - // We're on the dedicated thread. Collect some on main thread, the rest here. - batchFinalizeOnTwoThreads(zone, foreach, cursor, cursor_size); - } - -} - - -/* - * Zombie support - * Collector calls into this system when it finds resurrected objects. - * This keeps them pitifully alive and leaked, even if they reference garbage. - */ - -// idea: keep a side table mapping resurrected object pointers to their original Class, so we don't -// need to smash anything. alternatively, could use associative references to track against a secondary -// object with information about the resurrection, such as a stack crawl, etc. - -static Class _NSResurrectedObjectClass; -static NXMapTable *_NSResurrectedObjectMap = nil; -static pthread_mutex_t _NSResurrectedObjectLock = PTHREAD_MUTEX_INITIALIZER; - -static Class resurrectedObjectOriginalClass(id object) { - Class originalClass; - pthread_mutex_lock(&_NSResurrectedObjectLock); - originalClass = (Class) NXMapGet(_NSResurrectedObjectMap, object); - pthread_mutex_unlock(&_NSResurrectedObjectLock); - return originalClass; -} - -static id _NSResurrectedObject_classMethod(id self, SEL selector) { return self; } - -static id _NSResurrectedObject_instanceMethod(id self, SEL name) { - _objc_inform("**resurrected** object %p of class %s being sent message '%s'\n", (void*)self, class_getName(resurrectedObjectOriginalClass(self)), sel_getName(name)); - return self; -} - -static void _NSResurrectedObject_finalize(id self, SEL _cmd) { - Class originalClass; - pthread_mutex_lock(&_NSResurrectedObjectLock); - originalClass = (Class) NXMapRemove(_NSResurrectedObjectMap, self); - pthread_mutex_unlock(&_NSResurrectedObjectLock); - if (originalClass) _objc_inform("**resurrected** object %p of class %s being finalized\n", (void*)self, class_getName(originalClass)); - _objc_rootFinalize(self); -} - -static bool _NSResurrectedObject_resolveInstanceMethod(id self, SEL _cmd, SEL name) { - class_addMethod((Class)self, name, (IMP)_NSResurrectedObject_instanceMethod, "@@:"); - return YES; -} - -static bool _NSResurrectedObject_resolveClassMethod(id self, SEL _cmd, SEL name) { - class_addMethod(self->ISA(), name, (IMP)_NSResurrectedObject_classMethod, "@@:"); - return YES; -} - -static void _NSResurrectedObject_initialize() { - _NSResurrectedObjectMap = NXCreateMapTable(NXPtrValueMapPrototype, 128); - _NSResurrectedObjectClass = objc_allocateClassPair(objc_getClass("NSObject"), "_NSResurrectedObject", 0); - class_addMethod(_NSResurrectedObjectClass, @selector(finalize), (IMP)_NSResurrectedObject_finalize, "v@:"); - Class metaClass = _NSResurrectedObjectClass->ISA(); - class_addMethod(metaClass, @selector(resolveInstanceMethod:), (IMP)_NSResurrectedObject_resolveInstanceMethod, "c@::"); - class_addMethod(metaClass, @selector(resolveClassMethod:), (IMP)_NSResurrectedObject_resolveClassMethod, "c@::"); - objc_registerClassPair(_NSResurrectedObjectClass); -} - -static void resurrectZombie(auto_zone_t *zone, void *ptr) { - id object = (id) ptr; - Class cls = object->ISA(); - if (cls != _NSResurrectedObjectClass) { - // remember the original class for this instance. - pthread_mutex_lock(&_NSResurrectedObjectLock); - NXMapInsert(_NSResurrectedObjectMap, ptr, cls); - pthread_mutex_unlock(&_NSResurrectedObjectLock); - object_setClass(object, _NSResurrectedObjectClass); - } -} - -/*********************************************************************** -* Pretty printing support -* For development purposes. -**********************************************************************/ - - -static char *name_for_address(auto_zone_t *zone, vm_address_t base, vm_address_t offset, int withRetainCount); - -static char* objc_name_for_address(auto_zone_t *zone, vm_address_t base, vm_address_t offset) -{ - return name_for_address(zone, base, offset, false); -} - -static const char* objc_name_for_object(auto_zone_t *zone, void *object) { - Class cls = *(Class *)object; - if (!objc_isRegisteredClass(cls)) return ""; - return class_getName(cls); -} - -/*********************************************************************** -* Collection support -**********************************************************************/ - -static bool objc_isRegisteredClass(Class candidate); - -static const unsigned char *objc_layout_for_address(auto_zone_t *zone, void *address) { - id object = (id)address; - volatile void *clsptr = (void*)object->ISA(); - Class cls = (Class)clsptr; - return objc_isRegisteredClass(cls) ? _object_getIvarLayout(cls, object) : nil; -} - -static const unsigned char *objc_weak_layout_for_address(auto_zone_t *zone, void *address) { - id object = (id)address; - volatile void *clsptr = (void*)object->ISA(); - Class cls = (Class)clsptr; - return objc_isRegisteredClass(cls) ? class_getWeakIvarLayout(cls) : nil; -} - -void gc_register_datasegment(uintptr_t base, size_t size) { - auto_zone_register_datasegment(gc_zone, (void*)base, size); -} - -void gc_unregister_datasegment(uintptr_t base, size_t size) { - auto_zone_unregister_datasegment(gc_zone, (void*)base, size); -} - - -/*********************************************************************** -* Initialization -**********************************************************************/ - -static void objc_will_grow(auto_zone_t *zone, auto_heap_growth_info_t info) { - if (auto_zone_is_collecting(gc_zone)) { - ; - } - else { - auto_zone_collect(gc_zone, AUTO_ZONE_COLLECT_COALESCE|AUTO_ZONE_COLLECT_RATIO_COLLECTION); - } -} - - -static auto_zone_t *gc_zone_init(void) -{ - auto_zone_t *result; - static int didOnce = 0; - if (!didOnce) { - didOnce = 1; - - // initialize the batch finalization queue - MainThreadWorkQ.head = nil; - MainThreadWorkQ.tail = nil; - pthread_mutex_init(&MainThreadWorkQ.mutex, nil); - pthread_cond_init(&MainThreadWorkQ.condition, nil); - } - - result = auto_zone_create("auto_zone"); - - auto_zone_disable_compaction(result); - - auto_collection_control_t *control = auto_collection_parameters(result); - - // set up the magic control parameters - control->batch_invalidate = BatchInvalidate; - control->will_grow = objc_will_grow; - control->resurrect = resurrectZombie; - control->layout_for_address = objc_layout_for_address; - control->weak_layout_for_address = objc_weak_layout_for_address; - control->name_for_address = objc_name_for_address; - - if (control->version >= sizeof(auto_collection_control_t)) { - control->name_for_object = objc_name_for_object; - } - - return result; -} - - -/* should be defined in /usr/local/include/libdispatch_private.h. */ -extern void (*dispatch_begin_thread_4GC)(void); -extern void (*dispatch_end_thread_4GC)(void); - -static void objc_reapThreadLocalBlocks() -{ - if (UseGC) auto_zone_reap_all_local_blocks(gc_zone); -} - -void objc_registerThreadWithCollector() -{ - if (UseGC) auto_zone_register_thread(gc_zone); -} - -void objc_unregisterThreadWithCollector() -{ - if (UseGC) auto_zone_unregister_thread(gc_zone); -} - -void objc_assertRegisteredThreadWithCollector() -{ - if (UseGC) auto_zone_assert_thread_registered(gc_zone); -} - -// Always called by _objcInit, even if GC is off. -void gc_init(bool wantsGC) -{ - assert(UseGC == -1); - UseGC = wantsGC; - - if (PrintGC) { - _objc_inform("GC: is %s", wantsGC ? "ON" : "OFF"); - } - - if (UseGC) { - // Set up the GC zone - gc_zone = gc_zone_init(); - - // tell libdispatch to register its threads with the GC. - dispatch_begin_thread_4GC = objc_registerThreadWithCollector; - dispatch_end_thread_4GC = objc_reapThreadLocalBlocks; - - // set up the registered classes list - registeredClassTableInit(); - - // tell Blocks to use collectable memory. CF will cook up the classes separately. - gc_block_init(); - - // Add GC state to crash log reports - _objc_inform_on_crash("garbage collection is ON"); - } -} - - -// Called by NSObject +load to perform late GC setup -// This work must wait until after all of libSystem initializes. -void gc_init2(void) -{ - assert(UseGC); - - // create the _NSResurrectedObject class used to track resurrections. - _NSResurrectedObject_initialize(); - - // tell libauto to set up its dispatch queues - auto_collect_multithreaded(gc_zone); -} - -// Called by Foundation. -// This function used to initialize NSObject stuff, but now does nothing. -malloc_zone_t *objc_collect_init(int (*callback)(void) __unused) -{ - return (malloc_zone_t *)gc_zone; -} - -/* - * Support routines for the Block implementation - */ - - -// The Block runtime now needs to sometimes allocate a Block that is an Object - namely -// when it neesd to have a finalizer which, for now, is only if there are C++ destructors -// in the helper function. Hence the isObject parameter. -// Under GC a -copy message should allocate a refcount 0 block, ergo the isOne parameter. -static void *block_gc_alloc5(const unsigned long size, const bool isOne, const bool isObject) { - auto_memory_type_t type = isObject ? (AUTO_OBJECT|AUTO_MEMORY_SCANNED) : AUTO_MEMORY_SCANNED; - return auto_zone_allocate_object(gc_zone, size, type, isOne, false); -} - -// The Blocks runtime keeps track of everything above 1 and so it only calls -// up to the collector to tell it about the 0->1 transition and then the 1->0 transition -static void block_gc_setHasRefcount(const void *block, const bool hasRefcount) { - if (hasRefcount) - auto_zone_retain(gc_zone, (void *)block); - else - auto_zone_release(gc_zone, (void *)block); -} - -static void block_gc_memmove(void *dst, void *src, unsigned long size) { - auto_zone_write_barrier_memmove(gc_zone, dst, src, (size_t)size); -} - -static void gc_block_init(void) { - _Block_use_GC( - block_gc_alloc5, - block_gc_setHasRefcount, - (void (*)(void *, void **))objc_assign_strongCast_gc, - (void (*)(const void *, void *))objc_assign_weak, - block_gc_memmove - ); -} - - -/*********************************************************************** -* Track classes. -* In addition to the global class hashtable (set) indexed by name, we -* also keep one based purely by pointer when running under Garbage Collection. -* This allows the background collector to race against objects recycled from TLC. -* Specifically, the background collector can read the admin byte and see that -* a thread local object is an object, get scheduled out, and the TLC recovers it, -* linking it into the cache, then the background collector reads the isa field and -* finds linkage info. By qualifying all isa fields read we avoid this. -**********************************************************************/ - -// This is a self-contained hash table of all classes. The first two elements contain the (size-1) and count. -static volatile Class *AllClasses = nil; - -#define SHIFT 3 -#define INITIALSIZE 512 -#define REMOVED ~0ul - -// Allocate the side table. -static void registeredClassTableInit() { - assert(UseGC); - // allocate a collectable (refcount 0) zeroed hunk of unscanned memory - uintptr_t *table = (uintptr_t *)auto_zone_allocate_object(gc_zone, INITIALSIZE*sizeof(void *), AUTO_MEMORY_UNSCANNED, true, true); - // set initial capacity (as mask) - table[0] = INITIALSIZE - 1; - // set initial count - table[1] = 0; - AllClasses = (Class *)table; -} - -// Verify that a particular pointer is to a class. -// Safe from any thread anytime -static bool objc_isRegisteredClass(Class candidate) { - assert(UseGC); - // nil is never a valid ISA. - if (candidate == nil) return NO; - // We don't care about a race with another thread adding a class to which we randomly might have a pointer - // Get local copy of classes so that we're immune from updates. - // We keep the size of the list as the first element so there is no race as the list & size get updated. - uintptr_t *allClasses = (uintptr_t *)AllClasses; - // Slot 0 is always the size of the list in log 2 masked terms (e.g. size - 1) where size is always power of 2 - // Slot 1 is count - uintptr_t slot = (((uintptr_t)candidate) >> SHIFT) & allClasses[0]; - // avoid slot 0 and 1 - if (slot < 2) slot = 2; - for(;;) { - long int slotValue = allClasses[slot]; - if (slotValue == (long int)candidate) { - return YES; - } - if (slotValue == 0) { - return NO; - } - ++slot; - if (slot > allClasses[0]) - slot = 2; // skip size, count - } -} - -// Utility used when growing -// Assumes lock held -static void addClassHelper(uintptr_t *table, uintptr_t candidate) { - uintptr_t slot = (((long int)candidate) >> SHIFT) & table[0]; - if (slot < 2) slot = 2; - for(;;) { - uintptr_t slotValue = table[slot]; - if (slotValue == 0) { - table[slot] = candidate; - ++table[1]; - return; - } - ++slot; - if (slot > table[0]) - slot = 2; // skip size, count - } -} - -// lock held by callers -void objc_addRegisteredClass(Class candidate) { - if (!UseGC) return; - uintptr_t *table = (uintptr_t *)AllClasses; - // Slot 0 is always the size of the list in log 2 masked terms (e.g. size - 1) where size is always power of 2 - // Slot 1 is count - always non-zero - uintptr_t slot = (((long int)candidate) >> SHIFT) & table[0]; - if (slot < 2) slot = 2; - for(;;) { - uintptr_t slotValue = table[slot]; - assert(slotValue != (uintptr_t)candidate); - if (slotValue == REMOVED) { - table[slot] = (long)candidate; - return; - } - else if (slotValue == 0) { - table[slot] = (long)candidate; - if (2*++table[1] > table[0]) { // add to count; check if we cross 50% utilization - // grow - uintptr_t oldSize = table[0]+1; - uintptr_t *newTable = (uintptr_t *)auto_zone_allocate_object(gc_zone, oldSize*2*sizeof(void *), AUTO_MEMORY_UNSCANNED, true, true); - uintptr_t i; - newTable[0] = 2*oldSize - 1; - newTable[1] = 0; - for (i = 2; i < oldSize; ++i) { - if (table[i] && table[i] != REMOVED) - addClassHelper(newTable, table[i]); - } - AllClasses = (Class *)newTable; - // let the old table be collected when other threads are no longer reading it. - auto_zone_release(gc_zone, (void *)table); - } - return; - } - ++slot; - if (slot > table[0]) - slot = 2; // skip size, count - } -} - -// lock held by callers -void objc_removeRegisteredClass(Class candidate) { - if (!UseGC) return; - uintptr_t *table = (uintptr_t *)AllClasses; - // Slot 0 is always the size of the list in log 2 masked terms (e.g. size - 1) where size is always power of 2 - // Slot 1 is count - always non-zero - uintptr_t slot = (((uintptr_t)candidate) >> SHIFT) & table[0]; - if (slot < 2) slot = 2; - for(;;) { - uintptr_t slotValue = table[slot]; - if (slotValue == (uintptr_t)candidate) { - table[slot] = REMOVED; // if next slot == 0 we could set to 0 here and decr count - return; - } - assert(slotValue != 0); - ++slot; - if (slot > table[0]) - slot = 2; // skip size, count - } -} - - -/*********************************************************************** -* Debugging - support for smart printouts when errors occur -**********************************************************************/ - - -static malloc_zone_t *objc_debug_zone(void) -{ - static malloc_zone_t *z = nil; - if (!z) { - z = malloc_create_zone(PAGE_MAX_SIZE, 0); - malloc_set_zone_name(z, "objc-auto debug"); - } - return z; -} - -static char *_malloc_append_unsigned(uintptr_t value, unsigned base, char *head) { - if (!value) { - head[0] = '0'; - } else { - if (value >= base) head = _malloc_append_unsigned(value / base, base, head); - value = value % base; - head[0] = (value < 10) ? '0' + value : 'a' + value - 10; - } - return head+1; -} - -static void strlcati(char *str, uintptr_t value, size_t bufSize) -{ - if ( (bufSize - strlen(str)) < 30) - return; - str = _malloc_append_unsigned(value, 10, str + strlen(str)); - str[0] = '\0'; -} - - -static Ivar ivar_for_offset(Class cls, vm_address_t offset) -{ - unsigned i; - vm_address_t ivar_offset; - Ivar super_ivar, result; - Ivar *ivars; - unsigned int ivar_count; - - if (!cls) return nil; - - // scan base classes FIRST - super_ivar = ivar_for_offset(cls->superclass, offset); - // result is best-effort; our ivars may be closer - - ivars = class_copyIvarList(cls, &ivar_count); - if (ivars && ivar_count) { - // Try our first ivar. If it's too big, use super's best ivar. - // (lose 64-bit precision) - ivar_offset = ivar_getOffset(ivars[0]); - if (ivar_offset > offset) result = super_ivar; - else if (ivar_offset == offset) result = ivars[0]; - else result = nil; - - // Try our other ivars. If any is too big, use the previous. - for (i = 1; result == nil && i < ivar_count; i++) { - ivar_offset = ivar_getOffset(ivars[i]); - if (ivar_offset == offset) { - result = ivars[i]; - } else if (ivar_offset > offset) { - result = ivars[i - 1]; - } - } - - // Found nothing. Return our last ivar. - if (result == nil) - result = ivars[ivar_count - 1]; - - free(ivars); - } else { - result = super_ivar; - } - - return result; -} - -static void append_ivar_at_offset(char *buf, Class cls, vm_address_t offset, size_t bufSize) -{ - Ivar ivar = nil; - - if (offset == 0) return; // don't bother with isa - if (offset >= class_getInstanceSize(cls)) { - strlcat(buf, ".<extra>+", bufSize); - strlcati(buf, offset, bufSize); - return; - } - - ivar = ivar_for_offset(cls, offset); - if (!ivar) { - strlcat(buf, ".<?>", bufSize); - return; - } - - // fixme doesn't handle structs etc. - - strlcat(buf, ".", bufSize); - const char *ivar_name = ivar_getName(ivar); - if (ivar_name) strlcat(buf, ivar_name, bufSize); - else strlcat(buf, "<anonymous ivar>", bufSize); - - offset -= ivar_getOffset(ivar); - if (offset > 0) { - strlcat(buf, "+", bufSize); - strlcati(buf, offset, bufSize); - } -} - - -static const char *cf_class_for_object(void *cfobj) -{ - // ick - we don't link against CF anymore - - struct fake_cfclass { - size_t version; - const char *className; - // don't care about the rest - }; - - const char *result; - void *dlh; - size_t (*CFGetTypeID)(void *); - fake_cfclass * (*_CFRuntimeGetClassWithTypeID)(size_t); - - result = "anonymous_NSCFType"; - - dlh = dlopen("/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation", RTLD_LAZY | RTLD_NOLOAD | RTLD_FIRST); - if (!dlh) return result; - - CFGetTypeID = (size_t(*)(void*)) dlsym(dlh, "CFGetTypeID"); - _CFRuntimeGetClassWithTypeID = (fake_cfclass*(*)(size_t)) dlsym(dlh, "_CFRuntimeGetClassWithTypeID"); - - if (CFGetTypeID && _CFRuntimeGetClassWithTypeID) { - size_t cfid = (*CFGetTypeID)(cfobj); - result = (*_CFRuntimeGetClassWithTypeID)(cfid)->className; - } - - dlclose(dlh); - return result; -} - - -static char *name_for_address(auto_zone_t *zone, vm_address_t base, vm_address_t offset, int withRetainCount) -{ -#define APPEND_SIZE(s) \ - strlcat(buf, "[", sizeof(buf)); \ - strlcati(buf, s, sizeof(buf)); \ - strlcat(buf, "]", sizeof(buf)); - - char buf[1500]; - char *result; - - buf[0] = '\0'; - - size_t size = - auto_zone_size(zone, (void *)base); - auto_memory_type_t type = size ? - auto_zone_get_layout_type(zone, (void *)base) : AUTO_TYPE_UNKNOWN; - unsigned int refcount = size ? - auto_zone_retain_count(zone, (void *)base) : 0; - - switch (type) { - case AUTO_OBJECT_SCANNED: - case AUTO_OBJECT_UNSCANNED: - case AUTO_OBJECT_ALL_POINTERS: { - const char *class_name = object_getClassName((id)base); - if ((0 == strcmp(class_name, "__NSCFType")) || (0 == strcmp(class_name, "NSCFType"))) { - strlcat(buf, cf_class_for_object((void *)base), sizeof(buf)); - } else { - strlcat(buf, class_name, sizeof(buf)); - } - if (offset) { - append_ivar_at_offset(buf, ((id)base)->ISA(), offset, sizeof(buf)); - } - APPEND_SIZE(size); - break; - } - case AUTO_MEMORY_SCANNED: - strlcat(buf, "{conservative-block}", sizeof(buf)); - APPEND_SIZE(size); - break; - case AUTO_MEMORY_UNSCANNED: - strlcat(buf, "{no-pointers-block}", sizeof(buf)); - APPEND_SIZE(size); - break; - case AUTO_MEMORY_ALL_POINTERS: - strlcat(buf, "{all-pointers-block}", sizeof(buf)); - APPEND_SIZE(size); - break; - case AUTO_MEMORY_ALL_WEAK_POINTERS: - strlcat(buf, "{all-weak-pointers-block}", sizeof(buf)); - APPEND_SIZE(size); - break; - case AUTO_TYPE_UNKNOWN: - strlcat(buf, "{uncollectable-memory}", sizeof(buf)); - break; - default: - strlcat(buf, "{unknown-memory-type}", sizeof(buf)); - } - - if (withRetainCount && refcount > 0) { - strlcat(buf, " [[refcount=", sizeof(buf)); - strlcati(buf, refcount, sizeof(buf)); - strlcat(buf, "]]", sizeof(buf)); - } - - size_t len = 1 + strlen(buf); - result = (char *)malloc_zone_malloc(objc_debug_zone(), len); - memcpy(result, buf, len); - return result; - -#undef APPEND_SIZE -} - - -// not OBJC_NO_GC -#endif diff --git a/objc/objc-runtime/runtime/objc-block-trampolines.mm b/objc/objc-runtime/runtime/objc-block-trampolines.mm deleted file mode 100644 index ccde02a..0000000 --- a/objc/objc-runtime/runtime/objc-block-trampolines.mm +++ /dev/null @@ -1,477 +0,0 @@ -/* - * Copyright (c) 2010 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@ - */ -/*********************************************************************** - * objc-block-trampolines.m - * Author: b.bum - * - **********************************************************************/ - -/*********************************************************************** - * Imports. - **********************************************************************/ -#include "objc-private.h" -#include "runtime.h" - -#include <Block.h> -#include <Block_private.h> -#include <mach/mach.h> - -// symbols defined in assembly files -// Don't use the symbols directly; they're thumb-biased on some ARM archs. -#define TRAMP(tramp) \ - static inline __unused uintptr_t tramp(void) { \ - extern void *_##tramp; \ - return ((uintptr_t)&_##tramp) & ~1UL; \ - } -// Scalar return -TRAMP(a1a2_tramphead); // trampoline header code -TRAMP(a1a2_firsttramp); // first trampoline -TRAMP(a1a2_trampend); // after the last trampoline - -#if SUPPORT_STRET -// Struct return -TRAMP(a2a3_tramphead); -TRAMP(a2a3_firsttramp); -TRAMP(a2a3_trampend); -#endif - -// argument mode identifier -typedef enum { - ReturnValueInRegisterArgumentMode, -#if SUPPORT_STRET - ReturnValueOnStackArgumentMode, -#endif - - ArgumentModeCount -} ArgumentMode; - - -// We must take care with our data layout on architectures that support -// multiple page sizes. -// -// The trampoline template in __TEXT is sized and aligned with PAGE_MAX_SIZE. -// On some platforms this requires additional linker flags. -// -// When we allocate a page pair, we use PAGE_MAX_SIZE size. -// This allows trampoline code to find its data by subtracting PAGE_MAX_SIZE. -// -// When we allocate a page pair, we use the process's page alignment. -// This simplifies allocation because we don't need to force greater than -// default alignment when running with small pages, but it also means -// the trampoline code MUST NOT look for its data by masking with PAGE_MAX_MASK. - -struct TrampolineBlockPagePair -{ - TrampolineBlockPagePair *nextPagePair; // linked list of all pages - TrampolineBlockPagePair *nextAvailablePage; // linked list of pages with available slots - - uintptr_t nextAvailable; // index of next available slot, endIndex() if no more available - - // Payload data: block pointers and free list. - // Bytes parallel with trampoline header code are the fields above or unused - // uint8_t blocks[ PAGE_MAX_SIZE - sizeof(TrampolineBlockPagePair) ] - - // Code: trampoline header followed by trampolines. - // uint8_t trampolines[PAGE_MAX_SIZE]; - - // Per-trampoline block data format: - // initial value is 0 while page data is filled sequentially - // when filled, value is reference to Block_copy()d block - // when empty, value is index of next available slot OR 0 if never used yet - - union Payload { - id block; - uintptr_t nextAvailable; // free list - }; - - static uintptr_t headerSize() { - return (uintptr_t) (a1a2_firsttramp() - a1a2_tramphead()); - } - - static uintptr_t slotSize() { - return 8; - } - - static uintptr_t startIndex() { - // headerSize is assumed to be slot-aligned - return headerSize() / slotSize(); - } - - static uintptr_t endIndex() { - return (uintptr_t)PAGE_MAX_SIZE / slotSize(); - } - - static bool validIndex(uintptr_t index) { - return (index >= startIndex() && index < endIndex()); - } - - Payload *payload(uintptr_t index) { - assert(validIndex(index)); - return (Payload *)((char *)this + index*slotSize()); - } - - IMP trampoline(uintptr_t index) { - assert(validIndex(index)); - char *imp = (char *)this + index*slotSize() + PAGE_MAX_SIZE; -#if __arm__ - imp++; // trampoline is Thumb instructions -#endif - return (IMP)imp; - } - - uintptr_t indexForTrampoline(IMP tramp) { - uintptr_t tramp0 = (uintptr_t)this + PAGE_MAX_SIZE; - uintptr_t start = tramp0 + headerSize(); - uintptr_t end = tramp0 + PAGE_MAX_SIZE; - uintptr_t address = (uintptr_t)tramp; - if (address >= start && address < end) { - return (uintptr_t)(address - tramp0) / slotSize(); - } - return 0; - } - - static void check() { - assert(TrampolineBlockPagePair::slotSize() == 8); - assert(TrampolineBlockPagePair::headerSize() >= sizeof(TrampolineBlockPagePair)); - assert(TrampolineBlockPagePair::headerSize() % TrampolineBlockPagePair::slotSize() == 0); - - // _objc_inform("%p %p %p", a1a2_tramphead(), a1a2_firsttramp(), - // a1a2_trampend()); - assert(a1a2_tramphead() % PAGE_SIZE == 0); // not PAGE_MAX_SIZE - assert(a1a2_tramphead() + PAGE_MAX_SIZE == a1a2_trampend()); -#if SUPPORT_STRET - // _objc_inform("%p %p %p", a2a3_tramphead(), a2a3_firsttramp(), - // a2a3_trampend()); - assert(a2a3_tramphead() % PAGE_SIZE == 0); // not PAGE_MAX_SIZE - assert(a2a3_tramphead() + PAGE_MAX_SIZE == a2a3_trampend()); -#endif - -#if __arm__ - // make sure trampolines are Thumb - extern void *_a1a2_firsttramp; - extern void *_a2a3_firsttramp; - assert(((uintptr_t)&_a1a2_firsttramp) % 2 == 1); - assert(((uintptr_t)&_a2a3_firsttramp) % 2 == 1); -#endif - } - -}; - -// two sets of trampoline pages; one for stack returns and one for register returns -static TrampolineBlockPagePair *headPagePairs[ArgumentModeCount]; - -#pragma mark Utility Functions - -static inline void _lock() { -#if __OBJC2__ - runtimeLock.write(); -#else - classLock.lock(); -#endif -} - -static inline void _unlock() { -#if __OBJC2__ - runtimeLock.unlockWrite(); -#else - classLock.unlock(); -#endif -} - -static inline void _assert_locked() { -#if __OBJC2__ - runtimeLock.assertWriting(); -#else - classLock.assertLocked(); -#endif -} - -#pragma mark Trampoline Management Functions -static TrampolineBlockPagePair *_allocateTrampolinesAndData(ArgumentMode aMode) -{ - _assert_locked(); - - vm_address_t dataAddress; - - TrampolineBlockPagePair::check(); - - TrampolineBlockPagePair *headPagePair = headPagePairs[aMode]; - - if (headPagePair) { - assert(headPagePair->nextAvailablePage == nil); - } - - kern_return_t result; - for (int i = 0; i < 5; i++) { - result = vm_allocate(mach_task_self(), &dataAddress, - PAGE_MAX_SIZE * 2, - TRUE | VM_MAKE_TAG(VM_MEMORY_FOUNDATION)); - if (result != KERN_SUCCESS) { - mach_error("vm_allocate failed", result); - return nil; - } - - vm_address_t codeAddress = dataAddress + PAGE_MAX_SIZE; - result = vm_deallocate(mach_task_self(), codeAddress, PAGE_MAX_SIZE); - if (result != KERN_SUCCESS) { - mach_error("vm_deallocate failed", result); - return nil; - } - - uintptr_t codePage; - switch(aMode) { - case ReturnValueInRegisterArgumentMode: - codePage = a1a2_tramphead(); - break; -#if SUPPORT_STRET - case ReturnValueOnStackArgumentMode: - codePage = a2a3_tramphead(); - break; -#endif - default: - _objc_fatal("unknown return mode %d", (int)aMode); - break; - } - vm_prot_t currentProtection, maxProtection; - result = vm_remap(mach_task_self(), &codeAddress, PAGE_MAX_SIZE, - 0, FALSE, mach_task_self(), codePage, TRUE, - ¤tProtection, &maxProtection, VM_INHERIT_SHARE); - if (result != KERN_SUCCESS) { - result = vm_deallocate(mach_task_self(), - dataAddress, PAGE_MAX_SIZE); - if (result != KERN_SUCCESS) { - mach_error("vm_deallocate for retry failed.", result); - return nil; - } - } else { - break; - } - } - - if (result != KERN_SUCCESS) { - return nil; - } - - TrampolineBlockPagePair *pagePair = (TrampolineBlockPagePair *) dataAddress; - pagePair->nextAvailable = pagePair->startIndex(); - pagePair->nextPagePair = nil; - pagePair->nextAvailablePage = nil; - - if (headPagePair) { - TrampolineBlockPagePair *lastPagePair = headPagePair; - while(lastPagePair->nextPagePair) - lastPagePair = lastPagePair->nextPagePair; - - lastPagePair->nextPagePair = pagePair; - headPagePairs[aMode]->nextAvailablePage = pagePair; - } else { - headPagePairs[aMode] = pagePair; - } - - return pagePair; -} - -static TrampolineBlockPagePair * -_getOrAllocatePagePairWithNextAvailable(ArgumentMode aMode) -{ - _assert_locked(); - - TrampolineBlockPagePair *headPagePair = headPagePairs[aMode]; - - if (!headPagePair) - return _allocateTrampolinesAndData(aMode); - - // make sure head page is filled first - if (headPagePair->nextAvailable != headPagePair->endIndex()) - return headPagePair; - - if (headPagePair->nextAvailablePage) // check if there is a page w/a hole - return headPagePair->nextAvailablePage; - - return _allocateTrampolinesAndData(aMode); // tack on a new one -} - -static TrampolineBlockPagePair * -_pageAndIndexContainingIMP(IMP anImp, uintptr_t *outIndex, - TrampolineBlockPagePair **outHeadPagePair) -{ - _assert_locked(); - - for (int arg = 0; arg < ArgumentModeCount; arg++) { - for (TrampolineBlockPagePair *pagePair = headPagePairs[arg]; - pagePair; - pagePair = pagePair->nextPagePair) - { - uintptr_t index = pagePair->indexForTrampoline(anImp); - if (index) { - if (outIndex) *outIndex = index; - if (outHeadPagePair) *outHeadPagePair = headPagePairs[arg]; - return pagePair; - } - } - } - - return nil; -} - - -static ArgumentMode -_argumentModeForBlock(id block) -{ - ArgumentMode aMode = ReturnValueInRegisterArgumentMode; - -#if SUPPORT_STRET - if (_Block_has_signature(block) && _Block_use_stret(block)) - aMode = ReturnValueOnStackArgumentMode; -#else - assert(! (_Block_has_signature(block) && _Block_use_stret(block))); -#endif - - return aMode; -} - - -// `block` must already have been copied -IMP -_imp_implementationWithBlockNoCopy(id block) -{ - _assert_locked(); - - ArgumentMode aMode = _argumentModeForBlock(block); - - TrampolineBlockPagePair *pagePair = - _getOrAllocatePagePairWithNextAvailable(aMode); - if (!headPagePairs[aMode]) - headPagePairs[aMode] = pagePair; - - uintptr_t index = pagePair->nextAvailable; - assert(index >= pagePair->startIndex() && index < pagePair->endIndex()); - TrampolineBlockPagePair::Payload *payload = pagePair->payload(index); - - uintptr_t nextAvailableIndex = payload->nextAvailable; - if (nextAvailableIndex == 0) { - // First time through (unused slots are zero). Fill sequentially. - // If the page is now full this will now be endIndex(), handled below. - nextAvailableIndex = index + 1; - } - pagePair->nextAvailable = nextAvailableIndex; - if (nextAvailableIndex == pagePair->endIndex()) { - // PagePair is now full (free list or wilderness exhausted) - // Remove from available page linked list - TrampolineBlockPagePair *iterator = headPagePairs[aMode]; - while(iterator && (iterator->nextAvailablePage != pagePair)) { - iterator = iterator->nextAvailablePage; - } - if (iterator) { - iterator->nextAvailablePage = pagePair->nextAvailablePage; - pagePair->nextAvailablePage = nil; - } - } - - payload->block = block; - return pagePair->trampoline(index); -} - - -#pragma mark Public API -IMP imp_implementationWithBlock(id block) -{ - block = Block_copy(block); - _lock(); - IMP returnIMP = _imp_implementationWithBlockNoCopy(block); - _unlock(); - return returnIMP; -} - - -id imp_getBlock(IMP anImp) { - uintptr_t index; - TrampolineBlockPagePair *pagePair; - - if (!anImp) return nil; - - _lock(); - - pagePair = _pageAndIndexContainingIMP(anImp, &index, nil); - - if (!pagePair) { - _unlock(); - return nil; - } - - TrampolineBlockPagePair::Payload *payload = pagePair->payload(index); - - if (payload->nextAvailable <= TrampolineBlockPagePair::endIndex()) { - // unallocated - _unlock(); - return nil; - } - - _unlock(); - - return payload->block; -} - -BOOL imp_removeBlock(IMP anImp) { - TrampolineBlockPagePair *pagePair; - TrampolineBlockPagePair *headPagePair; - uintptr_t index; - - if (!anImp) return NO; - - _lock(); - pagePair = _pageAndIndexContainingIMP(anImp, &index, &headPagePair); - - if (!pagePair) { - _unlock(); - return NO; - } - - TrampolineBlockPagePair::Payload *payload = pagePair->payload(index); - id block = payload->block; - // block is released below - - payload->nextAvailable = pagePair->nextAvailable; - pagePair->nextAvailable = index; - - // make sure this page is on available linked list - TrampolineBlockPagePair *pagePairIterator = headPagePair; - - // see if page is the next available page for any existing pages - while (pagePairIterator->nextAvailablePage && - pagePairIterator->nextAvailablePage != pagePair) - { - pagePairIterator = pagePairIterator->nextAvailablePage; - } - - if (! pagePairIterator->nextAvailablePage) { - // if iteration stopped because nextAvail was nil - // add to end of list. - pagePairIterator->nextAvailablePage = pagePair; - pagePair->nextAvailablePage = nil; - } - - _unlock(); - Block_release(block); - return YES; -} diff --git a/objc/objc-runtime/runtime/objc-cache-old.h b/objc/objc-runtime/runtime/objc-cache-old.h deleted file mode 100644 index 7f0245e..0000000 --- a/objc/objc-runtime/runtime/objc-cache-old.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 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 _OBJC_CACHE_OLD_H -#define _OBJC_CACHE_OLD_H - -#include "objc-private.h" - -__BEGIN_DECLS - -extern IMP _cache_getImp(Class cls, SEL sel); -extern Method _cache_getMethod(Class cls, SEL sel, IMP objc_msgForward_internal_imp); - -extern void flush_cache(Class cls); -extern bool _cache_fill(Class cls, Method meth, SEL sel); -extern void _cache_addForwardEntry(Class cls, SEL sel); -extern IMP _cache_addIgnoredEntry(Class cls, SEL sel); -extern void _cache_free(Cache cache); -extern void _cache_collect(bool collectALot); - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/runtime/objc-cache-old.mm b/objc/objc-runtime/runtime/objc-cache-old.mm deleted file mode 100644 index a14556f..0000000 --- a/objc/objc-runtime/runtime/objc-cache-old.mm +++ /dev/null @@ -1,1845 +0,0 @@ -/* - * 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@ - */ - -/*********************************************************************** -* objc-cache.m -* Method cache management -* Cache flushing -* Cache garbage collection -* Cache instrumentation -* Dedicated allocator for large caches -**********************************************************************/ - - -/*********************************************************************** - * Method cache locking (GrP 2001-1-14) - * - * For speed, objc_msgSend does not acquire any locks when it reads - * method caches. Instead, all cache changes are performed so that any - * objc_msgSend running concurrently with the cache mutator will not - * crash or hang or get an incorrect result from the cache. - * - * When cache memory becomes unused (e.g. the old cache after cache - * expansion), it is not immediately freed, because a concurrent - * objc_msgSend could still be using it. Instead, the memory is - * disconnected from the data structures and placed on a garbage list. - * The memory is now only accessible to instances of objc_msgSend that - * were running when the memory was disconnected; any further calls to - * objc_msgSend will not see the garbage memory because the other data - * structures don't point to it anymore. The collecting_in_critical - * function checks the PC of all threads and returns FALSE when all threads - * are found to be outside objc_msgSend. This means any call to objc_msgSend - * that could have had access to the garbage has finished or moved past the - * cache lookup stage, so it is safe to free the memory. - * - * All functions that modify cache data or structures must acquire the - * cacheUpdateLock to prevent interference from concurrent modifications. - * The function that frees cache garbage must acquire the cacheUpdateLock - * and use collecting_in_critical() to flush out cache readers. - * The cacheUpdateLock is also used to protect the custom allocator used - * for large method cache blocks. - * - * Cache readers (PC-checked by collecting_in_critical()) - * objc_msgSend* - * _cache_getImp - * _cache_getMethod - * - * Cache writers (hold cacheUpdateLock while reading or writing; not PC-checked) - * _cache_fill (acquires lock) - * _cache_expand (only called from cache_fill) - * _cache_create (only called from cache_expand) - * bcopy (only called from instrumented cache_expand) - * flush_caches (acquires lock) - * _cache_flush (only called from cache_fill and flush_caches) - * _cache_collect_free (only called from cache_expand and cache_flush) - * - * UNPROTECTED cache readers (NOT thread-safe; used for debug info only) - * _cache_print - * _class_printMethodCaches - * _class_printDuplicateCacheEntries - * _class_printMethodCacheStatistics - * - * _class_lookupMethodAndLoadCache is a special case. It may read a - * method triplet out of one cache and store it in another cache. This - * is unsafe if the method triplet is a forward:: entry, because the - * triplet itself could be freed unless _class_lookupMethodAndLoadCache - * were PC-checked or used a lock. Additionally, storing the method - * triplet in both caches would result in double-freeing if both caches - * were flushed or expanded. The solution is for _cache_getMethod to - * ignore all entries whose implementation is _objc_msgForward_impcache, - * so _class_lookupMethodAndLoadCache cannot look at a forward:: entry - * unsafely or place it in multiple caches. - ***********************************************************************/ - -#if !__OBJC2__ - -#include "objc-private.h" -#include "objc-cache-old.h" -#include "hashtable2.h" - -typedef struct { - SEL name; // same layout as struct old_method - void *unused; - IMP imp; // same layout as struct old_method -} cache_entry; - - -/* When _class_slow_grow is non-zero, any given cache is actually grown - * only on the odd-numbered times it becomes full; on the even-numbered - * times, it is simply emptied and re-used. When this flag is zero, - * caches are grown every time. */ -static const int _class_slow_grow = 1; - -/* For min cache size: clear_cache=1, slow_grow=1 - For max cache size: clear_cache=0, slow_grow=0 */ - -/* Initial cache bucket count. INIT_CACHE_SIZE must be a power of two. */ -enum { - INIT_CACHE_SIZE_LOG2 = 2, - INIT_CACHE_SIZE = (1 << INIT_CACHE_SIZE_LOG2) -}; - - -/* Amount of space required for `count` hash table buckets, knowing that - * one entry is embedded in the cache structure itself. */ -#define TABLE_SIZE(count) ((count - 1) * sizeof(cache_entry *)) - - -#if !TARGET_OS_WIN32 -# define CACHE_ALLOCATOR -#endif - -/* Custom cache allocator parameters. - * CACHE_REGION_SIZE must be a multiple of CACHE_QUANTUM. */ -#define CACHE_ALLOCATOR_MIN 512 -#define CACHE_QUANTUM (CACHE_ALLOCATOR_MIN+sizeof(struct objc_cache)-sizeof(cache_entry*)) -#define CACHE_REGION_SIZE ((128*1024 / CACHE_QUANTUM) * CACHE_QUANTUM) -// #define CACHE_REGION_SIZE ((256*1024 / CACHE_QUANTUM) * CACHE_QUANTUM) - -static uintptr_t cache_allocator_mask_for_size(size_t size) -{ - return (size - sizeof(struct objc_cache)) / sizeof(cache_entry *); -} - -static size_t cache_allocator_size_for_mask(uintptr_t mask) -{ - size_t requested = sizeof(struct objc_cache) + TABLE_SIZE(mask+1); - size_t actual = CACHE_QUANTUM; - while (actual < requested) actual += CACHE_QUANTUM; - return actual; -} - - -/* Cache instrumentation data. Immediately follows the cache block itself. */ -#ifdef OBJC_INSTRUMENTED -typedef struct -{ - unsigned int hitCount; // cache lookup success tally - unsigned int hitProbes; // sum entries checked to hit - unsigned int maxHitProbes; // max entries checked to hit - unsigned int missCount; // cache lookup no-find tally - unsigned int missProbes; // sum entries checked to miss - unsigned int maxMissProbes; // max entries checked to miss - unsigned int flushCount; // cache flush tally - unsigned int flushedEntries; // sum cache entries flushed - unsigned int maxFlushedEntries; // max cache entries flushed -} CacheInstrumentation; - -#define CACHE_INSTRUMENTATION(cache) (CacheInstrumentation *) &cache->buckets[cache->mask + 1]; -#endif - -/* Cache filling and flushing instrumentation */ - -static int totalCacheFills = 0; - -#ifdef OBJC_INSTRUMENTED -unsigned int LinearFlushCachesCount = 0; -unsigned int LinearFlushCachesVisitedCount = 0; -unsigned int MaxLinearFlushCachesVisitedCount = 0; -unsigned int NonlinearFlushCachesCount = 0; -unsigned int NonlinearFlushCachesClassCount = 0; -unsigned int NonlinearFlushCachesVisitedCount = 0; -unsigned int MaxNonlinearFlushCachesVisitedCount = 0; -unsigned int IdealFlushCachesCount = 0; -unsigned int MaxIdealFlushCachesCount = 0; -#endif - - -/*********************************************************************** -* A static empty cache. All classes initially point at this cache. -* When the first message is sent it misses in the cache, and when -* the cache is grown it checks for this case and uses malloc rather -* than realloc. This avoids the need to check for NULL caches in the -* messenger. -***********************************************************************/ - -struct objc_cache _objc_empty_cache = -{ - 0, // mask - 0, // occupied - { NULL } // buckets -}; -#ifdef OBJC_INSTRUMENTED -CacheInstrumentation emptyCacheInstrumentation = {0}; -#endif - - -/* Local prototypes */ - -static bool _cache_isEmpty(Cache cache); -static Cache _cache_malloc(uintptr_t slotCount); -static Cache _cache_create(Class cls); -static Cache _cache_expand(Class cls); - -static int _collecting_in_critical(void); -static void _garbage_make_room(void); -static void _cache_collect_free(void *data, size_t size); - -#if defined(CACHE_ALLOCATOR) -static bool cache_allocator_is_block(void *block); -static Cache cache_allocator_calloc(size_t size); -static void cache_allocator_free(void *block); -#endif - -/*********************************************************************** -* Cache statistics for OBJC_PRINT_CACHE_SETUP -**********************************************************************/ -static unsigned int cache_counts[16]; -static size_t cache_allocations; -static size_t cache_collections; -static size_t cache_allocator_regions; - -static size_t log2u(size_t x) -{ - unsigned int log; - - log = 0; - while (x >>= 1) - log += 1; - - return log; -} - - -/*********************************************************************** -* _cache_isEmpty. -* Returns YES if the given cache is some empty cache. -* Empty caches should never be allocated on the heap. -**********************************************************************/ -static bool _cache_isEmpty(Cache cache) -{ - return (cache == NULL || cache == (Cache)&_objc_empty_cache || cache->mask == 0); -} - - -/*********************************************************************** -* _cache_malloc. -* -* Called from _cache_create() and cache_expand() -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -static Cache _cache_malloc(uintptr_t slotCount) -{ - Cache new_cache; - size_t size; - - cacheUpdateLock.assertLocked(); - - // Allocate table (why not check for failure?) - size = sizeof(struct objc_cache) + TABLE_SIZE(slotCount); -#if defined(OBJC_INSTRUMENTED) - // Custom cache allocator can't handle instrumentation. - size += sizeof(CacheInstrumentation); - new_cache = calloc(size, 1); - new_cache->mask = slotCount - 1; -#elif !defined(CACHE_ALLOCATOR) - // fixme cache allocator implementation isn't 64-bit clean - new_cache = calloc(size, 1); - new_cache->mask = (unsigned int)(slotCount - 1); -#else - if (size < CACHE_ALLOCATOR_MIN) { - new_cache = (Cache)calloc(size, 1); - new_cache->mask = slotCount - 1; - // occupied and buckets and instrumentation are all zero - } else { - new_cache = cache_allocator_calloc(size); - // mask is already set - // occupied and buckets and instrumentation are all zero - } -#endif - - if (PrintCaches) { - size_t bucket = log2u(slotCount); - if (bucket < sizeof(cache_counts) / sizeof(cache_counts[0])) { - cache_counts[bucket]++; - } - cache_allocations++; - } - - return new_cache; -} - -/*********************************************************************** -* _cache_free_block. -* -* Called from _cache_free() and _cache_collect_free(). -* block may be a cache or a forward:: entry. -* If block is a cache, forward:: entries it points to will NOT be freed. -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -static inline int isPowerOf2(unsigned long l) { return 1 == __builtin_popcountl(l); } -static void _cache_free_block(void *block) -{ - cacheUpdateLock.assertLocked(); - -#if !TARGET_OS_WIN32 - if (PrintCaches) { - Cache cache = (Cache)block; - size_t slotCount = cache->mask + 1; - if (isPowerOf2(slotCount)) { - size_t bucket = log2u(slotCount); - if (bucket < sizeof(cache_counts) / sizeof(cache_counts[0])) { - cache_counts[bucket]--; - } - } - } -#endif - -#if defined(CACHE_ALLOCATOR) - if (cache_allocator_is_block(block)) { - cache_allocator_free(block); - } else -#endif - { - free(block); - } -} - - -/*********************************************************************** -* _cache_free. -* -* Called from _objc_remove_classes_in_image(). -* forward:: entries in the cache ARE freed. -* Cache locks: cacheUpdateLock must NOT be held by the caller. -**********************************************************************/ -void _cache_free(Cache cache) -{ - unsigned int i; - - mutex_locker_t lock(cacheUpdateLock); - - for (i = 0; i < cache->mask + 1; i++) { - cache_entry *entry = (cache_entry *)cache->buckets[i]; - if (entry && entry->imp == _objc_msgForward_impcache) { - _cache_free_block(entry); - } - } - - _cache_free_block(cache); -} - - -/*********************************************************************** -* _cache_create. -* -* Called from _cache_expand(). -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -static Cache _cache_create(Class cls) -{ - Cache new_cache; - - cacheUpdateLock.assertLocked(); - - // Allocate new cache block - new_cache = _cache_malloc(INIT_CACHE_SIZE); - - // Install the cache - cls->cache = new_cache; - - // Clear the grow flag so that we will re-use the current storage, - // rather than actually grow the cache, when expanding the cache - // for the first time - if (_class_slow_grow) { - cls->setShouldGrowCache(false); - } - - // Return our creation - return new_cache; -} - - -/*********************************************************************** -* _cache_expand. -* -* Called from _cache_fill () -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -static Cache _cache_expand(Class cls) -{ - Cache old_cache; - Cache new_cache; - uintptr_t slotCount; - uintptr_t index; - - cacheUpdateLock.assertLocked(); - - // First growth goes from empty cache to a real one - old_cache = cls->cache; - if (_cache_isEmpty(old_cache)) - return _cache_create (cls); - - if (_class_slow_grow) { - // Cache grows every other time only. - if (cls->shouldGrowCache()) { - // Grow the cache this time. Don't grow next time. - cls->setShouldGrowCache(false); - } - else { - // Reuse the current cache storage this time. Do grow next time. - cls->setShouldGrowCache(true); - - // Clear the valid-entry counter - old_cache->occupied = 0; - - // Invalidate all the cache entries - for (index = 0; index < old_cache->mask + 1; index += 1) - { - // Remember what this entry was, so we can possibly - // deallocate it after the bucket has been invalidated - cache_entry *oldEntry = (cache_entry *)old_cache->buckets[index]; - - // Skip invalid entry - if (!oldEntry) - continue; - - // Invalidate this entry - old_cache->buckets[index] = NULL; - - // Deallocate "forward::" entry - if (oldEntry->imp == _objc_msgForward_impcache) { - _cache_collect_free (oldEntry, sizeof(cache_entry)); - } - } - - // Return the same old cache, freshly emptied - return old_cache; - } - } - - // Double the cache size - slotCount = (old_cache->mask + 1) << 1; - - new_cache = _cache_malloc(slotCount); - -#ifdef OBJC_INSTRUMENTED - // Propagate the instrumentation data - { - CacheInstrumentation *oldCacheData; - CacheInstrumentation *newCacheData; - - oldCacheData = CACHE_INSTRUMENTATION(old_cache); - newCacheData = CACHE_INSTRUMENTATION(new_cache); - bcopy ((const char *)oldCacheData, (char *)newCacheData, sizeof(CacheInstrumentation)); - } -#endif - - // Deallocate "forward::" entries from the old cache - for (index = 0; index < old_cache->mask + 1; index++) { - cache_entry *entry = (cache_entry *)old_cache->buckets[index]; - if (entry && entry->imp == _objc_msgForward_impcache) { - _cache_collect_free (entry, sizeof(cache_entry)); - } - } - - // Install new cache - cls->cache = new_cache; - - // Deallocate old cache, try freeing all the garbage - _cache_collect_free (old_cache, old_cache->mask * sizeof(cache_entry *)); - _cache_collect(false); - - return new_cache; -} - - -/*********************************************************************** -* _cache_fill. Add the specified method to the specified class' cache. -* Returns NO if the cache entry wasn't added: cache was busy, -* class is still being initialized, new entry is a duplicate. -* -* Called only from _class_lookupMethodAndLoadCache and -* class_respondsToMethod and _cache_addForwardEntry. -* -* Cache locks: cacheUpdateLock must not be held. -**********************************************************************/ -bool _cache_fill(Class cls, Method smt, SEL sel) -{ - uintptr_t newOccupied; - uintptr_t index; - cache_entry **buckets; - cache_entry *entry; - Cache cache; - - cacheUpdateLock.assertUnlocked(); - - // Never cache before +initialize is done - if (!cls->isInitialized()) { - return NO; - } - - // Keep tally of cache additions - totalCacheFills += 1; - - mutex_locker_t lock(cacheUpdateLock); - - entry = (cache_entry *)smt; - - cache = cls->cache; - - // Make sure the entry wasn't added to the cache by some other thread - // before we grabbed the cacheUpdateLock. - // Don't use _cache_getMethod() because _cache_getMethod() doesn't - // return forward:: entries. - if (_cache_getImp(cls, sel)) { - return NO; // entry is already cached, didn't add new one - } - - // Use the cache as-is if it is less than 3/4 full - newOccupied = cache->occupied + 1; - if ((newOccupied * 4) <= (cache->mask + 1) * 3) { - // Cache is less than 3/4 full. - cache->occupied = (unsigned int)newOccupied; - } else { - // Cache is too full. Expand it. - cache = _cache_expand (cls); - - // Account for the addition - cache->occupied += 1; - } - - // Scan for the first unused slot and insert there. - // There is guaranteed to be an empty slot because the - // minimum size is 4 and we resized at 3/4 full. - buckets = (cache_entry **)cache->buckets; - for (index = CACHE_HASH(sel, cache->mask); - buckets[index] != NULL; - index = (index+1) & cache->mask) - { - // empty - } - buckets[index] = entry; - - return YES; // successfully added new cache entry -} - - -/*********************************************************************** -* _cache_addForwardEntry -* Add a forward:: entry for the given selector to cls's method cache. -* Does nothing if the cache addition fails for any reason. -* Called from class_respondsToMethod and _class_lookupMethodAndLoadCache. -* Cache locks: cacheUpdateLock must not be held. -**********************************************************************/ -void _cache_addForwardEntry(Class cls, SEL sel) -{ - cache_entry *smt; - - smt = (cache_entry *)malloc(sizeof(cache_entry)); - smt->name = sel; - smt->imp = _objc_msgForward_impcache; - if (! _cache_fill(cls, (Method)smt, sel)) { // fixme hack - // Entry not added to cache. Don't leak the method struct. - free(smt); - } -} - - -/*********************************************************************** -* _cache_addIgnoredEntry -* Add an entry for the ignored selector to cls's method cache. -* Does nothing if the cache addition fails for any reason. -* Returns the ignored IMP. -* Cache locks: cacheUpdateLock must not be held. -**********************************************************************/ -#if SUPPORT_GC && !SUPPORT_IGNORED_SELECTOR_CONSTANT -static cache_entry *alloc_ignored_entries(void) -{ - cache_entry *e = (cache_entry *)malloc(5 * sizeof(cache_entry)); - e[0] = (cache_entry){ @selector(retain), 0,(IMP)&_objc_ignored_method}; - e[1] = (cache_entry){ @selector(release), 0,(IMP)&_objc_ignored_method}; - e[2] = (cache_entry){ @selector(autorelease),0,(IMP)&_objc_ignored_method}; - e[3] = (cache_entry){ @selector(retainCount),0,(IMP)&_objc_ignored_method}; - e[4] = (cache_entry){ @selector(dealloc), 0,(IMP)&_objc_ignored_method}; - return e; -} -#endif - -IMP _cache_addIgnoredEntry(Class cls, SEL sel) -{ - cache_entry *entryp = NULL; - -#if !SUPPORT_GC - _objc_fatal("selector ignored with GC off"); -#elif SUPPORT_IGNORED_SELECTOR_CONSTANT - static cache_entry entry = { (SEL)kIgnore, 0, (IMP)&_objc_ignored_method }; - entryp = &entry; - assert(sel == (SEL)kIgnore); -#else - // hack - int i; - static cache_entry *entries; - INIT_ONCE_PTR(entries, alloc_ignored_entries(), free(v)); - - assert(ignoreSelector(sel)); - for (i = 0; i < 5; i++) { - if (sel == entries[i].name) { - entryp = &entries[i]; - break; - } - } - if (!entryp) _objc_fatal("selector %s (%p) is not ignored", - sel_getName(sel), sel); -#endif - - _cache_fill(cls, (Method)entryp, sel); - return entryp->imp; -} - - -/*********************************************************************** -* _cache_flush. Invalidate all valid entries in the given class' cache. -* -* Called from flush_caches() and _cache_fill() -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -void _cache_flush(Class cls) -{ - Cache cache; - unsigned int index; - - cacheUpdateLock.assertLocked(); - - // Locate cache. Ignore unused cache. - cache = cls->cache; - if (_cache_isEmpty(cache)) return; - -#ifdef OBJC_INSTRUMENTED - { - CacheInstrumentation *cacheData; - - // Tally this flush - cacheData = CACHE_INSTRUMENTATION(cache); - cacheData->flushCount += 1; - cacheData->flushedEntries += cache->occupied; - if (cache->occupied > cacheData->maxFlushedEntries) - cacheData->maxFlushedEntries = cache->occupied; - } -#endif - - // Traverse the cache - for (index = 0; index <= cache->mask; index += 1) - { - // Remember what this entry was, so we can possibly - // deallocate it after the bucket has been invalidated - cache_entry *oldEntry = (cache_entry *)cache->buckets[index]; - - // Invalidate this entry - cache->buckets[index] = NULL; - - // Deallocate "forward::" entry - if (oldEntry && oldEntry->imp == _objc_msgForward_impcache) - _cache_collect_free (oldEntry, sizeof(cache_entry)); - } - - // Clear the valid-entry counter - cache->occupied = 0; -} - - -/*********************************************************************** -* flush_cache. Flushes the instance method cache for class cls only. -* Use flush_caches() if cls might have in-use subclasses. -**********************************************************************/ -void flush_cache(Class cls) -{ - if (cls) { - mutex_locker_t lock(cacheUpdateLock); - _cache_flush(cls); - } -} - - -/*********************************************************************** -* cache collection. -**********************************************************************/ - -#if !TARGET_OS_WIN32 - -// A sentinel (magic value) to report bad thread_get_state status. -// Must not be a valid PC. -// Must not be zero - thread_get_state() on a new thread returns PC == 0. -#define PC_SENTINEL 1 - -// UNIX03 compliance hack (4508809) -#if !__DARWIN_UNIX03 -#define __srr0 srr0 -#define __eip eip -#endif - -static uintptr_t _get_pc_for_thread(thread_t thread) -#if defined(__i386__) -{ - i386_thread_state_t state; - unsigned int count = i386_THREAD_STATE_COUNT; - kern_return_t okay = thread_get_state (thread, i386_THREAD_STATE, (thread_state_t)&state, &count); - return (okay == KERN_SUCCESS) ? state.__eip : PC_SENTINEL; -} -#elif defined(__x86_64__) -{ - x86_thread_state64_t state; - unsigned int count = x86_THREAD_STATE64_COUNT; - kern_return_t okay = thread_get_state (thread, x86_THREAD_STATE64, (thread_state_t)&state, &count); - return (okay == KERN_SUCCESS) ? state.__rip : PC_SENTINEL; -} -#elif defined(__arm__) -{ - arm_thread_state_t state; - unsigned int count = ARM_THREAD_STATE_COUNT; - kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE, (thread_state_t)&state, &count); - return (okay == KERN_SUCCESS) ? state.__pc : PC_SENTINEL; -} -#else -{ -#error _get_pc_for_thread () not implemented for this architecture -} -#endif - -#endif - -/*********************************************************************** -* _collecting_in_critical. -* Returns TRUE if some thread is currently executing a cache-reading -* function. Collection of cache garbage is not allowed when a cache- -* reading function is in progress because it might still be using -* the garbage memory. -**********************************************************************/ -OBJC_EXPORT uintptr_t objc_entryPoints[]; -OBJC_EXPORT uintptr_t objc_exitPoints[]; - -static int _collecting_in_critical(void) -{ -#if TARGET_OS_WIN32 - return TRUE; -#else - thread_act_port_array_t threads; - unsigned number; - unsigned count; - kern_return_t ret; - int result; - - mach_port_t mythread = pthread_mach_thread_np(pthread_self()); - - // Get a list of all the threads in the current task - ret = task_threads (mach_task_self (), &threads, &number); - if (ret != KERN_SUCCESS) - { - _objc_fatal("task_thread failed (result %d)\n", ret); - } - - // Check whether any thread is in the cache lookup code - result = FALSE; - for (count = 0; count < number; count++) - { - int region; - uintptr_t pc; - - // Don't bother checking ourselves - if (threads[count] == mythread) - continue; - - // Find out where thread is executing - pc = _get_pc_for_thread (threads[count]); - - // Check for bad status, and if so, assume the worse (can't collect) - if (pc == PC_SENTINEL) - { - result = TRUE; - goto done; - } - - // Check whether it is in the cache lookup code - for (region = 0; objc_entryPoints[region] != 0; region++) - { - if ((pc >= objc_entryPoints[region]) && - (pc <= objc_exitPoints[region])) - { - result = TRUE; - goto done; - } - } - } - - done: - // Deallocate the port rights for the threads - for (count = 0; count < number; count++) { - mach_port_deallocate(mach_task_self (), threads[count]); - } - - // Deallocate the thread list - vm_deallocate (mach_task_self (), (vm_address_t) threads, sizeof(threads[0]) * number); - - // Return our finding - return result; -#endif -} - - -/*********************************************************************** -* _garbage_make_room. Ensure that there is enough room for at least -* one more ref in the garbage. -**********************************************************************/ - -// amount of memory represented by all refs in the garbage -static size_t garbage_byte_size = 0; - -// do not empty the garbage until garbage_byte_size gets at least this big -static size_t garbage_threshold = 1024; - -// table of refs to free -static void **garbage_refs = 0; - -// current number of refs in garbage_refs -static size_t garbage_count = 0; - -// capacity of current garbage_refs -static size_t garbage_max = 0; - -// capacity of initial garbage_refs -enum { - INIT_GARBAGE_COUNT = 128 -}; - -static void _garbage_make_room(void) -{ - static int first = 1; - - // Create the collection table the first time it is needed - if (first) - { - first = 0; - garbage_refs = (void**) - malloc(INIT_GARBAGE_COUNT * sizeof(void *)); - garbage_max = INIT_GARBAGE_COUNT; - } - - // Double the table if it is full - else if (garbage_count == garbage_max) - { - garbage_refs = (void**) - realloc(garbage_refs, garbage_max * 2 * sizeof(void *)); - garbage_max *= 2; - } -} - - -/*********************************************************************** -* _cache_collect_free. Add the specified malloc'd memory to the list -* of them to free at some later point. -* size is used for the collection threshold. It does not have to be -* precisely the block's size. -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -static void _cache_collect_free(void *data, size_t size) -{ - cacheUpdateLock.assertLocked(); - - _garbage_make_room (); - garbage_byte_size += size; - garbage_refs[garbage_count++] = data; -} - - -/*********************************************************************** -* _cache_collect. Try to free accumulated dead caches. -* collectALot tries harder to free memory. -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -void _cache_collect(bool collectALot) -{ - cacheUpdateLock.assertLocked(); - - // Done if the garbage is not full - if (garbage_byte_size < garbage_threshold && !collectALot) { - return; - } - - // Synchronize collection with objc_msgSend and other cache readers - if (!collectALot) { - if (_collecting_in_critical ()) { - // objc_msgSend (or other cache reader) is currently looking in - // the cache and might still be using some garbage. - if (PrintCaches) { - _objc_inform ("CACHES: not collecting; " - "objc_msgSend in progress"); - } - return; - } - } - else { - // No excuses. - while (_collecting_in_critical()) - ; - } - - // No cache readers in progress - garbage is now deletable - - // Log our progress - if (PrintCaches) { - cache_collections++; - _objc_inform ("CACHES: COLLECTING %zu bytes (%zu regions, %zu allocations, %zu collections)", garbage_byte_size, cache_allocator_regions, cache_allocations, cache_collections); - } - - // Dispose all refs now in the garbage - while (garbage_count--) { - _cache_free_block(garbage_refs[garbage_count]); - } - - // Clear the garbage count and total size indicator - garbage_count = 0; - garbage_byte_size = 0; - - if (PrintCaches) { - size_t i; - size_t total = 0; - size_t ideal_total = 0; - size_t malloc_total = 0; - size_t local_total = 0; - - for (i = 0; i < sizeof(cache_counts) / sizeof(cache_counts[0]); i++) { - int count = cache_counts[i]; - int slots = 1 << i; - size_t size = sizeof(struct objc_cache) + TABLE_SIZE(slots); - size_t ideal = size; -#if TARGET_OS_WIN32 - size_t malloc = size; -#else - size_t malloc = malloc_good_size(size); -#endif - size_t local = size < CACHE_ALLOCATOR_MIN ? malloc : cache_allocator_size_for_mask(cache_allocator_mask_for_size(size)); - - if (!count) continue; - - _objc_inform("CACHES: %4d slots: %4d caches, %6zu / %6zu / %6zu bytes ideal/malloc/local, %6zu / %6zu bytes wasted malloc/local", slots, count, ideal*count, malloc*count, local*count, malloc*count-ideal*count, local*count-ideal*count); - - total += count; - ideal_total += ideal*count; - malloc_total += malloc*count; - local_total += local*count; - } - - _objc_inform("CACHES: total: %4zu caches, %6zu / %6zu / %6zu bytes ideal/malloc/local, %6zu / %6zu bytes wasted malloc/local", total, ideal_total, malloc_total, local_total, malloc_total-ideal_total, local_total-ideal_total); - } -} - - - - - -#if defined(CACHE_ALLOCATOR) - -/*********************************************************************** -* Custom method cache allocator. -* Method cache block sizes are 2^slots+2 words, which is a pessimal -* case for the system allocator. It wastes 504 bytes per cache block -* with 128 or more slots, which adds up to tens of KB for an AppKit process. -* To save memory, the custom cache allocator below is used. -* -* The cache allocator uses 128 KB allocation regions. Few processes will -* require a second region. Within a region, allocation is address-ordered -* first fit. -* -* The cache allocator uses a quantum of 520. -* Cache block ideal sizes: 520, 1032, 2056, 4104 -* Cache allocator sizes: 520, 1040, 2080, 4160 -* -* Because all blocks are known to be genuine method caches, the ordinary -* cache->mask and cache->occupied fields are used as block headers. -* No out-of-band headers are maintained. The number of blocks will -* almost always be fewer than 200, so for simplicity there is no free -* list or other optimization. -* -* Block in use: mask != 0, occupied != -1 (mask indicates block size) -* Block free: mask != 0, occupied == -1 (mask is precisely block size) -* -* No cache allocator functions take any locks. Instead, the caller -* must hold the cacheUpdateLock. -* -* fixme with 128 KB regions and 520 B min block size, an allocation -* bitmap would be only 32 bytes - better than free list? -**********************************************************************/ - -typedef struct cache_allocator_block { - uintptr_t size; - uintptr_t state; - struct cache_allocator_block *nextFree; -} cache_allocator_block; - -typedef struct cache_allocator_region { - cache_allocator_block *start; - cache_allocator_block *end; // first non-block address - cache_allocator_block *freeList; - struct cache_allocator_region *next; -} cache_allocator_region; - -static cache_allocator_region *cacheRegion = NULL; - - -/*********************************************************************** -* cache_allocator_add_region -* Allocates and returns a new region that can hold at least size -* bytes of large method caches. -* The actual size will be rounded up to a CACHE_QUANTUM boundary, -* with a minimum of CACHE_REGION_SIZE. -* The new region is lowest-priority for new allocations. Callers that -* know the other regions are already full should allocate directly -* into the returned region. -**********************************************************************/ -static cache_allocator_region *cache_allocator_add_region(size_t size) -{ - vm_address_t addr; - cache_allocator_block *b; - cache_allocator_region **rgnP; - cache_allocator_region *newRegion = (cache_allocator_region *) - calloc(1, sizeof(cache_allocator_region)); - - // Round size up to quantum boundary, and apply the minimum size. - size += CACHE_QUANTUM - (size % CACHE_QUANTUM); - if (size < CACHE_REGION_SIZE) size = CACHE_REGION_SIZE; - - // Allocate the region - addr = (vm_address_t)calloc(size, 1); - newRegion->start = (cache_allocator_block *)addr; - newRegion->end = (cache_allocator_block *)(addr + size); - - // Mark the first block: free and covers the entire region - b = newRegion->start; - b->size = size; - b->state = (uintptr_t)-1; - b->nextFree = NULL; - newRegion->freeList = b; - - // Add to end of the linked list of regions. - // Other regions should be re-used before this one is touched. - newRegion->next = NULL; - rgnP = &cacheRegion; - while (*rgnP) { - rgnP = &(**rgnP).next; - } - *rgnP = newRegion; - - cache_allocator_regions++; - - return newRegion; -} - - -/*********************************************************************** -* cache_allocator_coalesce -* Attempts to coalesce a free block with the single free block following -* it in the free list, if any. -**********************************************************************/ -static void cache_allocator_coalesce(cache_allocator_block *block) -{ - if (block->size + (uintptr_t)block == (uintptr_t)block->nextFree) { - block->size += block->nextFree->size; - block->nextFree = block->nextFree->nextFree; - } -} - - -/*********************************************************************** -* cache_region_calloc -* Attempt to allocate a size-byte block in the given region. -* Allocation is first-fit. The free list is already fully coalesced. -* Returns NULL if there is not enough room in the region for the block. -**********************************************************************/ -static void *cache_region_calloc(cache_allocator_region *rgn, size_t size) -{ - cache_allocator_block **blockP; - uintptr_t mask; - - // Save mask for allocated block, then round size - // up to CACHE_QUANTUM boundary - mask = cache_allocator_mask_for_size(size); - size = cache_allocator_size_for_mask(mask); - - // Search the free list for a sufficiently large free block. - - for (blockP = &rgn->freeList; - *blockP != NULL; - blockP = &(**blockP).nextFree) - { - cache_allocator_block *block = *blockP; - if (block->size < size) continue; // not big enough - - // block is now big enough. Allocate from it. - - // Slice off unneeded fragment of block, if any, - // and reconnect the free list around block. - if (block->size - size >= CACHE_QUANTUM) { - cache_allocator_block *leftover = - (cache_allocator_block *)(size + (uintptr_t)block); - leftover->size = block->size - size; - leftover->state = (uintptr_t)-1; - leftover->nextFree = block->nextFree; - *blockP = leftover; - } else { - *blockP = block->nextFree; - } - - // block is now exactly the right size. - - bzero(block, size); - block->size = mask; // Cache->mask - block->state = 0; // Cache->occupied - - return block; - } - - // No room in this region. - return NULL; -} - - -/*********************************************************************** -* cache_allocator_calloc -* Custom allocator for large method caches (128+ slots) -* The returned cache block already has cache->mask set. -* cache->occupied and the cache contents are zero. -* Cache locks: cacheUpdateLock must be held by the caller -**********************************************************************/ -static Cache cache_allocator_calloc(size_t size) -{ - cache_allocator_region *rgn; - - cacheUpdateLock.assertLocked(); - - for (rgn = cacheRegion; rgn != NULL; rgn = rgn->next) { - void *p = cache_region_calloc(rgn, size); - if (p) { - return (Cache)p; - } - } - - // No regions or all regions full - make a region and try one more time - // In the unlikely case of a cache over 256KB, it will get its own region. - return (Cache)cache_region_calloc(cache_allocator_add_region(size), size); -} - - -/*********************************************************************** -* cache_allocator_region_for_block -* Returns the cache allocator region that ptr points into, or NULL. -**********************************************************************/ -static cache_allocator_region *cache_allocator_region_for_block(cache_allocator_block *block) -{ - cache_allocator_region *rgn; - for (rgn = cacheRegion; rgn != NULL; rgn = rgn->next) { - if (block >= rgn->start && block < rgn->end) return rgn; - } - return NULL; -} - - -/*********************************************************************** -* cache_allocator_is_block -* If ptr is a live block from the cache allocator, return YES -* If ptr is a block from some other allocator, return NO. -* If ptr is a dead block from the cache allocator, result is undefined. -* Cache locks: cacheUpdateLock must be held by the caller -**********************************************************************/ -static bool cache_allocator_is_block(void *ptr) -{ - cacheUpdateLock.assertLocked(); - return (cache_allocator_region_for_block((cache_allocator_block *)ptr) != NULL); -} - -/*********************************************************************** -* cache_allocator_free -* Frees a block allocated by the cache allocator. -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -static void cache_allocator_free(void *ptr) -{ - cache_allocator_block *dead = (cache_allocator_block *)ptr; - cache_allocator_block *cur; - cache_allocator_region *rgn; - - cacheUpdateLock.assertLocked(); - - if (! (rgn = cache_allocator_region_for_block(dead))) { - // free of non-pointer - _objc_inform("cache_allocator_free of non-pointer %p", dead); - return; - } - - dead->size = cache_allocator_size_for_mask(dead->size); - dead->state = (uintptr_t)-1; - - if (!rgn->freeList || rgn->freeList > dead) { - // dead block belongs at front of free list - dead->nextFree = rgn->freeList; - rgn->freeList = dead; - cache_allocator_coalesce(dead); - return; - } - - // dead block belongs in the middle or end of free list - for (cur = rgn->freeList; cur != NULL; cur = cur->nextFree) { - cache_allocator_block *ahead = cur->nextFree; - - if (!ahead || ahead > dead) { - // cur and ahead straddle dead, OR dead belongs at end of free list - cur->nextFree = dead; - dead->nextFree = ahead; - - // coalesce into dead first in case both succeed - cache_allocator_coalesce(dead); - cache_allocator_coalesce(cur); - return; - } - } - - // uh-oh - _objc_inform("cache_allocator_free of non-pointer %p", ptr); -} - -// defined(CACHE_ALLOCATOR) -#endif - -/*********************************************************************** -* Cache instrumentation and debugging -**********************************************************************/ - -#ifdef OBJC_INSTRUMENTED -enum { - CACHE_HISTOGRAM_SIZE = 512 -}; - -unsigned int CacheHitHistogram [CACHE_HISTOGRAM_SIZE]; -unsigned int CacheMissHistogram [CACHE_HISTOGRAM_SIZE]; -#endif - - -/*********************************************************************** -* _cache_print. -**********************************************************************/ -static void _cache_print(Cache cache) -{ - uintptr_t index; - uintptr_t count; - - count = cache->mask + 1; - for (index = 0; index < count; index += 1) { - cache_entry *entry = (cache_entry *)cache->buckets[index]; - if (entry) { - if (entry->imp == _objc_msgForward_impcache) - printf ("does not recognize: \n"); - printf ("%s\n", sel_getName(entry->name)); - } - } -} - - -/*********************************************************************** -* _class_printMethodCaches. -**********************************************************************/ -void _class_printMethodCaches(Class cls) -{ - if (_cache_isEmpty(cls->cache)) { - printf("no instance-method cache for class %s\n",cls->nameForLogging()); - } else { - printf("instance-method cache for class %s:\n", cls->nameForLogging()); - _cache_print(cls->cache); - } - - if (_cache_isEmpty(cls->ISA()->cache)) { - printf("no class-method cache for class %s\n", cls->nameForLogging()); - } else { - printf ("class-method cache for class %s:\n", cls->nameForLogging()); - _cache_print(cls->ISA()->cache); - } -} - - -#if 0 -#warning fixme - - -/*********************************************************************** -* _class_printDuplicateCacheEntries. -**********************************************************************/ -void _class_printDuplicateCacheEntries(bool detail) -{ - NXHashState state; - Class cls; - unsigned int duplicates; - unsigned int index1; - unsigned int index2; - unsigned int mask; - unsigned int count; - unsigned int isMeta; - Cache cache; - - - printf ("Checking for duplicate cache entries \n"); - - // Outermost loop - iterate over all classes - state = NXInitHashState (class_hash); - duplicates = 0; - while (NXNextHashState (class_hash, &state, (void **) &cls)) - { - // Control loop - do given class' cache, then its isa's cache - for (isMeta = 0; isMeta <= 1; isMeta += 1) - { - // Select cache of interest and make sure it exists - cache = (isMeta ? cls->ISA : cls)->cache; - if (_cache_isEmpty(cache)) - continue; - - // Middle loop - check each entry in the given cache - mask = cache->mask; - count = mask + 1; - for (index1 = 0; index1 < count; index1 += 1) - { - // Skip invalid entry - if (!cache->buckets[index1]) - continue; - - // Inner loop - check that given entry matches no later entry - for (index2 = index1 + 1; index2 < count; index2 += 1) - { - // Skip invalid entry - if (!cache->buckets[index2]) - continue; - - // Check for duplication by method name comparison - if (strcmp ((char *) cache->buckets[index1]->name), - (char *) cache->buckets[index2]->name)) == 0) - { - if (detail) - printf ("%s %s\n", cls->nameForLogging(), sel_getName(cache->buckets[index1]->name)); - duplicates += 1; - break; - } - } - } - } - } - - // Log the findings - printf ("duplicates = %d\n", duplicates); - printf ("total cache fills = %d\n", totalCacheFills); -} - - -/*********************************************************************** -* PrintCacheHeader. -**********************************************************************/ -static void PrintCacheHeader(void) -{ -#ifdef OBJC_INSTRUMENTED - printf ("Cache Cache Slots Avg Max AvgS MaxS AvgS MaxS TotalD AvgD MaxD TotalD AvgD MaxD TotD AvgD MaxD\n"); - printf ("Size Count Used Used Used Hit Hit Miss Miss Hits Prbs Prbs Misses Prbs Prbs Flsh Flsh Flsh\n"); - printf ("----- ----- ----- ----- ---- ---- ---- ---- ---- ------- ---- ---- ------- ---- ---- ---- ---- ----\n"); -#else - printf ("Cache Cache Slots Avg Max AvgS MaxS AvgS MaxS\n"); - printf ("Size Count Used Used Used Hit Hit Miss Miss\n"); - printf ("----- ----- ----- ----- ---- ---- ---- ---- ----\n"); -#endif -} - - -/*********************************************************************** -* PrintCacheInfo. -**********************************************************************/ -static void PrintCacheInfo(unsigned int cacheSize, - unsigned int cacheCount, - unsigned int slotsUsed, - float avgUsed, unsigned int maxUsed, - float avgSHit, unsigned int maxSHit, - float avgSMiss, unsigned int maxSMiss -#ifdef OBJC_INSTRUMENTED - , unsigned int totDHits, - float avgDHit, - unsigned int maxDHit, - unsigned int totDMisses, - float avgDMiss, - unsigned int maxDMiss, - unsigned int totDFlsh, - float avgDFlsh, - unsigned int maxDFlsh -#endif - ) -{ -#ifdef OBJC_INSTRUMENTED - printf ("%5u %5u %5u %5.1f %4u %4.1f %4u %4.1f %4u %7u %4.1f %4u %7u %4.1f %4u %4u %4.1f %4u\n", -#else - printf ("%5u %5u %5u %5.1f %4u %4.1f %4u %4.1f %4u\n", -#endif - cacheSize, cacheCount, slotsUsed, avgUsed, maxUsed, avgSHit, maxSHit, avgSMiss, maxSMiss -#ifdef OBJC_INSTRUMENTED - , totDHits, avgDHit, maxDHit, totDMisses, avgDMiss, maxDMiss, totDFlsh, avgDFlsh, maxDFlsh -#endif - ); - -} - - -#ifdef OBJC_INSTRUMENTED -/*********************************************************************** -* PrintCacheHistogram. Show the non-zero entries from the specified -* cache histogram. -**********************************************************************/ -static void PrintCacheHistogram(char *title, - unsigned int *firstEntry, - unsigned int entryCount) -{ - unsigned int index; - unsigned int *thisEntry; - - printf ("%s\n", title); - printf (" Probes Tally\n"); - printf (" ------ -----\n"); - for (index = 0, thisEntry = firstEntry; - index < entryCount; - index += 1, thisEntry += 1) - { - if (*thisEntry == 0) - continue; - - printf (" %6d %5d\n", index, *thisEntry); - } -} -#endif - - -/*********************************************************************** -* _class_printMethodCacheStatistics. -**********************************************************************/ - -#define MAX_LOG2_SIZE 32 -#define MAX_CHAIN_SIZE 100 - -void _class_printMethodCacheStatistics(void) -{ - unsigned int isMeta; - unsigned int index; - NXHashState state; - Class cls; - unsigned int totalChain; - unsigned int totalMissChain; - unsigned int maxChain; - unsigned int maxMissChain; - unsigned int classCount; - unsigned int negativeEntryCount; - unsigned int cacheExpandCount; - unsigned int cacheCountBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int totalEntriesBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int maxEntriesBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int totalChainBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int totalMissChainBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int totalMaxChainBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int totalMaxMissChainBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int maxChainBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int maxMissChainBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int chainCount[MAX_CHAIN_SIZE] = {0}; - unsigned int missChainCount[MAX_CHAIN_SIZE] = {0}; -#ifdef OBJC_INSTRUMENTED - unsigned int hitCountBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int hitProbesBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int maxHitProbesBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int missCountBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int missProbesBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int maxMissProbesBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int flushCountBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int flushedEntriesBySize[2][MAX_LOG2_SIZE] = {{0}}; - unsigned int maxFlushedEntriesBySize[2][MAX_LOG2_SIZE] = {{0}}; -#endif - - printf ("Printing cache statistics\n"); - - // Outermost loop - iterate over all classes - state = NXInitHashState (class_hash); - classCount = 0; - negativeEntryCount = 0; - cacheExpandCount = 0; - while (NXNextHashState (class_hash, &state, (void **) &cls)) - { - // Tally classes - classCount += 1; - - // Control loop - do given class' cache, then its isa's cache - for (isMeta = 0; isMeta <= 1; isMeta += 1) - { - Cache cache; - unsigned int mask; - unsigned int log2Size; - unsigned int entryCount; - - // Select cache of interest - cache = (isMeta ? cls->ISA : cls)->cache; - - // Ignore empty cache... should we? - if (_cache_isEmpty(cache)) - continue; - - // Middle loop - do each entry in the given cache - mask = cache->mask; - entryCount = 0; - totalChain = 0; - totalMissChain = 0; - maxChain = 0; - maxMissChain = 0; - for (index = 0; index < mask + 1; index += 1) - { - cache_entry **buckets; - cache_entry *entry; - unsigned int hash; - unsigned int methodChain; - unsigned int methodMissChain; - unsigned int index2; - - // If entry is invalid, the only item of - // interest is that future insert hashes - // to this entry can use it directly. - buckets = (cache_entry **)cache->buckets; - if (!buckets[index]) - { - missChainCount[0] += 1; - continue; - } - - entry = buckets[index]; - - // Tally valid entries - entryCount += 1; - - // Tally "forward::" entries - if (entry->imp == _objc_msgForward_impcache) - negativeEntryCount += 1; - - // Calculate search distance (chain length) for this method - // The chain may wrap around to the beginning of the table. - hash = CACHE_HASH(entry->name, mask); - if (index >= hash) methodChain = index - hash; - else methodChain = (mask+1) + index - hash; - - // Tally chains of this length - if (methodChain < MAX_CHAIN_SIZE) - chainCount[methodChain] += 1; - - // Keep sum of all chain lengths - totalChain += methodChain; - - // Record greatest chain length - if (methodChain > maxChain) - maxChain = methodChain; - - // Calculate search distance for miss that hashes here - index2 = index; - while (buckets[index2]) - { - index2 += 1; - index2 &= mask; - } - methodMissChain = ((index2 - index) & mask); - - // Tally miss chains of this length - if (methodMissChain < MAX_CHAIN_SIZE) - missChainCount[methodMissChain] += 1; - - // Keep sum of all miss chain lengths in this class - totalMissChain += methodMissChain; - - // Record greatest miss chain length - if (methodMissChain > maxMissChain) - maxMissChain = methodMissChain; - } - - // Factor this cache into statistics about caches of the same - // type and size (all caches are a power of two in size) - log2Size = log2u (mask + 1); - cacheCountBySize[isMeta][log2Size] += 1; - totalEntriesBySize[isMeta][log2Size] += entryCount; - if (entryCount > maxEntriesBySize[isMeta][log2Size]) - maxEntriesBySize[isMeta][log2Size] = entryCount; - totalChainBySize[isMeta][log2Size] += totalChain; - totalMissChainBySize[isMeta][log2Size] += totalMissChain; - totalMaxChainBySize[isMeta][log2Size] += maxChain; - totalMaxMissChainBySize[isMeta][log2Size] += maxMissChain; - if (maxChain > maxChainBySize[isMeta][log2Size]) - maxChainBySize[isMeta][log2Size] = maxChain; - if (maxMissChain > maxMissChainBySize[isMeta][log2Size]) - maxMissChainBySize[isMeta][log2Size] = maxMissChain; -#ifdef OBJC_INSTRUMENTED - { - CacheInstrumentation *cacheData; - - cacheData = CACHE_INSTRUMENTATION(cache); - hitCountBySize[isMeta][log2Size] += cacheData->hitCount; - hitProbesBySize[isMeta][log2Size] += cacheData->hitProbes; - if (cacheData->maxHitProbes > maxHitProbesBySize[isMeta][log2Size]) - maxHitProbesBySize[isMeta][log2Size] = cacheData->maxHitProbes; - missCountBySize[isMeta][log2Size] += cacheData->missCount; - missProbesBySize[isMeta][log2Size] += cacheData->missProbes; - if (cacheData->maxMissProbes > maxMissProbesBySize[isMeta][log2Size]) - maxMissProbesBySize[isMeta][log2Size] = cacheData->maxMissProbes; - flushCountBySize[isMeta][log2Size] += cacheData->flushCount; - flushedEntriesBySize[isMeta][log2Size] += cacheData->flushedEntries; - if (cacheData->maxFlushedEntries > maxFlushedEntriesBySize[isMeta][log2Size]) - maxFlushedEntriesBySize[isMeta][log2Size] = cacheData->maxFlushedEntries; - } -#endif - // Caches start with a power of two number of entries, and grow by doubling, so - // we can calculate the number of times this cache has expanded - cacheExpandCount += log2Size - INIT_CACHE_SIZE_LOG2; - } - } - - { - unsigned int cacheCountByType[2] = {0}; - unsigned int totalCacheCount = 0; - unsigned int totalEntries = 0; - unsigned int maxEntries = 0; - unsigned int totalSlots = 0; -#ifdef OBJC_INSTRUMENTED - unsigned int totalHitCount = 0; - unsigned int totalHitProbes = 0; - unsigned int maxHitProbes = 0; - unsigned int totalMissCount = 0; - unsigned int totalMissProbes = 0; - unsigned int maxMissProbes = 0; - unsigned int totalFlushCount = 0; - unsigned int totalFlushedEntries = 0; - unsigned int maxFlushedEntries = 0; -#endif - - totalChain = 0; - maxChain = 0; - totalMissChain = 0; - maxMissChain = 0; - - // Sum information over all caches - for (isMeta = 0; isMeta <= 1; isMeta += 1) - { - for (index = 0; index < MAX_LOG2_SIZE; index += 1) - { - cacheCountByType[isMeta] += cacheCountBySize[isMeta][index]; - totalEntries += totalEntriesBySize[isMeta][index]; - totalSlots += cacheCountBySize[isMeta][index] * (1 << index); - totalChain += totalChainBySize[isMeta][index]; - if (maxEntriesBySize[isMeta][index] > maxEntries) - maxEntries = maxEntriesBySize[isMeta][index]; - if (maxChainBySize[isMeta][index] > maxChain) - maxChain = maxChainBySize[isMeta][index]; - totalMissChain += totalMissChainBySize[isMeta][index]; - if (maxMissChainBySize[isMeta][index] > maxMissChain) - maxMissChain = maxMissChainBySize[isMeta][index]; -#ifdef OBJC_INSTRUMENTED - totalHitCount += hitCountBySize[isMeta][index]; - totalHitProbes += hitProbesBySize[isMeta][index]; - if (maxHitProbesBySize[isMeta][index] > maxHitProbes) - maxHitProbes = maxHitProbesBySize[isMeta][index]; - totalMissCount += missCountBySize[isMeta][index]; - totalMissProbes += missProbesBySize[isMeta][index]; - if (maxMissProbesBySize[isMeta][index] > maxMissProbes) - maxMissProbes = maxMissProbesBySize[isMeta][index]; - totalFlushCount += flushCountBySize[isMeta][index]; - totalFlushedEntries += flushedEntriesBySize[isMeta][index]; - if (maxFlushedEntriesBySize[isMeta][index] > maxFlushedEntries) - maxFlushedEntries = maxFlushedEntriesBySize[isMeta][index]; -#endif - } - - totalCacheCount += cacheCountByType[isMeta]; - } - - // Log our findings - printf ("There are %u classes\n", classCount); - - for (isMeta = 0; isMeta <= 1; isMeta += 1) - { - // Number of this type of class - printf ("\nThere are %u %s-method caches, broken down by size (slot count):\n", - cacheCountByType[isMeta], - isMeta ? "class" : "instance"); - - // Print header - PrintCacheHeader (); - - // Keep format consistent even if there are caches of this kind - if (cacheCountByType[isMeta] == 0) - { - printf ("(none)\n"); - continue; - } - - // Usage information by cache size - for (index = 0; index < MAX_LOG2_SIZE; index += 1) - { - unsigned int cacheCount; - unsigned int cacheSlotCount; - unsigned int cacheEntryCount; - - // Get number of caches of this type and size - cacheCount = cacheCountBySize[isMeta][index]; - if (cacheCount == 0) - continue; - - // Get the cache slot count and the total number of valid entries - cacheSlotCount = (1 << index); - cacheEntryCount = totalEntriesBySize[isMeta][index]; - - // Give the analysis - PrintCacheInfo (cacheSlotCount, - cacheCount, - cacheEntryCount, - (float) cacheEntryCount / (float) cacheCount, - maxEntriesBySize[isMeta][index], - (float) totalChainBySize[isMeta][index] / (float) cacheEntryCount, - maxChainBySize[isMeta][index], - (float) totalMissChainBySize[isMeta][index] / (float) (cacheCount * cacheSlotCount), - maxMissChainBySize[isMeta][index] -#ifdef OBJC_INSTRUMENTED - , hitCountBySize[isMeta][index], - hitCountBySize[isMeta][index] ? - (float) hitProbesBySize[isMeta][index] / (float) hitCountBySize[isMeta][index] : 0.0, - maxHitProbesBySize[isMeta][index], - missCountBySize[isMeta][index], - missCountBySize[isMeta][index] ? - (float) missProbesBySize[isMeta][index] / (float) missCountBySize[isMeta][index] : 0.0, - maxMissProbesBySize[isMeta][index], - flushCountBySize[isMeta][index], - flushCountBySize[isMeta][index] ? - (float) flushedEntriesBySize[isMeta][index] / (float) flushCountBySize[isMeta][index] : 0.0, - maxFlushedEntriesBySize[isMeta][index] -#endif - ); - } - } - - // Give overall numbers - printf ("\nCumulative:\n"); - PrintCacheHeader (); - PrintCacheInfo (totalSlots, - totalCacheCount, - totalEntries, - (float) totalEntries / (float) totalCacheCount, - maxEntries, - (float) totalChain / (float) totalEntries, - maxChain, - (float) totalMissChain / (float) totalSlots, - maxMissChain -#ifdef OBJC_INSTRUMENTED - , totalHitCount, - totalHitCount ? - (float) totalHitProbes / (float) totalHitCount : 0.0, - maxHitProbes, - totalMissCount, - totalMissCount ? - (float) totalMissProbes / (float) totalMissCount : 0.0, - maxMissProbes, - totalFlushCount, - totalFlushCount ? - (float) totalFlushedEntries / (float) totalFlushCount : 0.0, - maxFlushedEntries -#endif - ); - - printf ("\nNumber of \"forward::\" entries: %d\n", negativeEntryCount); - printf ("Number of cache expansions: %d\n", cacheExpandCount); -#ifdef OBJC_INSTRUMENTED - printf ("flush_caches: total calls total visits average visits max visits total classes visits/class\n"); - printf (" ----------- ------------ -------------- ---------- ------------- -------------\n"); - printf (" linear %11u %12u %14.1f %10u %13u %12.2f\n", - LinearFlushCachesCount, - LinearFlushCachesVisitedCount, - LinearFlushCachesCount ? - (float) LinearFlushCachesVisitedCount / (float) LinearFlushCachesCount : 0.0, - MaxLinearFlushCachesVisitedCount, - LinearFlushCachesVisitedCount, - 1.0); - printf (" nonlinear %11u %12u %14.1f %10u %13u %12.2f\n", - NonlinearFlushCachesCount, - NonlinearFlushCachesVisitedCount, - NonlinearFlushCachesCount ? - (float) NonlinearFlushCachesVisitedCount / (float) NonlinearFlushCachesCount : 0.0, - MaxNonlinearFlushCachesVisitedCount, - NonlinearFlushCachesClassCount, - NonlinearFlushCachesClassCount ? - (float) NonlinearFlushCachesVisitedCount / (float) NonlinearFlushCachesClassCount : 0.0); - printf (" ideal %11u %12u %14.1f %10u %13u %12.2f\n", - LinearFlushCachesCount + NonlinearFlushCachesCount, - IdealFlushCachesCount, - LinearFlushCachesCount + NonlinearFlushCachesCount ? - (float) IdealFlushCachesCount / (float) (LinearFlushCachesCount + NonlinearFlushCachesCount) : 0.0, - MaxIdealFlushCachesCount, - LinearFlushCachesVisitedCount + NonlinearFlushCachesClassCount, - LinearFlushCachesVisitedCount + NonlinearFlushCachesClassCount ? - (float) IdealFlushCachesCount / (float) (LinearFlushCachesVisitedCount + NonlinearFlushCachesClassCount) : 0.0); - - PrintCacheHistogram ("\nCache hit histogram:", &CacheHitHistogram[0], CACHE_HISTOGRAM_SIZE); - PrintCacheHistogram ("\nCache miss histogram:", &CacheMissHistogram[0], CACHE_HISTOGRAM_SIZE); -#endif - -#if 0 - printf ("\nLookup chains:"); - for (index = 0; index < MAX_CHAIN_SIZE; index += 1) - { - if (chainCount[index] != 0) - printf (" %u:%u", index, chainCount[index]); - } - - printf ("\nMiss chains:"); - for (index = 0; index < MAX_CHAIN_SIZE; index += 1) - { - if (missChainCount[index] != 0) - printf (" %u:%u", index, missChainCount[index]); - } - - printf ("\nTotal memory usage for cache data structures: %lu bytes\n", - totalCacheCount * (sizeof(struct objc_cache) - sizeof(cache_entry *)) + - totalSlots * sizeof(cache_entry *) + - negativeEntryCount * sizeof(cache_entry)); -#endif - } -} - -#endif - - -// !__OBJC2__ -#endif diff --git a/objc/objc-runtime/runtime/objc-cache.h b/objc/objc-runtime/runtime/objc-cache.h deleted file mode 100644 index de348a0..0000000 --- a/objc/objc-runtime/runtime/objc-cache.h +++ /dev/null @@ -1,21 +0,0 @@ - -#ifndef _OBJC_CACHE_H -#define _OBJC_CACHE_H - -#include "objc-private.h" - -__BEGIN_DECLS - -extern IMP cache_getImp(Class cls, SEL sel); - -extern void cache_fill(Class cls, SEL sel, IMP imp, id receiver); - -extern void cache_erase_nolock(Class cls); - -extern void cache_delete(Class cls); - -extern void cache_collect(bool collectALot); - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/runtime/objc-cache.mm b/objc/objc-runtime/runtime/objc-cache.mm deleted file mode 100644 index ae3723b..0000000 --- a/objc/objc-runtime/runtime/objc-cache.mm +++ /dev/null @@ -1,1112 +0,0 @@ -/* - * 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@ - */ - -/*********************************************************************** -* objc-cache.m -* Method cache management -* Cache flushing -* Cache garbage collection -* Cache instrumentation -* Dedicated allocator for large caches -**********************************************************************/ - - -/*********************************************************************** - * Method cache locking (GrP 2001-1-14) - * - * For speed, objc_msgSend does not acquire any locks when it reads - * method caches. Instead, all cache changes are performed so that any - * objc_msgSend running concurrently with the cache mutator will not - * crash or hang or get an incorrect result from the cache. - * - * When cache memory becomes unused (e.g. the old cache after cache - * expansion), it is not immediately freed, because a concurrent - * objc_msgSend could still be using it. Instead, the memory is - * disconnected from the data structures and placed on a garbage list. - * The memory is now only accessible to instances of objc_msgSend that - * were running when the memory was disconnected; any further calls to - * objc_msgSend will not see the garbage memory because the other data - * structures don't point to it anymore. The collecting_in_critical - * function checks the PC of all threads and returns FALSE when all threads - * are found to be outside objc_msgSend. This means any call to objc_msgSend - * that could have had access to the garbage has finished or moved past the - * cache lookup stage, so it is safe to free the memory. - * - * All functions that modify cache data or structures must acquire the - * cacheUpdateLock to prevent interference from concurrent modifications. - * The function that frees cache garbage must acquire the cacheUpdateLock - * and use collecting_in_critical() to flush out cache readers. - * The cacheUpdateLock is also used to protect the custom allocator used - * for large method cache blocks. - * - * Cache readers (PC-checked by collecting_in_critical()) - * objc_msgSend* - * cache_getImp - * - * Cache writers (hold cacheUpdateLock while reading or writing; not PC-checked) - * cache_fill (acquires lock) - * cache_expand (only called from cache_fill) - * cache_create (only called from cache_expand) - * bcopy (only called from instrumented cache_expand) - * flush_caches (acquires lock) - * cache_flush (only called from cache_fill and flush_caches) - * cache_collect_free (only called from cache_expand and cache_flush) - * - * UNPROTECTED cache readers (NOT thread-safe; used for debug info only) - * cache_print - * _class_printMethodCaches - * _class_printDuplicateCacheEntries - * _class_printMethodCacheStatistics - * - ***********************************************************************/ - - -#if __OBJC2__ - -#include "objc-private.h" -#include "objc-cache.h" - - -/* Initial cache bucket count. INIT_CACHE_SIZE must be a power of two. */ -enum { - INIT_CACHE_SIZE_LOG2 = 2, - INIT_CACHE_SIZE = (1 << INIT_CACHE_SIZE_LOG2) -}; - -static void cache_collect_free(struct bucket_t *data, mask_t capacity); -static int _collecting_in_critical(void); -static void _garbage_make_room(void); - - -/*********************************************************************** -* Cache statistics for OBJC_PRINT_CACHE_SETUP -**********************************************************************/ -static unsigned int cache_counts[16]; -static size_t cache_allocations; -static size_t cache_collections; - -static void recordNewCache(mask_t capacity) -{ - size_t bucket = log2u(capacity); - if (bucket < countof(cache_counts)) { - cache_counts[bucket]++; - } - cache_allocations++; -} - -static void recordDeadCache(mask_t capacity) -{ - size_t bucket = log2u(capacity); - if (bucket < countof(cache_counts)) { - cache_counts[bucket]--; - } -} - -/*********************************************************************** -* Pointers used by compiled class objects -* These use asm to avoid conflicts with the compiler's internal declarations -**********************************************************************/ - -// EMPTY_BYTES includes space for a cache end marker bucket. -// This end marker doesn't actually have the wrap-around pointer -// because cache scans always find an empty bucket before they might wrap. -// 1024 buckets is fairly common. -#if DEBUG - // Use a smaller size to exercise heap-allocated empty caches. -# define EMPTY_BYTES ((8+1)*16) -#else -# define EMPTY_BYTES ((1024+1)*16) -#endif - -#define stringize(x) #x -#define stringize2(x) stringize(x) - -// "cache" is cache->buckets; "vtable" is cache->mask/occupied -// hack to avoid conflicts with compiler's internal declaration -asm("\n .section __TEXT,__const" - "\n .globl __objc_empty_vtable" - "\n .set __objc_empty_vtable, 0" - "\n .globl __objc_empty_cache" - "\n .align 3" - "\n __objc_empty_cache: .space " stringize2(EMPTY_BYTES) - ); - - -#if __arm__ || __x86_64__ || __i386__ -// objc_msgSend has few registers available. -// Cache scan increments and wraps at special end-marking bucket. -#define CACHE_END_MARKER 1 -static inline mask_t cache_next(mask_t i, mask_t mask) { - return (i+1) & mask; -} - -#elif __arm64__ -// objc_msgSend has lots of registers available. -// Cache scan decrements. No end marker needed. -#define CACHE_END_MARKER 0 -static inline mask_t cache_next(mask_t i, mask_t mask) { - return i ? i-1 : mask; -} - -#else -#error unknown architecture -#endif - - -#if SUPPORT_IGNORED_SELECTOR_CONSTANT -#error sorry not implemented -#endif - - -// copied from dispatch_atomic_maximally_synchronizing_barrier -// fixme verify that this barrier hack does in fact work here -#if __x86_64__ -#define mega_barrier() \ - do { unsigned long _clbr; __asm__ __volatile__( \ - "cpuid" \ - : "=a" (_clbr) : "0" (0) : "rbx", "rcx", "rdx", "cc", "memory" \ - ); } while(0) - -#elif __i386__ -#define mega_barrier() \ - do { unsigned long _clbr; __asm__ __volatile__( \ - "cpuid" \ - : "=a" (_clbr) : "0" (0) : "ebx", "ecx", "edx", "cc", "memory" \ - ); } while(0) - -#elif __arm__ || __arm64__ -#define mega_barrier() \ - __asm__ __volatile__( \ - "dsb ish" \ - : : : "memory") - -#else -#error unknown architecture -#endif - -#if __arm64__ - -// Use atomic double-word instructions to update cache entries. -// This requires cache buckets not cross cache line boundaries. -#define stp(onep, twop, destp) \ - __asm__ ("stp %[one], %[two], [%[dest]]" \ - : "=m" (((uint64_t *)(destp))[0]), \ - "=m" (((uint64_t *)(destp))[1]) \ - : [one] "r" (onep), \ - [two] "r" (twop), \ - [dest] "r" (destp) \ - : /* no clobbers */ \ - ) -#define ldp(onep, twop, srcp) \ - __asm__ ("ldp %[one], %[two], [%[src]]" \ - : [one] "=r" (onep), \ - [two] "=r" (twop) \ - : "m" (((uint64_t *)(srcp))[0]), \ - "m" (((uint64_t *)(srcp))[1]), \ - [src] "r" (srcp) \ - : /* no clobbers */ \ - ) - -#endif - - -// Class points to cache. SEL is key. Cache buckets store SEL+IMP. -// Caches are never built in the dyld shared cache. - -static inline mask_t cache_hash(cache_key_t key, mask_t mask) -{ - return (mask_t)(key & mask); -} - -cache_t *getCache(Class cls) -{ - assert(cls); - return &cls->cache; -} - -cache_key_t getKey(SEL sel) -{ - assert(sel); - return (cache_key_t)sel; -} - -#if __arm64__ - -void bucket_t::set(cache_key_t newKey, IMP newImp) -{ - assert(_key == 0 || _key == newKey); - - // LDP/STP guarantees that all observers get - // either key/imp or newKey/newImp - stp(newKey, newImp, this); -} - -#else - -void bucket_t::set(cache_key_t newKey, IMP newImp) -{ - assert(_key == 0 || _key == newKey); - - // objc_msgSend uses key and imp with no locks. - // It is safe for objc_msgSend to see new imp but NULL key - // (It will get a cache miss but not dispatch to the wrong place.) - // It is unsafe for objc_msgSend to see old imp and new key. - // Therefore we write new imp, wait a lot, then write new key. - - _imp = newImp; - - if (_key != newKey) { - mega_barrier(); - _key = newKey; - } -} - -#endif - -void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask) -{ - // objc_msgSend uses mask and buckets with no locks. - // It is safe for objc_msgSend to see new buckets but old mask. - // (It will get a cache miss but not overrun the buckets' bounds). - // It is unsafe for objc_msgSend to see old buckets and new mask. - // Therefore we write new buckets, wait a lot, then write new mask. - // objc_msgSend reads mask first, then buckets. - - // ensure other threads see buckets contents before buckets pointer - mega_barrier(); - - _buckets = newBuckets; - - // ensure other threads see new buckets before new mask - mega_barrier(); - - _mask = newMask; - _occupied = 0; -} - - -struct bucket_t *cache_t::buckets() -{ - return _buckets; -} - -mask_t cache_t::mask() -{ - return _mask; -} - -mask_t cache_t::occupied() -{ - return _occupied; -} - -void cache_t::incrementOccupied() -{ - _occupied++; -} - -void cache_t::initializeToEmpty() -{ - bzero(this, sizeof(*this)); - _buckets = (bucket_t *)&_objc_empty_cache; -} - - -mask_t cache_t::capacity() -{ - return mask() ? mask()+1 : 0; -} - - -#if CACHE_END_MARKER - -size_t cache_t::bytesForCapacity(uint32_t cap) -{ - // fixme put end marker inline when capacity+1 malloc is inefficient - return sizeof(bucket_t) * (cap + 1); -} - -bucket_t *cache_t::endMarker(struct bucket_t *b, uint32_t cap) -{ - // bytesForCapacity() chooses whether the end marker is inline or not - return (bucket_t *)((uintptr_t)b + bytesForCapacity(cap)) - 1; -} - -bucket_t *allocateBuckets(mask_t newCapacity) -{ - // Allocate one extra bucket to mark the end of the list. - // This can't overflow mask_t because newCapacity is a power of 2. - // fixme instead put the end mark inline when +1 is malloc-inefficient - bucket_t *newBuckets = (bucket_t *) - calloc(cache_t::bytesForCapacity(newCapacity), 1); - - bucket_t *end = cache_t::endMarker(newBuckets, newCapacity); - -#if __arm__ - // End marker's key is 1 and imp points BEFORE the first bucket. - // This saves an instruction in objc_msgSend. - end->setKey((cache_key_t)(uintptr_t)1); - end->setImp((IMP)(newBuckets - 1)); -#else - // End marker's key is 1 and imp points to the first bucket. - end->setKey((cache_key_t)(uintptr_t)1); - end->setImp((IMP)newBuckets); -#endif - - if (PrintCaches) recordNewCache(newCapacity); - - return newBuckets; -} - -#else - -size_t cache_t::bytesForCapacity(uint32_t cap) -{ - return sizeof(bucket_t) * cap; -} - -bucket_t *allocateBuckets(mask_t newCapacity) -{ - if (PrintCaches) recordNewCache(newCapacity); - - return (bucket_t *)calloc(cache_t::bytesForCapacity(newCapacity), 1); -} - -#endif - - -bucket_t *emptyBucketsForCapacity(mask_t capacity, bool allocate = true) -{ - cacheUpdateLock.assertLocked(); - - size_t bytes = cache_t::bytesForCapacity(capacity); - - // Use _objc_empty_cache if the buckets is small enough. - if (bytes <= EMPTY_BYTES) { - return (bucket_t *)&_objc_empty_cache; - } - - // Use shared empty buckets allocated on the heap. - static bucket_t **emptyBucketsList = nil; - static mask_t emptyBucketsListCount = 0; - - mask_t index = log2u(capacity); - - if (index >= emptyBucketsListCount) { - if (!allocate) return nil; - - mask_t newListCount = index + 1; - bucket_t *newBuckets = (bucket_t *)calloc(bytes, 1); - emptyBucketsList = (bucket_t**) - realloc(emptyBucketsList, newListCount * sizeof(bucket_t *)); - // Share newBuckets for every un-allocated size smaller than index. - // The array is therefore always fully populated. - for (mask_t i = emptyBucketsListCount; i < newListCount; i++) { - emptyBucketsList[i] = newBuckets; - } - emptyBucketsListCount = newListCount; - - if (PrintCaches) { - _objc_inform("CACHES: new empty buckets at %p (capacity %zu)", - newBuckets, (size_t)capacity); - } - } - - return emptyBucketsList[index]; -} - - -bool cache_t::isConstantEmptyCache() -{ - return - occupied() == 0 && - buckets() == emptyBucketsForCapacity(capacity(), false); -} - -bool cache_t::canBeFreed() -{ - return !isConstantEmptyCache(); -} - - -void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity) -{ - bool freeOld = canBeFreed(); - - bucket_t *oldBuckets = buckets(); - bucket_t *newBuckets = allocateBuckets(newCapacity); - - // Cache's old contents are not propagated. - // This is thought to save cache memory at the cost of extra cache fills. - // fixme re-measure this - - assert(newCapacity > 0); - assert((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1); - - setBucketsAndMask(newBuckets, newCapacity - 1); - - if (freeOld) { - cache_collect_free(oldBuckets, oldCapacity); - cache_collect(false); - } -} - - -void cache_t::bad_cache(id receiver, SEL sel, Class isa) -{ - // Log in separate steps in case the logging itself causes a crash. - _objc_inform_now_and_on_crash - ("Method cache corrupted. This may be a message to an " - "invalid object, or a memory error somewhere else."); - cache_t *cache = &isa->cache; - _objc_inform_now_and_on_crash - ("%s %p, SEL %p, isa %p, cache %p, buckets %p, " - "mask 0x%x, occupied 0x%x", - receiver ? "receiver" : "unused", receiver, - sel, isa, cache, cache->_buckets, - cache->_mask, cache->_occupied); - _objc_inform_now_and_on_crash - ("%s %zu bytes, buckets %zu bytes", - receiver ? "receiver" : "unused", malloc_size(receiver), - malloc_size(cache->_buckets)); - _objc_inform_now_and_on_crash - ("selector '%s'", sel_getName(sel)); - _objc_inform_now_and_on_crash - ("isa '%s'", isa->nameForLogging()); - _objc_fatal - ("Method cache corrupted."); -} - - -bucket_t * cache_t::find(cache_key_t k, id receiver) -{ - assert(k != 0); - - bucket_t *b = buckets(); - mask_t m = mask(); - mask_t begin = cache_hash(k, m); - mask_t i = begin; - do { - if (b[i].key() == 0 || b[i].key() == k) { - return &b[i]; - } - } while ((i = cache_next(i, m)) != begin); - - // hack - Class cls = (Class)((uintptr_t)this - offsetof(objc_class, cache)); - cache_t::bad_cache(receiver, (SEL)k, cls); -} - - -void cache_t::expand() -{ - cacheUpdateLock.assertLocked(); - - uint32_t oldCapacity = capacity(); - uint32_t newCapacity = oldCapacity ? oldCapacity*2 : INIT_CACHE_SIZE; - - if ((uint32_t)(mask_t)newCapacity != newCapacity) { - // mask overflow - can't grow further - // fixme this wastes one bit of mask - newCapacity = oldCapacity; - } - - reallocate(oldCapacity, newCapacity); -} - - -static void cache_fill_nolock(Class cls, SEL sel, IMP imp, id receiver) -{ - cacheUpdateLock.assertLocked(); - - // Never cache before +initialize is done - if (!cls->isInitialized()) return; - - // Make sure the entry wasn't added to the cache by some other thread - // before we grabbed the cacheUpdateLock. - if (cache_getImp(cls, sel)) return; - - cache_t *cache = getCache(cls); - cache_key_t key = getKey(sel); - - // Use the cache as-is if it is less than 3/4 full - mask_t newOccupied = cache->occupied() + 1; - mask_t capacity = cache->capacity(); - if (cache->isConstantEmptyCache()) { - // Cache is read-only. Replace it. - cache->reallocate(capacity, capacity ?: INIT_CACHE_SIZE); - } - else if (newOccupied <= capacity / 4 * 3) { - // Cache is less than 3/4 full. Use it as-is. - } - else { - // Cache is too full. Expand it. - cache->expand(); - } - - // Scan for the first unused slot and insert there. - // There is guaranteed to be an empty slot because the - // minimum size is 4 and we resized at 3/4 full. - bucket_t *bucket = cache->find(key, receiver); - if (bucket->key() == 0) cache->incrementOccupied(); - bucket->set(key, imp); -} - -void cache_fill(Class cls, SEL sel, IMP imp, id receiver) -{ -#if !DEBUG_TASK_THREADS - mutex_locker_t lock(cacheUpdateLock); - cache_fill_nolock(cls, sel, imp, receiver); -#else - _collecting_in_critical(); - return; -#endif -} - - -// Reset this entire cache to the uncached lookup by reallocating it. -// This must not shrink the cache - that breaks the lock-free scheme. -void cache_erase_nolock(Class cls) -{ - cacheUpdateLock.assertLocked(); - - cache_t *cache = getCache(cls); - - mask_t capacity = cache->capacity(); - if (capacity > 0 && cache->occupied() > 0) { - auto oldBuckets = cache->buckets(); - auto buckets = emptyBucketsForCapacity(capacity); - cache->setBucketsAndMask(buckets, capacity - 1); // also clears occupied - - cache_collect_free(oldBuckets, capacity); - cache_collect(false); - } -} - - -void cache_delete(Class cls) -{ - mutex_locker_t lock(cacheUpdateLock); - if (cls->cache.canBeFreed()) { - if (PrintCaches) recordDeadCache(cls->cache.capacity()); - free(cls->cache.buckets()); - } -} - - -/*********************************************************************** -* cache collection. -**********************************************************************/ - -#if !TARGET_OS_WIN32 - -// A sentinel (magic value) to report bad thread_get_state status. -// Must not be a valid PC. -// Must not be zero - thread_get_state() on a new thread returns PC == 0. -#define PC_SENTINEL 1 - -static uintptr_t _get_pc_for_thread(thread_t thread) -#if defined(__i386__) -{ - i386_thread_state_t state; - unsigned int count = i386_THREAD_STATE_COUNT; - kern_return_t okay = thread_get_state (thread, i386_THREAD_STATE, (thread_state_t)&state, &count); - return (okay == KERN_SUCCESS) ? state.__eip : PC_SENTINEL; -} -#elif defined(__x86_64__) -{ - x86_thread_state64_t state; - unsigned int count = x86_THREAD_STATE64_COUNT; - kern_return_t okay = thread_get_state (thread, x86_THREAD_STATE64, (thread_state_t)&state, &count); - return (okay == KERN_SUCCESS) ? state.__rip : PC_SENTINEL; -} -#elif defined(__arm__) -{ - arm_thread_state_t state; - unsigned int count = ARM_THREAD_STATE_COUNT; - kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE, (thread_state_t)&state, &count); - return (okay == KERN_SUCCESS) ? state.__pc : PC_SENTINEL; -} -#elif defined(__arm64__) -{ - arm_thread_state64_t state; - unsigned int count = ARM_THREAD_STATE64_COUNT; - kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE64, (thread_state_t)&state, &count); - return (okay == KERN_SUCCESS) ? state.__pc : PC_SENTINEL; -} -#else -{ -#error _get_pc_for_thread () not implemented for this architecture -} -#endif - -#endif - -/*********************************************************************** -* _collecting_in_critical. -* Returns TRUE if some thread is currently executing a cache-reading -* function. Collection of cache garbage is not allowed when a cache- -* reading function is in progress because it might still be using -* the garbage memory. -**********************************************************************/ -OBJC_EXPORT uintptr_t objc_entryPoints[]; -OBJC_EXPORT uintptr_t objc_exitPoints[]; - -static int _collecting_in_critical(void) -{ -#if TARGET_OS_WIN32 - return TRUE; -#else - thread_act_port_array_t threads; - unsigned number; - unsigned count; - kern_return_t ret; - int result; - - mach_port_t mythread = pthread_mach_thread_np(pthread_self()); - - // Get a list of all the threads in the current task -#if !DEBUG_TASK_THREADS - ret = task_threads(mach_task_self(), &threads, &number); -#else - ret = objc_task_threads(mach_task_self(), &threads, &number); -#endif - - if (ret != KERN_SUCCESS) { - // See DEBUG_TASK_THREADS below to help debug this. - _objc_fatal("task_threads failed (result 0x%x)\n", ret); - } - - // Check whether any thread is in the cache lookup code - result = FALSE; - for (count = 0; count < number; count++) - { - int region; - uintptr_t pc; - - // Don't bother checking ourselves - if (threads[count] == mythread) - continue; - - // Find out where thread is executing - pc = _get_pc_for_thread (threads[count]); - - // Check for bad status, and if so, assume the worse (can't collect) - if (pc == PC_SENTINEL) - { - result = TRUE; - goto done; - } - - // Check whether it is in the cache lookup code - for (region = 0; objc_entryPoints[region] != 0; region++) - { - if ((pc >= objc_entryPoints[region]) && - (pc <= objc_exitPoints[region])) - { - result = TRUE; - goto done; - } - } - } - - done: - // Deallocate the port rights for the threads - for (count = 0; count < number; count++) { - mach_port_deallocate(mach_task_self (), threads[count]); - } - - // Deallocate the thread list - vm_deallocate (mach_task_self (), (vm_address_t) threads, sizeof(threads[0]) * number); - - // Return our finding - return result; -#endif -} - - -/*********************************************************************** -* _garbage_make_room. Ensure that there is enough room for at least -* one more ref in the garbage. -**********************************************************************/ - -// amount of memory represented by all refs in the garbage -static size_t garbage_byte_size = 0; - -// do not empty the garbage until garbage_byte_size gets at least this big -static size_t garbage_threshold = 32*1024; - -// table of refs to free -static bucket_t **garbage_refs = 0; - -// current number of refs in garbage_refs -static size_t garbage_count = 0; - -// capacity of current garbage_refs -static size_t garbage_max = 0; - -// capacity of initial garbage_refs -enum { - INIT_GARBAGE_COUNT = 128 -}; - -static void _garbage_make_room(void) -{ - static int first = 1; - - // Create the collection table the first time it is needed - if (first) - { - first = 0; - garbage_refs = (bucket_t**) - malloc(INIT_GARBAGE_COUNT * sizeof(void *)); - garbage_max = INIT_GARBAGE_COUNT; - } - - // Double the table if it is full - else if (garbage_count == garbage_max) - { - garbage_refs = (bucket_t**) - realloc(garbage_refs, garbage_max * 2 * sizeof(void *)); - garbage_max *= 2; - } -} - - -/*********************************************************************** -* cache_collect_free. Add the specified malloc'd memory to the list -* of them to free at some later point. -* size is used for the collection threshold. It does not have to be -* precisely the block's size. -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -static void cache_collect_free(bucket_t *data, mask_t capacity) -{ - cacheUpdateLock.assertLocked(); - - if (PrintCaches) recordDeadCache(capacity); - - _garbage_make_room (); - garbage_byte_size += cache_t::bytesForCapacity(capacity); - garbage_refs[garbage_count++] = data; -} - - -/*********************************************************************** -* cache_collect. Try to free accumulated dead caches. -* collectALot tries harder to free memory. -* Cache locks: cacheUpdateLock must be held by the caller. -**********************************************************************/ -void cache_collect(bool collectALot) -{ - cacheUpdateLock.assertLocked(); - - // Done if the garbage is not full - if (garbage_byte_size < garbage_threshold && !collectALot) { - return; - } - - // Synchronize collection with objc_msgSend and other cache readers - if (!collectALot) { - if (_collecting_in_critical ()) { - // objc_msgSend (or other cache reader) is currently looking in - // the cache and might still be using some garbage. - if (PrintCaches) { - _objc_inform ("CACHES: not collecting; " - "objc_msgSend in progress"); - } - return; - } - } - else { - // No excuses. - while (_collecting_in_critical()) - ; - } - - // No cache readers in progress - garbage is now deletable - - // Log our progress - if (PrintCaches) { - cache_collections++; - _objc_inform ("CACHES: COLLECTING %zu bytes (%zu allocations, %zu collections)", garbage_byte_size, cache_allocations, cache_collections); - } - - // Dispose all refs now in the garbage - while (garbage_count--) { - free(garbage_refs[garbage_count]); - } - - // Clear the garbage count and total size indicator - garbage_count = 0; - garbage_byte_size = 0; - - if (PrintCaches) { - size_t i; - size_t total_count = 0; - size_t total_size = 0; - - for (i = 0; i < countof(cache_counts); i++) { - int count = cache_counts[i]; - int slots = 1 << i; - size_t size = count * slots * sizeof(bucket_t); - - if (!count) continue; - - _objc_inform("CACHES: %4d slots: %4d caches, %6zu bytes", - slots, count, size); - - total_count += count; - total_size += size; - } - - _objc_inform("CACHES: total: %4zu caches, %6zu bytes", - total_count, total_size); - } -} - - -/*********************************************************************** -* objc_task_threads -* Replacement for task_threads(). Define DEBUG_TASK_THREADS to debug -* crashes when task_threads() is failing. -* -* A failure in task_threads() usually means somebody has botched their -* Mach or MIG traffic. For example, somebody's error handling was wrong -* and they left a message queued on the MIG reply port for task_threads() -* to trip over. -* -* The code below is a modified version of task_threads(). It logs -* the msgh_id of the reply message. The msgh_id can identify the sender -* of the message, which can help pinpoint the faulty code. -* DEBUG_TASK_THREADS also calls collecting_in_critical() during every -* message dispatch, which can increase reproducibility of bugs. -* -* This code can be regenerated by running -* `mig /usr/include/mach/task.defs`. -**********************************************************************/ -#if DEBUG_TASK_THREADS - -#include <mach/mach.h> -#include <mach/message.h> -#include <mach/mig.h> - -#define __MIG_check__Reply__task_subsystem__ 1 -#define mig_internal static inline -#define __DeclareSendRpc(a, b) -#define __BeforeSendRpc(a, b) -#define __AfterSendRpc(a, b) -#define msgh_request_port msgh_remote_port -#define msgh_reply_port msgh_local_port - -#ifndef __MachMsgErrorWithTimeout -#define __MachMsgErrorWithTimeout(_R_) { \ - switch (_R_) { \ - case MACH_SEND_INVALID_DATA: \ - case MACH_SEND_INVALID_DEST: \ - case MACH_SEND_INVALID_HEADER: \ - mig_put_reply_port(InP->Head.msgh_reply_port); \ - break; \ - case MACH_SEND_TIMED_OUT: \ - case MACH_RCV_TIMED_OUT: \ - default: \ - mig_dealloc_reply_port(InP->Head.msgh_reply_port); \ - } \ - } -#endif /* __MachMsgErrorWithTimeout */ - -#ifndef __MachMsgErrorWithoutTimeout -#define __MachMsgErrorWithoutTimeout(_R_) { \ - switch (_R_) { \ - case MACH_SEND_INVALID_DATA: \ - case MACH_SEND_INVALID_DEST: \ - case MACH_SEND_INVALID_HEADER: \ - mig_put_reply_port(InP->Head.msgh_reply_port); \ - break; \ - default: \ - mig_dealloc_reply_port(InP->Head.msgh_reply_port); \ - } \ - } -#endif /* __MachMsgErrorWithoutTimeout */ - - -#if ( __MigTypeCheck ) -#if __MIG_check__Reply__task_subsystem__ -#if !defined(__MIG_check__Reply__task_threads_t__defined) -#define __MIG_check__Reply__task_threads_t__defined - -mig_internal kern_return_t __MIG_check__Reply__task_threads_t(__Reply__task_threads_t *Out0P) -{ - - typedef __Reply__task_threads_t __Reply; - boolean_t msgh_simple; -#if __MigTypeCheck - unsigned int msgh_size; -#endif /* __MigTypeCheck */ - if (Out0P->Head.msgh_id != 3502) { - if (Out0P->Head.msgh_id == MACH_NOTIFY_SEND_ONCE) - { return MIG_SERVER_DIED; } - else - { return MIG_REPLY_MISMATCH; } - } - - msgh_simple = !(Out0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX); -#if __MigTypeCheck - msgh_size = Out0P->Head.msgh_size; - - if ((msgh_simple || Out0P->msgh_body.msgh_descriptor_count != 1 || - msgh_size != (mach_msg_size_t)sizeof(__Reply)) && - (!msgh_simple || msgh_size != (mach_msg_size_t)sizeof(mig_reply_error_t) || - ((mig_reply_error_t *)Out0P)->RetCode == KERN_SUCCESS)) - { return MIG_TYPE_ERROR ; } -#endif /* __MigTypeCheck */ - - if (msgh_simple) { - return ((mig_reply_error_t *)Out0P)->RetCode; - } - -#if __MigTypeCheck - if (Out0P->act_list.type != MACH_MSG_OOL_PORTS_DESCRIPTOR || - Out0P->act_list.disposition != 17) { - return MIG_TYPE_ERROR; - } -#endif /* __MigTypeCheck */ - - return MACH_MSG_SUCCESS; -} -#endif /* !defined(__MIG_check__Reply__task_threads_t__defined) */ -#endif /* __MIG_check__Reply__task_subsystem__ */ -#endif /* ( __MigTypeCheck ) */ - - -/* Routine task_threads */ -static kern_return_t objc_task_threads -( - task_t target_task, - thread_act_array_t *act_list, - mach_msg_type_number_t *act_listCnt -) -{ - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - } Request; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - /* start of the kernel processed data */ - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t act_list; - /* end of the kernel processed data */ - NDR_record_t NDR; - mach_msg_type_number_t act_listCnt; - mach_msg_trailer_t trailer; - } Reply; -#ifdef __MigPackStructs -#pragma pack() -#endif - -#ifdef __MigPackStructs -#pragma pack(4) -#endif - typedef struct { - mach_msg_header_t Head; - /* start of the kernel processed data */ - mach_msg_body_t msgh_body; - mach_msg_ool_ports_descriptor_t act_list; - /* end of the kernel processed data */ - NDR_record_t NDR; - mach_msg_type_number_t act_listCnt; - } __Reply; -#ifdef __MigPackStructs -#pragma pack() -#endif - /* - * typedef struct { - * mach_msg_header_t Head; - * NDR_record_t NDR; - * kern_return_t RetCode; - * } mig_reply_error_t; - */ - - union { - Request In; - Reply Out; - } Mess; - - Request *InP = &Mess.In; - Reply *Out0P = &Mess.Out; - - mach_msg_return_t msg_result; - -#ifdef __MIG_check__Reply__task_threads_t__defined - kern_return_t check_result; -#endif /* __MIG_check__Reply__task_threads_t__defined */ - - __DeclareSendRpc(3402, "task_threads") - - InP->Head.msgh_bits = - MACH_MSGH_BITS(19, MACH_MSG_TYPE_MAKE_SEND_ONCE); - /* msgh_size passed as argument */ - InP->Head.msgh_request_port = target_task; - InP->Head.msgh_reply_port = mig_get_reply_port(); - InP->Head.msgh_id = 3402; - - __BeforeSendRpc(3402, "task_threads") - msg_result = mach_msg(&InP->Head, MACH_SEND_MSG|MACH_RCV_MSG|MACH_MSG_OPTION_NONE, (mach_msg_size_t)sizeof(Request), (mach_msg_size_t)sizeof(Reply), InP->Head.msgh_reply_port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); - __AfterSendRpc(3402, "task_threads") - if (msg_result != MACH_MSG_SUCCESS) { - _objc_inform("task_threads received unexpected reply msgh_id 0x%zx", - (size_t)Out0P->Head.msgh_id); - __MachMsgErrorWithoutTimeout(msg_result); - { return msg_result; } - } - - -#if defined(__MIG_check__Reply__task_threads_t__defined) - check_result = __MIG_check__Reply__task_threads_t((__Reply__task_threads_t *)Out0P); - if (check_result != MACH_MSG_SUCCESS) - { return check_result; } -#endif /* defined(__MIG_check__Reply__task_threads_t__defined) */ - - *act_list = (thread_act_array_t)(Out0P->act_list.address); - *act_listCnt = Out0P->act_listCnt; - - return KERN_SUCCESS; -} - -// DEBUG_TASK_THREADS -#endif - - -// __OBJC2__ -#endif diff --git a/objc/objc-runtime/runtime/objc-class-old.mm b/objc/objc-runtime/runtime/objc-class-old.mm deleted file mode 100644 index e07080b..0000000 --- a/objc/objc-runtime/runtime/objc-class-old.mm +++ /dev/null @@ -1,2642 +0,0 @@ -/* - * Copyright (c) 1999-2009 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@ - */ - -/*********************************************************************** -* objc-class-old.m -* Support for old-ABI classes, methods, and categories. -**********************************************************************/ - -#if !__OBJC2__ - -#include "objc-private.h" -#include "objc-runtime-old.h" -#include "objc-file-old.h" -#include "objc-cache-old.h" - -static Method _class_getMethod(Class cls, SEL sel); -static Method _class_getMethodNoSuper(Class cls, SEL sel); -static Method _class_getMethodNoSuper_nolock(Class cls, SEL sel); -static void flush_caches(Class cls, bool flush_meta); - - -// Freed objects have their isa set to point to this dummy class. -// This avoids the need to check for Nil classes in the messenger. -static const void* freedObjectClass[12] = -{ - Nil, // isa - Nil, // superclass - "FREED(id)", // name - 0, // version - 0, // info - 0, // instance_size - nil, // ivars - nil, // methodLists - (Cache) &_objc_empty_cache, // cache - nil, // protocols - nil, // ivar_layout; - nil // ext -}; - - -/*********************************************************************** -* _class_getFreedObjectClass. Return a pointer to the dummy freed -* object class. Freed objects get their isa pointers replaced with -* a pointer to the freedObjectClass, so that we can catch usages of -* the freed object. -**********************************************************************/ -static Class _class_getFreedObjectClass(void) -{ - return (Class)freedObjectClass; -} - - -/*********************************************************************** -* _objc_getFreedObjectClass. Return a pointer to the dummy freed -* object class. Freed objects get their isa pointers replaced with -* a pointer to the freedObjectClass, so that we can catch usages of -* the freed object. -**********************************************************************/ -Class _objc_getFreedObjectClass(void) -{ - return _class_getFreedObjectClass(); -} - - -static void allocateExt(Class cls) -{ - if (! (cls->info & CLS_EXT)) { - _objc_inform("class '%s' needs to be recompiled", cls->name); - return; - } - if (!cls->ext) { - uint32_t size = (uint32_t)sizeof(old_class_ext); - cls->ext = (old_class_ext *)calloc(size, 1); - cls->ext->size = size; - } -} - - -static inline old_method *_findNamedMethodInList(old_method_list * mlist, const char *meth_name) { - int i; - if (!mlist) return nil; - if (ignoreSelectorNamed(meth_name)) return nil; - for (i = 0; i < mlist->method_count; i++) { - old_method *m = &mlist->method_list[i]; - if (0 == strcmp((const char *)(m->method_name), meth_name)) { - return m; - } - } - return nil; -} - - -/*********************************************************************** -* Method list fixup markers. -* mlist->obsolete == fixed_up_method_list marks method lists with real SELs -* versus method lists with un-uniqued char*. -* PREOPTIMIZED VERSION: -* Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP -* dyld shared cache sets this for method lists it preoptimizes. -* UN-PREOPTIMIZED VERSION -* Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP_outside_dyld -* dyld shared cache uses OBJC_FIXED_UP, but those aren't trusted. -**********************************************************************/ -#define OBJC_FIXED_UP ((void *)1771) -#define OBJC_FIXED_UP_outside_dyld ((void *)1773) -static void *fixed_up_method_list = OBJC_FIXED_UP; - -// sel_init() decided that selectors in the dyld shared cache are untrustworthy -void disableSharedCacheOptimizations(void) -{ - fixed_up_method_list = OBJC_FIXED_UP_outside_dyld; -} - -/*********************************************************************** -* fixupSelectorsInMethodList -* Uniques selectors in the given method list. -* Also replaces imps for GC-ignored selectors -* The given method list must be non-nil and not already fixed-up. -* If the class was loaded from a bundle: -* fixes up the given list in place with heap-allocated selector strings -* If the class was not from a bundle: -* allocates a copy of the method list, fixes up the copy, and returns -* the copy. The given list is unmodified. -* -* If cls is already in use, methodListLock must be held by the caller. -**********************************************************************/ -static old_method_list *fixupSelectorsInMethodList(Class cls, old_method_list *mlist) -{ - int i; - size_t size; - old_method *method; - old_method_list *old_mlist; - - if ( ! mlist ) return nil; - if ( mlist->obsolete == fixed_up_method_list ) { - // method list OK - } else { - bool isBundle = cls->info & CLS_FROM_BUNDLE; - if (!isBundle) { - old_mlist = mlist; - size = sizeof(old_method_list) - sizeof(old_method) + old_mlist->method_count * sizeof(old_method); - mlist = (old_method_list *)malloc(size); - memmove(mlist, old_mlist, size); - } else { - // Mach-O bundles are fixed up in place. - // This prevents leaks when a bundle is unloaded. - } - sel_lock(); - for ( i = 0; i < mlist->method_count; i += 1 ) { - method = &mlist->method_list[i]; - method->method_name = - sel_registerNameNoLock((const char *)method->method_name, isBundle); // Always copy selector data from bundles. - - if (ignoreSelector(method->method_name)) { - method->method_imp = (IMP)&_objc_ignored_method; - } - } - sel_unlock(); - mlist->obsolete = fixed_up_method_list; - } - return mlist; -} - - -/*********************************************************************** -* nextMethodList -* Returns successive method lists from the given class. -* Method lists are returned in method search order (i.e. highest-priority -* implementations first). -* All necessary method list fixups are performed, so the -* returned method list is fully-constructed. -* -* If cls is already in use, methodListLock must be held by the caller. -* For full thread-safety, methodListLock must be continuously held by the -* caller across all calls to nextMethodList(). If the lock is released, -* the bad results listed in class_nextMethodList() may occur. -* -* void *iterator = nil; -* old_method_list *mlist; -* mutex_locker_t lock(methodListLock); -* while ((mlist = nextMethodList(cls, &iterator))) { -* // do something with mlist -* } -**********************************************************************/ -static old_method_list *nextMethodList(Class cls, - void **it) -{ - uintptr_t index = *(uintptr_t *)it; - old_method_list **resultp; - - if (index == 0) { - // First call to nextMethodList. - if (!cls->methodLists) { - resultp = nil; - } else if (cls->info & CLS_NO_METHOD_ARRAY) { - resultp = (old_method_list **)&cls->methodLists; - } else { - resultp = &cls->methodLists[0]; - if (!*resultp || *resultp == END_OF_METHODS_LIST) { - resultp = nil; - } - } - } else { - // Subsequent call to nextMethodList. - if (!cls->methodLists) { - resultp = nil; - } else if (cls->info & CLS_NO_METHOD_ARRAY) { - resultp = nil; - } else { - resultp = &cls->methodLists[index]; - if (!*resultp || *resultp == END_OF_METHODS_LIST) { - resultp = nil; - } - } - } - - // resultp now is nil, meaning there are no more method lists, - // OR the address of the method list pointer to fix up and return. - - if (resultp) { - if (*resultp) { - *resultp = fixupSelectorsInMethodList(cls, *resultp); - } - *it = (void *)(index + 1); - return *resultp; - } else { - *it = 0; - return nil; - } -} - - -/* These next three functions are the heart of ObjC method lookup. - * If the class is currently in use, methodListLock must be held by the caller. - */ -static inline old_method *_findMethodInList(old_method_list * mlist, SEL sel) { - int i; - if (!mlist) return nil; - for (i = 0; i < mlist->method_count; i++) { - old_method *m = &mlist->method_list[i]; - if (m->method_name == sel) { - return m; - } - } - return nil; -} - -static inline old_method * _findMethodInClass(Class cls, SEL sel) __attribute__((always_inline)); -static inline old_method * _findMethodInClass(Class cls, SEL sel) { - // Flattened version of nextMethodList(). The optimizer doesn't - // do a good job with hoisting the conditionals out of the loop. - // Conceptually, this looks like: - // while ((mlist = nextMethodList(cls, &iterator))) { - // old_method *m = _findMethodInList(mlist, sel); - // if (m) return m; - // } - - if (!cls->methodLists) { - // No method lists. - return nil; - } - else if (cls->info & CLS_NO_METHOD_ARRAY) { - // One method list. - old_method_list **mlistp; - mlistp = (old_method_list **)&cls->methodLists; - *mlistp = fixupSelectorsInMethodList(cls, *mlistp); - return _findMethodInList(*mlistp, sel); - } - else { - // Multiple method lists. - old_method_list **mlistp; - for (mlistp = cls->methodLists; - *mlistp != nil && *mlistp != END_OF_METHODS_LIST; - mlistp++) - { - old_method *m; - *mlistp = fixupSelectorsInMethodList(cls, *mlistp); - m = _findMethodInList(*mlistp, sel); - if (m) return m; - } - return nil; - } -} - -static inline old_method * _getMethod(Class cls, SEL sel) { - for (; cls; cls = cls->superclass) { - old_method *m; - m = _findMethodInClass(cls, sel); - if (m) return m; - } - return nil; -} - - -// fixme for gc debugging temporary use -IMP findIMPInClass(Class cls, SEL sel) -{ - old_method *m = _findMethodInClass(cls, sel); - if (m) return m->method_imp; - else return nil; -} - - -/*********************************************************************** -* _freedHandler. -**********************************************************************/ -static void _freedHandler(id obj, SEL sel) -{ - __objc_error (obj, "message %s sent to freed object=%p", - sel_getName(sel), (void*)obj); -} - - -/*********************************************************************** -* log_and_fill_cache -* Log this method call. If the logger permits it, fill the method cache. -* cls is the method whose cache should be filled. -* implementer is the class that owns the implementation in question. -**********************************************************************/ -static void -log_and_fill_cache(Class cls, Class implementer, Method meth, SEL sel) -{ -#if SUPPORT_MESSAGE_LOGGING - if (objcMsgLogEnabled) { - bool cacheIt = logMessageSend(implementer->isMetaClass(), - cls->nameForLogging(), - implementer->nameForLogging(), - sel); - if (!cacheIt) return; - } -#endif - _cache_fill (cls, meth, sel); -} - - -/*********************************************************************** -* _class_lookupMethodAndLoadCache. -* Method lookup for dispatchers ONLY. OTHER CODE SHOULD USE lookUpImp(). -* This lookup avoids optimistic cache scan because the dispatcher -* already tried that. -**********************************************************************/ -IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls) -{ - return lookUpImpOrForward(cls, sel, obj, - YES/*initialize*/, NO/*cache*/, YES/*resolver*/); -} - - -/*********************************************************************** -* lookUpImpOrForward. -* The standard IMP lookup. -* initialize==NO tries to avoid +initialize (but sometimes fails) -* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere) -* Most callers should use initialize==YES and cache==YES. -* inst is an instance of cls or a subclass thereof, or nil if none is known. -* If cls is an un-initialized metaclass then a non-nil inst is faster. -* May return _objc_msgForward_impcache. IMPs destined for external use -* must be converted to _objc_msgForward or _objc_msgForward_stret. -* If you don't want forwarding at all, use lookUpImpOrNil() instead. -**********************************************************************/ -IMP lookUpImpOrForward(Class cls, SEL sel, id inst, - bool initialize, bool cache, bool resolver) -{ - Class curClass; - IMP methodPC = nil; - Method meth; - bool triedResolver = NO; - - methodListLock.assertUnlocked(); - - // Optimistic cache lookup - if (cache) { - methodPC = _cache_getImp(cls, sel); - if (methodPC) return methodPC; - } - - // Check for freed class - if (cls == _class_getFreedObjectClass()) - return (IMP) _freedHandler; - - // Check for +initialize - if (initialize && !cls->isInitialized()) { - _class_initialize (_class_getNonMetaClass(cls, inst)); - // If sel == initialize, _class_initialize will send +initialize and - // then the messenger will send +initialize again after this - // procedure finishes. Of course, if this is not being called - // from the messenger then it won't happen. 2778172 - } - - // The lock is held to make method-lookup + cache-fill atomic - // with respect to method addition. Otherwise, a category could - // be added but ignored indefinitely because the cache was re-filled - // with the old value after the cache flush on behalf of the category. - retry: - methodListLock.lock(); - - // Ignore GC selectors - if (ignoreSelector(sel)) { - methodPC = _cache_addIgnoredEntry(cls, sel); - goto done; - } - - // Try this class's cache. - - methodPC = _cache_getImp(cls, sel); - if (methodPC) goto done; - - // Try this class's method lists. - - meth = _class_getMethodNoSuper_nolock(cls, sel); - if (meth) { - log_and_fill_cache(cls, cls, meth, sel); - methodPC = method_getImplementation(meth); - goto done; - } - - // Try superclass caches and method lists. - - curClass = cls; - while ((curClass = curClass->superclass)) { - // Superclass cache. - meth = _cache_getMethod(curClass, sel, _objc_msgForward_impcache); - if (meth) { - if (meth != (Method)1) { - // Found the method in a superclass. Cache it in this class. - log_and_fill_cache(cls, curClass, meth, sel); - methodPC = method_getImplementation(meth); - goto done; - } - else { - // Found a forward:: entry in a superclass. - // Stop searching, but don't cache yet; call method - // resolver for this class first. - break; - } - } - - // Superclass method list. - meth = _class_getMethodNoSuper_nolock(curClass, sel); - if (meth) { - log_and_fill_cache(cls, curClass, meth, sel); - methodPC = method_getImplementation(meth); - goto done; - } - } - - // No implementation found. Try method resolver once. - - if (resolver && !triedResolver) { - methodListLock.unlock(); - _class_resolveMethod(cls, sel, inst); - triedResolver = YES; - goto retry; - } - - // No implementation found, and method resolver didn't help. - // Use forwarding. - - _cache_addForwardEntry(cls, sel); - methodPC = _objc_msgForward_impcache; - - done: - methodListLock.unlock(); - - // paranoia: look for ignored selectors with non-ignored implementations - assert(!(ignoreSelector(sel) && methodPC != (IMP)&_objc_ignored_method)); - - return methodPC; -} - - -/*********************************************************************** -* lookUpImpOrNil. -* Like lookUpImpOrForward, but returns nil instead of _objc_msgForward_impcache -**********************************************************************/ -IMP lookUpImpOrNil(Class cls, SEL sel, id inst, - bool initialize, bool cache, bool resolver) -{ - IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver); - if (imp == _objc_msgForward_impcache) return nil; - else return imp; -} - - -/*********************************************************************** -* lookupMethodInClassAndLoadCache. -* Like _class_lookupMethodAndLoadCache, but does not search superclasses. -* Caches and returns objc_msgForward if the method is not found in the class. -**********************************************************************/ -IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel) -{ - Method meth; - IMP imp; - - // fixme this still has the method list vs method cache race - // because it doesn't hold a lock across lookup+cache_fill, - // but it's only used for .cxx_construct/destruct and we assume - // categories don't change them. - - // Search cache first. - imp = _cache_getImp(cls, sel); - if (imp) return imp; - - // Cache miss. Search method list. - - meth = _class_getMethodNoSuper(cls, sel); - - if (meth) { - // Hit in method list. Cache it. - _cache_fill(cls, meth, sel); - return method_getImplementation(meth); - } else { - // Miss in method list. Cache objc_msgForward. - _cache_addForwardEntry(cls, sel); - return _objc_msgForward_impcache; - } -} - - -/*********************************************************************** -* class_getVariable. Return the named instance variable. -**********************************************************************/ - -Ivar _class_getVariable(Class cls, const char *name, Class *memberOf) -{ - for (; cls != Nil; cls = cls->superclass) { - int i; - - // Skip class having no ivars - if (!cls->ivars) continue; - - for (i = 0; i < cls->ivars->ivar_count; i++) { - // Check this ivar's name. Be careful because the - // compiler generates ivar entries with nil ivar_name - // (e.g. for anonymous bit fields). - old_ivar *ivar = &cls->ivars->ivar_list[i]; - if (ivar->ivar_name && 0 == strcmp(name, ivar->ivar_name)) { - if (memberOf) *memberOf = cls; - return (Ivar)ivar; - } - } - } - - // Not found - return nil; -} - - -old_property * -property_list_nth(const old_property_list *plist, uint32_t i) -{ - return (old_property *)(i*plist->entsize + (char *)&plist->first); -} - -old_property ** -copyPropertyList(old_property_list *plist, unsigned int *outCount) -{ - old_property **result = nil; - unsigned int count = 0; - - if (plist) { - count = plist->count; - } - - if (count > 0) { - unsigned int i; - result = (old_property **)malloc((count+1) * sizeof(old_property *)); - - for (i = 0; i < count; i++) { - result[i] = property_list_nth(plist, i); - } - result[i] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -static old_property_list * -nextPropertyList(Class cls, uintptr_t *indexp) -{ - old_property_list *result = nil; - - classLock.assertLocked(); - if (! ((cls->info & CLS_EXT) && cls->ext)) { - // No class ext - result = nil; - } else if (!cls->ext->propertyLists) { - // No property lists - result = nil; - } else if (cls->info & CLS_NO_PROPERTY_ARRAY) { - // Only one property list - if (*indexp == 0) { - result = (old_property_list *)cls->ext->propertyLists; - } else { - result = nil; - } - } else { - // More than one property list - result = cls->ext->propertyLists[*indexp]; - } - - if (result) { - ++*indexp; - return result; - } else { - *indexp = 0; - return nil; - } -} - - -/*********************************************************************** -* class_getIvarLayout -* nil means all-scanned. "" means non-scanned. -**********************************************************************/ -const uint8_t * -class_getIvarLayout(Class cls) -{ - if (cls && (cls->info & CLS_EXT)) { - return cls->ivar_layout; - } else { - return nil; // conservative scan - } -} - - -/*********************************************************************** -* class_getWeakIvarLayout -* nil means no weak ivars. -**********************************************************************/ -const uint8_t * -class_getWeakIvarLayout(Class cls) -{ - if (cls && (cls->info & CLS_EXT) && cls->ext) { - return cls->ext->weak_ivar_layout; - } else { - return nil; // no weak ivars - } -} - - -/*********************************************************************** -* class_setIvarLayout -* nil means all-scanned. "" means non-scanned. -**********************************************************************/ -void class_setIvarLayout(Class cls, const uint8_t *layout) -{ - if (!cls) return; - - if (! (cls->info & CLS_EXT)) { - _objc_inform("class '%s' needs to be recompiled", cls->name); - return; - } - - // fixme leak - cls->ivar_layout = ustrdupMaybeNil(layout); -} - -// SPI: Instance-specific object layout. - -void _class_setIvarLayoutAccessor(Class cls, const uint8_t* (*accessor) (id object)) { - if (!cls) return; - - if (! (cls->info & CLS_EXT)) { - _objc_inform("class '%s' needs to be recompiled", cls->name); - return; - } - - // fixme leak - cls->ivar_layout = (const uint8_t *)accessor; - cls->setInfo(CLS_HAS_INSTANCE_SPECIFIC_LAYOUT); -} - -const uint8_t *_object_getIvarLayout(Class cls, id object) { - if (cls && (cls->info & CLS_EXT)) { - const uint8_t* layout = cls->ivar_layout; - if (cls->info & CLS_HAS_INSTANCE_SPECIFIC_LAYOUT) { - const uint8_t* (*accessor) (id object) = (const uint8_t* (*)(id))layout; - layout = accessor(object); - } - return layout; - } else { - return nil; - } -} - -/*********************************************************************** -* class_setWeakIvarLayout -* nil means no weak ivars. -**********************************************************************/ -void class_setWeakIvarLayout(Class cls, const uint8_t *layout) -{ - if (!cls) return; - - mutex_locker_t lock(classLock); - - allocateExt(cls); - - // fixme leak - cls->ext->weak_ivar_layout = ustrdupMaybeNil(layout); -} - - -/*********************************************************************** -* class_setVersion. Record the specified version with the class. -**********************************************************************/ -void class_setVersion(Class cls, int version) -{ - if (!cls) return; - cls->version = version; -} - -/*********************************************************************** -* class_getVersion. Return the version recorded with the class. -**********************************************************************/ -int class_getVersion(Class cls) -{ - if (!cls) return 0; - return (int)cls->version; -} - - -/*********************************************************************** -* class_getName. -**********************************************************************/ -const char *class_getName(Class cls) -{ - if (!cls) return "nil"; - else return cls->demangledName(); -} - - -/*********************************************************************** -* _class_getNonMetaClass. -* Return the ordinary class for this class or metaclass. -* Used by +initialize. -**********************************************************************/ -Class _class_getNonMetaClass(Class cls, id obj) -{ - // fixme ick - if (cls->isMetaClass()) { - if (cls->info & CLS_CONSTRUCTING) { - // Class is under construction and isn't in the class_hash, - // so objc_getClass doesn't work. - cls = obj; // fixme this may be nil in some paths - } - else if (strncmp(cls->name, "_%", 2) == 0) { - // Posee's meta's name is smashed and isn't in the class_hash, - // so objc_getClass doesn't work. - const char *baseName = strchr(cls->name, '%'); // get posee's real name - cls = objc_getClass(baseName); - } - else { - cls = objc_getClass(cls->name); - } - assert(cls); - } - - return cls; -} - - -Cache _class_getCache(Class cls) -{ - return cls->cache; -} - -void _class_setCache(Class cls, Cache cache) -{ - cls->cache = cache; -} - -const char *_category_getName(Category cat) -{ - return oldcategory(cat)->category_name; -} - -const char *_category_getClassName(Category cat) -{ - return oldcategory(cat)->class_name; -} - -Class _category_getClass(Category cat) -{ - return objc_getClass(oldcategory(cat)->class_name); -} - -IMP _category_getLoadMethod(Category cat) -{ - old_method_list *mlist = oldcategory(cat)->class_methods; - if (mlist) { - return lookupNamedMethodInMethodList(mlist, "load"); - } else { - return nil; - } -} - - - -/*********************************************************************** -* class_nextMethodList. -* External version of nextMethodList(). -* -* This function is not fully thread-safe. A series of calls to -* class_nextMethodList() may fail if methods are added to or removed -* from the class between calls. -* If methods are added between calls to class_nextMethodList(), it may -* return previously-returned method lists again, and may fail to return -* newly-added lists. -* If methods are removed between calls to class_nextMethodList(), it may -* omit surviving method lists or simply crash. -**********************************************************************/ -OBJC_EXPORT struct objc_method_list *class_nextMethodList(Class cls, void **it) -{ - OBJC_WARN_DEPRECATED; - - mutex_locker_t lock(methodListLock); - return (struct objc_method_list *) nextMethodList(cls, it); -} - - -/*********************************************************************** -* class_addMethods. -* -* Formerly class_addInstanceMethods () -**********************************************************************/ -OBJC_EXPORT void class_addMethods(Class cls, struct objc_method_list *meths) -{ - OBJC_WARN_DEPRECATED; - - // Add the methods. - { - mutex_locker_t lock(methodListLock); - _objc_insertMethods(cls, (old_method_list *)meths, nil); - } - - // Must flush when dynamically adding methods. No need to flush - // all the class method caches. If cls is a meta class, though, - // this will still flush it and any of its sub-meta classes. - flush_caches (cls, NO); -} - - -/*********************************************************************** -* class_removeMethods. -**********************************************************************/ -OBJC_EXPORT void class_removeMethods(Class cls, struct objc_method_list *meths) -{ - OBJC_WARN_DEPRECATED; - - // Remove the methods - { - mutex_locker_t lock(methodListLock); - _objc_removeMethods(cls, (old_method_list *)meths); - } - - // Must flush when dynamically removing methods. No need to flush - // all the class method caches. If cls is a meta class, though, - // this will still flush it and any of its sub-meta classes. - flush_caches (cls, NO); -} - -/*********************************************************************** -* lookupNamedMethodInMethodList -* Only called to find +load/-.cxx_construct/-.cxx_destruct methods, -* without fixing up the entire method list. -* The class is not yet in use, so methodListLock is not taken. -**********************************************************************/ -IMP lookupNamedMethodInMethodList(old_method_list *mlist, const char *meth_name) -{ - old_method *m; - m = meth_name ? _findNamedMethodInList(mlist, meth_name) : nil; - return (m ? m->method_imp : nil); -} - -static Method _class_getMethod(Class cls, SEL sel) -{ - mutex_locker_t lock(methodListLock); - return (Method)_getMethod(cls, sel); -} - -static Method _class_getMethodNoSuper(Class cls, SEL sel) -{ - mutex_locker_t lock(methodListLock); - return (Method)_findMethodInClass(cls, sel); -} - -static Method _class_getMethodNoSuper_nolock(Class cls, SEL sel) -{ - methodListLock.assertLocked(); - return (Method)_findMethodInClass(cls, sel); -} - - -/*********************************************************************** -* class_getInstanceMethod. Return the instance method for the -* specified class and selector. -**********************************************************************/ -Method class_getInstanceMethod(Class cls, SEL sel) -{ - if (!cls || !sel) return nil; - - // This deliberately avoids +initialize because it historically did so. - - // This implementation is a bit weird because it's the only place that - // wants a Method instead of an IMP. - - Method meth; - meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache); - if (meth == (Method)1) { - // Cache contains forward:: . Stop searching. - return nil; - } else if (meth) { - return meth; - } - - // Search method lists, try method resolver, etc. - lookUpImpOrNil(cls, sel, nil, - NO/*initialize*/, NO/*cache*/, YES/*resolver*/); - - meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache); - if (meth == (Method)1) { - // Cache contains forward:: . Stop searching. - return nil; - } else if (meth) { - return meth; - } - - return _class_getMethod(cls, sel); -} - - -BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen) -{ - old_protocol *proto = oldprotocol(proto_gen); - - if (!cls) return NO; - if (!proto) return NO; - - if (cls->ISA()->version >= 3) { - old_protocol_list *list; - for (list = cls->protocols; list != nil; list = list->next) { - int i; - for (i = 0; i < list->count; i++) { - if (list->list[i] == proto) return YES; - if (protocol_conformsToProtocol((Protocol *)list->list[i], proto_gen)) return YES; - } - if (cls->ISA()->version <= 4) break; - } - } - return NO; -} - - -static NXMapTable * posed_class_hash = nil; - -/*********************************************************************** -* objc_getOrigClass. -**********************************************************************/ -extern "C" -Class _objc_getOrigClass(const char *name) -{ - // Look for class among the posers - { - mutex_locker_t lock(classLock); - if (posed_class_hash) { - Class cls = (Class) NXMapGet (posed_class_hash, name); - if (cls) return cls; - } - } - - // Not a poser. Do a normal lookup. - Class cls = objc_getClass (name); - if (cls) return cls; - - _objc_inform ("class `%s' not linked into application", name); - return nil; -} - -Class objc_getOrigClass(const char *name) -{ - OBJC_WARN_DEPRECATED; - return _objc_getOrigClass(name); -} - -/*********************************************************************** -* _objc_addOrigClass. This function is only used from class_poseAs. -* Registers the original class names, before they get obscured by -* posing, so that [super ..] will work correctly from categories -* in posing classes and in categories in classes being posed for. -**********************************************************************/ -static void _objc_addOrigClass (Class origClass) -{ - mutex_locker_t lock(classLock); - - // Create the poser's hash table on first use - if (!posed_class_hash) - { - posed_class_hash = NXCreateMapTable(NXStrValueMapPrototype, 8); - } - - // Add the named class iff it is not already there (or collides?) - if (NXMapGet (posed_class_hash, origClass->name) == 0) - NXMapInsert (posed_class_hash, origClass->name, origClass); -} - - -/*********************************************************************** -* change_class_references -* Change classrefs and superclass pointers from original to imposter -* But if copy!=nil, don't change copy->superclass. -* If changeSuperRefs==YES, also change [super message] classrefs. -* Used by class_poseAs and objc_setFutureClass -* classLock must be locked. -**********************************************************************/ -void change_class_references(Class imposter, - Class original, - Class copy, - bool changeSuperRefs) -{ - header_info *hInfo; - Class clsObject; - NXHashState state; - - // Change all subclasses of the original to point to the imposter. - state = NXInitHashState (class_hash); - while (NXNextHashState (class_hash, &state, (void **) &clsObject)) - { - while ((clsObject) && (clsObject != imposter) && - (clsObject != copy)) - { - if (clsObject->superclass == original) - { - clsObject->superclass = imposter; - clsObject->ISA()->superclass = imposter->ISA(); - // We must flush caches here! - break; - } - - clsObject = clsObject->superclass; - } - } - - // Replace the original with the imposter in all class refs - // Major loop - process all headers - for (hInfo = FirstHeader; hInfo != nil; hInfo = hInfo->next) - { - Class *cls_refs; - size_t refCount; - unsigned int index; - - // Fix class refs associated with this header - cls_refs = _getObjcClassRefs(hInfo, &refCount); - if (cls_refs) { - for (index = 0; index < refCount; index += 1) { - if (cls_refs[index] == original) { - cls_refs[index] = imposter; - } - } - } - } -} - - -/*********************************************************************** -* class_poseAs. -* -* !!! class_poseAs () does not currently flush any caches. -**********************************************************************/ -Class class_poseAs(Class imposter, Class original) -{ - char * imposterNamePtr; - Class copy; - - OBJC_WARN_DEPRECATED; - - // Trivial case is easy - if (imposter == original) - return imposter; - - // Imposter must be an immediate subclass of the original - if (imposter->superclass != original) { - __objc_error(imposter, - "[%s poseAs:%s]: target not immediate superclass", - imposter->name, original->name); - } - - // Can't pose when you have instance variables (how could it work?) - if (imposter->ivars) { - __objc_error(imposter, - "[%s poseAs:%s]: %s defines new instance variables", - imposter->name, original->name, imposter->name); - } - - // Build a string to use to replace the name of the original class. -#if TARGET_OS_WIN32 -# define imposterNamePrefix "_%" - imposterNamePtr = malloc(strlen(original->name) + strlen(imposterNamePrefix) + 1); - strcpy(imposterNamePtr, imposterNamePrefix); - strcat(imposterNamePtr, original->name); -# undef imposterNamePrefix -#else - asprintf(&imposterNamePtr, "_%%%s", original->name); -#endif - - // We lock the class hashtable, so we are thread safe with respect to - // calls to objc_getClass (). However, the class names are not - // changed atomically, nor are all of the subclasses updated - // atomically. I have ordered the operations so that you will - // never crash, but you may get inconsistent results.... - - // Register the original class so that [super ..] knows - // exactly which classes are the "original" classes. - _objc_addOrigClass (original); - _objc_addOrigClass (imposter); - - // Copy the imposter, so that the imposter can continue - // its normal life in addition to changing the behavior of - // the original. As a hack we don't bother to copy the metaclass. - // For some reason we modify the original rather than the copy. - copy = (Class)malloc(sizeof(objc_class)); - memmove(copy, imposter, sizeof(objc_class)); - - mutex_locker_t lock(classLock); - - // Remove both the imposter and the original class. - NXHashRemove (class_hash, imposter); - NXHashRemove (class_hash, original); - - NXHashInsert (class_hash, copy); - objc_addRegisteredClass(copy); // imposter & original will rejoin later, just track the new guy - - // Mark the imposter as such - imposter->setInfo(CLS_POSING); - imposter->ISA()->setInfo(CLS_POSING); - - // Change the name of the imposter to that of the original class. - imposter->name = original->name; - imposter->ISA()->name = original->ISA()->name; - - // Also copy the version field to avoid archiving problems. - imposter->version = original->version; - - // Change classrefs and superclass pointers - // Don't change copy->superclass - // Don't change [super ...] messages - change_class_references(imposter, original, copy, NO); - - // Change the name of the original class. - original->name = imposterNamePtr + 1; - original->ISA()->name = imposterNamePtr; - - // Restore the imposter and the original class with their new names. - NXHashInsert (class_hash, imposter); - NXHashInsert (class_hash, original); - - return imposter; -} - - -/*********************************************************************** -* _objc_flush_caches. Flush the instance and class method caches -* of cls and all its subclasses. -* -* Specifying Nil for the class "all classes." -**********************************************************************/ -static void flush_caches(Class target, bool flush_meta) -{ - bool collectALot = (target == nil); - NXHashState state; - Class clsObject; -#ifdef OBJC_INSTRUMENTED - unsigned int classesVisited; - unsigned int subclassCount; -#endif - - mutex_locker_t lock(classLock); - mutex_locker_t lock2(cacheUpdateLock); - - // Leaf classes are fastest because there are no subclass caches to flush. - // fixme instrument - if (target && (target->info & CLS_LEAF)) { - _cache_flush (target); - - if (target->ISA() && (target->ISA()->info & CLS_LEAF)) { - _cache_flush (target->ISA()); - return; // done - } else { - // Reset target and handle it by one of the methods below. - target = target->ISA(); - flush_meta = NO; - // NOT done - } - } - - state = NXInitHashState(class_hash); - - // Handle nil and root instance class specially: flush all - // instance and class method caches. Nice that this - // loop is linear vs the N-squared loop just below. - if (!target || !target->superclass) - { -#ifdef OBJC_INSTRUMENTED - LinearFlushCachesCount += 1; - classesVisited = 0; - subclassCount = 0; -#endif - // Traverse all classes in the hash table - while (NXNextHashState(class_hash, &state, (void**)&clsObject)) - { - Class metaClsObject; -#ifdef OBJC_INSTRUMENTED - classesVisited += 1; -#endif - - // Skip class that is known not to be a subclass of this root - // (the isa pointer of any meta class points to the meta class - // of the root). - // NOTE: When is an isa pointer of a hash tabled class ever nil? - metaClsObject = clsObject->ISA(); - if (target && metaClsObject && target->ISA() != metaClsObject->ISA()) { - continue; - } - -#ifdef OBJC_INSTRUMENTED - subclassCount += 1; -#endif - - _cache_flush (clsObject); - if (flush_meta && metaClsObject != nil) { - _cache_flush (metaClsObject); - } - } -#ifdef OBJC_INSTRUMENTED - LinearFlushCachesVisitedCount += classesVisited; - if (classesVisited > MaxLinearFlushCachesVisitedCount) - MaxLinearFlushCachesVisitedCount = classesVisited; - IdealFlushCachesCount += subclassCount; - if (subclassCount > MaxIdealFlushCachesCount) - MaxIdealFlushCachesCount = subclassCount; -#endif - - goto done; - } - - // Outer loop - flush any cache that could now get a method from - // cls (i.e. the cache associated with cls and any of its subclasses). -#ifdef OBJC_INSTRUMENTED - NonlinearFlushCachesCount += 1; - classesVisited = 0; - subclassCount = 0; -#endif - while (NXNextHashState(class_hash, &state, (void**)&clsObject)) - { - Class clsIter; - -#ifdef OBJC_INSTRUMENTED - NonlinearFlushCachesClassCount += 1; -#endif - - // Inner loop - Process a given class - clsIter = clsObject; - while (clsIter) - { - -#ifdef OBJC_INSTRUMENTED - classesVisited += 1; -#endif - // Flush clsObject instance method cache if - // clsObject is a subclass of cls, or is cls itself - // Flush the class method cache if that was asked for - if (clsIter == target) - { -#ifdef OBJC_INSTRUMENTED - subclassCount += 1; -#endif - _cache_flush (clsObject); - if (flush_meta) - _cache_flush (clsObject->ISA()); - - break; - - } - - // Flush clsObject class method cache if cls is - // the meta class of clsObject or of one - // of clsObject's superclasses - else if (clsIter->ISA() == target) - { -#ifdef OBJC_INSTRUMENTED - subclassCount += 1; -#endif - _cache_flush (clsObject->ISA()); - break; - } - - // Move up superclass chain - // else if (clsIter->isInitialized()) - clsIter = clsIter->superclass; - - // clsIter is not initialized, so its cache - // must be empty. This happens only when - // clsIter == clsObject, because - // superclasses are initialized before - // subclasses, and this loop traverses - // from sub- to super- classes. - // else - // break; - } - } -#ifdef OBJC_INSTRUMENTED - NonlinearFlushCachesVisitedCount += classesVisited; - if (classesVisited > MaxNonlinearFlushCachesVisitedCount) - MaxNonlinearFlushCachesVisitedCount = classesVisited; - IdealFlushCachesCount += subclassCount; - if (subclassCount > MaxIdealFlushCachesCount) - MaxIdealFlushCachesCount = subclassCount; -#endif - - - done: - if (collectALot) { - _cache_collect(true); - } -} - - -void _objc_flush_caches(Class target) -{ - flush_caches(target, YES); -} - - - -/*********************************************************************** -* flush_marked_caches. Flush the method cache of any class marked -* CLS_FLUSH_CACHE (and all subclasses thereof) -* fixme instrument -**********************************************************************/ -void flush_marked_caches(void) -{ - Class cls; - Class supercls; - NXHashState state; - - mutex_locker_t lock(classLock); - mutex_locker_t lock2(cacheUpdateLock); - - state = NXInitHashState(class_hash); - while (NXNextHashState(class_hash, &state, (void**)&cls)) { - for (supercls = cls; supercls; supercls = supercls->superclass) { - if (supercls->info & CLS_FLUSH_CACHE) { - _cache_flush(cls); - break; - } - } - - for (supercls = cls->ISA(); supercls; supercls = supercls->superclass) { - if (supercls->info & CLS_FLUSH_CACHE) { - _cache_flush(cls->ISA()); - break; - } - } - } - - state = NXInitHashState(class_hash); - while (NXNextHashState(class_hash, &state, (void**)&cls)) { - if (cls->info & CLS_FLUSH_CACHE) { - cls->clearInfo(CLS_FLUSH_CACHE); - } - if (cls->ISA()->info & CLS_FLUSH_CACHE) { - cls->ISA()->clearInfo(CLS_FLUSH_CACHE); - } - } -} - - -/*********************************************************************** -* get_base_method_list -* Returns the method list containing the class's own methods, -* ignoring any method lists added by categories or class_addMethods. -* Called only by add_class_to_loadable_list. -* Does not hold methodListLock because add_class_to_loadable_list -* does not manipulate in-use classes. -**********************************************************************/ -static old_method_list *get_base_method_list(Class cls) -{ - old_method_list **ptr; - - if (!cls->methodLists) return nil; - if (cls->info & CLS_NO_METHOD_ARRAY) return (old_method_list *)cls->methodLists; - ptr = cls->methodLists; - if (!*ptr || *ptr == END_OF_METHODS_LIST) return nil; - while ( *ptr != 0 && *ptr != END_OF_METHODS_LIST ) { ptr++; } - --ptr; - return *ptr; -} - - -static IMP _class_getLoadMethod_nocheck(Class cls) -{ - old_method_list *mlist; - mlist = get_base_method_list(cls->ISA()); - if (mlist) { - return lookupNamedMethodInMethodList (mlist, "load"); - } - return nil; -} - - -bool _class_hasLoadMethod(Class cls) -{ - if (cls->ISA()->info & CLS_HAS_LOAD_METHOD) return YES; - return _class_getLoadMethod_nocheck(cls); -} - - -/*********************************************************************** -* objc_class::getLoadMethod -* Returns cls's +load implementation, or nil if it doesn't have one. -**********************************************************************/ -IMP objc_class::getLoadMethod() -{ - if (ISA()->info & CLS_HAS_LOAD_METHOD) { - return _class_getLoadMethod_nocheck((Class)this); - } - return nil; -} - -BOOL _class_usesAutomaticRetainRelease(Class cls) -{ - return NO; -} - -uint32_t _class_getInstanceStart(Class cls) -{ - _objc_fatal("_class_getInstanceStart() unimplemented for fragile instance variables"); - return 0; // PCB: never used just provided for ARR consistency. -} - -ptrdiff_t ivar_getOffset(Ivar ivar) -{ - return oldivar(ivar)->ivar_offset; -} - -const char *ivar_getName(Ivar ivar) -{ - return oldivar(ivar)->ivar_name; -} - -const char *ivar_getTypeEncoding(Ivar ivar) -{ - return oldivar(ivar)->ivar_type; -} - - -IMP method_getImplementation(Method m) -{ - if (!m) return nil; - return oldmethod(m)->method_imp; -} - -SEL method_getName(Method m) -{ - if (!m) return nil; - return oldmethod(m)->method_name; -} - -const char *method_getTypeEncoding(Method m) -{ - if (!m) return nil; - return oldmethod(m)->method_types; -} - -unsigned int method_getSizeOfArguments(Method m) -{ - OBJC_WARN_DEPRECATED; - if (!m) return 0; - return encoding_getSizeOfArguments(method_getTypeEncoding(m)); -} - -unsigned int method_getArgumentInfo(Method m, int arg, - const char **type, int *offset) -{ - OBJC_WARN_DEPRECATED; - if (!m) return 0; - return encoding_getArgumentInfo(method_getTypeEncoding(m), - arg, type, offset); -} - - -static spinlock_t impLock; - -IMP method_setImplementation(Method m_gen, IMP imp) -{ - IMP old; - old_method *m = oldmethod(m_gen); - if (!m) return nil; - if (!imp) return nil; - - if (ignoreSelector(m->method_name)) { - // Ignored methods stay ignored - return m->method_imp; - } - - impLock.lock(); - old = m->method_imp; - m->method_imp = imp; - impLock.unlock(); - return old; -} - - -void method_exchangeImplementations(Method m1_gen, Method m2_gen) -{ - IMP m1_imp; - old_method *m1 = oldmethod(m1_gen); - old_method *m2 = oldmethod(m2_gen); - if (!m1 || !m2) return; - - if (ignoreSelector(m1->method_name) || ignoreSelector(m2->method_name)) { - // Ignored methods stay ignored. Now they're both ignored. - m1->method_imp = (IMP)&_objc_ignored_method; - m2->method_imp = (IMP)&_objc_ignored_method; - return; - } - - impLock.lock(); - m1_imp = m1->method_imp; - m1->method_imp = m2->method_imp; - m2->method_imp = m1_imp; - impLock.unlock(); -} - - -struct objc_method_description * method_getDescription(Method m) -{ - if (!m) return nil; - return (struct objc_method_description *)oldmethod(m); -} - - -const char *property_getName(objc_property_t prop) -{ - return oldproperty(prop)->name; -} - -const char *property_getAttributes(objc_property_t prop) -{ - return oldproperty(prop)->attributes; -} - -objc_property_attribute_t *property_copyAttributeList(objc_property_t prop, - unsigned int *outCount) -{ - if (!prop) { - if (outCount) *outCount = 0; - return nil; - } - - mutex_locker_t lock(classLock); - return copyPropertyAttributeList(oldproperty(prop)->attributes,outCount); -} - -char * property_copyAttributeValue(objc_property_t prop, const char *name) -{ - if (!prop || !name || *name == '\0') return nil; - - mutex_locker_t lock(classLock); - return copyPropertyAttributeValue(oldproperty(prop)->attributes, name); -} - - -/*********************************************************************** -* class_addMethod -**********************************************************************/ -static IMP _class_addMethod(Class cls, SEL name, IMP imp, - const char *types, bool replace) -{ - old_method *m; - IMP result = nil; - - if (!types) types = ""; - - mutex_locker_t lock(methodListLock); - - if ((m = _findMethodInClass(cls, name))) { - // already exists - // fixme atomic - result = method_getImplementation((Method)m); - if (replace) { - method_setImplementation((Method)m, imp); - } - } else { - // fixme could be faster - old_method_list *mlist = - (old_method_list *)calloc(sizeof(old_method_list), 1); - mlist->obsolete = fixed_up_method_list; - mlist->method_count = 1; - mlist->method_list[0].method_name = name; - mlist->method_list[0].method_types = strdup(types); - if (!ignoreSelector(name)) { - mlist->method_list[0].method_imp = imp; - } else { - mlist->method_list[0].method_imp = (IMP)&_objc_ignored_method; - } - - _objc_insertMethods(cls, mlist, nil); - if (!(cls->info & CLS_CONSTRUCTING)) { - flush_caches(cls, NO); - } else { - // in-construction class has no subclasses - flush_cache(cls); - } - result = nil; - } - - return result; -} - - -/*********************************************************************** -* class_addMethod -**********************************************************************/ -BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types) -{ - IMP old; - if (!cls) return NO; - - old = _class_addMethod(cls, name, imp, types, NO); - return !old; -} - - -/*********************************************************************** -* class_replaceMethod -**********************************************************************/ -IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types) -{ - if (!cls) return nil; - - return _class_addMethod(cls, name, imp, types, YES); -} - - -/*********************************************************************** -* class_addIvar -**********************************************************************/ -BOOL class_addIvar(Class cls, const char *name, size_t size, - uint8_t alignment, const char *type) -{ - bool result = YES; - - if (!cls) return NO; - if (ISMETA(cls)) return NO; - if (!(cls->info & CLS_CONSTRUCTING)) return NO; - - if (!type) type = ""; - if (name && 0 == strcmp(name, "")) name = nil; - - mutex_locker_t lock(classLock); - - // Check for existing ivar with this name - // fixme check superclasses? - if (cls->ivars) { - int i; - for (i = 0; i < cls->ivars->ivar_count; i++) { - if (0 == strcmp(cls->ivars->ivar_list[i].ivar_name, name)) { - result = NO; - break; - } - } - } - - if (result) { - old_ivar_list *old = cls->ivars; - size_t oldSize; - int newCount; - old_ivar *ivar; - size_t alignBytes; - size_t misalign; - - if (old) { - oldSize = sizeof(old_ivar_list) + - (old->ivar_count - 1) * sizeof(old_ivar); - newCount = 1 + old->ivar_count; - } else { - oldSize = sizeof(old_ivar_list) - sizeof(old_ivar); - newCount = 1; - } - - // allocate new ivar list - cls->ivars = (old_ivar_list *) - calloc(oldSize+sizeof(old_ivar), 1); - if (old) memcpy(cls->ivars, old, oldSize); - if (old && malloc_size(old)) free(old); - cls->ivars->ivar_count = newCount; - ivar = &cls->ivars->ivar_list[newCount-1]; - - // set ivar name and type - ivar->ivar_name = strdup(name); - ivar->ivar_type = strdup(type); - - // align if necessary - alignBytes = 1 << alignment; - misalign = cls->instance_size % alignBytes; - if (misalign) cls->instance_size += (long)(alignBytes - misalign); - - // set ivar offset and increase instance size - ivar->ivar_offset = (int)cls->instance_size; - cls->instance_size += (long)size; - } - - return result; -} - - -/*********************************************************************** -* class_addProtocol -**********************************************************************/ -BOOL class_addProtocol(Class cls, Protocol *protocol_gen) -{ - old_protocol *protocol = oldprotocol(protocol_gen); - old_protocol_list *plist; - - if (!cls) return NO; - if (class_conformsToProtocol(cls, protocol_gen)) return NO; - - mutex_locker_t lock(classLock); - - // fixme optimize - protocol list doesn't escape? - plist = (old_protocol_list*)calloc(sizeof(old_protocol_list), 1); - plist->count = 1; - plist->list[0] = protocol; - plist->next = cls->protocols; - cls->protocols = plist; - - // fixme metaclass? - - return YES; -} - - -/*********************************************************************** -* _class_addProperties -* Internal helper to add properties to a class. -* Used by category attachment and class_addProperty() -* Locking: acquires classLock -**********************************************************************/ -bool -_class_addProperties(Class cls, - old_property_list *additions) -{ - old_property_list *newlist; - - if (!(cls->info & CLS_EXT)) return NO; - - newlist = (old_property_list *) - memdup(additions, sizeof(*newlist) - sizeof(newlist->first) - + (additions->entsize * additions->count)); - - mutex_locker_t lock(classLock); - - allocateExt(cls); - if (!cls->ext->propertyLists) { - // cls has no properties - simply use this list - cls->ext->propertyLists = (old_property_list **)newlist; - cls->setInfo(CLS_NO_PROPERTY_ARRAY); - } - else if (cls->info & CLS_NO_PROPERTY_ARRAY) { - // cls has one property list - make a new array - old_property_list **newarray = (old_property_list **) - malloc(3 * sizeof(*newarray)); - newarray[0] = newlist; - newarray[1] = (old_property_list *)cls->ext->propertyLists; - newarray[2] = nil; - cls->ext->propertyLists = newarray; - cls->clearInfo(CLS_NO_PROPERTY_ARRAY); - } - else { - // cls has a property array - make a bigger one - old_property_list **newarray; - int count = 0; - while (cls->ext->propertyLists[count]) count++; - newarray = (old_property_list **) - malloc((count+2) * sizeof(*newarray)); - newarray[0] = newlist; - memcpy(&newarray[1], &cls->ext->propertyLists[0], - count * sizeof(*newarray)); - newarray[count+1] = nil; - free(cls->ext->propertyLists); - cls->ext->propertyLists = newarray; - } - - return YES; -} - - -/*********************************************************************** -* class_addProperty -* Adds a property to a class. Returns NO if the proeprty already exists. -* Locking: acquires classLock -**********************************************************************/ -static bool -_class_addProperty(Class cls, const char *name, - const objc_property_attribute_t *attrs, unsigned int count, - bool replace) -{ - if (!cls) return NO; - if (!name) return NO; - - old_property *prop = oldproperty(class_getProperty(cls, name)); - if (prop && !replace) { - // already exists, refuse to replace - return NO; - } - else if (prop) { - // replace existing - mutex_locker_t lock(classLock); - try_free(prop->attributes); - prop->attributes = copyPropertyAttributeString(attrs, count); - return YES; - } - else { - // add new - old_property_list proplist; - proplist.entsize = sizeof(old_property); - proplist.count = 1; - proplist.first.name = strdup(name); - proplist.first.attributes = copyPropertyAttributeString(attrs, count); - - return _class_addProperties(cls, &proplist); - } -} - -BOOL -class_addProperty(Class cls, const char *name, - const objc_property_attribute_t *attrs, unsigned int n) -{ - return _class_addProperty(cls, name, attrs, n, NO); -} - -void -class_replaceProperty(Class cls, const char *name, - const objc_property_attribute_t *attrs, unsigned int n) -{ - _class_addProperty(cls, name, attrs, n, YES); -} - - -/*********************************************************************** -* class_copyProtocolList. Returns a heap block containing the -* protocols implemented by the class, or nil if the class -* implements no protocols. Caller must free the block. -* Does not copy any superclass's protocols. -**********************************************************************/ -Protocol * __unsafe_unretained * -class_copyProtocolList(Class cls, unsigned int *outCount) -{ - old_protocol_list *plist; - Protocol **result = nil; - unsigned int count = 0; - unsigned int p; - - if (!cls) { - if (outCount) *outCount = 0; - return nil; - } - - mutex_locker_t lock(classLock); - - for (plist = cls->protocols; plist != nil; plist = plist->next) { - count += (int)plist->count; - } - - if (count > 0) { - result = (Protocol **)malloc((count+1) * sizeof(Protocol *)); - - for (p = 0, plist = cls->protocols; - plist != nil; - plist = plist->next) - { - int i; - for (i = 0; i < plist->count; i++) { - result[p++] = (Protocol *)plist->list[i]; - } - } - result[p] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* class_getProperty. Return the named property. -**********************************************************************/ -objc_property_t class_getProperty(Class cls, const char *name) -{ - if (!cls || !name) return nil; - - mutex_locker_t lock(classLock); - - for (; cls; cls = cls->superclass) { - uintptr_t iterator = 0; - old_property_list *plist; - while ((plist = nextPropertyList(cls, &iterator))) { - uint32_t i; - for (i = 0; i < plist->count; i++) { - old_property *p = property_list_nth(plist, i); - if (0 == strcmp(name, p->name)) { - return (objc_property_t)p; - } - } - } - } - - return nil; -} - - -/*********************************************************************** -* class_copyPropertyList. Returns a heap block containing the -* properties declared in the class, or nil if the class -* declares no properties. Caller must free the block. -* Does not copy any superclass's properties. -**********************************************************************/ -objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount) -{ - old_property_list *plist; - uintptr_t iterator = 0; - old_property **result = nil; - unsigned int count = 0; - unsigned int p, i; - - if (!cls) { - if (outCount) *outCount = 0; - return nil; - } - - mutex_locker_t lock(classLock); - - iterator = 0; - while ((plist = nextPropertyList(cls, &iterator))) { - count += plist->count; - } - - if (count > 0) { - result = (old_property **)malloc((count+1) * sizeof(old_property *)); - - p = 0; - iterator = 0; - while ((plist = nextPropertyList(cls, &iterator))) { - for (i = 0; i < plist->count; i++) { - result[p++] = property_list_nth(plist, i); - } - } - result[p] = nil; - } - - if (outCount) *outCount = count; - return (objc_property_t *)result; -} - - -/*********************************************************************** -* class_copyMethodList. Returns a heap block containing the -* methods implemented by the class, or nil if the class -* implements no methods. Caller must free the block. -* Does not copy any superclass's methods. -**********************************************************************/ -Method *class_copyMethodList(Class cls, unsigned int *outCount) -{ - old_method_list *mlist; - void *iterator = nil; - Method *result = nil; - unsigned int count = 0; - unsigned int m; - - if (!cls) { - if (outCount) *outCount = 0; - return nil; - } - - mutex_locker_t lock(methodListLock); - - iterator = nil; - while ((mlist = nextMethodList(cls, &iterator))) { - count += mlist->method_count; - } - - if (count > 0) { - result = (Method *)malloc((count+1) * sizeof(Method)); - - m = 0; - iterator = nil; - while ((mlist = nextMethodList(cls, &iterator))) { - int i; - for (i = 0; i < mlist->method_count; i++) { - Method aMethod = (Method)&mlist->method_list[i]; - if (ignoreSelector(method_getName(aMethod))) { - count--; - continue; - } - result[m++] = aMethod; - } - } - result[m] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* class_copyIvarList. Returns a heap block containing the -* ivars declared in the class, or nil if the class -* declares no ivars. Caller must free the block. -* Does not copy any superclass's ivars. -**********************************************************************/ -Ivar *class_copyIvarList(Class cls, unsigned int *outCount) -{ - Ivar *result = nil; - unsigned int count = 0; - int i; - - if (!cls) { - if (outCount) *outCount = 0; - return nil; - } - - if (cls->ivars) { - count = cls->ivars->ivar_count; - } - - if (count > 0) { - result = (Ivar *)malloc((count+1) * sizeof(Ivar)); - - for (i = 0; i < cls->ivars->ivar_count; i++) { - result[i] = (Ivar)&cls->ivars->ivar_list[i]; - } - result[i] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* objc_allocateClass. -**********************************************************************/ - -void set_superclass(Class cls, Class supercls, bool cls_is_new) -{ - Class meta = cls->ISA(); - - if (supercls) { - cls->superclass = supercls; - meta->superclass = supercls->ISA(); - meta->initIsa(supercls->ISA()->ISA()); - - // Propagate C++ cdtors from superclass. - if (supercls->info & CLS_HAS_CXX_STRUCTORS) { - if (cls_is_new) cls->info |= CLS_HAS_CXX_STRUCTORS; - else cls->setInfo(CLS_HAS_CXX_STRUCTORS); - } - - // Superclass is no longer a leaf for cache flushing - if (supercls->info & CLS_LEAF) { - supercls->clearInfo(CLS_LEAF); - supercls->ISA()->clearInfo(CLS_LEAF); - } - } else { - cls->superclass = Nil; // superclass of root class is nil - meta->superclass = cls; // superclass of root metaclass is root class - meta->initIsa(meta); // metaclass of root metaclass is root metaclass - - // Root class is never a leaf for cache flushing, because the - // root metaclass is a subclass. (This could be optimized, but - // is too uncommon to bother.) - cls->clearInfo(CLS_LEAF); - meta->clearInfo(CLS_LEAF); - } -} - -// &UnsetLayout is the default ivar layout during class construction -static const uint8_t UnsetLayout = 0; - -Class objc_initializeClassPair(Class supercls, const char *name, Class cls, Class meta) -{ - // Connect to superclasses and metaclasses - cls->initIsa(meta); - set_superclass(cls, supercls, YES); - - // Set basic info - cls->name = strdup(name); - meta->name = strdup(name); - cls->version = 0; - meta->version = 7; - cls->info = CLS_CLASS | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF; - meta->info = CLS_META | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF; - - // Set instance size based on superclass. - if (supercls) { - cls->instance_size = supercls->instance_size; - meta->instance_size = supercls->ISA()->instance_size; - } else { - cls->instance_size = sizeof(Class); // just an isa - meta->instance_size = sizeof(objc_class); - } - - // No ivars. No methods. Empty cache. No protocols. No layout. Empty ext. - cls->ivars = nil; - cls->methodLists = nil; - cls->cache = (Cache)&_objc_empty_cache; - cls->protocols = nil; - cls->ivar_layout = &UnsetLayout; - cls->ext = nil; - allocateExt(cls); - cls->ext->weak_ivar_layout = &UnsetLayout; - - meta->ivars = nil; - meta->methodLists = nil; - meta->cache = (Cache)&_objc_empty_cache; - meta->protocols = nil; - meta->ext = nil; - - return cls; -} - -Class objc_allocateClassPair(Class supercls, const char *name, - size_t extraBytes) -{ - Class cls, meta; - - if (objc_getClass(name)) return nil; - // fixme reserve class name against simultaneous allocation - - if (supercls && (supercls->info & CLS_CONSTRUCTING)) { - // Can't make subclass of an in-construction class - return nil; - } - - // Allocate new classes. - if (supercls) { - cls = _calloc_class(supercls->ISA()->alignedInstanceSize() + extraBytes); - meta = _calloc_class(supercls->ISA()->ISA()->alignedInstanceSize() + extraBytes); - } else { - cls = _calloc_class(sizeof(objc_class) + extraBytes); - meta = _calloc_class(sizeof(objc_class) + extraBytes); - } - - - objc_initializeClassPair(supercls, name, cls, meta); - - return cls; -} - - -void objc_registerClassPair(Class cls) -{ - if ((cls->info & CLS_CONSTRUCTED) || - (cls->ISA()->info & CLS_CONSTRUCTED)) - { - _objc_inform("objc_registerClassPair: class '%s' was already " - "registered!", cls->name); - return; - } - - if (!(cls->info & CLS_CONSTRUCTING) || - !(cls->ISA()->info & CLS_CONSTRUCTING)) - { - _objc_inform("objc_registerClassPair: class '%s' was not " - "allocated with objc_allocateClassPair!", cls->name); - return; - } - - if (ISMETA(cls)) { - _objc_inform("objc_registerClassPair: class '%s' is a metaclass, " - "not a class!", cls->name); - return; - } - - mutex_locker_t lock(classLock); - - // Build ivar layouts - if (UseGC) { - if (cls->ivar_layout != &UnsetLayout) { - // Class builder already called class_setIvarLayout. - } - else if (!cls->superclass) { - // Root class. Scan conservatively (should be isa ivar only). - cls->ivar_layout = nil; - } - else if (cls->ivars == nil) { - // No local ivars. Use superclass's layout. - cls->ivar_layout = - ustrdupMaybeNil(cls->superclass->ivar_layout); - } - else { - // Has local ivars. Build layout based on superclass. - Class supercls = cls->superclass; - const uint8_t *superlayout = - class_getIvarLayout(supercls); - layout_bitmap bitmap = - layout_bitmap_create(superlayout, supercls->instance_size, - cls->instance_size, NO); - int i; - for (i = 0; i < cls->ivars->ivar_count; i++) { - old_ivar *iv = &cls->ivars->ivar_list[i]; - layout_bitmap_set_ivar(bitmap, iv->ivar_type, iv->ivar_offset); - } - cls->ivar_layout = layout_string_create(bitmap); - layout_bitmap_free(bitmap); - } - - if (cls->ext->weak_ivar_layout != &UnsetLayout) { - // Class builder already called class_setWeakIvarLayout. - } - else if (!cls->superclass) { - // Root class. No weak ivars (should be isa ivar only) - cls->ext->weak_ivar_layout = nil; - } - else if (cls->ivars == nil) { - // No local ivars. Use superclass's layout. - const uint8_t *weak = - class_getWeakIvarLayout(cls->superclass); - cls->ext->weak_ivar_layout = ustrdupMaybeNil(weak); - } - else { - // Has local ivars. Build layout based on superclass. - // No way to add weak ivars yet. - const uint8_t *weak = - class_getWeakIvarLayout(cls->superclass); - cls->ext->weak_ivar_layout = ustrdupMaybeNil(weak); - } - } - - // Clear "under construction" bit, set "done constructing" bit - cls->info &= ~CLS_CONSTRUCTING; - cls->ISA()->info &= ~CLS_CONSTRUCTING; - cls->info |= CLS_CONSTRUCTED; - cls->ISA()->info |= CLS_CONSTRUCTED; - - NXHashInsertIfAbsent(class_hash, cls); - objc_addRegisteredClass(cls); - //objc_addRegisteredClass(cls->ISA()); if we ever allocate classes from GC -} - - -Class objc_duplicateClass(Class original, const char *name, size_t extraBytes) -{ - unsigned int count, i; - old_method **originalMethods; - old_method_list *duplicateMethods; - // Don't use sizeof(objc_class) here because - // instance_size has historically contained two extra words, - // and instance_size is what objc_getIndexedIvars() actually uses. - Class duplicate = - _calloc_class(original->ISA()->alignedInstanceSize() + extraBytes); - - duplicate->initIsa(original->ISA()); - duplicate->superclass = original->superclass; - duplicate->name = strdup(name); - duplicate->version = original->version; - duplicate->info = original->info & (CLS_CLASS|CLS_META|CLS_INITIALIZED|CLS_JAVA_HYBRID|CLS_JAVA_CLASS|CLS_HAS_CXX_STRUCTORS|CLS_HAS_LOAD_METHOD); - duplicate->instance_size = original->instance_size; - duplicate->ivars = original->ivars; - // methodLists handled below - duplicate->cache = (Cache)&_objc_empty_cache; - duplicate->protocols = original->protocols; - if (original->info & CLS_EXT) { - duplicate->info |= original->info & (CLS_EXT|CLS_NO_PROPERTY_ARRAY); - duplicate->ivar_layout = original->ivar_layout; - if (original->ext) { - duplicate->ext = (old_class_ext *)malloc(original->ext->size); - memcpy(duplicate->ext, original->ext, original->ext->size); - } else { - duplicate->ext = nil; - } - } - - // Method lists are deep-copied so they can be stomped. - originalMethods = (old_method **)class_copyMethodList(original, &count); - if (originalMethods) { - duplicateMethods = (old_method_list *) - calloc(sizeof(old_method_list) + - (count-1)*sizeof(old_method), 1); - duplicateMethods->obsolete = fixed_up_method_list; - duplicateMethods->method_count = count; - for (i = 0; i < count; i++) { - duplicateMethods->method_list[i] = *(originalMethods[i]); - } - duplicate->methodLists = (old_method_list **)duplicateMethods; - duplicate->info |= CLS_NO_METHOD_ARRAY; - free(originalMethods); - } - - mutex_locker_t lock(classLock); - NXHashInsert(class_hash, duplicate); - objc_addRegisteredClass(duplicate); - - return duplicate; -} - - -void objc_disposeClassPair(Class cls) -{ - if (!(cls->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)) || - !(cls->ISA()->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING))) - { - // class not allocated with objc_allocateClassPair - // disposing still-unregistered class is OK! - _objc_inform("objc_disposeClassPair: class '%s' was not " - "allocated with objc_allocateClassPair!", cls->name); - return; - } - - if (ISMETA(cls)) { - _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, " - "not a class!", cls->name); - return; - } - - mutex_locker_t lock(classLock); - NXHashRemove(class_hash, cls); - objc_removeRegisteredClass(cls); - unload_class(cls->ISA()); - unload_class(cls); -} - - -/*********************************************************************** -* objc_constructInstance -* Creates an instance of `cls` at the location pointed to by `bytes`. -* `bytes` must point to at least class_getInstanceSize(cls) bytes of -* well-aligned zero-filled memory. -* The new object's isa is set. Any C++ constructors are called. -* Returns `bytes` if successful. Returns nil if `cls` or `bytes` is -* nil, or if C++ constructors fail. -**********************************************************************/ -id -objc_constructInstance(Class cls, void *bytes) -{ - if (!cls || !bytes) return nil; - - id obj = (id)bytes; - - obj->initIsa(cls); - - if (cls->hasCxxCtor()) { - return object_cxxConstructFromClass(obj, cls); - } else { - return obj; - } -} - - -/*********************************************************************** -* _class_createInstanceFromZone. Allocate an instance of the -* specified class with the specified number of bytes for indexed -* variables, in the specified zone. The isa field is set to the -* class, C++ default constructors are called, and all other fields are zeroed. -**********************************************************************/ -id -_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone) -{ - void *bytes; - size_t size; - - // Can't create something for nothing - if (!cls) return nil; - - // Allocate and initialize - size = cls->alignedInstanceSize() + extraBytes; - - // CF requires all objects be at least 16 bytes. - if (size < 16) size = 16; - -#if SUPPORT_GC - if (UseGC) { - bytes = auto_zone_allocate_object(gc_zone, size, - AUTO_OBJECT_SCANNED, 0, 1); - } else -#endif - if (zone) { - bytes = malloc_zone_calloc((malloc_zone_t *)zone, 1, size); - } else { - bytes = calloc(1, size); - } - - return objc_constructInstance(cls, bytes); -} - - -/*********************************************************************** -* _class_createInstance. Allocate an instance of the specified -* class with the specified number of bytes for indexed variables, in -* the default zone, using _class_createInstanceFromZone. -**********************************************************************/ -static id _class_createInstance(Class cls, size_t extraBytes) -{ - return _class_createInstanceFromZone (cls, extraBytes, nil); -} - - -static id _object_copyFromZone(id oldObj, size_t extraBytes, void *zone) -{ - id obj; - size_t size; - - if (!oldObj) return nil; - - obj = (*_zoneAlloc)(oldObj->ISA(), extraBytes, zone); - size = oldObj->ISA()->alignedInstanceSize() + extraBytes; - - // fixme need C++ copy constructor - objc_memmove_collectable(obj, oldObj, size); - -#if SUPPORT_GC - if (UseGC) gc_fixup_weakreferences(obj, oldObj); -#endif - - return obj; -} - - -/*********************************************************************** -* objc_destructInstance -* Destroys an instance without freeing memory. -* Calls C++ destructors. -* Removes associative references. -* Returns `obj`. Does nothing if `obj` is nil. -* Be warned that GC DOES NOT CALL THIS. If you edit this, also edit finalize. -* CoreFoundation and other clients do call this under GC. -**********************************************************************/ -void *objc_destructInstance(id obj) -{ - if (obj) { - Class isa = obj->getIsa(); - - if (isa->hasCxxDtor()) { - object_cxxDestruct(obj); - } - - if (isa->instancesHaveAssociatedObjects()) { - _object_remove_assocations(obj); - } - - if (!UseGC) objc_clear_deallocating(obj); - } - - return obj; -} - -static id -_object_dispose(id anObject) -{ - if (anObject==nil) return nil; - - objc_destructInstance(anObject); - -#if SUPPORT_GC - if (UseGC) { - auto_zone_retain(gc_zone, anObject); // gc free expects rc==1 - } else -#endif - { - // only clobber isa for non-gc - anObject->initIsa(_objc_getFreedObjectClass ()); - } - free(anObject); - return nil; -} - -static id _object_copy(id oldObj, size_t extraBytes) -{ - void *z = malloc_zone_from_ptr(oldObj); - return _object_copyFromZone(oldObj, extraBytes, - z ? z : malloc_default_zone()); -} - -static id _object_reallocFromZone(id anObject, size_t nBytes, void *zone) -{ - id newObject; - Class tmp; - - if (anObject == nil) - __objc_error(nil, "reallocating nil object"); - - if (anObject->ISA() == _objc_getFreedObjectClass ()) - __objc_error(anObject, "reallocating freed object"); - - if (nBytes < anObject->ISA()->alignedInstanceSize()) - __objc_error(anObject, "(%s, %zu) requested size too small", - object_getClassName(anObject), nBytes); - - // fixme need C++ copy constructor - // fixme GC copy - // Make sure not to modify space that has been declared free - tmp = anObject->ISA(); - anObject->initIsa(_objc_getFreedObjectClass ()); - newObject = (id)malloc_zone_realloc((malloc_zone_t *)zone, anObject, nBytes); - if (newObject) { - newObject->initIsa(tmp); - } else { - // realloc failed, anObject is still alive - anObject->initIsa(tmp); - } - return newObject; -} - - -static id _object_realloc(id anObject, size_t nBytes) -{ - void *z = malloc_zone_from_ptr(anObject); - return _object_reallocFromZone(anObject, - nBytes, - z ? z : malloc_default_zone()); -} - -id (*_alloc)(Class, size_t) = _class_createInstance; -id (*_copy)(id, size_t) = _object_copy; -id (*_realloc)(id, size_t) = _object_realloc; -id (*_dealloc)(id) = _object_dispose; -id (*_zoneAlloc)(Class, size_t, void *) = _class_createInstanceFromZone; -id (*_zoneCopy)(id, size_t, void *) = _object_copyFromZone; -id (*_zoneRealloc)(id, size_t, void *) = _object_reallocFromZone; -void (*_error)(id, const char *, va_list) = _objc_error; - - -id class_createInstance(Class cls, size_t extraBytes) -{ - if (UseGC) { - return _class_createInstance(cls, extraBytes); - } else { - return (*_alloc)(cls, extraBytes); - } -} - -id class_createInstanceFromZone(Class cls, size_t extraBytes, void *z) -{ - OBJC_WARN_DEPRECATED; - if (UseGC) { - return _class_createInstanceFromZone(cls, extraBytes, z); - } else { - return (*_zoneAlloc)(cls, extraBytes, z); - } -} - -unsigned class_createInstances(Class cls, size_t extraBytes, - id *results, unsigned num_requested) -{ - if (UseGC || _alloc == &_class_createInstance) { - return _class_createInstancesFromZone(cls, extraBytes, nil, - results, num_requested); - } else { - // _alloc in use, which isn't understood by the batch allocator - return 0; - } -} - -id object_copy(id obj, size_t extraBytes) -{ - if (UseGC) return _object_copy(obj, extraBytes); - else return (*_copy)(obj, extraBytes); -} - -id object_copyFromZone(id obj, size_t extraBytes, void *z) -{ - OBJC_WARN_DEPRECATED; - if (UseGC) return _object_copyFromZone(obj, extraBytes, z); - else return (*_zoneCopy)(obj, extraBytes, z); -} - -id object_dispose(id obj) -{ - if (UseGC) return _object_dispose(obj); - else return (*_dealloc)(obj); -} - -id object_realloc(id obj, size_t nBytes) -{ - OBJC_WARN_DEPRECATED; - if (UseGC) return _object_realloc(obj, nBytes); - else return (*_realloc)(obj, nBytes); -} - -id object_reallocFromZone(id obj, size_t nBytes, void *z) -{ - OBJC_WARN_DEPRECATED; - if (UseGC) return _object_reallocFromZone(obj, nBytes, z); - else return (*_zoneRealloc)(obj, nBytes, z); -} - - -/*********************************************************************** -* object_getIndexedIvars. -**********************************************************************/ -void *object_getIndexedIvars(id obj) -{ - // ivars are tacked onto the end of the object - if (!obj) return nil; - if (obj->isTaggedPointer()) return nil; - return ((char *) obj) + obj->ISA()->alignedInstanceSize(); -} - - -// ProKit SPI -Class class_setSuperclass(Class cls, Class newSuper) -{ - Class oldSuper = cls->superclass; - set_superclass(cls, newSuper, NO); - flush_caches(cls, YES); - return oldSuper; -} -#endif diff --git a/objc/objc-runtime/runtime/objc-class.h b/objc/objc-runtime/runtime/objc-class.h deleted file mode 100644 index 4599f08..0000000 --- a/objc/objc-runtime/runtime/objc-class.h +++ /dev/null @@ -1,2 +0,0 @@ -#include <objc/runtime.h> -#include <objc/message.h> diff --git a/objc/objc-runtime/runtime/objc-class.mm b/objc/objc-runtime/runtime/objc-class.mm deleted file mode 100644 index e9d2f15..0000000 --- a/objc/objc-runtime/runtime/objc-class.mm +++ /dev/null @@ -1,1188 +0,0 @@ -/* - * 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@ - */ -/*********************************************************************** -* objc-class.m -* Copyright 1988-1997, Apple Computer, Inc. -* Author: s. naroff -**********************************************************************/ - - -/*********************************************************************** - * Lazy method list arrays and method list locking (2004-10-19) - * - * cls->methodLists may be in one of three forms: - * 1. nil: The class has no methods. - * 2. non-nil, with CLS_NO_METHOD_ARRAY set: cls->methodLists points - * to a single method list, which is the class's only method list. - * 3. non-nil, with CLS_NO_METHOD_ARRAY clear: cls->methodLists points to - * an array of method list pointers. The end of the array's block - * is set to -1. If the actual number of method lists is smaller - * than that, the rest of the array is nil. - * - * Attaching categories and adding and removing classes may change - * the form of the class list. In addition, individual method lists - * may be reallocated when fixed up. - * - * Classes are initially read as #1 or #2. If a category is attached - * or other methods added, the class is changed to #3. Once in form #3, - * the class is never downgraded to #1 or #2, even if methods are removed. - * Classes added with objc_addClass are initially either #1 or #3. - * - * Accessing and manipulating a class's method lists are synchronized, - * to prevent races when one thread restructures the list. However, - * if the class is not yet in use (i.e. not in class_hash), then the - * thread loading the class may access its method lists without locking. - * - * The following functions acquire methodListLock: - * class_getInstanceMethod - * class_getClassMethod - * class_nextMethodList - * class_addMethods - * class_removeMethods - * class_respondsToMethod - * _class_lookupMethodAndLoadCache - * lookupMethodInClassAndLoadCache - * _objc_add_category_flush_caches - * - * The following functions don't acquire methodListLock because they - * only access method lists during class load and unload: - * _objc_register_category - * _resolve_categories_for_class (calls _objc_add_category) - * add_class_to_loadable_list - * _objc_addClass - * _objc_remove_classes_in_image - * - * The following functions use method lists without holding methodListLock. - * The caller must either hold methodListLock, or be loading the class. - * _getMethod (called by class_getInstanceMethod, class_getClassMethod, - * and class_respondsToMethod) - * _findMethodInClass (called by _class_lookupMethodAndLoadCache, - * lookupMethodInClassAndLoadCache, _getMethod) - * _findMethodInList (called by _findMethodInClass) - * nextMethodList (called by _findMethodInClass and class_nextMethodList - * fixupSelectorsInMethodList (called by nextMethodList) - * _objc_add_category (called by _objc_add_category_flush_caches, - * resolve_categories_for_class and _objc_register_category) - * _objc_insertMethods (called by class_addMethods and _objc_add_category) - * _objc_removeMethods (called by class_removeMethods) - * _objcTweakMethodListPointerForClass (called by _objc_insertMethods) - * get_base_method_list (called by add_class_to_loadable_list) - * lookupNamedMethodInMethodList (called by add_class_to_loadable_list) - ***********************************************************************/ - -/*********************************************************************** - * Thread-safety of class info bits (2004-10-19) - * - * Some class info bits are used to store mutable runtime state. - * Modifications of the info bits at particular times need to be - * synchronized to prevent races. - * - * Three thread-safe modification functions are provided: - * cls->setInfo() // atomically sets some bits - * cls->clearInfo() // atomically clears some bits - * cls->changeInfo() // atomically sets some bits and clears others - * These replace CLS_SETINFO() for the multithreaded cases. - * - * Three modification windows are defined: - * - compile time - * - class construction or image load (before +load) in one thread - * - multi-threaded messaging and method caches - * - * Info bit modification at compile time and class construction do not - * need to be locked, because only one thread is manipulating the class. - * Info bit modification during messaging needs to be locked, because - * there may be other threads simultaneously messaging or otherwise - * manipulating the class. - * - * Modification windows for each flag: - * - * CLS_CLASS: compile-time and class load - * CLS_META: compile-time and class load - * CLS_INITIALIZED: +initialize - * CLS_POSING: messaging - * CLS_MAPPED: compile-time - * CLS_FLUSH_CACHE: class load and messaging - * CLS_GROW_CACHE: messaging - * CLS_NEED_BIND: unused - * CLS_METHOD_ARRAY: unused - * CLS_JAVA_HYBRID: JavaBridge only - * CLS_JAVA_CLASS: JavaBridge only - * CLS_INITIALIZING: messaging - * CLS_FROM_BUNDLE: class load - * CLS_HAS_CXX_STRUCTORS: compile-time and class load - * CLS_NO_METHOD_ARRAY: class load and messaging - * CLS_HAS_LOAD_METHOD: class load - * - * CLS_INITIALIZED and CLS_INITIALIZING have additional thread-safety - * constraints to support thread-safe +initialize. See "Thread safety - * during class initialization" for details. - * - * CLS_JAVA_HYBRID and CLS_JAVA_CLASS are set immediately after JavaBridge - * calls objc_addClass(). The JavaBridge does not use an atomic update, - * but the modification counts as "class construction" unless some other - * thread quickly finds the class via the class list. This race is - * small and unlikely in well-behaved code. - * - * Most info bits that may be modified during messaging are also never - * read without a lock. There is no general read lock for the info bits. - * CLS_INITIALIZED: classInitLock - * CLS_FLUSH_CACHE: cacheUpdateLock - * CLS_GROW_CACHE: cacheUpdateLock - * CLS_NO_METHOD_ARRAY: methodListLock - * CLS_INITIALIZING: classInitLock - ***********************************************************************/ - -/*********************************************************************** -* Imports. -**********************************************************************/ - -#include "objc-private.h" -#include "objc-abi.h" -#include "objc-auto.h" -#include <objc/message.h> - - -/* overriding the default object allocation and error handling routines */ - -OBJC_EXPORT id (*_alloc)(Class, size_t); -OBJC_EXPORT id (*_copy)(id, size_t); -OBJC_EXPORT id (*_realloc)(id, size_t); -OBJC_EXPORT id (*_dealloc)(id); -OBJC_EXPORT id (*_zoneAlloc)(Class, size_t, void *); -OBJC_EXPORT id (*_zoneRealloc)(id, size_t, void *); -OBJC_EXPORT id (*_zoneCopy)(id, size_t, void *); - - -/*********************************************************************** -* Information about multi-thread support: -* -* Since we do not lock many operations which walk the superclass, method -* and ivar chains, these chains must remain intact once a class is published -* by inserting it into the class hashtable. All modifications must be -* atomic so that someone walking these chains will always geta valid -* result. -***********************************************************************/ - - - -/*********************************************************************** -* object_getClass. -* Locking: None. If you add locking, tell gdb (rdar://7516456). -**********************************************************************/ -Class object_getClass(id obj) -{ - if (obj) return obj->getIsa(); - else return Nil; -} - - -/*********************************************************************** -* object_setClass. -**********************************************************************/ -Class object_setClass(id obj, Class cls) -{ - if (!obj) return nil; - - // Prevent a deadlock between the weak reference machinery - // and the +initialize machinery by ensuring that no - // weakly-referenced object has an un-+initialized isa. - // Unresolved future classes are not so protected. - if (!cls->isFuture() && !cls->isInitialized()) { - _class_initialize(_class_getNonMetaClass(cls, nil)); - } - - return obj->changeIsa(cls); -} - - -/*********************************************************************** -* object_isClass. -**********************************************************************/ -BOOL object_isClass(id obj) -{ - if (!obj) return NO; - return obj->isClass(); -} - - -/*********************************************************************** -* object_getClassName. -**********************************************************************/ -const char *object_getClassName(id obj) -{ - return class_getName(obj ? obj->getIsa() : nil); -} - - -/*********************************************************************** - * object_getMethodImplementation. - **********************************************************************/ -IMP object_getMethodImplementation(id obj, SEL name) -{ - Class cls = (obj ? obj->getIsa() : nil); - return class_getMethodImplementation(cls, name); -} - - -/*********************************************************************** - * object_getMethodImplementation_stret. - **********************************************************************/ -#if SUPPORT_STRET -IMP object_getMethodImplementation_stret(id obj, SEL name) -{ - Class cls = (obj ? obj->getIsa() : nil); - return class_getMethodImplementation_stret(cls, name); -} -#endif - - -Ivar object_setInstanceVariable(id obj, const char *name, void *value) -{ - Ivar ivar = nil; - - if (obj && name && !obj->isTaggedPointer()) { - if ((ivar = class_getInstanceVariable(obj->ISA(), name))) { - object_setIvar(obj, ivar, (id)value); - } - } - return ivar; -} - -Ivar object_getInstanceVariable(id obj, const char *name, void **value) -{ - if (obj && name && !obj->isTaggedPointer()) { - Ivar ivar; - if ((ivar = class_getInstanceVariable(obj->ISA(), name))) { - if (value) *value = (void *)object_getIvar(obj, ivar); - return ivar; - } - } - if (value) *value = nil; - return nil; -} - -static bool is_scanned_offset(ptrdiff_t ivar_offset, const uint8_t *layout) { - ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*); - uint8_t byte; - while ((byte = *layout++)) { - unsigned skips = (byte >> 4); - unsigned scans = (byte & 0x0F); - index += skips; - while (scans--) { - if (index == ivar_index) return YES; - if (index > ivar_index) return NO; - ++index; - } - } - return NO; -} - -// FIXME: this could be optimized. - -static Class _ivar_getClass(Class cls, Ivar ivar) { - Class ivar_class = nil; - const char *ivar_name = ivar_getName(ivar); - Ivar named_ivar = _class_getVariable(cls, ivar_name, &ivar_class); - if (named_ivar) { - // the same ivar name can appear multiple times along the superclass chain. - while (named_ivar != ivar && ivar_class != nil) { - ivar_class = ivar_class->superclass; - named_ivar = _class_getVariable(cls, ivar_getName(ivar), &ivar_class); - } - } - return ivar_class; -} - -void object_setIvar(id obj, Ivar ivar, id value) -{ - if (obj && ivar && !obj->isTaggedPointer()) { - Class cls = _ivar_getClass(obj->ISA(), ivar); - ptrdiff_t ivar_offset = ivar_getOffset(ivar); - id *location = (id *)((char *)obj + ivar_offset); - // if this ivar is a member of an ARR compiled class, then issue the correct barrier according to the layout. - if (_class_usesAutomaticRetainRelease(cls)) { - // for ARR, layout strings are relative to the instance start. - uint32_t instanceStart = _class_getInstanceStart(cls); - const uint8_t *weak_layout = class_getWeakIvarLayout(cls); - if (weak_layout && is_scanned_offset(ivar_offset - instanceStart, weak_layout)) { - // use the weak system to write to this variable. - objc_storeWeak(location, value); - return; - } - const uint8_t *strong_layout = class_getIvarLayout(cls); - if (strong_layout && is_scanned_offset(ivar_offset - instanceStart, strong_layout)) { - objc_storeStrong(location, value); - return; - } - } -#if SUPPORT_GC - if (UseGC) { - // for GC, check for weak references. - const uint8_t *weak_layout = class_getWeakIvarLayout(cls); - if (weak_layout && is_scanned_offset(ivar_offset, weak_layout)) { - objc_assign_weak(value, location); - } - } - objc_assign_ivar(value, obj, ivar_offset); -#else - *location = value; -#endif - } -} - - -id object_getIvar(id obj, Ivar ivar) -{ - if (obj && ivar && !obj->isTaggedPointer()) { - Class cls = obj->ISA(); - ptrdiff_t ivar_offset = ivar_getOffset(ivar); - if (_class_usesAutomaticRetainRelease(cls)) { - // for ARR, layout strings are relative to the instance start. - uint32_t instanceStart = _class_getInstanceStart(cls); - const uint8_t *weak_layout = class_getWeakIvarLayout(cls); - if (weak_layout && is_scanned_offset(ivar_offset - instanceStart, weak_layout)) { - // use the weak system to read this variable. - id *location = (id *)((char *)obj + ivar_offset); - return objc_loadWeak(location); - } - } - id *idx = (id *)((char *)obj + ivar_offset); -#if SUPPORT_GC - if (UseGC) { - const uint8_t *weak_layout = class_getWeakIvarLayout(cls); - if (weak_layout && is_scanned_offset(ivar_offset, weak_layout)) { - return objc_read_weak(idx); - } - } -#endif - return *idx; - } - return nil; -} - - -/*********************************************************************** -* object_cxxDestructFromClass. -* Call C++ destructors on obj, starting with cls's -* dtor method (if any) followed by superclasses' dtors (if any), -* stopping at cls's dtor (if any). -* Uses methodListLock and cacheUpdateLock. The caller must hold neither. -**********************************************************************/ -static void object_cxxDestructFromClass(id obj, Class cls) -{ - void (*dtor)(id); - - // Call cls's dtor first, then superclasses's dtors. - - for ( ; cls; cls = cls->superclass) { - if (!cls->hasCxxDtor()) return; - dtor = (void(*)(id)) - lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct); - if (dtor != (void(*)(id))_objc_msgForward_impcache) { - if (PrintCxxCtors) { - _objc_inform("CXX: calling C++ destructors for class %s", - cls->nameForLogging()); - } - (*dtor)(obj); - } - } -} - - -/*********************************************************************** -* object_cxxDestruct. -* Call C++ destructors on obj, if any. -* Uses methodListLock and cacheUpdateLock. The caller must hold neither. -**********************************************************************/ -void object_cxxDestruct(id obj) -{ - if (!obj) return; - if (obj->isTaggedPointer()) return; - object_cxxDestructFromClass(obj, obj->ISA()); -} - - -/*********************************************************************** -* object_cxxConstructFromClass. -* Recursively call C++ constructors on obj, starting with base class's -* ctor method (if any) followed by subclasses' ctors (if any), stopping -* at cls's ctor (if any). -* Does not check cls->hasCxxCtor(). The caller should preflight that. -* Returns self if construction succeeded. -* Returns nil if some constructor threw an exception. The exception is -* caught and discarded. Any partial construction is destructed. -* Uses methodListLock and cacheUpdateLock. The caller must hold neither. -* -* .cxx_construct returns id. This really means: -* return self: construction succeeded -* return nil: construction failed because a C++ constructor threw an exception -**********************************************************************/ -id -object_cxxConstructFromClass(id obj, Class cls) -{ - assert(cls->hasCxxCtor()); // required for performance, not correctness - - id (*ctor)(id); - Class supercls; - - supercls = cls->superclass; - - // Call superclasses' ctors first, if any. - if (supercls && supercls->hasCxxCtor()) { - bool ok = object_cxxConstructFromClass(obj, supercls); - if (!ok) return nil; // some superclass's ctor failed - give up - } - - // Find this class's ctor, if any. - ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct); - if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok - - // Call this class's ctor. - if (PrintCxxCtors) { - _objc_inform("CXX: calling C++ constructors for class %s", - cls->nameForLogging()); - } - if ((*ctor)(obj)) return obj; // ctor called and succeeded - ok - - // This class's ctor was called and failed. - // Call superclasses's dtors to clean up. - if (supercls) object_cxxDestructFromClass(obj, supercls); - return nil; -} - - -/*********************************************************************** -* _class_resolveClassMethod -* Call +resolveClassMethod, looking for a method to be added to class cls. -* cls should be a metaclass. -* Does not check if the method already exists. -**********************************************************************/ -static void _class_resolveClassMethod(Class cls, SEL sel, id inst) -{ - assert(cls->isMetaClass()); - - if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst, - NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) - { - // Resolver not implemented. - return; - } - - BOOL (*msg)(Class, SEL, SEL) = (__typeof__(msg))objc_msgSend; - bool resolved = msg(_class_getNonMetaClass(cls, inst), - SEL_resolveClassMethod, sel); - - // Cache the result (good or bad) so the resolver doesn't fire next time. - // +resolveClassMethod adds to self->ISA() a.k.a. cls - IMP imp = lookUpImpOrNil(cls, sel, inst, - NO/*initialize*/, YES/*cache*/, NO/*resolver*/); - - if (resolved && PrintResolving) { - if (imp) { - _objc_inform("RESOLVE: method %c[%s %s] " - "dynamically resolved to %p", - cls->isMetaClass() ? '+' : '-', - cls->nameForLogging(), sel_getName(sel), imp); - } - else { - // Method resolver didn't add anything? - _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES" - ", but no new implementation of %c[%s %s] was found", - cls->nameForLogging(), sel_getName(sel), - cls->isMetaClass() ? '+' : '-', - cls->nameForLogging(), sel_getName(sel)); - } - } -} - - -/*********************************************************************** -* _class_resolveInstanceMethod -* Call +resolveInstanceMethod, looking for a method to be added to class cls. -* cls may be a metaclass or a non-meta class. -* Does not check if the method already exists. -**********************************************************************/ -static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst) -{ - if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls, - NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) - { - // Resolver not implemented. - return; - } - - BOOL (*msg)(Class, SEL, SEL) = (__typeof__(msg))objc_msgSend; - bool resolved = msg(cls, SEL_resolveInstanceMethod, sel); - - // Cache the result (good or bad) so the resolver doesn't fire next time. - // +resolveInstanceMethod adds to self a.k.a. cls - IMP imp = lookUpImpOrNil(cls, sel, inst, - NO/*initialize*/, YES/*cache*/, NO/*resolver*/); - - if (resolved && PrintResolving) { - if (imp) { - _objc_inform("RESOLVE: method %c[%s %s] " - "dynamically resolved to %p", - cls->isMetaClass() ? '+' : '-', - cls->nameForLogging(), sel_getName(sel), imp); - } - else { - // Method resolver didn't add anything? - _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES" - ", but no new implementation of %c[%s %s] was found", - cls->nameForLogging(), sel_getName(sel), - cls->isMetaClass() ? '+' : '-', - cls->nameForLogging(), sel_getName(sel)); - } - } -} - - -/*********************************************************************** -* _class_resolveMethod -* Call +resolveClassMethod or +resolveInstanceMethod. -* Returns nothing; any result would be potentially out-of-date already. -* Does not check if the method already exists. -**********************************************************************/ -void _class_resolveMethod(Class cls, SEL sel, id inst) -{ - if (! cls->isMetaClass()) { - // try [cls resolveInstanceMethod:sel] - _class_resolveInstanceMethod(cls, sel, inst); - } - else { - // try [nonMetaClass resolveClassMethod:sel] - // and [cls resolveInstanceMethod:sel] - _class_resolveClassMethod(cls, sel, inst); - if (!lookUpImpOrNil(cls, sel, inst, - NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) - { - _class_resolveInstanceMethod(cls, sel, inst); - } - } -} - - -/*********************************************************************** -* class_getClassMethod. Return the class method for the specified -* class and selector. -**********************************************************************/ -Method class_getClassMethod(Class cls, SEL sel) -{ - if (!cls || !sel) return nil; - - return class_getInstanceMethod(cls->getMeta(), sel); -} - - -/*********************************************************************** -* class_getInstanceVariable. Return the named instance variable. -**********************************************************************/ -Ivar class_getInstanceVariable(Class cls, const char *name) -{ - if (!cls || !name) return nil; - - return _class_getVariable(cls, name, nil); -} - - -/*********************************************************************** -* class_getClassVariable. Return the named class variable. -**********************************************************************/ -Ivar class_getClassVariable(Class cls, const char *name) -{ - if (!cls) return nil; - - return class_getInstanceVariable(cls->ISA(), name); -} - - -/*********************************************************************** -* gdb_objc_class_changed -* Tell gdb that a class changed. Currently used for OBJC2 ivar layouts only -* Does nothing; gdb sets a breakpoint on it. -**********************************************************************/ -BREAKPOINT_FUNCTION( - void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname) -); - - -/*********************************************************************** -* class_respondsToSelector. -**********************************************************************/ -BOOL class_respondsToMethod(Class cls, SEL sel) -{ - OBJC_WARN_DEPRECATED; - - return class_respondsToSelector(cls, sel); -} - - -BOOL class_respondsToSelector(Class cls, SEL sel) -{ - return class_respondsToSelector_inst(cls, sel, nil); -} - - -// inst is an instance of cls or a subclass thereof, or nil if none is known. -// Non-nil inst is faster in some cases. See lookUpImpOrForward() for details. -bool class_respondsToSelector_inst(Class cls, SEL sel, id inst) -{ - IMP imp; - - if (!sel || !cls) return NO; - - // Avoids +initialize because it historically did so. - // We're not returning a callable IMP anyway. - imp = lookUpImpOrNil(cls, sel, inst, - NO/*initialize*/, YES/*cache*/, YES/*resolver*/); - return bool(imp); -} - - -/*********************************************************************** -* class_getMethodImplementation. -* Returns the IMP that would be invoked if [obj sel] were sent, -* where obj is an instance of class cls. -**********************************************************************/ -IMP class_lookupMethod(Class cls, SEL sel) -{ - OBJC_WARN_DEPRECATED; - - // No one responds to zero! - if (!sel) { - __objc_error(cls, "invalid selector (null)"); - } - - return class_getMethodImplementation(cls, sel); -} - -IMP class_getMethodImplementation(Class cls, SEL sel) -{ - IMP imp; - - if (!cls || !sel) return nil; - - imp = lookUpImpOrNil(cls, sel, nil, - YES/*initialize*/, YES/*cache*/, YES/*resolver*/); - - // Translate forwarding function to C-callable external version - if (!imp) { - return _objc_msgForward; - } - - return imp; -} - -#if SUPPORT_STRET -IMP class_getMethodImplementation_stret(Class cls, SEL sel) -{ - IMP imp = class_getMethodImplementation(cls, sel); - - // Translate forwarding function to struct-returning version - if (imp == (IMP)&_objc_msgForward /* not _internal! */) { - return (IMP)&_objc_msgForward_stret; - } - return imp; -} -#endif - - -/*********************************************************************** -* instrumentObjcMessageSends -**********************************************************************/ -#if !SUPPORT_MESSAGE_LOGGING - -void instrumentObjcMessageSends(BOOL flag) -{ -} - -#else - -bool objcMsgLogEnabled = false; -static int objcMsgLogFD = -1; - -bool logMessageSend(bool isClassMethod, - const char *objectsClass, - const char *implementingClass, - SEL selector) -{ - char buf[ 1024 ]; - - // Create/open the log file - if (objcMsgLogFD == (-1)) - { - snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ()); - objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid()); - if (objcMsgLogFD < 0) { - // no log file - disable logging - objcMsgLogEnabled = false; - objcMsgLogFD = -1; - return true; - } - } - - // Make the log entry - snprintf(buf, sizeof(buf), "%c %s %s %s\n", - isClassMethod ? '+' : '-', - objectsClass, - implementingClass, - sel_getName(selector)); - - static spinlock_t lock; - lock.lock(); - write (objcMsgLogFD, buf, strlen(buf)); - lock.unlock(); - - // Tell caller to not cache the method - return false; -} - -void instrumentObjcMessageSends(BOOL flag) -{ - bool enable = flag; - - // Shortcut NOP - if (objcMsgLogEnabled == enable) - return; - - // If enabling, flush all method caches so we get some traces - if (enable) - _objc_flush_caches(Nil); - - // Sync our log file - if (objcMsgLogFD != -1) - fsync (objcMsgLogFD); - - objcMsgLogEnabled = enable; -} - -// SUPPORT_MESSAGE_LOGGING -#endif - - -Class _calloc_class(size_t size) -{ -#if SUPPORT_GC - if (UseGC) return (Class) malloc_zone_calloc(gc_zone, 1, size); -#endif - return (Class) calloc(1, size); -} - -Class class_getSuperclass(Class cls) -{ - if (!cls) return nil; - return cls->superclass; -} - -BOOL class_isMetaClass(Class cls) -{ - if (!cls) return NO; - return cls->isMetaClass(); -} - - -size_t class_getInstanceSize(Class cls) -{ - if (!cls) return 0; - return cls->alignedInstanceSize(); -} - - -/*********************************************************************** -* method_getNumberOfArguments. -**********************************************************************/ -unsigned int method_getNumberOfArguments(Method m) -{ - if (!m) return 0; - return encoding_getNumberOfArguments(method_getTypeEncoding(m)); -} - - -void method_getReturnType(Method m, char *dst, size_t dst_len) -{ - encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len); -} - - -char * method_copyReturnType(Method m) -{ - return encoding_copyReturnType(method_getTypeEncoding(m)); -} - - -void method_getArgumentType(Method m, unsigned int index, - char *dst, size_t dst_len) -{ - encoding_getArgumentType(method_getTypeEncoding(m), - index, dst, dst_len); -} - - -char * method_copyArgumentType(Method m, unsigned int index) -{ - return encoding_copyArgumentType(method_getTypeEncoding(m), index); -} - - -/*********************************************************************** -* _objc_constructOrFree -* Call C++ constructors, and free() if they fail. -* bytes->isa must already be set. -* cls must have cxx constructors. -* Returns the object, or nil. -**********************************************************************/ -id -_objc_constructOrFree(id bytes, Class cls) -{ - assert(cls->hasCxxCtor()); // for performance, not correctness - - id obj = object_cxxConstructFromClass(bytes, cls); - if (!obj) { -#if SUPPORT_GC - if (UseGC) { - auto_zone_retain(gc_zone, bytes); // gc free expects rc==1 - } -#endif - free(bytes); - } - - return obj; -} - - -/*********************************************************************** -* _class_createInstancesFromZone -* Batch-allocating version of _class_createInstanceFromZone. -* Attempts to allocate num_requested objects, each with extraBytes. -* Returns the number of allocated objects (possibly zero), with -* the allocated pointers in *results. -**********************************************************************/ -unsigned -_class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone, - id *results, unsigned num_requested) -{ - unsigned num_allocated; - if (!cls) return 0; - - size_t size = cls->instanceSize(extraBytes); - -#if SUPPORT_GC - if (UseGC) { - num_allocated = - auto_zone_batch_allocate(gc_zone, size, AUTO_OBJECT_SCANNED, 0, 1, - (void**)results, num_requested); - } else -#endif - { - unsigned i; - num_allocated = - malloc_zone_batch_malloc((malloc_zone_t *)(zone ? zone : malloc_default_zone()), - size, (void**)results, num_requested); - for (i = 0; i < num_allocated; i++) { - bzero(results[i], size); - } - } - - // Construct each object, and delete any that fail construction. - - unsigned shift = 0; - unsigned i; - bool ctor = cls->hasCxxCtor(); - for (i = 0; i < num_allocated; i++) { - id obj = results[i]; - obj->initIsa(cls); // fixme allow indexed - if (ctor) obj = _objc_constructOrFree(obj, cls); - - if (obj) { - results[i-shift] = obj; - } else { - shift++; - } - } - - return num_allocated - shift; -} - - -/*********************************************************************** -* inform_duplicate. Complain about duplicate class implementations. -**********************************************************************/ -void -inform_duplicate(const char *name, Class oldCls, Class cls) -{ -#if TARGET_OS_WIN32 - (DebugDuplicateClasses ? _objc_fatal : _objc_inform) - ("Class %s is implemented in two different images.", name); -#else - const header_info *oldHeader = _headerForClass(oldCls); - const header_info *newHeader = _headerForClass(cls); - const char *oldName = oldHeader ? oldHeader->fname : "??"; - const char *newName = newHeader ? newHeader->fname : "??"; - - (DebugDuplicateClasses ? _objc_fatal : _objc_inform) - ("Class %s is implemented in both %s and %s. " - "One of the two will be used. Which one is undefined.", - name, oldName, newName); -#endif -} - - -const char * -copyPropertyAttributeString(const objc_property_attribute_t *attrs, - unsigned int count) -{ - char *result; - unsigned int i; - if (count == 0) return strdup(""); - -#if DEBUG - // debug build: sanitize input - for (i = 0; i < count; i++) { - assert(attrs[i].name); - assert(strlen(attrs[i].name) > 0); - assert(! strchr(attrs[i].name, ',')); - assert(! strchr(attrs[i].name, '"')); - if (attrs[i].value) assert(! strchr(attrs[i].value, ',')); - } -#endif - - size_t len = 0; - for (i = 0; i < count; i++) { - if (attrs[i].value) { - size_t namelen = strlen(attrs[i].name); - if (namelen > 1) namelen += 2; // long names get quoted - len += namelen + strlen(attrs[i].value) + 1; - } - } - - result = (char *)malloc(len + 1); - char *s = result; - for (i = 0; i < count; i++) { - if (attrs[i].value) { - size_t namelen = strlen(attrs[i].name); - if (namelen > 1) { - s += sprintf(s, "\"%s\"%s,", attrs[i].name, attrs[i].value); - } else { - s += sprintf(s, "%s%s,", attrs[i].name, attrs[i].value); - } - } - } - - // remove trailing ',' if any - if (s > result) s[-1] = '\0'; - - return result; -} - -/* - Property attribute string format: - - - Comma-separated name-value pairs. - - Name and value may not contain , - - Name may not contain " - - Value may be empty - - Name is single char, value follows - - OR Name is double-quoted string of 2+ chars, value follows - - Grammar: - attribute-string: \0 - attribute-string: name-value-pair (',' name-value-pair)* - name-value-pair: unquoted-name optional-value - name-value-pair: quoted-name optional-value - unquoted-name: [^",] - quoted-name: '"' [^",]{2,} '"' - optional-value: [^,]* - -*/ -static unsigned int -iteratePropertyAttributes(const char *attrs, - bool (*fn)(unsigned int index, - void *ctx1, void *ctx2, - const char *name, size_t nlen, - const char *value, size_t vlen), - void *ctx1, void *ctx2) -{ - if (!attrs) return 0; - -#if DEBUG - const char *attrsend = attrs + strlen(attrs); -#endif - unsigned int attrcount = 0; - - while (*attrs) { - // Find the next comma-separated attribute - const char *start = attrs; - const char *end = start + strcspn(attrs, ","); - - // Move attrs past this attribute and the comma (if any) - attrs = *end ? end+1 : end; - - assert(attrs <= attrsend); - assert(start <= attrsend); - assert(end <= attrsend); - - // Skip empty attribute - if (start == end) continue; - - // Process one non-empty comma-free attribute [start,end) - const char *nameStart; - const char *nameEnd; - - assert(start < end); - assert(*start); - if (*start != '\"') { - // single-char short name - nameStart = start; - nameEnd = start+1; - start++; - } - else { - // double-quoted long name - nameStart = start+1; - nameEnd = nameStart + strcspn(nameStart, "\","); - start++; // leading quote - start += nameEnd - nameStart; // name - if (*start == '\"') start++; // trailing quote, if any - } - - // Process one possibly-empty comma-free attribute value [start,end) - const char *valueStart; - const char *valueEnd; - - assert(start <= end); - - valueStart = start; - valueEnd = end; - - bool more = (*fn)(attrcount, ctx1, ctx2, - nameStart, nameEnd-nameStart, - valueStart, valueEnd-valueStart); - attrcount++; - if (!more) break; - } - - return attrcount; -} - - -static bool -copyOneAttribute(unsigned int index, void *ctxa, void *ctxs, - const char *name, size_t nlen, const char *value, size_t vlen) -{ - objc_property_attribute_t **ap = (objc_property_attribute_t**)ctxa; - char **sp = (char **)ctxs; - - objc_property_attribute_t *a = *ap; - char *s = *sp; - - a->name = s; - memcpy(s, name, nlen); - s += nlen; - *s++ = '\0'; - - a->value = s; - memcpy(s, value, vlen); - s += vlen; - *s++ = '\0'; - - a++; - - *ap = a; - *sp = s; - - return YES; -} - - -objc_property_attribute_t * -copyPropertyAttributeList(const char *attrs, unsigned int *outCount) -{ - if (!attrs) { - if (outCount) *outCount = 0; - return nil; - } - - // Result size: - // number of commas plus 1 for the attributes (upper bound) - // plus another attribute for the attribute array terminator - // plus strlen(attrs) for name/value string data (upper bound) - // plus count*2 for the name/value string terminators (upper bound) - unsigned int attrcount = 1; - const char *s; - for (s = attrs; s && *s; s++) { - if (*s == ',') attrcount++; - } - - size_t size = - attrcount * sizeof(objc_property_attribute_t) + - sizeof(objc_property_attribute_t) + - strlen(attrs) + - attrcount * 2; - objc_property_attribute_t *result = (objc_property_attribute_t *) - calloc(size, 1); - - objc_property_attribute_t *ra = result; - char *rs = (char *)(ra+attrcount+1); - - attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs); - - assert((uint8_t *)(ra+1) <= (uint8_t *)result+size); - assert((uint8_t *)rs <= (uint8_t *)result+size); - - if (attrcount == 0) { - free(result); - result = nil; - } - - if (outCount) *outCount = attrcount; - return result; -} - - -static bool -findOneAttribute(unsigned int index, void *ctxa, void *ctxs, - const char *name, size_t nlen, const char *value, size_t vlen) -{ - const char *query = (char *)ctxa; - char **resultp = (char **)ctxs; - - if (strlen(query) == nlen && 0 == strncmp(name, query, nlen)) { - char *result = (char *)calloc(vlen+1, 1); - memcpy(result, value, vlen); - result[vlen] = '\0'; - *resultp = result; - return NO; - } - - return YES; -} - -char *copyPropertyAttributeValue(const char *attrs, const char *name) -{ - char *result = nil; - - iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result); - - return result; -} diff --git a/objc/objc-runtime/runtime/objc-config.h b/objc/objc-runtime/runtime/objc-config.h deleted file mode 100644 index 4bf952e..0000000 --- a/objc/objc-runtime/runtime/objc-config.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 1999-2002, 2005-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@ - */ - -#ifndef _OBJC_CONFIG_H_ -#define _OBJC_CONFIG_H_ - -#include <TargetConditionals.h> - -// Avoid the !NDEBUG double negative. -#if !NDEBUG -# define DEBUG 1 -#else -# define DEBUG 0 -#endif - -// Define SUPPORT_GC=1 to enable garbage collection. -// Be sure to edit OBJC_NO_GC and OBJC_NO_GC_API in objc-api.h as well. -#if TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || (TARGET_OS_MAC && __x86_64h__) -# define SUPPORT_GC 0 -#else -# define SUPPORT_GC 1 -#endif - -// Define SUPPORT_ZONES=1 to enable malloc zone support in NXHashTable. -#if TARGET_OS_EMBEDDED || TARGET_OS_IPHONE -# define SUPPORT_ZONES 0 -#else -# define SUPPORT_ZONES 1 -#endif - -// Define SUPPORT_MOD=1 to use the mod operator in NXHashTable and objc-sel-set -#if defined(__arm__) -# define SUPPORT_MOD 0 -#else -# define SUPPORT_MOD 1 -#endif - -// Define SUPPORT_PREOPT=1 to enable dyld shared cache optimizations -#if TARGET_OS_WIN32 || TARGET_IPHONE_SIMULATOR -# define SUPPORT_PREOPT 0 -#else -# define SUPPORT_PREOPT 1 -#endif - -// Define SUPPORT_TAGGED_POINTERS=1 to enable tagged pointer objects -// Be sure to edit tagged pointer SPI in objc-internal.h as well. -#if !(__OBJC2__ && __LP64__) -# define SUPPORT_TAGGED_POINTERS 0 -#else -# define SUPPORT_TAGGED_POINTERS 1 -#endif - -// Define SUPPORT_MSB_TAGGED_POINTERS to use the MSB -// as the tagged pointer marker instead of the LSB. -// Be sure to edit tagged pointer SPI in objc-internal.h as well. -#if !SUPPORT_TAGGED_POINTERS || !TARGET_OS_IPHONE -# define SUPPORT_MSB_TAGGED_POINTERS 0 -#else -# define SUPPORT_MSB_TAGGED_POINTERS 1 -#endif - -// Define SUPPORT_NONPOINTER_ISA=1 to enable extra data in the isa field. -#if !__LP64__ || TARGET_OS_WIN32 || TARGET_IPHONE_SIMULATOR -# define SUPPORT_NONPOINTER_ISA 0 -#else -# define SUPPORT_NONPOINTER_ISA 1 -#endif - -// Define SUPPORT_FIXUP=1 to repair calls sites for fixup dispatch. -// Fixup messaging itself is no longer supported. -// Be sure to edit objc-abi.h as well (objc_msgSend*_fixup) -// Note TARGET_OS_MAC is also set for iOS simulator. -#if !__x86_64__ || !TARGET_OS_MAC -# define SUPPORT_FIXUP 0 -#else -# define SUPPORT_FIXUP 1 -#endif - -// Define SUPPORT_IGNORED_SELECTOR_CONSTANT to remap GC-ignored selectors. -// Good: fast ignore in objc_msgSend. Bad: disable shared cache optimizations -// Now used only for old-ABI GC. -// This is required for binary compatibility on 32-bit Mac: rdar://13757938 -#if __OBJC2__ || !SUPPORT_GC -# define SUPPORT_IGNORED_SELECTOR_CONSTANT 0 -#else -# define SUPPORT_IGNORED_SELECTOR_CONSTANT 1 -# if defined(__i386__) -# define kIgnore 0xfffeb010 -# else -# error unknown architecture -# endif -#endif - -// Define SUPPORT_ZEROCOST_EXCEPTIONS to use "zero-cost" exceptions for OBJC2. -// Be sure to edit objc-exception.h as well (objc_add/removeExceptionHandler) -#if !__OBJC2__ || (defined(__arm__) && __USING_SJLJ_EXCEPTIONS__) -# define SUPPORT_ZEROCOST_EXCEPTIONS 0 -#else -# define SUPPORT_ZEROCOST_EXCEPTIONS 1 -#endif - -// Define SUPPORT_ALT_HANDLERS if you're using zero-cost exceptions -// but also need to support AppKit's alt-handler scheme -// Be sure to edit objc-exception.h as well (objc_add/removeExceptionHandler) -#if !SUPPORT_ZEROCOST_EXCEPTIONS || TARGET_OS_IPHONE || TARGET_OS_EMBEDDED -# define SUPPORT_ALT_HANDLERS 0 -#else -# define SUPPORT_ALT_HANDLERS 1 -#endif - -// Define SUPPORT_RETURN_AUTORELEASE to optimize autoreleased return values -#if !__OBJC2__ || TARGET_OS_WIN32 -# define SUPPORT_RETURN_AUTORELEASE 0 -#else -# define SUPPORT_RETURN_AUTORELEASE 1 -#endif - -// Define SUPPORT_STRET on architectures that need separate struct-return ABI. -#if defined(__arm64__) -# define SUPPORT_STRET 0 -#else -# define SUPPORT_STRET 1 -#endif - -// Define SUPPORT_MESSAGE_LOGGING to enable NSObjCMessageLoggingEnabled -#if TARGET_OS_WIN32 || TARGET_OS_EMBEDDED -# define SUPPORT_MESSAGE_LOGGING 0 -#else -# define SUPPORT_MESSAGE_LOGGING 1 -#endif - -// Define SUPPORT_QOS_HACK to work around deadlocks due to QoS bugs. -#if !__OBJC2__ || TARGET_OS_WIN32 -# define SUPPORT_QOS_HACK 0 -#else -# define SUPPORT_QOS_HACK 1 -#endif - -// OBJC_INSTRUMENTED controls whether message dispatching is dynamically -// monitored. Monitoring introduces substantial overhead. -// NOTE: To define this condition, do so in the build command, NOT by -// uncommenting the line here. This is because objc-class.h heeds this -// condition, but objc-class.h can not #include this file (objc-config.h) -// because objc-class.h is public and objc-config.h is not. -//#define OBJC_INSTRUMENTED - -#endif diff --git a/objc/objc-runtime/runtime/objc-env.h b/objc/objc-runtime/runtime/objc-env.h deleted file mode 100644 index a9a18ad..0000000 --- a/objc/objc-runtime/runtime/objc-env.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- truncate-lines: t; -*- - -// OPTION(var, env, help) - -OPTION( PrintImages, OBJC_PRINT_IMAGES, "log image and library names as they are loaded") -OPTION( PrintImageTimes, OBJC_PRINT_IMAGE_TIMES, "measure duration of image loading steps") -OPTION( PrintLoading, OBJC_PRINT_LOAD_METHODS, "log calls to class and category +load methods") -OPTION( PrintInitializing, OBJC_PRINT_INITIALIZE_METHODS, "log calls to class +initialize methods") -OPTION( PrintResolving, OBJC_PRINT_RESOLVED_METHODS, "log methods created by +resolveClassMethod: and +resolveInstanceMethod:") -OPTION( PrintConnecting, OBJC_PRINT_CLASS_SETUP, "log progress of class and category setup") -OPTION( PrintProtocols, OBJC_PRINT_PROTOCOL_SETUP, "log progress of protocol setup") -OPTION( PrintIvars, OBJC_PRINT_IVAR_SETUP, "log processing of non-fragile ivars") -OPTION( PrintVtables, OBJC_PRINT_VTABLE_SETUP, "log processing of class vtables") -OPTION( PrintVtableImages, OBJC_PRINT_VTABLE_IMAGES, "print vtable images showing overridden methods") -OPTION( PrintCaches, OBJC_PRINT_CACHE_SETUP, "log processing of method caches") -OPTION( PrintFuture, OBJC_PRINT_FUTURE_CLASSES, "log use of future classes for toll-free bridging") -OPTION( PrintGC, OBJC_PRINT_GC, "log some GC operations") -OPTION( PrintPreopt, OBJC_PRINT_PREOPTIMIZATION, "log preoptimization courtesy of dyld shared cache") -OPTION( PrintCxxCtors, OBJC_PRINT_CXX_CTORS, "log calls to C++ ctors and dtors for instance variables") -OPTION( PrintExceptions, OBJC_PRINT_EXCEPTIONS, "log exception handling") -OPTION( PrintExceptionThrow, OBJC_PRINT_EXCEPTION_THROW, "log backtrace of every objc_exception_throw()") -OPTION( PrintAltHandlers, OBJC_PRINT_ALT_HANDLERS, "log processing of exception alt handlers") -OPTION( PrintReplacedMethods, OBJC_PRINT_REPLACED_METHODS, "log methods replaced by category implementations") -OPTION( PrintDeprecation, OBJC_PRINT_DEPRECATION_WARNINGS, "warn about calls to deprecated runtime functions") -OPTION( PrintPoolHiwat, OBJC_PRINT_POOL_HIGHWATER, "log high-water marks for autorelease pools") -OPTION( PrintCustomRR, OBJC_PRINT_CUSTOM_RR, "log classes with un-optimized custom retain/release methods") -OPTION( PrintCustomAWZ, OBJC_PRINT_CUSTOM_AWZ, "log classes with un-optimized custom allocWithZone methods") -OPTION( PrintRawIsa, OBJC_PRINT_RAW_ISA, "log classes that require raw pointer isa fields") - -OPTION( DebugUnload, OBJC_DEBUG_UNLOAD, "warn about poorly-behaving bundles when unloaded") -OPTION( DebugFragileSuperclasses, OBJC_DEBUG_FRAGILE_SUPERCLASSES, "warn about subclasses that may have been broken by subsequent changes to superclasses") -OPTION( DebugFinalizers, OBJC_DEBUG_FINALIZERS, "warn about classes that implement -dealloc but not -finalize") -OPTION( DebugNilSync, OBJC_DEBUG_NIL_SYNC, "warn about @synchronized(nil), which does no synchronization") -OPTION( DebugNonFragileIvars, OBJC_DEBUG_NONFRAGILE_IVARS, "capriciously rearrange non-fragile ivars") -OPTION( DebugAltHandlers, OBJC_DEBUG_ALT_HANDLERS, "record more info about bad alt handler use") -OPTION( DebugMissingPools, OBJC_DEBUG_MISSING_POOLS, "warn about autorelease with no pool in place, which may be a leak") -OPTION( DebugPoolAllocation, OBJC_DEBUG_POOL_ALLOCATION, "halt when autorelease pools are popped out of order, and allow heap debuggers to track autorelease pools") -OPTION( DebugDuplicateClasses, OBJC_DEBUG_DUPLICATE_CLASSES, "halt when multiple classes with the same name are present") - -OPTION( DisableGC, OBJC_DISABLE_GC, "force GC OFF, even if the executable wants it on") -OPTION( DisableVtables, OBJC_DISABLE_VTABLES, "disable vtable dispatch") -OPTION( DisablePreopt, OBJC_DISABLE_PREOPTIMIZATION, "disable preoptimization courtesy of dyld shared cache") -OPTION( DisableTaggedPointers, OBJC_DISABLE_TAGGED_POINTERS, "disable tagged pointer optimization of NSNumber et al.") -OPTION( DisableIndexedIsa, OBJC_DISABLE_NONPOINTER_ISA, "disable non-pointer isa fields") diff --git a/objc/objc-runtime/runtime/objc-errors.mm b/objc/objc-runtime/runtime/objc-errors.mm deleted file mode 100644 index fcc851a..0000000 --- a/objc/objc-runtime/runtime/objc-errors.mm +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (c) 1999-2003, 2005-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@ - */ -/* - * objc-errors.m - * Copyright 1988-2001, NeXT Software, Inc., Apple Computer, Inc. - */ - -#include "objc-private.h" - -#if TARGET_OS_WIN32 - -#include <conio.h> - -void _objc_inform_on_crash(const char *fmt, ...) -{ -} - -void _objc_inform(const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - _vcprintf(fmt, args); - va_end(args); - _cprintf("\n"); -} - -void _objc_fatal(const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - _vcprintf(fmt, args); - va_end(args); - _cprintf("\n"); - - abort(); -} - -void __objc_error(id rcv, const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - _vcprintf(fmt, args); - va_end(args); - - abort(); -} - -void _objc_error(id rcv, const char *fmt, va_list args) -{ - _vcprintf(fmt, args); - - abort(); -} - -#else - -#include <vproc_priv.h> -//#include <_simple.h> - -OBJC_EXPORT void (*_error)(id, const char *, va_list); - -static void _objc_trap(void) __attribute__((noreturn)); - -// Return true if c is a UTF8 continuation byte -static bool isUTF8Continuation(char c) -{ - return (c & 0xc0) == 0x80; // continuation byte is 0b10xxxxxx -} - -// Add "message" to any forthcoming crash log. -static void _objc_crashlog(const char *message) -{ - char *newmsg; - -#if 0 - { - // for debugging at BOOT time. - extern char **_NSGetProgname(void); - FILE *crashlog = fopen("/_objc_crash.log", "a"); - setbuf(crashlog, NULL); - fprintf(crashlog, "[%s] %s\n", *_NSGetProgname(), message); - fclose(crashlog); - sync(); - } -#endif - - static mutex_t crashlog_lock; - mutex_locker_t lock(crashlog_lock); - - char *oldmsg = (char *)CRGetCrashLogMessage(); - size_t oldlen; - const size_t limit = 8000; - - if (!oldmsg) { - newmsg = strdup(message); - } else if ((oldlen = strlen(oldmsg)) > limit) { - // limit total length by dropping old contents - char *truncmsg = oldmsg + oldlen - limit; - // advance past partial UTF-8 bytes - while (isUTF8Continuation(*truncmsg)) truncmsg++; - asprintf(&newmsg, "... %s\n%s", truncmsg, message); - } else { - asprintf(&newmsg, "%s\n%s", oldmsg, message); - } - - if (newmsg) { - // Strip trailing newline - char *c = &newmsg[strlen(newmsg)-1]; - if (*c == '\n') *c = '\0'; - - if (oldmsg) free(oldmsg); - CRSetCrashLogMessage(newmsg); - } -} - -// Returns true if logs should be sent to stderr as well as syslog. -// Copied from CFUtilities.c -static bool also_do_stderr(void) -{ - struct stat st; - int ret = fstat(STDERR_FILENO, &st); - if (ret < 0) return false; - mode_t m = st.st_mode & S_IFMT; - if (m == S_IFREG || m == S_IFSOCK || m == S_IFIFO || m == S_IFCHR) { - return true; - } - return false; -} - -// Print "message" to the console. -static void _objc_syslog(const char *message) -{ -// _simple_asl_log(ASL_LEVEL_ERR, nil, message); - - if (also_do_stderr()) { - write(STDERR_FILENO, message, strlen(message)); - } -} - -/* - * _objc_error is the default *_error handler. - */ -#if __OBJC2__ -__attribute__((noreturn)) -#else -// used by ExceptionHandling.framework -#endif -void _objc_error(id self, const char *fmt, va_list ap) -{ - char *buf1; - char *buf2; - - vasprintf(&buf1, fmt, ap); - asprintf(&buf2, "objc[%d]: %s: %s\n", - getpid(), object_getClassName(self), buf1); - _objc_syslog(buf2); - _objc_crashlog(buf2); - - _objc_trap(); -} - -/* - * this routine handles errors that involve an object (or class). - */ -void __objc_error(id rcv, const char *fmt, ...) -{ - va_list vp; - - va_start(vp,fmt); -#if !__OBJC2__ - (*_error)(rcv, fmt, vp); -#endif - _objc_error (rcv, fmt, vp); /* In case (*_error)() returns. */ - va_end(vp); -} - -/* - * this routine handles severe runtime errors...like not being able - * to read the mach headers, allocate space, etc...very uncommon. - */ -void _objc_fatal(const char *fmt, ...) -{ - va_list ap; - char *buf1; - char *buf2; - - va_start(ap,fmt); - vasprintf(&buf1, fmt, ap); - va_end (ap); - - asprintf(&buf2, "objc[%d]: %s\n", getpid(), buf1); - _objc_syslog(buf2); - _objc_crashlog(buf2); - - _objc_trap(); -} - -/* - * this routine handles soft runtime errors...like not being able - * add a category to a class (because it wasn't linked in). - */ -void _objc_inform(const char *fmt, ...) -{ - va_list ap; - char *buf1; - char *buf2; - - va_start (ap,fmt); - vasprintf(&buf1, fmt, ap); - va_end (ap); - - asprintf(&buf2, "objc[%d]: %s\n", getpid(), buf1); - _objc_syslog(buf2); - - free(buf2); - free(buf1); -} - - -/* - * Like _objc_inform(), but prints the message only in any - * forthcoming crash log, not to the console. - */ -void _objc_inform_on_crash(const char *fmt, ...) -{ - va_list ap; - char *buf1; - char *buf2; - - va_start (ap,fmt); - vasprintf(&buf1, fmt, ap); - va_end (ap); - - asprintf(&buf2, "objc[%d]: %s\n", getpid(), buf1); - _objc_crashlog(buf2); - - free(buf2); - free(buf1); -} - - -/* - * Like calling both _objc_inform and _objc_inform_on_crash. - */ -void _objc_inform_now_and_on_crash(const char *fmt, ...) -{ - va_list ap; - char *buf1; - char *buf2; - - va_start (ap,fmt); - vasprintf(&buf1, fmt, ap); - va_end (ap); - - asprintf(&buf2, "objc[%d]: %s\n", getpid(), buf1); - _objc_crashlog(buf2); - _objc_syslog(buf2); - - free(buf2); - free(buf1); -} - - -/* Kill the process in a way that generates a crash log. - * This is better than calling exit(). */ -static void _objc_trap(void) -{ - __builtin_trap(); -} - -/* Try to keep _objc_warn_deprecated out of crash logs - * caused by _objc_trap(). rdar://4546883 */ -__attribute__((used)) -static void _objc_trap2(void) -{ - __builtin_trap(); -} - -#endif - - -BREAKPOINT_FUNCTION( - void _objc_warn_deprecated(void) -); - -void _objc_inform_deprecated(const char *oldf, const char *newf) -{ - if (PrintDeprecation) { - if (newf) { - _objc_inform("The function %s is obsolete. Use %s instead. Set a breakpoint on _objc_warn_deprecated to find the culprit.", oldf, newf); - } else { - _objc_inform("The function %s is obsolete. Do not use it. Set a breakpoint on _objc_warn_deprecated to find the culprit.", oldf); - } - } - _objc_warn_deprecated(); -} diff --git a/objc/objc-runtime/runtime/objc-exception.h b/objc/objc-runtime/runtime/objc-exception.h deleted file mode 100644 index 40668af..0000000 --- a/objc/objc-runtime/runtime/objc-exception.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2002-2003, 2006-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@ - */ - -#ifndef __OBJC_EXCEPTION_H_ -#define __OBJC_EXCEPTION_H_ - -#include <objc/objc.h> -#include <stdint.h> - -#if !__OBJC2__ - -// compiler reserves a setjmp buffer + 4 words as localExceptionData - -OBJC_EXPORT void objc_exception_throw(id exception) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); -OBJC_EXPORT void objc_exception_try_enter(void *localExceptionData) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); -OBJC_EXPORT void objc_exception_try_exit(void *localExceptionData) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); -OBJC_EXPORT id objc_exception_extract(void *localExceptionData) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); -OBJC_EXPORT int objc_exception_match(Class exceptionClass, id exception) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - - -typedef struct { - int version; - void (*throw_exc)(id); // version 0 - void (*try_enter)(void *); // version 0 - void (*try_exit)(void *); // version 0 - id (*extract)(void *); // version 0 - int (*match)(Class, id); // version 0 -} objc_exception_functions_t; - -// get table; version tells how many -OBJC_EXPORT void objc_exception_get_functions(objc_exception_functions_t *table) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - -// set table -OBJC_EXPORT void objc_exception_set_functions(objc_exception_functions_t *table) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - - -// !__OBJC2__ -#else -// __OBJC2__ - -typedef id (*objc_exception_preprocessor)(id exception); -typedef int (*objc_exception_matcher)(Class catch_type, id exception); -typedef void (*objc_uncaught_exception_handler)(id exception); -typedef void (*objc_exception_handler)(id unused, void *context); - -/** - * Throw a runtime exception. This function is inserted by the compiler - * where \c @throw would otherwise be. - * - * @param exception The exception to be thrown. - */ -OBJC_EXPORT void objc_exception_throw(id exception) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_exception_rethrow(void) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT id objc_begin_catch(void *exc_buf) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_end_catch(void) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT void objc_terminate(void) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); - -OBJC_EXPORT objc_exception_preprocessor objc_setExceptionPreprocessor(objc_exception_preprocessor fn) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT objc_exception_matcher objc_setExceptionMatcher(objc_exception_matcher fn) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT objc_uncaught_exception_handler objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -// Not for iOS. -OBJC_EXPORT uintptr_t objc_addExceptionHandler(objc_exception_handler fn, void *context) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); -OBJC_EXPORT void objc_removeExceptionHandler(uintptr_t token) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - -// __OBJC2__ -#endif - -#endif // __OBJC_EXCEPTION_H_ - diff --git a/objc/objc-runtime/runtime/objc-exception.mm b/objc/objc-runtime/runtime/objc-exception.mm deleted file mode 100644 index e9dbf2c..0000000 --- a/objc/objc-runtime/runtime/objc-exception.mm +++ /dev/null @@ -1,1427 +0,0 @@ -/* - * Copyright (c) 2002-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@ - */ - -#if !__OBJC2__ - -/*********************************************************************** -* 32-bit implementation -**********************************************************************/ - -#include "objc-private.h" -#include <stdlib.h> -#include <setjmp.h> -#include <execinfo.h> - -#include "objc-exception.h" - -static objc_exception_functions_t xtab; - -// forward declaration -static void set_default_handlers(); - - -/* - * Exported functions - */ - -// get table; version tells how many -void objc_exception_get_functions(objc_exception_functions_t *table) { - // only version 0 supported at this point - if (table && table->version == 0) - *table = xtab; -} - -// set table -void objc_exception_set_functions(objc_exception_functions_t *table) { - // only version 0 supported at this point - if (table && table->version == 0) - xtab = *table; -} - -/* - * The following functions are - * synthesized by the compiler upon encountering language constructs - */ - -void objc_exception_throw(id exception) { - if (!xtab.throw_exc) { - set_default_handlers(); - } - - if (PrintExceptionThrow) { - _objc_inform("EXCEPTIONS: throwing %p (%s)", - (void*)exception, object_getClassName(exception)); - void* callstack[500]; - int frameCount = backtrace(callstack, 500); - backtrace_symbols_fd(callstack, frameCount, fileno(stderr)); - } - - OBJC_RUNTIME_OBJC_EXCEPTION_THROW(exception); // dtrace probe to log throw activity. - xtab.throw_exc(exception); - _objc_fatal("objc_exception_throw failed"); -} - -void objc_exception_try_enter(void *localExceptionData) { - if (!xtab.throw_exc) { - set_default_handlers(); - } - xtab.try_enter(localExceptionData); -} - - -void objc_exception_try_exit(void *localExceptionData) { - if (!xtab.throw_exc) { - set_default_handlers(); - } - xtab.try_exit(localExceptionData); -} - - -id objc_exception_extract(void *localExceptionData) { - if (!xtab.throw_exc) { - set_default_handlers(); - } - return xtab.extract(localExceptionData); -} - - -int objc_exception_match(Class exceptionClass, id exception) { - if (!xtab.throw_exc) { - set_default_handlers(); - } - return xtab.match(exceptionClass, exception); -} - - -// quick and dirty exception handling code -// default implementation - mostly a toy for use outside/before Foundation -// provides its implementation -// Perhaps the default implementation should just complain loudly and quit - - -extern void _objc_inform(const char *fmt, ...); - -typedef struct { jmp_buf buf; void *pointers[4]; } LocalData_t; - -typedef struct _threadChain { - LocalData_t *topHandler; - objc_thread_t perThreadID; - struct _threadChain *next; -} - ThreadChainLink_t; - -static ThreadChainLink_t ThreadChainLink; - -static ThreadChainLink_t *getChainLink() { - // follow links until thread_self() found (someday) XXX - objc_thread_t self = thread_self(); - ThreadChainLink_t *walker = &ThreadChainLink; - while (walker->perThreadID != self) { - if (walker->next != nil) { - walker = walker->next; - continue; - } - // create a new one - // XXX not thread safe (!) - // XXX Also, we don't register to deallocate on thread death - walker->next = (ThreadChainLink_t *)malloc(sizeof(ThreadChainLink_t)); - walker = walker->next; - walker->next = nil; - walker->topHandler = nil; - walker->perThreadID = self; - } - return walker; -} - -static void default_try_enter(void *localExceptionData) { - LocalData_t *data = (LocalData_t *)localExceptionData; - ThreadChainLink_t *chainLink = getChainLink(); - data->pointers[1] = chainLink->topHandler; - chainLink->topHandler = data; - if (PrintExceptions) _objc_inform("EXCEPTIONS: entered try block %p\n", chainLink->topHandler); -} - -static void default_throw(id value) { - ThreadChainLink_t *chainLink = getChainLink(); - LocalData_t *led; - if (value == nil) { - if (PrintExceptions) _objc_inform("EXCEPTIONS: objc_exception_throw with nil value\n"); - return; - } - if (chainLink == nil) { - if (PrintExceptions) _objc_inform("EXCEPTIONS: No handler in place!\n"); - return; - } - if (PrintExceptions) _objc_inform("EXCEPTIONS: exception thrown, going to handler block %p\n", chainLink->topHandler); - led = chainLink->topHandler; - chainLink->topHandler = (LocalData_t *) - led->pointers[1]; // pop top handler - led->pointers[0] = value; // store exception that is thrown -#if TARGET_OS_WIN32 - longjmp(led->buf, 1); -#else - _longjmp(led->buf, 1); -#endif -} - -static void default_try_exit(void *led) { - ThreadChainLink_t *chainLink = getChainLink(); - if (!chainLink || led != chainLink->topHandler) { - if (PrintExceptions) _objc_inform("EXCEPTIONS: *** mismatched try block exit handlers\n"); - return; - } - if (PrintExceptions) _objc_inform("EXCEPTIONS: removing try block handler %p\n", chainLink->topHandler); - chainLink->topHandler = (LocalData_t *) - chainLink->topHandler->pointers[1]; // pop top handler -} - -static id default_extract(void *localExceptionData) { - LocalData_t *led = (LocalData_t *)localExceptionData; - return (id)led->pointers[0]; -} - -static int default_match(Class exceptionClass, id exception) { - //return [exception isKindOfClass:exceptionClass]; - Class cls; - for (cls = exception->getIsa(); nil != cls; cls = cls->superclass) - if (cls == exceptionClass) return 1; - return 0; -} - -static void set_default_handlers() { - objc_exception_functions_t default_functions = { - 0, default_throw, default_try_enter, default_try_exit, default_extract, default_match }; - - // should this always print? - if (PrintExceptions) _objc_inform("EXCEPTIONS: *** Setting default (non-Foundation) exception mechanism\n"); - objc_exception_set_functions(&default_functions); -} - - -void exception_init(void) -{ - // nothing to do -} - -void _destroyAltHandlerList(struct alt_handler_list *list) -{ - // nothing to do -} - - -// !__OBJC2__ -#else -// __OBJC2__ - -/*********************************************************************** -* 64-bit implementation. -**********************************************************************/ - -#include "objc-private.h" -#include <objc/objc-exception.h> -#include <objc/NSObject.h> -#include <execinfo.h> - -// unwind library types and functions -// Mostly adapted from Itanium C++ ABI: Exception Handling -// http://www.codesourcery.com/cxx-abi/abi-eh.html - -struct _Unwind_Exception; -struct _Unwind_Context; - -typedef int _Unwind_Action; -enum : _Unwind_Action { - _UA_SEARCH_PHASE = 1, - _UA_CLEANUP_PHASE = 2, - _UA_HANDLER_FRAME = 4, - _UA_FORCE_UNWIND = 8 -}; - -typedef int _Unwind_Reason_Code; -enum : _Unwind_Reason_Code { - _URC_NO_REASON = 0, - _URC_FOREIGN_EXCEPTION_CAUGHT = 1, - _URC_FATAL_PHASE2_ERROR = 2, - _URC_FATAL_PHASE1_ERROR = 3, - _URC_NORMAL_STOP = 4, - _URC_END_OF_STACK = 5, - _URC_HANDLER_FOUND = 6, - _URC_INSTALL_CONTEXT = 7, - _URC_CONTINUE_UNWIND = 8 -}; - -struct dwarf_eh_bases -{ - uintptr_t tbase; - uintptr_t dbase; - uintptr_t func; -}; - -OBJC_EXTERN uintptr_t _Unwind_GetIP (struct _Unwind_Context *); -OBJC_EXTERN uintptr_t _Unwind_GetCFA (struct _Unwind_Context *); -OBJC_EXTERN uintptr_t _Unwind_GetLanguageSpecificData(struct _Unwind_Context *); - - -// C++ runtime types and functions -// copied from cxxabi.h - -OBJC_EXTERN void *__cxa_allocate_exception(size_t thrown_size); -OBJC_EXTERN void __cxa_throw(void *exc, void *typeinfo, void (*destructor)(void *)) __attribute__((noreturn)); -OBJC_EXTERN void *__cxa_begin_catch(void *exc); -OBJC_EXTERN void __cxa_end_catch(void); -OBJC_EXTERN void __cxa_rethrow(void); -OBJC_EXTERN void *__cxa_current_exception_type(void); - -#if SUPPORT_ZEROCOST_EXCEPTIONS -# define CXX_PERSONALITY __gxx_personality_v0 -#else -# define CXX_PERSONALITY __gxx_personality_sj0 -#endif - -OBJC_EXTERN _Unwind_Reason_Code -CXX_PERSONALITY(int version, - _Unwind_Action actions, - uint64_t exceptionClass, - struct _Unwind_Exception *exceptionObject, - struct _Unwind_Context *context); - - -// objc's internal exception types and data - -struct objc_typeinfo { - // Position of vtable and name fields must match C++ typeinfo object - const void **vtable; // always objc_ehtype_vtable+2 - const char *name; // c++ typeinfo string - - Class cls_unremapped; -}; - -struct objc_exception { - id obj; - struct objc_typeinfo tinfo; -}; - - -static void _objc_exception_noop(void) { } -static bool _objc_exception_false(void) { return 0; } -// static bool _objc_exception_true(void) { return 1; } -static void _objc_exception_abort1(void) { - _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 1); -} -static void _objc_exception_abort2(void) { - _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 2); -} -static void _objc_exception_abort3(void) { - _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 3); -} -static void _objc_exception_abort4(void) { - _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 4); -} - -static bool _objc_exception_do_catch(struct objc_typeinfo *catch_tinfo, - struct objc_typeinfo *throw_tinfo, - void **throw_obj_p, - unsigned outer); - -// forward declaration -OBJC_EXPORT struct objc_typeinfo OBJC_EHTYPE_id; - -OBJC_EXPORT -const void *objc_ehtype_vtable[] = { - nil, // typeinfo's vtable? - fixme - (void*)&OBJC_EHTYPE_id, // typeinfo's typeinfo - hack - (void*)_objc_exception_noop, // in-place destructor? - (void*)_objc_exception_noop, // destructor? - (void*)_objc_exception_false, // OLD __is_pointer_p - (void*)_objc_exception_false, // OLD __is_function_p - (void*)_objc_exception_do_catch, // OLD __do_catch, NEW can_catch - (void*)_objc_exception_false, // OLD __do_upcast, NEW search_above_dst - (void*)_objc_exception_false, // NEW search_below_dst - (void*)_objc_exception_abort1, // paranoia: blow up if libc++abi - (void*)_objc_exception_abort2, // adds something new - (void*)_objc_exception_abort3, - (void*)_objc_exception_abort4, -}; - -OBJC_EXPORT -struct objc_typeinfo OBJC_EHTYPE_id = { - objc_ehtype_vtable+2, - "id", - nil -}; - - - -/*********************************************************************** -* Foundation customization -**********************************************************************/ - -/*********************************************************************** -* _objc_default_exception_preprocessor -* Default exception preprocessor. Expected to be overridden by Foundation. -**********************************************************************/ -static id _objc_default_exception_preprocessor(id exception) -{ - return exception; -} -static objc_exception_preprocessor exception_preprocessor = _objc_default_exception_preprocessor; - - -/*********************************************************************** -* _objc_default_exception_matcher -* Default exception matcher. Expected to be overridden by Foundation. -**********************************************************************/ -static int _objc_default_exception_matcher(Class catch_cls, id exception) -{ - Class cls; - for (cls = exception->getIsa(); - cls != nil; - cls = cls->superclass) - { - if (cls == catch_cls) return 1; - } - - return 0; -} -static objc_exception_matcher exception_matcher = _objc_default_exception_matcher; - - -/*********************************************************************** -* _objc_default_uncaught_exception_handler -* Default uncaught exception handler. Expected to be overridden by Foundation. -**********************************************************************/ -static void _objc_default_uncaught_exception_handler(id exception) -{ -} -static objc_uncaught_exception_handler uncaught_handler = _objc_default_uncaught_exception_handler; - - -/*********************************************************************** -* objc_setExceptionPreprocessor -* Set a handler for preprocessing Objective-C exceptions. -* Returns the previous handler. -**********************************************************************/ -objc_exception_preprocessor -objc_setExceptionPreprocessor(objc_exception_preprocessor fn) -{ - objc_exception_preprocessor result = exception_preprocessor; - exception_preprocessor = fn; - return result; -} - - -/*********************************************************************** -* objc_setExceptionMatcher -* Set a handler for matching Objective-C exceptions. -* Returns the previous handler. -**********************************************************************/ -objc_exception_matcher -objc_setExceptionMatcher(objc_exception_matcher fn) -{ - objc_exception_matcher result = exception_matcher; - exception_matcher = fn; - return result; -} - - -/*********************************************************************** -* objc_setUncaughtExceptionHandler -* Set a handler for uncaught Objective-C exceptions. -* Returns the previous handler. -**********************************************************************/ -objc_uncaught_exception_handler -objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn) -{ - objc_uncaught_exception_handler result = uncaught_handler; - uncaught_handler = fn; - return result; -} - - -/*********************************************************************** -* Exception personality -**********************************************************************/ - -static void call_alt_handlers(struct _Unwind_Context *ctx); - -_Unwind_Reason_Code -__objc_personality_v0(int version, - _Unwind_Action actions, - uint64_t exceptionClass, - struct _Unwind_Exception *exceptionObject, - struct _Unwind_Context *context) -{ - bool unwinding = ((actions & _UA_CLEANUP_PHASE) || - (actions & _UA_FORCE_UNWIND)); - - if (PrintExceptions) { - _objc_inform("EXCEPTIONS: %s through frame [ip=%p sp=%p] " - "for exception %p", - unwinding ? "unwinding" : "searching", - (void*)(_Unwind_GetIP(context)-1), - (void*)_Unwind_GetCFA(context), exceptionObject); - } - - // If we're executing the unwind, call this frame's alt handlers, if any. - if (unwinding) { - call_alt_handlers(context); - } - - // Let C++ handle the unwind itself. - return CXX_PERSONALITY(version, actions, exceptionClass, - exceptionObject, context); -} - - -/*********************************************************************** -* Compiler ABI -**********************************************************************/ - -static void _objc_exception_destructor(void *exc_gen) -{ - // Release the retain from objc_exception_throw(). - - struct objc_exception *exc = (struct objc_exception *)exc_gen; - id obj = exc->obj; - - if (PrintExceptions) { - _objc_inform("EXCEPTIONS: releasing completed exception %p (object %p, a %s)", - exc, obj, object_getClassName(obj)); - } - -#if SUPPORT_GC - if (UseGC) { - if (auto_zone_is_valid_pointer(gc_zone, obj)) { - auto_zone_release(gc_zone, exc->obj); - } - } - else -#endif - { - [obj release]; - } -} - - -void objc_exception_throw(id obj) -{ - struct objc_exception *exc = (struct objc_exception *) - __cxa_allocate_exception(sizeof(struct objc_exception)); - - obj = (*exception_preprocessor)(obj); - - // Retain the exception object during unwinding. - // GC: because `exc` is unscanned memory - // Non-GC: because otherwise an autorelease pool pop can cause a crash -#if SUPPORT_GC - if (UseGC) { - if (auto_zone_is_valid_pointer(gc_zone, obj)) { - auto_zone_retain(gc_zone, obj); - } - } - else -#endif - { - [obj retain]; - } - - exc->obj = obj; - exc->tinfo.vtable = objc_ehtype_vtable+2; - exc->tinfo.name = object_getClassName(obj); - exc->tinfo.cls_unremapped = obj ? obj->getIsa() : Nil; - - if (PrintExceptions) { - _objc_inform("EXCEPTIONS: throwing %p (object %p, a %s)", - exc, (void*)obj, object_getClassName(obj)); - } - - if (PrintExceptionThrow) { - if (!PrintExceptions) - _objc_inform("EXCEPTIONS: throwing %p (object %p, a %s)", - exc, (void*)obj, object_getClassName(obj)); - void* callstack[500]; - int frameCount = backtrace(callstack, 500); - backtrace_symbols_fd(callstack, frameCount, fileno(stderr)); - } - - OBJC_RUNTIME_OBJC_EXCEPTION_THROW(obj); // dtrace probe to log throw activity - __cxa_throw(exc, &exc->tinfo, &_objc_exception_destructor); - __builtin_trap(); -} - - -void objc_exception_rethrow(void) -{ - // exception_preprocessor doesn't get another bite of the apple - if (PrintExceptions) { - _objc_inform("EXCEPTIONS: rethrowing current exception"); - } - - OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW(); // dtrace probe to log throw activity. - __cxa_rethrow(); - __builtin_trap(); -} - - -id objc_begin_catch(void *exc_gen) -{ - if (PrintExceptions) { - _objc_inform("EXCEPTIONS: handling exception %p at %p", - exc_gen, __builtin_return_address(0)); - } - // NOT actually an id in the catch(...) case! - return (id)__cxa_begin_catch(exc_gen); -} - - -void objc_end_catch(void) -{ - if (PrintExceptions) { - _objc_inform("EXCEPTIONS: finishing handler"); - } - __cxa_end_catch(); -} - - -// `outer` is not passed by the new libcxxabi -static bool _objc_exception_do_catch(struct objc_typeinfo *catch_tinfo, - struct objc_typeinfo *throw_tinfo, - void **throw_obj_p, - unsigned outer UNAVAILABLE_ATTRIBUTE) -{ - id exception; - - if (throw_tinfo->vtable != objc_ehtype_vtable+2) { - // Only objc types can be caught here. - if (PrintExceptions) _objc_inform("EXCEPTIONS: skipping catch(?)"); - return false; - } - - // Adjust exception pointer. - // Old libcppabi: we lied about __is_pointer_p() so we have to do it here - // New libcxxabi: we have to do it here regardless - *throw_obj_p = **(void***)throw_obj_p; - - // `catch (id)` always catches objc types. - if (catch_tinfo == &OBJC_EHTYPE_id) { - if (PrintExceptions) _objc_inform("EXCEPTIONS: catch(id)"); - return true; - } - - exception = *(id *)throw_obj_p; - - Class handler_cls = _class_remap(catch_tinfo->cls_unremapped); - if (!handler_cls) { - // catch handler's class is weak-linked and missing. Not a match. - } - else if ((*exception_matcher)(handler_cls, exception)) { - if (PrintExceptions) _objc_inform("EXCEPTIONS: catch(%s)", - handler_cls->nameForLogging()); - return true; - } - - if (PrintExceptions) _objc_inform("EXCEPTIONS: skipping catch(%s)", - handler_cls->nameForLogging()); - - return false; -} - - -/*********************************************************************** -* _objc_terminate -* Custom std::terminate handler. -* -* The uncaught exception callback is implemented as a std::terminate handler. -* 1. Check if there's an active exception -* 2. If so, check if it's an Objective-C exception -* 3. If so, call our registered callback with the object. -* 4. Finally, call the previous terminate handler. -**********************************************************************/ -static void (*old_terminate)(void) = nil; -static void _objc_terminate(void) -{ - if (PrintExceptions) { - _objc_inform("EXCEPTIONS: terminating"); - } - - if (! __cxa_current_exception_type()) { - // No current exception. - (*old_terminate)(); - } - else { - // There is a current exception. Check if it's an objc exception. - @try { - __cxa_rethrow(); - } @catch (id e) { - // It's an objc object. Call Foundation's handler, if any. - (*uncaught_handler)((id)e); - (*old_terminate)(); - } @catch (...) { - // It's not an objc object. Continue to C++ terminate. - (*old_terminate)(); - } - } -} - - -/*********************************************************************** -* objc_terminate -* Calls std::terminate for clients who don't link to C++ themselves. -* Called by the compiler if an exception is thrown -* from a context where exceptions may not be thrown. -**********************************************************************/ -void objc_terminate(void) -{ - std::terminate(); -} - - -/*********************************************************************** -* alt handler support - zerocost implementation only -**********************************************************************/ - -#if !SUPPORT_ALT_HANDLERS - -void _destroyAltHandlerList(struct alt_handler_list *list) -{ -} - -static void call_alt_handlers(struct _Unwind_Context *ctx) -{ - // unsupported in sjlj environments -} - -#else - -#include <libunwind.h> -#include <execinfo.h> -#include <dispatch/dispatch.h> - -// Dwarf eh data encodings -#define DW_EH_PE_omit 0xff // no data follows - -#define DW_EH_PE_absptr 0x00 -#define DW_EH_PE_uleb128 0x01 -#define DW_EH_PE_udata2 0x02 -#define DW_EH_PE_udata4 0x03 -#define DW_EH_PE_udata8 0x04 -#define DW_EH_PE_sleb128 0x09 -#define DW_EH_PE_sdata2 0x0A -#define DW_EH_PE_sdata4 0x0B -#define DW_EH_PE_sdata8 0x0C - -#define DW_EH_PE_pcrel 0x10 -#define DW_EH_PE_textrel 0x20 -#define DW_EH_PE_datarel 0x30 -#define DW_EH_PE_funcrel 0x40 -#define DW_EH_PE_aligned 0x50 // fixme - -#define DW_EH_PE_indirect 0x80 // gcc extension - - -/*********************************************************************** -* read_uleb -* Read a LEB-encoded unsigned integer from the address stored in *pp. -* Increments *pp past the bytes read. -* Adapted from DWARF Debugging Information Format 1.1, appendix 4 -**********************************************************************/ -static uintptr_t read_uleb(uintptr_t *pp) -{ - uintptr_t result = 0; - uintptr_t shift = 0; - unsigned char byte; - do { - byte = *(const unsigned char *)(*pp)++; - result |= (byte & 0x7f) << shift; - shift += 7; - } while (byte & 0x80); - return result; -} - - -/*********************************************************************** -* read_sleb -* Read a LEB-encoded signed integer from the address stored in *pp. -* Increments *pp past the bytes read. -* Adapted from DWARF Debugging Information Format 1.1, appendix 4 -**********************************************************************/ -static intptr_t read_sleb(uintptr_t *pp) -{ - uintptr_t result = 0; - uintptr_t shift = 0; - unsigned char byte; - do { - byte = *(const unsigned char *)(*pp)++; - result |= (byte & 0x7f) << shift; - shift += 7; - } while (byte & 0x80); - if ((shift < 8*sizeof(intptr_t)) && (byte & 0x40)) { - result |= ((intptr_t)-1) << shift; - } - return result; -} - - -/*********************************************************************** -* read_address -* Reads an encoded address from the address stored in *pp. -* Increments *pp past the bytes read. -* The data is interpreted according to the given dwarf encoding -* and base addresses. -**********************************************************************/ -static uintptr_t read_address(uintptr_t *pp, - const struct dwarf_eh_bases *bases, - unsigned char encoding) -{ - uintptr_t result = 0; - uintptr_t oldp = *pp; - - // fixme need DW_EH_PE_aligned? - -#define READ(type) \ - result = *(type *)(*pp); \ - *pp += sizeof(type); - - if (encoding == DW_EH_PE_omit) return 0; - - switch (encoding & 0x0f) { - case DW_EH_PE_absptr: - READ(uintptr_t); - break; - case DW_EH_PE_uleb128: - result = read_uleb(pp); - break; - case DW_EH_PE_udata2: - READ(uint16_t); - break; - case DW_EH_PE_udata4: - READ(uint32_t); - break; -#if __LP64__ - case DW_EH_PE_udata8: - READ(uint64_t); - break; -#endif - case DW_EH_PE_sleb128: - result = read_sleb(pp); - break; - case DW_EH_PE_sdata2: - READ(int16_t); - break; - case DW_EH_PE_sdata4: - READ(int32_t); - break; -#if __LP64__ - case DW_EH_PE_sdata8: - READ(int64_t); - break; -#endif - default: - _objc_inform("unknown DWARF EH encoding 0x%x at %p", - encoding, (void *)*pp); - break; - } - -#undef READ - - if (result) { - switch (encoding & 0x70) { - case DW_EH_PE_pcrel: - // fixme correct? - result += (uintptr_t)oldp; - break; - case DW_EH_PE_textrel: - result += bases->tbase; - break; - case DW_EH_PE_datarel: - result += bases->dbase; - break; - case DW_EH_PE_funcrel: - result += bases->func; - break; - case DW_EH_PE_aligned: - _objc_inform("unknown DWARF EH encoding 0x%x at %p", - encoding, (void *)*pp); - break; - default: - // no adjustment - break; - } - - if (encoding & DW_EH_PE_indirect) { - result = *(uintptr_t *)result; - } - } - - return (uintptr_t)result; -} - - -struct frame_ips { - uintptr_t start; - uintptr_t end; -}; -struct frame_range { - uintptr_t ip_start; - uintptr_t ip_end; - uintptr_t cfa; - // precise ranges within ip_start..ip_end; nil or {0,0} terminated - frame_ips *ips; -}; - - -static bool isObjCExceptionCatcher(uintptr_t lsda, uintptr_t ip, - const struct dwarf_eh_bases* bases, - struct frame_range *frame) -{ - unsigned char LPStart_enc = *(const unsigned char *)lsda++; - - if (LPStart_enc != DW_EH_PE_omit) { - read_address(&lsda, bases, LPStart_enc); // LPStart - } - - unsigned char TType_enc = *(const unsigned char *)lsda++; - if (TType_enc != DW_EH_PE_omit) { - read_uleb(&lsda); // TType - } - - unsigned char call_site_enc = *(const unsigned char *)lsda++; - uintptr_t length = read_uleb(&lsda); - uintptr_t call_site_table = lsda; - uintptr_t call_site_table_end = call_site_table + length; - uintptr_t action_record_table = call_site_table_end; - - uintptr_t action_record = 0; - uintptr_t p = call_site_table; - - uintptr_t try_start; - uintptr_t try_end; - uintptr_t try_landing_pad; - - while (p < call_site_table_end) { - uintptr_t start = read_address(&p, bases, call_site_enc)+bases->func; - uintptr_t len = read_address(&p, bases, call_site_enc); - uintptr_t pad = read_address(&p, bases, call_site_enc); - uintptr_t action = read_uleb(&p); - - if (ip < start) { - // no more source ranges - return false; - } - else if (ip < start + len) { - // found the range - if (!pad) return false; // ...but it has no landing pad - // found the landing pad - action_record = action ? action_record_table + action - 1 : 0; - try_start = start; - try_end = start + len; - try_landing_pad = pad; - break; - } - } - - if (!action_record) return false; // no catch handlers - - // has handlers, destructors, and/or throws specifications - // Use this frame if it has any handlers - bool has_handler = false; - p = action_record; - intptr_t offset; - do { - intptr_t filter = read_sleb(&p); - uintptr_t temp = p; - offset = read_sleb(&temp); - p += offset; - - if (filter < 0) { - // throws specification - ignore - } else if (filter == 0) { - // destructor - ignore - } else /* filter >= 0 */ { - // catch handler - use this frame - has_handler = true; - break; - } - } while (offset); - - if (!has_handler) return false; - - // Count the number of source ranges with the same landing pad as our match - unsigned int range_count = 0; - p = call_site_table; - while (p < call_site_table_end) { - /*start*/ read_address(&p, bases, call_site_enc)/*+bases->func*/; - /*len*/ read_address(&p, bases, call_site_enc); - uintptr_t pad = read_address(&p, bases, call_site_enc); - /*action*/ read_uleb(&p); - - if (pad == try_landing_pad) { - range_count++; - } - } - - if (range_count == 1) { - // No other source ranges with the same landing pad. We're done here. - frame->ips = nil; - } - else { - // Record all ranges with the same landing pad as our match. - frame->ips = (frame_ips *) - malloc((range_count + 1) * sizeof(frame->ips[0])); - unsigned int r = 0; - p = call_site_table; - while (p < call_site_table_end) { - uintptr_t start = read_address(&p, bases, call_site_enc)+bases->func; - uintptr_t len = read_address(&p, bases, call_site_enc); - uintptr_t pad = read_address(&p, bases, call_site_enc); - /*action*/ read_uleb(&p); - - if (pad == try_landing_pad) { - if (start < try_start) try_start = start; - if (start+len > try_end) try_end = start+len; - frame->ips[r].start = start; - frame->ips[r].end = start+len; - r++; - } - } - - frame->ips[r].start = 0; - frame->ips[r].end = 0; - } - - frame->ip_start = try_start; - frame->ip_end = try_end; - - return true; -} - - -static struct frame_range findHandler(void) -{ - // walk stack looking for frame with objc catch handler - unw_context_t uc; - unw_cursor_t cursor; - unw_proc_info_t info; - unw_getcontext(&uc); - unw_init_local(&cursor, &uc); - while ( (unw_step(&cursor) > 0) && (unw_get_proc_info(&cursor, &info) == UNW_ESUCCESS) ) { - // must use objc personality handler - if ( info.handler != (uintptr_t)__objc_personality_v0 ) - continue; - // must have landing pad - if ( info.lsda == 0 ) - continue; - // must have landing pad that catches objc exceptions - struct dwarf_eh_bases bases; - bases.tbase = 0; // from unwind-dw2-fde-darwin.c:examine_objects() - bases.dbase = 0; // from unwind-dw2-fde-darwin.c:examine_objects() - bases.func = info.start_ip; - unw_word_t ip; - unw_get_reg(&cursor, UNW_REG_IP, &ip); - ip -= 1; - struct frame_range try_range = {0, 0, 0, 0}; - if ( isObjCExceptionCatcher(info.lsda, ip, &bases, &try_range) ) { - unw_word_t cfa; - unw_get_reg(&cursor, UNW_REG_SP, &cfa); - try_range.cfa = cfa; - return try_range; - } - } - - return (struct frame_range){0, 0, 0, 0}; -} - - -// This data structure assumes the number of -// active alt handlers per frame is small. - -// for OBJC_DEBUG_ALT_HANDLERS, record the call to objc_addExceptionHandler. -#define BACKTRACE_COUNT 46 -#define THREADNAME_COUNT 64 -struct alt_handler_debug { - uintptr_t token; - int backtraceSize; - void *backtrace[BACKTRACE_COUNT]; - char thread[THREADNAME_COUNT]; - char queue[THREADNAME_COUNT]; -}; - -struct alt_handler_data { - struct frame_range frame; - objc_exception_handler fn; - void *context; - struct alt_handler_debug *debug; -}; - -struct alt_handler_list { - unsigned int allocated; - unsigned int used; - struct alt_handler_data *handlers; - struct alt_handler_list *next_DEBUGONLY; -}; - -static mutex_t DebugLock; -static struct alt_handler_list *DebugLists; -static uintptr_t DebugCounter; - -void alt_handler_error(uintptr_t token) __attribute__((noinline)); - -static struct alt_handler_list * -fetch_handler_list(bool create) -{ - _objc_pthread_data *data = _objc_fetch_pthread_data(create); - if (!data) return nil; - - struct alt_handler_list *list = data->handlerList; - if (!list) { - if (!create) return nil; - list = (struct alt_handler_list *)calloc(1, sizeof(*list)); - data->handlerList = list; - - if (DebugAltHandlers) { - // Save this list so the debug code can find it from other threads - mutex_locker_t lock(DebugLock); - list->next_DEBUGONLY = DebugLists; - DebugLists = list; - } - } - - return list; -} - - -void _destroyAltHandlerList(struct alt_handler_list *list) -{ - if (list) { - if (DebugAltHandlers) { - // Detach from the list-of-lists. - mutex_locker_t lock(DebugLock); - struct alt_handler_list **listp = &DebugLists; - while (*listp && *listp != list) listp = &(*listp)->next_DEBUGONLY; - if (*listp) *listp = (*listp)->next_DEBUGONLY; - } - - if (list->handlers) { - for (unsigned int i = 0; i < list->allocated; i++) { - if (list->handlers[i].frame.ips) { - free(list->handlers[i].frame.ips); - } - } - free(list->handlers); - } - free(list); - } -} - - -uintptr_t objc_addExceptionHandler(objc_exception_handler fn, void *context) -{ - // Find the closest enclosing frame with objc catch handlers - struct frame_range target_frame = findHandler(); - if (!target_frame.ip_start) { - // No suitable enclosing handler found. - return 0; - } - - // Record this alt handler for the discovered frame. - struct alt_handler_list *list = fetch_handler_list(YES); - unsigned int i = 0; - - if (list->used == list->allocated) { - list->allocated = list->allocated*2 ?: 4; - list->handlers = (struct alt_handler_data *) - realloc(list->handlers, - list->allocated * sizeof(list->handlers[0])); - bzero(&list->handlers[list->used], (list->allocated - list->used) * sizeof(list->handlers[0])); - i = list->used; - } - else { - for (i = 0; i < list->allocated; i++) { - if (list->handlers[i].frame.ip_start == 0 && - list->handlers[i].frame.ip_end == 0 && - list->handlers[i].frame.cfa == 0) - { - break; - } - } - if (i == list->allocated) { - _objc_fatal("alt handlers in objc runtime are buggy!"); - } - } - - struct alt_handler_data *data = &list->handlers[i]; - - data->frame = target_frame; - data->fn = fn; - data->context = context; - list->used++; - - uintptr_t token = i+1; - - if (DebugAltHandlers) { - // Record backtrace in case this handler is misused later. - mutex_locker_t lock(DebugLock); - - token = DebugCounter++; - if (token == 0) token = DebugCounter++; - - if (!data->debug) { - data->debug = (struct alt_handler_debug *) - calloc(sizeof(*data->debug), 1); - } else { - bzero(data->debug, sizeof(*data->debug)); - } - - pthread_getname_np(pthread_self(), data->debug->thread, THREADNAME_COUNT); - strlcpy(data->debug->queue, - dispatch_queue_get_label(dispatch_get_current_queue()), - THREADNAME_COUNT); - data->debug->backtraceSize = - backtrace(data->debug->backtrace, BACKTRACE_COUNT); - data->debug->token = token; - } - - if (PrintAltHandlers) { - _objc_inform("ALT HANDLERS: installing alt handler #%lu %p(%p) on " - "frame [ip=%p..%p sp=%p]", (unsigned long)token, - data->fn, data->context, (void *)data->frame.ip_start, - (void *)data->frame.ip_end, (void *)data->frame.cfa); - if (data->frame.ips) { - unsigned int r = 0; - while (1) { - uintptr_t start = data->frame.ips[r].start; - uintptr_t end = data->frame.ips[r].end; - r++; - if (start == 0 && end == 0) break; - _objc_inform("ALT HANDLERS: ip=%p..%p", - (void*)start, (void*)end); - } - } - } - - if (list->used > 1000) { - static int warned = 0; - if (!warned) { - _objc_inform("ALT HANDLERS: *** over 1000 alt handlers installed; " - "this is probably a bug"); - warned = 1; - } - } - - return token; -} - - -void objc_removeExceptionHandler(uintptr_t token) -{ - if (!token) { - // objc_addExceptionHandler failed - return; - } - - struct alt_handler_list *list = fetch_handler_list(NO); - if (!list || !list->handlers) { - // no alt handlers active - alt_handler_error(token); - __builtin_trap(); - } - - uintptr_t i = token-1; - - if (DebugAltHandlers) { - // search for the token instead of using token-1 - for (i = 0; i < list->allocated; i++) { - struct alt_handler_data *data = &list->handlers[i]; - if (data->debug && data->debug->token == token) break; - } - } - - if (i >= list->allocated) { - // token out of range - alt_handler_error(token); - __builtin_trap(); - } - - struct alt_handler_data *data = &list->handlers[i]; - - if (data->frame.ip_start == 0 && data->frame.ip_end == 0 && data->frame.cfa == 0) { - // token in range, but invalid - alt_handler_error(token); - __builtin_trap(); - } - - if (PrintAltHandlers) { - _objc_inform("ALT HANDLERS: removing alt handler #%lu %p(%p) on " - "frame [ip=%p..%p sp=%p]", (unsigned long)token, - data->fn, data->context, (void *)data->frame.ip_start, - (void *)data->frame.ip_end, (void *)data->frame.cfa); - } - - if (data->debug) free(data->debug); - if (data->frame.ips) free(data->frame.ips); - bzero(data, sizeof(*data)); - list->used--; -} - -void objc_alt_handler_error(void) __attribute__((noinline)); - -void alt_handler_error(uintptr_t token) -{ - if (!DebugAltHandlers) { - _objc_inform_now_and_on_crash - ("objc_removeExceptionHandler() called with unknown alt handler; " - "this is probably a bug in multithreaded AppKit use. " - "Set environment variable OBJC_DEBUG_ALT_HANDLERS=YES " - "or break in objc_alt_handler_error() to debug."); - objc_alt_handler_error(); - } - - DebugLock.lock(); - - // Search other threads' alt handler lists for this handler. - struct alt_handler_list *list; - for (list = DebugLists; list; list = list->next_DEBUGONLY) { - unsigned h; - for (h = 0; h < list->allocated; h++) { - struct alt_handler_data *data = &list->handlers[h]; - if (data->debug && data->debug->token == token) { - // found it - int i; - - // Build a string from the recorded backtrace - char *symbolString; - char **symbols = - backtrace_symbols(data->debug->backtrace, - data->debug->backtraceSize); - size_t len = 1; - for (i = 0; i < data->debug->backtraceSize; i++){ - len += 4 + strlen(symbols[i]) + 1; - } - symbolString = (char *)calloc(len, 1); - for (i = 0; i < data->debug->backtraceSize; i++){ - strcat(symbolString, " "); - strcat(symbolString, symbols[i]); - strcat(symbolString, "\n"); - } - - free(symbols); - - _objc_inform_now_and_on_crash - ("objc_removeExceptionHandler() called with " - "unknown alt handler; this is probably a bug in " - "multithreaded AppKit use. \n" - "The matching objc_addExceptionHandler() was called by:\n" - "Thread '%s': Dispatch queue: '%s': \n%s", - data->debug->thread, data->debug->queue, symbolString); - - DebugLock.unlock(); - free(symbolString); - - objc_alt_handler_error(); - } - } - } - - DebugLock.unlock(); - - // not found - _objc_inform_now_and_on_crash - ("objc_removeExceptionHandler() called with unknown alt handler; " - "this is probably a bug in multithreaded AppKit use"); - objc_alt_handler_error(); -} - -void objc_alt_handler_error(void) -{ - __builtin_trap(); -} - -// called in order registered, to match 32-bit _NSAddAltHandler2 -// fixme reverse registration order matches c++ destructors better -static void call_alt_handlers(struct _Unwind_Context *ctx) -{ - uintptr_t ip = _Unwind_GetIP(ctx) - 1; - uintptr_t cfa = _Unwind_GetCFA(ctx); - unsigned int i; - - struct alt_handler_list *list = fetch_handler_list(NO); - if (!list || list->used == 0) return; - - for (i = 0; i < list->allocated; i++) { - struct alt_handler_data *data = &list->handlers[i]; - if (ip >= data->frame.ip_start && ip < data->frame.ip_end && data->frame.cfa == cfa) - { - if (data->frame.ips) { - unsigned int r = 0; - bool found; - while (1) { - uintptr_t start = data->frame.ips[r].start; - uintptr_t end = data->frame.ips[r].end; - r++; - if (start == 0 && end == 0) { - found = false; - break; - } - if (ip >= start && ip < end) { - found = true; - break; - } - } - if (!found) continue; - } - - // Copy and clear before the callback, in case the - // callback manipulates the alt handler list. - struct alt_handler_data copy = *data; - bzero(data, sizeof(*data)); - list->used--; - if (PrintExceptions || PrintAltHandlers) { - _objc_inform("EXCEPTIONS: calling alt handler %p(%p) from " - "frame [ip=%p..%p sp=%p]", copy.fn, copy.context, - (void *)copy.frame.ip_start, - (void *)copy.frame.ip_end, - (void *)copy.frame.cfa); - } - if (copy.fn) (*copy.fn)(nil, copy.context); - if (copy.frame.ips) free(copy.frame.ips); - } - } -} - -// SUPPORT_ALT_HANDLERS -#endif - - -/*********************************************************************** -* exception_init -* Initialize libobjc's exception handling system. -* Called by map_images(). -**********************************************************************/ -void exception_init(void) -{ - old_terminate = std::set_terminate(&_objc_terminate); -} - - -// __OBJC2__ -#endif diff --git a/objc/objc-runtime/runtime/objc-externalref.mm b/objc/objc-runtime/runtime/objc-externalref.mm deleted file mode 100644 index 8511fe9..0000000 --- a/objc/objc-runtime/runtime/objc-externalref.mm +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright (c) 2010 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 "objc-private.h" - -#include <malloc/malloc.h> -#include <assert.h> -#include "runtime.h" -#include "objc-os.h" -#include "message.h" -#if SUPPORT_GC -#include "auto_zone.h" -#endif - -enum { - // external references to data segment objects all use this type - OBJC_XREF_TYPE_STATIC = 3, - - OBJC_XREF_TYPE_MASK = 3 -}; - -// Macros to encode/decode reference values and types. -#define encode_pointer_and_type(pointer, type) (~((uintptr_t)(pointer) | type)) -#define decode_pointer(encoded) ((id)((~(encoded)) & (~OBJC_XREF_TYPE_MASK))) -#define decode_type(encoded) ((~(encoded)) & OBJC_XREF_TYPE_MASK) -#define encode_index_and_type(index, type) (~((index<<3) | type)) -#define decode_index(encoded) ((~encoded)>>3) - -#if SUPPORT_GC - -typedef struct { - objc_xref_type_t _type; // type of list. - dispatch_queue_t _synchronizer; // a reader/write lock - __strong void **_buffer; // a retained all pointers block - size_t _size; // number of pointers that fit in _list (buffer size) - size_t _count; // count of pointers in _list (in use count) - size_t _search; // lowest index in list which *might* be unused -} external_ref_list; - -static external_ref_list _xref_lists[2]; - -#define is_strong(list) (list->_type == OBJC_XREF_STRONG) -#define is_weak(list) (list->_type == OBJC_XREF_WEAK) - -inline static size_t _index_for_type(objc_xref_type_t ref_type) { - assert(ref_type == OBJC_XREF_STRONG || ref_type == OBJC_XREF_WEAK); - return (ref_type - 1); -} - -static void _initialize_gc() { - static dispatch_once_t init_guard; - dispatch_once(&init_guard, ^{ - external_ref_list *_strong_list = &_xref_lists[_index_for_type(OBJC_XREF_STRONG)]; - _strong_list->_type = OBJC_XREF_STRONG; - _strong_list->_synchronizer = dispatch_queue_create("OBJC_XREF_STRONG synchronizer", DISPATCH_QUEUE_CONCURRENT); - - external_ref_list *_weak_list = &_xref_lists[_index_for_type(OBJC_XREF_WEAK)]; - _weak_list->_type = OBJC_XREF_WEAK; - _weak_list->_synchronizer = dispatch_queue_create("OBJC_XREF_WEAK synchronizer", DISPATCH_QUEUE_CONCURRENT); - }); -} - -#define EMPTY_SLOT ((void*)0x1) - -// grow the buffer by one page -static bool _grow_list(external_ref_list *list) { - auto_memory_type_t memory_type = (is_strong(list) ? AUTO_MEMORY_ALL_POINTERS : AUTO_MEMORY_ALL_WEAK_POINTERS); - size_t new_size = list->_size + PAGE_MAX_SIZE / sizeof(void *); - // auto_realloc() has been enhanced to handle strong and weak memory. - void **new_list = (void **)(list->_buffer ? malloc_zone_realloc(gc_zone, list->_buffer, new_size * sizeof(void *)) : auto_zone_allocate_object(gc_zone, new_size * sizeof(void *), memory_type, false, false)); - if (!new_list) _objc_fatal("unable to allocate, size = %ld\n", new_size); - - list->_search = list->_size; - // Fill the newly allocated space with empty slot tokens. - for (size_t index = list->_size; index < new_size; ++index) - new_list[index] = EMPTY_SLOT; - list->_size = new_size; - auto_zone_root_write_barrier(gc_zone, &list->_buffer, new_list); - return true; -} - - -// find an unused slot in the list, growing the list if necessary -static size_t _find_unused_index(external_ref_list *list) { - size_t index; - if (list->_size == list->_count) { - _grow_list(list); - } - // find the lowest unused index in _list - index = list->_search; - while (list->_buffer[index] != EMPTY_SLOT) - index++; - // mark the slot as no longer empty, good form for weak slots. - list->_buffer[index] = NULL; - return index; -} - - -// return the strong or weak list -inline static external_ref_list *_list_for_type(objc_xref_type_t ref_type) { - return &_xref_lists[_index_for_type(ref_type)]; -} - - -// create a GC external reference -objc_xref_t _object_addExternalReference_gc(id obj, objc_xref_type_t ref_type) { - _initialize_gc(); - __block size_t index; - objc_xref_t xref; - - if (auto_zone_is_valid_pointer(gc_zone, obj)) { - external_ref_list *list = _list_for_type(ref_type); - - // writer lock - dispatch_barrier_sync(list->_synchronizer, (dispatch_block_t)^{ - index = _find_unused_index(list); - if (ref_type == OBJC_XREF_STRONG) { - auto_zone_set_write_barrier(gc_zone, &list->_buffer[index], obj); - } else { - auto_assign_weak_reference(gc_zone, obj, (const void **)&list->_buffer[index], NULL); - } - list->_count++; - }); - xref = encode_index_and_type(index, ref_type); - } else { - // data segment object - xref = encode_pointer_and_type(obj, OBJC_XREF_TYPE_STATIC); - } - return xref; -} - - -id _object_readExternalReference_gc(objc_xref_t ref) { - _initialize_gc(); - __block id result; - objc_xref_type_t ref_type = decode_type(ref); - if (ref_type != OBJC_XREF_TYPE_STATIC) { - size_t index = decode_index(ref); - external_ref_list *list = _list_for_type(ref_type); - - dispatch_sync(list->_synchronizer, ^{ - if (index >= list->_size) { - _objc_fatal("attempted to resolve invalid external reference\n"); - } - if (ref_type == OBJC_XREF_STRONG) - result = (id)list->_buffer[index]; - else - result = (id)auto_read_weak_reference(gc_zone, &list->_buffer[index]); - if (result == (id)EMPTY_SLOT) - _objc_fatal("attempted to resolve unallocated external reference\n"); - }); - } else { - // data segment object - result = decode_pointer(ref); - } - return result; -} - - -void _object_removeExternalReference_gc(objc_xref_t ref) { - _initialize_gc(); - objc_xref_type_t ref_type = decode_type(ref); - if (ref_type != OBJC_XREF_TYPE_STATIC) { - size_t index = decode_index(ref); - external_ref_list *list = _list_for_type(ref_type); - - dispatch_barrier_sync(list->_synchronizer, ^{ - if (index >= list->_size) { - _objc_fatal("attempted to destroy invalid external reference\n"); - } - id old_value; - if (ref_type == OBJC_XREF_STRONG) { - old_value = (id)list->_buffer[index]; - } else { - old_value = (id)auto_read_weak_reference(gc_zone, &list->_buffer[index]); - auto_assign_weak_reference(gc_zone, NULL, (const void **)&list->_buffer[index], NULL); - } - list->_buffer[index] = EMPTY_SLOT; - if (old_value == (id)EMPTY_SLOT) - _objc_fatal("attempted to destroy unallocated external reference\n"); - list->_count--; - if (list->_search > index) - list->_search = index; - }); - } else { - // nothing for data segment object - } -} - - -// SUPPORT_GC -#endif - - -objc_xref_t _object_addExternalReference_non_gc(id obj, objc_xref_type_t ref_type) { - switch (ref_type) { - case OBJC_XREF_STRONG: - ((id(*)(id, SEL))objc_msgSend)(obj, SEL_retain); - break; - case OBJC_XREF_WEAK: - break; - default: - _objc_fatal("invalid external reference type: %d", (int)ref_type); - break; - } - return encode_pointer_and_type(obj, ref_type); -} - - -id _object_readExternalReference_non_gc(objc_xref_t ref) { - id obj = decode_pointer(ref); - return obj; -} - - -void _object_removeExternalReference_non_gc(objc_xref_t ref) { - id obj = decode_pointer(ref); - objc_xref_type_t ref_type = decode_type(ref); - switch (ref_type) { - case OBJC_XREF_STRONG: - ((void(*)(id, SEL))objc_msgSend)(obj, SEL_release); - break; - case OBJC_XREF_WEAK: - break; - default: - _objc_fatal("invalid external reference type: %d", (int)ref_type); - break; - } -} - - -uintptr_t _object_getExternalHash(id object) { - return (uintptr_t)object; -} - - -#if SUPPORT_GC - -// These functions are resolver functions in objc-auto.mm. - -#else - -objc_xref_t -_object_addExternalReference(id obj, objc_xref_t type) -{ - return _object_addExternalReference_non_gc(obj, type); -} - - -id -_object_readExternalReference(objc_xref_t ref) -{ - return _object_readExternalReference_non_gc(ref); -} - - -void -_object_removeExternalReference(objc_xref_t ref) -{ - _object_removeExternalReference_non_gc(ref); -} - -#endif diff --git a/objc/objc-runtime/runtime/objc-file-old.h b/objc/objc-runtime/runtime/objc-file-old.h deleted file mode 100644 index 9d4dfa7..0000000 --- a/objc/objc-runtime/runtime/objc-file-old.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2009 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 _OBJC_FILE_OLD_H -#define _OBJC_FILE_OLD_H - -#if !__OBJC2__ - -#include "objc-os.h" - -struct objc_module; -struct old_protocol; -struct old_class; - -__BEGIN_DECLS - -extern struct objc_module *_getObjcModules(const header_info *hi, size_t *nmodules); -extern SEL *_getObjcSelectorRefs(const header_info *hi, size_t *nmess); -extern struct old_protocol **_getObjcProtocols(const header_info *hi, size_t *nprotos); -extern Class *_getObjcClassRefs(const header_info *hi, size_t *nclasses); -extern const char *_getObjcClassNames(const header_info *hi, size_t *size); - -__END_DECLS - -#endif - -#endif diff --git a/objc/objc-runtime/runtime/objc-file-old.mm b/objc/objc-runtime/runtime/objc-file-old.mm deleted file mode 100644 index 772e75d..0000000 --- a/objc/objc-runtime/runtime/objc-file-old.mm +++ /dev/null @@ -1,160 +0,0 @@ -/* - * 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@ - */ -// Copyright 1988-1996 NeXT Software, Inc. - -#if !__OBJC2__ - -#include "objc-private.h" -#include "objc-runtime-old.h" -#include "objc-file-old.h" - -#if TARGET_OS_WIN32 - -/* -Module -_getObjcModules(const header_info *hi, size_t *nmodules) -{ - if (nmodules) *nmodules = hi->moduleCount; - return hi->modules; -} -*/ -SEL * -_getObjcSelectorRefs(const header_info *hi, size_t *nmess) -{ - if (nmess) *nmess = hi->selrefCount; - return hi->selrefs; -} - -struct old_protocol ** -_getObjcProtocols(const header_info *hi, size_t *nprotos) -{ - if (nprotos) *nprotos = hi->protocolCount; - return hi->protocols; -} - -Class* -_getObjcClassRefs(const header_info *hi, size_t *nclasses) -{ - if (nclasses) *nclasses = hi->clsrefCount; - return (Class*)hi->clsrefs; -} - -// __OBJC,__class_names section only emitted by CodeWarrior rdar://4951638 -const char * -_getObjcClassNames(const header_info *hi, size_t *size) -{ - if (size) *size = 0; - return NULL; -} - -#else - -#define GETSECT(name, type, sectname) \ - type *name(const header_info *hi, size_t *outCount) \ - { \ - unsigned long byteCount = 0; \ - type *data = (type *) \ - getsectiondata(hi->mhdr, SEG_OBJC, sectname, &byteCount); \ - *outCount = byteCount / sizeof(type); \ - return data; \ - } - -GETSECT(_getObjcModules, struct objc_module, "__module_info"); -GETSECT(_getObjcSelectorRefs, SEL, "__message_refs"); -GETSECT(_getObjcClassRefs, Class, "__cls_refs"); -GETSECT(_getObjcClassNames, const char, "__class_names"); -// __OBJC,__class_names section only emitted by CodeWarrior rdar://4951638 - - -objc_image_info * -_getObjcImageInfo(const headerType *mhdr, size_t *outBytes) -{ - unsigned long byteCount = 0; - objc_image_info *info = (objc_image_info *) - getsectiondata(mhdr, SEG_OBJC, "__image_info", &byteCount); - *outBytes = byteCount; - return info; -} - - -struct old_protocol ** -_getObjcProtocols(const header_info *hi, size_t *nprotos) -{ - unsigned long size = 0; - struct old_protocol *protos = (struct old_protocol *) - getsectiondata(hi->mhdr, SEG_OBJC, "__protocol", &size); - *nprotos = size / sizeof(struct old_protocol); - - if (!hi->proto_refs && *nprotos) { - size_t i; - header_info *whi = (header_info *)hi; - whi->proto_refs = (struct old_protocol **) - malloc(*nprotos * sizeof(*hi->proto_refs)); - for (i = 0; i < *nprotos; i++) { - hi->proto_refs[i] = protos+i; - } - } - - return hi->proto_refs; -} - - -static const segmentType * -getsegbynamefromheader(const headerType *head, const char *segname) -{ - const segmentType *sgp; - unsigned long i; - - sgp = (const segmentType *) (head + 1); - for (i = 0; i < head->ncmds; i++){ - if (sgp->cmd == SEGMENT_CMD) { - if (strncmp(sgp->segname, segname, sizeof(sgp->segname)) == 0) { - return sgp; - } - } - sgp = (const segmentType *)((char *)sgp + sgp->cmdsize); - } - return NULL; -} - -bool -_hasObjcContents(const header_info *hi) -{ - // Look for an __OBJC,* section other than __OBJC,__image_info - const segmentType *seg = getsegbynamefromheader(hi->mhdr, "__OBJC"); - const sectionType *sect; - uint32_t i; - for (i = 0; i < seg->nsects; i++) { - sect = ((const sectionType *)(seg+1))+i; - if (0 != strncmp(sect->sectname, "__image_info", 12)) { - return YES; - } - } - - return NO; -} - - -#endif - -#endif diff --git a/objc/objc-runtime/runtime/objc-file.h b/objc/objc-runtime/runtime/objc-file.h deleted file mode 100644 index 5e78b61..0000000 --- a/objc/objc-runtime/runtime/objc-file.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2009 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 _OBJC_FILE_NEW_H -#define _OBJC_FILE_NEW_H - -#if __OBJC2__ - -#include "objc-runtime-new.h" - -// classref_t is not fixed up at launch; use remapClass() to convert - -extern SEL *_getObjc2SelectorRefs(const header_info *hi, size_t *count); -extern message_ref_t *_getObjc2MessageRefs(const header_info *hi, size_t *count); -extern Class*_getObjc2ClassRefs(const header_info *hi, size_t *count); -extern Class*_getObjc2SuperRefs(const header_info *hi, size_t *count); -extern classref_t *_getObjc2ClassList(const header_info *hi, size_t *count); -extern classref_t *_getObjc2NonlazyClassList(const header_info *hi, size_t *count); -extern category_t **_getObjc2CategoryList(const header_info *hi, size_t *count); -extern category_t **_getObjc2NonlazyCategoryList(const header_info *hi, size_t *count); -extern protocol_t **_getObjc2ProtocolList(const header_info *hi, size_t *count); -extern protocol_t **_getObjc2ProtocolRefs(const header_info *hi, size_t *count); -using Initializer = void(*)(void); -extern Initializer* getLibobjcInitializers(const header_info *hi, size_t *count); - -extern classref_t *_getObjc2NonlazyClassList(const headerType *mhdr, size_t *count); -extern category_t **_getObjc2NonlazyCategoryList(const headerType *mhdr, size_t *count); -extern Initializer* getLibobjcInitializers(const headerType *mhdr, size_t *count); - -#endif - -#endif diff --git a/objc/objc-runtime/runtime/objc-file.mm b/objc/objc-runtime/runtime/objc-file.mm deleted file mode 100644 index dac4ecd..0000000 --- a/objc/objc-runtime/runtime/objc-file.mm +++ /dev/null @@ -1,142 +0,0 @@ -/* - * 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@ - */ - -#if __OBJC2__ - -#include "objc-private.h" -#include "objc-file.h" - -// Segment and section names are 16 bytes and may be un-terminated. -bool segnameEquals(const char *lhs, const char *rhs) { - return 0 == strncmp(lhs, rhs, 16); -} - -bool segnameStartsWith(const char *segname, const char *prefix) { - return 0 == strncmp(segname, prefix, strlen(prefix)); -} - -bool sectnameEquals(const char *lhs, const char *rhs) { - return segnameEquals(lhs, rhs); -} - -bool sectnameStartsWith(const char *sectname, const char *prefix) { - return segnameStartsWith(sectname, prefix); -} - - -// Look for a __DATA or __DATA_CONST or __DATA_DIRTY section -// with the given name that stores an array of T. -template <typename T> -T* getDataSection(const headerType *mhdr, const char *sectname, - size_t *outBytes, size_t *outCount) -{ - unsigned long byteCount = 0; - T* data = (T*)getsectiondata(mhdr, "__DATA", sectname, &byteCount); - if (!data) { - data = (T*)getsectiondata(mhdr, "__DATA_CONST", sectname, &byteCount); - } - if (!data) { - data = (T*)getsectiondata(mhdr, "__DATA_DIRTY", sectname, &byteCount); - } - if (outBytes) *outBytes = byteCount; - if (outCount) *outCount = byteCount / sizeof(T); - return data; -} - -#define GETSECT(name, type, sectname) \ - type *name(const headerType *mhdr, size_t *outCount) { \ - return getDataSection<type>(mhdr, sectname, nil, outCount); \ - } \ - type *name(const header_info *hi, size_t *outCount) { \ - return getDataSection<type>(hi->mhdr, sectname, nil, outCount); \ - } - -// function name content type section name -GETSECT(_getObjc2SelectorRefs, SEL, "__objc_selrefs"); -GETSECT(_getObjc2MessageRefs, message_ref_t, "__objc_msgrefs"); -GETSECT(_getObjc2ClassRefs, Class, "__objc_classrefs"); -GETSECT(_getObjc2SuperRefs, Class, "__objc_superrefs"); -GETSECT(_getObjc2ClassList, classref_t, "__objc_classlist"); -GETSECT(_getObjc2NonlazyClassList, classref_t, "__objc_nlclslist"); -GETSECT(_getObjc2CategoryList, category_t *, "__objc_catlist"); -GETSECT(_getObjc2NonlazyCategoryList, category_t *, "__objc_nlcatlist"); -GETSECT(_getObjc2ProtocolList, protocol_t *, "__objc_protolist"); -GETSECT(_getObjc2ProtocolRefs, protocol_t *, "__objc_protorefs"); -GETSECT(getLibobjcInitializers, Initializer, "__objc_init_func"); - - -objc_image_info * -_getObjcImageInfo(const headerType *mhdr, size_t *outBytes) -{ - return getDataSection<objc_image_info>(mhdr, "__objc_imageinfo", - outBytes, nil); -} - - -static const segmentType * -getsegbynamefromheader(const headerType *mhdr, const char *segname) -{ - const segmentType *seg = (const segmentType *) (mhdr + 1); - for (unsigned long i = 0; i < mhdr->ncmds; i++){ - if (seg->cmd == SEGMENT_CMD && segnameEquals(seg->segname, segname)) { - return seg; - } - seg = (const segmentType *)((char *)seg + seg->cmdsize); - } - return nil; -} - -// Look for an __objc* section other than __objc_imageinfo -static bool segmentHasObjcContents(const segmentType *seg) -{ - if (seg) { - for (uint32_t i = 0; i < seg->nsects; i++) { - const sectionType *sect = ((const sectionType *)(seg+1))+i; - if (sectnameStartsWith(sect->sectname, "__objc_") && - !sectnameEquals(sect->sectname, "__objc_imageinfo")) - { - return true; - } - } - } - - return false; -} - -// Look for an __objc* section other than __objc_imageinfo -bool -_hasObjcContents(const header_info *hi) -{ - const segmentType *data = - getsegbynamefromheader(hi->mhdr, "__DATA"); - const segmentType *data_const = - getsegbynamefromheader(hi->mhdr, "__DATA_CONST"); - const segmentType *data_dirty = - getsegbynamefromheader(hi->mhdr, "__DATA_CONST"); - - return segmentHasObjcContents(data) - || segmentHasObjcContents(data_const) - || segmentHasObjcContents(data_dirty); -} - -#endif diff --git a/objc/objc-runtime/runtime/objc-gdb.h b/objc/objc-runtime/runtime/objc-gdb.h deleted file mode 100644 index 65b3862..0000000 --- a/objc/objc-runtime/runtime/objc-gdb.h +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -#ifndef _OBJC_GDB_H -#define _OBJC_GDB_H - -/* - * WARNING DANGER HAZARD BEWARE EEK - * - * Everything in this file is for debugger and developer tool use only. - * These will change in arbitrary OS updates and in unpredictable ways. - * When your program breaks, you get to keep both pieces. - */ - -#ifdef __APPLE_API_PRIVATE - -#define _OBJC_PRIVATE_H_ -#include <stdint.h> -#include <objc/hashtable.h> -#include <objc/maptable.h> - -__BEGIN_DECLS - - -/*********************************************************************** -* Class pointer preflighting -**********************************************************************/ - -// Return cls if it's a valid class, or crash. -OBJC_EXPORT Class gdb_class_getClass(Class cls) -#if __OBJC2__ - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); -#else - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_1); -#endif - -// Same as gdb_class_getClass(object_getClass(cls)). -OBJC_EXPORT Class gdb_object_getClass(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - - -/*********************************************************************** -* Class lists for heap. -**********************************************************************/ - -#if __OBJC2__ - -// Maps class name to Class, for in-use classes only. NXStrValueMapPrototype. -OBJC_EXPORT NXMapTable *gdb_objc_realized_classes - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); - -#else - -// Hashes Classes, for all known classes. Custom prototype. -OBJC_EXPORT NXHashTable *_objc_debug_class_hash - __OSX_AVAILABLE_STARTING(__MAC_10_2, __IPHONE_NA); - -#endif - - -/*********************************************************************** -* Non-pointer isa -**********************************************************************/ - -#if __OBJC2__ - -// Extract isa pointer from an isa field. -// (Class)(isa & mask) == class pointer -OBJC_EXPORT const uintptr_t objc_debug_isa_class_mask - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_7_0); - -// Extract magic cookie from an isa field. -// (isa & magic_mask) == magic_value -OBJC_EXPORT const uintptr_t objc_debug_isa_magic_mask - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_7_0); -OBJC_EXPORT const uintptr_t objc_debug_isa_magic_value - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_7_0); - -#endif - - -/*********************************************************************** -* Tagged pointer decoding -**********************************************************************/ -#if __OBJC2__ - -// if (obj & mask) obj is a tagged pointer object -OBJC_EXPORT uintptr_t objc_debug_taggedpointer_mask - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -// tag_slot = (obj >> slot_shift) & slot_mask -OBJC_EXPORT unsigned int objc_debug_taggedpointer_slot_shift - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); -OBJC_EXPORT uintptr_t objc_debug_taggedpointer_slot_mask - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -// class = classes[tag_slot] -OBJC_EXPORT Class objc_debug_taggedpointer_classes[] - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -// payload = (obj << payload_lshift) >> payload_rshift -// Payload signedness is determined by the signedness of the right-shift. -OBJC_EXPORT unsigned int objc_debug_taggedpointer_payload_lshift - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); -OBJC_EXPORT unsigned int objc_debug_taggedpointer_payload_rshift - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -#endif - - -/*********************************************************************** -* Breakpoints in objc_msgSend for debugger stepping. -* The array is a {0,0} terminated list of addresses. -* Each address is one of the following: -* OBJC_MESSENGER_START: Address is the start of a messenger function. -* OBJC_MESSENGER_END_FAST: Address is a jump insn that calls an IMP. -* OBJC_MESSENGER_END_SLOW: Address is some insn in the slow lookup path. -* OBJC_MESSENGER_END_NIL: Address is a return insn for messages to nil. -* -* Every path from OBJC_MESSENGER_START should reach some OBJC_MESSENGER_END. -* At all ENDs, the stack and parameter register state is the same as START. -* -* In some cases, the END_FAST case jumps to something other than the -* method's implementation. In those cases the jump's destination will -* be another function that is marked OBJC_MESSENGER_START. -**********************************************************************/ -#if __OBJC2__ - -#define OBJC_MESSENGER_START 1 -#define OBJC_MESSENGER_END_FAST 2 -#define OBJC_MESSENGER_END_SLOW 3 -#define OBJC_MESSENGER_END_NIL 4 - -struct objc_messenger_breakpoint { - uintptr_t address; - uintptr_t kind; -}; - -OBJC_EXPORT struct objc_messenger_breakpoint -gdb_objc_messenger_breakpoints[] - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -#endif - - -#ifndef OBJC_NO_GC - -/*********************************************************************** - * Garbage Collector heap dump -**********************************************************************/ - -/* Dump GC heap; if supplied the name is returned in filenamebuffer. Returns YES on success. */ -OBJC_EXPORT BOOL objc_dumpHeap(char *filenamebuffer, unsigned long length) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -#define OBJC_HEAP_DUMP_FILENAME_FORMAT "/tmp/objc-gc-heap-dump-%d-%d" - -#endif - -__END_DECLS - -#endif - -#endif diff --git a/objc/objc-runtime/runtime/objc-initialize.h b/objc/objc-runtime/runtime/objc-initialize.h deleted file mode 100644 index f516959..0000000 --- a/objc/objc-runtime/runtime/objc-initialize.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2005-2006 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 _OBJC_INITIALIZE_H -#define _OBJC_INITIALIZE_H - -#include "objc-private.h" - -__BEGIN_DECLS - -struct _objc_initializing_classes; - -extern void _class_initialize(Class cls); - -extern void _destroyInitializingClassList(struct _objc_initializing_classes *list); - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/runtime/objc-initialize.mm b/objc/objc-runtime/runtime/objc-initialize.mm deleted file mode 100644 index b4f0ba0..0000000 --- a/objc/objc-runtime/runtime/objc-initialize.mm +++ /dev/null @@ -1,444 +0,0 @@ -/* - * 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@ - */ - -/*********************************************************************** -* objc-initialize.m -* +initialize support -**********************************************************************/ - -/*********************************************************************** - * Thread-safety during class initialization (GrP 2001-9-24) - * - * Initial state: CLS_INITIALIZING and CLS_INITIALIZED both clear. - * During initialization: CLS_INITIALIZING is set - * After initialization: CLS_INITIALIZING clear and CLS_INITIALIZED set. - * CLS_INITIALIZING and CLS_INITIALIZED are never set at the same time. - * CLS_INITIALIZED is never cleared once set. - * - * Only one thread is allowed to actually initialize a class and send - * +initialize. Enforced by allowing only one thread to set CLS_INITIALIZING. - * - * Additionally, threads trying to send messages to a class must wait for - * +initialize to finish. During initialization of a class, that class's - * method cache is kept empty. objc_msgSend will revert to - * class_lookupMethodAndLoadCache, which checks CLS_INITIALIZED before - * messaging. If CLS_INITIALIZED is clear but CLS_INITIALIZING is set, - * the thread must block, unless it is the thread that started - * initializing the class in the first place. - * - * Each thread keeps a list of classes it's initializing. - * The global classInitLock is used to synchronize changes to CLS_INITIALIZED - * and CLS_INITIALIZING: the transition to CLS_INITIALIZING must be - * an atomic test-and-set with respect to itself and the transition - * to CLS_INITIALIZED. - * The global classInitWaitCond is used to block threads waiting for an - * initialization to complete. The classInitLock synchronizes - * condition checking and the condition variable. - **********************************************************************/ - -/*********************************************************************** - * +initialize deadlock case when a class is marked initializing while - * its superclass is initialized. Solved by completely initializing - * superclasses before beginning to initialize a class. - * - * OmniWeb class hierarchy: - * OBObject - * | ` OBPostLoader - * OFObject - * / \ - * OWAddressEntry OWController - * | - * OWConsoleController - * - * Thread 1 (evil testing thread): - * initialize OWAddressEntry - * super init OFObject - * super init OBObject - * [OBObject initialize] runs OBPostLoader, which inits lots of classes... - * initialize OWConsoleController - * super init OWController - wait for Thread 2 to finish OWController init - * - * Thread 2 (normal OmniWeb thread): - * initialize OWController - * super init OFObject - wait for Thread 1 to finish OFObject init - * - * deadlock! - * - * Solution: fully initialize super classes before beginning to initialize - * a subclass. Then the initializing+initialized part of the class hierarchy - * will be a contiguous subtree starting at the root, so other threads - * can't jump into the middle between two initializing classes, and we won't - * get stuck while a superclass waits for its subclass which waits for the - * superclass. - **********************************************************************/ - -#include "objc-private.h" -#include "message.h" -#include "objc-initialize.h" - -/* classInitLock protects CLS_INITIALIZED and CLS_INITIALIZING, and - * is signalled when any class is done initializing. - * Threads that are waiting for a class to finish initializing wait on this. */ -static monitor_t classInitLock; - - -/*********************************************************************** -* struct _objc_initializing_classes -* Per-thread list of classes currently being initialized by that thread. -* During initialization, that thread is allowed to send messages to that -* class, but other threads have to wait. -* The list is a simple array of metaclasses (the metaclass stores -* the initialization state). -**********************************************************************/ -typedef struct _objc_initializing_classes { - int classesAllocated; - Class *metaclasses; -} _objc_initializing_classes; - - -/*********************************************************************** -* _fetchInitializingClassList -* Return the list of classes being initialized by this thread. -* If create == YES, create the list when no classes are being initialized by this thread. -* If create == NO, return nil when no classes are being initialized by this thread. -**********************************************************************/ -static _objc_initializing_classes *_fetchInitializingClassList(BOOL create) -{ - _objc_pthread_data *data; - _objc_initializing_classes *list; - Class *classes; - - data = _objc_fetch_pthread_data(create); - if (data == nil) return nil; - - list = data->initializingClasses; - if (list == nil) { - if (!create) { - return nil; - } else { - list = (_objc_initializing_classes *) - calloc(1, sizeof(_objc_initializing_classes)); - data->initializingClasses = list; - } - } - - classes = list->metaclasses; - if (classes == nil) { - // If _objc_initializing_classes exists, allocate metaclass array, - // even if create == NO. - // Allow 4 simultaneous class inits on this thread before realloc. - list->classesAllocated = 4; - classes = (Class *) - calloc(list->classesAllocated, sizeof(Class)); - list->metaclasses = classes; - } - return list; -} - - -/*********************************************************************** -* _destroyInitializingClassList -* Deallocate memory used by the given initialization list. -* Any part of the list may be nil. -* Called from _objc_pthread_destroyspecific(). -**********************************************************************/ - -void _destroyInitializingClassList(struct _objc_initializing_classes *list) -{ - if (list != nil) { - if (list->metaclasses != nil) { - free(list->metaclasses); - } - free(list); - } -} - - -/*********************************************************************** -* _thisThreadIsInitializingClass -* Return TRUE if this thread is currently initializing the given class. -**********************************************************************/ -static BOOL _thisThreadIsInitializingClass(Class cls) -{ - int i; - - _objc_initializing_classes *list = _fetchInitializingClassList(NO); - if (list) { - cls = cls->getMeta(); - for (i = 0; i < list->classesAllocated; i++) { - if (cls == list->metaclasses[i]) return YES; - } - } - - // no list or not found in list - return NO; -} - - -/*********************************************************************** -* _setThisThreadIsInitializingClass -* Record that this thread is currently initializing the given class. -* This thread will be allowed to send messages to the class, but -* other threads will have to wait. -**********************************************************************/ -static void _setThisThreadIsInitializingClass(Class cls) -{ - int i; - _objc_initializing_classes *list = _fetchInitializingClassList(YES); - cls = cls->getMeta(); - - // paranoia: explicitly disallow duplicates - for (i = 0; i < list->classesAllocated; i++) { - if (cls == list->metaclasses[i]) { - _objc_fatal("thread is already initializing this class!"); - return; // already the initializer - } - } - - for (i = 0; i < list->classesAllocated; i++) { - if (! list->metaclasses[i]) { - list->metaclasses[i] = cls; - return; - } - } - - // class list is full - reallocate - list->classesAllocated = list->classesAllocated * 2 + 1; - list->metaclasses = (Class *) - realloc(list->metaclasses, - list->classesAllocated * sizeof(Class)); - // zero out the new entries - list->metaclasses[i++] = cls; - for ( ; i < list->classesAllocated; i++) { - list->metaclasses[i] = nil; - } -} - - -/*********************************************************************** -* _setThisThreadIsNotInitializingClass -* Record that this thread is no longer initializing the given class. -**********************************************************************/ -static void _setThisThreadIsNotInitializingClass(Class cls) -{ - int i; - - _objc_initializing_classes *list = _fetchInitializingClassList(NO); - if (list) { - cls = cls->getMeta(); - for (i = 0; i < list->classesAllocated; i++) { - if (cls == list->metaclasses[i]) { - list->metaclasses[i] = nil; - return; - } - } - } - - // no list or not found in list - _objc_fatal("thread is not initializing this class!"); -} - - -typedef struct PendingInitialize { - Class subclass; - struct PendingInitialize *next; -} PendingInitialize; - -static NXMapTable *pendingInitializeMap; - -/*********************************************************************** -* _finishInitializing -* cls has completed its +initialize method, and so has its superclass. -* Mark cls as initialized as well, then mark any of cls's subclasses -* that have already finished their own +initialize methods. -**********************************************************************/ -static void _finishInitializing(Class cls, Class supercls) -{ - PendingInitialize *pending; - - classInitLock.assertLocked(); - assert(!supercls || supercls->isInitialized()); - - if (PrintInitializing) { - _objc_inform("INITIALIZE: %s is fully +initialized", - cls->nameForLogging()); - } - - // propagate finalization affinity. - if (UseGC && supercls && supercls->shouldFinalizeOnMainThread()) { - cls->setShouldFinalizeOnMainThread(); - } - - // mark this class as fully +initialized - cls->setInitialized(); - classInitLock.notifyAll(); - _setThisThreadIsNotInitializingClass(cls); - - // mark any subclasses that were merely waiting for this class - if (!pendingInitializeMap) return; - pending = (PendingInitialize *)NXMapGet(pendingInitializeMap, cls); - if (!pending) return; - - NXMapRemove(pendingInitializeMap, cls); - - // Destroy the pending table if it's now empty, to save memory. - if (NXCountMapTable(pendingInitializeMap) == 0) { - NXFreeMapTable(pendingInitializeMap); - pendingInitializeMap = nil; - } - - while (pending) { - PendingInitialize *next = pending->next; - if (pending->subclass) _finishInitializing(pending->subclass, cls); - free(pending); - pending = next; - } -} - - -/*********************************************************************** -* _finishInitializingAfter -* cls has completed its +initialize method, but its superclass has not. -* Wait until supercls finishes before marking cls as initialized. -**********************************************************************/ -static void _finishInitializingAfter(Class cls, Class supercls) -{ - PendingInitialize *pending; - - classInitLock.assertLocked(); - - if (PrintInitializing) { - _objc_inform("INITIALIZE: %s waiting for superclass +[%s initialize]", - cls->nameForLogging(), supercls->nameForLogging()); - } - - if (!pendingInitializeMap) { - pendingInitializeMap = - NXCreateMapTable(NXPtrValueMapPrototype, 10); - // fixme pre-size this table for CF/NSObject +initialize - } - - pending = (PendingInitialize *)malloc(sizeof(*pending)); - pending->subclass = cls; - pending->next = (PendingInitialize *) - NXMapGet(pendingInitializeMap, supercls); - NXMapInsert(pendingInitializeMap, supercls, pending); -} - - -/*********************************************************************** -* class_initialize. Send the '+initialize' message on demand to any -* uninitialized class. Force initialization of superclasses first. -**********************************************************************/ -void _class_initialize(Class cls) -{ - assert(!cls->isMetaClass()); - - Class supercls; - BOOL reallyInitialize = NO; - - // Make sure super is done initializing BEFORE beginning to initialize cls. - // See note about deadlock above. - supercls = cls->superclass; - if (supercls && !supercls->isInitialized()) { - _class_initialize(supercls); - } - - // Try to atomically set CLS_INITIALIZING. - { - monitor_locker_t lock(classInitLock); - if (!cls->isInitialized() && !cls->isInitializing()) { - cls->setInitializing(); - reallyInitialize = YES; - } - } - - if (reallyInitialize) { - // We successfully set the CLS_INITIALIZING bit. Initialize the class. - - // Record that we're initializing this class so we can message it. - _setThisThreadIsInitializingClass(cls); - - // Send the +initialize message. - // Note that +initialize is sent to the superclass (again) if - // this class doesn't implement +initialize. 2157218 - if (PrintInitializing) { - _objc_inform("INITIALIZE: calling +[%s initialize]", - cls->nameForLogging()); - } - - ((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize); - - if (PrintInitializing) { - _objc_inform("INITIALIZE: finished +[%s initialize]", - cls->nameForLogging()); - } - - // Done initializing. - // If the superclass is also done initializing, then update - // the info bits and notify waiting threads. - // If not, update them later. (This can happen if this +initialize - // was itself triggered from inside a superclass +initialize.) - monitor_locker_t lock(classInitLock); - if (!supercls || supercls->isInitialized()) { - _finishInitializing(cls, supercls); - } else { - _finishInitializingAfter(cls, supercls); - } - return; - } - - else if (cls->isInitializing()) { - // We couldn't set INITIALIZING because INITIALIZING was already set. - // If this thread set it earlier, continue normally. - // If some other thread set it, block until initialize is done. - // It's ok if INITIALIZING changes to INITIALIZED while we're here, - // because we safely check for INITIALIZED inside the lock - // before blocking. - if (_thisThreadIsInitializingClass(cls)) { - return; - } else { - monitor_locker_t lock(classInitLock); - while (!cls->isInitialized()) { - classInitLock.wait(); - } - return; - } - } - - else if (cls->isInitialized()) { - // Set CLS_INITIALIZING failed because someone else already - // initialized the class. Continue normally. - // NOTE this check must come AFTER the ISINITIALIZING case. - // Otherwise: Another thread is initializing this class. ISINITIALIZED - // is false. Skip this clause. Then the other thread finishes - // initialization and sets INITIALIZING=no and INITIALIZED=yes. - // Skip the ISINITIALIZING clause. Die horribly. - return; - } - - else { - // We shouldn't be here. - _objc_fatal("thread-safe class init in objc runtime is buggy!"); - } -} diff --git a/objc/objc-runtime/runtime/objc-internal.h b/objc/objc-runtime/runtime/objc-internal.h deleted file mode 100644 index f77cb18..0000000 --- a/objc/objc-runtime/runtime/objc-internal.h +++ /dev/null @@ -1,673 +0,0 @@ -/* - * Copyright (c) 2009 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 _OBJC_INTERNAL_H -#define _OBJC_INTERNAL_H - -/* - * WARNING DANGER HAZARD BEWARE EEK - * - * Everything in this file is for Apple Internal use only. - * These will change in arbitrary OS updates and in unpredictable ways. - * When your program breaks, you get to keep both pieces. - */ - -/* - * objc-internal.h: Private SPI for use by other system frameworks. - */ - -#include <objc/objc.h> -#include <objc/runtime.h> -#include <Availability.h> -#include <malloc/malloc.h> -#include <dispatch/dispatch.h> - -__BEGIN_DECLS - -// This is the allocation size required for each of the class and the metaclass -// with objc_initializeClassPair() and objc_readClassPair(). -// The runtime's class structure will never grow beyond this. -#define OBJC_MAX_CLASS_SIZE (32*sizeof(void*)) - -// In-place construction of an Objective-C class. -// cls and metacls must each be OBJC_MAX_CLASS_SIZE bytes. -// Returns nil if a class with the same name already exists. -// Returns nil if the superclass is under construction. -// Call objc_registerClassPair() when you are done. -OBJC_EXPORT Class objc_initializeClassPair(Class superclass, const char *name, Class cls, Class metacls) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0); - -// Class and metaclass construction from a compiler-generated memory image. -// cls and cls->isa must each be OBJC_MAX_CLASS_SIZE bytes. -// Extra bytes not used the the metadata must be zero. -// info is the same objc_image_info that would be emitted by a static compiler. -// Returns nil if a class with the same name already exists. -// Returns nil if the superclass is nil and the class is not marked as a root. -// Returns nil if the superclass is under construction. -// Do not call objc_registerClassPair(). -#if __OBJC2__ -struct objc_image_info; -OBJC_EXPORT Class objc_readClassPair(Class cls, - const struct objc_image_info *info) - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0); -#endif - -// Batch object allocation using malloc_zone_batch_malloc(). -OBJC_EXPORT unsigned class_createInstances(Class cls, size_t extraBytes, - id *results, unsigned num_requested) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3) - OBJC_ARC_UNAVAILABLE; - -// Get the isa pointer written into objects just before being freed. -OBJC_EXPORT Class _objc_getFreedObjectClass(void) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -// Return YES if GC is on and `object` is a GC allocation. -OBJC_EXPORT BOOL objc_isAuto(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); - -// env NSObjCMessageLoggingEnabled -OBJC_EXPORT void instrumentObjcMessageSends(BOOL flag) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -// Initializer called by libSystem -#if __OBJC2__ -OBJC_EXPORT void _objc_init(void) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); -#endif - -#ifndef OBJC_NO_GC -// GC startup callback from Foundation -OBJC_EXPORT malloc_zone_t *objc_collect_init(int (*callback)(void)) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); -#endif - -// Plainly-implemented GC barriers. Rosetta used to use these. -OBJC_EXPORT id objc_assign_strongCast_generic(id value, id *dest) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT id objc_assign_global_generic(id value, id *dest) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT id objc_assign_threadlocal_generic(id value, id *dest) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT id objc_assign_ivar_generic(id value, id dest, ptrdiff_t offset) - UNAVAILABLE_ATTRIBUTE; - -// Install missing-class callback. Used by the late unlamented ZeroLink. -OBJC_EXPORT void _objc_setClassLoader(BOOL (*newClassLoader)(const char *)) OBJC2_UNAVAILABLE; - -// Install handler for allocation failures. -// Handler may abort, or throw, or provide an object to return. -OBJC_EXPORT void _objc_setBadAllocHandler(id (*newHandler)(Class isa)) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); - -// This can go away when AppKit stops calling it (rdar://7811851) -#if __OBJC2__ -OBJC_EXPORT void objc_setMultithreaded (BOOL flag) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); -#endif - -// Used by ExceptionHandling.framework -#if !__OBJC2__ -OBJC_EXPORT void _objc_error(id rcv, const char *fmt, va_list args) - __attribute__((noreturn)) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_NA,__IPHONE_NA); - -#endif - - -// Tagged pointer objects. - -#if __LP64__ -#define OBJC_HAVE_TAGGED_POINTERS 1 -#endif - -#if OBJC_HAVE_TAGGED_POINTERS - -// Tagged pointer layout and usage is subject to change -// on different OS versions. The current layout is: -// (MSB) -// 60 bits payload -// 3 bits tag index -// 1 bit 1 for tagged pointer objects, 0 for ordinary objects -// (LSB) - -#if __has_feature(objc_fixed_enum) || __cplusplus >= 201103L -enum objc_tag_index_t : uint8_t -#else -typedef uint8_t objc_tag_index_t; -enum -#endif -{ - OBJC_TAG_NSAtom = 0, - OBJC_TAG_1 = 1, - OBJC_TAG_NSString = 2, - OBJC_TAG_NSNumber = 3, - OBJC_TAG_NSIndexPath = 4, - OBJC_TAG_NSManagedObjectID = 5, - OBJC_TAG_NSDate = 6, - OBJC_TAG_7 = 7 -}; -#if __has_feature(objc_fixed_enum) && !defined(__cplusplus) -typedef enum objc_tag_index_t objc_tag_index_t; -#endif - -OBJC_EXPORT void _objc_registerTaggedPointerClass(objc_tag_index_t tag, Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -OBJC_EXPORT Class _objc_getClassForTag(objc_tag_index_t tag) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -static inline bool -_objc_taggedPointersEnabled(void) -{ - extern uintptr_t objc_debug_taggedpointer_mask; - return (objc_debug_taggedpointer_mask != 0); -} - -#if TARGET_OS_IPHONE -// tagged pointer marker is MSB - -static inline void * -_objc_makeTaggedPointer(objc_tag_index_t tag, uintptr_t value) -{ - // assert(_objc_taggedPointersEnabled()); - // assert((unsigned int)tag < 8); - // assert(((value << 4) >> 4) == value); - return (void*)((1UL << 63) | ((uintptr_t)tag << 60) | (value & ~(0xFUL << 60))); -} - -static inline bool -_objc_isTaggedPointer(const void *ptr) -{ - return (intptr_t)ptr < 0; // a.k.a. ptr & 0x8000000000000000 -} - -static inline objc_tag_index_t -_objc_getTaggedPointerTag(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (objc_tag_index_t)(((uintptr_t)ptr >> 60) & 0x7); -} - -static inline uintptr_t -_objc_getTaggedPointerValue(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (uintptr_t)ptr & 0x0fffffffffffffff; -} - -static inline intptr_t -_objc_getTaggedPointerSignedValue(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return ((intptr_t)ptr << 4) >> 4; -} - -// TARGET_OS_IPHONE -#else -// not TARGET_OS_IPHONE -// tagged pointer marker is LSB - -static inline void * -_objc_makeTaggedPointer(objc_tag_index_t tag, uintptr_t value) -{ - // assert(_objc_taggedPointersEnabled()); - // assert((unsigned int)tag < 8); - // assert(((value << 4) >> 4) == value); - return (void *)((value << 4) | ((uintptr_t)tag << 1) | 1); -} - -static inline bool -_objc_isTaggedPointer(const void *ptr) -{ - return (uintptr_t)ptr & 1; -} - -static inline objc_tag_index_t -_objc_getTaggedPointerTag(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (objc_tag_index_t)(((uintptr_t)ptr & 0xe) >> 1); -} - -static inline uintptr_t -_objc_getTaggedPointerValue(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (uintptr_t)ptr >> 4; -} - -static inline intptr_t -_objc_getTaggedPointerSignedValue(const void *ptr) -{ - // assert(_objc_isTaggedPointer(ptr)); - return (intptr_t)ptr >> 4; -} - -// not TARGET_OS_IPHONE -#endif - - -OBJC_EXPORT void _objc_insert_tagged_isa(unsigned char slotNumber, Class isa) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7,__MAC_10_9, __IPHONE_4_3,__IPHONE_7_0); - -#endif - - -// External Reference support. Used to support compaction. - -enum { - OBJC_XREF_STRONG = 1, - OBJC_XREF_WEAK = 2 -}; -typedef uintptr_t objc_xref_type_t; -typedef uintptr_t objc_xref_t; - -OBJC_EXPORT objc_xref_t _object_addExternalReference(id object, objc_xref_type_t type) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); -OBJC_EXPORT void _object_removeExternalReference(objc_xref_t xref) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); -OBJC_EXPORT id _object_readExternalReference(objc_xref_t xref) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -OBJC_EXPORT uintptr_t _object_getExternalHash(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -/** - * Returns the method implementation of an object. - * - * @param obj An Objective-C object. - * @param name An Objective-C selector. - * - * @return The IMP corresponding to the instance method implemented by - * the class of \e obj. - * - * @note Equivalent to: - * - * class_getMethodImplementation(object_getClass(obj), name); - */ -OBJC_EXPORT IMP object_getMethodImplementation(id obj, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -OBJC_EXPORT IMP object_getMethodImplementation_stret(id obj, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0) - OBJC_ARM64_UNAVAILABLE; - - -// Instance-specific instance variable layout. - -OBJC_EXPORT void _class_setIvarLayoutAccessor(Class cls_gen, const uint8_t* (*accessor) (id object)) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -OBJC_EXPORT const uint8_t *_object_getIvarLayout(Class cls_gen, id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -OBJC_EXPORT BOOL _class_usesAutomaticRetainRelease(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT BOOL _class_isFutureClass(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - - -// Obsolete ARC conversions. - -// hack - remove and reinstate objc.h's definitions -#undef objc_retainedObject -#undef objc_unretainedObject -#undef objc_unretainedPointer -OBJC_EXPORT id objc_retainedObject(objc_objectptr_t pointer) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT id objc_unretainedObject(objc_objectptr_t pointer) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -OBJC_EXPORT objc_objectptr_t objc_unretainedPointer(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); -#if __has_feature(objc_arc) -# define objc_retainedObject(o) ((__bridge_transfer id)(objc_objectptr_t)(o)) -# define objc_unretainedObject(o) ((__bridge id)(objc_objectptr_t)(o)) -# define objc_unretainedPointer(o) ((__bridge objc_objectptr_t)(id)(o)) -#else -# define objc_retainedObject(o) ((id)(objc_objectptr_t)(o)) -# define objc_unretainedObject(o) ((id)(objc_objectptr_t)(o)) -# define objc_unretainedPointer(o) ((objc_objectptr_t)(id)(o)) -#endif - -// API to only be called by root classes like NSObject or NSProxy - -OBJC_EXPORT -id -_objc_rootRetain(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -_objc_rootRelease(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -bool -_objc_rootReleaseWasZero(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -bool -_objc_rootTryRetain(id obj) -__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -bool -_objc_rootIsDeallocating(id obj) -__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -_objc_rootAutorelease(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -uintptr_t -_objc_rootRetainCount(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -_objc_rootInit(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -_objc_rootAlloc(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -_objc_rootDealloc(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -_objc_rootFinalize(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -malloc_zone_t * -_objc_rootZone(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -uintptr_t -_objc_rootHash(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void * -objc_autoreleasePoolPush(void) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -objc_autoreleasePoolPop(void *context) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -OBJC_EXPORT id objc_alloc(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -OBJC_EXPORT id objc_allocWithZone(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); - -OBJC_EXPORT id objc_retain(id obj) - __asm__("_objc_retain") - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT void objc_release(id obj) - __asm__("_objc_release") - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT id objc_autorelease(id obj) - __asm__("_objc_autorelease") - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Prepare a value at +1 for return through a +0 autoreleasing convention. -OBJC_EXPORT -id -objc_autoreleaseReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Prepare a value at +0 for return through a +0 autoreleasing convention. -OBJC_EXPORT -id -objc_retainAutoreleaseReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Accept a value returned through a +0 autoreleasing convention for use at +1. -OBJC_EXPORT -id -objc_retainAutoreleasedReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Accept a value returned through a +0 autoreleasing convention for use at +0. -OBJC_EXPORT -id -objc_unsafeClaimAutoreleasedReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_11, __IPHONE_9_0); - -OBJC_EXPORT -void -objc_storeStrong(id *location, id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -objc_retainAutorelease(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// obsolete. -OBJC_EXPORT id objc_retain_autorelease(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -objc_loadWeakRetained(id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -id -objc_initWeak(id *location, id val) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Like objc_storeWeak, but stores nil if the new object is deallocating -// or the new object's class does not support weak references. -// Returns the value stored (either the new object or nil). -OBJC_EXPORT -id -objc_storeWeakOrNil(id *location, id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_11, __IPHONE_9_0); - -// Like objc_initWeak, but stores nil if the new object is deallocating -// or the new object's class does not support weak references. -// Returns the value stored (either the new object or nil). -OBJC_EXPORT -id -objc_initWeakOrNil(id *location, id val) - __OSX_AVAILABLE_STARTING(__MAC_10_11, __IPHONE_9_0); - -OBJC_EXPORT -void -objc_destroyWeak(id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -objc_copyWeak(id *to, id *from) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -objc_moveWeak(id *to, id *from) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -OBJC_EXPORT -void -_objc_autoreleasePoolPrint(void) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT BOOL objc_should_deallocate(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT void objc_clear_deallocating(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -// to make CF link for now - -OBJC_EXPORT -void * -_objc_autoreleasePoolPush(void) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -OBJC_EXPORT -void -_objc_autoreleasePoolPop(void *context) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -// Extra @encode data for XPC, or NULL -OBJC_EXPORT const char *_protocol_getMethodTypeEncoding(Protocol *p, SEL sel, BOOL isRequiredMethod, BOOL isInstanceMethod) - __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0); - - -// API to only be called by classes that provide their own reference count storage - -OBJC_EXPORT -void -_objc_deallocOnMainThreadHelper(void *context) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// On async versus sync deallocation and the _dealloc2main flag -// -// Theory: -// -// If order matters, then code must always: [self dealloc]. -// If order doesn't matter, then always async should be safe. -// -// Practice: -// -// The _dealloc2main bit is set for GUI objects that may be retained by other -// threads. Once deallocation begins on the main thread, doing more async -// deallocation will at best cause extra UI latency and at worst cause -// use-after-free bugs in unretained delegate style patterns. Yes, this is -// extremely fragile. Yes, in the long run, developers should switch to weak -// references. -// -// Note is NOT safe to do any equality check against the result of -// dispatch_get_current_queue(). The main thread can and does drain more than -// one dispatch queue. That is why we call pthread_main_np(). -// - -typedef enum { - _OBJC_RESURRECT_OBJECT = -1, /* _logicBlock has called -retain, and scheduled a -release for later. */ - _OBJC_DEALLOC_OBJECT_NOW = 1, /* call [self dealloc] immediately. */ - _OBJC_DEALLOC_OBJECT_LATER = 2 /* call [self dealloc] on the main queue. */ -} _objc_object_disposition_t; - -#define _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC_BLOCK(_rc_ivar, _logicBlock) \ - -(id)retain { \ - /* this will fail to compile if _rc_ivar is an unsigned type */ \ - int _retain_count_ivar_must_not_be_unsigned[0L - (__typeof__(_rc_ivar))-1] __attribute__((unused)); \ - __typeof__(_rc_ivar) _prev = __sync_fetch_and_add(&_rc_ivar, 2); \ - if (_prev < -2) { /* specifically allow resurrection from logical 0. */ \ - __builtin_trap(); /* BUG: retain of over-released ref */ \ - } \ - return self; \ - } \ - -(oneway void)release { \ - __typeof__(_rc_ivar) _prev = __sync_fetch_and_sub(&_rc_ivar, 2); \ - if (_prev > 0) { \ - return; \ - } else if (_prev < 0) { \ - __builtin_trap(); /* BUG: over-release */ \ - } \ - _objc_object_disposition_t fate = _logicBlock(self); \ - if (fate == _OBJC_RESURRECT_OBJECT) { \ - return; \ - } \ - /* mark the object as deallocating. */ \ - if (!__sync_bool_compare_and_swap(&_rc_ivar, -2, 1)) { \ - __builtin_trap(); /* BUG: dangling ref did a retain */ \ - } \ - if (fate == _OBJC_DEALLOC_OBJECT_NOW) { \ - [self dealloc]; \ - } else if (fate == _OBJC_DEALLOC_OBJECT_LATER) { \ - dispatch_barrier_async_f(dispatch_get_main_queue(), self, \ - _objc_deallocOnMainThreadHelper); \ - } else { \ - __builtin_trap(); /* BUG: bogus fate value */ \ - } \ - } \ - -(NSUInteger)retainCount { \ - return (_rc_ivar + 2) >> 1; \ - } \ - -(BOOL)_tryRetain { \ - __typeof__(_rc_ivar) _prev; \ - do { \ - _prev = _rc_ivar; \ - if (_prev & 1) { \ - return 0; \ - } else if (_prev == -2) { \ - return 0; \ - } else if (_prev < -2) { \ - __builtin_trap(); /* BUG: over-release elsewhere */ \ - } \ - } while ( ! __sync_bool_compare_and_swap(&_rc_ivar, _prev, _prev + 2)); \ - return 1; \ - } \ - -(BOOL)_isDeallocating { \ - if (_rc_ivar == -2) { \ - return 1; \ - } else if (_rc_ivar < -2) { \ - __builtin_trap(); /* BUG: over-release elsewhere */ \ - } \ - return _rc_ivar & 1; \ - } - -#define _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC(_rc_ivar, _dealloc2main) \ - _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC_BLOCK(_rc_ivar, (^(id _self_ __attribute__((unused))) { \ - if (_dealloc2main && !pthread_main_np()) { \ - return _OBJC_DEALLOC_OBJECT_LATER; \ - } else { \ - return _OBJC_DEALLOC_OBJECT_NOW; \ - } \ - })) - -#define _OBJC_SUPPORTED_INLINE_REFCNT(_rc_ivar) _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC(_rc_ivar, 0) -#define _OBJC_SUPPORTED_INLINE_REFCNT_WITH_DEALLOC2MAIN(_rc_ivar) _OBJC_SUPPORTED_INLINE_REFCNT_LOGIC(_rc_ivar, 1) - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/runtime/objc-layout.mm b/objc/objc-runtime/runtime/objc-layout.mm deleted file mode 100644 index d125f08..0000000 --- a/objc/objc-runtime/runtime/objc-layout.mm +++ /dev/null @@ -1,928 +0,0 @@ -/* - * Copyright (c) 2004-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@ - */ - -#include <stdlib.h> -#include <assert.h> - -#include "objc-private.h" - -/********************************************************************** -* Object Layouts. -* -* Layouts are used by the garbage collector to identify references from -* the object to other objects. -* -* Layout information is in the form of a '\0' terminated byte string. -* Each byte contains a word skip count in the high nibble and a -* consecutive references count in the low nibble. Counts that exceed 15 are -* continued in the succeeding byte with a zero in the opposite nibble. -* Objects that should be scanned conservatively will have a NULL layout. -* Objects that have no references have a empty byte string. -* -* Example; -* -* For a class with pointers at offsets 4,12, 16, 32-128 -* the layout is { 0x11, 0x12, 0x3f, 0x0a, 0x00 } or -* skip 1 - 1 reference (4) -* skip 1 - 2 references (12, 16) -* skip 3 - 15 references (32-88) -* no skip - 10 references (92-128) -* end -* -**********************************************************************/ - - -/********************************************************************** -* compress_layout -* Allocates and returns a compressed string matching the given layout bitmap. -**********************************************************************/ -static unsigned char * -compress_layout(const uint8_t *bits, size_t bitmap_bits, bool weak) -{ - bool all_set = YES; - bool none_set = YES; - unsigned char *result; - - // overallocate a lot; reallocate at correct size later - unsigned char * const layout = (unsigned char *) - calloc(bitmap_bits + 1, 1); - unsigned char *l = layout; - - size_t i = 0; - while (i < bitmap_bits) { - size_t skip = 0; - size_t scan = 0; - - // Count one range each of skip and scan. - while (i < bitmap_bits) { - uint8_t bit = (uint8_t)((bits[i/8] >> (i % 8)) & 1); - if (bit) break; - i++; - skip++; - } - while (i < bitmap_bits) { - uint8_t bit = (uint8_t)((bits[i/8] >> (i % 8)) & 1); - if (!bit) break; - i++; - scan++; - none_set = NO; - } - - // Record skip and scan - if (skip) all_set = NO; - if (scan) none_set = NO; - while (skip > 0xf) { - *l++ = 0xf0; - skip -= 0xf; - } - if (skip || scan) { - *l = (uint8_t)(skip << 4); // NOT incremented - merges with scan - while (scan > 0xf) { - *l++ |= 0x0f; // May merge with short skip; must calloc - scan -= 0xf; - } - *l++ |= scan; // NOT checked for zero - always increments - // May merge with short skip; must calloc - } - } - - // insert terminating byte - *l++ = '\0'; - - // return result - if (none_set && weak) { - result = NULL; // NULL weak layout means none-weak - } else if (all_set && !weak) { - result = NULL; // NULL ivar layout means all-scanned - } else { - result = (unsigned char *)strdup((char *)layout); - } - free(layout); - return result; -} - - -static void set_bits(layout_bitmap bits, size_t which, size_t count) -{ - // fixme optimize for byte/word at a time - size_t bit; - for (bit = which; bit < which + count && bit < bits.bitCount; bit++) { - bits.bits[bit/8] |= 1 << (bit % 8); - } - if (bit == bits.bitCount && bit < which + count) { - // couldn't fit full type in bitmap - _objc_fatal("layout bitmap too short"); - } -} - -static void clear_bits(layout_bitmap bits, size_t which, size_t count) -{ - // fixme optimize for byte/word at a time - size_t bit; - for (bit = which; bit < which + count && bit < bits.bitCount; bit++) { - bits.bits[bit/8] &= ~(1 << (bit % 8)); - } - if (bit == bits.bitCount && bit < which + count) { - // couldn't fit full type in bitmap - _objc_fatal("layout bitmap too short"); - } -} - -static void move_bits(layout_bitmap bits, size_t src, size_t dst, - size_t count) -{ - // fixme optimize for byte/word at a time - - if (dst == src) { - return; - } - else if (dst > src) { - // Copy backwards in case of overlap - size_t pos = count; - while (pos--) { - size_t srcbit = src + pos; - size_t dstbit = dst + pos; - if (bits.bits[srcbit/8] & (1 << (srcbit % 8))) { - bits.bits[dstbit/8] |= 1 << (dstbit % 8); - } else { - bits.bits[dstbit/8] &= ~(1 << (dstbit % 8)); - } - } - } - else { - // Copy forwards in case of overlap - size_t pos; - for (pos = 0; pos < count; pos++) { - size_t srcbit = src + pos; - size_t dstbit = dst + pos; - if (bits.bits[srcbit/8] & (1 << (srcbit % 8))) { - bits.bits[dstbit/8] |= 1 << (dstbit % 8); - } else { - bits.bits[dstbit/8] &= ~(1 << (dstbit % 8)); - } - } - } -} - -// emacs autoindent hack - it doesn't like the loop in set_bits/clear_bits -#if 0 -} } -#endif - - -static void decompress_layout(const unsigned char *layout_string, layout_bitmap bits) -{ - unsigned char c; - size_t bit = 0; - while ((c = *layout_string++)) { - unsigned char skip = (c & 0xf0) >> 4; - unsigned char scan = (c & 0x0f); - bit += skip; - set_bits(bits, bit, scan); - bit += scan; - } -} - - -/*********************************************************************** -* layout_bitmap_create -* Allocate a layout bitmap. -* The new bitmap spans the given instance size bytes. -* The start of the bitmap is filled from the given layout string (which -* spans an instance size of layoutStringSize); the rest is zero-filled. -* The returned bitmap must be freed with layout_bitmap_free(). -**********************************************************************/ -layout_bitmap -layout_bitmap_create(const unsigned char *layout_string, - size_t layoutStringInstanceSize, - size_t instanceSize, bool weak) -{ - layout_bitmap result; - size_t words = instanceSize / sizeof(id); - - result.weak = weak; - result.bitCount = words; - result.bitsAllocated = words; - result.bits = (uint8_t *)calloc((words+7)/8, 1); - - if (!layout_string) { - if (!weak) { - // NULL ivar layout means all-scanned - // (but only up to layoutStringSize instance size) - set_bits(result, 0, layoutStringInstanceSize/sizeof(id)); - } else { - // NULL weak layout means none-weak. - } - } else { - decompress_layout(layout_string, result); - } - - return result; -} - - -/*********************************************************************** - * layout_bitmap_create_empty - * Allocate a layout bitmap. - * The new bitmap spans the given instance size bytes. - * The bitmap is empty, to represent an object whose ivars are completely unscanned. - * The returned bitmap must be freed with layout_bitmap_free(). - **********************************************************************/ -layout_bitmap -layout_bitmap_create_empty(size_t instanceSize, bool weak) -{ - layout_bitmap result; - size_t words = instanceSize / sizeof(id); - - result.weak = weak; - result.bitCount = words; - result.bitsAllocated = words; - result.bits = (uint8_t *)calloc((words+7)/8, 1); - - return result; -} - -void -layout_bitmap_free(layout_bitmap bits) -{ - if (bits.bits) free(bits.bits); -} - -const unsigned char * -layout_string_create(layout_bitmap bits) -{ - const unsigned char *result = - compress_layout(bits.bits, bits.bitCount, bits.weak); - -#if DEBUG - // paranoia: cycle to bitmap and back to string again, and compare - layout_bitmap check = layout_bitmap_create(result, bits.bitCount*sizeof(id), - bits.bitCount*sizeof(id), bits.weak); - unsigned char *result2 = - compress_layout(check.bits, check.bitCount, check.weak); - if (result != result2 && 0 != strcmp((char*)result, (char *)result2)) { - layout_bitmap_print(bits); - layout_bitmap_print(check); - _objc_fatal("libobjc bug: mishandled layout bitmap"); - } - free(result2); - layout_bitmap_free(check); -#endif - - return result; -} - - -void -layout_bitmap_set_ivar(layout_bitmap bits, const char *type, size_t offset) -{ - // fixme only handles some types - size_t bit = offset / sizeof(id); - - if (!type) return; - if (type[0] == '@' || 0 == strcmp(type, "^@")) { - // id - // id * - // Block ("@?") - set_bits(bits, bit, 1); - } - else if (type[0] == '[') { - // id[] - char *t; - unsigned long count = strtoul(type+1, &t, 10); - if (t && t[0] == '@') { - set_bits(bits, bit, count); - } - } - else if (strchr(type, '@')) { - _objc_inform("warning: failing to set GC layout for '%s'\n", type); - } -} - - - -/*********************************************************************** -* layout_bitmap_grow -* Expand a layout bitmap to span newCount bits. -* The new bits are undefined. -**********************************************************************/ -void -layout_bitmap_grow(layout_bitmap *bits, size_t newCount) -{ - if (bits->bitCount >= newCount) return; - bits->bitCount = newCount; - if (bits->bitsAllocated < newCount) { - size_t newAllocated = bits->bitsAllocated * 2; - if (newAllocated < newCount) newAllocated = newCount; - bits->bits = (uint8_t *) - realloc(bits->bits, (newAllocated+7) / 8); - bits->bitsAllocated = newAllocated; - } - assert(bits->bitsAllocated >= bits->bitCount); - assert(bits->bitsAllocated >= newCount); -} - - -/*********************************************************************** -* layout_bitmap_slide -* Slide the end of a layout bitmap farther from the start. -* Slides bits [oldPos, bits.bitCount) to [newPos, bits.bitCount+newPos-oldPos) -* Bits [oldPos, newPos) are zero-filled. -* The bitmap is expanded and bitCount updated if necessary. -* newPos >= oldPos. -**********************************************************************/ -void -layout_bitmap_slide(layout_bitmap *bits, size_t oldPos, size_t newPos) -{ - size_t shift; - size_t count; - - if (oldPos == newPos) return; - if (oldPos > newPos) _objc_fatal("layout bitmap sliding backwards"); - - shift = newPos - oldPos; - count = bits->bitCount - oldPos; - layout_bitmap_grow(bits, bits->bitCount + shift); - move_bits(*bits, oldPos, newPos, count); // slide - clear_bits(*bits, oldPos, shift); // zero-fill -} - - -/*********************************************************************** -* layout_bitmap_slide_anywhere -* Slide the end of a layout bitmap relative to the start. -* Like layout_bitmap_slide, but can slide backwards too. -* The end of the bitmap is truncated. -**********************************************************************/ -void -layout_bitmap_slide_anywhere(layout_bitmap *bits, size_t oldPos, size_t newPos) -{ - size_t shift; - size_t count; - - if (oldPos == newPos) return; - - if (oldPos < newPos) { - layout_bitmap_slide(bits, oldPos, newPos); - return; - } - - shift = oldPos - newPos; - count = bits->bitCount - oldPos; - move_bits(*bits, oldPos, newPos, count); // slide - bits->bitCount -= shift; -} - - -/*********************************************************************** -* layout_bitmap_splat -* Pastes the contents of bitmap src to the start of bitmap dst. -* dst bits between the end of src and oldSrcInstanceSize are zeroed. -* dst must be at least as long as src. -* Returns YES if any of dst's bits were changed. -**********************************************************************/ -bool -layout_bitmap_splat(layout_bitmap dst, layout_bitmap src, - size_t oldSrcInstanceSize) -{ - bool changed; - size_t oldSrcBitCount; - size_t bit; - - if (dst.bitCount < src.bitCount) _objc_fatal("layout bitmap too short"); - - changed = NO; - oldSrcBitCount = oldSrcInstanceSize / sizeof(id); - - // fixme optimize for byte/word at a time - for (bit = 0; bit < oldSrcBitCount; bit++) { - int dstset = dst.bits[bit/8] & (1 << (bit % 8)); - int srcset = (bit < src.bitCount) - ? src.bits[bit/8] & (1 << (bit % 8)) - : 0; - if (dstset != srcset) { - changed = YES; - if (srcset) { - dst.bits[bit/8] |= 1 << (bit % 8); - } else { - dst.bits[bit/8] &= ~(1 << (bit % 8)); - } - } - } - - return changed; -} - - -/*********************************************************************** -* layout_bitmap_or -* Set dst=dst|src. -* dst must be at least as long as src. -* Returns YES if any of dst's bits were changed. -**********************************************************************/ -bool -layout_bitmap_or(layout_bitmap dst, layout_bitmap src, const char *msg) -{ - bool changed = NO; - size_t bit; - - if (dst.bitCount < src.bitCount) { - _objc_fatal("layout_bitmap_or: layout bitmap too short%s%s", - msg ? ": " : "", msg ? msg : ""); - } - - // fixme optimize for byte/word at a time - for (bit = 0; bit < src.bitCount; bit++) { - int dstset = dst.bits[bit/8] & (1 << (bit % 8)); - int srcset = src.bits[bit/8] & (1 << (bit % 8)); - if (srcset && !dstset) { - changed = YES; - dst.bits[bit/8] |= 1 << (bit % 8); - } - } - - return changed; -} - - -/*********************************************************************** -* layout_bitmap_clear -* Set dst=dst&~src. -* dst must be at least as long as src. -* Returns YES if any of dst's bits were changed. -**********************************************************************/ -bool -layout_bitmap_clear(layout_bitmap dst, layout_bitmap src, const char *msg) -{ - bool changed = NO; - size_t bit; - - if (dst.bitCount < src.bitCount) { - _objc_fatal("layout_bitmap_clear: layout bitmap too short%s%s", - msg ? ": " : "", msg ? msg : ""); - } - - // fixme optimize for byte/word at a time - for (bit = 0; bit < src.bitCount; bit++) { - int dstset = dst.bits[bit/8] & (1 << (bit % 8)); - int srcset = src.bits[bit/8] & (1 << (bit % 8)); - if (srcset && dstset) { - changed = YES; - dst.bits[bit/8] &= ~(1 << (bit % 8)); - } - } - - return changed; -} - - -void -layout_bitmap_print(layout_bitmap bits) -{ - size_t i; - printf("%zu: ", bits.bitCount); - for (i = 0; i < bits.bitCount; i++) { - int set = bits.bits[i/8] & (1 << (i % 8)); - printf("%c", set ? '#' : '.'); - } - printf("\n"); -} - -#if 0 -// The code below may be useful when interpreting ivar types more precisely. - -/********************************************************************** -* mark_offset_for_layout -* -* Marks the appropriate bit in the bits array cooresponding to a the -* offset of a reference. If we are scanning a nested pointer structure -* then the bits array will be NULL then this function does nothing. -* -**********************************************************************/ -static void mark_offset_for_layout(long offset, long bits_size, unsigned char *bits) { - // references are ignored if bits is NULL - if (bits) { - long slot = offset / sizeof(long); - - // determine byte index using (offset / 8 bits per byte) - long i_byte = slot >> 3; - - // if the byte index is valid - if (i_byte < bits_size) { - // set the (offset / 8 bits per byte)th bit - bits[i_byte] |= 1 << (slot & 7); - } else { - // offset not within instance size - _objc_inform ("layout - offset exceeds instance size"); - } - } -} - -/********************************************************************** -* skip_ivar_type_name -* -* Skip over the name of a field/class in an ivar type string. Names -* are in the form of a double-quoted string. Returns the remaining -* string. -* -**********************************************************************/ -static char *skip_ivar_type_name(char *type) { - // current character - char ch; - - // if there is an open quote - if (*type == '\"') { - // skip quote - type++; - - // while no closing quote - while ((ch = *type) != '\"') { - // if end of string return end of string - if (!ch) return type; - - // skip character - type++; - } - - // skip closing quote - type++; - } - - // return remaining string - return type; -} - - -/********************************************************************** -* skip_ivar_struct_name -* -* Skip over the name of a struct in an ivar type string. Names -* may be followed by an equals sign. Returns the remaining string. -* -**********************************************************************/ -static char *skip_ivar_struct_name(char *type) { - // get first character - char ch = *type; - - if (ch == _C_UNDEF) { - // skip undefined name - type++; - } else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_') { - // if alphabetic - - // scan alphanumerics - do { - // next character - ch = *++type; - } while ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_' || (ch >= '0' && ch <= '9')); - } else { - // no struct name present - return type; - } - - // skip equals sign - if (*type == '=') type++; - - return type; -} - - -/********************************************************************** -* scan_basic_ivar_type -* -* Determines the size and alignment of a basic ivar type. If the basic -* type is a possible reference to another garbage collected type the -* is_reference is set to true (false otherwise.) Returns the remaining -* string. -* -**********************************************************************/ -static char *scan_ivar_type_for_layout(char *type, long offset, long bits_size, unsigned char *bits, long *next_offset); -static char *scan_basic_ivar_type(char *type, long *size, long *alignment, bool *is_reference) { - // assume it is a non-reference type - *is_reference = NO; - - // get the first character (advancing string) - const char *full_type = type; - char ch = *type++; - - // GCC 4 uses for const type*. - if (ch == _C_CONST) ch = *type++; - - // act on first character - switch (ch) { - case _C_ID: { - // ID type - - // skip over optional class name - type = skip_ivar_type_name(type); - - // size and alignment of an id type - *size = sizeof(id); - *alignment = __alignof(id); - - // is a reference type - *is_reference = YES; - break; - } - case _C_PTR: { - // C pointer type - - // skip underlying type - long ignored_offset; - type = scan_ivar_type_for_layout(type, 0, 0, NULL, &ignored_offset); - - // size and alignment of a generic pointer type - *size = sizeof(void *); - *alignment = __alignof(void *); - - // is a reference type - *is_reference = YES; - break; - } - case _C_CHARPTR: { - // C string - - // size and alignment of a char pointer type - *size = sizeof(char *); - *alignment = __alignof(char *); - - // is a reference type - *is_reference = YES; - break; - } - case _C_CLASS: - case _C_SEL: { - // classes and selectors are ignored for now - *size = sizeof(void *); - *alignment = __alignof(void *); - break; - } - case _C_CHR: - case _C_UCHR: { - // char and unsigned char - *size = sizeof(char); - *alignment = __alignof(char); - break; - } - case _C_SHT: - case _C_USHT: { - // short and unsigned short - *size = sizeof(short); - *alignment = __alignof(short); - break; - } - case _C_ATOM: - case _C_INT: - case _C_UINT: { - // int and unsigned int - *size = sizeof(int); - *alignment = __alignof(int); - break; - } - case _C_LNG: - case _C_ULNG: { - // long and unsigned long - *size = sizeof(long); - *alignment = __alignof(long); - break; - } - case _C_LNG_LNG: - case _C_ULNG_LNG: { - // long long and unsigned long long - *size = sizeof(long long); - *alignment = __alignof(long long); - break; - } - case _C_VECTOR: { - // vector - *size = 16; - *alignment = 16; - break; - } - case _C_FLT: { - // float - *size = sizeof(float); - *alignment = __alignof(float); - break; - } - case _C_DBL: { - // double - *size = sizeof(double); - *alignment = __alignof(double); - break; - } - case _C_BFLD: { - // bit field - - // get number of bits in bit field (advance type string) - long lng = strtol(type, &type, 10); - - // while next type is a bit field - while (*type == _C_BFLD) { - // skip over _C_BFLD - type++; - - // get next bit field length - long next_lng = strtol(type, &type, 10); - - // if spans next word then align to next word - if ((lng & ~31) != ((lng + next_lng) & ~31)) lng = (lng + 31) & ~31; - - // increment running length - lng += next_lng; - - // skip over potential field name - type = skip_ivar_type_name(type); - } - - // determine number of bytes bits represent - *size = (lng + 7) / 8; - - // byte alignment - *alignment = __alignof(char); - break; - } - case _C_BOOL: { - // double - *size = sizeof(BOOL); - *alignment = __alignof(BOOL); - break; - } - case _C_VOID: { - // skip void types - *size = 0; - *alignment = __alignof(char); - break; - } - case _C_UNDEF: { - *size = 0; - *alignment = __alignof(char); - break; - } - default: { - // unhandled type - _objc_fatal("unrecognized character \'%c\' in ivar type: \"%s\"", ch, full_type); - } - } - - return type; -} - - -/********************************************************************** -* scan_ivar_type_for_layout -* -* Scan an ivar type string looking for references. The offset indicates -* where the ivar begins. bits is a byte array of size bits_size used to -* contain the references bit map. next_offset is the offset beyond the -* ivar. Returns the remaining string. -* -**********************************************************************/ -static char *scan_ivar_type_for_layout(char *type, long offset, long bits_size, unsigned char *bits, long *next_offset) { - long size; // size of a basic type - long alignment; // alignment of the basic type - bool is_reference; // true if the type indicates a reference to a garbage collected object - - // get the first character - char ch = *type; - - // GCC 4 uses for const type*. - if (ch == _C_CONST) ch = *++type; - - // act on first character - switch (ch) { - case _C_ARY_B: { - // array type - - // get the array length - long lng = strtol(type + 1, &type, 10); - - // next type will be where to advance the type string once the array is processed - char *next_type = type; - - // repeat the next type x lng - if (!lng) { - next_type = scan_ivar_type_for_layout(type, 0, 0, NULL, &offset); - } else { - while (lng--) { - // repeatedly scan the same type - next_type = scan_ivar_type_for_layout(type, offset, bits_size, bits, &offset); - } - } - - // advance the type now - type = next_type; - - // after the end of the array - *next_offset = offset; - - // advance over closing bracket - if (*type == _C_ARY_E) type++; - else _objc_inform("missing \'%c\' in ivar type.", _C_ARY_E); - - break; - } - case _C_UNION_B: { - // union type - - // skip over possible union name - type = skip_ivar_struct_name(type + 1); - - // need to accumulate the maximum element offset - long max_offset = 0; - - // while not closing paren - while ((ch = *type) && ch != _C_UNION_E) { - // skip over potential field name - type = skip_ivar_type_name(type); - - // scan type - long union_offset; - type = scan_ivar_type_for_layout(type, offset, bits_size, bits, &union_offset); - - // adjust the maximum element offset - if (max_offset < union_offset) max_offset = union_offset; - } - - // after the largest element - *next_offset = max_offset; - - // advance over closing paren - if (ch == _C_UNION_E) { - type++; - } else { - _objc_inform("missing \'%c\' in ivar type", _C_UNION_E); - } - - break; - } - case _C_STRUCT_B: { - // struct type - - // skip over possible struct name - type = skip_ivar_struct_name(type + 1); - - // while not closing brace - while ((ch = *type) && ch != _C_STRUCT_E) { - // skip over potential field name - type = skip_ivar_type_name(type); - - // scan type - type = scan_ivar_type_for_layout(type, offset, bits_size, bits, &offset); - } - - // after the end of the struct - *next_offset = offset; - - // advance over closing brace - if (ch == _C_STRUCT_E) type++; - else _objc_inform("missing \'%c\' in ivar type", _C_STRUCT_E); - - break; - } - default: { - // basic type - - // scan type - type = scan_basic_ivar_type(type, &size, &alignment, &is_reference); - - // create alignment mask - alignment--; - - // align offset - offset = (offset + alignment) & ~alignment; - - // if is a reference then mark in the bit map - if (is_reference) mark_offset_for_layout(offset, bits_size, bits); - - // after the basic type - *next_offset = offset + size; - break; - } - } - - // return remainder of type string - return type; -} - -#endif diff --git a/objc/objc-runtime/runtime/objc-load.h b/objc/objc-runtime/runtime/objc-load.h deleted file mode 100644 index 8ec1fa2..0000000 --- a/objc/objc-runtime/runtime/objc-load.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 1999-2001, 2005-2006 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@ - */ -/* - * objc-load.h - * Copyright 1988-1996, NeXT Software, Inc. - */ - -#ifndef _OBJC_LOAD_H_ -#define _OBJC_LOAD_H_ - -#include <objc/objc-class.h> - -#include <mach-o/loader.h> - -/* dynamically loading Mach-O object files that contain Objective-C code */ - -OBJC_EXPORT long objc_loadModules ( - char *modlist[], - void *errStream, - void (*class_callback) (Class, Category), - /*headerType*/ struct mach_header **hdr_addr, - char *debug_file -) OBJC2_UNAVAILABLE; -OBJC_EXPORT int objc_loadModule ( - char * moduleName, - void (*class_callback) (Class, Category), - int * errorCode -) OBJC2_UNAVAILABLE; -OBJC_EXPORT long objc_unloadModules( - void *errorStream, /* input (optional) */ - void (*unloadCallback)(Class, Category) /* input (optional) */ -) OBJC2_UNAVAILABLE; - -#endif /* _OBJC_LOAD_H_ */ diff --git a/objc/objc-runtime/runtime/objc-load.mm b/objc/objc-runtime/runtime/objc-load.mm deleted file mode 100644 index 3e00a03..0000000 --- a/objc/objc-runtime/runtime/objc-load.mm +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 1999-2001, 2004-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@ - */ - -/* - * objc-load.m - * Copyright 1988-1996, NeXT Software, Inc. - * Author: s. naroff - * - */ - -#include "objc-private.h" -#include "objc-load.h" - -#if !__OBJC2__ && !TARGET_OS_WIN32 - -extern void (*callbackFunction)( Class, Category ); - - -/********************************************************************************** -* objc_loadModule. -* -* NOTE: Loading isn't really thread safe. If a load message recursively calls -* objc_loadModules() both sets will be loaded correctly, but if the original -* caller calls objc_unloadModules() it will probably unload the wrong modules. -* If a load message calls objc_unloadModules(), then it will unload -* the modules currently being loaded, which will probably cause a crash. -* -* Error handling is still somewhat crude. If we encounter errors while -* linking up classes or categories, we will not recover correctly. -* -* I removed attempts to lock the class hashtable, since this introduced -* deadlock which was hard to remove. The only way you can get into trouble -* is if one thread loads a module while another thread tries to access the -* loaded classes (using objc_lookUpClass) before the load is complete. -**********************************************************************************/ -int objc_loadModule(char *moduleName, void (*class_callback) (Class, Category), int *errorCode) -{ - int successFlag = 1; - int locErrorCode; - NSObjectFileImage objectFileImage; - NSObjectFileImageReturnCode code; - - // So we don't have to check this everywhere - if (errorCode == NULL) - errorCode = &locErrorCode; - - if (moduleName == NULL) - { - *errorCode = NSObjectFileImageInappropriateFile; - return 0; - } - - if (_dyld_present () == 0) - { - *errorCode = NSObjectFileImageFailure; - return 0; - } - - callbackFunction = class_callback; - code = NSCreateObjectFileImageFromFile (moduleName, &objectFileImage); - if (code != NSObjectFileImageSuccess) - { - *errorCode = code; - return 0; - } - - if (NSLinkModule(objectFileImage, moduleName, NSLINKMODULE_OPTION_RETURN_ON_ERROR) == NULL) { - NSLinkEditErrors error; - int errorNum; - const char *fileName, *errorString; - NSLinkEditError(&error, &errorNum, &fileName, &errorString); - // These errors may overlap with other errors that objc_loadModule returns in other failure cases. - *errorCode = error; - return 0; - } - callbackFunction = NULL; - - - return successFlag; -} - -/********************************************************************************** -* objc_loadModules. -**********************************************************************************/ -/* Lock for dynamic loading and unloading. */ -// static OBJC_DECLARE_LOCK (loadLock); - - -long objc_loadModules (char * modlist[], - void * errStream, - void (*class_callback) (Class, Category), - headerType ** hdr_addr, - char * debug_file) -{ - char ** modules; - int code; - int itWorked; - - if (modlist == 0) - return 0; - - for (modules = &modlist[0]; *modules != 0; modules++) - { - itWorked = objc_loadModule (*modules, class_callback, &code); - if (itWorked == 0) - { - //if (errStream) - // NXPrintf ((NXStream *) errStream, "objc_loadModules(%s) code = %d\n", *modules, code); - return 1; - } - - if (hdr_addr) - *(hdr_addr++) = 0; - } - - return 0; -} - -/********************************************************************************** -* objc_unloadModules. -* -* NOTE: Unloading isn't really thread safe. If an unload message calls -* objc_loadModules() or objc_unloadModules(), then the current call -* to objc_unloadModules() will probably unload the wrong stuff. -**********************************************************************************/ - -long objc_unloadModules (void * errStream, - void (*unload_callback) (Class, Category)) -{ - headerType * header_addr = 0; - int errflag = 0; - - // TODO: to make unloading work, should get the current header - - if (header_addr) - { - ; // TODO: unload the current header - } - else - { - errflag = 1; - } - - return errflag; -} - -#endif diff --git a/objc/objc-runtime/runtime/objc-loadmethod.h b/objc/objc-runtime/runtime/objc-loadmethod.h deleted file mode 100644 index f1f2b9c..0000000 --- a/objc/objc-runtime/runtime/objc-loadmethod.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2004-2006 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@ - */ - -/*********************************************************************** -* objc-loadmethod.h -* Support for +load methods. -**********************************************************************/ - -#ifndef _OBJC_LOADMETHOD_H -#define _OBJC_LOADMETHOD_H - -#include "objc-private.h" - -__BEGIN_DECLS - -extern void add_class_to_loadable_list(Class cls); -extern void add_category_to_loadable_list(Category cat); -extern void remove_class_from_loadable_list(Class cls); -extern void remove_category_from_loadable_list(Category cat); - -extern void call_load_methods(void); - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/runtime/objc-loadmethod.mm b/objc/objc-runtime/runtime/objc-loadmethod.mm deleted file mode 100644 index 1dec30c..0000000 --- a/objc/objc-runtime/runtime/objc-loadmethod.mm +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (c) 2004-2006 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@ - */ - -/*********************************************************************** -* objc-loadmethod.m -* Support for +load methods. -**********************************************************************/ - -#include "objc-loadmethod.h" -#include "objc-private.h" - -typedef void(*load_method_t)(id, SEL); - -struct loadable_class { - Class cls; // may be nil - IMP method; -}; - -struct loadable_category { - Category cat; // may be nil - IMP method; -}; - - -// List of classes that need +load called (pending superclass +load) -// This list always has superclasses first because of the way it is constructed -static struct loadable_class *loadable_classes = nil; -static int loadable_classes_used = 0; -static int loadable_classes_allocated = 0; - -// List of categories that need +load called (pending parent class +load) -static struct loadable_category *loadable_categories = nil; -static int loadable_categories_used = 0; -static int loadable_categories_allocated = 0; - - -/*********************************************************************** -* add_class_to_loadable_list -* Class cls has just become connected. Schedule it for +load if -* it implements a +load method. -**********************************************************************/ -void add_class_to_loadable_list(Class cls) -{ - IMP method; - - loadMethodLock.assertLocked(); - - method = cls->getLoadMethod(); - if (!method) return; // Don't bother if cls has no +load method - - if (PrintLoading) { - _objc_inform("LOAD: class '%s' scheduled for +load", - cls->nameForLogging()); - } - - if (loadable_classes_used == loadable_classes_allocated) { - loadable_classes_allocated = loadable_classes_allocated*2 + 16; - loadable_classes = (struct loadable_class *) - realloc(loadable_classes, - loadable_classes_allocated * - sizeof(struct loadable_class)); - } - - loadable_classes[loadable_classes_used].cls = cls; - loadable_classes[loadable_classes_used].method = method; - loadable_classes_used++; -} - - -/*********************************************************************** -* add_category_to_loadable_list -* Category cat's parent class exists and the category has been attached -* to its class. Schedule this category for +load after its parent class -* becomes connected and has its own +load method called. -**********************************************************************/ -void add_category_to_loadable_list(Category cat) -{ - IMP method; - - loadMethodLock.assertLocked(); - - method = _category_getLoadMethod(cat); - - // Don't bother if cat has no +load method - if (!method) return; - - if (PrintLoading) { - _objc_inform("LOAD: category '%s(%s)' scheduled for +load", - _category_getClassName(cat), _category_getName(cat)); - } - - - if (loadable_categories_used == loadable_categories_allocated) { - loadable_categories_allocated = loadable_categories_allocated*2 + 16; - loadable_categories = (struct loadable_category *) - realloc(loadable_categories, - loadable_categories_allocated * - sizeof(struct loadable_category)); - } - - loadable_categories[loadable_categories_used].cat = cat; - loadable_categories[loadable_categories_used].method = method; - loadable_categories_used++; -} - - -/*********************************************************************** -* remove_class_from_loadable_list -* Class cls may have been loadable before, but it is now no longer -* loadable (because its image is being unmapped). -**********************************************************************/ -void remove_class_from_loadable_list(Class cls) -{ - loadMethodLock.assertLocked(); - - if (loadable_classes) { - int i; - for (i = 0; i < loadable_classes_used; i++) { - if (loadable_classes[i].cls == cls) { - loadable_classes[i].cls = nil; - if (PrintLoading) { - _objc_inform("LOAD: class '%s' unscheduled for +load", - cls->nameForLogging()); - } - return; - } - } - } -} - - -/*********************************************************************** -* remove_category_from_loadable_list -* Category cat may have been loadable before, but it is now no longer -* loadable (because its image is being unmapped). -**********************************************************************/ -void remove_category_from_loadable_list(Category cat) -{ - loadMethodLock.assertLocked(); - - if (loadable_categories) { - int i; - for (i = 0; i < loadable_categories_used; i++) { - if (loadable_categories[i].cat == cat) { - loadable_categories[i].cat = nil; - if (PrintLoading) { - _objc_inform("LOAD: category '%s(%s)' unscheduled for +load", - _category_getClassName(cat), - _category_getName(cat)); - } - return; - } - } - } -} - - -/*********************************************************************** -* call_class_loads -* Call all pending class +load methods. -* If new classes become loadable, +load is NOT called for them. -* -* Called only by call_load_methods(). -**********************************************************************/ -static void call_class_loads(void) -{ - int i; - - // Detach current loadable list. - struct loadable_class *classes = loadable_classes; - int used = loadable_classes_used; - loadable_classes = nil; - loadable_classes_allocated = 0; - loadable_classes_used = 0; - - // Call all +loads for the detached list. - for (i = 0; i < used; i++) { - Class cls = classes[i].cls; - load_method_t load_method = (load_method_t)classes[i].method; - if (!cls) continue; - - if (PrintLoading) { - _objc_inform("LOAD: +[%s load]\n", cls->nameForLogging()); - } - (*load_method)(cls, SEL_load); - } - - // Destroy the detached list. - if (classes) free(classes); -} - - -/*********************************************************************** -* call_category_loads -* Call some pending category +load methods. -* The parent class of the +load-implementing categories has all of -* its categories attached, in case some are lazily waiting for +initalize. -* Don't call +load unless the parent class is connected. -* If new categories become loadable, +load is NOT called, and they -* are added to the end of the loadable list, and we return TRUE. -* Return FALSE if no new categories became loadable. -* -* Called only by call_load_methods(). -**********************************************************************/ -static bool call_category_loads(void) -{ - int i, shift; - bool new_categories_added = NO; - - // Detach current loadable list. - struct loadable_category *cats = loadable_categories; - int used = loadable_categories_used; - int allocated = loadable_categories_allocated; - loadable_categories = nil; - loadable_categories_allocated = 0; - loadable_categories_used = 0; - - // Call all +loads for the detached list. - for (i = 0; i < used; i++) { - Category cat = cats[i].cat; - load_method_t load_method = (load_method_t)cats[i].method; - Class cls; - if (!cat) continue; - - cls = _category_getClass(cat); - if (cls && cls->isLoadable()) { - if (PrintLoading) { - _objc_inform("LOAD: +[%s(%s) load]\n", - cls->nameForLogging(), - _category_getName(cat)); - } - (*load_method)(cls, SEL_load); - cats[i].cat = nil; - } - } - - // Compact detached list (order-preserving) - shift = 0; - for (i = 0; i < used; i++) { - if (cats[i].cat) { - cats[i-shift] = cats[i]; - } else { - shift++; - } - } - used -= shift; - - // Copy any new +load candidates from the new list to the detached list. - new_categories_added = (loadable_categories_used > 0); - for (i = 0; i < loadable_categories_used; i++) { - if (used == allocated) { - allocated = allocated*2 + 16; - cats = (struct loadable_category *) - realloc(cats, allocated * - sizeof(struct loadable_category)); - } - cats[used++] = loadable_categories[i]; - } - - // Destroy the new list. - if (loadable_categories) free(loadable_categories); - - // Reattach the (now augmented) detached list. - // But if there's nothing left to load, destroy the list. - if (used) { - loadable_categories = cats; - loadable_categories_used = used; - loadable_categories_allocated = allocated; - } else { - if (cats) free(cats); - loadable_categories = nil; - loadable_categories_used = 0; - loadable_categories_allocated = 0; - } - - if (PrintLoading) { - if (loadable_categories_used != 0) { - _objc_inform("LOAD: %d categories still waiting for +load\n", - loadable_categories_used); - } - } - - return new_categories_added; -} - - -/*********************************************************************** -* call_load_methods -* Call all pending class and category +load methods. -* Class +load methods are called superclass-first. -* Category +load methods are not called until after the parent class's +load. -* -* This method must be RE-ENTRANT, because a +load could trigger -* more image mapping. In addition, the superclass-first ordering -* must be preserved in the face of re-entrant calls. Therefore, -* only the OUTERMOST call of this function will do anything, and -* that call will handle all loadable classes, even those generated -* while it was running. -* -* The sequence below preserves +load ordering in the face of -* image loading during a +load, and make sure that no -* +load method is forgotten because it was added during -* a +load call. -* Sequence: -* 1. Repeatedly call class +loads until there aren't any more -* 2. Call category +loads ONCE. -* 3. Run more +loads if: -* (a) there are more classes to load, OR -* (b) there are some potential category +loads that have -* still never been attempted. -* Category +loads are only run once to ensure "parent class first" -* ordering, even if a category +load triggers a new loadable class -* and a new loadable category attached to that class. -* -* Locking: loadMethodLock must be held by the caller -* All other locks must not be held. -**********************************************************************/ -void call_load_methods(void) -{ - static bool loading = NO; - bool more_categories; - - loadMethodLock.assertLocked(); - - // Re-entrant calls do nothing; the outermost call will finish the job. - if (loading) return; - loading = YES; - - void *pool = objc_autoreleasePoolPush(); - - do { - // 1. Repeatedly call class +loads until there aren't any more - while (loadable_classes_used > 0) { - call_class_loads(); - } - - // 2. Call category +loads ONCE - more_categories = call_category_loads(); - - // 3. Run more +loads if there are classes OR more untried categories - } while (loadable_classes_used > 0 || more_categories); - - objc_autoreleasePoolPop(pool); - - loading = NO; -} - - diff --git a/objc/objc-runtime/runtime/objc-lockdebug.h b/objc/objc-runtime/runtime/objc-lockdebug.h deleted file mode 100644 index 071064d..0000000 --- a/objc/objc-runtime/runtime/objc-lockdebug.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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@ - */ - -extern void lockdebug_mutex_lock(mutex_tt<true> *lock); -extern void lockdebug_mutex_try_lock(mutex_tt<true> *lock); -extern void lockdebug_mutex_unlock(mutex_tt<true> *lock); -extern void lockdebug_mutex_assert_locked(mutex_tt<true> *lock); -extern void lockdebug_mutex_assert_unlocked(mutex_tt<true> *lock); - -static inline void lockdebug_mutex_lock(mutex_tt<false> *lock) { } -static inline void lockdebug_mutex_try_lock(mutex_tt<false> *lock) { } -static inline void lockdebug_mutex_unlock(mutex_tt<false> *lock) { } -static inline void lockdebug_mutex_assert_locked(mutex_tt<false> *lock) { } -static inline void lockdebug_mutex_assert_unlocked(mutex_tt<false> *lock) { } - - -extern void lockdebug_monitor_enter(monitor_tt<true> *lock); -extern void lockdebug_monitor_leave(monitor_tt<true> *lock); -extern void lockdebug_monitor_wait(monitor_tt<true> *lock); -extern void lockdebug_monitor_assert_locked(monitor_tt<true> *lock); -extern void lockdebug_monitor_assert_unlocked(monitor_tt<true> *lock); - -static inline void lockdebug_monitor_enter(monitor_tt<false> *lock) { } -static inline void lockdebug_monitor_leave(monitor_tt<false> *lock) { } -static inline void lockdebug_monitor_wait(monitor_tt<false> *lock) { } -static inline void lockdebug_monitor_assert_locked(monitor_tt<false> *lock) { } -static inline void lockdebug_monitor_assert_unlocked(monitor_tt<false> *lock) {} - - -extern void -lockdebug_recursive_mutex_lock(recursive_mutex_tt<true> *lock); -extern void -lockdebug_recursive_mutex_unlock(recursive_mutex_tt<true> *lock); -extern void -lockdebug_recursive_mutex_assert_locked(recursive_mutex_tt<true> *lock); -extern void -lockdebug_recursive_mutex_assert_unlocked(recursive_mutex_tt<true> *lock); - -static inline void -lockdebug_recursive_mutex_lock(recursive_mutex_tt<false> *lock) { } -static inline void -lockdebug_recursive_mutex_unlock(recursive_mutex_tt<false> *lock) { } -static inline void -lockdebug_recursive_mutex_assert_locked(recursive_mutex_tt<false> *lock) { } -static inline void -lockdebug_recursive_mutex_assert_unlocked(recursive_mutex_tt<false> *lock) { } - - -extern void lockdebug_rwlock_read(rwlock_tt<true> *lock); -extern void lockdebug_rwlock_try_read_success(rwlock_tt<true> *lock); -extern void lockdebug_rwlock_unlock_read(rwlock_tt<true> *lock); -extern void lockdebug_rwlock_write(rwlock_tt<true> *lock); -extern void lockdebug_rwlock_try_write_success(rwlock_tt<true> *lock); -extern void lockdebug_rwlock_unlock_write(rwlock_tt<true> *lock); -extern void lockdebug_rwlock_assert_reading(rwlock_tt<true> *lock); -extern void lockdebug_rwlock_assert_writing(rwlock_tt<true> *lock); -extern void lockdebug_rwlock_assert_locked(rwlock_tt<true> *lock); -extern void lockdebug_rwlock_assert_unlocked(rwlock_tt<true> *lock); - -static inline void lockdebug_rwlock_read(rwlock_tt<false> *) { } -static inline void lockdebug_rwlock_try_read_success(rwlock_tt<false> *) { } -static inline void lockdebug_rwlock_unlock_read(rwlock_tt<false> *) { } -static inline void lockdebug_rwlock_write(rwlock_tt<false> *) { } -static inline void lockdebug_rwlock_try_write_success(rwlock_tt<false> *) { } -static inline void lockdebug_rwlock_unlock_write(rwlock_tt<false> *) { } -static inline void lockdebug_rwlock_assert_reading(rwlock_tt<false> *) { } -static inline void lockdebug_rwlock_assert_writing(rwlock_tt<false> *) { } -static inline void lockdebug_rwlock_assert_locked(rwlock_tt<false> *) { } -static inline void lockdebug_rwlock_assert_unlocked(rwlock_tt<false> *) { } diff --git a/objc/objc-runtime/runtime/objc-lockdebug.mm b/objc/objc-runtime/runtime/objc-lockdebug.mm deleted file mode 100644 index 5423acd..0000000 --- a/objc/objc-runtime/runtime/objc-lockdebug.mm +++ /dev/null @@ -1,432 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -/*********************************************************************** -* objc-lock.m -* Error-checking locks for debugging. -**********************************************************************/ - -#include "objc-private.h" - -#if DEBUG && !TARGET_OS_WIN32 - -/*********************************************************************** -* Recording - per-thread list of mutexes and monitors held -**********************************************************************/ - -typedef struct { - void *l; // the lock itself - int k; // the kind of lock it is (MUTEX, MONITOR, etc) - int i; // the lock's nest count -} lockcount; - -#define MUTEX 1 -#define MONITOR 2 -#define RDLOCK 3 -#define WRLOCK 4 -#define RECURSIVE 5 - -typedef struct _objc_lock_list { - int allocated; - int used; - lockcount list[0]; -} _objc_lock_list; - -static tls_key_t lock_tls; - -static void -destroyLocks(void *value) -{ - _objc_lock_list *locks = (_objc_lock_list *)value; - // fixme complain about any still-held locks? - if (locks) free(locks); -} - -static struct _objc_lock_list * -getLocks(BOOL create) -{ - _objc_lock_list *locks; - - // Use a dedicated tls key to prevent differences vs non-debug in - // usage of objc's other tls keys (required for some unit tests). - INIT_ONCE_PTR(lock_tls, tls_create(&destroyLocks), (void)0); - - locks = (_objc_lock_list *)tls_get(lock_tls); - if (!locks) { - if (!create) { - return NULL; - } else { - locks = (_objc_lock_list *)calloc(1, sizeof(_objc_lock_list) + sizeof(lockcount) * 16); - locks->allocated = 16; - locks->used = 0; - tls_set(lock_tls, locks); - } - } - - if (locks->allocated == locks->used) { - if (!create) { - return locks; - } else { - _objc_lock_list *oldlocks = locks; - locks = (_objc_lock_list *)calloc(1, sizeof(_objc_lock_list) + 2 * oldlocks->used * sizeof(lockcount)); - locks->used = oldlocks->used; - locks->allocated = oldlocks->used * 2; - memcpy(locks->list, oldlocks->list, locks->used * sizeof(lockcount)); - tls_set(lock_tls, locks); - free(oldlocks); - } - } - - return locks; -} - -static BOOL -hasLock(_objc_lock_list *locks, void *lock, int kind) -{ - int i; - if (!locks) return NO; - - for (i = 0; i < locks->used; i++) { - if (locks->list[i].l == lock && locks->list[i].k == kind) return YES; - } - return NO; -} - - -static void -setLock(_objc_lock_list *locks, void *lock, int kind) -{ - int i; - for (i = 0; i < locks->used; i++) { - if (locks->list[i].l == lock && locks->list[i].k == kind) { - locks->list[i].i++; - return; - } - } - - locks->list[locks->used].l = lock; - locks->list[locks->used].i = 1; - locks->list[locks->used].k = kind; - locks->used++; -} - -static void -clearLock(_objc_lock_list *locks, void *lock, int kind) -{ - int i; - for (i = 0; i < locks->used; i++) { - if (locks->list[i].l == lock && locks->list[i].k == kind) { - if (--locks->list[i].i == 0) { - locks->list[i].l = NULL; - locks->list[i] = locks->list[--locks->used]; - } - return; - } - } - - _objc_fatal("lock not found!"); -} - - -/*********************************************************************** -* Mutex checking -**********************************************************************/ - -void -lockdebug_mutex_lock(mutex_t *lock) -{ - _objc_lock_list *locks = getLocks(YES); - - if (hasLock(locks, lock, MUTEX)) { - _objc_fatal("deadlock: relocking mutex"); - } - setLock(locks, lock, MUTEX); -} - -// try-lock success is the only case with lockdebug effects. -// try-lock when already locked is OK (will fail) -// try-lock failure does nothing. -void -lockdebug_mutex_try_lock_success(mutex_t *lock) -{ - _objc_lock_list *locks = getLocks(YES); - setLock(locks, lock, MUTEX); -} - -void -lockdebug_mutex_unlock(mutex_t *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, MUTEX)) { - _objc_fatal("unlocking unowned mutex"); - } - clearLock(locks, lock, MUTEX); -} - - -void -lockdebug_mutex_assert_locked(mutex_t *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, MUTEX)) { - _objc_fatal("mutex incorrectly not locked"); - } -} - -void -lockdebug_mutex_assert_unlocked(mutex_t *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (hasLock(locks, lock, MUTEX)) { - _objc_fatal("mutex incorrectly locked"); - } -} - - -/*********************************************************************** -* Recursive mutex checking -**********************************************************************/ - -void -lockdebug_recursive_mutex_lock(recursive_mutex_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(YES); - setLock(locks, lock, RECURSIVE); -} - -void -lockdebug_recursive_mutex_unlock(recursive_mutex_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, RECURSIVE)) { - _objc_fatal("unlocking unowned recursive mutex"); - } - clearLock(locks, lock, RECURSIVE); -} - - -void -lockdebug_recursive_mutex_assert_locked(recursive_mutex_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, RECURSIVE)) { - _objc_fatal("recursive mutex incorrectly not locked"); - } -} - -void -lockdebug_recursive_mutex_assert_unlocked(recursive_mutex_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (hasLock(locks, lock, RECURSIVE)) { - _objc_fatal("recursive mutex incorrectly locked"); - } -} - - -/*********************************************************************** -* Monitor checking -**********************************************************************/ - -void -lockdebug_monitor_enter(monitor_t *lock) -{ - _objc_lock_list *locks = getLocks(YES); - - if (hasLock(locks, lock, MONITOR)) { - _objc_fatal("deadlock: relocking monitor"); - } - setLock(locks, lock, MONITOR); -} - -void -lockdebug_monitor_leave(monitor_t *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, MONITOR)) { - _objc_fatal("unlocking unowned monitor"); - } - clearLock(locks, lock, MONITOR); -} - -void -lockdebug_monitor_wait(monitor_t *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, MONITOR)) { - _objc_fatal("waiting in unowned monitor"); - } -} - - -void -lockdebug_monitor_assert_locked(monitor_t *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, MONITOR)) { - _objc_fatal("monitor incorrectly not locked"); - } -} - -void -lockdebug_monitor_assert_unlocked(monitor_t *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (hasLock(locks, lock, MONITOR)) { - _objc_fatal("monitor incorrectly held"); - } -} - - -/*********************************************************************** -* rwlock checking -**********************************************************************/ - -void -lockdebug_rwlock_read(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(YES); - - if (hasLock(locks, lock, RDLOCK)) { - // Recursive rwlock read is bad (may deadlock vs pending writer) - _objc_fatal("recursive rwlock read"); - } - if (hasLock(locks, lock, WRLOCK)) { - _objc_fatal("deadlock: read after write for rwlock"); - } - setLock(locks, lock, RDLOCK); -} - -// try-read success is the only case with lockdebug effects. -// try-read when already reading is OK (won't deadlock) -// try-read when already writing is OK (will fail) -// try-read failure does nothing. -void -lockdebug_rwlock_try_read_success(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(YES); - setLock(locks, lock, RDLOCK); -} - -void -lockdebug_rwlock_unlock_read(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, RDLOCK)) { - _objc_fatal("un-reading unowned rwlock"); - } - clearLock(locks, lock, RDLOCK); -} - - -void -lockdebug_rwlock_write(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(YES); - - if (hasLock(locks, lock, RDLOCK)) { - // Lock promotion not allowed (may deadlock) - _objc_fatal("deadlock: write after read for rwlock"); - } - if (hasLock(locks, lock, WRLOCK)) { - _objc_fatal("recursive rwlock write"); - } - setLock(locks, lock, WRLOCK); -} - -// try-write success is the only case with lockdebug effects. -// try-write when already reading is OK (will fail) -// try-write when already writing is OK (will fail) -// try-write failure does nothing. -void -lockdebug_rwlock_try_write_success(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(YES); - setLock(locks, lock, WRLOCK); -} - -void -lockdebug_rwlock_unlock_write(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, WRLOCK)) { - _objc_fatal("un-writing unowned rwlock"); - } - clearLock(locks, lock, WRLOCK); -} - - -void -lockdebug_rwlock_assert_reading(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, RDLOCK)) { - _objc_fatal("rwlock incorrectly not reading"); - } -} - -void -lockdebug_rwlock_assert_writing(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, WRLOCK)) { - _objc_fatal("rwlock incorrectly not writing"); - } -} - -void -lockdebug_rwlock_assert_locked(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (!hasLock(locks, lock, RDLOCK) && !hasLock(locks, lock, WRLOCK)) { - _objc_fatal("rwlock incorrectly neither reading nor writing"); - } -} - -void -lockdebug_rwlock_assert_unlocked(rwlock_tt<true> *lock) -{ - _objc_lock_list *locks = getLocks(NO); - - if (hasLock(locks, lock, RDLOCK) || hasLock(locks, lock, WRLOCK)) { - _objc_fatal("rwlock incorrectly not unlocked"); - } -} - - -#endif diff --git a/objc/objc-runtime/runtime/objc-object.h b/objc/objc-runtime/runtime/objc-object.h deleted file mode 100644 index cf592d4..0000000 --- a/objc/objc-runtime/runtime/objc-object.h +++ /dev/null @@ -1,1157 +0,0 @@ -/* - * Copyright (c) 2010-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@ - */ - - -/*********************************************************************** -* Inlineable parts of NSObject / objc_object implementation -**********************************************************************/ - -#ifndef _OBJC_OBJCOBJECT_H_ -#define _OBJC_OBJCOBJECT_H_ - -#include "objc-private.h" - - -enum ReturnDisposition : bool { - ReturnAtPlus0 = false, ReturnAtPlus1 = true -}; - -static ALWAYS_INLINE -bool prepareOptimizedReturn(ReturnDisposition disposition); - - -#if SUPPORT_TAGGED_POINTERS - -#define TAG_COUNT 8 -#define TAG_SLOT_MASK 0xf - -#if SUPPORT_MSB_TAGGED_POINTERS -# define TAG_MASK (1ULL<<63) -# define TAG_SLOT_SHIFT 60 -# define TAG_PAYLOAD_LSHIFT 4 -# define TAG_PAYLOAD_RSHIFT 4 -#else -# define TAG_MASK 1 -# define TAG_SLOT_SHIFT 0 -# define TAG_PAYLOAD_LSHIFT 0 -# define TAG_PAYLOAD_RSHIFT 4 -#endif - -extern "C" { extern Class objc_debug_taggedpointer_classes[TAG_COUNT*2]; } -#define objc_tag_classes objc_debug_taggedpointer_classes - -#endif - - -inline bool -objc_object::isClass() -{ - if (isTaggedPointer()) return false; - return ISA()->isMetaClass(); -} - -#if SUPPORT_NONPOINTER_ISA - -# if !SUPPORT_TAGGED_POINTERS -# error sorry -# endif - - -inline Class -objc_object::ISA() -{ - assert(!isTaggedPointer()); - return (Class)(isa.bits & ISA_MASK); -} - - -inline bool -objc_object::hasIndexedIsa() -{ - return isa.indexed; -} - -inline Class -objc_object::getIsa() -{ - if (isTaggedPointer()) { - uintptr_t slot = ((uintptr_t)this >> TAG_SLOT_SHIFT) & TAG_SLOT_MASK; - return objc_tag_classes[slot]; - } - return ISA(); -} - - -inline void -objc_object::initIsa(Class cls) -{ - initIsa(cls, false, false); -} - -inline void -objc_object::initClassIsa(Class cls) -{ - if (DisableIndexedIsa) { - initIsa(cls, false, false); - } else { - initIsa(cls, true, false); - } -} - -inline void -objc_object::initProtocolIsa(Class cls) -{ - return initClassIsa(cls); -} - -inline void -objc_object::initInstanceIsa(Class cls, bool hasCxxDtor) -{ - assert(!UseGC); - assert(!cls->requiresRawIsa()); - assert(hasCxxDtor == cls->hasCxxDtor()); - - initIsa(cls, true, hasCxxDtor); -} - -inline void -objc_object::initIsa(Class cls, bool indexed, bool hasCxxDtor) -{ - assert(!isTaggedPointer()); - - if (!indexed) { - isa.cls = cls; - } else { - assert(!DisableIndexedIsa); - isa.bits = ISA_MAGIC_VALUE; - // isa.magic is part of ISA_MAGIC_VALUE - // isa.indexed is part of ISA_MAGIC_VALUE - isa.has_cxx_dtor = hasCxxDtor; - isa.shiftcls = (uintptr_t)cls >> 3; - } -} - - -inline Class -objc_object::changeIsa(Class newCls) -{ - // This is almost always rue but there are - // enough edge cases that we can't assert it. - // assert(newCls->isFuture() || - // newCls->isInitializing() || newCls->isInitialized()); - - assert(!isTaggedPointer()); - - isa_t oldisa; - isa_t newisa; - - bool sideTableLocked = false; - bool transcribeToSideTable = false; - - do { - transcribeToSideTable = false; - oldisa = LoadExclusive(&isa.bits); - if ((oldisa.bits == 0 || oldisa.indexed) && - !newCls->isFuture() && newCls->canAllocIndexed()) - { - // 0 -> indexed - // indexed -> indexed - if (oldisa.bits == 0) newisa.bits = ISA_MAGIC_VALUE; - else newisa = oldisa; - // isa.magic is part of ISA_MAGIC_VALUE - // isa.indexed is part of ISA_MAGIC_VALUE - newisa.has_cxx_dtor = newCls->hasCxxDtor(); - newisa.shiftcls = (uintptr_t)newCls >> 3; - } - else if (oldisa.indexed) { - // indexed -> not indexed - // Need to copy retain count et al to side table. - // Acquire side table lock before setting isa to - // prevent races such as concurrent -release. - if (!sideTableLocked) sidetable_lock(); - sideTableLocked = true; - transcribeToSideTable = true; - newisa.cls = newCls; - } - else { - // not indexed -> not indexed - newisa.cls = newCls; - } - } while (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)); - - if (transcribeToSideTable) { - // Copy oldisa's retain count et al to side table. - // oldisa.weakly_referenced: nothing to do - // oldisa.has_assoc: nothing to do - // oldisa.has_cxx_dtor: nothing to do - sidetable_moveExtraRC_nolock(oldisa.extra_rc, - oldisa.deallocating, - oldisa.weakly_referenced); - } - - if (sideTableLocked) sidetable_unlock(); - - Class oldCls; - if (oldisa.indexed) oldCls = (Class)((uintptr_t)oldisa.shiftcls << 3); - else oldCls = oldisa.cls; - - return oldCls; -} - - -inline bool -objc_object::isTaggedPointer() -{ - return ((uintptr_t)this & TAG_MASK); -} - - -inline bool -objc_object::hasAssociatedObjects() -{ - if (isTaggedPointer()) return true; - if (isa.indexed) return isa.has_assoc; - return true; -} - - -inline void -objc_object::setHasAssociatedObjects() -{ - if (isTaggedPointer()) return; - - retry: - isa_t oldisa = LoadExclusive(&isa.bits); - isa_t newisa = oldisa; - if (!newisa.indexed) return; - if (newisa.has_assoc) return; - newisa.has_assoc = true; - if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry; -} - - -inline bool -objc_object::isWeaklyReferenced() -{ - assert(!isTaggedPointer()); - if (isa.indexed) return isa.weakly_referenced; - else return sidetable_isWeaklyReferenced(); -} - - -inline void -objc_object::setWeaklyReferenced_nolock() -{ - retry: - isa_t oldisa = LoadExclusive(&isa.bits); - isa_t newisa = oldisa; - if (!newisa.indexed) return sidetable_setWeaklyReferenced_nolock(); - if (newisa.weakly_referenced) return; - newisa.weakly_referenced = true; - if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry; -} - - -inline bool -objc_object::hasCxxDtor() -{ - assert(!isTaggedPointer()); - if (isa.indexed) return isa.has_cxx_dtor; - else return isa.cls->hasCxxDtor(); -} - - - -inline bool -objc_object::rootIsDeallocating() -{ - assert(!UseGC); - - if (isTaggedPointer()) return false; - if (isa.indexed) return isa.deallocating; - return sidetable_isDeallocating(); -} - - -inline void -objc_object::clearDeallocating() -{ - if (!isa.indexed) { - // Slow path for raw pointer isa. - sidetable_clearDeallocating(); - } - else if (isa.weakly_referenced || isa.has_sidetable_rc) { - // Slow path for non-pointer isa with weak refs and/or side table data. - clearDeallocating_slow(); - } - - assert(!sidetable_present()); -} - - -inline void -objc_object::rootDealloc() -{ - assert(!UseGC); - if (isTaggedPointer()) return; - - if (isa.indexed && - !isa.weakly_referenced && - !isa.has_assoc && - !isa.has_cxx_dtor && - !isa.has_sidetable_rc) - { - assert(!sidetable_present()); - free(this); - } - else { - object_dispose((id)this); - } -} - - -// Equivalent to calling [this retain], with shortcuts if there is no override -inline id -objc_object::retain() -{ - // UseGC is allowed here, but requires hasCustomRR. - assert(!UseGC || ISA()->hasCustomRR()); - assert(!isTaggedPointer()); - - if (! ISA()->hasCustomRR()) { - return rootRetain(); - } - - return ((id(*)(objc_object *, SEL))objc_msgSend)(this, SEL_retain); -} - - -// Base retain implementation, ignoring overrides. -// This does not check isa.fast_rr; if there is an RR override then -// it was already called and it chose to call [super retain]. -// -// tryRetain=true is the -_tryRetain path. -// handleOverflow=false is the frameless fast path. -// handleOverflow=true is the framed slow path including overflow to side table -// The code is structured this way to prevent duplication. - -ALWAYS_INLINE id -objc_object::rootRetain() -{ - return rootRetain(false, false); -} - -ALWAYS_INLINE bool -objc_object::rootTryRetain() -{ - return rootRetain(true, false) ? true : false; -} - -ALWAYS_INLINE id -objc_object::rootRetain(bool tryRetain, bool handleOverflow) -{ - assert(!UseGC); - if (isTaggedPointer()) return (id)this; - - bool sideTableLocked = false; - bool transcribeToSideTable = false; - - isa_t oldisa; - isa_t newisa; - - do { - transcribeToSideTable = false; - oldisa = LoadExclusive(&isa.bits); - newisa = oldisa; - if (!newisa.indexed) goto unindexed; - // don't check newisa.fast_rr; we already called any RR overrides - if (tryRetain && newisa.deallocating) goto tryfail; - uintptr_t carry; - newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry); // extra_rc++ - - if (carry) { - // newisa.extra_rc++ overflowed - if (!handleOverflow) return rootRetain_overflow(tryRetain); - // Leave half of the retain counts inline and - // prepare to copy the other half to the side table. - if (!tryRetain && !sideTableLocked) sidetable_lock(); - sideTableLocked = true; - transcribeToSideTable = true; - newisa.extra_rc = RC_HALF; - newisa.has_sidetable_rc = true; - } - } while (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)); - - if (transcribeToSideTable) { - // Copy the other half of the retain counts to the side table. - sidetable_addExtraRC_nolock(RC_HALF); - } - - if (!tryRetain && sideTableLocked) sidetable_unlock(); - return (id)this; - - tryfail: - if (!tryRetain && sideTableLocked) sidetable_unlock(); - return nil; - - unindexed: - if (!tryRetain && sideTableLocked) sidetable_unlock(); - if (tryRetain) return sidetable_tryRetain() ? (id)this : nil; - else return sidetable_retain(); -} - - -// Equivalent to calling [this release], with shortcuts if there is no override -inline void -objc_object::release() -{ - // UseGC is allowed here, but requires hasCustomRR. - assert(!UseGC || ISA()->hasCustomRR()); - assert(!isTaggedPointer()); - - if (! ISA()->hasCustomRR()) { - rootRelease(); - return; - } - - ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_release); -} - - -// Base release implementation, ignoring overrides. -// Does not call -dealloc. -// Returns true if the object should now be deallocated. -// This does not check isa.fast_rr; if there is an RR override then -// it was already called and it chose to call [super release]. -// -// handleUnderflow=false is the frameless fast path. -// handleUnderflow=true is the framed slow path including side table borrow -// The code is structured this way to prevent duplication. - -ALWAYS_INLINE bool -objc_object::rootRelease() -{ - return rootRelease(true, false); -} - -ALWAYS_INLINE bool -objc_object::rootReleaseShouldDealloc() -{ - return rootRelease(false, false); -} - -ALWAYS_INLINE bool -objc_object::rootRelease(bool performDealloc, bool handleUnderflow) -{ - assert(!UseGC); - if (isTaggedPointer()) return false; - - bool sideTableLocked = false; - - isa_t oldisa; - isa_t newisa; - - retry: - do { - oldisa = LoadExclusive(&isa.bits); - newisa = oldisa; - if (!newisa.indexed) goto unindexed; - // don't check newisa.fast_rr; we already called any RR overrides - uintptr_t carry; - newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry); // extra_rc-- - if (carry) goto underflow; - } while (!StoreReleaseExclusive(&isa.bits, oldisa.bits, newisa.bits)); - - if (sideTableLocked) sidetable_unlock(); - return false; - - underflow: - // newisa.extra_rc-- underflowed: borrow from side table or deallocate - - // abandon newisa to undo the decrement - newisa = oldisa; - - if (newisa.has_sidetable_rc) { - if (!handleUnderflow) { - return rootRelease_underflow(performDealloc); - } - - // Transfer retain count from side table to inline storage. - - if (!sideTableLocked) { - sidetable_lock(); - sideTableLocked = true; - if (!isa.indexed) { - // Lost a race vs the indexed -> not indexed transition - // before we got the side table lock. Stop now to avoid - // breaking the safety checks in the sidetable ExtraRC code. - goto unindexed; - } - } - - // Try to remove some retain counts from the side table. - size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF); - - // To avoid races, has_sidetable_rc must remain set - // even if the side table count is now zero. - - if (borrowed > 0) { - // Side table retain count decreased. - // Try to add them to the inline count. - newisa.extra_rc = borrowed - 1; // redo the original decrement too - bool stored = StoreExclusive(&isa.bits, oldisa.bits, newisa.bits); - if (!stored) { - // Inline update failed. - // Try it again right now. This prevents livelock on LL/SC - // architectures where the side table access itself may have - // dropped the reservation. - isa_t oldisa2 = LoadExclusive(&isa.bits); - isa_t newisa2 = oldisa2; - if (newisa2.indexed) { - uintptr_t overflow; - newisa2.bits = - addc(newisa2.bits, RC_ONE * (borrowed-1), 0, &overflow); - if (!overflow) { - stored = StoreReleaseExclusive(&isa.bits, oldisa2.bits, - newisa2.bits); - } - } - } - - if (!stored) { - // Inline update failed. - // Put the retains back in the side table. - sidetable_addExtraRC_nolock(borrowed); - goto retry; - } - - // Decrement successful after borrowing from side table. - // This decrement cannot be the deallocating decrement - the side - // table lock and has_sidetable_rc bit ensure that if everyone - // else tried to -release while we worked, the last one would block. - sidetable_unlock(); - return false; - } - else { - // Side table is empty after all. Fall-through to the dealloc path. - } - } - - // Really deallocate. - - if (sideTableLocked) sidetable_unlock(); - - if (newisa.deallocating) { - return overrelease_error(); - } - newisa.deallocating = true; - if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry; - __sync_synchronize(); - if (performDealloc) { - ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc); - } - return true; - - unindexed: - if (sideTableLocked) sidetable_unlock(); - return sidetable_release(performDealloc); -} - - -// Equivalent to [this autorelease], with shortcuts if there is no override -inline id -objc_object::autorelease() -{ - // UseGC is allowed here, but requires hasCustomRR. - assert(!UseGC || ISA()->hasCustomRR()); - - if (isTaggedPointer()) return (id)this; - if (! ISA()->hasCustomRR()) return rootAutorelease(); - - return ((id(*)(objc_object *, SEL))objc_msgSend)(this, SEL_autorelease); -} - - -// Base autorelease implementation, ignoring overrides. -inline id -objc_object::rootAutorelease() -{ - assert(!UseGC); - - if (isTaggedPointer()) return (id)this; - if (prepareOptimizedReturn(ReturnAtPlus1)) return (id)this; - - return rootAutorelease2(); -} - - -inline uintptr_t -objc_object::rootRetainCount() -{ - assert(!UseGC); - if (isTaggedPointer()) return (uintptr_t)this; - - sidetable_lock(); - isa_t bits = LoadExclusive(&isa.bits); - if (bits.indexed) { - uintptr_t rc = 1 + bits.extra_rc; - if (bits.has_sidetable_rc) { - rc += sidetable_getExtraRC_nolock(); - } - sidetable_unlock(); - return rc; - } - - sidetable_unlock(); - return sidetable_retainCount(); -} - - -// SUPPORT_NONPOINTER_ISA -#else -// not SUPPORT_NONPOINTER_ISA - - -inline Class -objc_object::ISA() -{ - assert(!isTaggedPointer()); - return isa.cls; -} - - -inline bool -objc_object::hasIndexedIsa() -{ - return false; -} - - -inline Class -objc_object::getIsa() -{ -#if SUPPORT_TAGGED_POINTERS - if (isTaggedPointer()) { - uintptr_t slot = ((uintptr_t)this >> TAG_SLOT_SHIFT) & TAG_SLOT_MASK; - return objc_tag_classes[slot]; - } -#endif - return ISA(); -} - - -inline void -objc_object::initIsa(Class cls) -{ - assert(!isTaggedPointer()); - isa = (uintptr_t)cls; -} - - -inline void -objc_object::initClassIsa(Class cls) -{ - initIsa(cls); -} - - -inline void -objc_object::initProtocolIsa(Class cls) -{ - initIsa(cls); -} - - -inline void -objc_object::initInstanceIsa(Class cls, bool) -{ - initIsa(cls); -} - - -inline void -objc_object::initIsa(Class cls, bool, bool) -{ - initIsa(cls); -} - - -inline Class -objc_object::changeIsa(Class cls) -{ - // This is almost always rue but there are - // enough edge cases that we can't assert it. - // assert(cls->isFuture() || - // cls->isInitializing() || cls->isInitialized()); - - assert(!isTaggedPointer()); - - isa_t oldisa, newisa; - newisa.cls = cls; - do { - oldisa = LoadExclusive(&isa.bits); - } while (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)); - - if (oldisa.cls && oldisa.cls->instancesHaveAssociatedObjects()) { - cls->setInstancesHaveAssociatedObjects(); - } - - return oldisa.cls; -} - - -inline bool -objc_object::isTaggedPointer() -{ -#if SUPPORT_TAGGED_POINTERS - return ((uintptr_t)this & TAG_MASK); -#else - return false; -#endif -} - - -inline bool -objc_object::hasAssociatedObjects() -{ - assert(!UseGC); - - return getIsa()->instancesHaveAssociatedObjects(); -} - - -inline void -objc_object::setHasAssociatedObjects() -{ - assert(!UseGC); - - getIsa()->setInstancesHaveAssociatedObjects(); -} - - -inline bool -objc_object::isWeaklyReferenced() -{ - assert(!isTaggedPointer()); - assert(!UseGC); - - return sidetable_isWeaklyReferenced(); -} - - -inline void -objc_object::setWeaklyReferenced_nolock() -{ - assert(!isTaggedPointer()); - assert(!UseGC); - - sidetable_setWeaklyReferenced_nolock(); -} - - -inline bool -objc_object::hasCxxDtor() -{ - assert(!isTaggedPointer()); - return isa.cls->hasCxxDtor(); -} - - -inline bool -objc_object::rootIsDeallocating() -{ - assert(!UseGC); - - if (isTaggedPointer()) return false; - return sidetable_isDeallocating(); -} - - -inline void -objc_object::clearDeallocating() -{ - sidetable_clearDeallocating(); -} - - -inline void -objc_object::rootDealloc() -{ - if (isTaggedPointer()) return; - object_dispose((id)this); -} - - -// Equivalent to calling [this retain], with shortcuts if there is no override -inline id -objc_object::retain() -{ - // UseGC is allowed here, but requires hasCustomRR. - assert(!UseGC || ISA()->hasCustomRR()); - assert(!isTaggedPointer()); - - if (! ISA()->hasCustomRR()) { - return sidetable_retain(); - } - - return ((id(*)(objc_object *, SEL))objc_msgSend)(this, SEL_retain); -} - - -// Base retain implementation, ignoring overrides. -// This does not check isa.fast_rr; if there is an RR override then -// it was already called and it chose to call [super retain]. -inline id -objc_object::rootRetain() -{ - assert(!UseGC); - - if (isTaggedPointer()) return (id)this; - return sidetable_retain(); -} - - -// Equivalent to calling [this release], with shortcuts if there is no override -inline void -objc_object::release() -{ - // UseGC is allowed here, but requires hasCustomRR. - assert(!UseGC || ISA()->hasCustomRR()); - assert(!isTaggedPointer()); - - if (! ISA()->hasCustomRR()) { - sidetable_release(); - return; - } - - ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_release); -} - - -// Base release implementation, ignoring overrides. -// Does not call -dealloc. -// Returns true if the object should now be deallocated. -// This does not check isa.fast_rr; if there is an RR override then -// it was already called and it chose to call [super release]. -inline bool -objc_object::rootRelease() -{ - assert(!UseGC); - - if (isTaggedPointer()) return false; - return sidetable_release(true); -} - -inline bool -objc_object::rootReleaseShouldDealloc() -{ - if (isTaggedPointer()) return false; - return sidetable_release(false); -} - - -// Equivalent to [this autorelease], with shortcuts if there is no override -inline id -objc_object::autorelease() -{ - // UseGC is allowed here, but requires hasCustomRR. - assert(!UseGC || ISA()->hasCustomRR()); - - if (isTaggedPointer()) return (id)this; - if (! ISA()->hasCustomRR()) return rootAutorelease(); - - return ((id(*)(objc_object *, SEL))objc_msgSend)(this, SEL_autorelease); -} - - -// Base autorelease implementation, ignoring overrides. -inline id -objc_object::rootAutorelease() -{ - assert(!UseGC); - - if (isTaggedPointer()) return (id)this; - if (prepareOptimizedReturn(ReturnAtPlus1)) return (id)this; - - return rootAutorelease2(); -} - - -// Base tryRetain implementation, ignoring overrides. -// This does not check isa.fast_rr; if there is an RR override then -// it was already called and it chose to call [super _tryRetain]. -inline bool -objc_object::rootTryRetain() -{ - assert(!UseGC); - - if (isTaggedPointer()) return true; - return sidetable_tryRetain(); -} - - -inline uintptr_t -objc_object::rootRetainCount() -{ - assert(!UseGC); - - if (isTaggedPointer()) return (uintptr_t)this; - return sidetable_retainCount(); -} - - -// not SUPPORT_NONPOINTER_ISA -#endif - - -#if SUPPORT_RETURN_AUTORELEASE - -/*********************************************************************** - Fast handling of return through Cocoa's +0 autoreleasing convention. - The caller and callee cooperate to keep the returned object - out of the autorelease pool and eliminate redundant retain/release pairs. - - An optimized callee looks at the caller's instructions following the - return. If the caller's instructions are also optimized then the callee - skips all retain count operations: no autorelease, no retain/autorelease. - Instead it saves the result's current retain count (+0 or +1) in - thread-local storage. If the caller does not look optimized then - the callee performs autorelease or retain/autorelease as usual. - - An optimized caller looks at the thread-local storage. If the result - is set then it performs any retain or release needed to change the - result from the retain count left by the callee to the retain count - desired by the caller. Otherwise the caller assumes the result is - currently at +0 from an unoptimized callee and performs any retain - needed for that case. - - There are two optimized callees: - objc_autoreleaseReturnValue - result is currently +1. The unoptimized path autoreleases it. - objc_retainAutoreleaseReturnValue - result is currently +0. The unoptimized path retains and autoreleases it. - - There are two optimized callers: - objc_retainAutoreleasedReturnValue - caller wants the value at +1. The unoptimized path retains it. - objc_unsafeClaimAutoreleasedReturnValue - caller wants the value at +0 unsafely. The unoptimized path does nothing. - - Example: - - Callee: - // compute ret at +1 - return objc_autoreleaseReturnValue(ret); - - Caller: - ret = callee(); - ret = objc_retainAutoreleasedReturnValue(ret); - // use ret at +1 here - - Callee sees the optimized caller, sets TLS, and leaves the result at +1. - Caller sees the TLS, clears it, and accepts the result at +1 as-is. - - The callee's recognition of the optimized caller is architecture-dependent. - i386 and x86_64: Callee looks for `mov rax, rdi` followed by a call or - jump instruction to objc_retainAutoreleasedReturnValue or - objc_unsafeClaimAutoreleasedReturnValue. - armv7: Callee looks for a magic nop `mov r7, r7` (frame pointer register). - arm64: Callee looks for a magic nop `mov x29, x29` (frame pointer register). - - Tagged pointer objects do participate in the optimized return scheme, - because it saves message sends. They are not entered in the autorelease - pool in the unoptimized case. -**********************************************************************/ - -# if __x86_64__ - -static ALWAYS_INLINE bool -callerAcceptsOptimizedReturn(const void * const ra0) -{ - const uint8_t *ra1 = (const uint8_t *)ra0; - const uint16_t *ra2; - const uint32_t *ra4 = (const uint32_t *)ra1; - const void **sym; - -#define PREFER_GOTPCREL 0 -#if PREFER_GOTPCREL - // 48 89 c7 movq %rax,%rdi - // ff 15 callq *symbol@GOTPCREL(%rip) - if (*ra4 != 0xffc78948) { - return false; - } - if (ra1[4] != 0x15) { - return false; - } - ra1 += 3; -#else - // 48 89 c7 movq %rax,%rdi - // e8 callq symbol - if (*ra4 != 0xe8c78948) { - return false; - } - ra1 += (long)*(const int32_t *)(ra1 + 4) + 8l; - ra2 = (const uint16_t *)ra1; - // ff 25 jmpq *symbol@DYLDMAGIC(%rip) - if (*ra2 != 0x25ff) { - return false; - } -#endif - ra1 += 6l + (long)*(const int32_t *)(ra1 + 2); - sym = (const void **)ra1; - if (*sym != objc_retainAutoreleasedReturnValue && - *sym != objc_unsafeClaimAutoreleasedReturnValue) - { - return false; - } - - return true; -} - -// __x86_64__ -# elif __arm__ - -static ALWAYS_INLINE bool -callerAcceptsOptimizedReturn(const void *ra) -{ - // if the low bit is set, we're returning to thumb mode - if ((uintptr_t)ra & 1) { - // 3f 46 mov r7, r7 - // we mask off the low bit via subtraction - if (*(uint16_t *)((uint8_t *)ra - 1) == 0x463f) { - return true; - } - } else { - // 07 70 a0 e1 mov r7, r7 - if (*(uint32_t *)ra == 0xe1a07007) { - return true; - } - } - return false; -} - -// __arm__ -# elif __arm64__ - -static ALWAYS_INLINE bool -callerAcceptsOptimizedReturn(const void *ra) -{ - // fd 03 1d aa mov fp, fp - if (*(uint32_t *)ra == 0xaa1d03fd) { - return true; - } - return false; -} - -// __arm64__ -# elif __i386__ && TARGET_IPHONE_SIMULATOR - -static inline bool -callerAcceptsOptimizedReturn(const void *ra) -{ - return false; -} - -// __i386__ && TARGET_IPHONE_SIMULATOR -# else - -#warning unknown architecture - -static ALWAYS_INLINE bool -callerAcceptsOptimizedReturn(const void *ra) -{ - return false; -} - -// unknown architecture -# endif - - -static ALWAYS_INLINE ReturnDisposition -getReturnDisposition() -{ - return (ReturnDisposition)(uintptr_t)tls_get_direct(RETURN_DISPOSITION_KEY); -} - - -static ALWAYS_INLINE void -setReturnDisposition(ReturnDisposition disposition) -{ - tls_set_direct(RETURN_DISPOSITION_KEY, (void*)(uintptr_t)disposition); -} - - -// Try to prepare for optimized return with the given disposition (+0 or +1). -// Returns true if the optimized path is successful. -// Otherwise the return value must be retained and/or autoreleased as usual. -static ALWAYS_INLINE bool -prepareOptimizedReturn(ReturnDisposition disposition) -{ - assert(getReturnDisposition() == ReturnAtPlus0); - - if (callerAcceptsOptimizedReturn(__builtin_return_address(0))) { - if (disposition) setReturnDisposition(disposition); - return true; - } - - return false; -} - - -// Try to accept an optimized return. -// Returns the disposition of the returned object (+0 or +1). -// An un-optimized return is +0. -static ALWAYS_INLINE ReturnDisposition -acceptOptimizedReturn() -{ - ReturnDisposition disposition = getReturnDisposition(); - setReturnDisposition(ReturnAtPlus0); // reset to the unoptimized state - return disposition; -} - - -// SUPPORT_RETURN_AUTORELEASE -#else -// not SUPPORT_RETURN_AUTORELEASE - - -static ALWAYS_INLINE bool -prepareOptimizedReturn(ReturnDisposition disposition __unused) -{ - return false; -} - - -static ALWAYS_INLINE ReturnDisposition -acceptOptimizedReturn() -{ - return ReturnAtPlus0; -} - - -// not SUPPORT_RETURN_AUTORELEASE -#endif - - -// _OBJC_OBJECT_H_ -#endif diff --git a/objc/objc-runtime/runtime/objc-opt.mm b/objc/objc-runtime/runtime/objc-opt.mm deleted file mode 100644 index 55b8542..0000000 --- a/objc/objc-runtime/runtime/objc-opt.mm +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -/* - objc-opt.mm - Management of optimizations in the dyld shared cache -*/ - -#include "objc-private.h" - - -#if !SUPPORT_PREOPT -// Preoptimization not supported on this platform. - -struct objc_selopt_t; - -bool isPreoptimized(void) -{ - return false; -} - -bool header_info::isPreoptimized() const -{ - return false; -} - -objc_selopt_t *preoptimizedSelectors(void) -{ - return nil; -} - -Protocol *getPreoptimizedProtocol(const char *name) -{ - return nil; -} - -Class getPreoptimizedClass(const char *name) -{ - return nil; -} - -Class* copyPreoptimizedClasses(const char *name, int *outCount) -{ - *outCount = 0; - return nil; -} - -header_info *preoptimizedHinfoForHeader(const headerType *mhdr) -{ - return nil; -} - -void preopt_init(void) -{ - disableSharedCacheOptimizations(); - - if (PrintPreopt) { - _objc_inform("PREOPTIMIZATION: is DISABLED " - "(not supported on ths platform)"); - } -} - - -// !SUPPORT_PREOPT -#else -// SUPPORT_PREOPT - -#include <objc-shared-cache.h> - -using objc_opt::objc_stringhash_offset_t; -//using objc_opt::objc_protocolopt_t; -using objc_opt::objc_clsopt_t; -using objc_opt::objc_headeropt_t; -using objc_opt::objc_opt_t; - -__BEGIN_DECLS - -// preopt: the actual opt used at runtime (nil or &_objc_opt_data) -// _objc_opt_data: opt data possibly written by dyld -// opt is initialized to ~0 to detect incorrect use before preopt_init() - -static const objc_opt_t *opt = (objc_opt_t *)~0; -static bool preoptimized; - -extern const objc_opt_t _objc_opt_data; // in __TEXT, __objc_opt_ro - -bool isPreoptimized(void) -{ - return preoptimized; -} - - -/*********************************************************************** -* Return YES if this image's dyld shared cache optimizations are valid. -**********************************************************************/ -bool header_info::isPreoptimized() const -{ - // preoptimization disabled for some reason - if (!preoptimized) return NO; - - // image not from shared cache, or not fixed inside shared cache - if (!_objcHeaderOptimizedByDyld(this)) return NO; - - return YES; -} - - -objc_selopt_t *preoptimizedSelectors(void) -{ - return opt ? opt->selopt() : nil; -} - - -Protocol *getPreoptimizedProtocol(const char *name) -{ - return nil; -// objc_protocolopt_t *protocols = opt ? opt->protocolopt() : nil; -// if (!protocols) return nil; -// -// return (Protocol *)protocols->getProtocol(name); -} - - -Class getPreoptimizedClass(const char *name) -{ - objc_clsopt_t *classes = opt ? opt->clsopt() : nil; - if (!classes) return nil; - - void *cls; - void *hi; - uint32_t count = classes->getClassAndHeader(name, cls, hi); - if (count == 1 && ((header_info *)hi)->isLoaded()) { - // exactly one matching class, and its image is loaded - return (Class)cls; - } - else if (count > 1) { - // more than one matching class - find one that is loaded - void *clslist[count]; - void *hilist[count]; - classes->getClassesAndHeaders(name, clslist, hilist); - for (uint32_t i = 0; i < count; i++) { - if (((header_info *)hilist[i])->isLoaded()) { - return (Class)clslist[i]; - } - } - } - - // no match that is loaded - return nil; -} - - -Class* copyPreoptimizedClasses(const char *name, int *outCount) -{ - *outCount = 0; - - objc_clsopt_t *classes = opt ? opt->clsopt() : nil; - if (!classes) return nil; - - void *cls; - void *hi; - uint32_t count = classes->getClassAndHeader(name, cls, hi); - if (count == 0) return nil; - - Class *result = (Class *)calloc(count, sizeof(Class)); - if (count == 1 && ((header_info *)hi)->isLoaded()) { - // exactly one matching class, and its image is loaded - result[(*outCount)++] = (Class)cls; - return result; - } - else if (count > 1) { - // more than one matching class - find those that are loaded - void *clslist[count]; - void *hilist[count]; - classes->getClassesAndHeaders(name, clslist, hilist); - for (uint32_t i = 0; i < count; i++) { - if (((header_info *)hilist[i])->isLoaded()) { - result[(*outCount)++] = (Class)clslist[i]; - } - } - - if (*outCount == 0) { - // found multiple classes with that name, but none are loaded - free(result); - result = nil; - } - return result; - } - - // no match that is loaded - return nil; -} - -namespace objc_opt { -struct objc_headeropt_t { - uint32_t count; - uint32_t entsize; - header_info headers[0]; // sorted by mhdr address - - header_info *get(const headerType *mhdr) - { - assert(entsize == sizeof(header_info)); - - int32_t start = 0; - int32_t end = count; - while (start <= end) { - int32_t i = (start+end)/2; - header_info *hi = headers+i; - if (mhdr == hi->mhdr) return hi; - else if (mhdr < hi->mhdr) end = i-1; - else start = i+1; - } - -#if DEBUG - for (uint32_t i = 0; i < count; i++) { - header_info *hi = headers+i; - if (mhdr == hi->mhdr) { - _objc_fatal("failed to find header %p (%d/%d)", - mhdr, i, count); - } - } -#endif - - return nil; - } -}; -}; - - -header_info *preoptimizedHinfoForHeader(const headerType *mhdr) -{ - objc_headeropt_t *hinfos = opt ? opt->headeropt() : nil; - if (hinfos) return hinfos->get(mhdr); - else return nil; -} - - -void preopt_init(void) -{ - // `opt` not set at compile time in order to detect too-early usage - const char *failure = nil; - opt = &_objc_opt_data; - - if (DisablePreopt) { - // OBJC_DISABLE_PREOPTIMIZATION is set - // If opt->version != VERSION then you continue at your own risk. - failure = "(by OBJC_DISABLE_PREOPTIMIZATION)"; - } - else if (opt->version != objc_opt::VERSION) { - // This shouldn't happen. You probably forgot to edit objc-sel-table.s. - // If dyld really did write the wrong optimization version, - // then we must halt because we don't know what bits dyld twiddled. - _objc_fatal("bad objc preopt version (want %d, got %d)", - objc_opt::VERSION, opt->version); - } - else if (!opt->selopt() || !opt->headeropt()) { - // One of the tables is missing. - failure = "(dyld shared cache is absent or out of date)"; - } -#if SUPPORT_IGNORED_SELECTOR_CONSTANT - else if (UseGC) { - // GC is on, which renames some selectors - // Non-selector optimizations are still valid, but we don't have - // any of those yet - failure = "(GC is on)"; - } -#endif - - if (failure) { - // All preoptimized selector references are invalid. - preoptimized = NO; - opt = nil; - disableSharedCacheOptimizations(); - - if (PrintPreopt) { - _objc_inform("PREOPTIMIZATION: is DISABLED %s", failure); - } - } - else { - // Valid optimization data written by dyld shared cache - preoptimized = YES; - - if (PrintPreopt) { - _objc_inform("PREOPTIMIZATION: is ENABLED " - "(version %d)", opt->version); - } - } -} - - -__END_DECLS - -// SUPPORT_PREOPT -#endif diff --git a/objc/objc-runtime/runtime/objc-os.h b/objc/objc-runtime/runtime/objc-os.h deleted file mode 100644 index 932b04f..0000000 --- a/objc/objc-runtime/runtime/objc-os.h +++ /dev/null @@ -1,1207 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -/*********************************************************************** -* objc-os.h -* OS portability layer. -**********************************************************************/ - -#ifndef _OBJC_OS_H -#define _OBJC_OS_H - -#include <TargetConditionals.h> -#include "objc-config.h" - -#ifdef __LP64__ -# define WORD_SHIFT 3UL -# define WORD_MASK 7UL -# define WORD_BITS 64 -#else -# define WORD_SHIFT 2UL -# define WORD_MASK 3UL -# define WORD_BITS 32 -#endif - -static inline uint32_t word_align(uint32_t x) { - return (x + WORD_MASK) & ~WORD_MASK; -} -static inline size_t word_align(size_t x) { - return (x + WORD_MASK) & ~WORD_MASK; -} - - -// Mix-in for classes that must not be copied. -class nocopy_t { - private: - nocopy_t(const nocopy_t&) = delete; - const nocopy_t& operator=(const nocopy_t&) = delete; - protected: - nocopy_t() { } - ~nocopy_t() { } -}; - - -#if TARGET_OS_MAC - -# ifndef __STDC_LIMIT_MACROS -# define __STDC_LIMIT_MACROS -# endif - -# include <stdio.h> -# include <stdlib.h> -# include <stdint.h> -# include <stdarg.h> -# include <string.h> -# include <ctype.h> -# include <errno.h> -# include <dlfcn.h> -# include <fcntl.h> -# include <assert.h> -# include <limits.h> -# include <syslog.h> -# include <unistd.h> -# include <pthread.h> -# include <crt_externs.h> -# undef check -# include <Availability.h> -# include <TargetConditionals.h> -# include <sys/mman.h> -# include <sys/time.h> -# include <sys/stat.h> -# include <sys/param.h> -# include <mach/mach.h> -# include <mach/vm_param.h> -# include <mach/mach_time.h> -# include <mach-o/dyld.h> -# include <mach-o/ldsyms.h> -# include <mach-o/loader.h> -# include <mach-o/getsect.h> -# include <mach-o/dyld_priv.h> -# include <malloc/malloc.h> -//# include <os/lock_private.h> -# include <libkern/OSAtomic.h> -# include <libkern/OSCacheControl.h> -# include <System/pthread_machdep.h> -# include "objc-probes.h" // generated dtrace probe definitions. - -// Some libc functions call objc_msgSend() -// so we can't use them without deadlocks. -void syslog(int, const char *, ...) UNAVAILABLE_ATTRIBUTE; -void vsyslog(int, const char *, va_list) UNAVAILABLE_ATTRIBUTE; - - -#define ALWAYS_INLINE inline __attribute__((always_inline)) -#define NEVER_INLINE inline __attribute__((noinline)) - - -#include <libkern/OSAtomic.h> - -typedef OSSpinLock os_lock_handoff_s; -#define OS_LOCK_HANDOFF_INIT OS_SPINLOCK_INIT - -ALWAYS_INLINE void os_lock_lock(volatile os_lock_handoff_s *lock) { - return OSSpinLockLock(lock); -} - -ALWAYS_INLINE void os_lock_unlock(volatile os_lock_handoff_s *lock) { - return OSSpinLockUnlock(lock); -} - -ALWAYS_INLINE bool os_lock_trylock(volatile os_lock_handoff_s *lock) { - return OSSpinLockTry(lock); -} - - -static ALWAYS_INLINE uintptr_t -addc(uintptr_t lhs, uintptr_t rhs, uintptr_t carryin, uintptr_t *carryout) -{ - return __builtin_addcl(lhs, rhs, carryin, carryout); -} - -static ALWAYS_INLINE uintptr_t -subc(uintptr_t lhs, uintptr_t rhs, uintptr_t carryin, uintptr_t *carryout) -{ - return __builtin_subcl(lhs, rhs, carryin, carryout); -} - - -#if __arm64__ - -static ALWAYS_INLINE -uintptr_t -LoadExclusive(uintptr_t *src) -{ - uintptr_t result; - asm("ldxr %x0, [%x1]" - : "=r" (result) - : "r" (src), "m" (*src)); - return result; -} - -static ALWAYS_INLINE -bool -StoreExclusive(uintptr_t *dst, uintptr_t oldvalue __unused, uintptr_t value) -{ - uint32_t result; - asm("stxr %w0, %x2, [%x3]" - : "=r" (result), "=m" (*dst) - : "r" (value), "r" (dst)); - return !result; -} - - -static ALWAYS_INLINE -bool -StoreReleaseExclusive(uintptr_t *dst, uintptr_t oldvalue __unused, uintptr_t value) -{ - uint32_t result; - asm("stlxr %w0, %x2, [%x3]" - : "=r" (result), "=m" (*dst) - : "r" (value), "r" (dst)); - return !result; -} - - -#elif __arm__ - -static ALWAYS_INLINE -uintptr_t -LoadExclusive(uintptr_t *src) -{ - return *src; -} - -static ALWAYS_INLINE -bool -StoreExclusive(uintptr_t *dst, uintptr_t oldvalue, uintptr_t value) -{ - return OSAtomicCompareAndSwapPtr((void *)oldvalue, (void *)value, - (void **)dst); -} - -static ALWAYS_INLINE -bool -StoreReleaseExclusive(uintptr_t *dst, uintptr_t oldvalue, uintptr_t value) -{ - return OSAtomicCompareAndSwapPtrBarrier((void *)oldvalue, (void *)value, - (void **)dst); -} - - -#elif __x86_64__ || __i386__ - -static ALWAYS_INLINE -uintptr_t -LoadExclusive(uintptr_t *src) -{ - return *src; -} - -static ALWAYS_INLINE -bool -StoreExclusive(uintptr_t *dst, uintptr_t oldvalue, uintptr_t value) -{ - - return __sync_bool_compare_and_swap((void **)dst, (void *)oldvalue, (void *)value); -} - -static ALWAYS_INLINE -bool -StoreReleaseExclusive(uintptr_t *dst, uintptr_t oldvalue, uintptr_t value) -{ - return StoreExclusive(dst, oldvalue, value); -} - -#else -# error unknown architecture -#endif - - -class spinlock_t { - os_lock_handoff_s mLock; - public: - spinlock_t() : mLock(OS_LOCK_HANDOFF_INIT) { } - - void lock() { os_lock_lock(&mLock); } - void unlock() { os_lock_unlock(&mLock); } - bool trylock() { return os_lock_trylock(&mLock); } - - - // Address-ordered lock discipline for a pair of locks. - - static void lockTwo(spinlock_t *lock1, spinlock_t *lock2) { - if (lock1 > lock2) { - lock1->lock(); - lock2->lock(); - } else { - lock2->lock(); - if (lock2 != lock1) lock1->lock(); - } - } - - static void unlockTwo(spinlock_t *lock1, spinlock_t *lock2) { - lock1->unlock(); - if (lock2 != lock1) lock2->unlock(); - } -}; - - -#if !TARGET_OS_IPHONE -# include <CrashReporterClient.h> -#else - // CrashReporterClient not yet available on iOS - __BEGIN_DECLS - extern const char *CRSetCrashLogMessage(const char *msg); - extern const char *CRGetCrashLogMessage(void); - extern const char *CRSetCrashLogMessage2(const char *msg); - __END_DECLS -#endif - -# if __cplusplus -# include <vector> -# include <algorithm> -# include <functional> - using namespace std; -# endif - -# define PRIVATE_EXTERN __attribute__((visibility("hidden"))) -# undef __private_extern__ -# define __private_extern__ use_PRIVATE_EXTERN_instead -# undef private_extern -# define private_extern use_PRIVATE_EXTERN_instead - -/* Use this for functions that are intended to be breakpoint hooks. - If you do not, the compiler may optimize them away. - BREAKPOINT_FUNCTION( void stop_on_error(void) ); */ -# define BREAKPOINT_FUNCTION(prototype) \ - OBJC_EXTERN __attribute__((noinline, used, visibility("hidden"))) \ - prototype { asm(""); } - -#elif TARGET_OS_WIN32 - -# define WINVER 0x0501 // target Windows XP and later -# define _WIN32_WINNT 0x0501 // target Windows XP and later -# define WIN32_LEAN_AND_MEAN - // hack: windef.h typedefs BOOL as int -# define BOOL WINBOOL -# include <windows.h> -# undef BOOL - -# include <stdio.h> -# include <stdlib.h> -# include <stdint.h> -# include <stdarg.h> -# include <string.h> -# include <assert.h> -# include <malloc.h> -# include <Availability.h> - -# if __cplusplus -# include <vector> -# include <algorithm> -# include <functional> - using namespace std; -# define __BEGIN_DECLS extern "C" { -# define __END_DECLS } -# else -# define __BEGIN_DECLS /*empty*/ -# define __END_DECLS /*empty*/ -# endif - -# define PRIVATE_EXTERN -# define __attribute__(x) -# define inline __inline - -/* Use this for functions that are intended to be breakpoint hooks. - If you do not, the compiler may optimize them away. - BREAKPOINT_FUNCTION( void MyBreakpointFunction(void) ); */ -# define BREAKPOINT_FUNCTION(prototype) \ - __declspec(noinline) prototype { __asm { } } - -/* stub out dtrace probes */ -# define OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW() do {} while(0) -# define OBJC_RUNTIME_OBJC_EXCEPTION_THROW(arg0) do {} while(0) - -#else -# error unknown OS -#endif - - -#include <objc/objc.h> -#include <objc/objc-api.h> - -extern void _objc_fatal(const char *fmt, ...) __attribute__((noreturn, format (printf, 1, 2))); - -#define INIT_ONCE_PTR(var, create, delete) \ - do { \ - if (var) break; \ - __typeof__(var) v = create; \ - while (!var) { \ - if (OSAtomicCompareAndSwapPtrBarrier(0, (void*)v, (void**)&var)){ \ - goto done; \ - } \ - } \ - delete; \ - done:; \ - } while (0) - -#define INIT_ONCE_32(var, create, delete) \ - do { \ - if (var) break; \ - typeof(var) v = create; \ - while (!var) { \ - if (OSAtomicCompareAndSwap32Barrier(0, v, (volatile int32_t *)&var)) { \ - goto done; \ - } \ - } \ - delete; \ - done:; \ - } while (0) - - -// Thread keys reserved by libc for our use. -#if defined(__PTK_FRAMEWORK_OBJC_KEY0) -# define SUPPORT_DIRECT_THREAD_KEYS 1 -# define TLS_DIRECT_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY0) -# define SYNC_DATA_DIRECT_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY1) -# define SYNC_COUNT_DIRECT_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY2) -# define AUTORELEASE_POOL_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY3) -# if SUPPORT_RETURN_AUTORELEASE -# define RETURN_DISPOSITION_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY4) -# endif -# if SUPPORT_QOS_HACK -# define QOS_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY5) -# endif -#else -# define SUPPORT_DIRECT_THREAD_KEYS 0 -#endif - - -#if TARGET_OS_WIN32 - -// Compiler compatibility - -// OS compatibility - -#define strdup _strdup - -#define issetugid() 0 - -#define MIN(x, y) ((x) < (y) ? (x) : (y)) - -static __inline void bcopy(const void *src, void *dst, size_t size) { memcpy(dst, src, size); } -static __inline void bzero(void *dst, size_t size) { memset(dst, 0, size); } - -int asprintf(char **dstp, const char *format, ...); - -typedef void * malloc_zone_t; - -static __inline malloc_zone_t malloc_default_zone(void) { return (malloc_zone_t)-1; } -static __inline void *malloc_zone_malloc(malloc_zone_t z, size_t size) { return malloc(size); } -static __inline void *malloc_zone_calloc(malloc_zone_t z, size_t size, size_t count) { return calloc(size, count); } -static __inline void *malloc_zone_realloc(malloc_zone_t z, void *p, size_t size) { return realloc(p, size); } -static __inline void malloc_zone_free(malloc_zone_t z, void *p) { free(p); } -static __inline malloc_zone_t malloc_zone_from_ptr(const void *p) { return (malloc_zone_t)-1; } -static __inline size_t malloc_size(const void *p) { return _msize((void*)p); /* fixme invalid pointer check? */ } - - -// OSAtomic - -static __inline BOOL OSAtomicCompareAndSwapLong(long oldl, long newl, long volatile *dst) -{ - // fixme barrier is overkill - long original = InterlockedCompareExchange(dst, newl, oldl); - return (original == oldl); -} - -static __inline BOOL OSAtomicCompareAndSwapPtrBarrier(void *oldp, void *newp, void * volatile *dst) -{ - void *original = InterlockedCompareExchangePointer(dst, newp, oldp); - return (original == oldp); -} - -static __inline BOOL OSAtomicCompareAndSwap32Barrier(int32_t oldl, int32_t newl, int32_t volatile *dst) -{ - long original = InterlockedCompareExchange((volatile long *)dst, newl, oldl); - return (original == oldl); -} - -static __inline int32_t OSAtomicDecrement32Barrier(volatile int32_t *dst) -{ - return InterlockedDecrement((volatile long *)dst); -} - -static __inline int32_t OSAtomicIncrement32Barrier(volatile int32_t *dst) -{ - return InterlockedIncrement((volatile long *)dst); -} - - -// Internal data types - -typedef DWORD objc_thread_t; // thread ID -static __inline int thread_equal(objc_thread_t t1, objc_thread_t t2) { - return t1 == t2; -} -static __inline objc_thread_t thread_self(void) { - return GetCurrentThreadId(); -} - -typedef struct { - DWORD key; - void (*dtor)(void *); -} tls_key_t; -static __inline tls_key_t tls_create(void (*dtor)(void*)) { - // fixme need dtor registry for DllMain to call on thread detach - tls_key_t k; - k.key = TlsAlloc(); - k.dtor = dtor; - return k; -} -static __inline void *tls_get(tls_key_t k) { - return TlsGetValue(k.key); -} -static __inline void tls_set(tls_key_t k, void *value) { - TlsSetValue(k.key, value); -} - -typedef struct { - CRITICAL_SECTION *lock; -} mutex_t; -#define MUTEX_INITIALIZER {0}; -extern void mutex_init(mutex_t *m); -static __inline int _mutex_lock_nodebug(mutex_t *m) { - // fixme error check - if (!m->lock) { - mutex_init(m); - } - EnterCriticalSection(m->lock); - return 0; -} -static __inline bool _mutex_try_lock_nodebug(mutex_t *m) { - // fixme error check - if (!m->lock) { - mutex_init(m); - } - return TryEnterCriticalSection(m->lock); -} -static __inline int _mutex_unlock_nodebug(mutex_t *m) { - // fixme error check - LeaveCriticalSection(m->lock); - return 0; -} - - -typedef mutex_t spinlock_t; -#define spinlock_lock(l) mutex_lock(l) -#define spinlock_unlock(l) mutex_unlock(l) -#define SPINLOCK_INITIALIZER MUTEX_INITIALIZER - - -typedef struct { - HANDLE mutex; -} recursive_mutex_t; -#define RECURSIVE_MUTEX_INITIALIZER {0}; -#define RECURSIVE_MUTEX_NOT_LOCKED 1 -extern void recursive_mutex_init(recursive_mutex_t *m); -static __inline int _recursive_mutex_lock_nodebug(recursive_mutex_t *m) { - assert(m->mutex); - return WaitForSingleObject(m->mutex, INFINITE); -} -static __inline bool _recursive_mutex_try_lock_nodebug(recursive_mutex_t *m) { - assert(m->mutex); - return (WAIT_OBJECT_0 == WaitForSingleObject(m->mutex, 0)); -} -static __inline int _recursive_mutex_unlock_nodebug(recursive_mutex_t *m) { - assert(m->mutex); - return ReleaseMutex(m->mutex) ? 0 : RECURSIVE_MUTEX_NOT_LOCKED; -} - - -/* -typedef HANDLE mutex_t; -static inline void mutex_init(HANDLE *m) { *m = CreateMutex(NULL, FALSE, NULL); } -static inline void _mutex_lock(mutex_t *m) { WaitForSingleObject(*m, INFINITE); } -static inline bool mutex_try_lock(mutex_t *m) { return WaitForSingleObject(*m, 0) == WAIT_OBJECT_0; } -static inline void _mutex_unlock(mutex_t *m) { ReleaseMutex(*m); } -*/ - -// based on http://www.cs.wustl.edu/~schmidt/win32-cv-1.html -// Vista-only CONDITION_VARIABLE would be better -typedef struct { - HANDLE mutex; - HANDLE waiters; // semaphore for those in cond_wait() - HANDLE waitersDone; // auto-reset event after everyone gets a broadcast - CRITICAL_SECTION waitCountLock; // guards waitCount and didBroadcast - unsigned int waitCount; - int didBroadcast; -} monitor_t; -#define MONITOR_INITIALIZER { 0 } -#define MONITOR_NOT_ENTERED 1 -extern int monitor_init(monitor_t *c); - -static inline int _monitor_enter_nodebug(monitor_t *c) { - if (!c->mutex) { - int err = monitor_init(c); - if (err) return err; - } - return WaitForSingleObject(c->mutex, INFINITE); -} -static inline int _monitor_leave_nodebug(monitor_t *c) { - if (!ReleaseMutex(c->mutex)) return MONITOR_NOT_ENTERED; - else return 0; -} -static inline int _monitor_wait_nodebug(monitor_t *c) { - int last; - EnterCriticalSection(&c->waitCountLock); - c->waitCount++; - LeaveCriticalSection(&c->waitCountLock); - - SignalObjectAndWait(c->mutex, c->waiters, INFINITE, FALSE); - - EnterCriticalSection(&c->waitCountLock); - c->waitCount--; - last = c->didBroadcast && c->waitCount == 0; - LeaveCriticalSection(&c->waitCountLock); - - if (last) { - // tell broadcaster that all waiters have awoken - SignalObjectAndWait(c->waitersDone, c->mutex, INFINITE, FALSE); - } else { - WaitForSingleObject(c->mutex, INFINITE); - } - - // fixme error checking - return 0; -} -static inline int monitor_notify(monitor_t *c) { - int haveWaiters; - - EnterCriticalSection(&c->waitCountLock); - haveWaiters = c->waitCount > 0; - LeaveCriticalSection(&c->waitCountLock); - - if (haveWaiters) { - ReleaseSemaphore(c->waiters, 1, 0); - } - - // fixme error checking - return 0; -} -static inline int monitor_notifyAll(monitor_t *c) { - EnterCriticalSection(&c->waitCountLock); - if (c->waitCount == 0) { - LeaveCriticalSection(&c->waitCountLock); - return 0; - } - c->didBroadcast = 1; - ReleaseSemaphore(c->waiters, c->waitCount, 0); - LeaveCriticalSection(&c->waitCountLock); - - // fairness: wait for everyone to move from waiters to mutex - WaitForSingleObject(c->waitersDone, INFINITE); - // not under waitCountLock, but still under mutex - c->didBroadcast = 0; - - // fixme error checking - return 0; -} - - -// fixme no rwlock yet - - -typedef IMAGE_DOS_HEADER headerType; -// fixme YES bundle? NO bundle? sometimes? -#define headerIsBundle(hi) YES -OBJC_EXTERN IMAGE_DOS_HEADER __ImageBase; -#define libobjc_header ((headerType *)&__ImageBase) - -// Prototypes - - -#elif TARGET_OS_MAC - - -// OS headers -#include <mach-o/loader.h> -#ifndef __LP64__ -# define SEGMENT_CMD LC_SEGMENT -#else -# define SEGMENT_CMD LC_SEGMENT_64 -#endif - -#ifndef VM_MEMORY_OBJC_DISPATCHERS -# define VM_MEMORY_OBJC_DISPATCHERS 0 -#endif - - -// Compiler compatibility - -// OS compatibility - -static inline uint64_t nanoseconds() { - return mach_absolute_time(); -} - -// Internal data types - -typedef pthread_t objc_thread_t; - -static __inline int thread_equal(objc_thread_t t1, objc_thread_t t2) { - return pthread_equal(t1, t2); -} -static __inline objc_thread_t thread_self(void) { - return pthread_self(); -} - - -typedef pthread_key_t tls_key_t; - -static inline tls_key_t tls_create(void (*dtor)(void*)) { - tls_key_t k; - pthread_key_create(&k, dtor); - return k; -} -static inline void *tls_get(tls_key_t k) { - return pthread_getspecific(k); -} -static inline void tls_set(tls_key_t k, void *value) { - pthread_setspecific(k, value); -} - -#if SUPPORT_DIRECT_THREAD_KEYS - -#if DEBUG -static bool is_valid_direct_key(tls_key_t k) { - return ( k == SYNC_DATA_DIRECT_KEY - || k == SYNC_COUNT_DIRECT_KEY - || k == AUTORELEASE_POOL_KEY -# if SUPPORT_RETURN_AUTORELEASE - || k == RETURN_DISPOSITION_KEY -# endif -# if SUPPORT_QOS_HACK - || k == QOS_KEY -# endif - ); -} -#endif - -#if __arm__ - -// rdar://9162780 _pthread_get/setspecific_direct are inefficient -// copied from libdispatch - -__attribute__((const)) -static ALWAYS_INLINE void** -tls_base(void) -{ - uintptr_t p; -#if defined(__arm__) && defined(_ARM_ARCH_6) - __asm__("mrc p15, 0, %[p], c13, c0, 3" : [p] "=&r" (p)); - return (void**)(p & ~0x3ul); -#else -#error tls_base not implemented -#endif -} - - -static ALWAYS_INLINE void -tls_set_direct(void **tsdb, tls_key_t k, void *v) -{ - assert(is_valid_direct_key(k)); - - tsdb[k] = v; -} -#define tls_set_direct(k, v) \ - tls_set_direct(tls_base(), (k), (v)) - - -static ALWAYS_INLINE void * -tls_get_direct(void **tsdb, tls_key_t k) -{ - assert(is_valid_direct_key(k)); - - return tsdb[k]; -} -#define tls_get_direct(k) \ - tls_get_direct(tls_base(), (k)) - -// arm -#else -// not arm - -static inline void *tls_get_direct(tls_key_t k) -{ - assert(is_valid_direct_key(k)); - - if (_pthread_has_direct_tsd()) { - return _pthread_getspecific_direct(k); - } else { - return pthread_getspecific(k); - } -} -static inline void tls_set_direct(tls_key_t k, void *value) -{ - assert(is_valid_direct_key(k)); - - if (_pthread_has_direct_tsd()) { - _pthread_setspecific_direct(k, value); - } else { - pthread_setspecific(k, value); - } -} - -// not arm -#endif - -// SUPPORT_DIRECT_THREAD_KEYS -#endif - - -static inline pthread_t pthread_self_direct() -{ - return (pthread_t) - _pthread_getspecific_direct(_PTHREAD_TSD_SLOT_PTHREAD_SELF); -} - -static inline mach_port_t mach_thread_self_direct() -{ - return (mach_port_t)(uintptr_t) - _pthread_getspecific_direct(_PTHREAD_TSD_SLOT_MACH_THREAD_SELF); -} - -typedef unsigned long pthread_priority_t; -#include <pthread/tsd_private.h> - -#if SUPPORT_QOS_HACK - -#include <pthread/qos_private.h> - -static inline pthread_priority_t pthread_self_priority_direct() -{ - pthread_priority_t pri = (pthread_priority_t) - _pthread_getspecific_direct(_PTHREAD_TSD_SLOT_PTHREAD_QOS_CLASS); - return pri & ~_PTHREAD_PRIORITY_FLAGS_MASK; -} -#endif - - -template <bool Debug> class mutex_tt; -template <bool Debug> class monitor_tt; -template <bool Debug> class rwlock_tt; -template <bool Debug> class recursive_mutex_tt; - -#include "objc-lockdebug.h" - -template <bool Debug> -class mutex_tt : nocopy_t { - pthread_mutex_t mLock; - - public: - mutex_tt() : mLock((pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER) { } - - void lock() - { - lockdebug_mutex_lock(this); - - int err = pthread_mutex_lock(&mLock); - if (err) _objc_fatal("pthread_mutex_lock failed (%d)", err); - } - - bool tryLock() - { - int err = pthread_mutex_trylock(&mLock); - if (err == 0) { - lockdebug_mutex_try_lock_success(this); - return true; - } else if (err == EBUSY) { - return false; - } else { - _objc_fatal("pthread_mutex_trylock failed (%d)", err); - } - } - - void unlock() - { - lockdebug_mutex_unlock(this); - - int err = pthread_mutex_unlock(&mLock); - if (err) _objc_fatal("pthread_mutex_unlock failed (%d)", err); - } - - - void assertLocked() { - lockdebug_mutex_assert_locked(this); - } - - void assertUnlocked() { - lockdebug_mutex_assert_unlocked(this); - } -}; - -using mutex_t = mutex_tt<DEBUG>; - - -template <bool Debug> -class recursive_mutex_tt : nocopy_t { - pthread_mutex_t mLock; - - public: - recursive_mutex_tt() : mLock((pthread_mutex_t)PTHREAD_RECURSIVE_MUTEX_INITIALIZER) { } - - void lock() - { - lockdebug_recursive_mutex_lock(this); - - int err = pthread_mutex_lock(&mLock); - if (err) _objc_fatal("pthread_mutex_lock failed (%d)", err); - } - - bool tryLock() - { - int err = pthread_mutex_trylock(&mLock); - if (err == 0) { - lockdebug_recursive_mutex_lock(this); - return true; - } else if (err == EBUSY) { - return false; - } else { - _objc_fatal("pthread_mutex_trylock failed (%d)", err); - } - } - - - void unlock() - { - lockdebug_recursive_mutex_unlock(this); - - int err = pthread_mutex_unlock(&mLock); - if (err) _objc_fatal("pthread_mutex_unlock failed (%d)", err); - } - - bool tryUnlock() - { - int err = pthread_mutex_unlock(&mLock); - if (err == 0) { - lockdebug_recursive_mutex_unlock(this); - return true; - } else if (err == EPERM) { - return false; - } else { - _objc_fatal("pthread_mutex_unlock failed (%d)", err); - } - } - - - void assertLocked() { - lockdebug_recursive_mutex_assert_locked(this); - } - - void assertUnlocked() { - lockdebug_recursive_mutex_assert_unlocked(this); - } -}; - -using recursive_mutex_t = recursive_mutex_tt<DEBUG>; - - -template <bool Debug> -class monitor_tt { - pthread_mutex_t mutex; - pthread_cond_t cond; - - public: - monitor_tt() - : mutex((pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER), cond((pthread_cond_t)PTHREAD_COND_INITIALIZER) { } - - void enter() - { - lockdebug_monitor_enter(this); - - int err = pthread_mutex_lock(&mutex); - if (err) _objc_fatal("pthread_mutex_lock failed (%d)", err); - } - - void leave() - { - lockdebug_monitor_leave(this); - - int err = pthread_mutex_unlock(&mutex); - if (err) _objc_fatal("pthread_mutex_unlock failed (%d)", err); - } - - void wait() - { - lockdebug_monitor_wait(this); - - int err = pthread_cond_wait(&cond, &mutex); - if (err) _objc_fatal("pthread_cond_wait failed (%d)", err); - } - - void notify() - { - int err = pthread_cond_signal(&cond); - if (err) _objc_fatal("pthread_cond_signal failed (%d)", err); - } - - void notifyAll() - { - int err = pthread_cond_broadcast(&cond); - if (err) _objc_fatal("pthread_cond_broadcast failed (%d)", err); - } - - void assertLocked() - { - lockdebug_monitor_assert_locked(this); - } - - void assertUnlocked() - { - lockdebug_monitor_assert_unlocked(this); - } -}; - -using monitor_t = monitor_tt<DEBUG>; - - -// semaphore_create formatted for INIT_ONCE use -static inline semaphore_t create_semaphore(void) -{ - semaphore_t sem; - kern_return_t k; - k = semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, 0); - if (k) _objc_fatal("semaphore_create failed (0x%x)", k); - return sem; -} - - -#if SUPPORT_QOS_HACK -// Override QOS class to avoid priority inversion in rwlocks -// <rdar://17697862> do a qos override before taking rw lock in objc - -#include <pthread/workqueue_private.h> -extern pthread_priority_t BackgroundPriority; -extern pthread_priority_t MainPriority; - -static inline void qosStartOverride() -{ - uintptr_t overrideRefCount = (uintptr_t)tls_get_direct(QOS_KEY); - if (overrideRefCount > 0) { - // If there is a qos override, increment the refcount and continue - tls_set_direct(QOS_KEY, (void *)(overrideRefCount + 1)); - } - else { - pthread_priority_t currentPriority = pthread_self_priority_direct(); - // Check if override is needed. Only override if we are background qos - if (currentPriority != 0 && currentPriority <= BackgroundPriority) { - int res __unused = _pthread_override_qos_class_start_direct(mach_thread_self_direct(), MainPriority); - assert(res == 0); - // Once we override, we set the reference count in the tsd - // to know when to end the override - tls_set_direct(QOS_KEY, (void *)1); - } - } -} - -static inline void qosEndOverride() -{ - uintptr_t overrideRefCount = (uintptr_t)tls_get_direct(QOS_KEY); - if (overrideRefCount == 0) return; - - if (overrideRefCount == 1) { - // end the override - int res __unused = _pthread_override_qos_class_end_direct(mach_thread_self_direct()); - assert(res == 0); - } - - // decrement refcount - tls_set_direct(QOS_KEY, (void *)(overrideRefCount - 1)); -} - -// SUPPORT_QOS_HACK -#else -// not SUPPORT_QOS_HACK - -static inline void qosStartOverride() { } -static inline void qosEndOverride() { } - -// not SUPPORT_QOS_HACK -#endif - - -template <bool Debug> -class rwlock_tt : nocopy_t { - pthread_rwlock_t mLock = PTHREAD_RWLOCK_INITIALIZER; - - public: - - rwlock_tt() { - } - - void read() - { - lockdebug_rwlock_read(this); - - qosStartOverride(); - int err = pthread_rwlock_rdlock(&mLock); - if (err) _objc_fatal("pthread_rwlock_rdlock failed (%d)", err); - } - - void unlockRead() - { - lockdebug_rwlock_unlock_read(this); - - int err = pthread_rwlock_unlock(&mLock); - if (err) _objc_fatal("pthread_rwlock_unlock failed (%d)", err); - qosEndOverride(); - } - - bool tryRead() - { - qosStartOverride(); - int err = pthread_rwlock_tryrdlock(&mLock); - if (err == 0) { - lockdebug_rwlock_try_read_success(this); - return true; - } else if (err == EBUSY) { - qosEndOverride(); - return false; - } else { - _objc_fatal("pthread_rwlock_tryrdlock failed (%d)", err); - } - } - - void write() - { - lockdebug_rwlock_write(this); - - qosStartOverride(); - int err = pthread_rwlock_wrlock(&mLock); - if (err) _objc_fatal("pthread_rwlock_wrlock failed (%d)", err); - } - - void unlockWrite() - { - lockdebug_rwlock_unlock_write(this); - - int err = pthread_rwlock_unlock(&mLock); - if (err) _objc_fatal("pthread_rwlock_unlock failed (%d)", err); - qosEndOverride(); - } - - bool tryWrite() - { - qosStartOverride(); - int err = pthread_rwlock_trywrlock(&mLock); - if (err == 0) { - lockdebug_rwlock_try_write_success(this); - return true; - } else if (err == EBUSY) { - qosEndOverride(); - return false; - } else { - _objc_fatal("pthread_rwlock_trywrlock failed (%d)", err); - } - } - - - void assertReading() { - lockdebug_rwlock_assert_reading(this); - } - - void assertWriting() { - lockdebug_rwlock_assert_writing(this); - } - - void assertLocked() { - lockdebug_rwlock_assert_locked(this); - } - - void assertUnlocked() { - lockdebug_rwlock_assert_unlocked(this); - } -}; - -using rwlock_t = rwlock_tt<DEBUG>; - - -#ifndef __LP64__ -typedef struct mach_header headerType; -typedef struct segment_command segmentType; -typedef struct section sectionType; -#else -typedef struct mach_header_64 headerType; -typedef struct segment_command_64 segmentType; -typedef struct section_64 sectionType; -#endif -#define headerIsBundle(hi) (hi->mhdr->filetype == MH_BUNDLE) -#define libobjc_header ((headerType *)&_mh_dylib_header) - -// Prototypes - -/* Secure /tmp usage */ -extern int secure_open(const char *filename, int flags, uid_t euid); - - -#else - - -#error unknown OS - - -#endif - - -static inline void * -memdup(const void *mem, size_t len) -{ - void *dup = malloc(len); - memcpy(dup, mem, len); - return dup; -} - -// unsigned strdup -static inline uint8_t * -ustrdup(const uint8_t *str) -{ - return (uint8_t *)strdup((char *)str); -} - -// nil-checking strdup -static inline uint8_t * -strdupMaybeNil(const uint8_t *str) -{ - if (!str) return nil; - return (uint8_t *)strdup((char *)str); -} - -// nil-checking unsigned strdup -static inline uint8_t * -ustrdupMaybeNil(const uint8_t *str) -{ - if (!str) return nil; - return (uint8_t *)strdup((char *)str); -} - -#endif diff --git a/objc/objc-runtime/runtime/objc-os.mm b/objc/objc-runtime/runtime/objc-os.mm deleted file mode 100644 index 6a11fa6..0000000 --- a/objc/objc-runtime/runtime/objc-os.mm +++ /dev/null @@ -1,1001 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -/*********************************************************************** -* objc-os.m -* OS portability layer. -**********************************************************************/ - -#include "objc-private.h" -#include "objc-loadmethod.h" - -#if TARGET_OS_WIN32 - -#include "objc-runtime-old.h" -#include "objcrt.h" - -int monitor_init(monitor_t *c) -{ - // fixme error checking - HANDLE mutex = CreateMutex(NULL, TRUE, NULL); - while (!c->mutex) { - // fixme memory barrier here? - if (0 == InterlockedCompareExchangePointer(&c->mutex, mutex, 0)) { - // we win - finish construction - c->waiters = CreateSemaphore(NULL, 0, 0x7fffffff, NULL); - c->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL); - InitializeCriticalSection(&c->waitCountLock); - c->waitCount = 0; - c->didBroadcast = 0; - ReleaseMutex(c->mutex); - return 0; - } - } - - // someone else allocated the mutex and constructed the monitor - ReleaseMutex(mutex); - CloseHandle(mutex); - return 0; -} - -void mutex_init(mutex_t *m) -{ - while (!m->lock) { - CRITICAL_SECTION *newlock = malloc(sizeof(CRITICAL_SECTION)); - InitializeCriticalSection(newlock); - // fixme memory barrier here? - if (0 == InterlockedCompareExchangePointer(&m->lock, newlock, 0)) { - return; - } - // someone else installed their lock first - DeleteCriticalSection(newlock); - free(newlock); - } -} - - -void recursive_mutex_init(recursive_mutex_t *m) -{ - // fixme error checking - HANDLE newmutex = CreateMutex(NULL, FALSE, NULL); - while (!m->mutex) { - // fixme memory barrier here? - if (0 == InterlockedCompareExchangePointer(&m->mutex, newmutex, 0)) { - // we win - return; - } - } - - // someone else installed their lock first - CloseHandle(newmutex); -} - - -WINBOOL APIENTRY DllMain( HMODULE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - switch (ul_reason_for_call) { - case DLL_PROCESS_ATTACH: - environ_init(); - tls_init(); - lock_init(); - sel_init(NO, 3500); // old selector heuristic - exception_init(); - break; - - case DLL_THREAD_ATTACH: - break; - - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; -} - -OBJC_EXPORT void *_objc_init_image(HMODULE image, const objc_sections *sects) -{ - header_info *hi = malloc(sizeof(header_info)); - size_t count, i; - - hi->mhdr = (const headerType *)image; - hi->info = sects->iiStart; - hi->allClassesRealized = NO; - hi->modules = sects->modStart ? (Module *)((void **)sects->modStart+1) : 0; - hi->moduleCount = (Module *)sects->modEnd - hi->modules; - hi->protocols = sects->protoStart ? (struct old_protocol **)((void **)sects->protoStart+1) : 0; - hi->protocolCount = (struct old_protocol **)sects->protoEnd - hi->protocols; - hi->imageinfo = NULL; - hi->imageinfoBytes = 0; - // hi->imageinfo = sects->iiStart ? (uint8_t *)((void **)sects->iiStart+1) : 0;; -// hi->imageinfoBytes = (uint8_t *)sects->iiEnd - hi->imageinfo; - hi->selrefs = sects->selrefsStart ? (SEL *)((void **)sects->selrefsStart+1) : 0; - hi->selrefCount = (SEL *)sects->selrefsEnd - hi->selrefs; - hi->clsrefs = sects->clsrefsStart ? (Class *)((void **)sects->clsrefsStart+1) : 0; - hi->clsrefCount = (Class *)sects->clsrefsEnd - hi->clsrefs; - - count = 0; - for (i = 0; i < hi->moduleCount; i++) { - if (hi->modules[i]) count++; - } - hi->mod_count = 0; - hi->mod_ptr = 0; - if (count > 0) { - hi->mod_ptr = malloc(count * sizeof(struct objc_module)); - for (i = 0; i < hi->moduleCount; i++) { - if (hi->modules[i]) memcpy(&hi->mod_ptr[hi->mod_count++], hi->modules[i], sizeof(struct objc_module)); - } - } - - hi->moduleName = malloc(MAX_PATH * sizeof(TCHAR)); - GetModuleFileName((HMODULE)(hi->mhdr), hi->moduleName, MAX_PATH * sizeof(TCHAR)); - - appendHeader(hi); - - if (PrintImages) { - _objc_inform("IMAGES: loading image for %s%s%s\n", - hi->fname, - headerIsBundle(hi) ? " (bundle)" : "", - _objcHeaderIsReplacement(hi) ? " (replacement)":""); - } - - _read_images(&hi, 1); - - return hi; -} - -OBJC_EXPORT void _objc_load_image(HMODULE image, header_info *hinfo) -{ - prepare_load_methods(hinfo); - call_load_methods(); -} - -OBJC_EXPORT void _objc_unload_image(HMODULE image, header_info *hinfo) -{ - _objc_fatal("image unload not supported"); -} - - -bool crashlog_header_name(header_info *hi) -{ - return true; -} - - -// TARGET_OS_WIN32 -#elif TARGET_OS_MAC - -#include "objc-file-old.h" -#include "objc-file.h" - - -/*********************************************************************** -* bad_magic. -* Return YES if the header has invalid Mach-o magic. -**********************************************************************/ -bool bad_magic(const headerType *mhdr) -{ - return (mhdr->magic != MH_MAGIC && mhdr->magic != MH_MAGIC_64 && - mhdr->magic != MH_CIGAM && mhdr->magic != MH_CIGAM_64); -} - - -static header_info * addHeader(const headerType *mhdr) -{ - header_info *hi; - - if (bad_magic(mhdr)) return NULL; - -#if __OBJC2__ - // Look for hinfo from the dyld shared cache. - hi = preoptimizedHinfoForHeader(mhdr); - if (hi) { - // Found an hinfo in the dyld shared cache. - - // Weed out duplicates. - if (hi->loaded) { - return NULL; - } - - // Initialize fields not set by the shared cache - // hi->next is set by appendHeader - hi->fname = dyld_image_path_containing_address(hi->mhdr); - hi->loaded = true; - hi->inSharedCache = true; - - if (PrintPreopt) { - _objc_inform("PREOPTIMIZATION: honoring preoptimized header info at %p for %s", hi, hi->fname); - } - -# if DEBUG - // Verify image_info - size_t info_size = 0; - const objc_image_info *image_info = _getObjcImageInfo(mhdr,&info_size); - assert(image_info == hi->info); -# endif - } - else -#endif - { - // Didn't find an hinfo in the dyld shared cache. - - // Weed out duplicates - for (hi = FirstHeader; hi; hi = hi->next) { - if (mhdr == hi->mhdr) return NULL; - } - - // Locate the __OBJC segment - size_t info_size = 0; - unsigned long seg_size; - const objc_image_info *image_info = _getObjcImageInfo(mhdr,&info_size); - const uint8_t *objc_segment = getsegmentdata(mhdr,SEG_OBJC,&seg_size); - if (!objc_segment && !image_info) return NULL; - - // Allocate a header_info entry. - hi = (header_info *)calloc(sizeof(header_info), 1); - - // Set up the new header_info entry. - hi->mhdr = mhdr; -#if !__OBJC2__ - // mhdr must already be set - hi->mod_count = 0; - hi->mod_ptr = _getObjcModules(hi, &hi->mod_count); -#endif - hi->info = image_info; - hi->fname = dyld_image_path_containing_address(hi->mhdr); - hi->loaded = true; - hi->inSharedCache = false; - hi->allClassesRealized = NO; - } - - // dylibs are not allowed to unload - // ...except those with image_info and nothing else (5359412) - if (hi->mhdr->filetype == MH_DYLIB && _hasObjcContents(hi)) { - dlopen(hi->fname, RTLD_NOLOAD); - } - - appendHeader(hi); - - return hi; -} - - -#if !SUPPORT_GC - -const char *_gcForHInfo(const header_info *hinfo) -{ - return ""; -} -const char *_gcForHInfo2(const header_info *hinfo) -{ - return ""; -} - -#else - -/*********************************************************************** -* _gcForHInfo. -**********************************************************************/ -const char *_gcForHInfo(const header_info *hinfo) -{ - if (_objcHeaderRequiresGC(hinfo)) { - return "requires GC"; - } else if (_objcHeaderSupportsGC(hinfo)) { - return "supports GC"; - } else { - return "does not support GC"; - } -} -const char *_gcForHInfo2(const header_info *hinfo) -{ - if (_objcHeaderRequiresGC(hinfo)) { - return "(requires GC)"; - } else if (_objcHeaderSupportsGC(hinfo)) { - return "(supports GC)"; - } - return ""; -} - - -/*********************************************************************** -* linksToLibrary -* Returns true if the image links directly to a dylib whose install name -* is exactly the given name. -**********************************************************************/ -bool -linksToLibrary(const header_info *hi, const char *name) -{ - const struct dylib_command *cmd; - unsigned long i; - - cmd = (const struct dylib_command *) (hi->mhdr + 1); - for (i = 0; i < hi->mhdr->ncmds; i++) { - if (cmd->cmd == LC_LOAD_DYLIB || cmd->cmd == LC_LOAD_UPWARD_DYLIB || - cmd->cmd == LC_LOAD_WEAK_DYLIB || cmd->cmd == LC_REEXPORT_DYLIB) - { - const char *dylib = cmd->dylib.name.offset + (const char *)cmd; - if (0 == strcmp(dylib, name)) return true; - } - cmd = (const struct dylib_command *)((char *)cmd + cmd->cmdsize); - } - - return false; -} - - -/*********************************************************************** -* check_gc -* Check whether the executable supports or requires GC, and make sure -* all already-loaded libraries support the executable's GC mode. -* Returns TRUE if the executable wants GC on. -**********************************************************************/ -static void check_wants_gc(bool *appWantsGC) -{ - const header_info *hi; - - // Environment variables can override the following. - if (DisableGC) { - _objc_inform_on_crash("GC: forcing GC OFF because OBJC_DISABLE_GC is set"); - *appWantsGC = NO; - } - else { - // Find the executable and check its GC bits. - // If the executable cannot be found, default to NO. - // (The executable will not be found if the executable contains - // no Objective-C code.) - *appWantsGC = NO; - for (hi = FirstHeader; hi != NULL; hi = hi->next) { - if (hi->mhdr->filetype == MH_EXECUTE) { - *appWantsGC = _objcHeaderSupportsGC(hi); - - if (PrintGC) { - _objc_inform("GC: executable '%s' %s", - hi->fname, _gcForHInfo(hi)); - } - - if (*appWantsGC) { - // Exception: AppleScriptObjC apps run without GC in 10.9+ - // 1. executable defines no classes - // 2. executable references NSBundle only - // 3. executable links to AppleScriptObjC.framework - size_t classcount = 0; - size_t refcount = 0; -#if __OBJC2__ - _getObjc2ClassList(hi, &classcount); - _getObjc2ClassRefs(hi, &refcount); -#else - if (hi->mod_count == 0 || (hi->mod_count == 1 && !hi->mod_ptr[0].symtab)) classcount = 0; - else classcount = 1; - _getObjcClassRefs(hi, &refcount); -#endif - if (classcount == 0 && refcount == 1 && - linksToLibrary(hi, "/System/Library/Frameworks" - "/AppleScriptObjC.framework/Versions/A" - "/AppleScriptObjC")) - { - *appWantsGC = NO; - if (PrintGC) { - _objc_inform("GC: forcing GC OFF because this is " - "a trivial AppleScriptObjC app"); - } - } - } - } - } - } -} - - -/*********************************************************************** -* verify_gc_readiness -* if we want gc, verify that every header describes files compiled -* and presumably ready for gc. -************************************************************************/ -static void verify_gc_readiness(bool wantsGC, - header_info **hList, uint32_t hCount) -{ - bool busted = NO; - uint32_t i; - - // Find the libraries and check their GC bits against the app's request - for (i = 0; i < hCount; i++) { - header_info *hi = hList[i]; - if (hi->mhdr->filetype == MH_EXECUTE) { - continue; - } - else if (hi->mhdr == &_mh_dylib_header) { - // libobjc itself works with anything even though it is not - // compiled with -fobjc-gc (fixme should it be?) - } - else if (wantsGC && ! _objcHeaderSupportsGC(hi)) { - // App wants GC but library does not support it - bad - _objc_inform_now_and_on_crash - ("'%s' was not compiled with -fobjc-gc or -fobjc-gc-only, " - "but the application requires GC", - hi->fname); - busted = YES; - } - else if (!wantsGC && _objcHeaderRequiresGC(hi)) { - // App doesn't want GC but library requires it - bad - _objc_inform_now_and_on_crash - ("'%s' was compiled with -fobjc-gc-only, " - "but the application does not support GC", - hi->fname); - busted = YES; - } - - if (PrintGC) { - _objc_inform("GC: library '%s' %s", - hi->fname, _gcForHInfo(hi)); - } - } - - if (busted) { - // GC state is not consistent. - // Kill the process unless one of the forcing flags is set. - if (!DisableGC) { - _objc_fatal("*** GC capability of application and some libraries did not match"); - } - } -} - - -/*********************************************************************** -* gc_enforcer -* Make sure that images about to be loaded by dyld are GC-acceptable. -* Images linked to the executable are always permitted; they are -* enforced inside map_images() itself. -**********************************************************************/ -static bool InitialDyldRegistration = NO; -static const char *gc_enforcer(enum dyld_image_states state, - uint32_t infoCount, - const struct dyld_image_info info[]) -{ - uint32_t i; - - // Linked images get a free pass - if (InitialDyldRegistration) return NULL; - - if (PrintImages) { - _objc_inform("IMAGES: checking %d images for compatibility...", - infoCount); - } - - for (i = 0; i < infoCount; i++) { - crashlog_header_name_string(info[i].imageFilePath); - - const headerType *mhdr = (const headerType *)info[i].imageLoadAddress; - if (bad_magic(mhdr)) continue; - - objc_image_info *image_info; - size_t size; - - if (mhdr == &_mh_dylib_header) { - // libobjc itself - OK - continue; - } - -#if !__OBJC2__ - unsigned long seg_size; - // 32-bit: __OBJC seg but no image_info means no GC support - if (!getsegmentdata(mhdr, "__OBJC", &seg_size)) { - // not objc - assume OK - continue; - } - image_info = _getObjcImageInfo(mhdr, &size); - if (!image_info) { - // No image_info - assume GC unsupported - if (!UseGC) { - // GC is OFF - ok - continue; - } else { - // GC is ON - bad - if (PrintImages || PrintGC) { - _objc_inform("IMAGES: rejecting %d images because %s doesn't support GC (no image_info)", infoCount, info[i].imageFilePath); - } - goto reject; - } - } -#else - // 64-bit: no image_info means no objc at all - image_info = _getObjcImageInfo(mhdr, &size); - if (!image_info) { - // not objc - assume OK - continue; - } -#endif - - if (UseGC && !_objcInfoSupportsGC(image_info)) { - // GC is ON, but image does not support GC - if (PrintImages || PrintGC) { - _objc_inform("IMAGES: rejecting %d images because %s doesn't support GC", infoCount, info[i].imageFilePath); - } - goto reject; - } - if (!UseGC && _objcInfoRequiresGC(image_info)) { - // GC is OFF, but image requires GC - if (PrintImages || PrintGC) { - _objc_inform("IMAGES: rejecting %d images because %s requires GC", infoCount, info[i].imageFilePath); - } - goto reject; - } - } - - crashlog_header_name_string(NULL); - return NULL; - - reject: - crashlog_header_name_string(NULL); - return "GC capability mismatch"; -} - -// SUPPORT_GC -#endif - - -/*********************************************************************** -* map_images_nolock -* Process the given images which are being mapped in by dyld. -* All class registration and fixups are performed (or deferred pending -* discovery of missing superclasses etc), and +load methods are called. -* -* info[] is in bottom-up order i.e. libobjc will be earlier in the -* array than any library that links to libobjc. -* -* Locking: loadMethodLock(old) or runtimeLock(new) acquired by map_images. -**********************************************************************/ -#if __OBJC2__ -#include "objc-file.h" -#else -#include "objc-file-old.h" -#endif - -const char * -map_images_nolock(enum dyld_image_states state, uint32_t infoCount, - const struct dyld_image_info infoList[]) -{ - static bool firstTime = YES; - static bool wantsGC = NO; - uint32_t i; - header_info *hi; - header_info *hList[infoCount]; - uint32_t hCount; - size_t selrefCount = 0; - - // Perform first-time initialization if necessary. - // This function is called before ordinary library initializers. - // fixme defer initialization until an objc-using image is found? - if (firstTime) { - preopt_init(); -#if SUPPORT_GC - InitialDyldRegistration = YES; - dyld_register_image_state_change_handler(dyld_image_state_mapped, 0 /* batch */, &gc_enforcer); - InitialDyldRegistration = NO; -#endif - } - - if (PrintImages) { - _objc_inform("IMAGES: processing %u newly-mapped images...\n", infoCount); - } - - - // Find all images with Objective-C metadata. - hCount = 0; - i = infoCount; - while (i--) { - const headerType *mhdr = (headerType *)infoList[i].imageLoadAddress; - - hi = addHeader(mhdr); - if (!hi) { - // no objc data in this entry - continue; - } - - if (mhdr->filetype == MH_EXECUTE) { - // Size some data structures based on main executable's size -#if __OBJC2__ - size_t count; - _getObjc2SelectorRefs(hi, &count); - selrefCount += count; - _getObjc2MessageRefs(hi, &count); - selrefCount += count; -#else - _getObjcSelectorRefs(hi, &selrefCount); -#endif - } - - hList[hCount++] = hi; - - - if (PrintImages) { - _objc_inform("IMAGES: loading image for %s%s%s%s%s\n", - hi->fname, - mhdr->filetype == MH_BUNDLE ? " (bundle)" : "", - _objcHeaderIsReplacement(hi) ? " (replacement)" : "", - _objcHeaderOptimizedByDyld(hi)?" (preoptimized)" : "", - _gcForHInfo2(hi)); - } - } - - // Perform one-time runtime initialization that must be deferred until - // the executable itself is found. This needs to be done before - // further initialization. - // (The executable may not be present in this infoList if the - // executable does not contain Objective-C code but Objective-C - // is dynamically loaded later. In that case, check_wants_gc() - // will do the right thing.) -#if SUPPORT_GC - if (firstTime) { - check_wants_gc(&wantsGC); - - verify_gc_readiness(wantsGC, hList, hCount); - - gc_init(wantsGC); // needs executable for GC decision - } else { - verify_gc_readiness(wantsGC, hList, hCount); - } - - if (wantsGC) { - // tell the collector about the data segment ranges. - for (i = 0; i < hCount; ++i) { - uint8_t *seg; - unsigned long seg_size; - hi = hList[i]; - - seg = getsegmentdata(hi->mhdr, "__DATA", &seg_size); - if (seg) gc_register_datasegment((uintptr_t)seg, seg_size); - - seg = getsegmentdata(hi->mhdr, "__DATA_CONST", &seg_size); - if (seg) gc_register_datasegment((uintptr_t)seg, seg_size); - - seg = getsegmentdata(hi->mhdr, "__DATA_DIRTY", &seg_size); - if (seg) gc_register_datasegment((uintptr_t)seg, seg_size); - - seg = getsegmentdata(hi->mhdr, "__OBJC", &seg_size); - if (seg) gc_register_datasegment((uintptr_t)seg, seg_size); - // __OBJC contains no GC data, but pointers to it are - // used as associated reference values (rdar://6953570) - } - } -#endif - - if (firstTime) { - sel_init(wantsGC, selrefCount); - arr_init(); - } - - _read_images(hList, hCount); - - firstTime = NO; - - return NULL; -} - - -/*********************************************************************** -* load_images_nolock -* Prepares +load in the given images which are being mapped in by dyld. -* Returns YES if there are now +load methods to be called by call_load_methods. -* -* Locking: loadMethodLock(both) and runtimeLock(new) acquired by load_images -**********************************************************************/ -bool -load_images_nolock(enum dyld_image_states state,uint32_t infoCount, - const struct dyld_image_info infoList[]) -{ - bool found = NO; - uint32_t i; - - i = infoCount; - while (i--) { - const headerType *mhdr = (headerType*)infoList[i].imageLoadAddress; - if (!hasLoadMethods(mhdr)) continue; - - prepare_load_methods(mhdr); - found = YES; - } - - return found; -} - - -/*********************************************************************** -* unmap_image_nolock -* Process the given image which is about to be unmapped by dyld. -* mh is mach_header instead of headerType because that's what -* dyld_priv.h says even for 64-bit. -* -* Locking: loadMethodLock(both) and runtimeLock(new) acquired by unmap_image. -**********************************************************************/ -void -unmap_image_nolock(const struct mach_header *mh) -{ - if (PrintImages) { - _objc_inform("IMAGES: processing 1 newly-unmapped image...\n"); - } - - header_info *hi; - - // Find the runtime's header_info struct for the image - for (hi = FirstHeader; hi != NULL; hi = hi->next) { - if (hi->mhdr == (const headerType *)mh) { - break; - } - } - - if (!hi) return; - - if (PrintImages) { - _objc_inform("IMAGES: unloading image for %s%s%s%s\n", - hi->fname, - hi->mhdr->filetype == MH_BUNDLE ? " (bundle)" : "", - _objcHeaderIsReplacement(hi) ? " (replacement)" : "", - _gcForHInfo2(hi)); - } - -#if SUPPORT_GC - if (UseGC) { - uint8_t *seg; - unsigned long seg_size; - - seg = getsegmentdata(hi->mhdr, "__DATA", &seg_size); - if (seg) gc_unregister_datasegment((uintptr_t)seg, seg_size); - - seg = getsegmentdata(hi->mhdr, "__DATA_CONST", &seg_size); - if (seg) gc_unregister_datasegment((uintptr_t)seg, seg_size); - - seg = getsegmentdata(hi->mhdr, "__DATA_DIRTY", &seg_size); - if (seg) gc_unregister_datasegment((uintptr_t)seg, seg_size); - - seg = getsegmentdata(hi->mhdr, "__OBJC", &seg_size); - if (seg) gc_unregister_datasegment((uintptr_t)seg, seg_size); - } -#endif - - _unload_image(hi); - - // Remove header_info from header list - removeHeader(hi); - free(hi); -} - - -/*********************************************************************** -* static_init -* Run C++ static constructor functions. -* libc calls _objc_init() before dyld would call our static constructors, -* so we have to do it ourselves. -**********************************************************************/ -static void static_init() -{ -#if __OBJC2__ - size_t count; - Initializer *inits = getLibobjcInitializers(&_mh_dylib_header, &count); - for (size_t i = 0; i < count; i++) { - inits[i](); - } -#endif -} - - -/*********************************************************************** -* _objc_init -* Bootstrap initialization. Registers our image notifier with dyld. -* Old ABI: called by dyld as a library initializer -* New ABI: called by libSystem BEFORE library initialization time -**********************************************************************/ - -#if !__OBJC2__ -static __attribute__((constructor)) -#endif -void _objc_init(void) -{ - static bool initialized = false; - if (initialized) return; - initialized = true; - - // fixme defer initialization until an objc-using image is found? - environ_init(); - tls_init(); - static_init(); - lock_init(); - exception_init(); - - // Register for unmap first, in case some +load unmaps something - _dyld_register_func_for_remove_image(&unmap_image); - dyld_register_image_state_change_handler(dyld_image_state_bound, - 1/*batch*/, &map_2_images); - dyld_register_image_state_change_handler(dyld_image_state_dependents_initialized, 0/*not batch*/, &load_images); -} - - -/*********************************************************************** -* _headerForAddress. -* addr can be a class or a category -**********************************************************************/ -static const header_info *_headerForAddress(void *addr) -{ -#if __OBJC2__ - const char *segnames[] = { "__DATA", "__DATA_CONST", "__DATA_DIRTY" }; -#else - const char *segnames[] = { "__OBJC" }; -#endif - header_info *hi; - - for (hi = FirstHeader; hi != NULL; hi = hi->next) { - for (size_t i = 0; i < sizeof(segnames)/sizeof(segnames[0]); i++) { - unsigned long seg_size; - uint8_t *seg = getsegmentdata(hi->mhdr, segnames[i], &seg_size); - if (!seg) continue; - - // Is the class in this header? - if ((uint8_t *)addr >= seg && (uint8_t *)addr < seg + seg_size) { - return hi; - } - } - } - - // Not found - return 0; -} - - -/*********************************************************************** -* _headerForClass -* Return the image header containing this class, or NULL. -* Returns NULL on runtime-constructed classes, and the NSCF classes. -**********************************************************************/ -const header_info *_headerForClass(Class cls) -{ - return _headerForAddress(cls); -} - - -/********************************************************************** -* secure_open -* Securely open a file from a world-writable directory (like /tmp) -* If the file does not exist, it will be atomically created with mode 0600 -* If the file exists, it must be, and remain after opening: -* 1. a regular file (in particular, not a symlink) -* 2. owned by euid -* 3. permissions 0600 -* 4. link count == 1 -* Returns a file descriptor or -1. Errno may or may not be set on error. -**********************************************************************/ -int secure_open(const char *filename, int flags, uid_t euid) -{ - struct stat fs, ls; - int fd = -1; - bool truncate = NO; - bool create = NO; - - if (flags & O_TRUNC) { - // Don't truncate the file until after it is open and verified. - truncate = YES; - flags &= ~O_TRUNC; - } - if (flags & O_CREAT) { - // Don't create except when we're ready for it - create = YES; - flags &= ~O_CREAT; - flags &= ~O_EXCL; - } - - if (lstat(filename, &ls) < 0) { - if (errno == ENOENT && create) { - // No such file - create it - fd = open(filename, flags | O_CREAT | O_EXCL, 0600); - if (fd >= 0) { - // File was created successfully. - // New file does not need to be truncated. - return fd; - } else { - // File creation failed. - return -1; - } - } else { - // lstat failed, or user doesn't want to create the file - return -1; - } - } else { - // lstat succeeded - verify attributes and open - if (S_ISREG(ls.st_mode) && // regular file? - ls.st_nlink == 1 && // link count == 1? - ls.st_uid == euid && // owned by euid? - (ls.st_mode & ALLPERMS) == (S_IRUSR | S_IWUSR)) // mode 0600? - { - // Attributes look ok - open it and check attributes again - fd = open(filename, flags, 0000); - if (fd >= 0) { - // File is open - double-check attributes - if (0 == fstat(fd, &fs) && - fs.st_nlink == ls.st_nlink && // link count == 1? - fs.st_uid == ls.st_uid && // owned by euid? - fs.st_mode == ls.st_mode && // regular file, 0600? - fs.st_ino == ls.st_ino && // same inode as before? - fs.st_dev == ls.st_dev) // same device as before? - { - // File is open and OK - if (truncate) ftruncate(fd, 0); - return fd; - } else { - // Opened file looks funny - close it - close(fd); - return -1; - } - } else { - // File didn't open - return -1; - } - } else { - // Unopened file looks funny - don't open it - return -1; - } - } -} - - -bool crashlog_header_name(header_info *hi) -{ - return crashlog_header_name_string(hi ? hi->fname : NULL); -} - -bool crashlog_header_name_string(const char *name) -{ - CRSetCrashLogMessage2(name); - return true; -} - - -#if TARGET_OS_IPHONE - -const char *__crashreporter_info__ = NULL; - -const char *CRSetCrashLogMessage(const char *msg) -{ - __crashreporter_info__ = msg; - return msg; -} -const char *CRGetCrashLogMessage(void) -{ - return __crashreporter_info__; -} - -const char *CRSetCrashLogMessage2(const char *msg) -{ - // sorry - return msg; -} - -#endif - -// TARGET_OS_MAC -#else - - -#error unknown OS - - -#endif diff --git a/objc/objc-runtime/runtime/objc-private.h b/objc/objc-runtime/runtime/objc-private.h deleted file mode 100644 index b81f16a..0000000 --- a/objc/objc-runtime/runtime/objc-private.h +++ /dev/null @@ -1,992 +0,0 @@ -/* - * 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@ - */ -/* - * objc-private.h - * Copyright 1988-1996, NeXT Software, Inc. - */ - -#ifndef _OBJC_PRIVATE_H_ -#define _OBJC_PRIVATE_H_ - -#include "objc-config.h" - -/* Isolate ourselves from the definitions of id and Class in the compiler - * and public headers. - */ - -#ifdef _OBJC_OBJC_H_ -#error include objc-private.h before other headers -#endif - -#define OBJC_TYPES_DEFINED 1 -#define OBJC_OLD_DISPATCH_PROTOTYPES 0 - -#include <cstddef> // for nullptr_t -#include <stdint.h> -#include <assert.h> - -struct objc_class; -struct objc_object; - -typedef struct objc_class *Class; -typedef struct objc_object *id; - -namespace { - struct SideTable; -}; - - -union isa_t -{ - isa_t() { } - isa_t(uintptr_t value) : bits(value) { } - - Class cls; - uintptr_t bits; - -#if SUPPORT_NONPOINTER_ISA - - // extra_rc must be the MSB-most field (so it matches carry/overflow flags) - // indexed must be the LSB (fixme or get rid of it) - // shiftcls must occupy the same bits that a real class pointer would - // bits + RC_ONE is equivalent to extra_rc + 1 - // RC_HALF is the high bit of extra_rc (i.e. half of its range) - - // future expansion: - // uintptr_t fast_rr : 1; // no r/r overrides - // uintptr_t lock : 2; // lock for atomic property, @synch - // uintptr_t extraBytes : 1; // allocated with extra bytes - -# if __arm64__ -# define ISA_MASK 0x0000000ffffffff8ULL -# define ISA_MAGIC_MASK 0x000003f000000001ULL -# define ISA_MAGIC_VALUE 0x000001a000000001ULL - struct { - uintptr_t indexed : 1; - uintptr_t has_assoc : 1; - uintptr_t has_cxx_dtor : 1; - uintptr_t shiftcls : 33; // MACH_VM_MAX_ADDRESS 0x1000000000 - uintptr_t magic : 6; - uintptr_t weakly_referenced : 1; - uintptr_t deallocating : 1; - uintptr_t has_sidetable_rc : 1; - uintptr_t extra_rc : 19; -# define RC_ONE (1ULL<<45) -# define RC_HALF (1ULL<<18) - }; - -# elif __x86_64__ -# define ISA_MASK 0x00007ffffffffff8ULL -# define ISA_MAGIC_MASK 0x001f800000000001ULL -# define ISA_MAGIC_VALUE 0x001d800000000001ULL - struct { - uintptr_t indexed : 1; - uintptr_t has_assoc : 1; - uintptr_t has_cxx_dtor : 1; - uintptr_t shiftcls : 44; // MACH_VM_MAX_ADDRESS 0x7fffffe00000 - uintptr_t magic : 6; - uintptr_t weakly_referenced : 1; - uintptr_t deallocating : 1; - uintptr_t has_sidetable_rc : 1; - uintptr_t extra_rc : 8; -# define RC_ONE (1ULL<<56) -# define RC_HALF (1ULL<<7) - }; - -# else - // Available bits in isa field are architecture-specific. -# error unknown architecture -# endif - -// SUPPORT_NONPOINTER_ISA -#endif - -}; - - -struct objc_object { -private: - isa_t isa; - -public: - - // ISA() assumes this is NOT a tagged pointer object - Class ISA(); - - // getIsa() allows this to be a tagged pointer object - Class getIsa(); - - // initIsa() should be used to init the isa of new objects only. - // If this object already has an isa, use changeIsa() for correctness. - // initInstanceIsa(): objects with no custom RR/AWZ - // initClassIsa(): class objects - // initProtocolIsa(): protocol objects - // initIsa(): other objects - void initIsa(Class cls /*indexed=false*/); - void initClassIsa(Class cls /*indexed=maybe*/); - void initProtocolIsa(Class cls /*indexed=maybe*/); - void initInstanceIsa(Class cls, bool hasCxxDtor); - - // changeIsa() should be used to change the isa of existing objects. - // If this is a new object, use initIsa() for performance. - Class changeIsa(Class newCls); - - bool hasIndexedIsa(); - bool isTaggedPointer(); - bool isClass(); - - // object may have associated objects? - bool hasAssociatedObjects(); - void setHasAssociatedObjects(); - - // object may be weakly referenced? - bool isWeaklyReferenced(); - void setWeaklyReferenced_nolock(); - - // object may have -.cxx_destruct implementation? - bool hasCxxDtor(); - - // Optimized calls to retain/release methods - id retain(); - void release(); - id autorelease(); - - // Implementations of retain/release methods - id rootRetain(); - bool rootRelease(); - id rootAutorelease(); - bool rootTryRetain(); - bool rootReleaseShouldDealloc(); - uintptr_t rootRetainCount(); - - // Implementation of dealloc methods - bool rootIsDeallocating(); - void clearDeallocating(); - void rootDealloc(); - -private: - void initIsa(Class newCls, bool indexed, bool hasCxxDtor); - - // Slow paths for inline control - id rootAutorelease2(); - bool overrelease_error(); - -#if SUPPORT_NONPOINTER_ISA - // Unified retain count manipulation for nonpointer isa - id rootRetain(bool tryRetain, bool handleOverflow); - bool rootRelease(bool performDealloc, bool handleUnderflow); - id rootRetain_overflow(bool tryRetain); - bool rootRelease_underflow(bool performDealloc); - - void clearDeallocating_slow(); - - // Side table retain count overflow for nonpointer isa - void sidetable_lock(); - void sidetable_unlock(); - - void sidetable_moveExtraRC_nolock(size_t extra_rc, bool isDeallocating, bool weaklyReferenced); - bool sidetable_addExtraRC_nolock(size_t delta_rc); - size_t sidetable_subExtraRC_nolock(size_t delta_rc); - size_t sidetable_getExtraRC_nolock(); -#endif - - // Side-table-only retain count - bool sidetable_isDeallocating(); - void sidetable_clearDeallocating(); - - bool sidetable_isWeaklyReferenced(); - void sidetable_setWeaklyReferenced_nolock(); - - id sidetable_retain(); - id sidetable_retain_slow(SideTable& table); - - uintptr_t sidetable_release(bool performDealloc = true); - uintptr_t sidetable_release_slow(SideTable& table, bool performDealloc = true); - - bool sidetable_tryRetain(); - - uintptr_t sidetable_retainCount(); -#if DEBUG - bool sidetable_present(); -#endif -}; - - -#if __OBJC2__ -typedef struct method_t *Method; -typedef struct ivar_t *Ivar; -typedef struct category_t *Category; -typedef struct property_t *objc_property_t; -#else -typedef struct old_method *Method; -typedef struct old_ivar *Ivar; -typedef struct old_category *Category; -typedef struct old_property *objc_property_t; -#endif - -// Public headers - -#include "objc.h" -#include "runtime.h" -#include "objc-os.h" -#include "objc-abi.h" -#include "objc-api.h" -#include "objc-config.h" -#include "objc-internal.h" -#include "maptable.h" -#include "hashtable2.h" - -#if SUPPORT_GC -#include "objc-auto.h" -#endif - -/* Do not include message.h here. */ -/* #include "message.h" */ - -#define __APPLE_API_PRIVATE -#include "objc-gdb.h" -#undef __APPLE_API_PRIVATE - - -// Private headers - -#if __OBJC2__ -#include "objc-runtime-new.h" -#else -#include "objc-runtime-old.h" -#endif - -#include "objc-references.h" -#include "objc-initialize.h" -#include "objc-loadmethod.h" - - -#if SUPPORT_PREOPT && __cplusplus -#include <objc-shared-cache.h> -using objc_selopt_t = const objc_opt::objc_selopt_t; -#else -struct objc_selopt_t; -#endif - - -__BEGIN_DECLS - - -#if (defined(OBJC_NO_GC) && SUPPORT_GC) || \ - (!defined(OBJC_NO_GC) && !SUPPORT_GC) -# error OBJC_NO_GC and SUPPORT_GC inconsistent -#endif - -#if SUPPORT_GC -# include <auto_zone.h> - // PRIVATE_EXTERN is needed to help the compiler know "how" extern these are - PRIVATE_EXTERN extern int8_t UseGC; // equivalent to calling objc_collecting_enabled() - PRIVATE_EXTERN extern auto_zone_t *gc_zone; // the GC zone, or NULL if no GC - extern void objc_addRegisteredClass(Class c); - extern void objc_removeRegisteredClass(Class c); -#else -# define UseGC NO -# define gc_zone NULL -# define objc_addRegisteredClass(c) do {} while(0) -# define objc_removeRegisteredClass(c) do {} while(0) - /* Uses of the following must be protected with UseGC. */ - extern id gc_unsupported_dont_call(); -# define auto_zone_allocate_object gc_unsupported_dont_call -# define auto_zone_retain gc_unsupported_dont_call -# define auto_zone_release gc_unsupported_dont_call -# define auto_zone_is_valid_pointer gc_unsupported_dont_call -# define auto_zone_write_barrier_memmove gc_unsupported_dont_call -# define AUTO_OBJECT_SCANNED 0 -#endif - - -#define _objcHeaderIsReplacement(h) ((h)->info && ((h)->info->flags & OBJC_IMAGE_IS_REPLACEMENT)) - -/* OBJC_IMAGE_IS_REPLACEMENT: - Don't load any classes - Don't load any categories - Do fix up selector refs (@selector points to them) - Do fix up class refs (@class and objc_msgSend points to them) - Do fix up protocols (@protocol points to them) - Do fix up superclass pointers in classes ([super ...] points to them) - Future: do load new classes? - Future: do load new categories? - Future: do insert new methods on existing classes? - Future: do insert new methods on existing categories? -*/ - -#define _objcInfoSupportsGC(info) (((info)->flags & OBJC_IMAGE_SUPPORTS_GC) ? 1 : 0) -#define _objcInfoRequiresGC(info) (((info)->flags & OBJC_IMAGE_REQUIRES_GC) ? 1 : 0) -#define _objcHeaderSupportsGC(h) ((h)->info && _objcInfoSupportsGC((h)->info)) -#define _objcHeaderRequiresGC(h) ((h)->info && _objcInfoRequiresGC((h)->info)) - -/* OBJC_IMAGE_SUPPORTS_GC: - was compiled with -fobjc-gc flag, regardless of whether write-barriers were issued - if executable image compiled this way, then all subsequent libraries etc. must also be this way -*/ - -#define _objcHeaderOptimizedByDyld(h) ((h)->info && ((h)->info->flags & OBJC_IMAGE_OPTIMIZED_BY_DYLD)) - -/* OBJC_IMAGE_OPTIMIZED_BY_DYLD: - Assorted metadata precooked in the dyld shared cache. - Never set for images outside the shared cache file itself. -*/ - - -typedef struct header_info { - struct header_info *next; - const headerType *mhdr; - const objc_image_info *info; - const char *fname; // same as Dl_info.dli_fname - bool loaded; - bool inSharedCache; - bool allClassesRealized; - - // Do not add fields without editing ObjCModernAbstraction.hpp - - bool isLoaded() { - return loaded; - } - - bool isBundle() { - return mhdr->filetype == MH_BUNDLE; - } - - bool isPreoptimized() const; - -#if !__OBJC2__ - struct old_protocol **proto_refs; - struct objc_module *mod_ptr; - size_t mod_count; -# if TARGET_OS_WIN32 - struct objc_module **modules; - size_t moduleCount; - struct old_protocol **protocols; - size_t protocolCount; - void *imageinfo; - size_t imageinfoBytes; - SEL *selrefs; - size_t selrefCount; - struct objc_class **clsrefs; - size_t clsrefCount; - TCHAR *moduleName; -# endif -#endif -} header_info; - -extern header_info *FirstHeader; -extern header_info *LastHeader; -extern int HeaderCount; - -extern void appendHeader(header_info *hi); -extern void removeHeader(header_info *hi); - -extern objc_image_info *_getObjcImageInfo(const headerType *head, size_t *size); -extern bool _hasObjcContents(const header_info *hi); - - -/* selectors */ -extern void sel_init(bool gc, size_t selrefCount); -extern SEL sel_registerNameNoLock(const char *str, bool copy); -extern void sel_lock(void); -extern void sel_unlock(void); - -extern SEL SEL_load; -extern SEL SEL_initialize; -extern SEL SEL_resolveClassMethod; -extern SEL SEL_resolveInstanceMethod; -extern SEL SEL_cxx_construct; -extern SEL SEL_cxx_destruct; -extern SEL SEL_retain; -extern SEL SEL_release; -extern SEL SEL_autorelease; -extern SEL SEL_retainCount; -extern SEL SEL_alloc; -extern SEL SEL_allocWithZone; -extern SEL SEL_dealloc; -extern SEL SEL_copy; -extern SEL SEL_new; -extern SEL SEL_finalize; -extern SEL SEL_forwardInvocation; -extern SEL SEL_tryRetain; -extern SEL SEL_isDeallocating; -extern SEL SEL_retainWeakReference; -extern SEL SEL_allowsWeakReference; - -/* preoptimization */ -extern void preopt_init(void); -extern void disableSharedCacheOptimizations(void); -extern bool isPreoptimized(void); -extern header_info *preoptimizedHinfoForHeader(const headerType *mhdr); - -extern objc_selopt_t *preoptimizedSelectors(void); - -extern Protocol *getPreoptimizedProtocol(const char *name); - -extern Class getPreoptimizedClass(const char *name); -extern Class* copyPreoptimizedClasses(const char *name, int *outCount); - -extern Class _calloc_class(size_t size); - -/* method lookup */ -extern IMP lookUpImpOrNil(Class, SEL, id obj, bool initialize, bool cache, bool resolver); -extern IMP lookUpImpOrForward(Class, SEL, id obj, bool initialize, bool cache, bool resolver); - -extern IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel); -extern bool class_respondsToSelector_inst(Class cls, SEL sel, id inst); - -extern bool objcMsgLogEnabled; -extern bool logMessageSend(bool isClassMethod, - const char *objectsClass, - const char *implementingClass, - SEL selector); - -/* message dispatcher */ -extern IMP _class_lookupMethodAndLoadCache3(id, SEL, Class); - -#if !OBJC_OLD_DISPATCH_PROTOTYPES -extern void _objc_msgForward_impcache(void); -extern void _objc_ignored_method(void); -extern void _objc_msgSend_uncached_impcache(void); -#else -extern id _objc_msgForward_impcache(id, SEL, ...); -extern id _objc_ignored_method(id, SEL, ...); -extern id _objc_msgSend_uncached_impcache(id, SEL, ...); -#endif - -/* errors */ -extern void __objc_error(id, const char *, ...) __attribute__((format (printf, 2, 3), noreturn)); -extern void _objc_inform(const char *fmt, ...) __attribute__((format (printf, 1, 2))); -extern void _objc_inform_on_crash(const char *fmt, ...) __attribute__((format (printf, 1, 2))); -extern void _objc_inform_now_and_on_crash(const char *fmt, ...) __attribute__((format (printf, 1, 2))); -extern void _objc_inform_deprecated(const char *oldname, const char *newname) __attribute__((noinline)); -extern void inform_duplicate(const char *name, Class oldCls, Class cls); -extern bool crashlog_header_name(header_info *hi); -extern bool crashlog_header_name_string(const char *name); - -/* magic */ -extern Class _objc_getFreedObjectClass (void); - -/* map table additions */ -extern void *NXMapKeyCopyingInsert(NXMapTable *table, const void *key, const void *value); -extern void *NXMapKeyFreeingRemove(NXMapTable *table, const void *key); - -/* hash table additions */ -extern unsigned _NXHashCapacity(NXHashTable *table); -extern void _NXHashRehashToCapacity(NXHashTable *table, unsigned newCapacity); - -/* property attribute parsing */ -extern const char *copyPropertyAttributeString(const objc_property_attribute_t *attrs, unsigned int count); -extern objc_property_attribute_t *copyPropertyAttributeList(const char *attrs, unsigned int *outCount); -extern char *copyPropertyAttributeValue(const char *attrs, const char *name); - -/* locking */ -extern void lock_init(void); -extern rwlock_t selLock; -extern mutex_t cacheUpdateLock; -extern recursive_mutex_t loadMethodLock; -#if __OBJC2__ -extern rwlock_t runtimeLock; -#else -extern mutex_t classLock; -extern mutex_t methodListLock; -#endif - -class monitor_locker_t : nocopy_t { - monitor_t& lock; - public: - monitor_locker_t(monitor_t& newLock) : lock(newLock) { lock.enter(); } - ~monitor_locker_t() { lock.leave(); } -}; - -class mutex_locker_t : nocopy_t { - mutex_t& lock; - public: - mutex_locker_t(mutex_t& newLock) - : lock(newLock) { lock.lock(); } - ~mutex_locker_t() { lock.unlock(); } -}; - -class recursive_mutex_locker_t : nocopy_t { - recursive_mutex_t& lock; - public: - recursive_mutex_locker_t(recursive_mutex_t& newLock) - : lock(newLock) { lock.lock(); } - ~recursive_mutex_locker_t() { lock.unlock(); } -}; - -class rwlock_reader_t : nocopy_t { - rwlock_t& lock; - public: - rwlock_reader_t(rwlock_t& newLock) : lock(newLock) { lock.read(); } - ~rwlock_reader_t() { lock.unlockRead(); } -}; - -class rwlock_writer_t : nocopy_t { - rwlock_t& lock; - public: - rwlock_writer_t(rwlock_t& newLock) : lock(newLock) { lock.write(); } - ~rwlock_writer_t() { lock.unlockWrite(); } -}; - -/* ignored selector support */ - -/* Non-GC: no ignored selectors - GC (i386 Mac): some selectors ignored, remapped to kIgnore - GC (others): some selectors ignored, but not remapped -*/ - -static inline int ignoreSelector(SEL sel) -{ -#if !SUPPORT_GC - return NO; -#elif SUPPORT_IGNORED_SELECTOR_CONSTANT - return UseGC && sel == (SEL)kIgnore; -#else - return UseGC && - (sel == @selector(retain) || - sel == @selector(release) || - sel == @selector(autorelease) || - sel == @selector(retainCount) || - sel == @selector(dealloc)); -#endif -} - -static inline int ignoreSelectorNamed(const char *sel) -{ -#if !SUPPORT_GC - return NO; -#else - // release retain retainCount dealloc autorelease - return (UseGC && - ( (sel[0] == 'r' && sel[1] == 'e' && - (strcmp(&sel[2], "lease") == 0 || - strcmp(&sel[2], "tain") == 0 || - strcmp(&sel[2], "tainCount") == 0 )) - || - (strcmp(sel, "dealloc") == 0) - || - (sel[0] == 'a' && sel[1] == 'u' && - strcmp(&sel[2], "torelease") == 0))); -#endif -} - -/* GC startup */ -extern void gc_init(bool wantsGC); -extern void gc_init2(void); - -/* Exceptions */ -struct alt_handler_list; -extern void exception_init(void); -extern void _destroyAltHandlerList(struct alt_handler_list *list); - -/* Class change notifications (gdb only for now) */ -#define OBJC_CLASS_ADDED (1<<0) -#define OBJC_CLASS_REMOVED (1<<1) -#define OBJC_CLASS_IVARS_CHANGED (1<<2) -#define OBJC_CLASS_METHODS_CHANGED (1<<3) -extern void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname) - __attribute__((noinline)); - -#if SUPPORT_GC - -/* Write barrier implementations */ -extern id objc_getAssociatedObject_non_gc(id object, const void *key); -extern void objc_setAssociatedObject_non_gc(id object, const void *key, id value, objc_AssociationPolicy policy); - -extern id objc_getAssociatedObject_gc(id object, const void *key); -extern void objc_setAssociatedObject_gc(id object, const void *key, id value, objc_AssociationPolicy policy); - -/* xrefs */ -extern objc_xref_t _object_addExternalReference_non_gc(id obj, objc_xref_t type); -extern id _object_readExternalReference_non_gc(objc_xref_t ref); -extern void _object_removeExternalReference_non_gc(objc_xref_t ref); - -extern objc_xref_t _object_addExternalReference_gc(id obj, objc_xref_t type); -extern id _object_readExternalReference_gc(objc_xref_t ref); -extern void _object_removeExternalReference_gc(objc_xref_t ref); - -/* GC weak reference fixup. */ -extern void gc_fixup_weakreferences(id newObject, id oldObject); - -/* GC datasegment registration. */ -extern void gc_register_datasegment(uintptr_t base, size_t size); -extern void gc_unregister_datasegment(uintptr_t base, size_t size); - -/* objc_dumpHeap implementation */ -extern bool _objc_dumpHeap(auto_zone_t *zone, const char *filename); - -#endif - - -// Settings from environment variables -#define OPTION(var, env, help) extern bool var; -#include "objc-env.h" -#undef OPTION - -extern void environ_init(void); - -extern void logReplacedMethod(const char *className, SEL s, bool isMeta, const char *catName, IMP oldImp, IMP newImp); - - -// objc per-thread storage -typedef struct { - struct _objc_initializing_classes *initializingClasses; // for +initialize - struct SyncCache *syncCache; // for @synchronize - struct alt_handler_list *handlerList; // for exception alt handlers - char *printableNames[4]; // temporary demangled names for logging - - // If you add new fields here, don't forget to update - // _objc_pthread_destroyspecific() - -} _objc_pthread_data; - -extern _objc_pthread_data *_objc_fetch_pthread_data(bool create); -extern void tls_init(void); - -// encoding.h -extern unsigned int encoding_getNumberOfArguments(const char *typedesc); -extern unsigned int encoding_getSizeOfArguments(const char *typedesc); -extern unsigned int encoding_getArgumentInfo(const char *typedesc, unsigned int arg, const char **type, int *offset); -extern void encoding_getReturnType(const char *t, char *dst, size_t dst_len); -extern char * encoding_copyReturnType(const char *t); -extern void encoding_getArgumentType(const char *t, unsigned int index, char *dst, size_t dst_len); -extern char *encoding_copyArgumentType(const char *t, unsigned int index); - -// sync.h -extern void _destroySyncCache(struct SyncCache *cache); - -// arr -extern void arr_init(void); -extern id objc_autoreleaseReturnValue(id obj); - -// block trampolines -extern IMP _imp_implementationWithBlockNoCopy(id block); - -// layout.h -typedef struct { - uint8_t *bits; - size_t bitCount; - size_t bitsAllocated; - bool weak; -} layout_bitmap; -extern layout_bitmap layout_bitmap_create(const unsigned char *layout_string, size_t layoutStringInstanceSize, size_t instanceSize, bool weak); -extern layout_bitmap layout_bitmap_create_empty(size_t instanceSize, bool weak); -extern void layout_bitmap_free(layout_bitmap bits); -extern const unsigned char *layout_string_create(layout_bitmap bits); -extern void layout_bitmap_set_ivar(layout_bitmap bits, const char *type, size_t offset); -extern void layout_bitmap_grow(layout_bitmap *bits, size_t newCount); -extern void layout_bitmap_slide(layout_bitmap *bits, size_t oldPos, size_t newPos); -extern void layout_bitmap_slide_anywhere(layout_bitmap *bits, size_t oldPos, size_t newPos); -extern bool layout_bitmap_splat(layout_bitmap dst, layout_bitmap src, - size_t oldSrcInstanceSize); -extern bool layout_bitmap_or(layout_bitmap dst, layout_bitmap src, const char *msg); -extern bool layout_bitmap_clear(layout_bitmap dst, layout_bitmap src, const char *msg); -extern void layout_bitmap_print(layout_bitmap bits); - - -// fixme runtime -extern Class look_up_class(const char *aClassName, bool includeUnconnected, bool includeClassHandler); -extern "C" const char *map_2_images(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info infoList[]); -extern const char *map_images_nolock(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info infoList[]); -extern const char * load_images(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info infoList[]); -extern bool load_images_nolock(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info infoList[]); -extern void unmap_image(const struct mach_header *mh, intptr_t vmaddr_slide); -extern void unmap_image_nolock(const struct mach_header *mh); -extern void _read_images(header_info **hList, uint32_t hCount); -extern void prepare_load_methods(const headerType *mhdr); -extern bool hasLoadMethods(const headerType *mhdr); -extern void _unload_image(header_info *hi); -extern const char ** _objc_copyClassNamesForImage(header_info *hi, unsigned int *outCount); - - -extern const header_info *_headerForClass(Class cls); - -extern Class _class_remap(Class cls); -extern Class _class_getNonMetaClass(Class cls, id obj); -extern Ivar _class_getVariable(Class cls, const char *name, Class *memberOf); -extern uint32_t _class_getInstanceStart(Class cls); - -extern unsigned _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone, id *results, unsigned num_requested); -extern id _objc_constructOrFree(id bytes, Class cls); - -extern const char *_category_getName(Category cat); -extern const char *_category_getClassName(Category cat); -extern Class _category_getClass(Category cat); -extern IMP _category_getLoadMethod(Category cat); - -extern id object_cxxConstructFromClass(id obj, Class cls); -extern void object_cxxDestruct(id obj); - -extern void _class_resolveMethod(Class cls, SEL sel, id inst); - -#define OBJC_WARN_DEPRECATED \ - do { \ - static int warned = 0; \ - if (!warned) { \ - warned = 1; \ - _objc_inform_deprecated(__FUNCTION__, NULL); \ - } \ - } while (0) \ - -__END_DECLS - - -#ifndef STATIC_ASSERT -# define STATIC_ASSERT(x) _STATIC_ASSERT2(x, __LINE__) -# define _STATIC_ASSERT2(x, line) _STATIC_ASSERT3(x, line) -# define _STATIC_ASSERT3(x, line) \ - typedef struct { \ - int _static_assert[(x) ? 0 : -1]; \ - } _static_assert_ ## line __attribute__((unavailable)) -#endif - -#define countof(arr) (sizeof(arr) / sizeof((arr)[0])) - - -static __inline uint32_t _objc_strhash(const char *s) { - uint32_t hash = 0; - for (;;) { - int a = *s++; - if (0 == a) break; - hash += (hash << 8) + a; - } - return hash; -} - -#if __cplusplus - -template <typename T> -static inline T log2u(T x) { - return (x<2) ? 0 : log2u(x>>1)+1; -} - -template <typename T> -static inline T exp2u(T x) { - return (1 << x); -} - -template <typename T> -static T exp2m1u(T x) { - return (1 << x) - 1; -} - -#endif - - -// Global operator new and delete. We must not use any app overrides. -// This ALSO REQUIRES each of these be in libobjc's unexported symbol list. -#if __cplusplus -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Winline-new-delete" -#include <new> -inline void* operator new(std::size_t size) throw (std::bad_alloc) { return malloc(size); } -inline void* operator new[](std::size_t size) throw (std::bad_alloc) { return malloc(size); } -inline void* operator new(std::size_t size, const std::nothrow_t&) throw() { return malloc(size); } -inline void* operator new[](std::size_t size, const std::nothrow_t&) throw() { return malloc(size); } -inline void operator delete(void* p) throw() { free(p); } -inline void operator delete[](void* p) throw() { free(p); } -inline void operator delete(void* p, const std::nothrow_t&) throw() { free(p); } -inline void operator delete[](void* p, const std::nothrow_t&) throw() { free(p); } -#pragma clang diagnostic pop -#endif - - -class TimeLogger { - uint64_t mStart; - bool mRecord; - public: - TimeLogger(bool record = true) - : mStart(nanoseconds()) - , mRecord(record) - { } - - void log(const char *msg) { - if (mRecord) { - uint64_t end = nanoseconds(); - _objc_inform("%.2f ms: %s", (end - mStart) / 1000000.0, msg); - mStart = nanoseconds(); - } - } -}; - - -// StripedMap<T> is a map of void* -> T, sized appropriately -// for cache-friendly lock striping. -// For example, this may be used as StripedMap<spinlock_t> -// or as StripedMap<SomeStruct> where SomeStruct stores a spin lock. -template<typename T> -class StripedMap { - - enum { CacheLineSize = 64 }; - -#if TARGET_OS_EMBEDDED - enum { StripeCount = 8 }; -#else - enum { StripeCount = 64 }; -#endif - - struct PaddedT { - T value alignas(CacheLineSize); - }; - - PaddedT array[StripeCount]; - - static unsigned int indexForPointer(const void *p) { - uintptr_t addr = reinterpret_cast<uintptr_t>(p); - return ((addr >> 4) ^ (addr >> 9)) % StripeCount; - } - - public: - T& operator[] (const void *p) { - return array[indexForPointer(p)].value; - } - const T& operator[] (const void *p) const { - return const_cast<StripedMap<T> >(this)[p]; - } - -#if DEBUG - StripedMap() { - // Verify alignment expectations. - uintptr_t base = (uintptr_t)&array[0].value; - uintptr_t delta = (uintptr_t)&array[1].value - base; - assert(delta % CacheLineSize == 0); - assert(base % CacheLineSize == 0); - } -#endif -}; - - -// DisguisedPtr<T> acts like pointer type T*, except the -// stored value is disguised to hide it from tools like `leaks`. -// nil is disguised as itself so zero-filled memory works as expected, -// which means 0x80..00 is also diguised as itself but we don't care -template <typename T> -class DisguisedPtr { - uintptr_t value; - - static uintptr_t disguise(T* ptr) { - return -(uintptr_t)ptr; - } - - static T* undisguise(uintptr_t val) { - return (T*)-val; - } - - public: - DisguisedPtr() { } - DisguisedPtr(T* ptr) - : value(disguise(ptr)) { } - DisguisedPtr(const DisguisedPtr<T>& ptr) - : value(ptr.value) { } - - DisguisedPtr<T>& operator = (T* rhs) { - value = disguise(rhs); - return *this; - } - DisguisedPtr<T>& operator = (const DisguisedPtr<T>& rhs) { - value = rhs.value; - return *this; - } - - operator T* () const { - return undisguise(value); - } - T* operator -> () const { - return undisguise(value); - } - T& operator * () const { - return *undisguise(value); - } - T& operator [] (size_t i) const { - return undisguise(value)[i]; - } - - // pointer arithmetic operators omitted - // because we don't currently use them anywhere -}; - -// fixme type id is weird and not identical to objc_object* -static inline bool operator == (DisguisedPtr<objc_object> lhs, id rhs) { - return lhs == (objc_object *)rhs; -} -static inline bool operator != (DisguisedPtr<objc_object> lhs, id rhs) { - return lhs != (objc_object *)rhs; -} - - -// Pointer hash function. -// This is not a terrific hash, but it is fast -// and not outrageously flawed for our purposes. - -// Based on principles from http://locklessinc.com/articles/fast_hash/ -// and evaluation ideas from http://floodyberry.com/noncryptohashzoo/ -#if __LP64__ -static inline uint32_t ptr_hash(uint64_t key) -{ - key ^= key >> 4; - key *= 0x8a970be7488fda55; - key ^= __builtin_bswap64(key); - return (uint32_t)key; -} -#else -static inline uint32_t ptr_hash(uint32_t key) -{ - key ^= key >> 4; - key *= 0x5052acdb; - key ^= __builtin_bswap32(key); - return key; -} -#endif - -/* - Higher-quality hash function. This is measurably slower in some workloads. -#if __LP64__ - uint32_t ptr_hash(uint64_t key) -{ - key -= __builtin_bswap64(key); - key *= 0x8a970be7488fda55; - key ^= __builtin_bswap64(key); - key *= 0x8a970be7488fda55; - key ^= __builtin_bswap64(key); - return (uint32_t)key; -} -#else -static uint32_t ptr_hash(uint32_t key) -{ - key -= __builtin_bswap32(key); - key *= 0x5052acdb; - key ^= __builtin_bswap32(key); - key *= 0x5052acdb; - key ^= __builtin_bswap32(key); - return key; -} -#endif -*/ - - -// Inlined parts of objc_object's implementation -#include "objc-object.h" - -#endif /* _OBJC_PRIVATE_H_ */ - diff --git a/objc/objc-runtime/runtime/objc-probes.d b/objc/objc-runtime/runtime/objc-probes.d deleted file mode 100644 index 4a1e224..0000000 --- a/objc/objc-runtime/runtime/objc-probes.d +++ /dev/null @@ -1,5 +0,0 @@ -provider objc_runtime -{ - probe objc_exception_throw(void *id); - probe objc_exception_rethrow(); -}; diff --git a/objc/objc-runtime/runtime/objc-references.h b/objc/objc-runtime/runtime/objc-references.h deleted file mode 100644 index 1e49f7c..0000000 --- a/objc/objc-runtime/runtime/objc-references.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 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@ - */ -/* - * objc-references.h - */ - -#ifndef _OBJC_REFERENCES_H_ -#define _OBJC_REFERENCES_H_ - -#include "objc-api.h" -#include "objc-config.h" - -__BEGIN_DECLS - -extern void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy); -extern id _object_get_associative_reference(id object, void *key); -extern void _object_remove_assocations(id object); - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/runtime/objc-references.mm b/objc/objc-runtime/runtime/objc-references.mm deleted file mode 100644 index 712b88e..0000000 --- a/objc/objc-runtime/runtime/objc-references.mm +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright (c) 2004-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@ - */ -/* - Implementation of the weak / associative references for non-GC mode. -*/ - - -#include "objc-private.h" -#include <objc/message.h> -#include <map> - -#if _LIBCPP_VERSION -# include <unordered_map> -#else -# include <tr1/unordered_map> - using namespace tr1; -#endif - - -// wrap all the murky C++ details in a namespace to get them out of the way. - -namespace objc_references_support { - struct DisguisedPointerEqual { - bool operator()(uintptr_t p1, uintptr_t p2) const { - return p1 == p2; - } - }; - - struct DisguisedPointerHash { - uintptr_t operator()(uintptr_t k) const { - // borrowed from CFSet.c -#if __LP64__ - uintptr_t a = 0x4368726973746F70ULL; - uintptr_t b = 0x686572204B616E65ULL; -#else - uintptr_t a = 0x4B616E65UL; - uintptr_t b = 0x4B616E65UL; -#endif - uintptr_t c = 1; - a += k; -#if __LP64__ - a -= b; a -= c; a ^= (c >> 43); - b -= c; b -= a; b ^= (a << 9); - c -= a; c -= b; c ^= (b >> 8); - a -= b; a -= c; a ^= (c >> 38); - b -= c; b -= a; b ^= (a << 23); - c -= a; c -= b; c ^= (b >> 5); - a -= b; a -= c; a ^= (c >> 35); - b -= c; b -= a; b ^= (a << 49); - c -= a; c -= b; c ^= (b >> 11); - a -= b; a -= c; a ^= (c >> 12); - b -= c; b -= a; b ^= (a << 18); - c -= a; c -= b; c ^= (b >> 22); -#else - a -= b; a -= c; a ^= (c >> 13); - b -= c; b -= a; b ^= (a << 8); - c -= a; c -= b; c ^= (b >> 13); - a -= b; a -= c; a ^= (c >> 12); - b -= c; b -= a; b ^= (a << 16); - c -= a; c -= b; c ^= (b >> 5); - a -= b; a -= c; a ^= (c >> 3); - b -= c; b -= a; b ^= (a << 10); - c -= a; c -= b; c ^= (b >> 15); -#endif - return c; - } - }; - - struct ObjectPointerLess { - bool operator()(const void *p1, const void *p2) const { - return p1 < p2; - } - }; - - struct ObjcPointerHash { - uintptr_t operator()(void *p) const { - return DisguisedPointerHash()(uintptr_t(p)); - } - }; - - // STL allocator that uses the runtime's internal allocator. - - template <typename T> struct ObjcAllocator { - typedef T value_type; - typedef value_type* pointer; - typedef const value_type *const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - - template <typename U> struct rebind { typedef ObjcAllocator<U> other; }; - - template <typename U> ObjcAllocator(const ObjcAllocator<U>&) {} - ObjcAllocator() {} - ObjcAllocator(const ObjcAllocator&) {} - ~ObjcAllocator() {} - - pointer address(reference x) const { return &x; } - const_pointer address(const_reference x) const { - return x; - } - - pointer allocate(size_type n, const_pointer = 0) { - return static_cast<pointer>(::malloc(n * sizeof(T))); - } - - void deallocate(pointer p, size_type) { ::free(p); } - - size_type max_size() const { - return static_cast<size_type>(-1) / sizeof(T); - } - - void construct(pointer p, const value_type& x) { - new(p) value_type(x); - } - - void destroy(pointer p) { p->~value_type(); } - - void operator=(const ObjcAllocator&); - - }; - - template<> struct ObjcAllocator<void> { - typedef void value_type; - typedef void* pointer; - typedef const void *const_pointer; - template <typename U> struct rebind { typedef ObjcAllocator<U> other; }; - }; - - typedef uintptr_t disguised_ptr_t; - inline disguised_ptr_t DISGUISE(id value) { return ~uintptr_t(value); } - inline id UNDISGUISE(disguised_ptr_t dptr) { return id(~dptr); } - - class ObjcAssociation { - uintptr_t _policy; - id _value; - public: - ObjcAssociation(uintptr_t policy, id value) : _policy(policy), _value(value) {} - ObjcAssociation() : _policy(0), _value(nil) {} - - uintptr_t policy() const { return _policy; } - id value() const { return _value; } - - bool hasValue() { return _value != nil; } - }; - -#if TARGET_OS_WIN32 - typedef hash_map<void *, ObjcAssociation> ObjectAssociationMap; - typedef hash_map<disguised_ptr_t, ObjectAssociationMap *> AssociationsHashMap; -#else - typedef ObjcAllocator<std::pair<void * const, ObjcAssociation> > ObjectAssociationMapAllocator; - class ObjectAssociationMap : public std::map<void *, ObjcAssociation, ObjectPointerLess, ObjectAssociationMapAllocator> { - public: - void *operator new(size_t n) { return ::malloc(n); } - void operator delete(void *ptr) { ::free(ptr); } - }; - typedef ObjcAllocator<std::pair<const disguised_ptr_t, ObjectAssociationMap*> > AssociationsHashMapAllocator; - class AssociationsHashMap : public unordered_map<disguised_ptr_t, ObjectAssociationMap *, DisguisedPointerHash, DisguisedPointerEqual, AssociationsHashMapAllocator> { - public: - void *operator new(size_t n) { return ::malloc(n); } - void operator delete(void *ptr) { ::free(ptr); } - }; -#endif -} - -using namespace objc_references_support; - -// class AssociationsManager manages a lock / hash table singleton pair. -// Allocating an instance acquires the lock, and calling its assocations() method -// lazily allocates it. - -class AssociationsManager { - static spinlock_t _lock; - static AssociationsHashMap *_map; // associative references: object pointer -> PtrPtrHashMap. -public: - AssociationsManager() { _lock.lock(); } - ~AssociationsManager() { _lock.unlock(); } - - AssociationsHashMap &associations() { - if (_map == NULL) - _map = new AssociationsHashMap(); - return *_map; - } -}; - -spinlock_t AssociationsManager::_lock; -AssociationsHashMap *AssociationsManager::_map = NULL; - -// expanded policy bits. - -enum { - OBJC_ASSOCIATION_SETTER_ASSIGN = 0, - OBJC_ASSOCIATION_SETTER_RETAIN = 1, - OBJC_ASSOCIATION_SETTER_COPY = 3, // NOTE: both bits are set, so we can simply test 1 bit in releaseValue below. - OBJC_ASSOCIATION_GETTER_READ = (0 << 8), - OBJC_ASSOCIATION_GETTER_RETAIN = (1 << 8), - OBJC_ASSOCIATION_GETTER_AUTORELEASE = (2 << 8) -}; - -id _object_get_associative_reference(id object, void *key) { - id value = nil; - uintptr_t policy = OBJC_ASSOCIATION_ASSIGN; - { - AssociationsManager manager; - AssociationsHashMap &associations(manager.associations()); - disguised_ptr_t disguised_object = DISGUISE(object); - AssociationsHashMap::iterator i = associations.find(disguised_object); - if (i != associations.end()) { - ObjectAssociationMap *refs = i->second; - ObjectAssociationMap::iterator j = refs->find(key); - if (j != refs->end()) { - ObjcAssociation &entry = j->second; - value = entry.value(); - policy = entry.policy(); - if (policy & OBJC_ASSOCIATION_GETTER_RETAIN) ((id(*)(id, SEL))objc_msgSend)(value, SEL_retain); - } - } - } - if (value && (policy & OBJC_ASSOCIATION_GETTER_AUTORELEASE)) { - ((id(*)(id, SEL))objc_msgSend)(value, SEL_autorelease); - } - return value; -} - -static id acquireValue(id value, uintptr_t policy) { - switch (policy & 0xFF) { - case OBJC_ASSOCIATION_SETTER_RETAIN: - return ((id(*)(id, SEL))objc_msgSend)(value, SEL_retain); - case OBJC_ASSOCIATION_SETTER_COPY: - return ((id(*)(id, SEL))objc_msgSend)(value, SEL_copy); - } - return value; -} - -static void releaseValue(id value, uintptr_t policy) { - if (policy & OBJC_ASSOCIATION_SETTER_RETAIN) { - ((id(*)(id, SEL))objc_msgSend)(value, SEL_release); - } -} - -struct ReleaseValue { - void operator() (ObjcAssociation &association) { - releaseValue(association.value(), association.policy()); - } -}; - -void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy) { - // retain the new value (if any) outside the lock. - ObjcAssociation old_association(0, nil); - id new_value = value ? acquireValue(value, policy) : nil; - { - AssociationsManager manager; - AssociationsHashMap &associations(manager.associations()); - disguised_ptr_t disguised_object = DISGUISE(object); - if (new_value) { - // break any existing association. - AssociationsHashMap::iterator i = associations.find(disguised_object); - if (i != associations.end()) { - // secondary table exists - ObjectAssociationMap *refs = i->second; - ObjectAssociationMap::iterator j = refs->find(key); - if (j != refs->end()) { - old_association = j->second; - j->second = ObjcAssociation(policy, new_value); - } else { - (*refs)[key] = ObjcAssociation(policy, new_value); - } - } else { - // create the new association (first time). - ObjectAssociationMap *refs = new ObjectAssociationMap; - associations[disguised_object] = refs; - (*refs)[key] = ObjcAssociation(policy, new_value); - object->setHasAssociatedObjects(); - } - } else { - // setting the association to nil breaks the association. - AssociationsHashMap::iterator i = associations.find(disguised_object); - if (i != associations.end()) { - ObjectAssociationMap *refs = i->second; - ObjectAssociationMap::iterator j = refs->find(key); - if (j != refs->end()) { - old_association = j->second; - refs->erase(j); - } - } - } - } - // release the old value (outside of the lock). - if (old_association.hasValue()) ReleaseValue()(old_association); -} - -void _object_remove_assocations(id object) { - vector< ObjcAssociation,ObjcAllocator<ObjcAssociation> > elements; - { - AssociationsManager manager; - AssociationsHashMap &associations(manager.associations()); - if (associations.size() == 0) return; - disguised_ptr_t disguised_object = DISGUISE(object); - AssociationsHashMap::iterator i = associations.find(disguised_object); - if (i != associations.end()) { - // copy all of the associations that need to be removed. - ObjectAssociationMap *refs = i->second; - for (ObjectAssociationMap::iterator j = refs->begin(), end = refs->end(); j != end; ++j) { - elements.push_back(j->second); - } - // remove the secondary table. - delete refs; - associations.erase(i); - } - } - // the calls to releaseValue() happen outside of the lock. - for_each(elements.begin(), elements.end(), ReleaseValue()); -} diff --git a/objc/objc-runtime/runtime/objc-runtime-new.h b/objc/objc-runtime/runtime/objc-runtime-new.h deleted file mode 100644 index cdea941..0000000 --- a/objc/objc-runtime/runtime/objc-runtime-new.h +++ /dev/null @@ -1,1311 +0,0 @@ -/* - * Copyright (c) 2005-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@ - */ - -#ifndef _OBJC_RUNTIME_NEW_H -#define _OBJC_RUNTIME_NEW_H - -#if __LP64__ -typedef uint32_t mask_t; // x86_64 & arm64 asm are less efficient with 16-bits -#else -typedef uint16_t mask_t; -#endif -typedef uintptr_t cache_key_t; - -struct swift_class_t; - - -struct bucket_t { -private: - cache_key_t _key; - IMP _imp; - -public: - inline cache_key_t key() const { return _key; } - inline IMP imp() const { return (IMP)_imp; } - inline void setKey(cache_key_t newKey) { _key = newKey; } - inline void setImp(IMP newImp) { _imp = newImp; } - - void set(cache_key_t newKey, IMP newImp); -}; - - -struct cache_t { - struct bucket_t *_buckets; - mask_t _mask; - mask_t _occupied; - -public: - struct bucket_t *buckets(); - mask_t mask(); - mask_t occupied(); - void incrementOccupied(); - void setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask); - void initializeToEmpty(); - - mask_t capacity(); - bool isConstantEmptyCache(); - bool canBeFreed(); - - static size_t bytesForCapacity(uint32_t cap); - static struct bucket_t * endMarker(struct bucket_t *b, uint32_t cap); - - void expand(); - void reallocate(mask_t oldCapacity, mask_t newCapacity); - struct bucket_t * find(cache_key_t key, id receiver); - - static void bad_cache(id receiver, SEL sel, Class isa) __attribute__((noreturn)); -}; - - -// classref_t is unremapped class_t* -typedef struct classref * classref_t; - -/*********************************************************************** -* entsize_list_tt<Element, List, FlagMask> -* Generic implementation of an array of non-fragile structs. -* -* Element is the struct type (e.g. method_t) -* List is the specialization of entsize_list_tt (e.g. method_list_t) -* FlagMask is used to stash extra bits in the entsize field -* (e.g. method list fixup markers) -**********************************************************************/ -template <typename Element, typename List, uint32_t FlagMask> -struct entsize_list_tt { - uint32_t entsizeAndFlags; - uint32_t count; - Element first; - - uint32_t entsize() const { - return entsizeAndFlags & ~FlagMask; - } - uint32_t flags() const { - return entsizeAndFlags & FlagMask; - } - - Element& getOrEnd(uint32_t i) const { - assert(i <= count); - return *(Element *)((uint8_t *)&first + i*entsize()); - } - Element& get(uint32_t i) const { - assert(i < count); - return getOrEnd(i); - } - - size_t byteSize() const { - return sizeof(*this) + (count-1)*entsize(); - } - - List *duplicate() const { - return (List *)memdup(this, this->byteSize()); - } - - struct iterator; - const iterator begin() const { - return iterator(*static_cast<const List*>(this), 0); - } - iterator begin() { - return iterator(*static_cast<const List*>(this), 0); - } - const iterator end() const { - return iterator(*static_cast<const List*>(this), count); - } - iterator end() { - return iterator(*static_cast<const List*>(this), count); - } - - struct iterator { - uint32_t entsize; - uint32_t index; // keeping track of this saves a divide in operator- - Element* element; - - typedef std::random_access_iterator_tag iterator_category; - typedef Element value_type; - typedef ptrdiff_t difference_type; - typedef Element* pointer; - typedef Element& reference; - - iterator() { } - - iterator(const List& list, uint32_t start = 0) - : entsize(list.entsize()) - , index(start) - , element(&list.getOrEnd(start)) - { } - - const iterator& operator += (ptrdiff_t delta) { - element = (Element*)((uint8_t *)element + delta*entsize); - index += (int32_t)delta; - return *this; - } - const iterator& operator -= (ptrdiff_t delta) { - element = (Element*)((uint8_t *)element - delta*entsize); - index -= (int32_t)delta; - return *this; - } - const iterator operator + (ptrdiff_t delta) const { - return iterator(*this) += delta; - } - const iterator operator - (ptrdiff_t delta) const { - return iterator(*this) -= delta; - } - - iterator& operator ++ () { *this += 1; return *this; } - iterator& operator -- () { *this -= 1; return *this; } - iterator operator ++ (int) { - iterator result(*this); *this += 1; return result; - } - iterator operator -- (int) { - iterator result(*this); *this -= 1; return result; - } - - ptrdiff_t operator - (const iterator& rhs) const { - return (ptrdiff_t)this->index - (ptrdiff_t)rhs.index; - } - - Element& operator * () const { return *element; } - Element* operator -> () const { return element; } - - operator Element& () const { return *element; } - - bool operator == (const iterator& rhs) const { - return this->element == rhs.element; - } - bool operator != (const iterator& rhs) const { - return this->element != rhs.element; - } - - bool operator < (const iterator& rhs) const { - return this->element < rhs.element; - } - bool operator > (const iterator& rhs) const { - return this->element > rhs.element; - } - }; -}; - - -struct method_t { - SEL name; - const char *types; - IMP imp; - - struct SortBySELAddress : - public std::binary_function<const method_t&, - const method_t&, bool> - { - bool operator() (const method_t& lhs, - const method_t& rhs) - { return lhs.name < rhs.name; } - }; -}; - -struct ivar_t { -#if __x86_64__ - // *offset was originally 64-bit on some x86_64 platforms. - // We read and write only 32 bits of it. - // Some metadata provides all 64 bits. This is harmless for unsigned - // little-endian values. - // Some code uses all 64 bits. class_addIvar() over-allocates the - // offset for their benefit. -#endif - int32_t *offset; - const char *name; - const char *type; - // alignment is sometimes -1; use alignment() instead - uint32_t alignment_raw; - uint32_t size; - - uint32_t alignment() const { - if (alignment_raw == ~(uint32_t)0) return 1U << WORD_SHIFT; - return 1 << alignment_raw; - } -}; - -struct property_t { - const char *name; - const char *attributes; -}; - -// Two bits of entsize are used for fixup markers. -struct method_list_t : entsize_list_tt<method_t, method_list_t, 0x3> { - bool isFixedUp() const; - void setFixedUp(); - - uint32_t indexOfMethod(const method_t *meth) const { - uint32_t i = - (uint32_t)(((uintptr_t)meth - (uintptr_t)this) / entsize()); - assert(i < count); - return i; - } -}; - -struct ivar_list_t : entsize_list_tt<ivar_t, ivar_list_t, 0> { -}; - -struct property_list_t : entsize_list_tt<property_t, property_list_t, 0> { -}; - - -typedef uintptr_t protocol_ref_t; // protocol_t *, but unremapped - -// Values for protocol_t->flags -#define PROTOCOL_FIXED_UP_2 (1<<31) // must never be set by compiler -#define PROTOCOL_FIXED_UP_1 (1<<30) // must never be set by compiler - -#define PROTOCOL_FIXED_UP_MASK (PROTOCOL_FIXED_UP_1 | PROTOCOL_FIXED_UP_2) - -struct protocol_t : objc_object { - const char *mangledName; - struct protocol_list_t *protocols; - method_list_t *instanceMethods; - method_list_t *classMethods; - method_list_t *optionalInstanceMethods; - method_list_t *optionalClassMethods; - property_list_t *instanceProperties; - uint32_t size; // sizeof(protocol_t) - uint32_t flags; - // Fields below this point are not always present on disk. - const char **extendedMethodTypes; - const char *_demangledName; - - const char *demangledName(); - - const char *nameForLogging() { - return demangledName(); - } - - bool isFixedUp() const; - void setFixedUp(); - - bool hasExtendedMethodTypesField() const { - return size >= (offsetof(protocol_t, extendedMethodTypes) - + sizeof(extendedMethodTypes)); - } - bool hasExtendedMethodTypes() const { - return hasExtendedMethodTypesField() && extendedMethodTypes; - } -}; - -struct protocol_list_t { - // count is 64-bit by accident. - uintptr_t count; - protocol_ref_t list[0]; // variable-size - - size_t byteSize() const { - return sizeof(*this) + count*sizeof(list[0]); - } - - protocol_list_t *duplicate() const { - return (protocol_list_t *)memdup(this, this->byteSize()); - } - - typedef protocol_ref_t* iterator; - typedef const protocol_ref_t* const_iterator; - - const_iterator begin() const { - return list; - } - iterator begin() { - return list; - } - const_iterator end() const { - return list + count; - } - iterator end() { - return list + count; - } -}; - -struct locstamped_category_t { - category_t *cat; - struct header_info *hi; -}; - -struct locstamped_category_list_t { - uint32_t count; -#if __LP64__ - uint32_t reserved; -#endif - locstamped_category_t list[0]; -}; - - -// class_data_bits_t is the class_t->data field (class_rw_t pointer plus flags) -// The extra bits are optimized for the retain/release and alloc/dealloc paths. - -// Values for class_ro_t->flags -// These are emitted by the compiler and are part of the ABI. -// class is a metaclass -#define RO_META (1<<0) -// class is a root class -#define RO_ROOT (1<<1) -// class has .cxx_construct/destruct implementations -#define RO_HAS_CXX_STRUCTORS (1<<2) -// class has +load implementation -// #define RO_HAS_LOAD_METHOD (1<<3) -// class has visibility=hidden set -#define RO_HIDDEN (1<<4) -// class has attribute(objc_exception): OBJC_EHTYPE_$_ThisClass is non-weak -#define RO_EXCEPTION (1<<5) -// this bit is available for reassignment -// #define RO_REUSE_ME (1<<6) -// class compiled with -fobjc-arc (automatic retain/release) -#define RO_IS_ARR (1<<7) -// class has .cxx_destruct but no .cxx_construct (with RO_HAS_CXX_STRUCTORS) -#define RO_HAS_CXX_DTOR_ONLY (1<<8) - -// class is in an unloadable bundle - must never be set by compiler -#define RO_FROM_BUNDLE (1<<29) -// class is unrealized future class - must never be set by compiler -#define RO_FUTURE (1<<30) -// class is realized - must never be set by compiler -#define RO_REALIZED (1<<31) - -// Values for class_rw_t->flags -// These are not emitted by the compiler and are never used in class_ro_t. -// Their presence should be considered in future ABI versions. -// class_t->data is class_rw_t, not class_ro_t -#define RW_REALIZED (1<<31) -// class is unresolved future class -#define RW_FUTURE (1<<30) -// class is initialized -#define RW_INITIALIZED (1<<29) -// class is initializing -#define RW_INITIALIZING (1<<28) -// class_rw_t->ro is heap copy of class_ro_t -#define RW_COPIED_RO (1<<27) -// class allocated but not yet registered -#define RW_CONSTRUCTING (1<<26) -// class allocated and registered -#define RW_CONSTRUCTED (1<<25) -// GC: class has unsafe finalize method -#define RW_FINALIZE_ON_MAIN_THREAD (1<<24) -// class +load has been called -#define RW_LOADED (1<<23) -#if !SUPPORT_NONPOINTER_ISA -// class instances may have associative references -#define RW_INSTANCES_HAVE_ASSOCIATED_OBJECTS (1<<22) -#endif -// class has instance-specific GC layout -#define RW_HAS_INSTANCE_SPECIFIC_LAYOUT (1 << 21) -// available for use -// #define RW_20 (1<<20) -// class has started realizing but not yet completed it -#define RW_REALIZING (1<<19) - -// NOTE: MORE RW_ FLAGS DEFINED BELOW - - -// Values for class_rw_t->flags or class_t->bits -// These flags are optimized for retain/release and alloc/dealloc -// 64-bit stores more of them in class_t->bits to reduce pointer indirection. - -#if !__LP64__ - -// class or superclass has .cxx_construct implementation -#define RW_HAS_CXX_CTOR (1<<18) -// class or superclass has .cxx_destruct implementation -#define RW_HAS_CXX_DTOR (1<<17) -// class or superclass has default alloc/allocWithZone: implementation -// Note this is is stored in the metaclass. -#define RW_HAS_DEFAULT_AWZ (1<<16) -// class's instances requires raw isa -// not tracked for 32-bit because it only applies to non-pointer isa -// #define RW_REQUIRES_RAW_ISA - -// class is a Swift class -#define FAST_IS_SWIFT (1UL<<0) -// class or superclass has default retain/release/autorelease/retainCount/ -// _tryRetain/_isDeallocating/retainWeakReference/allowsWeakReference -#define FAST_HAS_DEFAULT_RR (1UL<<1) -// data pointer -#define FAST_DATA_MASK 0xfffffffcUL - -#elif 1 -// Leaks-compatible version that steals low bits only. - -// class or superclass has .cxx_construct implementation -#define RW_HAS_CXX_CTOR (1<<18) -// class or superclass has .cxx_destruct implementation -#define RW_HAS_CXX_DTOR (1<<17) -// class or superclass has default alloc/allocWithZone: implementation -// Note this is is stored in the metaclass. -#define RW_HAS_DEFAULT_AWZ (1<<16) - -// class is a Swift class -#define FAST_IS_SWIFT (1UL<<0) -// class or superclass has default retain/release/autorelease/retainCount/ -// _tryRetain/_isDeallocating/retainWeakReference/allowsWeakReference -#define FAST_HAS_DEFAULT_RR (1UL<<1) -// class's instances requires raw isa -#define FAST_REQUIRES_RAW_ISA (1UL<<2) -// data pointer -#define FAST_DATA_MASK 0x00007ffffffffff8UL - -#else -// Leaks-incompatible version that steals lots of bits. - -// class is a Swift class -#define FAST_IS_SWIFT (1UL<<0) -// class's instances requires raw isa -#define FAST_REQUIRES_RAW_ISA (1UL<<1) -// class or superclass has .cxx_destruct implementation -// This bit is aligned with isa_t->hasCxxDtor to save an instruction. -#define FAST_HAS_CXX_DTOR (1UL<<2) -// data pointer -#define FAST_DATA_MASK 0x00007ffffffffff8UL -// class or superclass has .cxx_construct implementation -#define FAST_HAS_CXX_CTOR (1UL<<47) -// class or superclass has default alloc/allocWithZone: implementation -// Note this is is stored in the metaclass. -#define FAST_HAS_DEFAULT_AWZ (1UL<<48) -// class or superclass has default retain/release/autorelease/retainCount/ -// _tryRetain/_isDeallocating/retainWeakReference/allowsWeakReference -#define FAST_HAS_DEFAULT_RR (1UL<<49) -// summary bit for fast alloc path: !hasCxxCtor and -// !requiresRawIsa and instanceSize fits into shiftedSize -#define FAST_ALLOC (1UL<<50) -// instance size in units of 16 bytes -// or 0 if the instance size is too big in this field -// This field must be LAST -#define FAST_SHIFTED_SIZE_SHIFT 51 - -// FAST_ALLOC means -// FAST_HAS_CXX_CTOR is set -// FAST_REQUIRES_RAW_ISA is not set -// FAST_SHIFTED_SIZE is not zero -// FAST_ALLOC does NOT check FAST_HAS_DEFAULT_AWZ because that -// bit is stored on the metaclass. -#define FAST_ALLOC_MASK (FAST_HAS_CXX_CTOR | FAST_REQUIRES_RAW_ISA) -#define FAST_ALLOC_VALUE (0) - -#endif - - -struct class_ro_t { - uint32_t flags; - uint32_t instanceStart; - uint32_t instanceSize; -#ifdef __LP64__ - uint32_t reserved; -#endif - - const uint8_t * ivarLayout; - - const char * name; - method_list_t * baseMethodList; - protocol_list_t * baseProtocols; - const ivar_list_t * ivars; - - const uint8_t * weakIvarLayout; - property_list_t *baseProperties; - - method_list_t *baseMethods() const { - return baseMethodList; - } -}; - - -/*********************************************************************** -* list_array_tt<Element, List> -* Generic implementation for metadata that can be augmented by categories. -* -* Element is the underlying metadata type (e.g. method_t) -* List is the metadata's list type (e.g. method_list_t) -* -* A list_array_tt has one of three values: -* - empty -* - a pointer to a single list -* - an array of pointers to lists -* -* countLists/beginLists/endLists iterate the metadata lists -* count/begin/end iterate the underlying metadata elements -**********************************************************************/ -template <typename Element, typename List> -class list_array_tt { - struct array_t { - uint32_t count; - List* lists[0]; - - static size_t byteSize(uint32_t count) { - return sizeof(array_t) + count*sizeof(lists[0]); - } - size_t byteSize() { - return byteSize(count); - } - }; - - protected: - class iterator { - List **lists; - List **listsEnd; - typename List::iterator m, mEnd; - - public: - iterator(List **begin, List **end) - : lists(begin), listsEnd(end) - { - if (begin != end) { - m = (*begin)->begin(); - mEnd = (*begin)->end(); - } - } - - const Element& operator * () const { - return *m; - } - Element& operator * () { - return *m; - } - - bool operator != (const iterator& rhs) const { - if (lists != rhs.lists) return true; - if (lists == listsEnd) return false; // m is undefined - if (m != rhs.m) return true; - return false; - } - - const iterator& operator ++ () { - assert(m != mEnd); - m++; - if (m == mEnd) { - assert(lists != listsEnd); - lists++; - if (lists != listsEnd) { - m = (*lists)->begin(); - mEnd = (*lists)->end(); - } - } - return *this; - } - }; - - private: - union { - List* list; - uintptr_t arrayAndFlag; - }; - - bool hasArray() const { - return arrayAndFlag & 1; - } - - array_t *array() { - return (array_t *)(arrayAndFlag & ~1); - } - - void setArray(array_t *array) { - arrayAndFlag = (uintptr_t)array | 1; - } - - public: - - uint32_t count() { - uint32_t result = 0; - for (auto lists = beginLists(), end = endLists(); - lists != end; - ++lists) - { - result += (*lists)->count; - } - return result; - } - - iterator begin() { - return iterator(beginLists(), endLists()); - } - - iterator end() { - List **e = endLists(); - return iterator(e, e); - } - - - uint32_t countLists() { - if (hasArray()) { - return array()->count; - } else if (list) { - return 1; - } else { - return 0; - } - } - - List** beginLists() { - if (hasArray()) { - return array()->lists; - } else { - return &list; - } - } - - List** endLists() { - if (hasArray()) { - return array()->lists + array()->count; - } else if (list) { - return &list + 1; - } else { - return &list; - } - } - - void attachLists(List* const * addedLists, uint32_t addedCount) { - if (addedCount == 0) return; - - if (hasArray()) { - // many lists -> many lists - uint32_t oldCount = array()->count; - uint32_t newCount = oldCount + addedCount; - setArray((array_t *)realloc(array(), array_t::byteSize(newCount))); - array()->count = newCount; - memmove(array()->lists + addedCount, array()->lists, - oldCount * sizeof(array()->lists[0])); - memcpy(array()->lists, addedLists, - addedCount * sizeof(array()->lists[0])); - } - else if (!list && addedCount == 1) { - // 0 lists -> 1 list - list = addedLists[0]; - } - else { - // 1 list -> many lists - List* oldList = list; - uint32_t oldCount = oldList ? 1 : 0; - uint32_t newCount = oldCount + addedCount; - setArray((array_t *)malloc(array_t::byteSize(newCount))); - array()->count = newCount; - if (oldList) array()->lists[addedCount] = oldList; - memcpy(array()->lists, addedLists, - addedCount * sizeof(array()->lists[0])); - } - } - - void tryFree() { - if (hasArray()) { - for (uint32_t i = 0; i < array()->count; i++) { - try_free(array()->lists[i]); - } - try_free(array()); - } - else if (list) { - try_free(list); - } - } - - template<typename Result> - Result duplicate() { - Result result; - - if (hasArray()) { - array_t *a = array(); - result.setArray((array_t *)memdup(a, a->byteSize())); - for (uint32_t i = 0; i < a->count; i++) { - result.array()->lists[i] = a->lists[i]->duplicate(); - } - } else if (list) { - result.list = list->duplicate(); - } else { - result.list = nil; - } - - return result; - } -}; - - -class method_array_t : - public list_array_tt<method_t, method_list_t> -{ - typedef list_array_tt<method_t, method_list_t> Super; - - public: - method_list_t **beginCategoryMethodLists() { - return beginLists(); - } - - method_list_t **endCategoryMethodLists(Class cls); - - method_array_t duplicate() { - return Super::duplicate<method_array_t>(); - } -}; - - -class property_array_t : - public list_array_tt<property_t, property_list_t> -{ - typedef list_array_tt<property_t, property_list_t> Super; - - public: - property_array_t duplicate() { - return Super::duplicate<property_array_t>(); - } -}; - - -class protocol_array_t : - public list_array_tt<protocol_ref_t, protocol_list_t> -{ - typedef list_array_tt<protocol_ref_t, protocol_list_t> Super; - - public: - protocol_array_t duplicate() { - return Super::duplicate<protocol_array_t>(); - } -}; - - -struct class_rw_t { - uint32_t flags; - uint32_t version; - - const class_ro_t *ro; - - method_array_t methods; - property_array_t properties; - protocol_array_t protocols; - - Class firstSubclass; - Class nextSiblingClass; - - char *demangledName; - - void setFlags(uint32_t set) - { - OSAtomicOr32Barrier(set, &flags); - } - - void clearFlags(uint32_t clear) - { - OSAtomicXor32Barrier(clear, &flags); - } - - // set and clear must not overlap - void changeFlags(uint32_t set, uint32_t clear) - { - assert((set & clear) == 0); - - uint32_t oldf, newf; - do { - oldf = flags; - newf = (oldf | set) & ~clear; - } while (!OSAtomicCompareAndSwap32Barrier(oldf, newf, (volatile int32_t *)&flags)); - } -}; - - -struct class_data_bits_t { - - // Values are the FAST_ flags above. - uintptr_t bits; -private: - bool getBit(uintptr_t bit) - { - return bits & bit; - } - -#if FAST_ALLOC - static uintptr_t updateFastAlloc(uintptr_t oldBits, uintptr_t change) - { - if (change & FAST_ALLOC_MASK) { - if (((oldBits & FAST_ALLOC_MASK) == FAST_ALLOC_VALUE) && - ((oldBits >> FAST_SHIFTED_SIZE_SHIFT) != 0)) - { - oldBits |= FAST_ALLOC; - } else { - oldBits &= ~FAST_ALLOC; - } - } - return oldBits; - } -#else - static uintptr_t updateFastAlloc(uintptr_t oldBits, uintptr_t change) { - return oldBits; - } -#endif - - void setBits(uintptr_t set) - { - uintptr_t oldBits; - uintptr_t newBits; - do { - oldBits = LoadExclusive(&bits); - newBits = updateFastAlloc(oldBits | set, set); - } while (!StoreReleaseExclusive(&bits, oldBits, newBits)); - } - - void clearBits(uintptr_t clear) - { - uintptr_t oldBits; - uintptr_t newBits; - do { - oldBits = LoadExclusive(&bits); - newBits = updateFastAlloc(oldBits & ~clear, clear); - } while (!StoreReleaseExclusive(&bits, oldBits, newBits)); - } - -public: - - class_rw_t* data() { - return (class_rw_t *)(bits & FAST_DATA_MASK); - } - void setData(class_rw_t *newData) - { - assert(!data() || (newData->flags & (RW_REALIZING | RW_FUTURE))); - // Set during realization or construction only. No locking needed. - bits = (bits & ~FAST_DATA_MASK) | (uintptr_t)newData; - } - - bool hasDefaultRR() { - return getBit(FAST_HAS_DEFAULT_RR); - } - void setHasDefaultRR() { - setBits(FAST_HAS_DEFAULT_RR); - } - void setHasCustomRR() { - clearBits(FAST_HAS_DEFAULT_RR); - } - -#if FAST_HAS_DEFAULT_AWZ - bool hasDefaultAWZ() { - return getBit(FAST_HAS_DEFAULT_AWZ); - } - void setHasDefaultAWZ() { - setBits(FAST_HAS_DEFAULT_AWZ); - } - void setHasCustomAWZ() { - clearBits(FAST_HAS_DEFAULT_AWZ); - } -#else - bool hasDefaultAWZ() { - return data()->flags & RW_HAS_DEFAULT_AWZ; - } - void setHasDefaultAWZ() { - data()->setFlags(RW_HAS_DEFAULT_AWZ); - } - void setHasCustomAWZ() { - data()->clearFlags(RW_HAS_DEFAULT_AWZ); - } -#endif - -#if FAST_HAS_CXX_CTOR - bool hasCxxCtor() { - return getBit(FAST_HAS_CXX_CTOR); - } - void setHasCxxCtor() { - setBits(FAST_HAS_CXX_CTOR); - } -#else - bool hasCxxCtor() { - return data()->flags & RW_HAS_CXX_CTOR; - } - void setHasCxxCtor() { - data()->setFlags(RW_HAS_CXX_CTOR); - } -#endif - -#if FAST_HAS_CXX_DTOR - bool hasCxxDtor() { - return getBit(FAST_HAS_CXX_DTOR); - } - void setHasCxxDtor() { - setBits(FAST_HAS_CXX_DTOR); - } -#else - bool hasCxxDtor() { - return data()->flags & RW_HAS_CXX_DTOR; - } - void setHasCxxDtor() { - data()->setFlags(RW_HAS_CXX_DTOR); - } -#endif - -#if FAST_REQUIRES_RAW_ISA - bool requiresRawIsa() { - return getBit(FAST_REQUIRES_RAW_ISA); - } - void setRequiresRawIsa() { - setBits(FAST_REQUIRES_RAW_ISA); - } -#else -# if SUPPORT_NONPOINTER_ISA -# error oops -# endif - bool requiresRawIsa() { - return true; - } - void setRequiresRawIsa() { - // nothing - } -#endif - -#if FAST_ALLOC - size_t fastInstanceSize() - { - assert(bits & FAST_ALLOC); - return (bits >> FAST_SHIFTED_SIZE_SHIFT) * 16; - } - void setFastInstanceSize(size_t newSize) - { - // Set during realization or construction only. No locking needed. - assert(data()->flags & RW_REALIZING); - - // Round up to 16-byte boundary, then divide to get 16-byte units - newSize = ((newSize + 15) & ~15) / 16; - - uintptr_t newBits = newSize << FAST_SHIFTED_SIZE_SHIFT; - if ((newBits >> FAST_SHIFTED_SIZE_SHIFT) == newSize) { - int shift = WORD_BITS - FAST_SHIFTED_SIZE_SHIFT; - uintptr_t oldBits = (bits << shift) >> shift; - if ((oldBits & FAST_ALLOC_MASK) == FAST_ALLOC_VALUE) { - newBits |= FAST_ALLOC; - } - bits = oldBits | newBits; - } - } - - bool canAllocFast() { - return bits & FAST_ALLOC; - } -#else - size_t fastInstanceSize() { - abort(); - } - void setFastInstanceSize(size_t) { - // nothing - } - bool canAllocFast() { - return false; - } -#endif - - bool isSwift() { - return getBit(FAST_IS_SWIFT); - } - - void setIsSwift() { - setBits(FAST_IS_SWIFT); - } -}; - - -struct objc_class : objc_object { - // Class ISA; - Class superclass; - cache_t cache; // formerly cache pointer and vtable - class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags - - class_rw_t *data() { - return bits.data(); - } - void setData(class_rw_t *newData) { - bits.setData(newData); - } - - void setInfo(uint32_t set) { - assert(isFuture() || isRealized()); - data()->setFlags(set); - } - - void clearInfo(uint32_t clear) { - assert(isFuture() || isRealized()); - data()->clearFlags(clear); - } - - // set and clear must not overlap - void changeInfo(uint32_t set, uint32_t clear) { - assert(isFuture() || isRealized()); - assert((set & clear) == 0); - data()->changeFlags(set, clear); - } - - bool hasCustomRR() { - return ! bits.hasDefaultRR(); - } - void setHasDefaultRR() { - assert(isInitializing()); - bits.setHasDefaultRR(); - } - void setHasCustomRR(bool inherited = false); - void printCustomRR(bool inherited); - - bool hasCustomAWZ() { - return ! bits.hasDefaultAWZ(); - } - void setHasDefaultAWZ() { - assert(isInitializing()); - bits.setHasDefaultAWZ(); - } - void setHasCustomAWZ(bool inherited = false); - void printCustomAWZ(bool inherited); - - bool requiresRawIsa() { - return bits.requiresRawIsa(); - } - void setRequiresRawIsa(bool inherited = false); - void printRequiresRawIsa(bool inherited); - - bool canAllocIndexed() { - assert(!isFuture()); - return !requiresRawIsa(); - } - bool canAllocFast() { - assert(!isFuture()); - return bits.canAllocFast(); - } - - - bool hasCxxCtor() { - // addSubclass() propagates this flag from the superclass. - assert(isRealized()); - return bits.hasCxxCtor(); - } - void setHasCxxCtor() { - bits.setHasCxxCtor(); - } - - bool hasCxxDtor() { - // addSubclass() propagates this flag from the superclass. - assert(isRealized()); - return bits.hasCxxDtor(); - } - void setHasCxxDtor() { - bits.setHasCxxDtor(); - } - - - bool isSwift() { - return bits.isSwift(); - } - - -#if SUPPORT_NONPOINTER_ISA - // Tracked in non-pointer isas; not tracked otherwise -#else - bool instancesHaveAssociatedObjects() { - // this may be an unrealized future class in the CF-bridged case - assert(isFuture() || isRealized()); - return data()->flags & RW_INSTANCES_HAVE_ASSOCIATED_OBJECTS; - } - - void setInstancesHaveAssociatedObjects() { - // this may be an unrealized future class in the CF-bridged case - assert(isFuture() || isRealized()); - setInfo(RW_INSTANCES_HAVE_ASSOCIATED_OBJECTS); - } -#endif - - bool shouldGrowCache() { - return true; - } - - void setShouldGrowCache(bool) { - // fixme good or bad for memory use? - } - - bool shouldFinalizeOnMainThread() { - // finishInitializing() propagates this flag from the superclass. - assert(isRealized()); - return data()->flags & RW_FINALIZE_ON_MAIN_THREAD; - } - - void setShouldFinalizeOnMainThread() { - assert(isRealized()); - setInfo(RW_FINALIZE_ON_MAIN_THREAD); - } - - bool isInitializing() { - return getMeta()->data()->flags & RW_INITIALIZING; - } - - void setInitializing() { - assert(!isMetaClass()); - ISA()->setInfo(RW_INITIALIZING); - } - - bool isInitialized() { - return getMeta()->data()->flags & RW_INITIALIZED; - } - - void setInitialized(); - - bool isLoadable() { - assert(isRealized()); - return true; // any class registered for +load is definitely loadable - } - - IMP getLoadMethod(); - - // Locking: To prevent concurrent realization, hold runtimeLock. - bool isRealized() { - return data()->flags & RW_REALIZED; - } - - // Returns true if this is an unrealized future class. - // Locking: To prevent concurrent realization, hold runtimeLock. - bool isFuture() { - return data()->flags & RW_FUTURE; - } - - bool isMetaClass() { - assert(this); - assert(isRealized()); - return data()->ro->flags & RO_META; - } - - // NOT identical to this->ISA when this is a metaclass - Class getMeta() { - if (isMetaClass()) return (Class)this; - else return this->ISA(); - } - - bool isRootClass() { - return superclass == nil; - } - bool isRootMetaclass() { - return ISA() == (Class)this; - } - - const char *mangledName() { - // fixme can't assert locks here - assert(this); - - if (isRealized() || isFuture()) { - return data()->ro->name; - } else { - return ((const class_ro_t *)data())->name; - } - } - - const char *demangledName(bool realize = false); - const char *nameForLogging(); - - // May be unaligned depending on class's ivars. - uint32_t unalignedInstanceSize() { - assert(isRealized()); - return data()->ro->instanceSize; - } - - // Class's ivar size rounded up to a pointer-size boundary. - uint32_t alignedInstanceSize() { - return word_align(unalignedInstanceSize()); - } - - size_t instanceSize(size_t extraBytes) { - size_t size = alignedInstanceSize() + extraBytes; - // CF requires all objects be at least 16 bytes. - if (size < 16) size = 16; - return size; - } - - void setInstanceSize(uint32_t newSize) { - assert(isRealized()); - if (newSize != data()->ro->instanceSize) { - assert(data()->flags & RW_COPIED_RO); - *const_cast<uint32_t *>(&data()->ro->instanceSize) = newSize; - } - bits.setFastInstanceSize(newSize); - } -}; - - -struct swift_class_t : objc_class { - uint32_t flags; - uint32_t instanceAddressOffset; - uint32_t instanceSize; - uint16_t instanceAlignMask; - uint16_t reserved; - - uint32_t classSize; - uint32_t classAddressOffset; - void *description; - // ... - - void *baseAddress() { - return (void *)((uint8_t *)this - classAddressOffset); - } -}; - - -struct category_t { - const char *name; - classref_t cls; - struct method_list_t *instanceMethods; - struct method_list_t *classMethods; - struct protocol_list_t *protocols; - struct property_list_t *instanceProperties; - - method_list_t *methodsForMeta(bool isMeta) { - if (isMeta) return classMethods; - else return instanceMethods; - } - - property_list_t *propertiesForMeta(bool isMeta) { - if (isMeta) return nil; // classProperties; - else return instanceProperties; - } -}; - -struct objc_super2 { - id receiver; - Class current_class; -}; - -struct message_ref_t { - IMP imp; - SEL sel; -}; - - -extern Method protocol_getMethod(protocol_t *p, SEL sel, bool isRequiredMethod, bool isInstanceMethod, bool recursive); - -static inline void -foreach_realized_class_and_subclass_2(Class top, bool (^code)(Class)) -{ - // runtimeLock.assertWriting(); - assert(top); - Class cls = top; - while (1) { - if (!code(cls)) break; - - if (cls->data()->firstSubclass) { - cls = cls->data()->firstSubclass; - } else { - while (!cls->data()->nextSiblingClass && cls != top) { - cls = cls->superclass; - } - if (cls == top) break; - cls = cls->data()->nextSiblingClass; - } - } -} - -static inline void -foreach_realized_class_and_subclass(Class top, void (^code)(Class)) -{ - foreach_realized_class_and_subclass_2(top, ^bool(Class cls) { - code(cls); return true; - }); -} - -#endif diff --git a/objc/objc-runtime/runtime/objc-runtime-new.mm b/objc/objc-runtime/runtime/objc-runtime-new.mm deleted file mode 100644 index 26a6901..0000000 --- a/objc/objc-runtime/runtime/objc-runtime-new.mm +++ /dev/null @@ -1,6708 +0,0 @@ -/* - * Copyright (c) 2005-2009 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@ - */ - -/*********************************************************************** -* objc-runtime-new.m -* Support for new-ABI classes and images. -**********************************************************************/ - -#if __OBJC2__ - -#include "objc-private.h" -#include "objc-runtime-new.h" -#include "objc-file.h" -#include "objc-cache.h" -#include <Block.h> -#include <objc/message.h> -#include <mach/shared_region.h> - -#define newprotocol(p) ((protocol_t *)p) - -static void disableTaggedPointers(); -static void detach_class(Class cls, bool isMeta); -static void free_class(Class cls); -static Class setSuperclass(Class cls, Class newSuper); -static Class realizeClass(Class cls); -static method_t *getMethodNoSuper_nolock(Class cls, SEL sel); -static method_t *getMethod_nolock(Class cls, SEL sel); -static IMP addMethod(Class cls, SEL name, IMP imp, const char *types, bool replace); -static NXHashTable *realizedClasses(void); -static bool isRRSelector(SEL sel); -static bool isAWZSelector(SEL sel); -static bool methodListImplementsRR(const method_list_t *mlist); -static bool methodListImplementsAWZ(const method_list_t *mlist); -static void updateCustomRR_AWZ(Class cls, method_t *meth); -static method_t *search_method_list(const method_list_t *mlist, SEL sel); -static void flushCaches(Class cls); -#if SUPPORT_FIXUP -static void fixupMessageRef(message_ref_t *msg); -#endif - -static bool MetaclassNSObjectAWZSwizzled; -static bool ClassNSObjectRRSwizzled; - -#define SDK_FORMAT "%hu.%hhu.%hhu" -#define FORMAT_SDK(v) \ - (unsigned short)(((uint32_t)(v))>>16), \ - (unsigned char)(((uint32_t)(v))>>8), \ - (unsigned char)(((uint32_t)(v))>>0) - - -id objc_noop_imp(id self, SEL _cmd __unused) { - return self; -} - - -/*********************************************************************** -* Lock management -**********************************************************************/ -rwlock_t runtimeLock; -rwlock_t selLock; -mutex_t cacheUpdateLock; -recursive_mutex_t loadMethodLock; - -#if SUPPORT_QOS_HACK -pthread_priority_t BackgroundPriority = 0; -pthread_priority_t MainPriority = 0; -# if DEBUG -static __unused void destroyQOSKey(void *arg) { - _objc_fatal("QoS override level at thread exit is %zu instead of zero", - (size_t)(uintptr_t)arg); -} -# endif -#endif - -void lock_init(void) -{ -#if SUPPORT_QOS_HACK - BackgroundPriority = _pthread_qos_class_encode(QOS_CLASS_BACKGROUND, 0, 0); - MainPriority = _pthread_qos_class_encode(qos_class_main(), 0, 0); -# if DEBUG - pthread_key_init_np(QOS_KEY, &destroyQOSKey); -# endif -#endif -} - - -/*********************************************************************** -* Non-pointer isa decoding -**********************************************************************/ -#if SUPPORT_NONPOINTER_ISA - -const uintptr_t objc_debug_isa_class_mask = ISA_MASK; -const uintptr_t objc_debug_isa_magic_mask = ISA_MAGIC_MASK; -const uintptr_t objc_debug_isa_magic_value = ISA_MAGIC_VALUE; - -// die if masks overlap -STATIC_ASSERT((ISA_MASK & ISA_MAGIC_MASK) == 0); - -// die if magic is wrong -STATIC_ASSERT((~ISA_MAGIC_MASK & ISA_MAGIC_VALUE) == 0); - -// die if virtual address space bound goes up -STATIC_ASSERT((~ISA_MASK & MACH_VM_MAX_ADDRESS) == 0 || - ISA_MASK + sizeof(void*) == MACH_VM_MAX_ADDRESS); - -#else - -// These variables exist but enforce pointer alignment only. -const uintptr_t objc_debug_isa_class_mask = (~WORD_MASK); -const uintptr_t objc_debug_isa_magic_mask = WORD_MASK; -const uintptr_t objc_debug_isa_magic_value = 0; - -#endif - - -typedef locstamped_category_list_t category_list; - - -/* - Low two bits of mlist->entsize is used as the fixed-up marker. - PREOPTIMIZED VERSION: - Method lists from shared cache are 1 (uniqued) or 3 (uniqued and sorted). - (Protocol method lists are not sorted because of their extra parallel data) - Runtime fixed-up method lists get 3. - UN-PREOPTIMIZED VERSION: - Method lists from shared cache are 1 (uniqued) or 3 (uniqued and sorted) - Shared cache's sorting and uniquing are not trusted, but do affect the - location of the selector name string. - Runtime fixed-up method lists get 2. - - High two bits of protocol->flags is used as the fixed-up marker. - PREOPTIMIZED VERSION: - Protocols from shared cache are 1<<30. - Runtime fixed-up protocols get 1<<30. - UN-PREOPTIMIZED VERSION: - Protocols from shared cache are 1<<30. - Shared cache's fixups are not trusted. - Runtime fixed-up protocols get 3<<30. -*/ - -static uint32_t fixed_up_method_list = 3; -static uint32_t fixed_up_protocol = PROTOCOL_FIXED_UP_1; - -void -disableSharedCacheOptimizations(void) -{ - fixed_up_method_list = 2; - fixed_up_protocol = PROTOCOL_FIXED_UP_1 | PROTOCOL_FIXED_UP_2; -} - -bool method_list_t::isFixedUp() const { - return flags() == fixed_up_method_list; -} - -void method_list_t::setFixedUp() { - runtimeLock.assertWriting(); - assert(!isFixedUp()); - entsizeAndFlags = entsize() | fixed_up_method_list; -} - -bool protocol_t::isFixedUp() const { - return (flags & PROTOCOL_FIXED_UP_MASK) == fixed_up_protocol; -} - -void protocol_t::setFixedUp() { - runtimeLock.assertWriting(); - assert(!isFixedUp()); - flags = (flags & ~PROTOCOL_FIXED_UP_MASK) | fixed_up_protocol; -} - - -method_list_t **method_array_t::endCategoryMethodLists(Class cls) -{ - method_list_t **mlists = beginLists(); - method_list_t **mlistsEnd = endLists(); - - if (mlists == mlistsEnd || !cls->data()->ro->baseMethods()) - { - // No methods, or no base methods. - // Everything here is a category method. - return mlistsEnd; - } - - // Have base methods. Category methods are - // everything except the last method list. - return mlistsEnd - 1; -} - -static const char *sel_cname(SEL sel) -{ - return (const char *)(void *)sel; -} - - -static size_t protocol_list_size(const protocol_list_t *plist) -{ - return sizeof(protocol_list_t) + plist->count * sizeof(protocol_t *); -} - - -static void try_free(const void *p) -{ - if (p && malloc_size(p)) free((void *)p); -} - - -static Class -alloc_class_for_subclass(Class supercls, size_t extraBytes) -{ - if (!supercls || !supercls->isSwift()) { - return _calloc_class(sizeof(objc_class) + extraBytes); - } - - // Superclass is a Swift class. New subclass must duplicate its extra bits. - - // Allocate the new class, with space for super's prefix and suffix - // and self's extraBytes. - swift_class_t *swiftSupercls = (swift_class_t *)supercls; - size_t superSize = swiftSupercls->classSize; - void *superBits = swiftSupercls->baseAddress(); - void *bits = malloc(superSize + extraBytes); - - // Copy all of the superclass's data to the new class. - memcpy(bits, superBits, superSize); - - // Erase the objc data and the Swift description in the new class. - swift_class_t *swcls = (swift_class_t *) - ((uint8_t *)bits + swiftSupercls->classAddressOffset); - bzero(swcls, sizeof(objc_class)); - swcls->description = nil; - - // Mark this class as Swift-enhanced. - swcls->bits.setIsSwift(); - - return (Class)swcls; -} - - -/*********************************************************************** -* object_getIndexedIvars. -**********************************************************************/ -void *object_getIndexedIvars(id obj) -{ - uint8_t *base = (uint8_t *)obj; - - if (!obj) return nil; - if (obj->isTaggedPointer()) return nil; - - if (!obj->isClass()) return base + obj->ISA()->alignedInstanceSize(); - - Class cls = (Class)obj; - if (!cls->isSwift()) return base + sizeof(objc_class); - - swift_class_t *swcls = (swift_class_t *)cls; - return base - swcls->classAddressOffset + word_align(swcls->classSize); -} - - -/*********************************************************************** -* make_ro_writeable -* Reallocates rw->ro if necessary to make it writeable. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static class_ro_t *make_ro_writeable(class_rw_t *rw) -{ - runtimeLock.assertWriting(); - - if (rw->flags & RW_COPIED_RO) { - // already writeable, do nothing - } else { - class_ro_t *ro = (class_ro_t *) - memdup(rw->ro, sizeof(*rw->ro)); - rw->ro = ro; - rw->flags |= RW_COPIED_RO; - } - return (class_ro_t *)rw->ro; -} - - -/*********************************************************************** -* unattachedCategories -* Returns the class => categories map of unattached categories. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static NXMapTable *unattachedCategories(void) -{ - runtimeLock.assertWriting(); - - static NXMapTable *category_map = nil; - - if (category_map) return category_map; - - // fixme initial map size - category_map = NXCreateMapTable(NXPtrValueMapPrototype, 16); - - return category_map; -} - - -/*********************************************************************** -* addUnattachedCategoryForClass -* Records an unattached category. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static void addUnattachedCategoryForClass(category_t *cat, Class cls, - header_info *catHeader) -{ - runtimeLock.assertWriting(); - - // DO NOT use cat->cls! cls may be cat->cls->isa instead - NXMapTable *cats = unattachedCategories(); - category_list *list; - - list = (category_list *)NXMapGet(cats, cls); - if (!list) { - list = (category_list *) - calloc(sizeof(*list) + sizeof(list->list[0]), 1); - } else { - list = (category_list *) - realloc(list, sizeof(*list) + sizeof(list->list[0]) * (list->count + 1)); - } - list->list[list->count++] = (locstamped_category_t){cat, catHeader}; - NXMapInsert(cats, cls, list); -} - - -/*********************************************************************** -* removeUnattachedCategoryForClass -* Removes an unattached category. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static void removeUnattachedCategoryForClass(category_t *cat, Class cls) -{ - runtimeLock.assertWriting(); - - // DO NOT use cat->cls! cls may be cat->cls->isa instead - NXMapTable *cats = unattachedCategories(); - category_list *list; - - list = (category_list *)NXMapGet(cats, cls); - if (!list) return; - - uint32_t i; - for (i = 0; i < list->count; i++) { - if (list->list[i].cat == cat) { - // shift entries to preserve list order - memmove(&list->list[i], &list->list[i+1], - (list->count-i-1) * sizeof(list->list[i])); - list->count--; - return; - } - } -} - - -/*********************************************************************** -* unattachedCategoriesForClass -* Returns the list of unattached categories for a class, and -* deletes them from the list. -* The result must be freed by the caller. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static category_list * -unattachedCategoriesForClass(Class cls, bool realizing) -{ - runtimeLock.assertWriting(); - return (category_list *)NXMapRemove(unattachedCategories(), cls); -} - - -/*********************************************************************** -* removeAllUnattachedCategoriesForClass -* Deletes all unattached categories (loaded or not) for a class. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static void removeAllUnattachedCategoriesForClass(Class cls) -{ - runtimeLock.assertWriting(); - - void *list = NXMapRemove(unattachedCategories(), cls); - if (list) free(list); -} - - -/*********************************************************************** -* classNSObject -* Returns class NSObject. -* Locking: none -**********************************************************************/ -static Class classNSObject(void) -{ - extern objc_class OBJC_CLASS_$_NSObject; - return (Class)&OBJC_CLASS_$_NSObject; -} - - -/*********************************************************************** -* printReplacements -* Implementation of PrintReplacedMethods / OBJC_PRINT_REPLACED_METHODS. -* Warn about methods from cats that override other methods in cats or cls. -* Assumes no methods from cats have been added to cls yet. -**********************************************************************/ -static void printReplacements(Class cls, category_list *cats) -{ - uint32_t c; - bool isMeta = cls->isMetaClass(); - - if (!cats) return; - - // Newest categories are LAST in cats - // Later categories override earlier ones. - for (c = 0; c < cats->count; c++) { - category_t *cat = cats->list[c].cat; - - method_list_t *mlist = cat->methodsForMeta(isMeta); - if (!mlist) continue; - - for (const auto& meth : *mlist) { - SEL s = sel_registerName(sel_cname(meth.name)); - - // Don't warn about GC-ignored selectors - if (ignoreSelector(s)) continue; - - // Search for replaced methods in method lookup order. - // Complain about the first duplicate only. - - // Look for method in earlier categories - for (uint32_t c2 = 0; c2 < c; c2++) { - category_t *cat2 = cats->list[c2].cat; - - const method_list_t *mlist2 = cat2->methodsForMeta(isMeta); - if (!mlist2) continue; - - for (const auto& meth2 : *mlist2) { - SEL s2 = sel_registerName(sel_cname(meth2.name)); - if (s == s2) { - logReplacedMethod(cls->nameForLogging(), s, - cls->isMetaClass(), cat->name, - meth2.imp, meth.imp); - goto complained; - } - } - } - - // Look for method in cls - for (const auto& meth2 : cls->data()->methods) { - SEL s2 = sel_registerName(sel_cname(meth2.name)); - if (s == s2) { - logReplacedMethod(cls->nameForLogging(), s, - cls->isMetaClass(), cat->name, - meth2.imp, meth.imp); - goto complained; - } - } - - complained: - ; - } - } -} - - -static bool isBundleClass(Class cls) -{ - return cls->data()->ro->flags & RO_FROM_BUNDLE; -} - - -static void -fixupMethodList(method_list_t *mlist, bool bundleCopy, bool sort) -{ - runtimeLock.assertWriting(); - assert(!mlist->isFixedUp()); - - // fixme lock less in attachMethodLists ? - sel_lock(); - - // Unique selectors in list. - for (auto& meth : *mlist) { - const char *name = sel_cname(meth.name); - - SEL sel = sel_registerNameNoLock(name, bundleCopy); - meth.name = sel; - - if (ignoreSelector(sel)) { - meth.imp = (IMP)&_objc_ignored_method; - } - } - - sel_unlock(); - - // Sort by selector address. - if (sort) { - method_t::SortBySELAddress sorter; - std::stable_sort(mlist->begin(), mlist->end(), sorter); - } - - // Mark method list as uniqued and sorted - mlist->setFixedUp(); -} - - -static void -prepareMethodLists(Class cls, method_list_t **addedLists, int addedCount, - bool baseMethods, bool methodsFromBundle) -{ - runtimeLock.assertWriting(); - - if (addedCount == 0) return; - - // Don't scan redundantly - bool scanForCustomRR = !UseGC && !cls->hasCustomRR(); - bool scanForCustomAWZ = !UseGC && !cls->hasCustomAWZ(); - - // There exist RR/AWZ special cases for some class's base methods. - // But this code should never need to scan base methods for RR/AWZ: - // default RR/AWZ cannot be set before setInitialized(). - // Therefore we need not handle any special cases here. - if (baseMethods) { - assert(!scanForCustomRR && !scanForCustomAWZ); - } - - // Add method lists to array. - // Reallocate un-fixed method lists. - // The new methods are PREPENDED to the method list array. - - for (int i = 0; i < addedCount; i++) { - method_list_t *mlist = addedLists[i]; - assert(mlist); - - // Fixup selectors if necessary - if (!mlist->isFixedUp()) { - fixupMethodList(mlist, methodsFromBundle, true/*sort*/); - } - - // Scan for method implementations tracked by the class's flags - if (scanForCustomRR && methodListImplementsRR(mlist)) { - cls->setHasCustomRR(); - scanForCustomRR = false; - } - if (scanForCustomAWZ && methodListImplementsAWZ(mlist)) { - cls->setHasCustomAWZ(); - scanForCustomAWZ = false; - } - } -} - - -// Attach method lists and properties and protocols from categories to a class. -// Assumes the categories in cats are all loaded and sorted by load order, -// oldest categories first. -static void -attachCategories(Class cls, category_list *cats, bool flush_caches) -{ - if (!cats) return; - if (PrintReplacedMethods) printReplacements(cls, cats); - - bool isMeta = cls->isMetaClass(); - - // fixme rearrange to remove these intermediate allocations - method_list_t **mlists = (method_list_t **) - malloc(cats->count * sizeof(*mlists)); - property_list_t **proplists = (property_list_t **) - malloc(cats->count * sizeof(*proplists)); - protocol_list_t **protolists = (protocol_list_t **) - malloc(cats->count * sizeof(*protolists)); - - // Count backwards through cats to get newest categories first - int mcount = 0; - int propcount = 0; - int protocount = 0; - int i = cats->count; - bool fromBundle = NO; - while (i--) { - auto& entry = cats->list[i]; - - method_list_t *mlist = entry.cat->methodsForMeta(isMeta); - if (mlist) { - mlists[mcount++] = mlist; - fromBundle |= entry.hi->isBundle(); - } - - property_list_t *proplist = entry.cat->propertiesForMeta(isMeta); - if (proplist) { - proplists[propcount++] = proplist; - } - - protocol_list_t *protolist = entry.cat->protocols; - if (protolist) { - protolists[protocount++] = protolist; - } - } - - auto rw = cls->data(); - - prepareMethodLists(cls, mlists, mcount, NO, fromBundle); - rw->methods.attachLists(mlists, mcount); - free(mlists); - if (flush_caches && mcount > 0) flushCaches(cls); - - rw->properties.attachLists(proplists, propcount); - free(proplists); - - rw->protocols.attachLists(protolists, protocount); - free(protolists); -} - - -/*********************************************************************** -* methodizeClass -* Fixes up cls's method list, protocol list, and property list. -* Attaches any outstanding categories. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void methodizeClass(Class cls) -{ - runtimeLock.assertWriting(); - - bool isMeta = cls->isMetaClass(); - auto rw = cls->data(); - auto ro = rw->ro; - - // Methodizing for the first time - if (PrintConnecting) { - _objc_inform("CLASS: methodizing class '%s' %s", - cls->nameForLogging(), isMeta ? "(meta)" : ""); - } - - // Install methods and properties that the class implements itself. - method_list_t *list = ro->baseMethods(); - if (list) { - prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls)); - rw->methods.attachLists(&list, 1); - } - - property_list_t *proplist = ro->baseProperties; - if (proplist) { - rw->properties.attachLists(&proplist, 1); - } - - protocol_list_t *protolist = ro->baseProtocols; - if (protolist) { - rw->protocols.attachLists(&protolist, 1); - } - - // Root classes get bonus method implementations if they don't have - // them already. These apply before category replacements. - if (cls->isRootMetaclass()) { - // root metaclass - addMethod(cls, SEL_initialize, (IMP)&objc_noop_imp, "", NO); - } - - // Attach categories. - category_list *cats = unattachedCategoriesForClass(cls, true /*realizing*/); - attachCategories(cls, cats, false /*don't flush caches*/); - - if (PrintConnecting) { - if (cats) { - for (uint32_t i = 0; i < cats->count; i++) { - _objc_inform("CLASS: attached category %c%s(%s)", - isMeta ? '+' : '-', - cls->nameForLogging(), cats->list[i].cat->name); - } - } - } - - if (cats) free(cats); - -#if DEBUG - // Debug: sanity-check all SELs; log method list contents - for (const auto& meth : rw->methods) { - if (PrintConnecting) { - _objc_inform("METHOD %c[%s %s]", isMeta ? '+' : '-', - cls->nameForLogging(), sel_getName(meth.name)); - } - assert(ignoreSelector(meth.name) || - sel_registerName(sel_getName(meth.name)) == meth.name); - } -#endif -} - - -/*********************************************************************** -* remethodizeClass -* Attach outstanding categories to an existing class. -* Fixes up cls's method list, protocol list, and property list. -* Updates method caches for cls and its subclasses. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void remethodizeClass(Class cls) -{ - category_list *cats; - bool isMeta; - - runtimeLock.assertWriting(); - - isMeta = cls->isMetaClass(); - - // Re-methodizing: check for more categories - if ((cats = unattachedCategoriesForClass(cls, false/*not realizing*/))) { - if (PrintConnecting) { - _objc_inform("CLASS: attaching categories to class '%s' %s", - cls->nameForLogging(), isMeta ? "(meta)" : ""); - } - - attachCategories(cls, cats, true /*flush caches*/); - free(cats); - } -} - - -/*********************************************************************** -* nonMetaClasses -* Returns the secondary metaclass => class map -* Used for some cases of +initialize and +resolveClassMethod:. -* This map does not contain all class and metaclass pairs. It only -* contains metaclasses whose classes would be in the runtime-allocated -* named-class table, but are not because some other class with the same name -* is in that table. -* Classes with no duplicates are not included. -* Classes in the preoptimized named-class table are not included. -* Classes whose duplicates are in the preoptimized table are not included. -* Most code should use getNonMetaClass() instead of reading this table. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static NXMapTable *nonmeta_class_map = nil; -static NXMapTable *nonMetaClasses(void) -{ - runtimeLock.assertLocked(); - - if (nonmeta_class_map) return nonmeta_class_map; - - // nonmeta_class_map is typically small - INIT_ONCE_PTR(nonmeta_class_map, - NXCreateMapTable(NXPtrValueMapPrototype, 32), - NXFreeMapTable(v)); - - return nonmeta_class_map; -} - - -/*********************************************************************** -* addNonMetaClass -* Adds metacls => cls to the secondary metaclass map -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void addNonMetaClass(Class cls) -{ - runtimeLock.assertWriting(); - void *old; - old = NXMapInsert(nonMetaClasses(), cls->ISA(), cls); - - assert(!cls->isMetaClass()); - assert(cls->ISA()->isMetaClass()); - assert(!old); -} - - -static void removeNonMetaClass(Class cls) -{ - runtimeLock.assertWriting(); - NXMapRemove(nonMetaClasses(), cls->ISA()); -} - - -static bool scanMangledField(const char *&string, const char *end, - const char *&field, int& length) -{ - // Leading zero not allowed. - if (*string == '0') return false; - - length = 0; - field = string; - while (field < end) { - char c = *field; - if (!isdigit(c)) break; - field++; - if (__builtin_smul_overflow(length, 10, &length)) return false; - if (__builtin_sadd_overflow(length, c - '0', &length)) return false; - } - - string = field + length; - return length > 0 && string <= end; -} - - -/*********************************************************************** -* copySwiftV1DemangledName -* Returns the pretty form of the given Swift-v1-mangled class or protocol name. -* Returns nil if the string doesn't look like a mangled Swift v1 name. -* The result must be freed with free(). -**********************************************************************/ -static char *copySwiftV1DemangledName(const char *string, bool isProtocol = false) -{ - if (!string) return nil; - - // Swift mangling prefix. - if (strncmp(string, isProtocol ? "_TtP" : "_TtC", 4) != 0) return nil; - string += 4; - - const char *end = string + strlen(string); - - // Module name. - const char *prefix; - int prefixLength; - if (strncmp(string, "Ss", 2) == 0) { - prefix = "Swift"; - prefixLength = 5; - string += 2; - } else { - if (! scanMangledField(string, end, prefix, prefixLength)) return nil; - } - - // Class or protocol name. - const char *suffix; - int suffixLength; - if (! scanMangledField(string, end, suffix, suffixLength)) return nil; - - if (isProtocol) { - // Remainder must be "_". - if (strcmp(string, "_") != 0) return nil; - } else { - // Remainder must be empty. - if (string != end) return nil; - } - - char *result; - asprintf(&result, "%.*s.%.*s", prefixLength,prefix, suffixLength,suffix); - return result; -} - - -/*********************************************************************** -* copySwiftV1MangledName -* Returns the Swift 1.0 mangled form of the given class or protocol name. -* Returns nil if the string doesn't look like an unmangled Swift name. -* The result must be freed with free(). -**********************************************************************/ -static char *copySwiftV1MangledName(const char *string, bool isProtocol = false) -{ - if (!string) return nil; - - size_t dotCount = 0; - size_t dotIndex; - const char *s; - for (s = string; *s; s++) { - if (*s == '.') { - dotCount++; - dotIndex = s - string; - } - } - size_t stringLength = s - string; - - if (dotCount != 1 || dotIndex == 0 || dotIndex >= stringLength-1) { - return nil; - } - - const char *prefix = string; - size_t prefixLength = dotIndex; - const char *suffix = string + dotIndex + 1; - size_t suffixLength = stringLength - (dotIndex + 1); - - char *name; - - if (prefixLength == 5 && memcmp(prefix, "Swift", 5) == 0) { - asprintf(&name, "_Tt%cSs%zu%.*s%s", - isProtocol ? 'P' : 'C', - suffixLength, (int)suffixLength, suffix, - isProtocol ? "_" : ""); - } else { - asprintf(&name, "_Tt%c%zu%.*s%zu%.*s%s", - isProtocol ? 'P' : 'C', - prefixLength, (int)prefixLength, prefix, - suffixLength, (int)suffixLength, suffix, - isProtocol ? "_" : ""); - } - return name; -} - - -/*********************************************************************** -* getClass -* Looks up a class by name. The class MIGHT NOT be realized. -* Demangled Swift names are recognized. -* Locking: runtimeLock must be read- or write-locked by the caller. -**********************************************************************/ - -// This is a misnomer: gdb_objc_realized_classes is actually a list of -// named classes not in the dyld shared cache, whether realized or not. -NXMapTable *gdb_objc_realized_classes; // exported for debuggers in objc-gdb.h - -static Class getClass_impl(const char *name) -{ - runtimeLock.assertLocked(); - - // allocated in _read_images - assert(gdb_objc_realized_classes); - - // Try runtime-allocated table - Class result = (Class)NXMapGet(gdb_objc_realized_classes, name); - if (result) return result; - - // Try table from dyld shared cache - return getPreoptimizedClass(name); -} - -static Class getClass(const char *name) -{ - runtimeLock.assertLocked(); - - // Try name as-is - Class result = getClass_impl(name); - if (result) return result; - - // Try Swift-mangled equivalent of the given name. - if (char *swName = copySwiftV1MangledName(name)) { - result = getClass_impl(swName); - free(swName); - return result; - } - - return nil; -} - - -/*********************************************************************** -* addNamedClass -* Adds name => cls to the named non-meta class map. -* Warns about duplicate class names and keeps the old mapping. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void addNamedClass(Class cls, const char *name, Class replacing = nil) -{ - runtimeLock.assertWriting(); - Class old; - if ((old = getClass(name)) && old != replacing) { - inform_duplicate(name, old, cls); - - // getNonMetaClass uses name lookups. Classes not found by name - // lookup must be in the secondary meta->nonmeta table. - addNonMetaClass(cls); - } else { - NXMapInsert(gdb_objc_realized_classes, name, cls); - } - assert(!(cls->data()->flags & RO_META)); - - // wrong: constructed classes are already realized when they get here - // assert(!cls->isRealized()); -} - - -/*********************************************************************** -* removeNamedClass -* Removes cls from the name => cls map. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void removeNamedClass(Class cls, const char *name) -{ - runtimeLock.assertWriting(); - assert(!(cls->data()->flags & RO_META)); - if (cls == NXMapGet(gdb_objc_realized_classes, name)) { - NXMapRemove(gdb_objc_realized_classes, name); - } else { - // cls has a name collision with another class - don't remove the other - // but do remove cls from the secondary metaclass->class map. - removeNonMetaClass(cls); - } -} - - -/*********************************************************************** -* realizedClasses -* Returns the class list for realized non-meta classes. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static NXHashTable *realized_class_hash = nil; - -static NXHashTable *realizedClasses(void) -{ - runtimeLock.assertLocked(); - - // allocated in _read_images - assert(realized_class_hash); - - return realized_class_hash; -} - - -/*********************************************************************** -* realizedMetaclasses -* Returns the class list for realized metaclasses. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static NXHashTable *realized_metaclass_hash = nil; -static NXHashTable *realizedMetaclasses(void) -{ - runtimeLock.assertLocked(); - - // allocated in _read_images - assert(realized_metaclass_hash); - - return realized_metaclass_hash; -} - - -/*********************************************************************** -* addRealizedClass -* Adds cls to the realized non-meta class hash. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void addRealizedClass(Class cls) -{ - runtimeLock.assertWriting(); - void *old; - old = NXHashInsert(realizedClasses(), cls); - objc_addRegisteredClass(cls); - assert(!cls->isMetaClass()); - assert(!old); -} - - -/*********************************************************************** -* removeRealizedClass -* Removes cls from the realized non-meta class hash. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void removeRealizedClass(Class cls) -{ - runtimeLock.assertWriting(); - if (cls->isRealized()) { - assert(!cls->isMetaClass()); - NXHashRemove(realizedClasses(), cls); - objc_removeRegisteredClass(cls); - } -} - - -/*********************************************************************** -* addRealizedMetaclass -* Adds cls to the realized metaclass hash. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void addRealizedMetaclass(Class cls) -{ - runtimeLock.assertWriting(); - void *old; - old = NXHashInsert(realizedMetaclasses(), cls); - assert(cls->isMetaClass()); - assert(!old); -} - - -/*********************************************************************** -* removeRealizedMetaclass -* Removes cls from the realized metaclass hash. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void removeRealizedMetaclass(Class cls) -{ - runtimeLock.assertWriting(); - if (cls->isRealized()) { - assert(cls->isMetaClass()); - NXHashRemove(realizedMetaclasses(), cls); - } -} - - -/*********************************************************************** -* futureNamedClasses -* Returns the classname => future class map for unrealized future classes. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static NXMapTable *future_named_class_map = nil; -static NXMapTable *futureNamedClasses() -{ - runtimeLock.assertWriting(); - - if (future_named_class_map) return future_named_class_map; - - // future_named_class_map is big enough for CF's classes and a few others - future_named_class_map = - NXCreateMapTable(NXStrValueMapPrototype, 32); - - return future_named_class_map; -} - - -/*********************************************************************** -* addFutureNamedClass -* Installs cls as the class structure to use for the named class if it appears. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void addFutureNamedClass(const char *name, Class cls) -{ - void *old; - - runtimeLock.assertWriting(); - - if (PrintFuture) { - _objc_inform("FUTURE: reserving %p for %s", (void*)cls, name); - } - - class_rw_t *rw = (class_rw_t *)calloc(sizeof(class_rw_t), 1); - class_ro_t *ro = (class_ro_t *)calloc(sizeof(class_ro_t), 1); - ro->name = strdup(name); - rw->ro = ro; - cls->setData(rw); - cls->data()->flags = RO_FUTURE; - - old = NXMapKeyCopyingInsert(futureNamedClasses(), name, cls); - assert(!old); -} - - -/*********************************************************************** -* popFutureNamedClass -* Removes the named class from the unrealized future class list, -* because it has been realized. -* Returns nil if the name is not used by a future class. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static Class popFutureNamedClass(const char *name) -{ - runtimeLock.assertWriting(); - - Class cls = nil; - - if (future_named_class_map) { - cls = (Class)NXMapKeyFreeingRemove(future_named_class_map, name); - if (cls && NXCountMapTable(future_named_class_map) == 0) { - NXFreeMapTable(future_named_class_map); - future_named_class_map = nil; - } - } - - return cls; -} - - -/*********************************************************************** -* remappedClasses -* Returns the oldClass => newClass map for realized future classes. -* Returns the oldClass => nil map for ignored weak-linked classes. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static NXMapTable *remappedClasses(bool create) -{ - static NXMapTable *remapped_class_map = nil; - - runtimeLock.assertLocked(); - - if (remapped_class_map) return remapped_class_map; - if (!create) return nil; - - // remapped_class_map is big enough to hold CF's classes and a few others - INIT_ONCE_PTR(remapped_class_map, - NXCreateMapTable(NXPtrValueMapPrototype, 32), - NXFreeMapTable(v)); - - return remapped_class_map; -} - - -/*********************************************************************** -* noClassesRemapped -* Returns YES if no classes have been remapped -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static bool noClassesRemapped(void) -{ - runtimeLock.assertLocked(); - - bool result = (remappedClasses(NO) == nil); -#if DEBUG - // Catch construction of an empty table, which defeats optimization. - NXMapTable *map = remappedClasses(NO); - if (map) assert(NXCountMapTable(map) > 0); -#endif - return result; -} - - -/*********************************************************************** -* addRemappedClass -* newcls is a realized future class, replacing oldcls. -* OR newcls is nil, replacing ignored weak-linked class oldcls. -* Locking: runtimeLock must be write-locked by the caller -**********************************************************************/ -static void addRemappedClass(Class oldcls, Class newcls) -{ - runtimeLock.assertWriting(); - - if (PrintFuture) { - _objc_inform("FUTURE: using %p instead of %p for %s", - (void*)newcls, (void*)oldcls, oldcls->nameForLogging()); - } - - void *old; - old = NXMapInsert(remappedClasses(YES), oldcls, newcls); - assert(!old); -} - - -/*********************************************************************** -* remapClass -* Returns the live class pointer for cls, which may be pointing to -* a class struct that has been reallocated. -* Returns nil if cls is ignored because of weak linking. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static Class remapClass(Class cls) -{ - runtimeLock.assertLocked(); - - Class c2; - - if (!cls) return nil; - - NXMapTable *map = remappedClasses(NO); - if (!map || NXMapMember(map, cls, (void**)&c2) == NX_MAPNOTAKEY) { - return cls; - } else { - return c2; - } -} - -static Class remapClass(classref_t cls) -{ - return remapClass((Class)cls); -} - -Class _class_remap(Class cls) -{ - rwlock_reader_t lock(runtimeLock); - return remapClass(cls); -} - -/*********************************************************************** -* remapClassRef -* Fix up a class ref, in case the class referenced has been reallocated -* or is an ignored weak-linked class. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static void remapClassRef(Class *clsref) -{ - runtimeLock.assertLocked(); - - Class newcls = remapClass(*clsref); - if (*clsref != newcls) *clsref = newcls; -} - - -/*********************************************************************** -* getNonMetaClass -* Return the ordinary class for this class or metaclass. -* `inst` is an instance of `cls` or a subclass thereof, or nil. -* Non-nil inst is faster. -* Used by +initialize. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static Class getNonMetaClass(Class metacls, id inst) -{ - static int total, named, secondary, sharedcache; - runtimeLock.assertLocked(); - - realizeClass(metacls); - - total++; - - // return cls itself if it's already a non-meta class - if (!metacls->isMetaClass()) return metacls; - - // metacls really is a metaclass - - // special case for root metaclass - // where inst == inst->ISA() == metacls is possible - if (metacls->ISA() == metacls) { - Class cls = metacls->superclass; - assert(cls->isRealized()); - assert(!cls->isMetaClass()); - assert(cls->ISA() == metacls); - if (cls->ISA() == metacls) return cls; - } - - // use inst if available - if (inst) { - Class cls = (Class)inst; - realizeClass(cls); - // cls may be a subclass - find the real class for metacls - while (cls && cls->ISA() != metacls) { - cls = cls->superclass; - realizeClass(cls); - } - if (cls) { - assert(!cls->isMetaClass()); - assert(cls->ISA() == metacls); - return cls; - } -#if DEBUG - _objc_fatal("cls is not an instance of metacls"); -#else - // release build: be forgiving and fall through to slow lookups -#endif - } - - // try name lookup - { - Class cls = getClass(metacls->mangledName()); - if (cls->ISA() == metacls) { - named++; - if (PrintInitializing) { - _objc_inform("INITIALIZE: %d/%d (%g%%) " - "successful by-name metaclass lookups", - named, total, named*100.0/total); - } - - realizeClass(cls); - return cls; - } - } - - // try secondary table - { - Class cls = (Class)NXMapGet(nonMetaClasses(), metacls); - if (cls) { - secondary++; - if (PrintInitializing) { - _objc_inform("INITIALIZE: %d/%d (%g%%) " - "successful secondary metaclass lookups", - secondary, total, secondary*100.0/total); - } - - assert(cls->ISA() == metacls); - realizeClass(cls); - return cls; - } - } - - // try any duplicates in the dyld shared cache - { - Class cls = nil; - - int count; - Class *classes = copyPreoptimizedClasses(metacls->mangledName(),&count); - if (classes) { - for (int i = 0; i < count; i++) { - if (classes[i]->ISA() == metacls) { - cls = classes[i]; - break; - } - } - free(classes); - } - - if (cls) { - sharedcache++; - if (PrintInitializing) { - _objc_inform("INITIALIZE: %d/%d (%g%%) " - "successful shared cache metaclass lookups", - sharedcache, total, sharedcache*100.0/total); - } - - realizeClass(cls); - return cls; - } - } - - _objc_fatal("no class for metaclass %p", (void*)metacls); -} - - -/*********************************************************************** -* _class_getNonMetaClass -* Return the ordinary class for this class or metaclass. -* Used by +initialize. -* Locking: acquires runtimeLock -**********************************************************************/ -Class _class_getNonMetaClass(Class cls, id obj) -{ - rwlock_writer_t lock(runtimeLock); - cls = getNonMetaClass(cls, obj); - assert(cls->isRealized()); - return cls; -} - - -/*********************************************************************** -* addSubclass -* Adds subcls as a subclass of supercls. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static void addSubclass(Class supercls, Class subcls) -{ - runtimeLock.assertWriting(); - - if (supercls && subcls) { - assert(supercls->isRealized()); - assert(subcls->isRealized()); - subcls->data()->nextSiblingClass = supercls->data()->firstSubclass; - supercls->data()->firstSubclass = subcls; - - if (supercls->hasCxxCtor()) { - subcls->setHasCxxCtor(); - } - - if (supercls->hasCxxDtor()) { - subcls->setHasCxxDtor(); - } - - if (supercls->hasCustomRR()) { - subcls->setHasCustomRR(true); - } - - if (supercls->hasCustomAWZ()) { - subcls->setHasCustomAWZ(true); - } - - if (supercls->requiresRawIsa()) { - subcls->setRequiresRawIsa(true); - } - } -} - - -/*********************************************************************** -* removeSubclass -* Removes subcls as a subclass of supercls. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static void removeSubclass(Class supercls, Class subcls) -{ - runtimeLock.assertWriting(); - assert(supercls->isRealized()); - assert(subcls->isRealized()); - assert(subcls->superclass == supercls); - - Class *cp; - for (cp = &supercls->data()->firstSubclass; - *cp && *cp != subcls; - cp = &(*cp)->data()->nextSiblingClass) - ; - assert(*cp == subcls); - *cp = subcls->data()->nextSiblingClass; -} - - - -/*********************************************************************** -* protocols -* Returns the protocol name => protocol map for protocols. -* Locking: runtimeLock must read- or write-locked by the caller -**********************************************************************/ -static NXMapTable *protocols(void) -{ - static NXMapTable *protocol_map = nil; - - runtimeLock.assertLocked(); - - INIT_ONCE_PTR(protocol_map, - NXCreateMapTable(NXStrValueMapPrototype, 16), - NXFreeMapTable(v) ); - - return protocol_map; -} - - -/*********************************************************************** -* getProtocol -* Looks up a protocol by name. Demangled Swift names are recognized. -* Locking: runtimeLock must be read- or write-locked by the caller. -**********************************************************************/ -static Protocol *getProtocol(const char *name) -{ - runtimeLock.assertLocked(); - - // Try name as-is. - Protocol *result = (Protocol *)NXMapGet(protocols(), name); - if (result) return result; - - // Try Swift-mangled equivalent of the given name. - if (char *swName = copySwiftV1MangledName(name, true/*isProtocol*/)) { - result = (Protocol *)NXMapGet(protocols(), swName); - free(swName); - return result; - } - - return nil; -} - - -/*********************************************************************** -* remapProtocol -* Returns the live protocol pointer for proto, which may be pointing to -* a protocol struct that has been reallocated. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static protocol_t *remapProtocol(protocol_ref_t proto) -{ - runtimeLock.assertLocked(); - - protocol_t *newproto = (protocol_t *) - getProtocol(((protocol_t *)proto)->mangledName); - return newproto ? newproto : (protocol_t *)proto; -} - - -/*********************************************************************** -* remapProtocolRef -* Fix up a protocol ref, in case the protocol referenced has been reallocated. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static size_t UnfixedProtocolReferences; -static void remapProtocolRef(protocol_t **protoref) -{ - runtimeLock.assertLocked(); - - protocol_t *newproto = remapProtocol((protocol_ref_t)*protoref); - if (*protoref != newproto) { - *protoref = newproto; - UnfixedProtocolReferences++; - } -} - - -/*********************************************************************** -* moveIvars -* Slides a class's ivars to accommodate the given superclass size. -* Also slides ivar and weak GC layouts if provided. -* Ivars are NOT compacted to compensate for a superclass that shrunk. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static void moveIvars(class_ro_t *ro, uint32_t superSize, - layout_bitmap *ivarBitmap, layout_bitmap *weakBitmap) -{ - runtimeLock.assertWriting(); - - uint32_t diff; - - assert(superSize > ro->instanceStart); - diff = superSize - ro->instanceStart; - - if (ro->ivars) { - // Find maximum alignment in this class's ivars - uint32_t maxAlignment = 1; - for (const auto& ivar : *ro->ivars) { - if (!ivar.offset) continue; // anonymous bitfield - - uint32_t alignment = ivar.alignment(); - if (alignment > maxAlignment) maxAlignment = alignment; - } - - // Compute a slide value that preserves that alignment - uint32_t alignMask = maxAlignment - 1; - if (diff & alignMask) diff = (diff + alignMask) & ~alignMask; - - // Slide all of this class's ivars en masse - for (const auto& ivar : *ro->ivars) { - if (!ivar.offset) continue; // anonymous bitfield - - uint32_t oldOffset = (uint32_t)*ivar.offset; - uint32_t newOffset = oldOffset + diff; - *ivar.offset = newOffset; - - if (PrintIvars) { - _objc_inform("IVARS: offset %u -> %u for %s " - "(size %u, align %u)", - oldOffset, newOffset, ivar.name, - ivar.size, ivar.alignment()); - } - } - - // Slide GC layouts - uint32_t oldOffset = ro->instanceStart; - uint32_t newOffset = ro->instanceStart + diff; - - if (ivarBitmap) { - layout_bitmap_slide(ivarBitmap, - oldOffset >> WORD_SHIFT, - newOffset >> WORD_SHIFT); - } - if (weakBitmap) { - layout_bitmap_slide(weakBitmap, - oldOffset >> WORD_SHIFT, - newOffset >> WORD_SHIFT); - } - } - - *(uint32_t *)&ro->instanceStart += diff; - *(uint32_t *)&ro->instanceSize += diff; - - if (!ro->ivars) { - // No ivars slid, but superclass changed size. - // Expand bitmap in preparation for layout_bitmap_splat(). - if (ivarBitmap) layout_bitmap_grow(ivarBitmap, ro->instanceSize >> WORD_SHIFT); - if (weakBitmap) layout_bitmap_grow(weakBitmap, ro->instanceSize >> WORD_SHIFT); - } -} - - -/*********************************************************************** -* getIvar -* Look up an ivar by name. -* Locking: runtimeLock must be read- or write-locked by the caller. -**********************************************************************/ -static ivar_t *getIvar(Class cls, const char *name) -{ - runtimeLock.assertLocked(); - - const ivar_list_t *ivars; - assert(cls->isRealized()); - if ((ivars = cls->data()->ro->ivars)) { - for (auto& ivar : *ivars) { - if (!ivar.offset) continue; // anonymous bitfield - - // ivar.name may be nil for anonymous bitfields etc. - if (ivar.name && 0 == strcmp(name, ivar.name)) { - return &ivar; - } - } - } - - return nil; -} - - -static void reconcileInstanceVariables(Class cls, Class supercls, const class_ro_t*& ro) -{ - class_rw_t *rw = cls->data(); - - assert(supercls); - assert(!cls->isMetaClass()); - - /* debug: print them all before sliding - if (ro->ivars) { - for (const auto& ivar : *ro->ivars) { - if (!ivar.offset) continue; // anonymous bitfield - - _objc_inform("IVARS: %s.%s (offset %u, size %u, align %u)", - ro->name, ivar.name, - *ivar.offset, ivar.size, ivar.alignment()); - } - } - */ - - // Non-fragile ivars - reconcile this class with its superclass - layout_bitmap ivarBitmap; - layout_bitmap weakBitmap; - bool layoutsChanged = NO; - bool mergeLayouts = UseGC; - const class_ro_t *super_ro = supercls->data()->ro; - - if (DebugNonFragileIvars) { - // Debugging: Force non-fragile ivars to slide. - // Intended to find compiler, runtime, and program bugs. - // If it fails with this and works without, you have a problem. - - // Operation: Reset everything to 0 + misalignment. - // Then force the normal sliding logic to push everything back. - - // Exceptions: root classes, metaclasses, *NSCF* classes, - // __CF* classes, NSConstantString, NSSimpleCString - - // (already know it's not root because supercls != nil) - const char *clsname = cls->mangledName(); - if (!strstr(clsname, "NSCF") && - 0 != strncmp(clsname, "__CF", 4) && - 0 != strcmp(clsname, "NSConstantString") && - 0 != strcmp(clsname, "NSSimpleCString")) - { - uint32_t oldStart = ro->instanceStart; - uint32_t oldSize = ro->instanceSize; - class_ro_t *ro_w = make_ro_writeable(rw); - ro = rw->ro; - - // Find max ivar alignment in class. - // default to word size to simplify ivar update - uint32_t alignment = 1<<WORD_SHIFT; - if (ro->ivars) { - for (const auto& ivar : *ro->ivars) { - if (ivar.alignment() > alignment) { - alignment = ivar.alignment(); - } - } - } - uint32_t misalignment = ro->instanceStart % alignment; - uint32_t delta = ro->instanceStart - misalignment; - ro_w->instanceStart = misalignment; - ro_w->instanceSize -= delta; - - if (PrintIvars) { - _objc_inform("IVARS: DEBUG: forcing ivars for class '%s' " - "to slide (instanceStart %zu -> %zu)", - cls->nameForLogging(), (size_t)oldStart, - (size_t)ro->instanceStart); - } - - if (ro->ivars) { - for (const auto& ivar : *ro->ivars) { - if (!ivar.offset) continue; // anonymous bitfield - *ivar.offset -= delta; - } - } - - if (mergeLayouts) { - layout_bitmap layout; - if (ro->ivarLayout) { - layout = layout_bitmap_create(ro->ivarLayout, - oldSize, oldSize, NO); - layout_bitmap_slide_anywhere(&layout, - delta >> WORD_SHIFT, 0); - ro_w->ivarLayout = layout_string_create(layout); - layout_bitmap_free(layout); - } - if (ro->weakIvarLayout) { - layout = layout_bitmap_create(ro->weakIvarLayout, - oldSize, oldSize, YES); - layout_bitmap_slide_anywhere(&layout, - delta >> WORD_SHIFT, 0); - ro_w->weakIvarLayout = layout_string_create(layout); - layout_bitmap_free(layout); - } - } - } - } - - if (ro->instanceStart >= super_ro->instanceSize && !mergeLayouts) { - // Superclass has not overgrown its space, and we don't - // need to rebuild GC layouts. We're done here. - return; - } - // fixme can optimize for "class has no new ivars", etc - - if (mergeLayouts) { - // WARNING: gcc c++ sets instanceStart/Size=0 for classes with - // no local ivars, but does provide a layout bitmap. - // Handle that case specially so layout_bitmap_create doesn't die - // The other ivar sliding code below still works fine, and - // the final result is a good class. - if (ro->instanceStart == 0 && ro->instanceSize == 0) { - // We can't use ro->ivarLayout because we don't know - // how long it is. Force a new layout to be created. - if (PrintIvars) { - _objc_inform("IVARS: instanceStart/Size==0 for class %s; " - "disregarding ivar layout", cls->nameForLogging()); - } - ivarBitmap = layout_bitmap_create_empty(super_ro->instanceSize, NO); - weakBitmap = layout_bitmap_create_empty(super_ro->instanceSize, YES); - layoutsChanged = YES; - } - else { - ivarBitmap = - layout_bitmap_create(ro->ivarLayout, - ro->instanceSize, - ro->instanceSize, NO); - weakBitmap = - layout_bitmap_create(ro->weakIvarLayout, - ro->instanceSize, - ro->instanceSize, YES); - } - } - - if (ro->instanceStart < super_ro->instanceSize) { - // Superclass has changed size. This class's ivars must move. - // Also slide layout bits in parallel. - // This code is incapable of compacting the subclass to - // compensate for a superclass that shrunk, so don't do that. - if (PrintIvars) { - _objc_inform("IVARS: sliding ivars for class %s " - "(superclass was %u bytes, now %u)", - cls->nameForLogging(), ro->instanceStart, - super_ro->instanceSize); - } - class_ro_t *ro_w = make_ro_writeable(rw); - ro = rw->ro; - moveIvars(ro_w, super_ro->instanceSize, - mergeLayouts ? &ivarBitmap : nil, - mergeLayouts ? &weakBitmap : nil); - gdb_objc_class_changed(cls, OBJC_CLASS_IVARS_CHANGED, ro->name); - layoutsChanged = YES; - } - - if (mergeLayouts) { - // Check superclass's layout against this class's layout. - // This needs to be done even if the superclass is not bigger. - layout_bitmap superBitmap; - - superBitmap = layout_bitmap_create(super_ro->ivarLayout, - super_ro->instanceSize, - super_ro->instanceSize, NO); - layoutsChanged |= layout_bitmap_splat(ivarBitmap, superBitmap, - ro->instanceStart); - layout_bitmap_free(superBitmap); - - // check the superclass' weak layout. - superBitmap = layout_bitmap_create(super_ro->weakIvarLayout, - super_ro->instanceSize, - super_ro->instanceSize, YES); - layoutsChanged |= layout_bitmap_splat(weakBitmap, superBitmap, - ro->instanceStart); - layout_bitmap_free(superBitmap); - - // Rebuild layout strings if necessary. - if (layoutsChanged) { - if (PrintIvars) { - _objc_inform("IVARS: gc layout changed for class %s", - cls->nameForLogging()); - } - class_ro_t *ro_w = make_ro_writeable(rw); - ro = rw->ro; - if (DebugNonFragileIvars) { - try_free(ro_w->ivarLayout); - try_free(ro_w->weakIvarLayout); - } - ro_w->ivarLayout = layout_string_create(ivarBitmap); - ro_w->weakIvarLayout = layout_string_create(weakBitmap); - } - - layout_bitmap_free(ivarBitmap); - layout_bitmap_free(weakBitmap); - } -} - - -/*********************************************************************** -* realizeClass -* Performs first-time initialization on class cls, -* including allocating its read-write data. -* Returns the real class structure for the class. -* Locking: runtimeLock must be write-locked by the caller -**********************************************************************/ -static Class realizeClass(Class cls) -{ - runtimeLock.assertWriting(); - - const class_ro_t *ro; - class_rw_t *rw; - Class supercls; - Class metacls; - bool isMeta; - - if (!cls) return nil; - if (cls->isRealized()) return cls; - assert(cls == remapClass(cls)); - - // fixme verify class is not in an un-dlopened part of the shared cache? - - ro = (const class_ro_t *)cls->data(); - if (ro->flags & RO_FUTURE) { - // This was a future class. rw data is already allocated. - rw = cls->data(); - ro = cls->data()->ro; - cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE); - } else { - // Normal class. Allocate writeable class data. - rw = (class_rw_t *)calloc(sizeof(class_rw_t), 1); - rw->ro = ro; - rw->flags = RW_REALIZED|RW_REALIZING; - cls->setData(rw); - } - - isMeta = ro->flags & RO_META; - - rw->version = isMeta ? 7 : 0; // old runtime went up to 6 - - if (PrintConnecting) { - _objc_inform("CLASS: realizing class '%s' %s %p %p", - cls->nameForLogging(), isMeta ? "(meta)" : "", - (void*)cls, ro); - } - - // Realize superclass and metaclass, if they aren't already. - // This needs to be done after RW_REALIZED is set above, for root classes. - supercls = realizeClass(remapClass(cls->superclass)); - metacls = realizeClass(remapClass(cls->ISA())); - - // Update superclass and metaclass in case of remapping - cls->superclass = supercls; - cls->initClassIsa(metacls); - - // Reconcile instance variable offsets / layout. - // This may reallocate class_ro_t, updating our ro variable. - if (supercls && !isMeta) reconcileInstanceVariables(cls, supercls, ro); - - // Set fastInstanceSize if it wasn't set already. - cls->setInstanceSize(ro->instanceSize); - - // Copy some flags from ro to rw - if (ro->flags & RO_HAS_CXX_STRUCTORS) { - cls->setHasCxxDtor(); - if (! (ro->flags & RO_HAS_CXX_DTOR_ONLY)) { - cls->setHasCxxCtor(); - } - } - - // Disable non-pointer isa for some classes and/or platforms. -#if SUPPORT_NONPOINTER_ISA - { - bool disable = false; - static bool hackedDispatch = false; - - if (DisableIndexedIsa) { - // Non-pointer isa disabled by environment or GC or app SDK version - disable = true; - } - else if (!hackedDispatch && !(ro->flags & RO_META) && - 0 == strcmp(ro->name, "OS_object")) - { - // hack for libdispatch et al - isa also acts as vtable pointer - hackedDispatch = true; - disable = true; - } - - if (disable) { - cls->setRequiresRawIsa(false/*inherited*/); - } - } -#endif - - // Connect this class to its superclass's subclass lists - if (supercls) { - addSubclass(supercls, cls); - } - - // Attach categories - methodizeClass(cls); - - if (!isMeta) { - addRealizedClass(cls); - } else { - addRealizedMetaclass(cls); - } - - return cls; -} - - -/*********************************************************************** -* missingWeakSuperclass -* Return YES if some superclass of cls was weak-linked and is missing. -**********************************************************************/ -static bool -missingWeakSuperclass(Class cls) -{ - assert(!cls->isRealized()); - - if (!cls->superclass) { - // superclass nil. This is normal for root classes only. - return (!(cls->data()->flags & RO_ROOT)); - } else { - // superclass not nil. Check if a higher superclass is missing. - Class supercls = remapClass(cls->superclass); - assert(cls != cls->superclass); - assert(cls != supercls); - if (!supercls) return YES; - if (supercls->isRealized()) return NO; - return missingWeakSuperclass(supercls); - } -} - - -/*********************************************************************** -* realizeAllClassesInImage -* Non-lazily realizes all unrealized classes in the given image. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static void realizeAllClassesInImage(header_info *hi) -{ - runtimeLock.assertWriting(); - - size_t count, i; - classref_t *classlist; - - if (hi->allClassesRealized) return; - - classlist = _getObjc2ClassList(hi, &count); - - for (i = 0; i < count; i++) { - realizeClass(remapClass(classlist[i])); - } - - hi->allClassesRealized = YES; -} - - -/*********************************************************************** -* realizeAllClasses -* Non-lazily realizes all unrealized classes in all known images. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static void realizeAllClasses(void) -{ - runtimeLock.assertWriting(); - - header_info *hi; - for (hi = FirstHeader; hi; hi = hi->next) { - realizeAllClassesInImage(hi); - } -} - - -/*********************************************************************** -* _objc_allocateFutureClass -* Allocate an unresolved future class for the given class name. -* Returns any existing allocation if one was already made. -* Assumes the named class doesn't exist yet. -* Locking: acquires runtimeLock -**********************************************************************/ -Class _objc_allocateFutureClass(const char *name) -{ - rwlock_writer_t lock(runtimeLock); - - Class cls; - NXMapTable *map = futureNamedClasses(); - - if ((cls = (Class)NXMapGet(map, name))) { - // Already have a future class for this name. - return cls; - } - - cls = _calloc_class(sizeof(objc_class)); - addFutureNamedClass(name, cls); - - return cls; -} - - -/*********************************************************************** -* objc_getFutureClass. Return the id of the named class. -* If the class does not exist, return an uninitialized class -* structure that will be used for the class when and if it -* does get loaded. -* Not thread safe. -**********************************************************************/ -Class objc_getFutureClass(const char *name) -{ - Class cls; - - // YES unconnected, NO class handler - // (unconnected is OK because it will someday be the real class) - cls = look_up_class(name, YES, NO); - if (cls) { - if (PrintFuture) { - _objc_inform("FUTURE: found %p already in use for %s", - (void*)cls, name); - } - - return cls; - } - - // No class or future class with that name yet. Make one. - // fixme not thread-safe with respect to - // simultaneous library load or getFutureClass. - return _objc_allocateFutureClass(name); -} - - -BOOL _class_isFutureClass(Class cls) -{ - return cls && cls->isFuture(); -} - - -/*********************************************************************** -* _objc_flush_caches -* Flushes all caches. -* (Historical behavior: flush caches for cls, its metaclass, -* and subclasses thereof. Nil flushes all classes.) -* Locking: acquires runtimeLock -**********************************************************************/ -static void flushCaches(Class cls) -{ - runtimeLock.assertWriting(); - - mutex_locker_t lock(cacheUpdateLock); - - if (cls) { - foreach_realized_class_and_subclass(cls, ^(Class c){ - cache_erase_nolock(c); - }); - - if (!cls->superclass) { - // root; metaclasses are subclasses and were flushed above - } else { - foreach_realized_class_and_subclass(cls->ISA(), ^(Class c){ - cache_erase_nolock(c); - }); - } - } - else { - Class c; - NXHashTable *classes = realizedClasses(); - NXHashState state = NXInitHashState(classes); - while (NXNextHashState(classes, &state, (void **)&c)) { - cache_erase_nolock(c); - } - classes = realizedMetaclasses(); - state = NXInitHashState(classes); - while (NXNextHashState(classes, &state, (void **)&c)) { - cache_erase_nolock(c); - } - } -} - - -void _objc_flush_caches(Class cls) -{ - { - rwlock_writer_t lock(runtimeLock); - flushCaches(cls); - } - - if (!cls) { - mutex_locker_t lock(cacheUpdateLock); - // collectALot if cls==nil - cache_collect(true); - } -} - - -/*********************************************************************** -* map_images -* Process the given images which are being mapped in by dyld. -* Calls ABI-agnostic code after taking ABI-specific locks. -* -* Locking: write-locks runtimeLock -**********************************************************************/ -const char * -map_2_images(enum dyld_image_states state, uint32_t infoCount, - const struct dyld_image_info infoList[]) -{ - rwlock_writer_t lock(runtimeLock); - return map_images_nolock(state, infoCount, infoList); -} - - -/*********************************************************************** -* load_images -* Process +load in the given images which are being mapped in by dyld. -* Calls ABI-agnostic code after taking ABI-specific locks. -* -* Locking: write-locks runtimeLock and loadMethodLock -**********************************************************************/ -const char * -load_images(enum dyld_image_states state, uint32_t infoCount, - const struct dyld_image_info infoList[]) -{ - bool found; - - // Return without taking locks if there are no +load methods here. - found = false; - for (uint32_t i = 0; i < infoCount; i++) { - if (hasLoadMethods((const headerType *)infoList[i].imageLoadAddress)) { - found = true; - break; - } - } - if (!found) return nil; - - recursive_mutex_locker_t lock(loadMethodLock); - - // Discover load methods - { - rwlock_writer_t lock2(runtimeLock); - found = load_images_nolock(state, infoCount, infoList); - } - - // Call +load methods (without runtimeLock - re-entrant) - if (found) { - call_load_methods(); - } - - return nil; -} - - -/*********************************************************************** -* unmap_image -* Process the given image which is about to be unmapped by dyld. -* mh is mach_header instead of headerType because that's what -* dyld_priv.h says even for 64-bit. -* -* Locking: write-locks runtimeLock and loadMethodLock -**********************************************************************/ -void -unmap_image(const struct mach_header *mh, intptr_t vmaddr_slide) -{ - recursive_mutex_locker_t lock(loadMethodLock); - rwlock_writer_t lock2(runtimeLock); - unmap_image_nolock(mh); -} - - - - -/*********************************************************************** -* readClass -* Read a class and metaclass as written by a compiler. -* Returns the new class pointer. This could be: -* - cls -* - nil (cls has a missing weak-linked superclass) -* - something else (space for this class was reserved by a future class) -* -* Locking: runtimeLock acquired by map_images or objc_readClassPair -**********************************************************************/ -Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized) -{ - const char *mangledName = cls->mangledName(); - - if (missingWeakSuperclass(cls)) { - // No superclass (probably weak-linked). - // Disavow any knowledge of this subclass. - if (PrintConnecting) { - _objc_inform("CLASS: IGNORING class '%s' with " - "missing weak-linked superclass", - cls->nameForLogging()); - } - addRemappedClass(cls, nil); - cls->superclass = nil; - return nil; - } - - // Note: Class __ARCLite__'s hack does not go through here. - // Class structure fixups that apply to it also need to be - // performed in non-lazy realization below. - - // These fields should be set to zero because of the - // binding of _objc_empty_vtable, but OS X 10.8's dyld - // does not bind shared cache absolute symbols as expected. - // This (and the __ARCLite__ hack below) can be removed - // once the simulator drops 10.8 support. -#if TARGET_IPHONE_SIMULATOR - if (cls->cache._mask) cls->cache._mask = 0; - if (cls->cache._occupied) cls->cache._occupied = 0; - if (cls->ISA()->cache._mask) cls->ISA()->cache._mask = 0; - if (cls->ISA()->cache._occupied) cls->ISA()->cache._occupied = 0; -#endif - - Class replacing = nil; - if (Class newCls = popFutureNamedClass(mangledName)) { - // This name was previously allocated as a future class. - // Copy objc_class to future class's struct. - // Preserve future's rw data block. - - if (newCls->isSwift()) { - _objc_fatal("Can't complete future class request for '%s' " - "because the real class is too big.", - cls->nameForLogging()); - } - - class_rw_t *rw = newCls->data(); - const class_ro_t *old_ro = rw->ro; - memcpy(newCls, cls, sizeof(objc_class)); - rw->ro = (class_ro_t *)newCls->data(); - newCls->setData(rw); - free((void *)old_ro->name); - free((void *)old_ro); - - addRemappedClass(cls, newCls); - - replacing = cls; - cls = newCls; - } - - if (headerIsPreoptimized && !replacing) { - // class list built in shared cache - // fixme strict assert doesn't work because of duplicates - // assert(cls == getClass(name)); - assert(getClass(mangledName)); - } else { - addNamedClass(cls, mangledName, replacing); - } - - // for future reference: shared cache never contains MH_BUNDLEs - if (headerIsBundle) { - cls->data()->flags |= RO_FROM_BUNDLE; - cls->ISA()->data()->flags |= RO_FROM_BUNDLE; - } - - return cls; -} - - -/*********************************************************************** -* readProtocol -* Read a protocol as written by a compiler. -**********************************************************************/ -static void -readProtocol(protocol_t *newproto, Class protocol_class, - NXMapTable *protocol_map, - bool headerIsPreoptimized, bool headerIsBundle) -{ - // This is not enough to make protocols in unloaded bundles safe, - // but it does prevent crashes when looking up unrelated protocols. - auto insertFn = headerIsBundle ? NXMapKeyCopyingInsert : NXMapInsert; - - protocol_t *oldproto = (protocol_t *)getProtocol(newproto->mangledName); - - if (oldproto) { - // Some other definition already won. - if (PrintProtocols) { - _objc_inform("PROTOCOLS: protocol at %p is %s " - "(duplicate of %p)", - newproto, oldproto->nameForLogging(), oldproto); - } - } - else if (headerIsPreoptimized) { - // Shared cache initialized the protocol object itself, - // but in order to allow out-of-cache replacement we need - // to add it to the protocol table now. - - protocol_t *cacheproto = (protocol_t *) - getPreoptimizedProtocol(newproto->mangledName); - protocol_t *installedproto; - if (cacheproto && cacheproto != newproto) { - // Another definition in the shared cache wins (because - // everything in the cache was fixed up to point to it). - installedproto = cacheproto; - } - else { - // This definition wins. - installedproto = newproto; - } - - assert(installedproto->getIsa() == protocol_class); - assert(installedproto->size >= sizeof(protocol_t)); - insertFn(protocol_map, installedproto->mangledName, - installedproto); - - if (PrintProtocols) { - _objc_inform("PROTOCOLS: protocol at %p is %s", - installedproto, installedproto->nameForLogging()); - if (newproto != installedproto) { - _objc_inform("PROTOCOLS: protocol at %p is %s " - "(duplicate of %p)", - newproto, installedproto->nameForLogging(), - installedproto); - } - } - } - else if (newproto->size >= sizeof(protocol_t)) { - // New protocol from an un-preoptimized image - // with sufficient storage. Fix it up in place. - // fixme duplicate protocols from unloadable bundle - newproto->initIsa(protocol_class); // fixme pinned - insertFn(protocol_map, newproto->mangledName, newproto); - if (PrintProtocols) { - _objc_inform("PROTOCOLS: protocol at %p is %s", - newproto, newproto->nameForLogging()); - } - } - else { - // New protocol from an un-preoptimized image - // with insufficient storage. Reallocate it. - // fixme duplicate protocols from unloadable bundle - size_t size = max(sizeof(protocol_t), (size_t)newproto->size); - protocol_t *installedproto = (protocol_t *)calloc(size, 1); - memcpy(installedproto, newproto, newproto->size); - installedproto->size = (__typeof__(installedproto->size))size; - - installedproto->initIsa(protocol_class); // fixme pinned - insertFn(protocol_map, installedproto->mangledName, installedproto); - if (PrintProtocols) { - _objc_inform("PROTOCOLS: protocol at %p is %s ", - installedproto, installedproto->nameForLogging()); - _objc_inform("PROTOCOLS: protocol at %p is %s " - "(reallocated to %p)", - newproto, installedproto->nameForLogging(), - installedproto); - } - } -} - -/*********************************************************************** -* _read_images -* Perform initial processing of the headers in the linked -* list beginning with headerList. -* -* Called by: map_images_nolock -* -* Locking: runtimeLock acquired by map_images -**********************************************************************/ - -extern "C" int dyld_get_program_sdk_version(); -#define DYLD_MACOSX_VERSION_10_11 MAC_OS_X_VERSION_10_11 - -void _read_images(header_info **hList, uint32_t hCount) -{ - header_info *hi; - uint32_t hIndex; - size_t count; - size_t i; - Class *resolvedFutureClasses = nil; - size_t resolvedFutureClassCount = 0; - static bool doneOnce; - TimeLogger ts(PrintImageTimes); - - runtimeLock.assertWriting(); - -#define EACH_HEADER \ - hIndex = 0; \ - crashlog_header_name(nil) && hIndex < hCount && (hi = hList[hIndex]) && crashlog_header_name(hi); \ - hIndex++ - - if (!doneOnce) { - doneOnce = YES; - -#if SUPPORT_NONPOINTER_ISA - -# if TARGET_OS_MAC && !TARGET_OS_IPHONE - // Disable non-pointer isa if the app is too old - // (linked before OS X 10.11) - if (dyld_get_program_sdk_version() < DYLD_MACOSX_VERSION_10_11) { - DisableIndexedIsa = true; - if (PrintRawIsa) { - _objc_inform("RAW ISA: disabling non-pointer isa because " - "the app is too old (SDK version " SDK_FORMAT ")", - FORMAT_SDK(dyld_get_program_sdk_version())); - } - } - - // Disable non-pointer isa if the app has a __DATA,__objc_rawisa section - // New apps that load old extensions may need this. - for (EACH_HEADER) { - if (hi->mhdr->filetype != MH_EXECUTE) continue; - unsigned long size; - if (getsectiondata(hi->mhdr, "__DATA", "__objc_rawisa", &size)) { - DisableIndexedIsa = true; - if (PrintRawIsa) { - _objc_inform("RAW ISA: disabling non-pointer isa because " - "the app has a __DATA,__objc_rawisa section"); - } - } - break; // assume only one MH_EXECUTE image - } -# endif - - // Disable non-pointer isa for all GC apps. - if (UseGC) { - DisableIndexedIsa = true; - if (PrintRawIsa) { - _objc_inform("RAW ISA: disabling non-pointer isa because " - "the app is GC"); - } - } - -#endif - - if (DisableTaggedPointers) { - disableTaggedPointers(); - } - - // Count classes. Size various table based on the total. - int total = 0; - int unoptimizedTotal = 0; - for (EACH_HEADER) { - if (_getObjc2ClassList(hi, &count)) { - total += (int)count; - if (!hi->inSharedCache) unoptimizedTotal += count; - } - } - - if (PrintConnecting) { - _objc_inform("CLASS: found %d classes during launch", total); - } - - // namedClasses (NOT realizedClasses) - // Preoptimized classes don't go in this table. - // 4/3 is NXMapTable's load factor - int namedClassesSize = - (isPreoptimized() ? unoptimizedTotal : total) * 4 / 3; - gdb_objc_realized_classes = - NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize); - - // realizedClasses and realizedMetaclasses - less than the full total - realized_class_hash = - NXCreateHashTable(NXPtrPrototype, total / 8, nil); - realized_metaclass_hash = - NXCreateHashTable(NXPtrPrototype, total / 8, nil); - - ts.log("IMAGE TIMES: first time tasks"); - } - - - // Discover classes. Fix up unresolved future classes. Mark bundle classes. - - for (EACH_HEADER) { - bool headerIsBundle = hi->isBundle(); - bool headerIsPreoptimized = hi->isPreoptimized(); - - classref_t *classlist = _getObjc2ClassList(hi, &count); - for (i = 0; i < count; i++) { - Class cls = (Class)classlist[i]; - Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized); - - if (newCls != cls && newCls) { - // Class was moved but not deleted. Currently this occurs - // only when the new class resolved a future class. - // Non-lazily realize the class below. - resolvedFutureClasses = (Class *) - realloc(resolvedFutureClasses, - (resolvedFutureClassCount+1) - * sizeof(Class)); - resolvedFutureClasses[resolvedFutureClassCount++] = newCls; - } - } - } - - ts.log("IMAGE TIMES: discover classes"); - - // Fix up remapped classes - // Class list and nonlazy class list remain unremapped. - // Class refs and super refs are remapped for message dispatching. - - if (!noClassesRemapped()) { - for (EACH_HEADER) { - Class *classrefs = _getObjc2ClassRefs(hi, &count); - for (i = 0; i < count; i++) { - remapClassRef(&classrefs[i]); - } - // fixme why doesn't test future1 catch the absence of this? - classrefs = _getObjc2SuperRefs(hi, &count); - for (i = 0; i < count; i++) { - remapClassRef(&classrefs[i]); - } - } - } - - ts.log("IMAGE TIMES: remap classes"); - - // Fix up @selector references - static size_t UnfixedSelectors; - sel_lock(); - for (EACH_HEADER) { - if (hi->isPreoptimized()) continue; - - bool isBundle = hi->isBundle(); - SEL *sels = _getObjc2SelectorRefs(hi, &count); - UnfixedSelectors += count; - for (i = 0; i < count; i++) { - const char *name = sel_cname(sels[i]); - sels[i] = sel_registerNameNoLock(name, isBundle); - } - } - sel_unlock(); - - ts.log("IMAGE TIMES: fix up selector references"); - -#if SUPPORT_FIXUP - // Fix up old objc_msgSend_fixup call sites - for (EACH_HEADER) { - message_ref_t *refs = _getObjc2MessageRefs(hi, &count); - if (count == 0) continue; - - if (PrintVtables) { - _objc_inform("VTABLES: repairing %zu unsupported vtable dispatch " - "call sites in %s", count, hi->fname); - } - for (i = 0; i < count; i++) { - fixupMessageRef(refs+i); - } - } - - ts.log("IMAGE TIMES: fix up objc_msgSend_fixup"); -#endif - - // Discover protocols. Fix up protocol refs. - for (EACH_HEADER) { - extern objc_class OBJC_CLASS_$_Protocol; - Class cls = (Class)&OBJC_CLASS_$_Protocol; - assert(cls); - NXMapTable *protocol_map = protocols(); - bool isPreoptimized = hi->isPreoptimized(); - bool isBundle = hi->isBundle(); - - protocol_t **protolist = _getObjc2ProtocolList(hi, &count); - for (i = 0; i < count; i++) { - readProtocol(protolist[i], cls, protocol_map, - isPreoptimized, isBundle); - } - } - - ts.log("IMAGE TIMES: discover protocols"); - - // Fix up @protocol references - // Preoptimized images may have the right - // answer already but we don't know for sure. - for (EACH_HEADER) { - protocol_t **protolist = _getObjc2ProtocolRefs(hi, &count); - for (i = 0; i < count; i++) { - remapProtocolRef(&protolist[i]); - } - } - - ts.log("IMAGE TIMES: fix up @protocol references"); - - // Realize non-lazy classes (for +load methods and static instances) - for (EACH_HEADER) { - classref_t *classlist = - _getObjc2NonlazyClassList(hi, &count); - for (i = 0; i < count; i++) { - Class cls = remapClass(classlist[i]); - if (!cls) continue; - - // hack for class __ARCLite__, which didn't get this above -#if TARGET_IPHONE_SIMULATOR - if (cls->cache._buckets == (void*)&_objc_empty_cache && - (cls->cache._mask || cls->cache._occupied)) - { - cls->cache._mask = 0; - cls->cache._occupied = 0; - } - if (cls->ISA()->cache._buckets == (void*)&_objc_empty_cache && - (cls->ISA()->cache._mask || cls->ISA()->cache._occupied)) - { - cls->ISA()->cache._mask = 0; - cls->ISA()->cache._occupied = 0; - } -#endif - - realizeClass(cls); - } - } - - ts.log("IMAGE TIMES: realize non-lazy classes"); - - // Realize newly-resolved future classes, in case CF manipulates them - if (resolvedFutureClasses) { - for (i = 0; i < resolvedFutureClassCount; i++) { - realizeClass(resolvedFutureClasses[i]); - resolvedFutureClasses[i]->setRequiresRawIsa(false/*inherited*/); - } - free(resolvedFutureClasses); - } - - ts.log("IMAGE TIMES: realize future classes"); - - // Discover categories. - for (EACH_HEADER) { - category_t **catlist = - _getObjc2CategoryList(hi, &count); - for (i = 0; i < count; i++) { - category_t *cat = catlist[i]; - Class cls = remapClass(cat->cls); - - if (!cls) { - // Category's target class is missing (probably weak-linked). - // Disavow any knowledge of this category. - catlist[i] = nil; - if (PrintConnecting) { - _objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with " - "missing weak-linked target class", - cat->name, cat); - } - continue; - } - - // Process this category. - // First, register the category with its target class. - // Then, rebuild the class's method lists (etc) if - // the class is realized. - bool classExists = NO; - if (cat->instanceMethods || cat->protocols - || cat->instanceProperties) - { - addUnattachedCategoryForClass(cat, cls, hi); - if (cls->isRealized()) { - remethodizeClass(cls); - classExists = YES; - } - if (PrintConnecting) { - _objc_inform("CLASS: found category -%s(%s) %s", - cls->nameForLogging(), cat->name, - classExists ? "on existing class" : ""); - } - } - - if (cat->classMethods || cat->protocols - /* || cat->classProperties */) - { - addUnattachedCategoryForClass(cat, cls->ISA(), hi); - if (cls->ISA()->isRealized()) { - remethodizeClass(cls->ISA()); - } - if (PrintConnecting) { - _objc_inform("CLASS: found category +%s(%s)", - cls->nameForLogging(), cat->name); - } - } - } - } - - ts.log("IMAGE TIMES: discover categories"); - - // Category discovery MUST BE LAST to avoid potential races - // when other threads call the new category code before - // this thread finishes its fixups. - - // +load handled by prepare_load_methods() - - if (DebugNonFragileIvars) { - realizeAllClasses(); - } - - - // Print preoptimization statistics - if (PrintPreopt) { - static unsigned int PreoptTotalMethodLists; - static unsigned int PreoptOptimizedMethodLists; - static unsigned int PreoptTotalClasses; - static unsigned int PreoptOptimizedClasses; - - for (EACH_HEADER) { - if (hi->isPreoptimized()) { - _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors " - "in %s", hi->fname); - } - else if (_objcHeaderOptimizedByDyld(hi)) { - _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors " - "in %s", hi->fname); - } - - classref_t *classlist = _getObjc2ClassList(hi, &count); - for (i = 0; i < count; i++) { - Class cls = remapClass(classlist[i]); - if (!cls) continue; - - PreoptTotalClasses++; - if (hi->isPreoptimized()) { - PreoptOptimizedClasses++; - } - - const method_list_t *mlist; - if ((mlist = ((class_ro_t *)cls->data())->baseMethods())) { - PreoptTotalMethodLists++; - if (mlist->isFixedUp()) { - PreoptOptimizedMethodLists++; - } - } - if ((mlist=((class_ro_t *)cls->ISA()->data())->baseMethods())) { - PreoptTotalMethodLists++; - if (mlist->isFixedUp()) { - PreoptOptimizedMethodLists++; - } - } - } - } - - _objc_inform("PREOPTIMIZATION: %zu selector references not " - "pre-optimized", UnfixedSelectors); - _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) method lists pre-sorted", - PreoptOptimizedMethodLists, PreoptTotalMethodLists, - PreoptTotalMethodLists - ? 100.0*PreoptOptimizedMethodLists/PreoptTotalMethodLists - : 0.0); - _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) classes pre-registered", - PreoptOptimizedClasses, PreoptTotalClasses, - PreoptTotalClasses - ? 100.0*PreoptOptimizedClasses/PreoptTotalClasses - : 0.0); - _objc_inform("PREOPTIMIZATION: %zu protocol references not " - "pre-optimized", UnfixedProtocolReferences); - } - -#undef EACH_HEADER -} - - -/*********************************************************************** -* prepare_load_methods -* Schedule +load for classes in this image, any un-+load-ed -* superclasses in other images, and any categories in this image. -**********************************************************************/ -// Recursively schedule +load for cls and any un-+load-ed superclasses. -// cls must already be connected. -static void schedule_class_load(Class cls) -{ - if (!cls) return; - assert(cls->isRealized()); // _read_images should realize - - if (cls->data()->flags & RW_LOADED) return; - - // Ensure superclass-first ordering - schedule_class_load(cls->superclass); - - add_class_to_loadable_list(cls); - cls->setInfo(RW_LOADED); -} - -// Quick scan for +load methods that doesn't take a lock. -bool hasLoadMethods(const headerType *mhdr) -{ - size_t count; - if (_getObjc2NonlazyClassList(mhdr, &count) && count > 0) return true; - if (_getObjc2NonlazyCategoryList(mhdr, &count) && count > 0) return true; - return false; -} - -void prepare_load_methods(const headerType *mhdr) -{ - size_t count, i; - - runtimeLock.assertWriting(); - - classref_t *classlist = - _getObjc2NonlazyClassList(mhdr, &count); - for (i = 0; i < count; i++) { - schedule_class_load(remapClass(classlist[i])); - } - - category_t **categorylist = _getObjc2NonlazyCategoryList(mhdr, &count); - for (i = 0; i < count; i++) { - category_t *cat = categorylist[i]; - Class cls = remapClass(cat->cls); - if (!cls) continue; // category for ignored weak-linked class - realizeClass(cls); - assert(cls->ISA()->isRealized()); - add_category_to_loadable_list(cat); - } -} - - -/*********************************************************************** -* _unload_image -* Only handles MH_BUNDLE for now. -* Locking: write-lock and loadMethodLock acquired by unmap_image -**********************************************************************/ -void _unload_image(header_info *hi) -{ - size_t count, i; - - loadMethodLock.assertLocked(); - runtimeLock.assertWriting(); - - // Unload unattached categories and categories waiting for +load. - - category_t **catlist = _getObjc2CategoryList(hi, &count); - for (i = 0; i < count; i++) { - category_t *cat = catlist[i]; - if (!cat) continue; // category for ignored weak-linked class - Class cls = remapClass(cat->cls); - assert(cls); // shouldn't have live category for dead class - - // fixme for MH_DYLIB cat's class may have been unloaded already - - // unattached list - removeUnattachedCategoryForClass(cat, cls); - - // +load queue - remove_category_from_loadable_list(cat); - } - - // Unload classes. - - classref_t *classlist = _getObjc2ClassList(hi, &count); - - // First detach classes from each other. Then free each class. - // This avoid bugs where this loop unloads a subclass before its superclass - - for (i = 0; i < count; i++) { - Class cls = remapClass(classlist[i]); - if (cls) { - remove_class_from_loadable_list(cls); - detach_class(cls->ISA(), YES); - detach_class(cls, NO); - } - } - - for (i = 0; i < count; i++) { - Class cls = remapClass(classlist[i]); - if (cls) { - free_class(cls->ISA()); - free_class(cls); - } - } - - // XXX FIXME -- Clean up protocols: - // <rdar://problem/9033191> Support unloading protocols at dylib/image unload time - - // fixme DebugUnload -} - - -/*********************************************************************** -* method_getDescription -* Returns a pointer to this method's objc_method_description. -* Locking: none -**********************************************************************/ -struct objc_method_description * -method_getDescription(Method m) -{ - if (!m) return nil; - return (struct objc_method_description *)m; -} - - -IMP -method_getImplementation(Method m) -{ - return m ? m->imp : nil; -} - - -/*********************************************************************** -* method_getName -* Returns this method's selector. -* The method must not be nil. -* The method must already have been fixed-up. -* Locking: none -**********************************************************************/ -SEL -method_getName(Method m) -{ - if (!m) return nil; - - assert(m->name == sel_registerName(sel_getName(m->name))); - return m->name; -} - - -/*********************************************************************** -* method_getTypeEncoding -* Returns this method's old-style type encoding string. -* The method must not be nil. -* Locking: none -**********************************************************************/ -const char * -method_getTypeEncoding(Method m) -{ - if (!m) return nil; - return m->types; -} - - -/*********************************************************************** -* method_setImplementation -* Sets this method's implementation to imp. -* The previous implementation is returned. -**********************************************************************/ -static IMP -_method_setImplementation(Class cls, method_t *m, IMP imp) -{ - runtimeLock.assertWriting(); - - if (!m) return nil; - if (!imp) return nil; - - if (ignoreSelector(m->name)) { - // Ignored methods stay ignored - return m->imp; - } - - IMP old = m->imp; - m->imp = imp; - - // Cache updates are slow if cls is nil (i.e. unknown) - // RR/AWZ updates are slow if cls is nil (i.e. unknown) - // fixme build list of classes whose Methods are known externally? - - flushCaches(cls); - - updateCustomRR_AWZ(cls, m); - - return old; -} - -IMP -method_setImplementation(Method m, IMP imp) -{ - // Don't know the class - will be slow if RR/AWZ are affected - // fixme build list of classes whose Methods are known externally? - rwlock_writer_t lock(runtimeLock); - return _method_setImplementation(Nil, m, imp); -} - - -void method_exchangeImplementations(Method m1, Method m2) -{ - if (!m1 || !m2) return; - - rwlock_writer_t lock(runtimeLock); - - if (ignoreSelector(m1->name) || ignoreSelector(m2->name)) { - // Ignored methods stay ignored. Now they're both ignored. - m1->imp = (IMP)&_objc_ignored_method; - m2->imp = (IMP)&_objc_ignored_method; - return; - } - - IMP m1_imp = m1->imp; - m1->imp = m2->imp; - m2->imp = m1_imp; - - - // RR/AWZ updates are slow because class is unknown - // Cache updates are slow because class is unknown - // fixme build list of classes whose Methods are known externally? - - flushCaches(nil); - - updateCustomRR_AWZ(nil, m1); - updateCustomRR_AWZ(nil, m2); -} - - -/*********************************************************************** -* ivar_getOffset -* fixme -* Locking: none -**********************************************************************/ -ptrdiff_t -ivar_getOffset(Ivar ivar) -{ - if (!ivar) return 0; - return *ivar->offset; -} - - -/*********************************************************************** -* ivar_getName -* fixme -* Locking: none -**********************************************************************/ -const char * -ivar_getName(Ivar ivar) -{ - if (!ivar) return nil; - return ivar->name; -} - - -/*********************************************************************** -* ivar_getTypeEncoding -* fixme -* Locking: none -**********************************************************************/ -const char * -ivar_getTypeEncoding(Ivar ivar) -{ - if (!ivar) return nil; - return ivar->type; -} - - - -const char *property_getName(objc_property_t prop) -{ - return prop->name; -} - -const char *property_getAttributes(objc_property_t prop) -{ - return prop->attributes; -} - -objc_property_attribute_t *property_copyAttributeList(objc_property_t prop, - unsigned int *outCount) -{ - if (!prop) { - if (outCount) *outCount = 0; - return nil; - } - - rwlock_reader_t lock(runtimeLock); - return copyPropertyAttributeList(prop->attributes,outCount); -} - -char * property_copyAttributeValue(objc_property_t prop, const char *name) -{ - if (!prop || !name || *name == '\0') return nil; - - rwlock_reader_t lock(runtimeLock); - return copyPropertyAttributeValue(prop->attributes, name); -} - - -/*********************************************************************** -* getExtendedTypesIndexesForMethod -* Returns: -* a is the count of methods in all method lists before m's method list -* b is the index of m in m's method list -* a+b is the index of m's extended types in the extended types array -**********************************************************************/ -static void getExtendedTypesIndexesForMethod(protocol_t *proto, const method_t *m, bool isRequiredMethod, bool isInstanceMethod, uint32_t& a, uint32_t &b) -{ - a = 0; - - if (proto->instanceMethods) { - if (isRequiredMethod && isInstanceMethod) { - b = proto->instanceMethods->indexOfMethod(m); - return; - } - a += proto->instanceMethods->count; - } - - if (proto->classMethods) { - if (isRequiredMethod && !isInstanceMethod) { - b = proto->classMethods->indexOfMethod(m); - return; - } - a += proto->classMethods->count; - } - - if (proto->optionalInstanceMethods) { - if (!isRequiredMethod && isInstanceMethod) { - b = proto->optionalInstanceMethods->indexOfMethod(m); - return; - } - a += proto->optionalInstanceMethods->count; - } - - if (proto->optionalClassMethods) { - if (!isRequiredMethod && !isInstanceMethod) { - b = proto->optionalClassMethods->indexOfMethod(m); - return; - } - a += proto->optionalClassMethods->count; - } -} - - -/*********************************************************************** -* getExtendedTypesIndexForMethod -* Returns the index of m's extended types in proto's extended types array. -**********************************************************************/ -static uint32_t getExtendedTypesIndexForMethod(protocol_t *proto, const method_t *m, bool isRequiredMethod, bool isInstanceMethod) -{ - uint32_t a; - uint32_t b; - getExtendedTypesIndexesForMethod(proto, m, isRequiredMethod, - isInstanceMethod, a, b); - return a + b; -} - - -/*********************************************************************** -* fixupProtocolMethodList -* Fixes up a single method list in a protocol. -**********************************************************************/ -static void -fixupProtocolMethodList(protocol_t *proto, method_list_t *mlist, - bool required, bool instance) -{ - runtimeLock.assertWriting(); - - if (!mlist) return; - if (mlist->isFixedUp()) return; - - bool hasExtendedMethodTypes = proto->hasExtendedMethodTypes(); - fixupMethodList(mlist, true/*always copy for simplicity*/, - !hasExtendedMethodTypes/*sort if no ext*/); - - if (hasExtendedMethodTypes) { - // Sort method list and extended method types together. - // fixupMethodList() can't do this. - // fixme COW stomp - uint32_t count = mlist->count; - uint32_t prefix; - uint32_t junk; - getExtendedTypesIndexesForMethod(proto, &mlist->get(0), - required, instance, prefix, junk); - const char **types = proto->extendedMethodTypes; - for (uint32_t i = 0; i < count; i++) { - for (uint32_t j = i+1; j < count; j++) { - method_t& mi = mlist->get(i); - method_t& mj = mlist->get(j); - if (mi.name > mj.name) { - std::swap(mi, mj); - std::swap(types[prefix+i], types[prefix+j]); - } - } - } - } -} - - -/*********************************************************************** -* fixupProtocol -* Fixes up all of a protocol's method lists. -**********************************************************************/ -static void -fixupProtocol(protocol_t *proto) -{ - runtimeLock.assertWriting(); - - if (proto->protocols) { - for (uintptr_t i = 0; i < proto->protocols->count; i++) { - protocol_t *sub = remapProtocol(proto->protocols->list[i]); - if (!sub->isFixedUp()) fixupProtocol(sub); - } - } - - fixupProtocolMethodList(proto, proto->instanceMethods, YES, YES); - fixupProtocolMethodList(proto, proto->classMethods, YES, NO); - fixupProtocolMethodList(proto, proto->optionalInstanceMethods, NO, YES); - fixupProtocolMethodList(proto, proto->optionalClassMethods, NO, NO); - - // fixme memory barrier so we can check this with no lock - proto->setFixedUp(); -} - - -/*********************************************************************** -* fixupProtocolIfNeeded -* Fixes up all of a protocol's method lists if they aren't fixed up already. -* Locking: write-locks runtimeLock. -**********************************************************************/ -static void -fixupProtocolIfNeeded(protocol_t *proto) -{ - runtimeLock.assertUnlocked(); - assert(proto); - - if (!proto->isFixedUp()) { - rwlock_writer_t lock(runtimeLock); - fixupProtocol(proto); - } -} - - -static method_list_t * -getProtocolMethodList(protocol_t *proto, bool required, bool instance) -{ - method_list_t **mlistp = nil; - if (required) { - if (instance) { - mlistp = &proto->instanceMethods; - } else { - mlistp = &proto->classMethods; - } - } else { - if (instance) { - mlistp = &proto->optionalInstanceMethods; - } else { - mlistp = &proto->optionalClassMethods; - } - } - - return *mlistp; -} - - -/*********************************************************************** -* protocol_getMethod_nolock -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static method_t * -protocol_getMethod_nolock(protocol_t *proto, SEL sel, - bool isRequiredMethod, bool isInstanceMethod, - bool recursive) -{ - runtimeLock.assertLocked(); - - if (!proto || !sel) return nil; - - assert(proto->isFixedUp()); - - method_list_t *mlist = - getProtocolMethodList(proto, isRequiredMethod, isInstanceMethod); - if (mlist) { - method_t *m = search_method_list(mlist, sel); - if (m) return m; - } - - if (recursive && proto->protocols) { - method_t *m; - for (uint32_t i = 0; i < proto->protocols->count; i++) { - protocol_t *realProto = remapProtocol(proto->protocols->list[i]); - m = protocol_getMethod_nolock(realProto, sel, - isRequiredMethod, isInstanceMethod, - true); - if (m) return m; - } - } - - return nil; -} - - -/*********************************************************************** -* protocol_getMethod -* fixme -* Locking: acquires runtimeLock -**********************************************************************/ -Method -protocol_getMethod(protocol_t *proto, SEL sel, bool isRequiredMethod, bool isInstanceMethod, bool recursive) -{ - if (!proto) return nil; - fixupProtocolIfNeeded(proto); - - rwlock_reader_t lock(runtimeLock); - return protocol_getMethod_nolock(proto, sel, isRequiredMethod, - isInstanceMethod, recursive); -} - - -/*********************************************************************** -* protocol_getMethodTypeEncoding_nolock -* Return the @encode string for the requested protocol method. -* Returns nil if the compiler did not emit any extended @encode data. -* Locking: runtimeLock must be held for writing by the caller -**********************************************************************/ -const char * -protocol_getMethodTypeEncoding_nolock(protocol_t *proto, SEL sel, - bool isRequiredMethod, - bool isInstanceMethod) -{ - runtimeLock.assertLocked(); - - if (!proto) return nil; - if (!proto->hasExtendedMethodTypes()) return nil; - - assert(proto->isFixedUp()); - - method_t *m = - protocol_getMethod_nolock(proto, sel, - isRequiredMethod, isInstanceMethod, false); - if (m) { - uint32_t i = getExtendedTypesIndexForMethod(proto, m, - isRequiredMethod, - isInstanceMethod); - return proto->extendedMethodTypes[i]; - } - - // No method with that name. Search incorporated protocols. - if (proto->protocols) { - for (uintptr_t i = 0; i < proto->protocols->count; i++) { - const char *enc = - protocol_getMethodTypeEncoding_nolock(remapProtocol(proto->protocols->list[i]), sel, isRequiredMethod, isInstanceMethod); - if (enc) return enc; - } - } - - return nil; -} - -/*********************************************************************** -* _protocol_getMethodTypeEncoding -* Return the @encode string for the requested protocol method. -* Returns nil if the compiler did not emit any extended @encode data. -* Locking: acquires runtimeLock -**********************************************************************/ -const char * -_protocol_getMethodTypeEncoding(Protocol *proto_gen, SEL sel, - BOOL isRequiredMethod, BOOL isInstanceMethod) -{ - protocol_t *proto = newprotocol(proto_gen); - - if (!proto) return nil; - fixupProtocolIfNeeded(proto); - - rwlock_reader_t lock(runtimeLock); - return protocol_getMethodTypeEncoding_nolock(proto, sel, - isRequiredMethod, - isInstanceMethod); -} - - -/*********************************************************************** -* protocol_t::demangledName -* Returns the (Swift-demangled) name of the given protocol. -* Locking: none -**********************************************************************/ -const char * -protocol_t::demangledName() -{ - assert(size >= offsetof(protocol_t, _demangledName)+sizeof(_demangledName)); - - if (! _demangledName) { - char *de = copySwiftV1DemangledName(mangledName, true/*isProtocol*/); - if (! OSAtomicCompareAndSwapPtrBarrier(nil, (void*)(de ?: mangledName), - (void**)&_demangledName)) - { - if (de) free(de); - } - } - return _demangledName; -} - -/*********************************************************************** -* protocol_getName -* Returns the (Swift-demangled) name of the given protocol. -* Locking: runtimeLock must not be held by the caller -**********************************************************************/ -const char * -protocol_getName(Protocol *proto) -{ - if (!proto) return "nil"; - else return newprotocol(proto)->demangledName(); -} - - -/*********************************************************************** -* protocol_getInstanceMethodDescription -* Returns the description of a named instance method. -* Locking: runtimeLock must not be held by the caller -**********************************************************************/ -struct objc_method_description -protocol_getMethodDescription(Protocol *p, SEL aSel, - BOOL isRequiredMethod, BOOL isInstanceMethod) -{ - Method m = - protocol_getMethod(newprotocol(p), aSel, - isRequiredMethod, isInstanceMethod, true); - if (m) return *method_getDescription(m); - else return (struct objc_method_description){nil, nil}; -} - - -/*********************************************************************** -* protocol_conformsToProtocol_nolock -* Returns YES if self conforms to other. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static bool -protocol_conformsToProtocol_nolock(protocol_t *self, protocol_t *other) -{ - runtimeLock.assertLocked(); - - if (!self || !other) { - return NO; - } - - // protocols need not be fixed up - - if (0 == strcmp(self->mangledName, other->mangledName)) { - return YES; - } - - if (self->protocols) { - uintptr_t i; - for (i = 0; i < self->protocols->count; i++) { - protocol_t *proto = remapProtocol(self->protocols->list[i]); - if (0 == strcmp(other->mangledName, proto->mangledName)) { - return YES; - } - if (protocol_conformsToProtocol_nolock(proto, other)) { - return YES; - } - } - } - - return NO; -} - - -/*********************************************************************** -* protocol_conformsToProtocol -* Returns YES if self conforms to other. -* Locking: acquires runtimeLock -**********************************************************************/ -BOOL protocol_conformsToProtocol(Protocol *self, Protocol *other) -{ - rwlock_reader_t lock(runtimeLock); - return protocol_conformsToProtocol_nolock(newprotocol(self), - newprotocol(other)); -} - - -/*********************************************************************** -* protocol_isEqual -* Return YES if two protocols are equal (i.e. conform to each other) -* Locking: acquires runtimeLock -**********************************************************************/ -BOOL protocol_isEqual(Protocol *self, Protocol *other) -{ - if (self == other) return YES; - if (!self || !other) return NO; - - if (!protocol_conformsToProtocol(self, other)) return NO; - if (!protocol_conformsToProtocol(other, self)) return NO; - - return YES; -} - - -/*********************************************************************** -* protocol_copyMethodDescriptionList -* Returns descriptions of a protocol's methods. -* Locking: acquires runtimeLock -**********************************************************************/ -struct objc_method_description * -protocol_copyMethodDescriptionList(Protocol *p, - BOOL isRequiredMethod,BOOL isInstanceMethod, - unsigned int *outCount) -{ - protocol_t *proto = newprotocol(p); - struct objc_method_description *result = nil; - unsigned int count = 0; - - if (!proto) { - if (outCount) *outCount = 0; - return nil; - } - - fixupProtocolIfNeeded(proto); - - rwlock_reader_t lock(runtimeLock); - - method_list_t *mlist = - getProtocolMethodList(proto, isRequiredMethod, isInstanceMethod); - - if (mlist) { - result = (struct objc_method_description *) - calloc(mlist->count + 1, sizeof(struct objc_method_description)); - for (const auto& meth : *mlist) { - result[count].name = meth.name; - result[count].types = (char *)meth.types; - count++; - } - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* protocol_getProperty -* fixme -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static property_t * -protocol_getProperty_nolock(protocol_t *proto, const char *name, - bool isRequiredProperty, bool isInstanceProperty) -{ - runtimeLock.assertLocked(); - - if (!isRequiredProperty || !isInstanceProperty) { - // Only required instance properties are currently supported - return nil; - } - - property_list_t *plist; - if ((plist = proto->instanceProperties)) { - for (auto& prop : *plist) { - if (0 == strcmp(name, prop.name)) { - return ∝ - } - } - } - - if (proto->protocols) { - uintptr_t i; - for (i = 0; i < proto->protocols->count; i++) { - protocol_t *p = remapProtocol(proto->protocols->list[i]); - property_t *prop = - protocol_getProperty_nolock(p, name, - isRequiredProperty, - isInstanceProperty); - if (prop) return prop; - } - } - - return nil; -} - -objc_property_t protocol_getProperty(Protocol *p, const char *name, - BOOL isRequiredProperty, BOOL isInstanceProperty) -{ - if (!p || !name) return nil; - - rwlock_reader_t lock(runtimeLock); - return (objc_property_t) - protocol_getProperty_nolock(newprotocol(p), name, - isRequiredProperty, isInstanceProperty); -} - - -/*********************************************************************** -* protocol_copyPropertyList -* fixme -* Locking: acquires runtimeLock -**********************************************************************/ -static property_t ** -copyPropertyList(property_list_t *plist, unsigned int *outCount) -{ - property_t **result = nil; - unsigned int count = 0; - - if (plist) { - count = plist->count; - } - - if (count > 0) { - result = (property_t **)malloc((count+1) * sizeof(property_t *)); - - count = 0; - for (auto& prop : *plist) { - result[count++] = ∝ - } - result[count] = nil; - } - - if (outCount) *outCount = count; - return result; -} - -objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount) -{ - if (!proto) { - if (outCount) *outCount = 0; - return nil; - } - - rwlock_reader_t lock(runtimeLock); - - property_list_t *plist = newprotocol(proto)->instanceProperties; - return (objc_property_t *)copyPropertyList(plist, outCount); -} - - -/*********************************************************************** -* protocol_copyProtocolList -* Copies this protocol's incorporated protocols. -* Does not copy those protocol's incorporated protocols in turn. -* Locking: acquires runtimeLock -**********************************************************************/ -Protocol * __unsafe_unretained * -protocol_copyProtocolList(Protocol *p, unsigned int *outCount) -{ - unsigned int count = 0; - Protocol **result = nil; - protocol_t *proto = newprotocol(p); - - if (!proto) { - if (outCount) *outCount = 0; - return nil; - } - - rwlock_reader_t lock(runtimeLock); - - if (proto->protocols) { - count = (unsigned int)proto->protocols->count; - } - if (count > 0) { - result = (Protocol **)malloc((count+1) * sizeof(Protocol *)); - - unsigned int i; - for (i = 0; i < count; i++) { - result[i] = (Protocol *)remapProtocol(proto->protocols->list[i]); - } - result[i] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* objc_allocateProtocol -* Creates a new protocol. The protocol may not be used until -* objc_registerProtocol() is called. -* Returns nil if a protocol with the same name already exists. -* Locking: acquires runtimeLock -**********************************************************************/ -Protocol * -objc_allocateProtocol(const char *name) -{ - rwlock_writer_t lock(runtimeLock); - - if (getProtocol(name)) { - return nil; - } - - protocol_t *result = (protocol_t *)calloc(sizeof(protocol_t), 1); - - extern objc_class OBJC_CLASS_$___IncompleteProtocol; - Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol; - result->initProtocolIsa(cls); - result->size = sizeof(protocol_t); - // fixme mangle the name if it looks swift-y? - result->mangledName = strdup(name); - - // fixme reserve name without installing - - return (Protocol *)result; -} - - -/*********************************************************************** -* objc_registerProtocol -* Registers a newly-constructed protocol. The protocol is now -* ready for use and immutable. -* Locking: acquires runtimeLock -**********************************************************************/ -void objc_registerProtocol(Protocol *proto_gen) -{ - protocol_t *proto = newprotocol(proto_gen); - - rwlock_writer_t lock(runtimeLock); - - extern objc_class OBJC_CLASS_$___IncompleteProtocol; - Class oldcls = (Class)&OBJC_CLASS_$___IncompleteProtocol; - extern objc_class OBJC_CLASS_$_Protocol; - Class cls = (Class)&OBJC_CLASS_$_Protocol; - - if (proto->ISA() == cls) { - _objc_inform("objc_registerProtocol: protocol '%s' was already " - "registered!", proto->nameForLogging()); - return; - } - if (proto->ISA() != oldcls) { - _objc_inform("objc_registerProtocol: protocol '%s' was not allocated " - "with objc_allocateProtocol!", proto->nameForLogging()); - return; - } - - // NOT initProtocolIsa(). The protocol object may already - // have been retained and we must preserve that count. - proto->changeIsa(cls); - - NXMapKeyCopyingInsert(protocols(), proto->mangledName, proto); -} - - -/*********************************************************************** -* protocol_addProtocol -* Adds an incorporated protocol to another protocol. -* No method enforcement is performed. -* `proto` must be under construction. `addition` must not. -* Locking: acquires runtimeLock -**********************************************************************/ -void -protocol_addProtocol(Protocol *proto_gen, Protocol *addition_gen) -{ - protocol_t *proto = newprotocol(proto_gen); - protocol_t *addition = newprotocol(addition_gen); - - extern objc_class OBJC_CLASS_$___IncompleteProtocol; - Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol; - - if (!proto_gen) return; - if (!addition_gen) return; - - rwlock_writer_t lock(runtimeLock); - - if (proto->ISA() != cls) { - _objc_inform("protocol_addProtocol: modified protocol '%s' is not " - "under construction!", proto->nameForLogging()); - return; - } - if (addition->ISA() == cls) { - _objc_inform("protocol_addProtocol: added protocol '%s' is still " - "under construction!", addition->nameForLogging()); - return; - } - - protocol_list_t *protolist = proto->protocols; - if (!protolist) { - protolist = (protocol_list_t *) - calloc(1, sizeof(protocol_list_t) - + sizeof(protolist->list[0])); - } else { - protolist = (protocol_list_t *) - realloc(protolist, protocol_list_size(protolist) - + sizeof(protolist->list[0])); - } - - protolist->list[protolist->count++] = (protocol_ref_t)addition; - proto->protocols = protolist; -} - - -/*********************************************************************** -* protocol_addMethodDescription -* Adds a method to a protocol. The protocol must be under construction. -* Locking: acquires runtimeLock -**********************************************************************/ -static void -protocol_addMethod_nolock(method_list_t*& list, SEL name, const char *types) -{ - if (!list) { - list = (method_list_t *)calloc(sizeof(method_list_t), 1); - list->entsizeAndFlags = sizeof(list->first); - list->setFixedUp(); - } else { - size_t size = list->byteSize() + list->entsize(); - list = (method_list_t *)realloc(list, size); - } - - method_t& meth = list->get(list->count++); - meth.name = name; - meth.types = strdup(types ? types : ""); - meth.imp = nil; -} - -void -protocol_addMethodDescription(Protocol *proto_gen, SEL name, const char *types, - BOOL isRequiredMethod, BOOL isInstanceMethod) -{ - protocol_t *proto = newprotocol(proto_gen); - - extern objc_class OBJC_CLASS_$___IncompleteProtocol; - Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol; - - if (!proto_gen) return; - - rwlock_writer_t lock(runtimeLock); - - if (proto->ISA() != cls) { - _objc_inform("protocol_addMethodDescription: protocol '%s' is not " - "under construction!", proto->nameForLogging()); - return; - } - - if (isRequiredMethod && isInstanceMethod) { - protocol_addMethod_nolock(proto->instanceMethods, name, types); - } else if (isRequiredMethod && !isInstanceMethod) { - protocol_addMethod_nolock(proto->classMethods, name, types); - } else if (!isRequiredMethod && isInstanceMethod) { - protocol_addMethod_nolock(proto->optionalInstanceMethods, name,types); - } else /* !isRequiredMethod && !isInstanceMethod) */ { - protocol_addMethod_nolock(proto->optionalClassMethods, name, types); - } -} - - -/*********************************************************************** -* protocol_addProperty -* Adds a property to a protocol. The protocol must be under construction. -* Locking: acquires runtimeLock -**********************************************************************/ -static void -protocol_addProperty_nolock(property_list_t *&plist, const char *name, - const objc_property_attribute_t *attrs, - unsigned int count) -{ - if (!plist) { - plist = (property_list_t *)calloc(sizeof(property_list_t), 1); - plist->entsizeAndFlags = sizeof(property_t); - } else { - plist = (property_list_t *) - realloc(plist, sizeof(property_list_t) - + plist->count * plist->entsize()); - } - - property_t& prop = plist->get(plist->count++); - prop.name = strdup(name); - prop.attributes = copyPropertyAttributeString(attrs, count); -} - -void -protocol_addProperty(Protocol *proto_gen, const char *name, - const objc_property_attribute_t *attrs, - unsigned int count, - BOOL isRequiredProperty, BOOL isInstanceProperty) -{ - protocol_t *proto = newprotocol(proto_gen); - - extern objc_class OBJC_CLASS_$___IncompleteProtocol; - Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol; - - if (!proto) return; - if (!name) return; - - rwlock_writer_t lock(runtimeLock); - - if (proto->ISA() != cls) { - _objc_inform("protocol_addProperty: protocol '%s' is not " - "under construction!", proto->nameForLogging()); - return; - } - - if (isRequiredProperty && isInstanceProperty) { - protocol_addProperty_nolock(proto->instanceProperties, name, attrs, count); - } - //else if (isRequiredProperty && !isInstanceProperty) { - // protocol_addProperty_nolock(proto->classProperties, name, attrs, count); - //} else if (!isRequiredProperty && isInstanceProperty) { - // protocol_addProperty_nolock(proto->optionalInstanceProperties, name, attrs, count); - //} else /* !isRequiredProperty && !isInstanceProperty) */ { - // protocol_addProperty_nolock(proto->optionalClassProperties, name, attrs, count); - //} -} - - -/*********************************************************************** -* objc_getClassList -* Returns pointers to all classes. -* This requires all classes be realized, which is regretfully non-lazy. -* Locking: acquires runtimeLock -**********************************************************************/ -int -objc_getClassList(Class *buffer, int bufferLen) -{ - rwlock_writer_t lock(runtimeLock); - - realizeAllClasses(); - - int count; - Class cls; - NXHashState state; - NXHashTable *classes = realizedClasses(); - int allCount = NXCountHashTable(classes); - - if (!buffer) { - return allCount; - } - - count = 0; - state = NXInitHashState(classes); - while (count < bufferLen && - NXNextHashState(classes, &state, (void **)&cls)) - { - buffer[count++] = cls; - } - - return allCount; -} - - -/*********************************************************************** -* objc_copyClassList -* Returns pointers to all classes. -* This requires all classes be realized, which is regretfully non-lazy. -* -* outCount may be nil. *outCount is the number of classes returned. -* If the returned array is not nil, it is nil-terminated and must be -* freed with free(). -* Locking: write-locks runtimeLock -**********************************************************************/ -Class * -objc_copyClassList(unsigned int *outCount) -{ - rwlock_writer_t lock(runtimeLock); - - realizeAllClasses(); - - Class *result = nil; - NXHashTable *classes = realizedClasses(); - unsigned int count = NXCountHashTable(classes); - - if (count > 0) { - Class cls; - NXHashState state = NXInitHashState(classes); - result = (Class *)malloc((1+count) * sizeof(Class)); - count = 0; - while (NXNextHashState(classes, &state, (void **)&cls)) { - result[count++] = cls; - } - result[count] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* objc_copyProtocolList -* Returns pointers to all protocols. -* Locking: read-locks runtimeLock -**********************************************************************/ -Protocol * __unsafe_unretained * -objc_copyProtocolList(unsigned int *outCount) -{ - rwlock_reader_t lock(runtimeLock); - - NXMapTable *protocol_map = protocols(); - - unsigned int count = NXCountMapTable(protocol_map); - if (count == 0) { - if (outCount) *outCount = 0; - return nil; - } - - Protocol **result = (Protocol **)malloc((count+1) * sizeof(Protocol*)); - - unsigned int i = 0; - Protocol *proto; - const char *name; - NXMapState state = NXInitMapState(protocol_map); - while (NXNextMapState(protocol_map, &state, - (const void **)&name, (const void **)&proto)) - { - result[i++] = proto; - } - - result[i++] = nil; - assert(i == count+1); - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* objc_getProtocol -* Get a protocol by name, or return nil -* Locking: read-locks runtimeLock -**********************************************************************/ -Protocol *objc_getProtocol(const char *name) -{ - rwlock_reader_t lock(runtimeLock); - return getProtocol(name); -} - - -/*********************************************************************** -* class_copyMethodList -* fixme -* Locking: read-locks runtimeLock -**********************************************************************/ -Method * -class_copyMethodList(Class cls, unsigned int *outCount) -{ - unsigned int count = 0; - Method *result = nil; - - if (!cls) { - if (outCount) *outCount = 0; - return nil; - } - - rwlock_reader_t lock(runtimeLock); - - assert(cls->isRealized()); - - count = cls->data()->methods.count(); - - if (count > 0) { - result = (Method *)malloc((count + 1) * sizeof(Method)); - - count = 0; - for (auto& meth : cls->data()->methods) { - if (! ignoreSelector(meth.name)) { - result[count++] = &meth; - } - } - result[count] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* class_copyIvarList -* fixme -* Locking: read-locks runtimeLock -**********************************************************************/ -Ivar * -class_copyIvarList(Class cls, unsigned int *outCount) -{ - const ivar_list_t *ivars; - Ivar *result = nil; - unsigned int count = 0; - - if (!cls) { - if (outCount) *outCount = 0; - return nil; - } - - rwlock_reader_t lock(runtimeLock); - - assert(cls->isRealized()); - - if ((ivars = cls->data()->ro->ivars) && ivars->count) { - result = (Ivar *)malloc((ivars->count+1) * sizeof(Ivar)); - - for (auto& ivar : *ivars) { - if (!ivar.offset) continue; // anonymous bitfield - result[count++] = &ivar; - } - result[count] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* class_copyPropertyList. Returns a heap block containing the -* properties declared in the class, or nil if the class -* declares no properties. Caller must free the block. -* Does not copy any superclass's properties. -* Locking: read-locks runtimeLock -**********************************************************************/ -objc_property_t * -class_copyPropertyList(Class cls, unsigned int *outCount) -{ - if (!cls) { - if (outCount) *outCount = 0; - return nil; - } - - rwlock_reader_t lock(runtimeLock); - - assert(cls->isRealized()); - auto rw = cls->data(); - - property_t **result = nil; - unsigned int count = rw->properties.count(); - if (count > 0) { - result = (property_t **)malloc((count + 1) * sizeof(property_t *)); - - count = 0; - for (auto& prop : rw->properties) { - result[count++] = ∝ - } - result[count] = nil; - } - - if (outCount) *outCount = count; - return (objc_property_t *)result; -} - - -/*********************************************************************** -* objc_class::getLoadMethod -* fixme -* Called only from add_class_to_loadable_list. -* Locking: runtimeLock must be read- or write-locked by the caller. -**********************************************************************/ -IMP -objc_class::getLoadMethod() -{ - runtimeLock.assertLocked(); - - const method_list_t *mlist; - - assert(isRealized()); - assert(ISA()->isRealized()); - assert(!isMetaClass()); - assert(ISA()->isMetaClass()); - - mlist = ISA()->data()->ro->baseMethods(); - if (mlist) { - for (const auto& meth : *mlist) { - const char *name = sel_cname(meth.name); - if (0 == strcmp(name, "load")) { - return meth.imp; - } - } - } - - return nil; -} - - -/*********************************************************************** -* _category_getName -* Returns a category's name. -* Locking: none -**********************************************************************/ -const char * -_category_getName(Category cat) -{ - return cat->name; -} - - -/*********************************************************************** -* _category_getClassName -* Returns a category's class's name -* Called only from add_category_to_loadable_list and -* remove_category_from_loadable_list for logging purposes. -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -const char * -_category_getClassName(Category cat) -{ - runtimeLock.assertLocked(); - return remapClass(cat->cls)->nameForLogging(); -} - - -/*********************************************************************** -* _category_getClass -* Returns a category's class -* Called only by call_category_loads. -* Locking: read-locks runtimeLock -**********************************************************************/ -Class -_category_getClass(Category cat) -{ - rwlock_reader_t lock(runtimeLock); - Class result = remapClass(cat->cls); - assert(result->isRealized()); // ok for call_category_loads' usage - return result; -} - - -/*********************************************************************** -* _category_getLoadMethod -* fixme -* Called only from add_category_to_loadable_list -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -IMP -_category_getLoadMethod(Category cat) -{ - runtimeLock.assertLocked(); - - const method_list_t *mlist; - - mlist = cat->classMethods; - if (mlist) { - for (const auto& meth : *mlist) { - const char *name = sel_cname(meth.name); - if (0 == strcmp(name, "load")) { - return meth.imp; - } - } - } - - return nil; -} - - -/*********************************************************************** -* class_copyProtocolList -* fixme -* Locking: read-locks runtimeLock -**********************************************************************/ -Protocol * __unsafe_unretained * -class_copyProtocolList(Class cls, unsigned int *outCount) -{ - unsigned int count = 0; - Protocol **result = nil; - - if (!cls) { - if (outCount) *outCount = 0; - return nil; - } - - rwlock_reader_t lock(runtimeLock); - - assert(cls->isRealized()); - - count = cls->data()->protocols.count(); - - if (count > 0) { - result = (Protocol **)malloc((count+1) * sizeof(Protocol *)); - - count = 0; - for (const auto& proto : cls->data()->protocols) { - result[count++] = (Protocol *)remapProtocol(proto); - } - result[count] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* _objc_copyClassNamesForImage -* fixme -* Locking: write-locks runtimeLock -**********************************************************************/ -const char ** -_objc_copyClassNamesForImage(header_info *hi, unsigned int *outCount) -{ - size_t count, i, shift; - classref_t *classlist; - const char **names; - - // Need to write-lock in case demangledName() needs to realize a class. - rwlock_writer_t lock(runtimeLock); - - classlist = _getObjc2ClassList(hi, &count); - names = (const char **)malloc((count+1) * sizeof(const char *)); - - shift = 0; - for (i = 0; i < count; i++) { - Class cls = remapClass(classlist[i]); - if (cls) { - names[i-shift] = cls->demangledName(true/*realize*/); - } else { - shift++; // ignored weak-linked class - } - } - count -= shift; - names[count] = nil; - - if (outCount) *outCount = (unsigned int)count; - return names; -} - - -/*********************************************************************** - * _class_getInstanceStart - * Uses alignedInstanceStart() to ensure that ARR layout strings are - * interpreted relative to the first word aligned ivar of an object. - * Locking: none - **********************************************************************/ - -static uint32_t -alignedInstanceStart(Class cls) -{ - assert(cls); - assert(cls->isRealized()); - return (uint32_t)word_align(cls->data()->ro->instanceStart); -} - -uint32_t _class_getInstanceStart(Class cls) { - return alignedInstanceStart(cls); -} - - -/*********************************************************************** -* saveTemporaryString -* Save a string in a thread-local FIFO buffer. -* This is suitable for temporary strings generated for logging purposes. -**********************************************************************/ -static void -saveTemporaryString(char *str) -{ - // Fixed-size FIFO. We free the first string, shift - // the rest, and add the new string to the end. - _objc_pthread_data *data = _objc_fetch_pthread_data(true); - if (data->printableNames[0]) { - free(data->printableNames[0]); - } - int last = countof(data->printableNames) - 1; - for (int i = 0; i < last; i++) { - data->printableNames[i] = data->printableNames[i+1]; - } - data->printableNames[last] = str; -} - - -/*********************************************************************** -* objc_class::nameForLogging -* Returns the class's name, suitable for display. -* The returned memory is TEMPORARY. Print it or copy it immediately. -* Locking: none -**********************************************************************/ -const char * -objc_class::nameForLogging() -{ - // Handle the easy case directly. - if (isRealized() || isFuture()) { - if (data()->demangledName) return data()->demangledName; - } - - char *result; - - const char *name = mangledName(); - char *de = copySwiftV1DemangledName(name); - if (de) result = de; - else result = strdup(name); - - saveTemporaryString(result); - return result; -} - - -/*********************************************************************** -* objc_class::demangledName -* If realize=false, the class must already be realized or future. -* Locking: If realize=true, runtimeLock must be held for writing by the caller. -**********************************************************************/ -const char * -objc_class::demangledName(bool realize) -{ - // Return previously demangled name if available. - if (isRealized() || isFuture()) { - if (data()->demangledName) return data()->demangledName; - } - - // Try demangling the mangled name. - const char *mangled = mangledName(); - char *de = copySwiftV1DemangledName(mangled); - if (isRealized() || isFuture()) { - // Class is already realized or future. - // Save demangling result in rw data. - // We may not own rwlock for writing so use an atomic operation instead. - if (! OSAtomicCompareAndSwapPtrBarrier(nil, (void*)(de ?: mangled), - (void**)&data()->demangledName)) - { - if (de) free(de); - } - return data()->demangledName; - } - - // Class is not yet realized. - if (!de) { - // Name is not mangled. Return it without caching. - return mangled; - } - - // Class is not yet realized and name is mangled. Realize the class. - // Only objc_copyClassNamesForImage() should get here. - runtimeLock.assertWriting(); - assert(realize); - if (realize) { - realizeClass((Class)this); - data()->demangledName = de; - return de; - } else { - return de; // bug - just leak - } -} - - -/*********************************************************************** -* class_getName -* fixme -* Locking: acquires runtimeLock -**********************************************************************/ -const char *class_getName(Class cls) -{ - if (!cls) return "nil"; - assert(cls->isRealized() || cls->isFuture()); - return cls->demangledName(); -} - - -/*********************************************************************** -* class_getVersion -* fixme -* Locking: none -**********************************************************************/ -int -class_getVersion(Class cls) -{ - if (!cls) return 0; - assert(cls->isRealized()); - return cls->data()->version; -} - - -/*********************************************************************** -* class_setVersion -* fixme -* Locking: none -**********************************************************************/ -void -class_setVersion(Class cls, int version) -{ - if (!cls) return; - assert(cls->isRealized()); - cls->data()->version = version; -} - - -static method_t *findMethodInSortedMethodList(SEL key, const method_list_t *list) -{ - assert(list); - - const method_t * const first = &list->first; - const method_t *base = first; - const method_t *probe; - uintptr_t keyValue = (uintptr_t)key; - uint32_t count; - - for (count = list->count; count != 0; count >>= 1) { - probe = base + (count >> 1); - - uintptr_t probeValue = (uintptr_t)probe->name; - - if (keyValue == probeValue) { - // `probe` is a match. - // Rewind looking for the *first* occurrence of this value. - // This is required for correct category overrides. - while (probe > first && keyValue == (uintptr_t)probe[-1].name) { - probe--; - } - return (method_t *)probe; - } - - if (keyValue > probeValue) { - base = probe + 1; - count--; - } - } - - return nil; -} - -/*********************************************************************** -* getMethodNoSuper_nolock -* fixme -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static method_t *search_method_list(const method_list_t *mlist, SEL sel) -{ - int methodListIsFixedUp = mlist->isFixedUp(); - int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t); - - if (__builtin_expect(methodListIsFixedUp && methodListHasExpectedSize, 1)) { - return findMethodInSortedMethodList(sel, mlist); - } else { - // Linear search of unsorted method list - for (auto& meth : *mlist) { - if (meth.name == sel) return &meth; - } - } - -#if DEBUG - // sanity-check negative results - if (mlist->isFixedUp()) { - for (auto& meth : *mlist) { - if (meth.name == sel) { - _objc_fatal("linear search worked when binary search did not"); - } - } - } -#endif - - return nil; -} - -static method_t * -getMethodNoSuper_nolock(Class cls, SEL sel) -{ - runtimeLock.assertLocked(); - - assert(cls->isRealized()); - // fixme nil cls? - // fixme nil sel? - - for (auto mlists = cls->data()->methods.beginLists(), - end = cls->data()->methods.endLists(); - mlists != end; - ++mlists) - { - method_t *m = search_method_list(*mlists, sel); - if (m) return m; - } - - return nil; -} - - -/*********************************************************************** -* getMethod_nolock -* fixme -* Locking: runtimeLock must be read- or write-locked by the caller -**********************************************************************/ -static method_t * -getMethod_nolock(Class cls, SEL sel) -{ - method_t *m = nil; - - runtimeLock.assertLocked(); - - // fixme nil cls? - // fixme nil sel? - - assert(cls->isRealized()); - - while (cls && ((m = getMethodNoSuper_nolock(cls, sel))) == nil) { - cls = cls->superclass; - } - - return m; -} - - -/*********************************************************************** -* _class_getMethod -* fixme -* Locking: read-locks runtimeLock -**********************************************************************/ -static Method _class_getMethod(Class cls, SEL sel) -{ - rwlock_reader_t lock(runtimeLock); - return getMethod_nolock(cls, sel); -} - - -/*********************************************************************** -* class_getInstanceMethod. Return the instance method for the -* specified class and selector. -**********************************************************************/ -Method class_getInstanceMethod(Class cls, SEL sel) -{ - if (!cls || !sel) return nil; - - // This deliberately avoids +initialize because it historically did so. - - // This implementation is a bit weird because it's the only place that - // wants a Method instead of an IMP. - -#warning fixme build and search caches - - // Search method lists, try method resolver, etc. - lookUpImpOrNil(cls, sel, nil, - NO/*initialize*/, NO/*cache*/, YES/*resolver*/); - -#warning fixme build and search caches - - return _class_getMethod(cls, sel); -} - - -/*********************************************************************** -* log_and_fill_cache -* Log this method call. If the logger permits it, fill the method cache. -* cls is the method whose cache should be filled. -* implementer is the class that owns the implementation in question. -**********************************************************************/ -static void -log_and_fill_cache(Class cls, IMP imp, SEL sel, id receiver, Class implementer) -{ -#if SUPPORT_MESSAGE_LOGGING - if (objcMsgLogEnabled) { - bool cacheIt = logMessageSend(implementer->isMetaClass(), - cls->nameForLogging(), - implementer->nameForLogging(), - sel); - if (!cacheIt) return; - } -#endif - cache_fill (cls, sel, imp, receiver); -} - - -/*********************************************************************** -* _class_lookupMethodAndLoadCache. -* Method lookup for dispatchers ONLY. OTHER CODE SHOULD USE lookUpImp(). -* This lookup avoids optimistic cache scan because the dispatcher -* already tried that. -**********************************************************************/ -IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls) -{ - return lookUpImpOrForward(cls, sel, obj, - YES/*initialize*/, NO/*cache*/, YES/*resolver*/); -} - - -/*********************************************************************** -* lookUpImpOrForward. -* The standard IMP lookup. -* initialize==NO tries to avoid +initialize (but sometimes fails) -* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere) -* Most callers should use initialize==YES and cache==YES. -* inst is an instance of cls or a subclass thereof, or nil if none is known. -* If cls is an un-initialized metaclass then a non-nil inst is faster. -* May return _objc_msgForward_impcache. IMPs destined for external use -* must be converted to _objc_msgForward or _objc_msgForward_stret. -* If you don't want forwarding at all, use lookUpImpOrNil() instead. -**********************************************************************/ -IMP lookUpImpOrForward(Class cls, SEL sel, id inst, - bool initialize, bool cache, bool resolver) -{ - Class curClass; - IMP imp = nil; - Method meth; - bool triedResolver = NO; - - runtimeLock.assertUnlocked(); - - // Optimistic cache lookup - if (cache) { - imp = cache_getImp(cls, sel); - if (imp) return imp; - } - - if (!cls->isRealized()) { - rwlock_writer_t lock(runtimeLock); - realizeClass(cls); - } - - if (initialize && !cls->isInitialized()) { - _class_initialize (_class_getNonMetaClass(cls, inst)); - // If sel == initialize, _class_initialize will send +initialize and - // then the messenger will send +initialize again after this - // procedure finishes. Of course, if this is not being called - // from the messenger then it won't happen. 2778172 - } - - // The lock is held to make method-lookup + cache-fill atomic - // with respect to method addition. Otherwise, a category could - // be added but ignored indefinitely because the cache was re-filled - // with the old value after the cache flush on behalf of the category. - retry: - runtimeLock.read(); - - // Ignore GC selectors - if (ignoreSelector(sel)) { - imp = _objc_ignored_method; - cache_fill(cls, sel, imp, inst); - goto done; - } - - // Try this class's cache. - - imp = cache_getImp(cls, sel); - if (imp) goto done; - - // Try this class's method lists. - - meth = getMethodNoSuper_nolock(cls, sel); - if (meth) { - log_and_fill_cache(cls, meth->imp, sel, inst, cls); - imp = meth->imp; - goto done; - } - - // Try superclass caches and method lists. - - curClass = cls; - while ((curClass = curClass->superclass)) { - // Superclass cache. - imp = cache_getImp(curClass, sel); - if (imp) { - if (imp != (IMP)_objc_msgForward_impcache) { - // Found the method in a superclass. Cache it in this class. - log_and_fill_cache(cls, imp, sel, inst, curClass); - goto done; - } - else { - // Found a forward:: entry in a superclass. - // Stop searching, but don't cache yet; call method - // resolver for this class first. - break; - } - } - - // Superclass method list. - meth = getMethodNoSuper_nolock(curClass, sel); - if (meth) { - log_and_fill_cache(cls, meth->imp, sel, inst, curClass); - imp = meth->imp; - goto done; - } - } - - // No implementation found. Try method resolver once. - - if (resolver && !triedResolver) { - runtimeLock.unlockRead(); - _class_resolveMethod(cls, sel, inst); - // Don't cache the result; we don't hold the lock so it may have - // changed already. Re-do the search from scratch instead. - triedResolver = YES; - goto retry; - } - - // No implementation found, and method resolver didn't help. - // Use forwarding. - - imp = (IMP)_objc_msgForward_impcache; - cache_fill(cls, sel, imp, inst); - - done: - runtimeLock.unlockRead(); - - // paranoia: look for ignored selectors with non-ignored implementations - assert(!(ignoreSelector(sel) && imp != (IMP)&_objc_ignored_method)); - - // paranoia: never let uncached leak out - assert(imp != _objc_msgSend_uncached_impcache); - - return imp; -} - - -/*********************************************************************** -* lookUpImpOrNil. -* Like lookUpImpOrForward, but returns nil instead of _objc_msgForward_impcache -**********************************************************************/ -IMP lookUpImpOrNil(Class cls, SEL sel, id inst, - bool initialize, bool cache, bool resolver) -{ - IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver); - if (imp == _objc_msgForward_impcache) return nil; - else return imp; -} - - -/*********************************************************************** -* lookupMethodInClassAndLoadCache. -* Like _class_lookupMethodAndLoadCache, but does not search superclasses. -* Caches and returns objc_msgForward if the method is not found in the class. -**********************************************************************/ -IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel) -{ - Method meth; - IMP imp; - - // fixme this is incomplete - no resolver, +initialize, GC - - // but it's only used for .cxx_construct/destruct so we don't care - assert(sel == SEL_cxx_construct || sel == SEL_cxx_destruct); - - // Search cache first. - imp = cache_getImp(cls, sel); - if (imp) return imp; - - // Cache miss. Search method list. - - rwlock_reader_t lock(runtimeLock); - - meth = getMethodNoSuper_nolock(cls, sel); - - if (meth) { - // Hit in method list. Cache it. - cache_fill(cls, sel, meth->imp, nil); - return meth->imp; - } else { - // Miss in method list. Cache objc_msgForward. - cache_fill(cls, sel, _objc_msgForward_impcache, nil); - return _objc_msgForward_impcache; - } -} - - -/*********************************************************************** -* class_getProperty -* fixme -* Locking: read-locks runtimeLock -**********************************************************************/ -objc_property_t class_getProperty(Class cls, const char *name) -{ - if (!cls || !name) return nil; - - rwlock_reader_t lock(runtimeLock); - - assert(cls->isRealized()); - - for ( ; cls; cls = cls->superclass) { - for (auto& prop : cls->data()->properties) { - if (0 == strcmp(name, prop.name)) { - return (objc_property_t)∝ - } - } - } - - return nil; -} - - -/*********************************************************************** -* Locking: fixme -**********************************************************************/ - -Class gdb_class_getClass(Class cls) -{ - const char *className = cls->mangledName(); - if(!className || !strlen(className)) return Nil; - Class rCls = look_up_class(className, NO, NO); - return rCls; -} - -Class gdb_object_getClass(id obj) -{ - if (!obj) return nil; - return gdb_class_getClass(obj->getIsa()); -} - - -/*********************************************************************** -* Locking: write-locks runtimeLock -**********************************************************************/ -void -objc_class::setInitialized() -{ - Class metacls; - Class cls; - - assert(!isMetaClass()); - - cls = (Class)this; - metacls = cls->ISA(); - - rwlock_reader_t lock(runtimeLock); - - // Scan metaclass for custom AWZ. - // Scan metaclass for custom RR. - // Scan class for custom RR. - // Also print custom RR/AWZ because we probably haven't done it yet. - - // Special cases: - // GC's RR and AWZ are never default. - // NSObject AWZ class methods are default. - // NSObject RR instance methods are default. - // updateCustomRR_AWZ() also knows these special cases. - // attachMethodLists() also knows these special cases. - - bool inherited; - bool metaCustomAWZ = NO; - if (UseGC) { - // GC is always custom AWZ - metaCustomAWZ = YES; - inherited = NO; - } - else if (MetaclassNSObjectAWZSwizzled) { - // Somebody already swizzled NSObject's methods - metaCustomAWZ = YES; - inherited = NO; - } - else if (metacls == classNSObject()->ISA()) { - // NSObject's metaclass AWZ is default, but we still need to check cats - auto& methods = metacls->data()->methods; - for (auto mlists = methods.beginCategoryMethodLists(), - end = methods.endCategoryMethodLists(metacls); - mlists != end; - ++mlists) - { - if (methodListImplementsAWZ(*mlists)) { - metaCustomAWZ = YES; - inherited = NO; - break; - } - } - } - else if (metacls->superclass->hasCustomAWZ()) { - // Superclass is custom AWZ, therefore we are too. - metaCustomAWZ = YES; - inherited = YES; - } - else { - // Not metaclass NSObject. - auto& methods = metacls->data()->methods; - for (auto mlists = methods.beginLists(), - end = methods.endLists(); - mlists != end; - ++mlists) - { - if (methodListImplementsAWZ(*mlists)) { - metaCustomAWZ = YES; - inherited = NO; - break; - } - } - } - if (!metaCustomAWZ) metacls->setHasDefaultAWZ(); - - if (PrintCustomAWZ && metaCustomAWZ) metacls->printCustomAWZ(inherited); - // metacls->printCustomRR(); - - - bool clsCustomRR = NO; - if (UseGC) { - // GC is always custom RR - clsCustomRR = YES; - inherited = NO; - } - else if (ClassNSObjectRRSwizzled) { - // Somebody already swizzled NSObject's methods - clsCustomRR = YES; - inherited = NO; - } - if (cls == classNSObject()) { - // NSObject's RR is default, but we still need to check categories - auto& methods = cls->data()->methods; - for (auto mlists = methods.beginCategoryMethodLists(), - end = methods.endCategoryMethodLists(cls); - mlists != end; - ++mlists) - { - if (methodListImplementsRR(*mlists)) { - clsCustomRR = YES; - inherited = NO; - break; - } - } - } - else if (!cls->superclass) { - // Custom root class - clsCustomRR = YES; - inherited = NO; - } - else if (cls->superclass->hasCustomRR()) { - // Superclass is custom RR, therefore we are too. - clsCustomRR = YES; - inherited = YES; - } - else { - // Not class NSObject. - auto& methods = cls->data()->methods; - for (auto mlists = methods.beginLists(), - end = methods.endLists(); - mlists != end; - ++mlists) - { - if (methodListImplementsRR(*mlists)) { - clsCustomRR = YES; - inherited = NO; - break; - } - } - } - if (!clsCustomRR) cls->setHasDefaultRR(); - - // cls->printCustomAWZ(); - if (PrintCustomRR && clsCustomRR) cls->printCustomRR(inherited); - - // Update the +initialize flags. - // Do this last. - metacls->changeInfo(RW_INITIALIZED, RW_INITIALIZING); -} - - -/*********************************************************************** - * _class_usesAutomaticRetainRelease - * Returns YES if class was compiled with -fobjc-arc - **********************************************************************/ -BOOL _class_usesAutomaticRetainRelease(Class cls) -{ - return bool(cls->data()->ro->flags & RO_IS_ARR); -} - - -/*********************************************************************** -* Return YES if sel is used by retain/release implementors -**********************************************************************/ -static bool -isRRSelector(SEL sel) -{ - return (sel == SEL_retain || sel == SEL_release || - sel == SEL_autorelease || sel == SEL_retainCount || - sel == SEL_tryRetain || sel == SEL_retainWeakReference || - sel == SEL_isDeallocating || sel == SEL_allowsWeakReference); -} - - -/*********************************************************************** -* Return YES if mlist implements one of the isRRSelector() methods -**********************************************************************/ -static bool -methodListImplementsRR(const method_list_t *mlist) -{ - return (search_method_list(mlist, SEL_retain) || - search_method_list(mlist, SEL_release) || - search_method_list(mlist, SEL_autorelease) || - search_method_list(mlist, SEL_retainCount) || - search_method_list(mlist, SEL_tryRetain) || - search_method_list(mlist, SEL_isDeallocating) || - search_method_list(mlist, SEL_retainWeakReference) || - search_method_list(mlist, SEL_allowsWeakReference)); -} - - -/*********************************************************************** -* Return YES if sel is used by alloc or allocWithZone implementors -**********************************************************************/ -static bool -isAWZSelector(SEL sel) -{ - return (sel == SEL_allocWithZone || sel == SEL_alloc); -} - - -/*********************************************************************** -* Return YES if mlist implements one of the isAWZSelector() methods -**********************************************************************/ -static bool -methodListImplementsAWZ(const method_list_t *mlist) -{ - return (search_method_list(mlist, SEL_allocWithZone) || - search_method_list(mlist, SEL_alloc)); -} - - -void -objc_class::printCustomRR(bool inherited) -{ - assert(PrintCustomRR); - assert(hasCustomRR()); - _objc_inform("CUSTOM RR: %s%s%s", nameForLogging(), - isMetaClass() ? " (meta)" : "", - inherited ? " (inherited)" : ""); -} - -void -objc_class::printCustomAWZ(bool inherited) -{ - assert(PrintCustomAWZ); - assert(hasCustomAWZ()); - _objc_inform("CUSTOM AWZ: %s%s%s", nameForLogging(), - isMetaClass() ? " (meta)" : "", - inherited ? " (inherited)" : ""); -} - -void -objc_class::printRequiresRawIsa(bool inherited) -{ - assert(PrintRawIsa); - assert(requiresRawIsa()); - _objc_inform("RAW ISA: %s%s%s", nameForLogging(), - isMetaClass() ? " (meta)" : "", - inherited ? " (inherited)" : ""); -} - - -/*********************************************************************** -* Mark this class and all of its subclasses as implementors or -* inheritors of custom RR (retain/release/autorelease/retainCount) -**********************************************************************/ -void objc_class::setHasCustomRR(bool inherited) -{ - Class cls = (Class)this; - runtimeLock.assertWriting(); - - if (hasCustomRR()) return; - - foreach_realized_class_and_subclass(cls, ^(Class c){ - if (c != cls && !c->isInitialized()) { - // Subclass not yet initialized. Wait for setInitialized() to do it - // fixme short circuit recursion? - return; - } - if (c->hasCustomRR()) { - // fixme short circuit recursion? - return; - } - - c->bits.setHasCustomRR(); - - if (PrintCustomRR) c->printCustomRR(inherited || c != cls); - }); -} - -/*********************************************************************** -* Mark this class and all of its subclasses as implementors or -* inheritors of custom alloc/allocWithZone: -**********************************************************************/ -void objc_class::setHasCustomAWZ(bool inherited) -{ - Class cls = (Class)this; - runtimeLock.assertWriting(); - - if (hasCustomAWZ()) return; - - foreach_realized_class_and_subclass(cls, ^(Class c){ - if (c != cls && !c->isInitialized()) { - // Subclass not yet initialized. Wait for setInitialized() to do it - // fixme short circuit recursion? - return; - } - if (c->hasCustomAWZ()) { - // fixme short circuit recursion? - return; - } - - c->bits.setHasCustomAWZ(); - - if (PrintCustomAWZ) c->printCustomAWZ(inherited || c != cls); - }); -} - - -/*********************************************************************** -* Mark this class and all of its subclasses as requiring raw isa pointers -**********************************************************************/ -void objc_class::setRequiresRawIsa(bool inherited) -{ - Class cls = (Class)this; - runtimeLock.assertWriting(); - - if (requiresRawIsa()) return; - - foreach_realized_class_and_subclass(cls, ^(Class c){ - if (c->isInitialized()) { - _objc_fatal("too late to require raw isa"); - return; - } - if (c->requiresRawIsa()) { - // fixme short circuit recursion? - return; - } - - c->bits.setRequiresRawIsa(); - - if (PrintRawIsa) c->printRequiresRawIsa(inherited || c != cls); - }); -} - - -/*********************************************************************** -* Update custom RR and AWZ when a method changes its IMP -**********************************************************************/ -static void -updateCustomRR_AWZ(Class cls, method_t *meth) -{ - // In almost all cases, IMP swizzling does not affect custom RR/AWZ bits. - // Custom RR/AWZ search will already find the method whether or not - // it is swizzled, so it does not transition from non-custom to custom. - // - // The only cases where IMP swizzling can affect the RR/AWZ bits is - // if the swizzled method is one of the methods that is assumed to be - // non-custom. These special cases are listed in setInitialized(). - // We look for such cases here. - - if (isRRSelector(meth->name)) { - - if ((classNSObject()->isInitialized() && - classNSObject()->hasCustomRR()) - || - ClassNSObjectRRSwizzled) - { - // already custom, nothing would change - return; - } - - bool swizzlingNSObject = NO; - if (cls == classNSObject()) { - swizzlingNSObject = YES; - } else { - // Don't know the class. - // The only special case is class NSObject. - for (const auto& meth2 : classNSObject()->data()->methods) { - if (meth == &meth2) { - swizzlingNSObject = YES; - break; - } - } - } - if (swizzlingNSObject) { - if (classNSObject()->isInitialized()) { - classNSObject()->setHasCustomRR(); - } else { - // NSObject not yet +initialized, so custom RR has not yet - // been checked, and setInitialized() will not notice the - // swizzle. - ClassNSObjectRRSwizzled = YES; - } - } - } - else if (isAWZSelector(meth->name)) { - Class metaclassNSObject = classNSObject()->ISA(); - - if ((metaclassNSObject->isInitialized() && - metaclassNSObject->hasCustomAWZ()) - || - MetaclassNSObjectAWZSwizzled) - { - // already custom, nothing would change - return; - } - - bool swizzlingNSObject = NO; - if (cls == metaclassNSObject) { - swizzlingNSObject = YES; - } else { - // Don't know the class. - // The only special case is metaclass NSObject. - for (const auto& meth2 : metaclassNSObject->data()->methods) { - if (meth == &meth2) { - swizzlingNSObject = YES; - break; - } - } - } - if (swizzlingNSObject) { - if (metaclassNSObject->isInitialized()) { - metaclassNSObject->setHasCustomAWZ(); - } else { - // NSObject not yet +initialized, so custom RR has not yet - // been checked, and setInitialized() will not notice the - // swizzle. - MetaclassNSObjectAWZSwizzled = YES; - } - } - } -} - - -/*********************************************************************** -* class_getIvarLayout -* Called by the garbage collector. -* The class must be nil or already realized. -* Locking: none -**********************************************************************/ -const uint8_t * -class_getIvarLayout(Class cls) -{ - if (cls) return cls->data()->ro->ivarLayout; - else return nil; -} - - -/*********************************************************************** -* class_getWeakIvarLayout -* Called by the garbage collector. -* The class must be nil or already realized. -* Locking: none -**********************************************************************/ -const uint8_t * -class_getWeakIvarLayout(Class cls) -{ - if (cls) return cls->data()->ro->weakIvarLayout; - else return nil; -} - - -/*********************************************************************** -* class_setIvarLayout -* Changes the class's GC scan layout. -* nil layout means no unscanned ivars -* The class must be under construction. -* fixme: sanity-check layout vs instance size? -* fixme: sanity-check layout vs superclass? -* Locking: acquires runtimeLock -**********************************************************************/ -void -class_setIvarLayout(Class cls, const uint8_t *layout) -{ - if (!cls) return; - - rwlock_writer_t lock(runtimeLock); - - // Can only change layout of in-construction classes. - // note: if modifications to post-construction classes were - // allowed, there would be a race below (us vs. concurrent GC scan) - if (!(cls->data()->flags & RW_CONSTRUCTING)) { - _objc_inform("*** Can't set ivar layout for already-registered " - "class '%s'", cls->nameForLogging()); - return; - } - - class_ro_t *ro_w = make_ro_writeable(cls->data()); - - try_free(ro_w->ivarLayout); - ro_w->ivarLayout = ustrdupMaybeNil(layout); -} - -// SPI: Instance-specific object layout. - -void -_class_setIvarLayoutAccessor(Class cls, const uint8_t* (*accessor) (id object)) { - if (!cls) return; - - rwlock_writer_t lock(runtimeLock); - - class_ro_t *ro_w = make_ro_writeable(cls->data()); - - // FIXME: this really isn't safe to free if there are instances of this class already. - if (!(cls->data()->flags & RW_HAS_INSTANCE_SPECIFIC_LAYOUT)) try_free(ro_w->ivarLayout); - ro_w->ivarLayout = (uint8_t *)accessor; - cls->setInfo(RW_HAS_INSTANCE_SPECIFIC_LAYOUT); -} - -const uint8_t * -_object_getIvarLayout(Class cls, id object) -{ - if (cls) { - const uint8_t* layout = cls->data()->ro->ivarLayout; - if (cls->data()->flags & RW_HAS_INSTANCE_SPECIFIC_LAYOUT) { - const uint8_t* (*accessor) (id object) = (const uint8_t* (*)(id))layout; - layout = accessor(object); - } - return layout; - } - return nil; -} - -/*********************************************************************** -* class_setWeakIvarLayout -* Changes the class's GC weak layout. -* nil layout means no weak ivars -* The class must be under construction. -* fixme: sanity-check layout vs instance size? -* fixme: sanity-check layout vs superclass? -* Locking: acquires runtimeLock -**********************************************************************/ -void -class_setWeakIvarLayout(Class cls, const uint8_t *layout) -{ - if (!cls) return; - - rwlock_writer_t lock(runtimeLock); - - // Can only change layout of in-construction classes. - // note: if modifications to post-construction classes were - // allowed, there would be a race below (us vs. concurrent GC scan) - if (!(cls->data()->flags & RW_CONSTRUCTING)) { - _objc_inform("*** Can't set weak ivar layout for already-registered " - "class '%s'", cls->nameForLogging()); - return; - } - - class_ro_t *ro_w = make_ro_writeable(cls->data()); - - try_free(ro_w->weakIvarLayout); - ro_w->weakIvarLayout = ustrdupMaybeNil(layout); -} - - -/*********************************************************************** -* _class_getVariable -* fixme -* Locking: read-locks runtimeLock -**********************************************************************/ -Ivar -_class_getVariable(Class cls, const char *name, Class *memberOf) -{ - rwlock_reader_t lock(runtimeLock); - - for ( ; cls; cls = cls->superclass) { - ivar_t *ivar = getIvar(cls, name); - if (ivar) { - if (memberOf) *memberOf = cls; - return ivar; - } - } - - return nil; -} - - -/*********************************************************************** -* class_conformsToProtocol -* fixme -* Locking: read-locks runtimeLock -**********************************************************************/ -BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen) -{ - protocol_t *proto = newprotocol(proto_gen); - - if (!cls) return NO; - if (!proto_gen) return NO; - - rwlock_reader_t lock(runtimeLock); - - assert(cls->isRealized()); - - for (const auto& proto_ref : cls->data()->protocols) { - protocol_t *p = remapProtocol(proto_ref); - if (p == proto || protocol_conformsToProtocol_nolock(p, proto)) { - return YES; - } - } - - return NO; -} - - -/********************************************************************** -* addMethod -* fixme -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static IMP -addMethod(Class cls, SEL name, IMP imp, const char *types, bool replace) -{ - IMP result = nil; - - runtimeLock.assertWriting(); - - assert(types); - assert(cls->isRealized()); - - method_t *m; - if ((m = getMethodNoSuper_nolock(cls, name))) { - // already exists - if (!replace) { - result = m->imp; - } else { - result = _method_setImplementation(cls, m, imp); - } - } else { - // fixme optimize - method_list_t *newlist; - newlist = (method_list_t *)calloc(sizeof(*newlist), 1); - newlist->entsizeAndFlags = - (uint32_t)sizeof(method_t) | fixed_up_method_list; - newlist->count = 1; - newlist->first.name = name; - newlist->first.types = strdup(types); - if (!ignoreSelector(name)) { - newlist->first.imp = imp; - } else { - newlist->first.imp = (IMP)&_objc_ignored_method; - } - - prepareMethodLists(cls, &newlist, 1, NO, NO); - cls->data()->methods.attachLists(&newlist, 1); - flushCaches(cls); - - result = nil; - } - - return result; -} - - -BOOL -class_addMethod(Class cls, SEL name, IMP imp, const char *types) -{ - if (!cls) return NO; - - rwlock_writer_t lock(runtimeLock); - return ! addMethod(cls, name, imp, types ?: "", NO); -} - - -IMP -class_replaceMethod(Class cls, SEL name, IMP imp, const char *types) -{ - if (!cls) return nil; - - rwlock_writer_t lock(runtimeLock); - return addMethod(cls, name, imp, types ?: "", YES); -} - - -/*********************************************************************** -* class_addIvar -* Adds an ivar to a class. -* Locking: acquires runtimeLock -**********************************************************************/ -BOOL -class_addIvar(Class cls, const char *name, size_t size, - uint8_t alignment, const char *type) -{ - if (!cls) return NO; - - if (!type) type = ""; - if (name && 0 == strcmp(name, "")) name = nil; - - rwlock_writer_t lock(runtimeLock); - - assert(cls->isRealized()); - - // No class variables - if (cls->isMetaClass()) { - return NO; - } - - // Can only add ivars to in-construction classes. - if (!(cls->data()->flags & RW_CONSTRUCTING)) { - return NO; - } - - // Check for existing ivar with this name, unless it's anonymous. - // Check for too-big ivar. - // fixme check for superclass ivar too? - if ((name && getIvar(cls, name)) || size > UINT32_MAX) { - return NO; - } - - class_ro_t *ro_w = make_ro_writeable(cls->data()); - - // fixme allocate less memory here - - ivar_list_t *oldlist, *newlist; - if ((oldlist = (ivar_list_t *)cls->data()->ro->ivars)) { - size_t oldsize = oldlist->byteSize(); - newlist = (ivar_list_t *)calloc(oldsize + oldlist->entsize(), 1); - memcpy(newlist, oldlist, oldsize); - free(oldlist); - } else { - newlist = (ivar_list_t *)calloc(sizeof(ivar_list_t), 1); - newlist->entsizeAndFlags = (uint32_t)sizeof(ivar_t); - } - - uint32_t offset = cls->unalignedInstanceSize(); - uint32_t alignMask = (1<<alignment)-1; - offset = (offset + alignMask) & ~alignMask; - - ivar_t& ivar = newlist->get(newlist->count++); -#if __x86_64__ - // Deliberately over-allocate the ivar offset variable. - // Use calloc() to clear all 64 bits. See the note in struct ivar_t. - ivar.offset = (int32_t *)(int64_t *)calloc(sizeof(int64_t), 1); -#else - ivar.offset = (int32_t *)malloc(sizeof(int32_t)); -#endif - *ivar.offset = offset; - ivar.name = name ? strdup(name) : nil; - ivar.type = strdup(type); - ivar.alignment_raw = alignment; - ivar.size = (uint32_t)size; - - ro_w->ivars = newlist; - cls->setInstanceSize((uint32_t)(offset + size)); - - // Ivar layout updated in registerClass. - - return YES; -} - - -/*********************************************************************** -* class_addProtocol -* Adds a protocol to a class. -* Locking: acquires runtimeLock -**********************************************************************/ -BOOL class_addProtocol(Class cls, Protocol *protocol_gen) -{ - protocol_t *protocol = newprotocol(protocol_gen); - - if (!cls) return NO; - if (class_conformsToProtocol(cls, protocol_gen)) return NO; - - rwlock_writer_t lock(runtimeLock); - - assert(cls->isRealized()); - - // fixme optimize - protocol_list_t *protolist = (protocol_list_t *) - malloc(sizeof(protocol_list_t) + sizeof(protocol_t *)); - protolist->count = 1; - protolist->list[0] = (protocol_ref_t)protocol; - - cls->data()->protocols.attachLists(&protolist, 1); - - // fixme metaclass? - - return YES; -} - - -/*********************************************************************** -* class_addProperty -* Adds a property to a class. -* Locking: acquires runtimeLock -**********************************************************************/ -static bool -_class_addProperty(Class cls, const char *name, - const objc_property_attribute_t *attrs, unsigned int count, - bool replace) -{ - if (!cls) return NO; - if (!name) return NO; - - property_t *prop = class_getProperty(cls, name); - if (prop && !replace) { - // already exists, refuse to replace - return NO; - } - else if (prop) { - // replace existing - rwlock_writer_t lock(runtimeLock); - try_free(prop->attributes); - prop->attributes = copyPropertyAttributeString(attrs, count); - return YES; - } - else { - rwlock_writer_t lock(runtimeLock); - - assert(cls->isRealized()); - - property_list_t *proplist = (property_list_t *) - malloc(sizeof(*proplist)); - proplist->count = 1; - proplist->entsizeAndFlags = sizeof(proplist->first); - proplist->first.name = strdup(name); - proplist->first.attributes = copyPropertyAttributeString(attrs, count); - - cls->data()->properties.attachLists(&proplist, 1); - - return YES; - } -} - -BOOL -class_addProperty(Class cls, const char *name, - const objc_property_attribute_t *attrs, unsigned int n) -{ - return _class_addProperty(cls, name, attrs, n, NO); -} - -void -class_replaceProperty(Class cls, const char *name, - const objc_property_attribute_t *attrs, unsigned int n) -{ - _class_addProperty(cls, name, attrs, n, YES); -} - - -/*********************************************************************** -* look_up_class -* Look up a class by name, and realize it. -* Locking: acquires runtimeLock -**********************************************************************/ -Class -look_up_class(const char *name, - bool includeUnconnected __attribute__((unused)), - bool includeClassHandler __attribute__((unused))) -{ - if (!name) return nil; - - Class result; - bool unrealized; - { - rwlock_reader_t lock(runtimeLock); - result = getClass(name); - unrealized = result && !result->isRealized(); - } - if (unrealized) { - rwlock_writer_t lock(runtimeLock); - realizeClass(result); - } - return result; -} - - -/*********************************************************************** -* objc_duplicateClass -* fixme -* Locking: acquires runtimeLock -**********************************************************************/ -Class -objc_duplicateClass(Class original, const char *name, - size_t extraBytes) -{ - Class duplicate; - - rwlock_writer_t lock(runtimeLock); - - assert(original->isRealized()); - assert(!original->isMetaClass()); - - duplicate = alloc_class_for_subclass(original, extraBytes); - - duplicate->initClassIsa(original->ISA()); - duplicate->superclass = original->superclass; - - duplicate->cache.initializeToEmpty(); - - class_rw_t *rw = (class_rw_t *)calloc(sizeof(*original->data()), 1); - rw->flags = (original->data()->flags | RW_COPIED_RO | RW_REALIZING); - rw->version = original->data()->version; - rw->firstSubclass = nil; - rw->nextSiblingClass = nil; - - duplicate->bits = original->bits; - duplicate->setData(rw); - - rw->ro = (class_ro_t *) - memdup(original->data()->ro, sizeof(*original->data()->ro)); - *(char **)&rw->ro->name = strdup(name); - - rw->methods = original->data()->methods.duplicate(); - - // fixme dies when categories are added to the base - rw->properties = original->data()->properties; - rw->protocols = original->data()->protocols; - - if (duplicate->superclass) { - addSubclass(duplicate->superclass, duplicate); - } - - // Don't methodize class - construction above is correct - - addNamedClass(duplicate, duplicate->data()->ro->name); - addRealizedClass(duplicate); - // no: duplicate->ISA == original->ISA - // addRealizedMetaclass(duplicate->ISA); - - if (PrintConnecting) { - _objc_inform("CLASS: realizing class '%s' (duplicate of %s) %p %p", - name, original->nameForLogging(), - (void*)duplicate, duplicate->data()->ro); - } - - duplicate->clearInfo(RW_REALIZING); - - return duplicate; -} - -/*********************************************************************** -* objc_initializeClassPair -* Locking: runtimeLock must be write-locked by the caller -**********************************************************************/ - -// &UnsetLayout is the default ivar layout during class construction -static const uint8_t UnsetLayout = 0; - -static void objc_initializeClassPair_internal(Class superclass, const char *name, Class cls, Class meta) -{ - runtimeLock.assertWriting(); - - class_ro_t *cls_ro_w, *meta_ro_w; - - cls->cache.initializeToEmpty(); - meta->cache.initializeToEmpty(); - - cls->setData((class_rw_t *)calloc(sizeof(class_rw_t), 1)); - meta->setData((class_rw_t *)calloc(sizeof(class_rw_t), 1)); - cls_ro_w = (class_ro_t *)calloc(sizeof(class_ro_t), 1); - meta_ro_w = (class_ro_t *)calloc(sizeof(class_ro_t), 1); - cls->data()->ro = cls_ro_w; - meta->data()->ro = meta_ro_w; - - // Set basic info - - cls->data()->flags = RW_CONSTRUCTING | RW_COPIED_RO | RW_REALIZED | RW_REALIZING; - meta->data()->flags = RW_CONSTRUCTING | RW_COPIED_RO | RW_REALIZED | RW_REALIZING; - cls->data()->version = 0; - meta->data()->version = 7; - - cls_ro_w->flags = 0; - meta_ro_w->flags = RO_META; - if (!superclass) { - cls_ro_w->flags |= RO_ROOT; - meta_ro_w->flags |= RO_ROOT; - } - if (superclass) { - cls_ro_w->instanceStart = superclass->unalignedInstanceSize(); - meta_ro_w->instanceStart = superclass->ISA()->unalignedInstanceSize(); - cls->setInstanceSize(cls_ro_w->instanceStart); - meta->setInstanceSize(meta_ro_w->instanceStart); - } else { - cls_ro_w->instanceStart = 0; - meta_ro_w->instanceStart = (uint32_t)sizeof(objc_class); - cls->setInstanceSize((uint32_t)sizeof(id)); // just an isa - meta->setInstanceSize(meta_ro_w->instanceStart); - } - - cls_ro_w->name = strdup(name); - meta_ro_w->name = strdup(name); - - cls_ro_w->ivarLayout = &UnsetLayout; - cls_ro_w->weakIvarLayout = &UnsetLayout; - - // Connect to superclasses and metaclasses - cls->initClassIsa(meta); - if (superclass) { - meta->initClassIsa(superclass->ISA()->ISA()); - cls->superclass = superclass; - meta->superclass = superclass->ISA(); - addSubclass(superclass, cls); - addSubclass(superclass->ISA(), meta); - } else { - meta->initClassIsa(meta); - cls->superclass = Nil; - meta->superclass = cls; - addSubclass(cls, meta); - } -} - - -/*********************************************************************** -* verifySuperclass -* Sanity-check the superclass provided to -* objc_allocateClassPair, objc_initializeClassPair, or objc_readClassPair. -**********************************************************************/ -bool -verifySuperclass(Class superclass, bool rootOK) -{ - if (!superclass) { - // Superclass does not exist. - // If subclass may be a root class, this is OK. - // If subclass must not be a root class, this is bad. - return rootOK; - } - - // Superclass must be realized. - if (! superclass->isRealized()) return false; - - // Superclass must not be under construction. - if (superclass->data()->flags & RW_CONSTRUCTING) return false; - - return true; -} - - -/*********************************************************************** -* objc_initializeClassPair -**********************************************************************/ -Class objc_initializeClassPair(Class superclass, const char *name, Class cls, Class meta) -{ - rwlock_writer_t lock(runtimeLock); - - // Fail if the class name is in use. - // Fail if the superclass isn't kosher. - if (getClass(name) || !verifySuperclass(superclass, true/*rootOK*/)) { - return nil; - } - - objc_initializeClassPair_internal(superclass, name, cls, meta); - - return cls; -} - - -/*********************************************************************** -* objc_allocateClassPair -* fixme -* Locking: acquires runtimeLock -**********************************************************************/ -Class objc_allocateClassPair(Class superclass, const char *name, - size_t extraBytes) -{ - Class cls, meta; - - rwlock_writer_t lock(runtimeLock); - - // Fail if the class name is in use. - // Fail if the superclass isn't kosher. - if (getClass(name) || !verifySuperclass(superclass, true/*rootOK*/)) { - return nil; - } - - // Allocate new classes. - cls = alloc_class_for_subclass(superclass, extraBytes); - meta = alloc_class_for_subclass(superclass, extraBytes); - - // fixme mangle the name if it looks swift-y? - objc_initializeClassPair_internal(superclass, name, cls, meta); - - return cls; -} - - -/*********************************************************************** -* objc_registerClassPair -* fixme -* Locking: acquires runtimeLock -**********************************************************************/ -void objc_registerClassPair(Class cls) -{ - rwlock_writer_t lock(runtimeLock); - - if ((cls->data()->flags & RW_CONSTRUCTED) || - (cls->ISA()->data()->flags & RW_CONSTRUCTED)) - { - _objc_inform("objc_registerClassPair: class '%s' was already " - "registered!", cls->data()->ro->name); - return; - } - - if (!(cls->data()->flags & RW_CONSTRUCTING) || - !(cls->ISA()->data()->flags & RW_CONSTRUCTING)) - { - _objc_inform("objc_registerClassPair: class '%s' was not " - "allocated with objc_allocateClassPair!", - cls->data()->ro->name); - return; - } - - // Build ivar layouts - if (UseGC) { - Class supercls = cls->superclass; - class_ro_t *ro_w = (class_ro_t *)cls->data()->ro; - - if (ro_w->ivarLayout != &UnsetLayout) { - // Class builder already called class_setIvarLayout. - } - else if (!supercls) { - // Root class. Scan conservatively (should be isa ivar only). - ro_w->ivarLayout = nil; - } - else if (ro_w->ivars == nil) { - // No local ivars. Use superclass's layouts. - ro_w->ivarLayout = - ustrdupMaybeNil(supercls->data()->ro->ivarLayout); - } - else { - // Has local ivars. Build layouts based on superclass. - layout_bitmap bitmap = - layout_bitmap_create(supercls->data()->ro->ivarLayout, - supercls->unalignedInstanceSize(), - cls->unalignedInstanceSize(), NO); - for (const auto& ivar : *ro_w->ivars) { - if (!ivar.offset) continue; // anonymous bitfield - - layout_bitmap_set_ivar(bitmap, ivar.type, *ivar.offset); - } - ro_w->ivarLayout = layout_string_create(bitmap); - layout_bitmap_free(bitmap); - } - - if (ro_w->weakIvarLayout != &UnsetLayout) { - // Class builder already called class_setWeakIvarLayout. - } - else if (!supercls) { - // Root class. No weak ivars (should be isa ivar only). - ro_w->weakIvarLayout = nil; - } - else if (ro_w->ivars == nil) { - // No local ivars. Use superclass's layout. - ro_w->weakIvarLayout = - ustrdupMaybeNil(supercls->data()->ro->weakIvarLayout); - } - else { - // Has local ivars. Build layout based on superclass. - // No way to add weak ivars yet. - ro_w->weakIvarLayout = - ustrdupMaybeNil(supercls->data()->ro->weakIvarLayout); - } - } - - // Clear "under construction" bit, set "done constructing" bit - cls->ISA()->changeInfo(RW_CONSTRUCTED, RW_CONSTRUCTING | RW_REALIZING); - cls->changeInfo(RW_CONSTRUCTED, RW_CONSTRUCTING | RW_REALIZING); - - // Add to named and realized classes - addNamedClass(cls, cls->data()->ro->name); - addRealizedClass(cls); - addRealizedMetaclass(cls->ISA()); -} - - -/*********************************************************************** -* objc_readClassPair() -* Read a class and metaclass as written by a compiler. -* Assumes the class and metaclass are not referenced by other things -* that might need to be fixed up (such as categories and subclasses). -* Does not call +load. -* Returns the class pointer, or nil. -* -* Locking: runtimeLock acquired by map_images -**********************************************************************/ -Class objc_readClassPair(Class bits, const struct objc_image_info *info) -{ - rwlock_writer_t lock(runtimeLock); - - // No info bits are significant yet. - (void)info; - - // Fail if the class name is in use. - // Fail if the superclass isn't kosher. - const char *name = bits->mangledName(); - bool rootOK = bits->data()->flags & RO_ROOT; - if (getClass(name) || !verifySuperclass(bits->superclass, rootOK)){ - return nil; - } - - Class cls = readClass(bits, false/*bundle*/, false/*shared cache*/); - if (cls != bits) { - // This function isn't allowed to remap anything. - _objc_fatal("objc_readClassPair for class %s changed %p to %p", - cls->nameForLogging(), bits, cls); - } - realizeClass(cls); - - return cls; -} - - -/*********************************************************************** -* detach_class -* Disconnect a class from other data structures. -* Exception: does not remove the class from the +load list -* Call this before free_class. -* Locking: runtimeLock must be held by the caller. -**********************************************************************/ -static void detach_class(Class cls, bool isMeta) -{ - runtimeLock.assertWriting(); - - // categories not yet attached to this class - removeAllUnattachedCategoriesForClass(cls); - - // superclass's subclass list - if (cls->isRealized()) { - Class supercls = cls->superclass; - if (supercls) { - removeSubclass(supercls, cls); - } - } - - // class tables and +load queue - if (!isMeta) { - removeNamedClass(cls, cls->mangledName()); - removeRealizedClass(cls); - } else { - removeRealizedMetaclass(cls); - } -} - - -/*********************************************************************** -* free_class -* Frees a class's data structures. -* Call this after detach_class. -* Locking: runtimeLock must be held by the caller -**********************************************************************/ -static void free_class(Class cls) -{ - runtimeLock.assertWriting(); - - if (! cls->isRealized()) return; - - auto rw = cls->data(); - auto ro = rw->ro; - - cache_delete(cls); - - for (auto& meth : rw->methods) { - try_free(meth.types); - } - rw->methods.tryFree(); - - const ivar_list_t *ivars = ro->ivars; - if (ivars) { - for (auto& ivar : *ivars) { - try_free(ivar.offset); - try_free(ivar.name); - try_free(ivar.type); - } - try_free(ivars); - } - - for (auto& prop : rw->properties) { - try_free(prop.name); - try_free(prop.attributes); - } - rw->properties.tryFree(); - - rw->protocols.tryFree(); - - try_free(ro->ivarLayout); - try_free(ro->weakIvarLayout); - try_free(ro->name); - try_free(ro); - try_free(rw); - try_free(cls); -} - - -void objc_disposeClassPair(Class cls) -{ - rwlock_writer_t lock(runtimeLock); - - if (!(cls->data()->flags & (RW_CONSTRUCTED|RW_CONSTRUCTING)) || - !(cls->ISA()->data()->flags & (RW_CONSTRUCTED|RW_CONSTRUCTING))) - { - // class not allocated with objc_allocateClassPair - // disposing still-unregistered class is OK! - _objc_inform("objc_disposeClassPair: class '%s' was not " - "allocated with objc_allocateClassPair!", - cls->data()->ro->name); - return; - } - - if (cls->isMetaClass()) { - _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, " - "not a class!", cls->data()->ro->name); - return; - } - - // Shouldn't have any live subclasses. - if (cls->data()->firstSubclass) { - _objc_inform("objc_disposeClassPair: class '%s' still has subclasses, " - "including '%s'!", cls->data()->ro->name, - cls->data()->firstSubclass->nameForLogging()); - } - if (cls->ISA()->data()->firstSubclass) { - _objc_inform("objc_disposeClassPair: class '%s' still has subclasses, " - "including '%s'!", cls->data()->ro->name, - cls->ISA()->data()->firstSubclass->nameForLogging()); - } - - // don't remove_class_from_loadable_list() - // - it's not there and we don't have the lock - detach_class(cls->ISA(), YES); - detach_class(cls, NO); - free_class(cls->ISA()); - free_class(cls); -} - - -/*********************************************************************** -* objc_constructInstance -* Creates an instance of `cls` at the location pointed to by `bytes`. -* `bytes` must point to at least class_getInstanceSize(cls) bytes of -* well-aligned zero-filled memory. -* The new object's isa is set. Any C++ constructors are called. -* Returns `bytes` if successful. Returns nil if `cls` or `bytes` is -* nil, or if C++ constructors fail. -* Note: class_createInstance() and class_createInstances() preflight this. -**********************************************************************/ -id -objc_constructInstance(Class cls, void *bytes) -{ - if (!cls || !bytes) return nil; - - id obj = (id)bytes; - - // Read class's info bits all at once for performance - bool hasCxxCtor = cls->hasCxxCtor(); - bool hasCxxDtor = cls->hasCxxDtor(); - bool fast = cls->canAllocIndexed(); - - if (!UseGC && fast) { - obj->initInstanceIsa(cls, hasCxxDtor); - } else { - obj->initIsa(cls); - } - - if (hasCxxCtor) { - return object_cxxConstructFromClass(obj, cls); - } else { - return obj; - } -} - - -/*********************************************************************** -* class_createInstance -* fixme -* Locking: none -**********************************************************************/ - -static __attribute__((always_inline)) -id -_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone, - bool cxxConstruct = true, - size_t *outAllocatedSize = nil) -{ - if (!cls) return nil; - - assert(cls->isRealized()); - - // Read class's info bits all at once for performance - bool hasCxxCtor = cls->hasCxxCtor(); - bool hasCxxDtor = cls->hasCxxDtor(); - bool fast = cls->canAllocIndexed(); - - size_t size = cls->instanceSize(extraBytes); - if (outAllocatedSize) *outAllocatedSize = size; - - id obj; - if (!UseGC && !zone && fast) { - obj = (id)calloc(1, size); - if (!obj) return nil; - obj->initInstanceIsa(cls, hasCxxDtor); - } - else { -#if SUPPORT_GC - if (UseGC) { - obj = (id)auto_zone_allocate_object(gc_zone, size, - AUTO_OBJECT_SCANNED, 0, 1); - } else -#endif - if (zone) { - obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size); - } else { - obj = (id)calloc(1, size); - } - if (!obj) return nil; - - // Use non-indexed isa on the assumption that they might be - // doing something weird with the zone or RR. - obj->initIsa(cls); - } - - if (cxxConstruct && hasCxxCtor) { - obj = _objc_constructOrFree(obj, cls); - } - - return obj; -} - - -id -class_createInstance(Class cls, size_t extraBytes) -{ - return _class_createInstanceFromZone(cls, extraBytes, nil); -} - - -/*********************************************************************** -* class_createInstances -* fixme -* Locking: none -**********************************************************************/ -#if SUPPORT_NONPOINTER_ISA -#warning fixme optimize class_createInstances -#endif -unsigned -class_createInstances(Class cls, size_t extraBytes, - id *results, unsigned num_requested) -{ - return _class_createInstancesFromZone(cls, extraBytes, nil, - results, num_requested); -} - -static bool classOrSuperClassesUseARR(Class cls) { - while (cls) { - if (_class_usesAutomaticRetainRelease(cls)) return true; - cls = cls->superclass; - } - return false; -} - -static void arr_fixup_copied_references(id newObject, id oldObject) -{ - // use ARR layouts to correctly copy the references from old object to new, both strong and weak. - Class cls = oldObject->ISA(); - for ( ; cls; cls = cls->superclass) { - if (_class_usesAutomaticRetainRelease(cls)) { - // FIXME: align the instance start to nearest id boundary. This currently handles the case where - // the the compiler folds a leading BOOL (char, short, etc.) into the alignment slop of a superclass. - size_t instanceStart = _class_getInstanceStart(cls); - const uint8_t *strongLayout = class_getIvarLayout(cls); - if (strongLayout) { - id *newPtr = (id *)((char*)newObject + instanceStart); - unsigned char byte; - while ((byte = *strongLayout++)) { - unsigned skips = (byte >> 4); - unsigned scans = (byte & 0x0F); - newPtr += skips; - while (scans--) { - // ensure strong references are properly retained. - id value = *newPtr++; - if (value) objc_retain(value); - } - } - } - const uint8_t *weakLayout = class_getWeakIvarLayout(cls); - // fix up weak references if any. - if (weakLayout) { - id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart); - unsigned char byte; - while ((byte = *weakLayout++)) { - unsigned skips = (byte >> 4); - unsigned weaks = (byte & 0x0F); - newPtr += skips, oldPtr += skips; - while (weaks--) { - *newPtr = nil; - objc_storeWeak(newPtr, objc_loadWeak(oldPtr)); - ++newPtr, ++oldPtr; - } - } - } - } - } -} - -/*********************************************************************** -* object_copyFromZone -* fixme -* Locking: none -**********************************************************************/ -static id -_object_copyFromZone(id oldObj, size_t extraBytes, void *zone) -{ - if (!oldObj) return nil; - if (oldObj->isTaggedPointer()) return oldObj; - - // fixme this doesn't handle C++ ivars correctly (#4619414) - - Class cls = oldObj->ISA(); - size_t size; - id obj = _class_createInstanceFromZone(cls, extraBytes, zone, false, &size); - if (!obj) return nil; - - // Copy everything except the isa, which was already set above. - uint8_t *copyDst = (uint8_t *)obj + sizeof(Class); - uint8_t *copySrc = (uint8_t *)oldObj + sizeof(Class); - size_t copySize = size - sizeof(Class); -#if SUPPORT_GC - objc_memmove_collectable(copyDst, copySrc, copySize); -#else - memmove(copyDst, copySrc, copySize); -#endif - -#if SUPPORT_GC - if (UseGC) - gc_fixup_weakreferences(obj, oldObj); - else -#endif - if (classOrSuperClassesUseARR(cls)) - arr_fixup_copied_references(obj, oldObj); - - return obj; -} - - -/*********************************************************************** -* object_copy -* fixme -* Locking: none -**********************************************************************/ -id -object_copy(id oldObj, size_t extraBytes) -{ - return _object_copyFromZone(oldObj, extraBytes, malloc_default_zone()); -} - - -#if !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE) - -/*********************************************************************** -* class_createInstanceFromZone -* fixme -* Locking: none -**********************************************************************/ -id -class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone) -{ - return _class_createInstanceFromZone(cls, extraBytes, zone); -} - -/*********************************************************************** -* object_copyFromZone -* fixme -* Locking: none -**********************************************************************/ -id -object_copyFromZone(id oldObj, size_t extraBytes, void *zone) -{ - return _object_copyFromZone(oldObj, extraBytes, zone); -} - -#endif - - -/*********************************************************************** -* objc_destructInstance -* Destroys an instance without freeing memory. -* Calls C++ destructors. -* Calls ARR ivar cleanup. -* Removes associative references. -* Returns `obj`. Does nothing if `obj` is nil. -* Be warned that GC DOES NOT CALL THIS. If you edit this, also edit finalize. -* CoreFoundation and other clients do call this under GC. -**********************************************************************/ -void *objc_destructInstance(id obj) -{ - if (obj) { - // Read all of the flags at once for performance. - bool cxx = obj->hasCxxDtor(); - bool assoc = !UseGC && obj->hasAssociatedObjects(); - bool dealloc = !UseGC; - - // This order is important. - if (cxx) object_cxxDestruct(obj); - if (assoc) _object_remove_assocations(obj); - if (dealloc) obj->clearDeallocating(); - } - - return obj; -} - - -/*********************************************************************** -* object_dispose -* fixme -* Locking: none -**********************************************************************/ -id -object_dispose(id obj) -{ - if (!obj) return nil; - - objc_destructInstance(obj); - -#if SUPPORT_GC - if (UseGC) { - auto_zone_retain(gc_zone, obj); // gc free expects rc==1 - } -#endif - - free(obj); - - return nil; -} - - -/*********************************************************************** -* _objc_getFreedObjectClass -* fixme -* Locking: none -**********************************************************************/ -Class _objc_getFreedObjectClass (void) -{ - return nil; -} - - - -/*********************************************************************** -* Tagged pointer objects. -* -* Tagged pointer objects store the class and the object value in the -* object pointer; the "pointer" does not actually point to anything. -* -* Tagged pointer objects currently use this representation: -* (LSB) -* 1 bit set if tagged, clear if ordinary object pointer -* 3 bits tag index -* 60 bits payload -* (MSB) -* The tag index defines the object's class. -* The payload format is defined by the object's class. -* -* This representation is subject to change. Representation-agnostic SPI is: -* objc-internal.h for class implementers. -* objc-gdb.h for debuggers. -**********************************************************************/ -#if !SUPPORT_TAGGED_POINTERS - -// These variables are always provided for debuggers. -uintptr_t objc_debug_taggedpointer_mask = 0; -unsigned objc_debug_taggedpointer_slot_shift = 0; -uintptr_t objc_debug_taggedpointer_slot_mask = 0; -unsigned objc_debug_taggedpointer_payload_lshift = 0; -unsigned objc_debug_taggedpointer_payload_rshift = 0; -Class objc_debug_taggedpointer_classes[1] = { nil }; - -static void -disableTaggedPointers() { } - -#else - -// The "slot" used in the class table and given to the debugger -// includes the is-tagged bit. This makes objc_msgSend faster. - -uintptr_t objc_debug_taggedpointer_mask = TAG_MASK; -unsigned objc_debug_taggedpointer_slot_shift = TAG_SLOT_SHIFT; -uintptr_t objc_debug_taggedpointer_slot_mask = TAG_SLOT_MASK; -unsigned objc_debug_taggedpointer_payload_lshift = TAG_PAYLOAD_LSHIFT; -unsigned objc_debug_taggedpointer_payload_rshift = TAG_PAYLOAD_RSHIFT; -// objc_debug_taggedpointer_classes is defined in objc-msg-*.s - -static void -disableTaggedPointers() -{ - objc_debug_taggedpointer_mask = 0; - objc_debug_taggedpointer_slot_shift = 0; - objc_debug_taggedpointer_slot_mask = 0; - objc_debug_taggedpointer_payload_lshift = 0; - objc_debug_taggedpointer_payload_rshift = 0; -} - -static int -tagSlotForTagIndex(objc_tag_index_t tag) -{ -#if SUPPORT_MSB_TAGGED_POINTERS - return 0x8 | tag; -#else - return (tag << 1) | 1; -#endif -} - - -/*********************************************************************** -* _objc_registerTaggedPointerClass -* Set the class to use for the given tagged pointer index. -* Aborts if the tag is out of range, or if the tag is already -* used by some other class. -**********************************************************************/ -void -_objc_registerTaggedPointerClass(objc_tag_index_t tag, Class cls) -{ - if (objc_debug_taggedpointer_mask == 0) { - _objc_fatal("tagged pointers are disabled"); - } - - if ((unsigned int)tag >= TAG_COUNT) { - _objc_fatal("tag index %u is too large.", tag); - } - - int slot = tagSlotForTagIndex(tag); - Class oldCls = objc_tag_classes[slot]; - - if (cls && oldCls && cls != oldCls) { - _objc_fatal("tag index %u used for two different classes " - "(was %p %s, now %p %s)", tag, - oldCls, oldCls->nameForLogging(), - cls, cls->nameForLogging()); - } - - objc_tag_classes[slot] = cls; -} - - -// Deprecated name. -void _objc_insert_tagged_isa(unsigned char slotNumber, Class isa) -{ - return _objc_registerTaggedPointerClass((objc_tag_index_t)slotNumber, isa); -} - - -/*********************************************************************** -* _objc_getClassForTag -* Returns the class that is using the given tagged pointer tag. -* Returns nil if no class is using that tag or the tag is out of range. -**********************************************************************/ -Class -_objc_getClassForTag(objc_tag_index_t tag) -{ - if ((unsigned int)tag >= TAG_COUNT) return nil; - return objc_tag_classes[tagSlotForTagIndex(tag)]; -} - -#endif - - -#if SUPPORT_FIXUP - -OBJC_EXTERN void objc_msgSend_fixup(void); -OBJC_EXTERN void objc_msgSendSuper2_fixup(void); -OBJC_EXTERN void objc_msgSend_stret_fixup(void); -OBJC_EXTERN void objc_msgSendSuper2_stret_fixup(void); -#if defined(__i386__) || defined(__x86_64__) -OBJC_EXTERN void objc_msgSend_fpret_fixup(void); -#endif -#if defined(__x86_64__) -OBJC_EXTERN void objc_msgSend_fp2ret_fixup(void); -#endif - -OBJC_EXTERN void objc_msgSend_fixedup(void); -OBJC_EXTERN void objc_msgSendSuper2_fixedup(void); -OBJC_EXTERN void objc_msgSend_stret_fixedup(void); -OBJC_EXTERN void objc_msgSendSuper2_stret_fixedup(void); -#if defined(__i386__) || defined(__x86_64__) -OBJC_EXTERN void objc_msgSend_fpret_fixedup(void); -#endif -#if defined(__x86_64__) -OBJC_EXTERN void objc_msgSend_fp2ret_fixedup(void); -#endif - -/*********************************************************************** -* fixupMessageRef -* Repairs an old vtable dispatch call site. -* vtable dispatch itself is not supported. -**********************************************************************/ -static void -fixupMessageRef(message_ref_t *msg) -{ - msg->sel = sel_registerName((const char *)msg->sel); - - if (ignoreSelector(msg->sel)) { - // ignored selector - bypass dispatcher - msg->imp = (IMP)&_objc_ignored_method; - } - else if (msg->imp == &objc_msgSend_fixup) { - if (msg->sel == SEL_alloc) { - msg->imp = (IMP)&objc_alloc; - } else if (msg->sel == SEL_allocWithZone) { - msg->imp = (IMP)&objc_allocWithZone; - } else if (msg->sel == SEL_retain) { - msg->imp = (IMP)&objc_retain; - } else if (msg->sel == SEL_release) { - msg->imp = (IMP)&objc_release; - } else if (msg->sel == SEL_autorelease) { - msg->imp = (IMP)&objc_autorelease; - } else { - msg->imp = &objc_msgSend_fixedup; - } - } - else if (msg->imp == &objc_msgSendSuper2_fixup) { - msg->imp = &objc_msgSendSuper2_fixedup; - } - else if (msg->imp == &objc_msgSend_stret_fixup) { - msg->imp = &objc_msgSend_stret_fixedup; - } - else if (msg->imp == &objc_msgSendSuper2_stret_fixup) { - msg->imp = &objc_msgSendSuper2_stret_fixedup; - } -#if defined(__i386__) || defined(__x86_64__) - else if (msg->imp == &objc_msgSend_fpret_fixup) { - msg->imp = &objc_msgSend_fpret_fixedup; - } -#endif -#if defined(__x86_64__) - else if (msg->imp == &objc_msgSend_fp2ret_fixup) { - msg->imp = &objc_msgSend_fp2ret_fixedup; - } -#endif -} - -// SUPPORT_FIXUP -#endif - - -// ProKit SPI -static Class setSuperclass(Class cls, Class newSuper) -{ - Class oldSuper; - - runtimeLock.assertWriting(); - - assert(cls->isRealized()); - assert(newSuper->isRealized()); - - oldSuper = cls->superclass; - removeSubclass(oldSuper, cls); - removeSubclass(oldSuper->ISA(), cls->ISA()); - - cls->superclass = newSuper; - cls->ISA()->superclass = newSuper->ISA(); - addSubclass(newSuper, cls); - addSubclass(newSuper->ISA(), cls->ISA()); - - // Flush subclass's method caches. - flushCaches(cls); - - return oldSuper; -} - - -Class class_setSuperclass(Class cls, Class newSuper) -{ - rwlock_writer_t lock(runtimeLock); - return setSuperclass(cls, newSuper); -} - - -// __OBJC2__ -#endif diff --git a/objc/objc-runtime/runtime/objc-runtime-old.h b/objc/objc-runtime/runtime/objc-runtime-old.h deleted file mode 100644 index 76cd8e4..0000000 --- a/objc/objc-runtime/runtime/objc-runtime-old.h +++ /dev/null @@ -1,360 +0,0 @@ -/* - * 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@ - */ - -#ifndef _OBJC_RUNTIME_OLD_H -#define _OBJC_RUNTIME_OLD_H - -#include "objc-private.h" - -#define CLS_CLASS 0x1 -#define CLS_META 0x2 -#define CLS_INITIALIZED 0x4 -#define CLS_POSING 0x8 -#define CLS_MAPPED 0x10 -#define CLS_FLUSH_CACHE 0x20 -#define CLS_GROW_CACHE 0x40 -#define CLS_NEED_BIND 0x80 -#define CLS_METHOD_ARRAY 0x100 -// the JavaBridge constructs classes with these markers -#define CLS_JAVA_HYBRID 0x200 -#define CLS_JAVA_CLASS 0x400 -// thread-safe +initialize -#define CLS_INITIALIZING 0x800 -// bundle unloading -#define CLS_FROM_BUNDLE 0x1000 -// C++ ivar support -#define CLS_HAS_CXX_STRUCTORS 0x2000 -// Lazy method list arrays -#define CLS_NO_METHOD_ARRAY 0x4000 -// +load implementation -#define CLS_HAS_LOAD_METHOD 0x8000 -// objc_allocateClassPair API -#define CLS_CONSTRUCTING 0x10000 -// visibility=hidden -#define CLS_HIDDEN 0x20000 -// GC: class has unsafe finalize method -#define CLS_FINALIZE_ON_MAIN_THREAD 0x40000 -// Lazy property list arrays -#define CLS_NO_PROPERTY_ARRAY 0x80000 -// +load implementation -#define CLS_CONNECTED 0x100000 -#define CLS_LOADED 0x200000 -// objc_allocateClassPair API -#define CLS_CONSTRUCTED 0x400000 -// class is leaf for cache flushing -#define CLS_LEAF 0x800000 -// class instances may have associative references -#define CLS_INSTANCES_HAVE_ASSOCIATED_OBJECTS 0x1000000 -// class has instance-specific GC layout -#define CLS_HAS_INSTANCE_SPECIFIC_LAYOUT 0x2000000 - - -// Terminator for array of method lists -#define END_OF_METHODS_LIST ((struct old_method_list*)-1) - -#define ISCLASS(cls) (((cls)->info & CLS_CLASS) != 0) -#define ISMETA(cls) (((cls)->info & CLS_META) != 0) -#define GETMETA(cls) (ISMETA(cls) ? (cls) : (cls)->ISA()) - - -struct objc_class : objc_object { - Class superclass; - const char *name; - uint32_t version; - uint32_t info; - uint32_t instance_size; - struct old_ivar_list *ivars; - struct old_method_list **methodLists; - Cache cache; - struct old_protocol_list *protocols; - // CLS_EXT only - const uint8_t *ivar_layout; - struct old_class_ext *ext; - - void setInfo(uint32_t set) { - OSAtomicOr32Barrier(set, (volatile uint32_t *)&info); - } - - void clearInfo(uint32_t clear) { - OSAtomicXor32Barrier(clear, (volatile uint32_t *)&info); - } - - - // set and clear must not overlap - void changeInfo(uint32_t set, uint32_t clear) { - assert((set & clear) == 0); - - uint32_t oldf, newf; - do { - oldf = this->info; - newf = (oldf | set) & ~clear; - } while (!OSAtomicCompareAndSwap32Barrier(oldf, newf, (volatile int32_t *)&info)); - } - - bool hasCxxCtor() { - // set_superclass propagates the flag from the superclass. - return info & CLS_HAS_CXX_STRUCTORS; - } - - bool hasCxxDtor() { - return hasCxxCtor(); // one bit for both ctor and dtor - } - - bool hasCustomRR() { - return true; - } - void setHasCustomRR(bool = false) { } - void setHasDefaultRR() { } - void printCustomRR(bool) { } - - bool hasCustomAWZ() { - return true; - } - void setHasCustomAWZ(bool = false) { } - void setHasDefaultAWZ() { } - void printCustomAWZ(bool) { } - - bool instancesHaveAssociatedObjects() { - return info & CLS_INSTANCES_HAVE_ASSOCIATED_OBJECTS; - } - - void setInstancesHaveAssociatedObjects() { - setInfo(CLS_INSTANCES_HAVE_ASSOCIATED_OBJECTS); - } - - bool shouldGrowCache() { - return info & CLS_GROW_CACHE; - } - - void setShouldGrowCache(bool grow) { - if (grow) setInfo(CLS_GROW_CACHE); - else clearInfo(CLS_GROW_CACHE); - } - - bool shouldFinalizeOnMainThread() { - return info & CLS_FINALIZE_ON_MAIN_THREAD; - } - - void setShouldFinalizeOnMainThread() { - setInfo(CLS_FINALIZE_ON_MAIN_THREAD); - } - - // +initialize bits are stored on the metaclass only - bool isInitializing() { - return getMeta()->info & CLS_INITIALIZING; - } - - // +initialize bits are stored on the metaclass only - void setInitializing() { - getMeta()->setInfo(CLS_INITIALIZING); - } - - // +initialize bits are stored on the metaclass only - bool isInitialized() { - return getMeta()->info & CLS_INITIALIZED; - } - - // +initialize bits are stored on the metaclass only - void setInitialized() { - getMeta()->changeInfo(CLS_INITIALIZED, CLS_INITIALIZING); - } - - bool isLoadable() { - // A class registered for +load is ready for +load to be called - // if it is connected. - return isConnected(); - } - - IMP getLoadMethod(); - - bool isFuture(); - - bool isConnected(); - - const char *mangledName() { return name; } - const char *demangledName() { return name; } - const char *nameForLogging() { return name; } - - bool isMetaClass() { - return info & CLS_META; - } - - // NOT identical to this->ISA() when this is a metaclass - Class getMeta() { - if (isMetaClass()) return (Class)this; - else return this->ISA(); - } - - // May be unaligned depending on class's ivars. - uint32_t unalignedInstanceSize() { - return instance_size; - } - - // Class's ivar size rounded up to a pointer-size boundary. - uint32_t alignedInstanceSize() { - return (unalignedInstanceSize() + WORD_MASK) & ~WORD_MASK; - } - - size_t instanceSize(size_t extraBytes) { - size_t size = alignedInstanceSize() + extraBytes; - // CF requires all objects be at least 16 bytes. - if (size < 16) size = 16; - return size; - } - -}; - -struct old_class_ext { - uint32_t size; - const uint8_t *weak_ivar_layout; - struct old_property_list **propertyLists; -}; - -struct old_category { - char *category_name; - char *class_name; - struct old_method_list *instance_methods; - struct old_method_list *class_methods; - struct old_protocol_list *protocols; - uint32_t size; - struct old_property_list *instance_properties; -}; - -struct old_ivar { - char *ivar_name; - char *ivar_type; - int ivar_offset; -#ifdef __LP64__ - int space; -#endif -}; - -struct old_ivar_list { - int ivar_count; -#ifdef __LP64__ - int space; -#endif - /* variable length structure */ - struct old_ivar ivar_list[1]; -}; - - -struct old_method { - SEL method_name; - char *method_types; - IMP method_imp; -}; - -struct old_method_list { - void *obsolete; - - int method_count; -#ifdef __LP64__ - int space; -#endif - /* variable length structure */ - struct old_method method_list[1]; -}; - -struct old_protocol { - Class isa; - const char *protocol_name; - struct old_protocol_list *protocol_list; - struct objc_method_description_list *instance_methods; - struct objc_method_description_list *class_methods; -}; - -struct old_protocol_list { - struct old_protocol_list *next; - long count; - struct old_protocol *list[1]; -}; - -struct old_protocol_ext { - uint32_t size; - struct objc_method_description_list *optional_instance_methods; - struct objc_method_description_list *optional_class_methods; - struct old_property_list *instance_properties; - const char **extendedMethodTypes; -}; - - -struct old_property { - const char *name; - const char *attributes; -}; - -struct old_property_list { - uint32_t entsize; - uint32_t count; - struct old_property first; -}; - - -#include "hashtable2.h" - -__BEGIN_DECLS - -#define oldprotocol(proto) ((struct old_protocol *)proto) -#define oldmethod(meth) ((struct old_method *)meth) -#define oldcategory(cat) ((struct old_category *)cat) -#define oldivar(ivar) ((struct old_ivar *)ivar) -#define oldproperty(prop) ((struct old_property *)prop) - -extern NXHashTable *class_hash; - -extern void unload_class(Class cls); - -extern IMP lookupNamedMethodInMethodList(struct old_method_list *mlist, const char *meth_name); -extern void _objc_insertMethods(Class cls, struct old_method_list *mlist, struct old_category *cat); -extern void _objc_removeMethods(Class cls, struct old_method_list *mlist); -extern void _objc_flush_caches (Class cls); -extern bool _class_addProperties(Class cls, struct old_property_list *additions); -extern bool _class_hasLoadMethod(Class cls); -extern void change_class_references(Class imposter, Class original, Class copy, bool changeSuperRefs); -extern void flush_marked_caches(void); -extern void set_superclass(Class cls, Class supercls, bool cls_is_new); -extern void try_free(const void *p); - -extern struct old_property *property_list_nth(const struct old_property_list *plist, uint32_t i); -extern struct old_property **copyPropertyList(struct old_property_list *plist, unsigned int *outCount); - -extern struct objc_method_description * lookup_protocol_method(struct old_protocol *proto, SEL aSel, bool isRequiredMethod, bool isInstanceMethod, bool recursive); - -// used by flush_caches outside objc-cache.m -extern void _cache_flush(Class cls); -#ifdef OBJC_INSTRUMENTED -extern unsigned int LinearFlushCachesCount; -extern unsigned int LinearFlushCachesVisitedCount; -extern unsigned int MaxLinearFlushCachesVisitedCount; -extern unsigned int NonlinearFlushCachesCount; -extern unsigned int NonlinearFlushCachesClassCount; -extern unsigned int NonlinearFlushCachesVisitedCount; -extern unsigned int MaxNonlinearFlushCachesVisitedCount; -extern unsigned int IdealFlushCachesCount; -extern unsigned int MaxIdealFlushCachesCount; -#endif - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/runtime/objc-runtime-old.mm b/objc/objc-runtime/runtime/objc-runtime-old.mm deleted file mode 100644 index 045db63..0000000 --- a/objc/objc-runtime/runtime/objc-runtime-old.mm +++ /dev/null @@ -1,3291 +0,0 @@ -/* - * 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@ - */ - -/*********************************************************************** -* objc-runtime-old.m -* Support for old-ABI classes and images. -**********************************************************************/ - -/*********************************************************************** - * Class loading and connecting (GrP 2004-2-11) - * - * When images are loaded (during program startup or otherwise), the - * runtime needs to load classes and categories from the images, connect - * classes to superclasses and categories to parent classes, and call - * +load methods. - * - * The Objective-C runtime can cope with classes arriving in any order. - * That is, a class may be discovered by the runtime before some - * superclass is known. To handle out-of-order class loads, the - * runtime uses a "pending class" system. - * - * (Historical note) - * Panther and earlier: many classes arrived out-of-order because of - * the poorly-ordered callback from dyld. However, the runtime's - * pending mechanism only handled "missing superclass" and not - * "present superclass but missing higher class". See Radar #3225652. - * Tiger: The runtime's pending mechanism was augmented to handle - * arbitrary missing classes. In addition, dyld was rewritten and - * now sends the callbacks in strictly bottom-up link order. - * The pending mechanism may now be needed only for rare and - * hard to construct programs. - * (End historical note) - * - * A class when first seen in an image is considered "unconnected". - * It is stored in `unconnected_class_hash`. If all of the class's - * superclasses exist and are already "connected", then the new class - * can be connected to its superclasses and moved to `class_hash` for - * normal use. Otherwise, the class waits in `unconnected_class_hash` - * until the superclasses finish connecting. - * - * A "connected" class is - * (1) in `class_hash`, - * (2) connected to its superclasses, - * (3) has no unconnected superclasses, - * (4) is otherwise initialized and ready for use, and - * (5) is eligible for +load if +load has not already been called. - * - * An "unconnected" class is - * (1) in `unconnected_class_hash`, - * (2) not connected to its superclasses, - * (3) has an immediate superclass which is either missing or unconnected, - * (4) is not ready for use, and - * (5) is not yet eligible for +load. - * - * Image mapping is NOT CURRENTLY THREAD-SAFE with respect to just about - * anything. Image mapping IS RE-ENTRANT in several places: superclass - * lookup may cause ZeroLink to load another image, and +load calls may - * cause dyld to load another image. - * - * Image mapping sequence: - * - * Read all classes in all new images. - * Add them all to unconnected_class_hash. - * Note any +load implementations before categories are attached. - * Attach any pending categories. - * Read all categories in all new images. - * Attach categories whose parent class exists (connected or not), - * and pend the rest. - * Mark them all eligible for +load (if implemented), even if the - * parent class is missing. - * Try to connect all classes in all new images. - * If the superclass is missing, pend the class - * If the superclass is unconnected, try to recursively connect it - * If the superclass is connected: - * connect the class - * mark the class eligible for +load, if implemented - * fix up any pended classrefs referring to the class - * connect any pended subclasses of the class - * Resolve selector refs and class refs in all new images. - * Class refs whose classes still do not exist are pended. - * Fix up protocol objects in all new images. - * Call +load for classes and categories. - * May include classes or categories that are not in these images, - * but are newly eligible because of these image. - * Class +loads will be called superclass-first because of the - * superclass-first nature of the connecting process. - * Category +load needs to be deferred until the parent class is - * connected and has had its +load called. - * - * Performance: all classes are read before any categories are read. - * Fewer categories need be pended for lack of a parent class. - * - * Performance: all categories are attempted to be attached before - * any classes are connected. Fewer class caches need be flushed. - * (Unconnected classes and their respective subclasses are guaranteed - * to be un-messageable, so their caches will be empty.) - * - * Performance: all classes are read before any classes are connected. - * Fewer classes need be pended for lack of a superclass. - * - * Correctness: all selector and class refs are fixed before any - * protocol fixups or +load methods. libobjc itself contains selector - * and class refs which are used in protocol fixup and +load. - * - * Correctness: +load methods are scheduled in bottom-up link order. - * This constraint is in addition to superclass order. Some +load - * implementations expect to use another class in a linked-to library, - * even if the two classes don't share a direct superclass relationship. - * - * Correctness: all classes are scanned for +load before any categories - * are attached. Otherwise, if a category implements +load and its class - * has no class methods, the class's +load scan would find the category's - * +load method, which would then be called twice. - * - * Correctness: pended class refs are not fixed up until the class is - * connected. Classes with missing weak superclasses remain unconnected. - * Class refs to classes with missing weak superclasses must be nil. - * Therefore class refs to unconnected classes must remain un-fixed. - * - **********************************************************************/ - -#if !__OBJC2__ - -#include "objc-private.h" -#include "objc-runtime-old.h" -#include "objc-file-old.h" -#include "objc-cache-old.h" -#include "objc-loadmethod.h" - - -typedef struct _objc_unresolved_category -{ - struct _objc_unresolved_category *next; - old_category *cat; // may be nil - long version; -} _objc_unresolved_category; - -typedef struct _PendingSubclass -{ - Class subclass; // subclass to finish connecting; may be nil - struct _PendingSubclass *next; -} PendingSubclass; - -typedef struct _PendingClassRef -{ - Class *ref; // class reference to fix up; may be nil - // (ref & 1) is a metaclass reference - struct _PendingClassRef *next; -} PendingClassRef; - - -static uintptr_t classHash(void *info, Class data); -static int classIsEqual(void *info, Class name, Class cls); -static int _objc_defaultClassHandler(const char *clsName); -static inline NXMapTable *pendingClassRefsMapTable(void); -static inline NXMapTable *pendingSubclassesMapTable(void); -static void pendClassInstallation(Class cls, const char *superName); -static void pendClassReference(Class *ref, const char *className, bool isMeta); -static void resolve_references_to_class(Class cls); -static void resolve_subclasses_of_class(Class cls); -static void really_connect_class(Class cls, Class supercls); -static bool connect_class(Class cls); -static void map_method_descs (struct objc_method_description_list * methods, bool copy); -static void _objcTweakMethodListPointerForClass(Class cls); -static inline void _objc_add_category(Class cls, old_category *category, int version); -static bool _objc_add_category_flush_caches(Class cls, old_category *category, int version); -static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat); -static void resolve_categories_for_class(Class cls); -static bool _objc_register_category(old_category *cat, int version); - - -// Function called when a class is loaded from an image -void (*callbackFunction)(Class, Category) = 0; - -// Hash table of classes -NXHashTable * class_hash = 0; -static NXHashTablePrototype classHashPrototype = -{ - (uintptr_t (*) (const void *, const void *)) classHash, - (int (*)(const void *, const void *, const void *)) classIsEqual, - NXNoEffectFree, 0 -}; - -// Hash table of unconnected classes -static NXHashTable *unconnected_class_hash = nil; - -// Exported copy of class_hash variable (hook for debugging tools) -NXHashTable *_objc_debug_class_hash = nil; - -// Category and class registries -// Keys are COPIES of strings, to prevent stale pointers with unloaded bundles -// Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove -static NXMapTable * category_hash = nil; - -// Keys are COPIES of strings, to prevent stale pointers with unloaded bundles -// Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove -static NXMapTable * pendingClassRefsMap = nil; -static NXMapTable * pendingSubclassesMap = nil; - -// Protocols -static NXMapTable *protocol_map = nil; // name -> protocol -static NXMapTable *protocol_ext_map = nil; // protocol -> protocol ext - -// Function pointer objc_getClass calls through when class is not found -static int (*objc_classHandler) (const char *) = _objc_defaultClassHandler; - -// Function pointer called by objc_getClass and objc_lookupClass when -// class is not found. _objc_classLoader is called before objc_classHandler. -static BOOL (*_objc_classLoader)(const char *) = nil; - - -/*********************************************************************** -* objc_dump_class_hash. Log names of all known classes. -**********************************************************************/ -void objc_dump_class_hash(void) -{ - NXHashTable *table; - unsigned count; - Class data; - NXHashState state; - - table = class_hash; - count = 0; - state = NXInitHashState (table); - while (NXNextHashState (table, &state, (void **) &data)) - printf ("class %d: %s\n", ++count, data->nameForLogging()); -} - - -/*********************************************************************** -* _objc_init_class_hash. Return the class lookup table, create it if -* necessary. -**********************************************************************/ -void _objc_init_class_hash(void) -{ - // Do nothing if class hash table already exists - if (class_hash) - return; - - // class_hash starts small, with only enough capacity for libobjc itself. - // If a second library is found by map_images(), class_hash is immediately - // resized to capacity 1024 to cut down on rehashes. - // Old numbers: A smallish Foundation+AppKit program will have - // about 520 classes. Larger apps (like IB or WOB) have more like - // 800 classes. Some customers have massive quantities of classes. - // Foundation-only programs aren't likely to notice the ~6K loss. - class_hash = NXCreateHashTable(classHashPrototype, 16, nil); - _objc_debug_class_hash = class_hash; -} - - -/*********************************************************************** -* objc_getClassList. Return the known classes. -**********************************************************************/ -int objc_getClassList(Class *buffer, int bufferLen) -{ - NXHashState state; - Class cls; - int cnt, num; - - mutex_locker_t lock(classLock); - if (!class_hash) return 0; - - num = NXCountHashTable(class_hash); - if (nil == buffer) return num; - - cnt = 0; - state = NXInitHashState(class_hash); - while (cnt < bufferLen && - NXNextHashState(class_hash, &state, (void **)&cls)) - { - buffer[cnt++] = cls; - } - - return num; -} - - -/*********************************************************************** -* objc_copyClassList -* Returns pointers to all classes. -* This requires all classes be realized, which is regretfully non-lazy. -* -* outCount may be nil. *outCount is the number of classes returned. -* If the returned array is not nil, it is nil-terminated and must be -* freed with free(). -* Locking: acquires classLock -**********************************************************************/ -Class * -objc_copyClassList(unsigned int *outCount) -{ - Class *result; - unsigned int count; - - mutex_locker_t lock(classLock); - result = nil; - count = class_hash ? NXCountHashTable(class_hash) : 0; - - if (count > 0) { - Class cls; - NXHashState state = NXInitHashState(class_hash); - result = (Class *)malloc((1+count) * sizeof(Class)); - count = 0; - while (NXNextHashState(class_hash, &state, (void **)&cls)) { - result[count++] = cls; - } - result[count] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* objc_copyProtocolList -* Returns pointers to all protocols. -* Locking: acquires classLock -**********************************************************************/ -Protocol * __unsafe_unretained * -objc_copyProtocolList(unsigned int *outCount) -{ - int count, i; - Protocol *proto; - const char *name; - NXMapState state; - Protocol **result; - - mutex_locker_t lock(classLock); - - count = NXCountMapTable(protocol_map); - if (count == 0) { - if (outCount) *outCount = 0; - return nil; - } - - result = (Protocol **)calloc(1 + count, sizeof(Protocol *)); - - i = 0; - state = NXInitMapState(protocol_map); - while (NXNextMapState(protocol_map, &state, - (const void **)&name, (const void **)&proto)) - { - result[i++] = proto; - } - - result[i++] = nil; - assert(i == count+1); - - if (outCount) *outCount = count; - return result; -} - - -/*********************************************************************** -* objc_getClasses. Return class lookup table. -* -* NOTE: This function is very dangerous, since you cannot safely use -* the hashtable without locking it, and the lock is private! -**********************************************************************/ -void *objc_getClasses(void) -{ - OBJC_WARN_DEPRECATED; - - // Return the class lookup hash table - return class_hash; -} - - -/*********************************************************************** -* classHash. -**********************************************************************/ -static uintptr_t classHash(void *info, Class data) -{ - // Nil classes hash to zero - if (!data) - return 0; - - // Call through to real hash function - return _objc_strhash (data->mangledName()); -} - -/*********************************************************************** -* classIsEqual. Returns whether the class names match. If we ever -* check more than the name, routines like objc_lookUpClass have to -* change as well. -**********************************************************************/ -static int classIsEqual(void *info, Class name, Class cls) -{ - // Standard string comparison - return strcmp(name->mangledName(), cls->mangledName()) == 0; -} - - -// Unresolved future classes -static NXHashTable *future_class_hash = nil; - -// Resolved future<->original classes -static NXMapTable *future_class_to_original_class_map = nil; -static NXMapTable *original_class_to_future_class_map = nil; - -// CF requests about 20 future classes; HIToolbox requests one. -#define FUTURE_COUNT 32 - - -/*********************************************************************** -* setOriginalClassForFutureClass -* Record resolution of a future class. -**********************************************************************/ -static void setOriginalClassForFutureClass(Class futureClass, - Class originalClass) -{ - if (!future_class_to_original_class_map) { - future_class_to_original_class_map = - NXCreateMapTable(NXPtrValueMapPrototype, FUTURE_COUNT); - original_class_to_future_class_map = - NXCreateMapTable(NXPtrValueMapPrototype, FUTURE_COUNT); - } - - NXMapInsert (future_class_to_original_class_map, - futureClass, originalClass); - NXMapInsert (original_class_to_future_class_map, - originalClass, futureClass); - - if (PrintFuture) { - _objc_inform("FUTURE: using %p instead of %p for %s", (void*)futureClass, (void*)originalClass, originalClass->name); - } -} - -/*********************************************************************** -* getOriginalClassForFutureClass -* getFutureClassForOriginalClass -* Switch between a future class and its corresponding original class. -* The future class is the one actually in use. -* The original class is the one from disk. -**********************************************************************/ -/* -static Class -getOriginalClassForFutureClass(Class futureClass) -{ - if (!future_class_to_original_class_map) return Nil; - return NXMapGet (future_class_to_original_class_map, futureClass); -} -*/ -static Class -getFutureClassForOriginalClass(Class originalClass) -{ - if (!original_class_to_future_class_map) return Nil; - return (Class)NXMapGet(original_class_to_future_class_map, originalClass); -} - - -/*********************************************************************** -* makeFutureClass -* Initialize the memory in *cls with an unresolved future class with the -* given name. The memory is recorded in future_class_hash. -**********************************************************************/ -static void makeFutureClass(Class cls, const char *name) -{ - // CF requests about 20 future classes, plus HIToolbox has one. - if (!future_class_hash) { - future_class_hash = - NXCreateHashTable(classHashPrototype, FUTURE_COUNT, nil); - } - - cls->name = strdup(name); - NXHashInsert(future_class_hash, cls); - - if (PrintFuture) { - _objc_inform("FUTURE: reserving %p for %s", (void*)cls, name); - } -} - - -/*********************************************************************** -* _objc_allocateFutureClass -* Allocate an unresolved future class for the given class name. -* Returns any existing allocation if one was already made. -* Assumes the named class doesn't exist yet. -* Not thread safe. -**********************************************************************/ -Class _objc_allocateFutureClass(const char *name) -{ - Class cls; - - if (future_class_hash) { - objc_class query; - query.name = name; - if ((cls = (Class)NXHashGet(future_class_hash, &query))) { - // Already have a future class for this name. - return cls; - } - } - - cls = _calloc_class(sizeof(objc_class)); - makeFutureClass(cls, name); - return cls; -} - - -/*********************************************************************** -* objc_getFutureClass. Return the id of the named class. -* If the class does not exist, return an uninitialized class -* structure that will be used for the class when and if it -* does get loaded. -* Not thread safe. -**********************************************************************/ -Class objc_getFutureClass(const char *name) -{ - Class cls; - - // YES unconnected, NO class handler - // (unconnected is OK because it will someday be the real class) - cls = look_up_class(name, YES, NO); - if (cls) { - if (PrintFuture) { - _objc_inform("FUTURE: found %p already in use for %s", - (void*)cls, name); - } - return cls; - } - - // No class or future class with that name yet. Make one. - // fixme not thread-safe with respect to - // simultaneous library load or getFutureClass. - return _objc_allocateFutureClass(name); -} - - -BOOL _class_isFutureClass(Class cls) -{ - return cls && cls->isFuture(); -} - -bool objc_class::isFuture() -{ - return future_class_hash && NXHashGet(future_class_hash, this); -} - - -/*********************************************************************** -* _objc_defaultClassHandler. Default objc_classHandler. Does nothing. -**********************************************************************/ -static int _objc_defaultClassHandler(const char *clsName) -{ - // Return zero so objc_getClass doesn't bother re-searching - return 0; -} - -/*********************************************************************** -* objc_setClassHandler. Set objc_classHandler to the specified value. -* -* NOTE: This should probably deal with userSuppliedHandler being nil, -* because the objc_classHandler caller does not check... it would bus -* error. It would make sense to handle nil by restoring the default -* handler. Is anyone hacking with this, though? -**********************************************************************/ -void objc_setClassHandler(int (*userSuppliedHandler)(const char *)) -{ - OBJC_WARN_DEPRECATED; - - objc_classHandler = userSuppliedHandler; -} - - -/*********************************************************************** -* _objc_setClassLoader -* Similar to objc_setClassHandler, but objc_classLoader is used for -* both objc_getClass() and objc_lookupClass(), and objc_classLoader -* pre-empts objc_classHandler. -**********************************************************************/ -void _objc_setClassLoader(BOOL (*newClassLoader)(const char *)) -{ - _objc_classLoader = newClassLoader; -} - - -/*********************************************************************** -* objc_getProtocol -* Get a protocol by name, or nil. -**********************************************************************/ -Protocol *objc_getProtocol(const char *name) -{ - mutex_locker_t lock(classLock); - if (!protocol_map) return nil; - return (Protocol *)NXMapGet(protocol_map, name); -} - - -/*********************************************************************** -* look_up_class -* Map a class name to a class using various methods. -* This is the common implementation of objc_lookUpClass and objc_getClass, -* and is also used internally to get additional search options. -* Sequence: -* 1. class_hash -* 2. unconnected_class_hash (optional) -* 3. classLoader callback -* 4. classHandler callback (optional) -**********************************************************************/ -Class look_up_class(const char *aClassName, bool includeUnconnected, - bool includeClassHandler) -{ - bool includeClassLoader = YES; // class loader cannot be skipped - Class result = nil; - struct objc_class query; - - query.name = aClassName; - - retry: - - if (!result && class_hash) { - // Check ordinary classes - mutex_locker_t lock(classLock); - result = (Class)NXHashGet(class_hash, &query); - } - - if (!result && includeUnconnected && unconnected_class_hash) { - // Check not-yet-connected classes - mutex_locker_t lock(classLock); - result = (Class)NXHashGet(unconnected_class_hash, &query); - } - - if (!result && includeClassLoader && _objc_classLoader) { - // Try class loader callback - if ((*_objc_classLoader)(aClassName)) { - // Re-try lookup without class loader - includeClassLoader = NO; - goto retry; - } - } - - if (!result && includeClassHandler && objc_classHandler) { - // Try class handler callback - if ((*objc_classHandler)(aClassName)) { - // Re-try lookup without class handler or class loader - includeClassLoader = NO; - includeClassHandler = NO; - goto retry; - } - } - - return result; -} - - -/*********************************************************************** -* objc_class::isConnected -* Returns TRUE if class cls is connected. -* A connected class has either a connected superclass or a nil superclass, -* and is present in class_hash. -**********************************************************************/ -bool objc_class::isConnected() -{ - mutex_locker_t lock(classLock); - return NXHashMember(class_hash, this); -} - - -/*********************************************************************** -* pendingClassRefsMapTable. Return a pointer to the lookup table for -* pending class refs. -**********************************************************************/ -static inline NXMapTable *pendingClassRefsMapTable(void) -{ - // Allocate table if needed - if (!pendingClassRefsMap) { - pendingClassRefsMap = NXCreateMapTable(NXStrValueMapPrototype, 10); - } - - // Return table pointer - return pendingClassRefsMap; -} - - -/*********************************************************************** -* pendingSubclassesMapTable. Return a pointer to the lookup table for -* pending subclasses. -**********************************************************************/ -static inline NXMapTable *pendingSubclassesMapTable(void) -{ - // Allocate table if needed - if (!pendingSubclassesMap) { - pendingSubclassesMap = NXCreateMapTable(NXStrValueMapPrototype, 10); - } - - // Return table pointer - return pendingSubclassesMap; -} - - -/*********************************************************************** -* pendClassInstallation -* Finish connecting class cls when its superclass becomes connected. -* Check for multiple pends of the same class because connect_class does not. -**********************************************************************/ -static void pendClassInstallation(Class cls, const char *superName) -{ - NXMapTable *table; - PendingSubclass *pending; - PendingSubclass *oldList; - PendingSubclass *l; - - // Create and/or locate pending class lookup table - table = pendingSubclassesMapTable (); - - // Make sure this class isn't already in the pending list. - oldList = (PendingSubclass *)NXMapGet(table, superName); - for (l = oldList; l != nil; l = l->next) { - if (l->subclass == cls) return; // already here, nothing to do - } - - // Create entry referring to this class - pending = (PendingSubclass *)malloc(sizeof(PendingSubclass)); - pending->subclass = cls; - - // Link new entry into head of list of entries for this class - pending->next = oldList; - - // (Re)place entry list in the table - NXMapKeyCopyingInsert (table, superName, pending); -} - - -/*********************************************************************** -* pendClassReference -* Fix up a class ref when the class with the given name becomes connected. -**********************************************************************/ -static void pendClassReference(Class *ref, const char *className, bool isMeta) -{ - NXMapTable *table; - PendingClassRef *pending; - - // Create and/or locate pending class lookup table - table = pendingClassRefsMapTable (); - - // Create entry containing the class reference - pending = (PendingClassRef *)malloc(sizeof(PendingClassRef)); - pending->ref = ref; - if (isMeta) { - pending->ref = (Class *)((uintptr_t)pending->ref | 1); - } - - // Link new entry into head of list of entries for this class - pending->next = (PendingClassRef *)NXMapGet(table, className); - - // (Re)place entry list in the table - NXMapKeyCopyingInsert (table, className, pending); - - if (PrintConnecting) { - _objc_inform("CONNECT: pended reference to class '%s%s' at %p", - className, isMeta ? " (meta)" : "", (void *)ref); - } -} - - -/*********************************************************************** -* resolve_references_to_class -* Fix up any pending class refs to this class. -**********************************************************************/ -static void resolve_references_to_class(Class cls) -{ - PendingClassRef *pending; - - if (!pendingClassRefsMap) return; // no unresolved refs for any class - - pending = (PendingClassRef *)NXMapGet(pendingClassRefsMap, cls->name); - if (!pending) return; // no unresolved refs for this class - - NXMapKeyFreeingRemove(pendingClassRefsMap, cls->name); - - if (PrintConnecting) { - _objc_inform("CONNECT: resolving references to class '%s'", cls->name); - } - - while (pending) { - PendingClassRef *next = pending->next; - if (pending->ref) { - bool isMeta = (uintptr_t)pending->ref & 1; - Class *ref = - (Class *)((uintptr_t)pending->ref & ~(uintptr_t)1); - *ref = isMeta ? cls->ISA() : cls; - } - free(pending); - pending = next; - } - - if (NXCountMapTable(pendingClassRefsMap) == 0) { - NXFreeMapTable(pendingClassRefsMap); - pendingClassRefsMap = nil; - } -} - - -/*********************************************************************** -* resolve_subclasses_of_class -* Fix up any pending subclasses of this class. -**********************************************************************/ -static void resolve_subclasses_of_class(Class cls) -{ - PendingSubclass *pending; - - if (!pendingSubclassesMap) return; // no unresolved subclasses - - pending = (PendingSubclass *)NXMapGet(pendingSubclassesMap, cls->name); - if (!pending) return; // no unresolved subclasses for this class - - NXMapKeyFreeingRemove(pendingSubclassesMap, cls->name); - - // Destroy the pending table if it's now empty, to save memory. - if (NXCountMapTable(pendingSubclassesMap) == 0) { - NXFreeMapTable(pendingSubclassesMap); - pendingSubclassesMap = nil; - } - - if (PrintConnecting) { - _objc_inform("CONNECT: resolving subclasses of class '%s'", cls->name); - } - - while (pending) { - PendingSubclass *next = pending->next; - if (pending->subclass) connect_class(pending->subclass); - free(pending); - pending = next; - } -} - - -/*********************************************************************** -* really_connect_class -* Connect cls to superclass supercls unconditionally. -* Also adjust the class hash tables and handle pended subclasses. -* -* This should be called from connect_class() ONLY. -**********************************************************************/ -static void really_connect_class(Class cls, - Class supercls) -{ - Class oldCls; - - // Connect superclass pointers. - set_superclass(cls, supercls, YES); - - // Update GC layouts - // For paranoia, this is a conservative update: - // only non-strong -> strong and weak -> strong are corrected. - if (UseGC && supercls && - (cls->info & CLS_EXT) && (supercls->info & CLS_EXT)) - { - bool layoutChanged; - layout_bitmap ivarBitmap = - layout_bitmap_create(cls->ivar_layout, - cls->instance_size, - cls->instance_size, NO); - - layout_bitmap superBitmap = - layout_bitmap_create(supercls->ivar_layout, - supercls->instance_size, - supercls->instance_size, NO); - - // non-strong -> strong: bits set in super should be set in sub - layoutChanged = layout_bitmap_or(ivarBitmap, superBitmap, cls->name); - layout_bitmap_free(superBitmap); - - if (layoutChanged) { - layout_bitmap weakBitmap = {}; - bool weakLayoutChanged = NO; - - if (cls->ext && cls->ext->weak_ivar_layout) { - // weak -> strong: strong bits should be cleared in weak layout - // This is a subset of non-strong -> strong - weakBitmap = - layout_bitmap_create(cls->ext->weak_ivar_layout, - cls->instance_size, - cls->instance_size, YES); - - weakLayoutChanged = - layout_bitmap_clear(weakBitmap, ivarBitmap, cls->name); - } else { - // no existing weak ivars, so no weak -> strong changes - } - - // Rebuild layout strings. - if (PrintIvars) { - _objc_inform("IVARS: gc layout changed " - "for class %s (super %s)", - cls->name, supercls->name); - if (weakLayoutChanged) { - _objc_inform("IVARS: gc weak layout changed " - "for class %s (super %s)", - cls->name, supercls->name); - } - } - cls->ivar_layout = layout_string_create(ivarBitmap); - if (weakLayoutChanged) { - cls->ext->weak_ivar_layout = layout_string_create(weakBitmap); - } - - layout_bitmap_free(weakBitmap); - } - - layout_bitmap_free(ivarBitmap); - } - - // Done! - cls->info |= CLS_CONNECTED; - - { - mutex_locker_t lock(classLock); - - // Update hash tables. - NXHashRemove(unconnected_class_hash, cls); - oldCls = (Class)NXHashInsert(class_hash, cls); - objc_addRegisteredClass(cls); - - // Delete unconnected_class_hash if it is now empty. - if (NXCountHashTable(unconnected_class_hash) == 0) { - NXFreeHashTable(unconnected_class_hash); - unconnected_class_hash = nil; - } - - // No duplicate classes allowed. - // Duplicates should have been rejected by _objc_read_classes_from_image - assert(!oldCls); - } - - // Fix up pended class refs to this class, if any - resolve_references_to_class(cls); - - // Connect newly-connectable subclasses - resolve_subclasses_of_class(cls); - - // GC debugging: make sure all classes with -dealloc also have -finalize - if (DebugFinalizers) { - extern IMP findIMPInClass(Class cls, SEL sel); - if (findIMPInClass(cls, sel_getUid("dealloc")) && - ! findIMPInClass(cls, sel_getUid("finalize"))) - { - _objc_inform("GC: class '%s' implements -dealloc but not -finalize", cls->name); - } - } - - // Debugging: if this class has ivars, make sure this class's ivars don't - // overlap with its super's. This catches some broken fragile base classes. - // Do not use super->instance_size vs. self->ivar[0] to check this. - // Ivars may be packed across instance_size boundaries. - if (DebugFragileSuperclasses && cls->ivars && cls->ivars->ivar_count) { - Class ivar_cls = supercls; - - // Find closest superclass that has some ivars, if one exists. - while (ivar_cls && - (!ivar_cls->ivars || ivar_cls->ivars->ivar_count == 0)) - { - ivar_cls = ivar_cls->superclass; - } - - if (ivar_cls) { - // Compare superclass's last ivar to this class's first ivar - old_ivar *super_ivar = - &ivar_cls->ivars->ivar_list[ivar_cls->ivars->ivar_count - 1]; - old_ivar *self_ivar = - &cls->ivars->ivar_list[0]; - - // fixme could be smarter about super's ivar size - if (self_ivar->ivar_offset <= super_ivar->ivar_offset) { - _objc_inform("WARNING: ivars of superclass '%s' and " - "subclass '%s' overlap; superclass may have " - "changed since subclass was compiled", - ivar_cls->name, cls->name); - } - } - } -} - - -/*********************************************************************** -* connect_class -* Connect class cls to its superclasses, if possible. -* If cls becomes connected, move it from unconnected_class_hash -* to connected_class_hash. -* Returns TRUE if cls is connected. -* Returns FALSE if cls could not be connected for some reason -* (missing superclass or still-unconnected superclass) -**********************************************************************/ -static bool connect_class(Class cls) -{ - if (cls->isConnected()) { - // This class is already connected to its superclass. - // Do nothing. - return TRUE; - } - else if (cls->superclass == nil) { - // This class is a root class. - // Connect it to itself. - - if (PrintConnecting) { - _objc_inform("CONNECT: class '%s' now connected (root class)", - cls->name); - } - - really_connect_class(cls, nil); - return TRUE; - } - else { - // This class is not a root class and is not yet connected. - // Connect it if its superclass and root class are already connected. - // Otherwise, add this class to the to-be-connected list, - // pending the completion of its superclass and root class. - - // At this point, cls->superclass and cls->ISA()->ISA() are still STRINGS - char *supercls_name = (char *)cls->superclass; - Class supercls; - - // YES unconnected, YES class handler - if (nil == (supercls = look_up_class(supercls_name, YES, YES))) { - // Superclass does not exist yet. - // pendClassInstallation will handle duplicate pends of this class - pendClassInstallation(cls, supercls_name); - - if (PrintConnecting) { - _objc_inform("CONNECT: class '%s' NOT connected (missing super)", cls->name); - } - return FALSE; - } - - if (! connect_class(supercls)) { - // Superclass exists but is not yet connected. - // pendClassInstallation will handle duplicate pends of this class - pendClassInstallation(cls, supercls_name); - - if (PrintConnecting) { - _objc_inform("CONNECT: class '%s' NOT connected (unconnected super)", cls->name); - } - return FALSE; - } - - // Superclass exists and is connected. - // Connect this class to the superclass. - - if (PrintConnecting) { - _objc_inform("CONNECT: class '%s' now connected", cls->name); - } - - really_connect_class(cls, supercls); - return TRUE; - } -} - - -/*********************************************************************** -* _objc_read_categories_from_image. -* Read all categories from the given image. -* Install them on their parent classes, or register them for later -* installation. -* Returns YES if some method caches now need to be flushed. -**********************************************************************/ -static bool _objc_read_categories_from_image (header_info * hi) -{ - Module mods; - size_t midx; - bool needFlush = NO; - - if (_objcHeaderIsReplacement(hi)) { - // Ignore any categories in this image - return NO; - } - - - // Major loop - process all modules in the header - mods = hi->mod_ptr; - - // NOTE: The module and category lists are traversed backwards - // to preserve the pre-10.4 processing order. Changing the order - // would have a small chance of introducing binary compatibility bugs. - midx = hi->mod_count; - while (midx-- > 0) { - unsigned int index; - unsigned int total; - - // Nothing to do for a module without a symbol table - if (mods[midx].symtab == nil) - continue; - - // Total entries in symbol table (class entries followed - // by category entries) - total = mods[midx].symtab->cls_def_cnt + - mods[midx].symtab->cat_def_cnt; - - // Minor loop - register all categories from given module - index = total; - while (index-- > mods[midx].symtab->cls_def_cnt) { - old_category *cat = (old_category *)mods[midx].symtab->defs[index]; - needFlush |= _objc_register_category(cat, (int)mods[midx].version); - } - } - - return needFlush; -} - - -/*********************************************************************** -* _objc_read_classes_from_image. -* Read classes from the given image, perform assorted minor fixups, -* scan for +load implementation. -* Does not connect classes to superclasses. -* Does attach pended categories to the classes. -* Adds all classes to unconnected_class_hash. class_hash is unchanged. -**********************************************************************/ -static void _objc_read_classes_from_image(header_info *hi) -{ - unsigned int index; - unsigned int midx; - Module mods; - int isBundle = headerIsBundle(hi); - - if (_objcHeaderIsReplacement(hi)) { - // Ignore any classes in this image - return; - } - - // class_hash starts small, enough only for libobjc itself. - // If other Objective-C libraries are found, immediately resize - // class_hash, assuming that Foundation and AppKit are about - // to add lots of classes. - { - mutex_locker_t lock(classLock); - if (hi->mhdr != libobjc_header && _NXHashCapacity(class_hash) < 1024) { - _NXHashRehashToCapacity(class_hash, 1024); - } - } - - // Major loop - process all modules in the image - mods = hi->mod_ptr; - for (midx = 0; midx < hi->mod_count; midx += 1) - { - // Skip module containing no classes - if (mods[midx].symtab == nil) - continue; - - // Minor loop - process all the classes in given module - for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1) - { - Class newCls, oldCls; - bool rejected; - - // Locate the class description pointer - newCls = (Class)mods[midx].symtab->defs[index]; - - // Classes loaded from Mach-O bundles can be unloaded later. - // Nothing uses this class yet, so cls->setInfo is not needed. - if (isBundle) newCls->info |= CLS_FROM_BUNDLE; - if (isBundle) newCls->ISA()->info |= CLS_FROM_BUNDLE; - - // Use common static empty cache instead of nil - if (newCls->cache == nil) - newCls->cache = (Cache) &_objc_empty_cache; - if (newCls->ISA()->cache == nil) - newCls->ISA()->cache = (Cache) &_objc_empty_cache; - - // Set metaclass version - newCls->ISA()->version = mods[midx].version; - - // methodLists is nil or a single list, not an array - newCls->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY; - newCls->ISA()->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY; - - // class has no subclasses for cache flushing - newCls->info |= CLS_LEAF; - newCls->ISA()->info |= CLS_LEAF; - - if (mods[midx].version >= 6) { - // class structure has ivar_layout and ext fields - newCls->info |= CLS_EXT; - newCls->ISA()->info |= CLS_EXT; - } - - // Check for +load implementation before categories are attached - if (_class_hasLoadMethod(newCls)) { - newCls->ISA()->info |= CLS_HAS_LOAD_METHOD; - } - - // Install into unconnected_class_hash. - { - mutex_locker_t lock(classLock); - - if (future_class_hash) { - Class futureCls = (Class) - NXHashRemove(future_class_hash, newCls); - if (futureCls) { - // Another class structure for this class was already - // prepared by objc_getFutureClass(). Use it instead. - free((char *)futureCls->name); - memcpy(futureCls, newCls, sizeof(objc_class)); - setOriginalClassForFutureClass(futureCls, newCls); - newCls = futureCls; - - if (NXCountHashTable(future_class_hash) == 0) { - NXFreeHashTable(future_class_hash); - future_class_hash = nil; - } - } - } - - if (!unconnected_class_hash) { - unconnected_class_hash = - NXCreateHashTable(classHashPrototype, 128, nil); - } - - if ((oldCls = (Class)NXHashGet(class_hash, newCls)) || - (oldCls = (Class)NXHashGet(unconnected_class_hash, newCls))) - { - // Another class with this name exists. Complain and reject. - inform_duplicate(newCls->name, oldCls, newCls); - rejected = YES; - } - else { - NXHashInsert(unconnected_class_hash, newCls); - rejected = NO; - } - } - - if (!rejected) { - // Attach pended categories for this class, if any - resolve_categories_for_class(newCls); - } - } - } -} - - -/*********************************************************************** -* _objc_connect_classes_from_image. -* Connect the classes in the given image to their superclasses, -* or register them for later connection if any superclasses are missing. -**********************************************************************/ -static void _objc_connect_classes_from_image(header_info *hi) -{ - unsigned int index; - unsigned int midx; - Module mods; - bool replacement = _objcHeaderIsReplacement(hi); - - // Major loop - process all modules in the image - mods = hi->mod_ptr; - for (midx = 0; midx < hi->mod_count; midx += 1) - { - // Skip module containing no classes - if (mods[midx].symtab == nil) - continue; - - // Minor loop - process all the classes in given module - for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1) - { - Class cls = (Class)mods[midx].symtab->defs[index]; - if (! replacement) { - bool connected; - Class futureCls = getFutureClassForOriginalClass(cls); - if (futureCls) { - // objc_getFutureClass() requested a different class - // struct. Fix up the original struct's superclass - // field for [super ...] use, but otherwise perform - // fixups on the new class struct only. - const char *super_name = (const char *) cls->superclass; - if (super_name) cls->superclass = objc_getClass(super_name); - cls = futureCls; - } - connected = connect_class(cls); - if (connected && callbackFunction) { - (*callbackFunction)(cls, 0); - } - } else { - // Replacement image - fix up superclass only (#3704817) - // And metaclass's superclass (#5351107) - const char *super_name = (const char *) cls->superclass; - if (super_name) { - cls->superclass = objc_getClass(super_name); - // metaclass's superclass is superclass's metaclass - cls->ISA()->superclass = cls->superclass->ISA(); - } else { - // Replacement for a root class - // cls->superclass already nil - // root metaclass's superclass is root class - cls->ISA()->superclass = cls; - } - } - } - } -} - - -/*********************************************************************** -* _objc_map_class_refs_for_image. Convert the class ref entries from -* a class name string pointer to a class pointer. If the class does -* not yet exist, the reference is added to a list of pending references -* to be fixed up at a later date. -**********************************************************************/ -static void fix_class_ref(Class *ref, const char *name, bool isMeta) -{ - Class cls; - - // Get pointer to class of this name - // NO unconnected, YES class loader - // (real class with weak-missing superclass is unconnected now) - cls = look_up_class(name, NO, YES); - if (cls) { - // Referenced class exists. Fix up the reference. - *ref = isMeta ? cls->ISA() : cls; - } else { - // Referenced class does not exist yet. Insert nil for now - // (weak-linking) and fix up the reference if the class arrives later. - pendClassReference (ref, name, isMeta); - *ref = nil; - } -} - -static void _objc_map_class_refs_for_image (header_info * hi) -{ - Class *cls_refs; - size_t count; - unsigned int index; - - // Locate class refs in image - cls_refs = _getObjcClassRefs (hi, &count); - if (cls_refs) { - // Process each class ref - for (index = 0; index < count; index += 1) { - // Ref is initially class name char* - const char *name = (const char *) cls_refs[index]; - if (!name) continue; - fix_class_ref(&cls_refs[index], name, NO /*never meta*/); - } - } -} - - -/*********************************************************************** -* _objc_remove_pending_class_refs_in_image -* Delete any pending class ref fixups for class refs in the given image, -* because the image is about to be unloaded. -**********************************************************************/ -static void removePendingReferences(Class *refs, size_t count) -{ - Class *end = refs + count; - - if (!refs) return; - if (!pendingClassRefsMap) return; - - // Search the pending class ref table for class refs in this range. - // The class refs may have already been stomped with nil, - // so there's no way to recover the original class name. - - { - const char *key; - PendingClassRef *pending; - NXMapState state = NXInitMapState(pendingClassRefsMap); - while(NXNextMapState(pendingClassRefsMap, &state, - (const void **)&key, (const void **)&pending)) - { - for ( ; pending != nil; pending = pending->next) { - if (pending->ref >= refs && pending->ref < end) { - pending->ref = nil; - } - } - } - } -} - -static void _objc_remove_pending_class_refs_in_image(header_info *hi) -{ - Class *cls_refs; - size_t count; - - // Locate class refs in this image - cls_refs = _getObjcClassRefs(hi, &count); - removePendingReferences(cls_refs, count); -} - - -/*********************************************************************** -* map_selrefs. For each selector in the specified array, -* replace the name pointer with a uniqued selector. -* If copy is TRUE, all selector data is always copied. This is used -* for registering selectors from unloadable bundles, so the selector -* can still be used after the bundle's data segment is unmapped. -* Returns YES if dst was written to, NO if it was unchanged. -**********************************************************************/ -static inline void map_selrefs(SEL *sels, size_t count, bool copy) -{ - size_t index; - - if (!sels) return; - - sel_lock(); - - // Process each selector - for (index = 0; index < count; index += 1) - { - SEL sel; - - // Lookup pointer to uniqued string - sel = sel_registerNameNoLock((const char *) sels[index], copy); - - // Replace this selector with uniqued one (avoid - // modifying the VM page if this would be a NOP) - if (sels[index] != sel) { - sels[index] = sel; - } - } - - sel_unlock(); -} - - -/*********************************************************************** -* map_method_descs. For each method in the specified method list, -* replace the name pointer with a uniqued selector. -* If copy is TRUE, all selector data is always copied. This is used -* for registering selectors from unloadable bundles, so the selector -* can still be used after the bundle's data segment is unmapped. -**********************************************************************/ -static void map_method_descs (struct objc_method_description_list * methods, bool copy) -{ - int index; - - if (!methods) return; - - sel_lock(); - - // Process each method - for (index = 0; index < methods->count; index += 1) - { - struct objc_method_description * method; - SEL sel; - - // Get method entry to fix up - method = &methods->list[index]; - - // Lookup pointer to uniqued string - sel = sel_registerNameNoLock((const char *) method->name, copy); - - // Replace this selector with uniqued one (avoid - // modifying the VM page if this would be a NOP) - if (method->name != sel) - method->name = sel; - } - - sel_unlock(); -} - - -/*********************************************************************** -* ext_for_protocol -* Returns the protocol extension for the given protocol. -* Returns nil if the protocol has no extension. -**********************************************************************/ -static old_protocol_ext *ext_for_protocol(old_protocol *proto) -{ - if (!proto) return nil; - if (!protocol_ext_map) return nil; - else return (old_protocol_ext *)NXMapGet(protocol_ext_map, proto); -} - - -/*********************************************************************** -* lookup_method -* Search a protocol method list for a selector. -**********************************************************************/ -static struct objc_method_description * -lookup_method(struct objc_method_description_list *mlist, SEL aSel) -{ - if (mlist) { - int i; - for (i = 0; i < mlist->count; i++) { - if (mlist->list[i].name == aSel) { - return mlist->list+i; - } - } - } - return nil; -} - - -/*********************************************************************** -* lookup_protocol_method -* Search for a selector in a protocol -* (and optionally recursively all incorporated protocols) -**********************************************************************/ -struct objc_method_description * -lookup_protocol_method(old_protocol *proto, SEL aSel, - bool isRequiredMethod, bool isInstanceMethod, - bool recursive) -{ - struct objc_method_description *m = nil; - old_protocol_ext *ext; - - if (isRequiredMethod) { - if (isInstanceMethod) { - m = lookup_method(proto->instance_methods, aSel); - } else { - m = lookup_method(proto->class_methods, aSel); - } - } else if ((ext = ext_for_protocol(proto))) { - if (isInstanceMethod) { - m = lookup_method(ext->optional_instance_methods, aSel); - } else { - m = lookup_method(ext->optional_class_methods, aSel); - } - } - - if (!m && recursive && proto->protocol_list) { - int i; - for (i = 0; !m && i < proto->protocol_list->count; i++) { - m = lookup_protocol_method(proto->protocol_list->list[i], aSel, - isRequiredMethod,isInstanceMethod,true); - } - } - - return m; -} - - -/*********************************************************************** -* protocol_getName -* Returns the name of the given protocol. -**********************************************************************/ -const char *protocol_getName(Protocol *p) -{ - old_protocol *proto = oldprotocol(p); - if (!proto) return "nil"; - return proto->protocol_name; -} - - -/*********************************************************************** -* protocol_getMethodDescription -* Returns the description of a named method. -* Searches either required or optional methods. -* Searches either instance or class methods. -**********************************************************************/ -struct objc_method_description -protocol_getMethodDescription(Protocol *p, SEL aSel, - BOOL isRequiredMethod, BOOL isInstanceMethod) -{ - struct objc_method_description empty = {nil, nil}; - old_protocol *proto = oldprotocol(p); - struct objc_method_description *desc; - if (!proto) return empty; - - desc = lookup_protocol_method(proto, aSel, - isRequiredMethod, isInstanceMethod, true); - if (desc) return *desc; - else return empty; -} - - -/*********************************************************************** -* protocol_copyMethodDescriptionList -* Returns an array of method descriptions from a protocol. -* Copies either required or optional methods. -* Copies either instance or class methods. -**********************************************************************/ -struct objc_method_description * -protocol_copyMethodDescriptionList(Protocol *p, - BOOL isRequiredMethod, - BOOL isInstanceMethod, - unsigned int *outCount) -{ - struct objc_method_description_list *mlist = nil; - old_protocol *proto = oldprotocol(p); - old_protocol_ext *ext; - unsigned int i, count; - struct objc_method_description *result; - - if (!proto) { - if (outCount) *outCount = 0; - return nil; - } - - if (isRequiredMethod) { - if (isInstanceMethod) { - mlist = proto->instance_methods; - } else { - mlist = proto->class_methods; - } - } else if ((ext = ext_for_protocol(proto))) { - if (isInstanceMethod) { - mlist = ext->optional_instance_methods; - } else { - mlist = ext->optional_class_methods; - } - } - - if (!mlist) { - if (outCount) *outCount = 0; - return nil; - } - - count = mlist->count; - result = (struct objc_method_description *) - calloc(count + 1, sizeof(struct objc_method_description)); - for (i = 0; i < count; i++) { - result[i] = mlist->list[i]; - } - - if (outCount) *outCount = count; - return result; -} - - -objc_property_t protocol_getProperty(Protocol *p, const char *name, - BOOL isRequiredProperty, BOOL isInstanceProperty) -{ - old_protocol *proto = oldprotocol(p); - old_protocol_ext *ext; - old_protocol_list *proto_list; - - if (!proto || !name) return nil; - - if (!isRequiredProperty || !isInstanceProperty) { - // Only required instance properties are currently supported - return nil; - } - - if ((ext = ext_for_protocol(proto))) { - old_property_list *plist; - if ((plist = ext->instance_properties)) { - uint32_t i; - for (i = 0; i < plist->count; i++) { - old_property *prop = property_list_nth(plist, i); - if (0 == strcmp(name, prop->name)) { - return (objc_property_t)prop; - } - } - } - } - - if ((proto_list = proto->protocol_list)) { - int i; - for (i = 0; i < proto_list->count; i++) { - objc_property_t prop = - protocol_getProperty((Protocol *)proto_list->list[i], name, - isRequiredProperty, isInstanceProperty); - if (prop) return prop; - } - } - - return nil; -} - - -objc_property_t *protocol_copyPropertyList(Protocol *p, unsigned int *outCount) -{ - old_property **result = nil; - old_protocol_ext *ext; - old_property_list *plist; - - old_protocol *proto = oldprotocol(p); - if (! (ext = ext_for_protocol(proto))) { - if (outCount) *outCount = 0; - return nil; - } - - plist = ext->instance_properties; - result = copyPropertyList(plist, outCount); - - return (objc_property_t *)result; -} - - -/*********************************************************************** -* protocol_copyProtocolList -* Copies this protocol's incorporated protocols. -* Does not copy those protocol's incorporated protocols in turn. -**********************************************************************/ -Protocol * __unsafe_unretained * -protocol_copyProtocolList(Protocol *p, unsigned int *outCount) -{ - unsigned int count = 0; - Protocol **result = nil; - old_protocol *proto = oldprotocol(p); - - if (!proto) { - if (outCount) *outCount = 0; - return nil; - } - - if (proto->protocol_list) { - count = (unsigned int)proto->protocol_list->count; - } - if (count > 0) { - unsigned int i; - result = (Protocol **)malloc((count+1) * sizeof(Protocol *)); - - for (i = 0; i < count; i++) { - result[i] = (Protocol *)proto->protocol_list->list[i]; - } - result[i] = nil; - } - - if (outCount) *outCount = count; - return result; -} - - -BOOL protocol_conformsToProtocol(Protocol *self_gen, Protocol *other_gen) -{ - old_protocol *self = oldprotocol(self_gen); - old_protocol *other = oldprotocol(other_gen); - - if (!self || !other) { - return NO; - } - - if (0 == strcmp(self->protocol_name, other->protocol_name)) { - return YES; - } - - if (self->protocol_list) { - int i; - for (i = 0; i < self->protocol_list->count; i++) { - old_protocol *proto = self->protocol_list->list[i]; - if (0 == strcmp(other->protocol_name, proto->protocol_name)) { - return YES; - } - if (protocol_conformsToProtocol((Protocol *)proto, other_gen)) { - return YES; - } - } - } - - return NO; -} - - -BOOL protocol_isEqual(Protocol *self, Protocol *other) -{ - if (self == other) return YES; - if (!self || !other) return NO; - - if (!protocol_conformsToProtocol(self, other)) return NO; - if (!protocol_conformsToProtocol(other, self)) return NO; - - return YES; -} - - -/*********************************************************************** -* _protocol_getMethodTypeEncoding -* Return the @encode string for the requested protocol method. -* Returns nil if the compiler did not emit any extended @encode data. -* Locking: runtimeLock must not be held by the caller -**********************************************************************/ -const char * -_protocol_getMethodTypeEncoding(Protocol *proto_gen, SEL sel, - BOOL isRequiredMethod, BOOL isInstanceMethod) -{ - old_protocol *proto = oldprotocol(proto_gen); - if (!proto) return nil; - old_protocol_ext *ext = ext_for_protocol(proto); - if (!ext) return nil; - if (ext->size < offsetof(old_protocol_ext, extendedMethodTypes) + sizeof(ext->extendedMethodTypes)) return nil; - if (! ext->extendedMethodTypes) return nil; - - struct objc_method_description *m = - lookup_protocol_method(proto, sel, - isRequiredMethod, isInstanceMethod, false); - if (!m) { - // No method with that name. Search incorporated protocols. - if (proto->protocol_list) { - for (int i = 0; i < proto->protocol_list->count; i++) { - const char *enc = - _protocol_getMethodTypeEncoding((Protocol *)proto->protocol_list->list[i], sel, isRequiredMethod, isInstanceMethod); - if (enc) return enc; - } - } - return nil; - } - - int i = 0; - if (isRequiredMethod && isInstanceMethod) { - i += ((uintptr_t)m - (uintptr_t)proto->instance_methods) / sizeof(proto->instance_methods->list[0]); - goto done; - } else if (proto->instance_methods) { - i += proto->instance_methods->count; - } - - if (isRequiredMethod && !isInstanceMethod) { - i += ((uintptr_t)m - (uintptr_t)proto->class_methods) / sizeof(proto->class_methods->list[0]); - goto done; - } else if (proto->class_methods) { - i += proto->class_methods->count; - } - - if (!isRequiredMethod && isInstanceMethod) { - i += ((uintptr_t)m - (uintptr_t)ext->optional_instance_methods) / sizeof(ext->optional_instance_methods->list[0]); - goto done; - } else if (ext->optional_instance_methods) { - i += ext->optional_instance_methods->count; - } - - if (!isRequiredMethod && !isInstanceMethod) { - i += ((uintptr_t)m - (uintptr_t)ext->optional_class_methods) / sizeof(ext->optional_class_methods->list[0]); - goto done; - } else if (ext->optional_class_methods) { - i += ext->optional_class_methods->count; - } - - done: - return ext->extendedMethodTypes[i]; -} - - -/*********************************************************************** -* objc_allocateProtocol -* Creates a new protocol. The protocol may not be used until -* objc_registerProtocol() is called. -* Returns nil if a protocol with the same name already exists. -* Locking: acquires classLock -**********************************************************************/ -Protocol * -objc_allocateProtocol(const char *name) -{ - Class cls = objc_getClass("__IncompleteProtocol"); - - mutex_locker_t lock(classLock); - - if (NXMapGet(protocol_map, name)) return nil; - - old_protocol *result = (old_protocol *) - calloc(1, sizeof(old_protocol) - + sizeof(old_protocol_ext)); - old_protocol_ext *ext = (old_protocol_ext *)(result+1); - - result->isa = cls; - result->protocol_name = strdup(name); - ext->size = sizeof(old_protocol_ext); - - // fixme reserve name without installing - - NXMapInsert(protocol_ext_map, result, result+1); - - return (Protocol *)result; -} - - -/*********************************************************************** -* objc_registerProtocol -* Registers a newly-constructed protocol. The protocol is now -* ready for use and immutable. -* Locking: acquires classLock -**********************************************************************/ -void objc_registerProtocol(Protocol *proto_gen) -{ - old_protocol *proto = oldprotocol(proto_gen); - - Class oldcls = objc_getClass("__IncompleteProtocol"); - Class cls = objc_getClass("Protocol"); - - mutex_locker_t lock(classLock); - - if (proto->isa == cls) { - _objc_inform("objc_registerProtocol: protocol '%s' was already " - "registered!", proto->protocol_name); - return; - } - if (proto->isa != oldcls) { - _objc_inform("objc_registerProtocol: protocol '%s' was not allocated " - "with objc_allocateProtocol!", proto->protocol_name); - return; - } - - proto->isa = cls; - - NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto); -} - - -/*********************************************************************** -* protocol_addProtocol -* Adds an incorporated protocol to another protocol. -* No method enforcement is performed. -* `proto` must be under construction. `addition` must not. -* Locking: acquires classLock -**********************************************************************/ -void -protocol_addProtocol(Protocol *proto_gen, Protocol *addition_gen) -{ - old_protocol *proto = oldprotocol(proto_gen); - old_protocol *addition = oldprotocol(addition_gen); - - Class cls = objc_getClass("__IncompleteProtocol"); - - if (!proto_gen) return; - if (!addition_gen) return; - - mutex_locker_t lock(classLock); - - if (proto->isa != cls) { - _objc_inform("protocol_addProtocol: modified protocol '%s' is not " - "under construction!", proto->protocol_name); - return; - } - if (addition->isa == cls) { - _objc_inform("protocol_addProtocol: added protocol '%s' is still " - "under construction!", addition->protocol_name); - return; - } - - old_protocol_list *protolist = proto->protocol_list; - if (protolist) { - size_t size = sizeof(old_protocol_list) - + protolist->count * sizeof(protolist->list[0]); - protolist = (old_protocol_list *) - realloc(protolist, size); - } else { - protolist = (old_protocol_list *) - calloc(1, sizeof(old_protocol_list)); - } - - protolist->list[protolist->count++] = addition; - proto->protocol_list = protolist; -} - - -/*********************************************************************** -* protocol_addMethodDescription -* Adds a method to a protocol. The protocol must be under construction. -* Locking: acquires classLock -**********************************************************************/ -static void -_protocol_addMethod(struct objc_method_description_list **list, SEL name, const char *types) -{ - if (!*list) { - *list = (struct objc_method_description_list *) - calloc(sizeof(struct objc_method_description_list), 1); - } else { - size_t size = sizeof(struct objc_method_description_list) - + (*list)->count * sizeof(struct objc_method_description); - *list = (struct objc_method_description_list *) - realloc(*list, size); - } - - struct objc_method_description *desc = &(*list)->list[(*list)->count++]; - desc->name = name; - desc->types = strdup(types ?: ""); -} - -void -protocol_addMethodDescription(Protocol *proto_gen, SEL name, const char *types, - BOOL isRequiredMethod, BOOL isInstanceMethod) -{ - old_protocol *proto = oldprotocol(proto_gen); - - Class cls = objc_getClass("__IncompleteProtocol"); - - if (!proto_gen) return; - - mutex_locker_t lock(classLock); - - if (proto->isa != cls) { - _objc_inform("protocol_addMethodDescription: protocol '%s' is not " - "under construction!", proto->protocol_name); - return; - } - - if (isRequiredMethod && isInstanceMethod) { - _protocol_addMethod(&proto->instance_methods, name, types); - } else if (isRequiredMethod && !isInstanceMethod) { - _protocol_addMethod(&proto->class_methods, name, types); - } else if (!isRequiredMethod && isInstanceMethod) { - old_protocol_ext *ext = (old_protocol_ext *)(proto+1); - _protocol_addMethod(&ext->optional_instance_methods, name, types); - } else /* !isRequiredMethod && !isInstanceMethod) */ { - old_protocol_ext *ext = (old_protocol_ext *)(proto+1); - _protocol_addMethod(&ext->optional_class_methods, name, types); - } -} - - -/*********************************************************************** -* protocol_addProperty -* Adds a property to a protocol. The protocol must be under construction. -* Locking: acquires classLock -**********************************************************************/ -static void -_protocol_addProperty(old_property_list **plist, const char *name, - const objc_property_attribute_t *attrs, - unsigned int count) -{ - if (!*plist) { - *plist = (old_property_list *) - calloc(sizeof(old_property_list), 1); - (*plist)->entsize = sizeof(old_property); - } else { - *plist = (old_property_list *) - realloc(*plist, sizeof(old_property_list) - + (*plist)->count * (*plist)->entsize); - } - - old_property *prop = property_list_nth(*plist, (*plist)->count++); - prop->name = strdup(name); - prop->attributes = copyPropertyAttributeString(attrs, count); -} - -void -protocol_addProperty(Protocol *proto_gen, const char *name, - const objc_property_attribute_t *attrs, - unsigned int count, - BOOL isRequiredProperty, BOOL isInstanceProperty) -{ - old_protocol *proto = oldprotocol(proto_gen); - - Class cls = objc_getClass("__IncompleteProtocol"); - - if (!proto) return; - if (!name) return; - - mutex_locker_t lock(classLock); - - if (proto->isa != cls) { - _objc_inform("protocol_addProperty: protocol '%s' is not " - "under construction!", proto->protocol_name); - return; - } - - old_protocol_ext *ext = ext_for_protocol(proto); - - if (isRequiredProperty && isInstanceProperty) { - _protocol_addProperty(&ext->instance_properties, name, attrs, count); - } - //else if (isRequiredProperty && !isInstanceProperty) { - // _protocol_addProperty(&ext->class_properties, name, attrs, count); - //} else if (!isRequiredProperty && isInstanceProperty) { - // _protocol_addProperty(&ext->optional_instance_properties, name, attrs, count); - //} else /* !isRequiredProperty && !isInstanceProperty) */ { - // _protocol_addProperty(&ext->optional_class_properties, name, attrs, count); - //} -} - - -/*********************************************************************** -* _objc_fixup_protocol_objects_for_image. For each protocol in the -* specified image, selectorize the method names and add to the protocol hash. -**********************************************************************/ - -static bool versionIsExt(uintptr_t version, const char *names, size_t size) -{ - // CodeWarrior used isa field for string "Protocol" - // from section __OBJC,__class_names. rdar://4951638 - // gcc (10.4 and earlier) used isa field for version number; - // the only version number used on Mac OS X was 2. - // gcc (10.5 and later) uses isa field for ext pointer - - if (version < 4096 /* not PAGE_SIZE */) { - return NO; - } - - if (version >= (uintptr_t)names && version < (uintptr_t)(names + size)) { - return NO; - } - - return YES; -} - -static void fix_protocol(old_protocol *proto, Class protocolClass, - bool isBundle, const char *names, size_t names_size) -{ - uintptr_t version; - if (!proto) return; - - version = (uintptr_t)proto->isa; - - // Set the protocol's isa - proto->isa = protocolClass; - - // Fix up method lists - // fixme share across duplicates - map_method_descs (proto->instance_methods, isBundle); - map_method_descs (proto->class_methods, isBundle); - - // Fix up ext, if any - if (versionIsExt(version, names, names_size)) { - old_protocol_ext *ext = (old_protocol_ext *)version; - NXMapInsert(protocol_ext_map, proto, ext); - map_method_descs (ext->optional_instance_methods, isBundle); - map_method_descs (ext->optional_class_methods, isBundle); - } - - // Record the protocol it if we don't have one with this name yet - // fixme bundles - copy protocol - // fixme unloading - if (!NXMapGet(protocol_map, proto->protocol_name)) { - NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto); - if (PrintProtocols) { - _objc_inform("PROTOCOLS: protocol at %p is %s", - proto, proto->protocol_name); - } - } else { - // duplicate - do nothing - if (PrintProtocols) { - _objc_inform("PROTOCOLS: protocol at %p is %s (duplicate)", - proto, proto->protocol_name); - } - } -} - -static void _objc_fixup_protocol_objects_for_image (header_info * hi) -{ - Class protocolClass = objc_getClass("Protocol"); - size_t count, i; - old_protocol **protos; - int isBundle = headerIsBundle(hi); - const char *names; - size_t names_size; - - mutex_locker_t lock(classLock); - - // Allocate the protocol registry if necessary. - if (!protocol_map) { - protocol_map = - NXCreateMapTable(NXStrValueMapPrototype, 32); - } - if (!protocol_ext_map) { - protocol_ext_map = - NXCreateMapTable(NXPtrValueMapPrototype, 32); - } - - protos = _getObjcProtocols(hi, &count); - names = _getObjcClassNames(hi, &names_size); - for (i = 0; i < count; i++) { - fix_protocol(protos[i], protocolClass, isBundle, names, names_size); - } -} - - -/*********************************************************************** -* _objc_fixup_selector_refs. Register all of the selectors in each -* image, and fix them all up. -**********************************************************************/ -static void _objc_fixup_selector_refs (const header_info *hi) -{ - size_t count; - SEL *sels; - - bool preoptimized = hi->isPreoptimized(); -# if SUPPORT_IGNORED_SELECTOR_CONSTANT - // shared cache can't fix constant ignored selectors - if (UseGC) preoptimized = NO; -# endif - - if (PrintPreopt) { - if (preoptimized) { - _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors in %s", - hi->fname); - } - else if (_objcHeaderOptimizedByDyld(hi)) { - _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors in %s", - hi->fname); - } - } - - if (preoptimized) return; - - sels = _getObjcSelectorRefs (hi, &count); - - map_selrefs(sels, count, headerIsBundle(hi)); -} - -static inline bool _is_threaded() { -#if TARGET_OS_WIN32 - return YES; -#else - return pthread_is_threaded_np() != 0; -#endif -} - -#if !TARGET_OS_WIN32 -/*********************************************************************** -* unmap_image -* Process the given image which is about to be unmapped by dyld. -* mh is mach_header instead of headerType because that's what -* dyld_priv.h says even for 64-bit. -**********************************************************************/ -void -unmap_image(const struct mach_header *mh, intptr_t vmaddr_slide) -{ - recursive_mutex_locker_t lock(loadMethodLock); - unmap_image_nolock(mh); -} - - -/*********************************************************************** -* map_images -* Process the given images which are being mapped in by dyld. -* Calls ABI-agnostic code after taking ABI-specific locks. -**********************************************************************/ -const char * -map_2_images(enum dyld_image_states state, uint32_t infoCount, - const struct dyld_image_info infoList[]) -{ - recursive_mutex_locker_t lock(loadMethodLock); - return map_images_nolock(state, infoCount, infoList); -} - - -/*********************************************************************** -* load_images -* Process +load in the given images which are being mapped in by dyld. -* Calls ABI-agnostic code after taking ABI-specific locks. -* -* Locking: acquires classLock and loadMethodLock -**********************************************************************/ -const char * -load_images(enum dyld_image_states state, uint32_t infoCount, - const struct dyld_image_info infoList[]) -{ - bool found; - - recursive_mutex_locker_t lock(loadMethodLock); - - // Discover +load methods - found = load_images_nolock(state, infoCount, infoList); - - // Call +load methods (without classLock - re-entrant) - if (found) { - call_load_methods(); - } - - return nil; -} -#endif - - -/*********************************************************************** -* _read_images -* Perform metadata processing for hCount images starting with firstNewHeader -**********************************************************************/ -void _read_images(header_info **hList, uint32_t hCount) -{ - uint32_t i; - bool categoriesLoaded = NO; - - if (!class_hash) _objc_init_class_hash(); - - // Parts of this order are important for correctness or performance. - - // Read classes from all images. - for (i = 0; i < hCount; i++) { - _objc_read_classes_from_image(hList[i]); - } - - // Read categories from all images. - // But not if any other threads are running - they might - // call a category method before the fixups below are complete. - if (!_is_threaded()) { - bool needFlush = NO; - for (i = 0; i < hCount; i++) { - needFlush |= _objc_read_categories_from_image(hList[i]); - } - if (needFlush) flush_marked_caches(); - categoriesLoaded = YES; - } - - // Connect classes from all images. - for (i = 0; i < hCount; i++) { - _objc_connect_classes_from_image(hList[i]); - } - - // Fix up class refs, selector refs, and protocol objects from all images. - for (i = 0; i < hCount; i++) { - _objc_map_class_refs_for_image(hList[i]); - _objc_fixup_selector_refs(hList[i]); - _objc_fixup_protocol_objects_for_image(hList[i]); - } - - // Read categories from all images. - // But not if this is the only thread - it's more - // efficient to attach categories earlier if safe. - if (!categoriesLoaded) { - bool needFlush = NO; - for (i = 0; i < hCount; i++) { - needFlush |= _objc_read_categories_from_image(hList[i]); - } - if (needFlush) flush_marked_caches(); - } - - // Multi-threaded category load MUST BE LAST to avoid a race. -} - - -/*********************************************************************** -* prepare_load_methods -* Schedule +load for classes in this image, any un-+load-ed -* superclasses in other images, and any categories in this image. -**********************************************************************/ -// Recursively schedule +load for cls and any un-+load-ed superclasses. -// cls must already be connected. -static void schedule_class_load(Class cls) -{ - if (cls->info & CLS_LOADED) return; - if (cls->superclass) schedule_class_load(cls->superclass); - add_class_to_loadable_list(cls); - cls->info |= CLS_LOADED; -} - -bool hasLoadMethods(const headerType *mhdr) -{ - return true; -} - -void prepare_load_methods(const headerType *mhdr) -{ - Module mods; - unsigned int midx; - - header_info *hi; - for (hi = FirstHeader; hi; hi = hi->next) { - if (mhdr == hi->mhdr) break; - } - if (!hi) return; - - if (_objcHeaderIsReplacement(hi)) { - // Ignore any classes in this image - return; - } - - // Major loop - process all modules in the image - mods = hi->mod_ptr; - for (midx = 0; midx < hi->mod_count; midx += 1) - { - unsigned int index; - - // Skip module containing no classes - if (mods[midx].symtab == nil) - continue; - - // Minor loop - process all the classes in given module - for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1) - { - // Locate the class description pointer - Class cls = (Class)mods[midx].symtab->defs[index]; - if (cls->info & CLS_CONNECTED) { - schedule_class_load(cls); - } - } - } - - - // Major loop - process all modules in the header - mods = hi->mod_ptr; - - // NOTE: The module and category lists are traversed backwards - // to preserve the pre-10.4 processing order. Changing the order - // would have a small chance of introducing binary compatibility bugs. - midx = (unsigned int)hi->mod_count; - while (midx-- > 0) { - unsigned int index; - unsigned int total; - Symtab symtab = mods[midx].symtab; - - // Nothing to do for a module without a symbol table - if (mods[midx].symtab == nil) - continue; - // Total entries in symbol table (class entries followed - // by category entries) - total = mods[midx].symtab->cls_def_cnt + - mods[midx].symtab->cat_def_cnt; - - // Minor loop - register all categories from given module - index = total; - while (index-- > mods[midx].symtab->cls_def_cnt) { - old_category *cat = (old_category *)symtab->defs[index]; - add_category_to_loadable_list((Category)cat); - } - } -} - - -#if TARGET_OS_WIN32 - -void unload_class(Class cls) -{ -} - -#else - -/*********************************************************************** -* _objc_remove_classes_in_image -* Remove all classes in the given image from the runtime, because -* the image is about to be unloaded. -* Things to clean up: -* class_hash -* unconnected_class_hash -* pending subclasses list (only if class is still unconnected) -* loadable class list -* class's method caches -* class refs in all other images -**********************************************************************/ -// Re-pend any class references in refs that point into [start..end) -static void rependClassReferences(Class *refs, size_t count, - uintptr_t start, uintptr_t end) -{ - size_t i; - - if (!refs) return; - - // Process each class ref - for (i = 0; i < count; i++) { - if ((uintptr_t)(refs[i]) >= start && (uintptr_t)(refs[i]) < end) { - pendClassReference(&refs[i], refs[i]->name, - refs[i]->info & CLS_META); - refs[i] = nil; - } - } -} - - -void try_free(const void *p) -{ - if (p && malloc_size(p)) free((void *)p); -} - -// Deallocate all memory in a method list -static void unload_mlist(old_method_list *mlist) -{ - int i; - for (i = 0; i < mlist->method_count; i++) { - try_free(mlist->method_list[i].method_types); - } - try_free(mlist); -} - -static void unload_property_list(old_property_list *proplist) -{ - uint32_t i; - - if (!proplist) return; - - for (i = 0; i < proplist->count; i++) { - old_property *prop = property_list_nth(proplist, i); - try_free(prop->name); - try_free(prop->attributes); - } - try_free(proplist); -} - - -// Deallocate all memory in a class. -void unload_class(Class cls) -{ - // Free method cache - // This dereferences the cache contents; do this before freeing methods - if (cls->cache && cls->cache != &_objc_empty_cache) { - _cache_free(cls->cache); - } - - // Free ivar lists - if (cls->ivars) { - int i; - for (i = 0; i < cls->ivars->ivar_count; i++) { - try_free(cls->ivars->ivar_list[i].ivar_name); - try_free(cls->ivars->ivar_list[i].ivar_type); - } - try_free(cls->ivars); - } - - // Free fixed-up method lists and method list array - if (cls->methodLists) { - // more than zero method lists - if (cls->info & CLS_NO_METHOD_ARRAY) { - // one method list - unload_mlist((old_method_list *)cls->methodLists); - } - else { - // more than one method list - old_method_list **mlistp; - for (mlistp = cls->methodLists; - *mlistp != nil && *mlistp != END_OF_METHODS_LIST; - mlistp++) - { - unload_mlist(*mlistp); - } - free(cls->methodLists); - } - } - - // Free protocol list - old_protocol_list *protos = cls->protocols; - while (protos) { - old_protocol_list *dead = protos; - protos = protos->next; - try_free(dead); - } - - if ((cls->info & CLS_EXT)) { - if (cls->ext) { - // Free property lists and property list array - if (cls->ext->propertyLists) { - // more than zero property lists - if (cls->info & CLS_NO_PROPERTY_ARRAY) { - // one property list - old_property_list *proplist = - (old_property_list *)cls->ext->propertyLists; - unload_property_list(proplist); - } else { - // more than one property list - old_property_list **plistp; - for (plistp = cls->ext->propertyLists; - *plistp != nil; - plistp++) - { - unload_property_list(*plistp); - } - try_free(cls->ext->propertyLists); - } - } - - // Free weak ivar layout - try_free(cls->ext->weak_ivar_layout); - - // Free ext - try_free(cls->ext); - } - - // Free non-weak ivar layout - try_free(cls->ivar_layout); - } - - // Free class name - try_free(cls->name); - - // Free cls - try_free(cls); -} - - -static void _objc_remove_classes_in_image(header_info *hi) -{ - unsigned int index; - unsigned int midx; - Module mods; - - mutex_locker_t lock(classLock); - - // Major loop - process all modules in the image - mods = hi->mod_ptr; - for (midx = 0; midx < hi->mod_count; midx += 1) - { - // Skip module containing no classes - if (mods[midx].symtab == nil) - continue; - - // Minor loop - process all the classes in given module - for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1) - { - Class cls; - - // Locate the class description pointer - cls = (Class)mods[midx].symtab->defs[index]; - - // Remove from loadable class list, if present - remove_class_from_loadable_list(cls); - - // Remove from unconnected_class_hash and pending subclasses - if (unconnected_class_hash && NXHashMember(unconnected_class_hash, cls)) { - NXHashRemove(unconnected_class_hash, cls); - if (pendingSubclassesMap) { - // Find this class in its superclass's pending list - char *supercls_name = (char *)cls->superclass; - PendingSubclass *pending = (PendingSubclass *) - NXMapGet(pendingSubclassesMap, supercls_name); - for ( ; pending != nil; pending = pending->next) { - if (pending->subclass == cls) { - pending->subclass = Nil; - break; - } - } - } - } - - // Remove from class_hash - NXHashRemove(class_hash, cls); - objc_removeRegisteredClass(cls); - - // Free heap memory pointed to by the class - unload_class(cls->ISA()); - unload_class(cls); - } - } - - - // Search all other images for class refs that point back to this range. - // Un-fix and re-pend any such class refs. - - // Get the location of the dying image's __OBJC segment - uintptr_t seg; - unsigned long seg_size; - seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size); - - header_info *other_hi; - for (other_hi = FirstHeader; other_hi != nil; other_hi = other_hi->next) { - Class *other_refs; - size_t count; - if (other_hi == hi) continue; // skip the image being unloaded - - // Fix class refs in the other image - other_refs = _getObjcClassRefs(other_hi, &count); - rependClassReferences(other_refs, count, seg, seg+seg_size); - } -} - - -/*********************************************************************** -* _objc_remove_categories_in_image -* Remove all categories in the given image from the runtime, because -* the image is about to be unloaded. -* Things to clean up: -* unresolved category list -* loadable category list -**********************************************************************/ -static void _objc_remove_categories_in_image(header_info *hi) -{ - Module mods; - unsigned int midx; - - // Major loop - process all modules in the header - mods = hi->mod_ptr; - - for (midx = 0; midx < hi->mod_count; midx++) { - unsigned int index; - unsigned int total; - Symtab symtab = mods[midx].symtab; - - // Nothing to do for a module without a symbol table - if (symtab == nil) continue; - - // Total entries in symbol table (class entries followed - // by category entries) - total = symtab->cls_def_cnt + symtab->cat_def_cnt; - - // Minor loop - check all categories from given module - for (index = symtab->cls_def_cnt; index < total; index++) { - old_category *cat = (old_category *)symtab->defs[index]; - - // Clean up loadable category list - remove_category_from_loadable_list((Category)cat); - - // Clean up category_hash - if (category_hash) { - _objc_unresolved_category *cat_entry = (_objc_unresolved_category *)NXMapGet(category_hash, cat->class_name); - for ( ; cat_entry != nil; cat_entry = cat_entry->next) { - if (cat_entry->cat == cat) { - cat_entry->cat = nil; - break; - } - } - } - } - } -} - - -/*********************************************************************** -* unload_paranoia -* Various paranoid debugging checks that look for poorly-behaving -* unloadable bundles. -* Called by _objc_unmap_image when OBJC_UNLOAD_DEBUG is set. -**********************************************************************/ -static void unload_paranoia(header_info *hi) -{ - // Get the location of the dying image's __OBJC segment - uintptr_t seg; - unsigned long seg_size; - seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size); - - _objc_inform("UNLOAD DEBUG: unloading image '%s' [%p..%p]", - hi->fname, (void *)seg, (void*)(seg+seg_size)); - - mutex_locker_t lock(classLock); - - // Make sure the image contains no categories on surviving classes. - { - Module mods; - unsigned int midx; - - // Major loop - process all modules in the header - mods = hi->mod_ptr; - - for (midx = 0; midx < hi->mod_count; midx++) { - unsigned int index; - unsigned int total; - Symtab symtab = mods[midx].symtab; - - // Nothing to do for a module without a symbol table - if (symtab == nil) continue; - - // Total entries in symbol table (class entries followed - // by category entries) - total = symtab->cls_def_cnt + symtab->cat_def_cnt; - - // Minor loop - check all categories from given module - for (index = symtab->cls_def_cnt; index < total; index++) { - old_category *cat = (old_category *)symtab->defs[index]; - struct objc_class query; - - query.name = cat->class_name; - if (NXHashMember(class_hash, &query)) { - _objc_inform("UNLOAD DEBUG: dying image contains category '%s(%s)' on surviving class '%s'!", cat->class_name, cat->category_name, cat->class_name); - } - } - } - } - - // Make sure no surviving class is in the dying image. - // Make sure no surviving class has a superclass in the dying image. - // fixme check method implementations too - { - Class cls; - NXHashState state; - - state = NXInitHashState(class_hash); - while (NXNextHashState(class_hash, &state, (void **)&cls)) { - if ((vm_address_t)cls >= seg && - (vm_address_t)cls < seg+seg_size) - { - _objc_inform("UNLOAD DEBUG: dying image contains surviving class '%s'!", cls->name); - } - - if ((vm_address_t)cls->superclass >= seg && - (vm_address_t)cls->superclass < seg+seg_size) - { - _objc_inform("UNLOAD DEBUG: dying image contains superclass '%s' of surviving class '%s'!", cls->superclass->name, cls->name); - } - } - } -} - - -/*********************************************************************** -* _unload_image -* Only handles MH_BUNDLE for now. -* Locking: loadMethodLock acquired by unmap_image -**********************************************************************/ -void _unload_image(header_info *hi) -{ - loadMethodLock.assertLocked(); - - // Cleanup: - // Remove image's classes from the class list and free auxiliary data. - // Remove image's unresolved or loadable categories and free auxiliary data - // Remove image's unresolved class refs. - _objc_remove_classes_in_image(hi); - _objc_remove_categories_in_image(hi); - _objc_remove_pending_class_refs_in_image(hi); - - // Perform various debugging checks if requested. - if (DebugUnload) unload_paranoia(hi); -} - -#endif - - -/*********************************************************************** -* objc_addClass. Add the specified class to the table of known classes, -* after doing a little verification and fixup. -**********************************************************************/ -void objc_addClass (Class cls) -{ - OBJC_WARN_DEPRECATED; - - // Synchronize access to hash table - mutex_locker_t lock(classLock); - - // Make sure both the class and the metaclass have caches! - // Clear all bits of the info fields except CLS_CLASS and CLS_META. - // Normally these bits are already clear but if someone tries to cons - // up their own class on the fly they might need to be cleared. - if (cls->cache == nil) { - cls->cache = (Cache) &_objc_empty_cache; - cls->info = CLS_CLASS; - } - - if (cls->ISA()->cache == nil) { - cls->ISA()->cache = (Cache) &_objc_empty_cache; - cls->ISA()->info = CLS_META; - } - - // methodLists should be: - // 1. nil (Tiger and later only) - // 2. A -1 terminated method list array - // In either case, CLS_NO_METHOD_ARRAY remains clear. - // If the user manipulates the method list directly, - // they must use the magic private format. - - // Add the class to the table - (void) NXHashInsert (class_hash, cls); - objc_addRegisteredClass(cls); - - // Superclass is no longer a leaf for cache flushing - if (cls->superclass && (cls->superclass->info & CLS_LEAF)) { - cls->superclass->clearInfo(CLS_LEAF); - cls->superclass->ISA()->clearInfo(CLS_LEAF); - } -} - -/*********************************************************************** -* _objcTweakMethodListPointerForClass. -* Change the class's method list pointer to a method list array. -* Does nothing if the method list pointer is already a method list array. -* If the class is currently in use, methodListLock must be held by the caller. -**********************************************************************/ -static void _objcTweakMethodListPointerForClass(Class cls) -{ - old_method_list * originalList; - const int initialEntries = 4; - size_t mallocSize; - old_method_list ** ptr; - - // Do nothing if methodLists is already an array. - if (cls->methodLists && !(cls->info & CLS_NO_METHOD_ARRAY)) return; - - // Remember existing list - originalList = (old_method_list *) cls->methodLists; - - // Allocate and zero a method list array - mallocSize = sizeof(old_method_list *) * initialEntries; - ptr = (old_method_list **) calloc(1, mallocSize); - - // Insert the existing list into the array - ptr[initialEntries - 1] = END_OF_METHODS_LIST; - ptr[0] = originalList; - - // Replace existing list with array - cls->methodLists = ptr; - cls->clearInfo(CLS_NO_METHOD_ARRAY); -} - - -/*********************************************************************** -* _objc_insertMethods. -* Adds methods to a class. -* Does not flush any method caches. -* Does not take any locks. -* If the class is already in use, use class_addMethods() instead. -**********************************************************************/ -void _objc_insertMethods(Class cls, old_method_list *mlist, old_category *cat) -{ - old_method_list ***list; - old_method_list **ptr; - ptrdiff_t endIndex; - size_t oldSize; - size_t newSize; - - if (!cls->methodLists) { - // cls has no methods - simply use this method list - cls->methodLists = (old_method_list **)mlist; - cls->setInfo(CLS_NO_METHOD_ARRAY); - return; - } - - // Log any existing methods being replaced - if (PrintReplacedMethods) { - int i; - for (i = 0; i < mlist->method_count; i++) { - extern IMP findIMPInClass(Class cls, SEL sel); - SEL sel = sel_registerName((char *)mlist->method_list[i].method_name); - IMP newImp = mlist->method_list[i].method_imp; - IMP oldImp; - - if ((oldImp = findIMPInClass(cls, sel))) { - logReplacedMethod(cls->name, sel, ISMETA(cls), - cat ? cat->category_name : nil, - oldImp, newImp); - } - } - } - - // Create method list array if necessary - _objcTweakMethodListPointerForClass(cls); - - list = &cls->methodLists; - - // Locate unused entry for insertion point - ptr = *list; - while ((*ptr != 0) && (*ptr != END_OF_METHODS_LIST)) - ptr += 1; - - // If array is full, add to it - if (*ptr == END_OF_METHODS_LIST) - { - // Calculate old and new dimensions - endIndex = ptr - *list; - oldSize = (endIndex + 1) * sizeof(void *); - newSize = oldSize + sizeof(old_method_list *); // only increase by 1 - - // Grow the method list array by one. - *list = (old_method_list **)realloc(*list, newSize); - - // Zero out addition part of new array - bzero (&((*list)[endIndex]), newSize - oldSize); - - // Place new end marker - (*list)[(newSize/sizeof(void *)) - 1] = END_OF_METHODS_LIST; - - // Insertion point corresponds to old array end - ptr = &((*list)[endIndex]); - } - - // Right shift existing entries by one - bcopy (*list, (*list) + 1, (uint8_t *)ptr - (uint8_t *)*list); - - // Insert at method list at beginning of array - **list = mlist; -} - -/*********************************************************************** -* _objc_removeMethods. -* Remove methods from a class. -* Does not take any locks. -* Does not flush any method caches. -* If the class is currently in use, use class_removeMethods() instead. -**********************************************************************/ -void _objc_removeMethods(Class cls, old_method_list *mlist) -{ - old_method_list ***list; - old_method_list **ptr; - - if (cls->methodLists == nil) { - // cls has no methods - return; - } - if (cls->methodLists == (old_method_list **)mlist) { - // mlist is the class's only method list - erase it - cls->methodLists = nil; - return; - } - if (cls->info & CLS_NO_METHOD_ARRAY) { - // cls has only one method list, and this isn't it - do nothing - return; - } - - // cls has a method list array - search it - - list = &cls->methodLists; - - // Locate list in the array - ptr = *list; - while (*ptr != mlist) { - // fix for radar # 2538790 - if ( *ptr == END_OF_METHODS_LIST ) return; - ptr += 1; - } - - // Remove this entry - *ptr = 0; - - // Left shift the following entries - while (*(++ptr) != END_OF_METHODS_LIST) - *(ptr-1) = *ptr; - *(ptr-1) = 0; -} - -/*********************************************************************** -* _objc_add_category. Install the specified category's methods and -* protocols into the class it augments. -* The class is assumed not to be in use yet: no locks are taken and -* no method caches are flushed. -**********************************************************************/ -static inline void _objc_add_category(Class cls, old_category *category, int version) -{ - if (PrintConnecting) { - _objc_inform("CONNECT: attaching category '%s (%s)'", cls->name, category->category_name); - } - - // Augment instance methods - if (category->instance_methods) - _objc_insertMethods (cls, category->instance_methods, category); - - // Augment class methods - if (category->class_methods) - _objc_insertMethods (cls->ISA(), category->class_methods, category); - - // Augment protocols - if ((version >= 5) && category->protocols) - { - if (cls->ISA()->version >= 5) - { - category->protocols->next = cls->protocols; - cls->protocols = category->protocols; - cls->ISA()->protocols = category->protocols; - } - else - { - _objc_inform ("unable to add protocols from category %s...\n", category->category_name); - _objc_inform ("class `%s' must be recompiled\n", category->class_name); - } - } - - // Augment properties - if (version >= 7 && category->instance_properties) { - if (cls->ISA()->version >= 6) { - _class_addProperties(cls, category->instance_properties); - } else { - _objc_inform ("unable to add properties from category %s...\n", category->category_name); - _objc_inform ("class `%s' must be recompiled\n", category->class_name); - } - } -} - -/*********************************************************************** -* _objc_add_category_flush_caches. Install the specified category's -* methods into the class it augments, and flush the class' method cache. -* Return YES if some method caches now need to be flushed. -**********************************************************************/ -static bool _objc_add_category_flush_caches(Class cls, old_category *category, int version) -{ - bool needFlush = NO; - - // Install the category's methods into its intended class - { - mutex_locker_t lock(methodListLock); - _objc_add_category (cls, category, version); - } - - // Queue for cache flushing so category's methods can get called - if (category->instance_methods) { - cls->setInfo(CLS_FLUSH_CACHE); - needFlush = YES; - } - if (category->class_methods) { - cls->ISA()->setInfo(CLS_FLUSH_CACHE); - needFlush = YES; - } - - return needFlush; -} - - -/*********************************************************************** -* reverse_cat -* Reverse the given linked list of pending categories. -* The pending category list is built backwards, and needs to be -* reversed before actually attaching the categories to a class. -* Returns the head of the new linked list. -**********************************************************************/ -static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat) -{ - _objc_unresolved_category *prev; - _objc_unresolved_category *cur; - _objc_unresolved_category *ahead; - - if (!cat) return nil; - - prev = nil; - cur = cat; - ahead = cat->next; - - while (cur) { - ahead = cur->next; - cur->next = prev; - prev = cur; - cur = ahead; - } - - return prev; -} - - -/*********************************************************************** -* resolve_categories_for_class. -* Install all existing categories intended for the specified class. -* cls must be a true class and not a metaclass. -**********************************************************************/ -static void resolve_categories_for_class(Class cls) -{ - _objc_unresolved_category * pending; - _objc_unresolved_category * next; - - // Nothing to do if there are no categories at all - if (!category_hash) return; - - // Locate and remove first element in category list - // associated with this class - pending = (_objc_unresolved_category *) - NXMapKeyFreeingRemove (category_hash, cls->name); - - // Traverse the list of categories, if any, registered for this class - - // The pending list is built backwards. Reverse it and walk forwards. - pending = reverse_cat(pending); - - while (pending) { - if (pending->cat) { - // Install the category - // use the non-flush-cache version since we are only - // called from the class intialization code - _objc_add_category(cls, pending->cat, (int)pending->version); - } - - // Delink and reclaim this registration - next = pending->next; - free(pending); - pending = next; - } -} - - -/*********************************************************************** -* _objc_resolve_categories_for_class. -* Public version of resolve_categories_for_class. This was -* exported pre-10.4 for Omni et al. to workaround a problem -* with too-lazy category attachment. -* cls should be a class, but this function can also cope with metaclasses. -**********************************************************************/ -void _objc_resolve_categories_for_class(Class cls) -{ - // If cls is a metaclass, get the class. - // resolve_categories_for_class() requires a real class to work correctly. - if (ISMETA(cls)) { - if (strncmp(cls->name, "_%", 2) == 0) { - // Posee's meta's name is smashed and isn't in the class_hash, - // so objc_getClass doesn't work. - const char *baseName = strchr(cls->name, '%'); // get posee's real name - cls = objc_getClass(baseName); - } else { - cls = objc_getClass(cls->name); - } - } - - resolve_categories_for_class(cls); -} - - -/*********************************************************************** -* _objc_register_category. -* Process a category read from an image. -* If the category's class exists, attach the category immediately. -* Classes that need cache flushing are marked but not flushed. -* If the category's class does not exist yet, pend the category for -* later attachment. Pending categories are attached in the order -* they were discovered. -* Returns YES if some method caches now need to be flushed. -**********************************************************************/ -static bool _objc_register_category(old_category *cat, int version) -{ - _objc_unresolved_category * new_cat; - _objc_unresolved_category * old; - Class theClass; - - // If the category's class exists, attach the category. - if ((theClass = objc_lookUpClass(cat->class_name))) { - return _objc_add_category_flush_caches(theClass, cat, version); - } - - // If the category's class exists but is unconnected, - // then attach the category to the class but don't bother - // flushing any method caches (because they must be empty). - // YES unconnected, NO class_handler - if ((theClass = look_up_class(cat->class_name, YES, NO))) { - _objc_add_category(theClass, cat, version); - return NO; - } - - - // Category's class does not exist yet. - // Save the category for later attachment. - - if (PrintConnecting) { - _objc_inform("CONNECT: pending category '%s (%s)'", cat->class_name, cat->category_name); - } - - // Create category lookup table if needed - if (!category_hash) - category_hash = NXCreateMapTable(NXStrValueMapPrototype, 128); - - // Locate an existing list of categories, if any, for the class. - old = (_objc_unresolved_category *) - NXMapGet (category_hash, cat->class_name); - - // Register the category to be fixed up later. - // The category list is built backwards, and is reversed again - // by resolve_categories_for_class(). - new_cat = (_objc_unresolved_category *) - malloc(sizeof(_objc_unresolved_category)); - new_cat->next = old; - new_cat->cat = cat; - new_cat->version = version; - (void) NXMapKeyCopyingInsert (category_hash, cat->class_name, new_cat); - - return NO; -} - - -const char ** -_objc_copyClassNamesForImage(header_info *hi, unsigned int *outCount) -{ - Module mods; - unsigned int m; - const char **list; - int count; - int allocated; - - list = nil; - count = 0; - allocated = 0; - - mods = hi->mod_ptr; - for (m = 0; m < hi->mod_count; m++) { - int d; - - if (!mods[m].symtab) continue; - - for (d = 0; d < mods[m].symtab->cls_def_cnt; d++) { - Class cls = (Class)mods[m].symtab->defs[d]; - // fixme what about future-ified classes? - if (cls->isConnected()) { - if (count == allocated) { - allocated = allocated*2 + 16; - list = (const char **) - realloc((void *)list, allocated * sizeof(char *)); - } - list[count++] = cls->name; - } - } - } - - if (count > 0) { - // nil-terminate non-empty list - if (count == allocated) { - allocated = allocated+1; - list = (const char **) - realloc((void *)list, allocated * sizeof(char *)); - } - list[count] = nil; - } - - if (outCount) *outCount = count; - return list; -} - -Class gdb_class_getClass(Class cls) -{ - const char *className = cls->name; - if(!className || !strlen(className)) return Nil; - Class rCls = look_up_class(className, NO, NO); - return rCls; - -} - -Class gdb_object_getClass(id obj) -{ - if (!obj) return nil; - return gdb_class_getClass(obj->getIsa()); -} - - -/*********************************************************************** -* Lock management -**********************************************************************/ -rwlock_t selLock; -mutex_t classLock; -mutex_t methodListLock; -mutex_t cacheUpdateLock; -recursive_mutex_t loadMethodLock; - -void lock_init(void) -{ -} - - -#endif diff --git a/objc/objc-runtime/runtime/objc-runtime.h b/objc/objc-runtime/runtime/objc-runtime.h deleted file mode 100644 index 4599f08..0000000 --- a/objc/objc-runtime/runtime/objc-runtime.h +++ /dev/null @@ -1,2 +0,0 @@ -#include <objc/runtime.h> -#include <objc/message.h> diff --git a/objc/objc-runtime/runtime/objc-runtime.mm b/objc/objc-runtime/runtime/objc-runtime.mm deleted file mode 100644 index b29f7e8..0000000 --- a/objc/objc-runtime/runtime/objc-runtime.mm +++ /dev/null @@ -1,670 +0,0 @@ -/* - * 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@ - */ -/*********************************************************************** -* objc-runtime.m -* Copyright 1988-1996, NeXT Software, Inc. -* Author: s. naroff -* -**********************************************************************/ - - - -/*********************************************************************** -* Imports. -**********************************************************************/ - -#include "objc-private.h" -#include "objc-loadmethod.h" -#include "message.h" - -OBJC_EXPORT Class getOriginalClassForPosingClass(Class); - - -/*********************************************************************** -* Exports. -**********************************************************************/ - -// Settings from environment variables -#define OPTION(var, env, help) bool var = false; -#include "objc-env.h" -#undef OPTION - -struct option_t { - bool* var; - const char *env; - const char *help; - size_t envlen; -}; - -const option_t Settings[] = { -#define OPTION(var, env, help) {&var, #env, help, strlen(#env)}, -#include "objc-env.h" -#undef OPTION -}; - - -// objc's key for pthread_getspecific -static tls_key_t _objc_pthread_key; - -// Selectors -SEL SEL_load = NULL; -SEL SEL_initialize = NULL; -SEL SEL_resolveInstanceMethod = NULL; -SEL SEL_resolveClassMethod = NULL; -SEL SEL_cxx_construct = NULL; -SEL SEL_cxx_destruct = NULL; -SEL SEL_retain = NULL; -SEL SEL_release = NULL; -SEL SEL_autorelease = NULL; -SEL SEL_retainCount = NULL; -SEL SEL_alloc = NULL; -SEL SEL_allocWithZone = NULL; -SEL SEL_dealloc = NULL; -SEL SEL_copy = NULL; -SEL SEL_new = NULL; -SEL SEL_finalize = NULL; -SEL SEL_forwardInvocation = NULL; -SEL SEL_tryRetain = NULL; -SEL SEL_isDeallocating = NULL; -SEL SEL_retainWeakReference = NULL; -SEL SEL_allowsWeakReference = NULL; - - -header_info *FirstHeader = 0; // NULL means empty list -header_info *LastHeader = 0; // NULL means invalid; recompute it -int HeaderCount = 0; - - -/*********************************************************************** -* objc_getClass. Return the id of the named class. If the class does -* not exist, call _objc_classLoader and then objc_classHandler, either of -* which may create a new class. -* Warning: doesn't work if aClassName is the name of a posed-for class's isa! -**********************************************************************/ -Class objc_getClass(const char *aClassName) -{ - if (!aClassName) return Nil; - - // NO unconnected, YES class handler - return look_up_class(aClassName, NO, YES); -} - - -/*********************************************************************** -* objc_getRequiredClass. -* Same as objc_getClass, but kills the process if the class is not found. -* This is used by ZeroLink, where failing to find a class would be a -* compile-time link error without ZeroLink. -**********************************************************************/ -Class objc_getRequiredClass(const char *aClassName) -{ - Class cls = objc_getClass(aClassName); - if (!cls) _objc_fatal("link error: class '%s' not found.", aClassName); - return cls; -} - - -/*********************************************************************** -* objc_lookUpClass. Return the id of the named class. -* If the class does not exist, call _objc_classLoader, which may create -* a new class. -* -* Formerly objc_getClassWithoutWarning () -**********************************************************************/ -Class objc_lookUpClass(const char *aClassName) -{ - if (!aClassName) return Nil; - - // NO unconnected, NO class handler - return look_up_class(aClassName, NO, NO); -} - - -/*********************************************************************** -* objc_getMetaClass. Return the id of the meta class the named class. -* Warning: doesn't work if aClassName is the name of a posed-for class's isa! -**********************************************************************/ -Class objc_getMetaClass(const char *aClassName) -{ - Class cls; - - if (!aClassName) return Nil; - - cls = objc_getClass (aClassName); - if (!cls) - { - _objc_inform ("class `%s' not linked into application", aClassName); - return Nil; - } - - return cls->ISA(); -} - - -/*********************************************************************** -* appendHeader. Add a newly-constructed header_info to the list. -**********************************************************************/ -void appendHeader(header_info *hi) -{ - // Add the header to the header list. - // The header is appended to the list, to preserve the bottom-up order. - HeaderCount++; - hi->next = NULL; - if (!FirstHeader) { - // list is empty - FirstHeader = LastHeader = hi; - } else { - if (!LastHeader) { - // list is not empty, but LastHeader is invalid - recompute it - LastHeader = FirstHeader; - while (LastHeader->next) LastHeader = LastHeader->next; - } - // LastHeader is now valid - LastHeader->next = hi; - LastHeader = hi; - } -} - - -/*********************************************************************** -* removeHeader -* Remove the given header from the header list. -* FirstHeader is updated. -* LastHeader is set to NULL. Any code that uses LastHeader must -* detect this NULL and recompute LastHeader by traversing the list. -**********************************************************************/ -void removeHeader(header_info *hi) -{ - header_info **hiP; - - for (hiP = &FirstHeader; *hiP != NULL; hiP = &(**hiP).next) { - if (*hiP == hi) { - header_info *deadHead = *hiP; - - // Remove from the linked list (updating FirstHeader if necessary). - *hiP = (**hiP).next; - - // Update LastHeader if necessary. - if (LastHeader == deadHead) { - LastHeader = NULL; // will be recomputed next time it's used - } - - HeaderCount--; - break; - } - } -} - - -/*********************************************************************** -* environ_init -* Read environment variables that affect the runtime. -* Also print environment variable help, if requested. -**********************************************************************/ -void environ_init(void) -{ - if (issetugid()) { - // All environment variables are silently ignored when setuid or setgid - // This includes OBJC_HELP and OBJC_PRINT_OPTIONS themselves. - return; - } - - bool PrintHelp = false; - bool PrintOptions = false; - bool maybeMallocDebugging = false; - - // Scan environ[] directly instead of calling getenv() a lot. - // This optimizes the case where none are set. - for (char **p = *_NSGetEnviron(); *p != nil; p++) { - if (0 == strncmp(*p, "Malloc", 6) || 0 == strncmp(*p, "DYLD", 4) || - 0 == strncmp(*p, "NSZombiesEnabled", 16)) - { - maybeMallocDebugging = true; - } - - if (0 != strncmp(*p, "OBJC_", 5)) continue; - - if (0 == strncmp(*p, "OBJC_HELP=", 10)) { - PrintHelp = true; - continue; - } - if (0 == strncmp(*p, "OBJC_PRINT_OPTIONS=", 19)) { - PrintOptions = true; - continue; - } - - const char *value = strchr(*p, '='); - if (!*value) continue; - value++; - - for (size_t i = 0; i < sizeof(Settings)/sizeof(Settings[0]); i++) { - const option_t *opt = &Settings[i]; - if ((size_t)(value - *p) == 1+opt->envlen && - 0 == strncmp(*p, opt->env, opt->envlen)) - { - *opt->var = (0 == strcmp(value, "YES")); - break; - } - } - } - - // Special case: enable some autorelease pool debugging - // when some malloc debugging is enabled - // and OBJC_DEBUG_POOL_ALLOCATION is not set to something other than NO. - if (maybeMallocDebugging) { - const char *insert = getenv("DYLD_INSERT_LIBRARIES"); - const char *zombie = getenv("NSZombiesEnabled"); - const char *pooldebug = getenv("OBJC_DEBUG_POOL_ALLOCATION"); - if ((getenv("MallocStackLogging") - || getenv("MallocStackLoggingNoCompact") - || (zombie && (*zombie == 'Y' || *zombie == 'y')) - || (insert && strstr(insert, "libgmalloc"))) - && - (!pooldebug || 0 == strcmp(pooldebug, "YES"))) - { - DebugPoolAllocation = true; - } - } - - // Print OBJC_HELP and OBJC_PRINT_OPTIONS output. - if (PrintHelp || PrintOptions) { - if (PrintHelp) { - _objc_inform("Objective-C runtime debugging. Set variable=YES to enable."); - _objc_inform("OBJC_HELP: describe available environment variables"); - if (PrintOptions) { - _objc_inform("OBJC_HELP is set"); - } - _objc_inform("OBJC_PRINT_OPTIONS: list which options are set"); - } - if (PrintOptions) { - _objc_inform("OBJC_PRINT_OPTIONS is set"); - } - - for (size_t i = 0; i < sizeof(Settings)/sizeof(Settings[0]); i++) { - const option_t *opt = &Settings[i]; - if (PrintHelp) _objc_inform("%s: %s", opt->env, opt->help); - if (PrintOptions && *opt->var) _objc_inform("%s is set", opt->env); - } - } -} - - -/*********************************************************************** -* logReplacedMethod -* OBJC_PRINT_REPLACED_METHODS implementation -**********************************************************************/ -void -logReplacedMethod(const char *className, SEL s, - bool isMeta, const char *catName, - IMP oldImp, IMP newImp) -{ - const char *oldImage = "??"; - const char *newImage = "??"; - - // Silently ignore +load replacement because category +load is special - if (s == SEL_load) return; - -#if TARGET_OS_WIN32 - // don't know dladdr()/dli_fname equivalent -#else - Dl_info dl; - - if (dladdr((void*)oldImp, &dl) && dl.dli_fname) oldImage = dl.dli_fname; - if (dladdr((void*)newImp, &dl) && dl.dli_fname) newImage = dl.dli_fname; -#endif - - _objc_inform("REPLACED: %c[%s %s] %s%s (IMP was %p (%s), now %p (%s))", - isMeta ? '+' : '-', className, sel_getName(s), - catName ? "by category " : "", catName ? catName : "", - oldImp, oldImage, newImp, newImage); -} - - - -/*********************************************************************** -* objc_setMultithreaded. -**********************************************************************/ -void objc_setMultithreaded (BOOL flag) -{ - OBJC_WARN_DEPRECATED; - - // Nothing here. Thread synchronization in the runtime is always active. -} - - -/*********************************************************************** -* _objc_fetch_pthread_data -* Fetch objc's pthread data for this thread. -* If the data doesn't exist yet and create is NO, return NULL. -* If the data doesn't exist yet and create is YES, allocate and return it. -**********************************************************************/ -_objc_pthread_data *_objc_fetch_pthread_data(bool create) -{ - _objc_pthread_data *data; - - data = (_objc_pthread_data *)tls_get(_objc_pthread_key); - if (!data && create) { - data = (_objc_pthread_data *) - calloc(1, sizeof(_objc_pthread_data)); - tls_set(_objc_pthread_key, data); - } - - return data; -} - - -/*********************************************************************** -* _objc_pthread_destroyspecific -* Destructor for objc's per-thread data. -* arg shouldn't be NULL, but we check anyway. -**********************************************************************/ -extern void _destroyInitializingClassList(struct _objc_initializing_classes *list); -void _objc_pthread_destroyspecific(void *arg) -{ - _objc_pthread_data *data = (_objc_pthread_data *)arg; - if (data != NULL) { - _destroyInitializingClassList(data->initializingClasses); - _destroySyncCache(data->syncCache); - _destroyAltHandlerList(data->handlerList); - for (int i = 0; i < (int)countof(data->printableNames); i++) { - if (data->printableNames[i]) { - free(data->printableNames[i]); - } - } - - // add further cleanup here... - - free(data); - } -} - - -void tls_init(void) -{ -#if SUPPORT_DIRECT_THREAD_KEYS - _objc_pthread_key = TLS_DIRECT_KEY; - pthread_key_init_np(TLS_DIRECT_KEY, &_objc_pthread_destroyspecific); -#else - _objc_pthread_key = tls_create(&_objc_pthread_destroyspecific); -#endif -} - - -/*********************************************************************** -* _objcInit -* Former library initializer. This function is now merely a placeholder -* for external callers. All runtime initialization has now been moved -* to map_images() and _objc_init. -**********************************************************************/ -void _objcInit(void) -{ - // do nothing -} - - -/*********************************************************************** -* objc_setForwardHandler -**********************************************************************/ - -#if !__OBJC2__ - -// Default forward handler (nil) goes to forward:: dispatch. -void *_objc_forward_handler = nil; -void *_objc_forward_stret_handler = nil; - -#else - -// Default forward handler halts the process. -__attribute__((noreturn)) void -objc_defaultForwardHandler(id self, SEL sel) -{ - _objc_fatal("%c[%s %s]: unrecognized selector sent to instance %p " - "(no message forward handler is installed)", - class_isMetaClass(object_getClass(self)) ? '+' : '-', - object_getClassName(self), sel_getName(sel), self); -} -void *_objc_forward_handler = (void*)objc_defaultForwardHandler; - -#if SUPPORT_STRET -struct stret { int i[100]; }; -__attribute__((noreturn)) struct stret -objc_defaultForwardStretHandler(id self, SEL sel) -{ - objc_defaultForwardHandler(self, sel); -} -void *_objc_forward_stret_handler = (void*)objc_defaultForwardStretHandler; -#endif - -#endif - -void objc_setForwardHandler(void *fwd, void *fwd_stret) -{ - _objc_forward_handler = fwd; -#if SUPPORT_STRET - _objc_forward_stret_handler = fwd_stret; -#endif -} - - -#if !__OBJC2__ -// GrP fixme -extern "C" Class _objc_getOrigClass(const char *name); -#endif -const char *class_getImageName(Class cls) -{ -#if TARGET_OS_WIN32 - TCHAR *szFileName; - DWORD charactersCopied; - Class origCls; - HMODULE classModule; - bool res; -#endif - if (!cls) return NULL; - -#if !__OBJC2__ - cls = _objc_getOrigClass(cls->demangledName()); -#endif -#if TARGET_OS_WIN32 - charactersCopied = 0; - szFileName = malloc(MAX_PATH * sizeof(TCHAR)); - - origCls = objc_getOrigClass(cls->demangledName()); - classModule = NULL; - res = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)origCls, &classModule); - if (res && classModule) { - charactersCopied = GetModuleFileName(classModule, szFileName, MAX_PATH * sizeof(TCHAR)); - } - if (classModule) FreeLibrary(classModule); - if (charactersCopied) { - return (const char *)szFileName; - } else { - free(szFileName); - } - return NULL; -#else - return dyld_image_path_containing_address(cls); -#endif -} - - -const char **objc_copyImageNames(unsigned int *outCount) -{ - header_info *hi; - int count = 0; - int max = HeaderCount; -#if TARGET_OS_WIN32 - const TCHAR **names = (const TCHAR **)calloc(max+1, sizeof(TCHAR *)); -#else - const char **names = (const char **)calloc(max+1, sizeof(char *)); -#endif - - for (hi = FirstHeader; hi != NULL && count < max; hi = hi->next) { -#if TARGET_OS_WIN32 - if (hi->moduleName) { - names[count++] = hi->moduleName; - } -#else - if (hi->fname) { - names[count++] = hi->fname; - } -#endif - } - names[count] = NULL; - - if (count == 0) { - // Return NULL instead of empty list if there are no images - free((void *)names); - names = NULL; - } - - if (outCount) *outCount = count; - return names; -} - - -/********************************************************************** -* -**********************************************************************/ -const char ** -objc_copyClassNamesForImage(const char *image, unsigned int *outCount) -{ - header_info *hi; - - if (!image) { - if (outCount) *outCount = 0; - return NULL; - } - - // Find the image. - for (hi = FirstHeader; hi != NULL; hi = hi->next) { -#if TARGET_OS_WIN32 - if (0 == wcscmp((TCHAR *)image, hi->moduleName)) break; -#else - if (0 == strcmp(image, hi->fname)) break; -#endif - } - - if (!hi) { - if (outCount) *outCount = 0; - return NULL; - } - - return _objc_copyClassNamesForImage(hi, outCount); -} - - -/********************************************************************** -* Fast Enumeration Support -**********************************************************************/ - -static void (*enumerationMutationHandler)(id); - -/********************************************************************** -* objc_enumerationMutation -* called by compiler when a mutation is detected during foreach iteration -**********************************************************************/ -void objc_enumerationMutation(id object) { - if (enumerationMutationHandler == nil) { - _objc_fatal("mutation detected during 'for(... in ...)' enumeration of object %p.", (void*)object); - } - (*enumerationMutationHandler)(object); -} - - -/********************************************************************** -* objc_setEnumerationMutationHandler -* an entry point to customize mutation error handing -**********************************************************************/ -void objc_setEnumerationMutationHandler(void (*handler)(id)) { - enumerationMutationHandler = handler; -} - - -/********************************************************************** -* Associative Reference Support -**********************************************************************/ - -id objc_getAssociatedObject_non_gc(id object, const void *key) { - return _object_get_associative_reference(object, (void *)key); -} - - -void objc_setAssociatedObject_non_gc(id object, const void *key, id value, objc_AssociationPolicy policy) { - _object_set_associative_reference(object, (void *)key, value, policy); -} - - -#if SUPPORT_GC - -id objc_getAssociatedObject_gc(id object, const void *key) { - // auto_zone doesn't handle tagged pointer objects. Track it ourselves. - if (object->isTaggedPointer()) return objc_getAssociatedObject_non_gc(object, key); - - return (id)auto_zone_get_associative_ref(gc_zone, object, (void *)key); -} - -void objc_setAssociatedObject_gc(id object, const void *key, id value, objc_AssociationPolicy policy) { - // auto_zone doesn't handle tagged pointer objects. Track it ourselves. - if (object->isTaggedPointer()) return objc_setAssociatedObject_non_gc(object, key, value, policy); - - if ((policy & OBJC_ASSOCIATION_COPY_NONATOMIC) == OBJC_ASSOCIATION_COPY_NONATOMIC) { - value = ((id(*)(id, SEL))objc_msgSend)(value, SEL_copy); - } - auto_zone_set_associative_ref(gc_zone, object, (void *)key, value); -} - -// objc_setAssociatedObject and objc_getAssociatedObject are -// resolver functions in objc-auto.mm. - -#else - -id -objc_getAssociatedObject(id object, const void *key) -{ - return objc_getAssociatedObject_non_gc(object, key); -} - -void -objc_setAssociatedObject(id object, const void *key, id value, - objc_AssociationPolicy policy) -{ - objc_setAssociatedObject_non_gc(object, key, value, policy); -} - -#endif - - -void objc_removeAssociatedObjects(id object) -{ -#if SUPPORT_GC - if (UseGC) { - auto_zone_erase_associative_refs(gc_zone, object); - } else -#endif - { - if (object && object->hasAssociatedObjects()) { - _object_remove_assocations(object); - } - } -} - diff --git a/objc/objc-runtime/runtime/objc-sel-old.mm b/objc/objc-runtime/runtime/objc-sel-old.mm deleted file mode 100644 index 6962475..0000000 --- a/objc/objc-runtime/runtime/objc-sel-old.mm +++ /dev/null @@ -1,232 +0,0 @@ -/* - * 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@ - */ - -/* - * Utilities for registering and looking up selectors. The sole - * purpose of the selector tables is a registry whereby there is - * exactly one address (selector) associated with a given string - * (method name). - */ - -#if !__OBJC2__ - -#include "objc-private.h" -#include "objc-sel-set.h" - -#if SUPPORT_PREOPT -#include <objc-shared-cache.h> -static const objc_selopt_t *builtins = NULL; -#endif - -__BEGIN_DECLS - -static size_t SelrefCount = 0; - -static const char *_objc_empty_selector = ""; -static struct __objc_sel_set *_objc_selectors = NULL; - - -static SEL _objc_search_builtins(const char *key) -{ -#if defined(DUMP_SELECTORS) - if (NULL != key) printf("\t\"%s\",\n", key); -#endif - - if (!key) return (SEL)0; -#if SUPPORT_IGNORED_SELECTOR_CONSTANT - if ((uintptr_t)key == kIgnore) return (SEL)kIgnore; - if (ignoreSelectorNamed(key)) return (SEL)kIgnore; -#endif - if ('\0' == *key) return (SEL)_objc_empty_selector; - -#if SUPPORT_PREOPT - if (builtins) return (SEL)builtins->get(key); -#endif - - return (SEL)0; -} - - -const char *sel_getName(SEL sel) { -#if SUPPORT_IGNORED_SELECTOR_CONSTANT - if ((uintptr_t)sel == kIgnore) return "<ignored selector>"; -#endif - return sel ? (const char *)sel : "<null selector>"; -} - - -BOOL sel_isMapped(SEL name) -{ - SEL sel; - - if (!name) return NO; -#if SUPPORT_IGNORED_SELECTOR_CONSTANT - if ((uintptr_t)name == kIgnore) return YES; -#endif - - sel = _objc_search_builtins((const char *)name); - if (sel) return YES; - - rwlock_reader_t lock(selLock); - if (_objc_selectors) { - sel = __objc_sel_set_get(_objc_selectors, name); - } - return bool(sel); -} - -static SEL __sel_registerName(const char *name, int lock, int copy) -{ - SEL result = 0; - - if (lock) selLock.assertUnlocked(); - else selLock.assertWriting(); - - if (!name) return (SEL)0; - result = _objc_search_builtins(name); - if (result) return result; - - if (lock) selLock.read(); - if (_objc_selectors) { - result = __objc_sel_set_get(_objc_selectors, (SEL)name); - } - if (lock) selLock.unlockRead(); - if (result) return result; - - // No match. Insert. - - if (lock) selLock.write(); - - if (!_objc_selectors) { - _objc_selectors = __objc_sel_set_create(SelrefCount); - } - if (lock) { - // Rescan in case it was added while we dropped the lock - result = __objc_sel_set_get(_objc_selectors, (SEL)name); - } - if (!result) { - result = (SEL)(copy ? strdup(name) : name); - __objc_sel_set_add(_objc_selectors, result); -#if defined(DUMP_UNKNOWN_SELECTORS) - printf("\t\"%s\",\n", name); -#endif - } - - if (lock) selLock.unlockWrite(); - return result; -} - - -SEL sel_registerName(const char *name) { - return __sel_registerName(name, 1, 1); // YES lock, YES copy -} - -SEL sel_registerNameNoLock(const char *name, bool copy) { - return __sel_registerName(name, 0, copy); // NO lock, maybe copy -} - -void sel_lock(void) -{ - selLock.write(); -} - -void sel_unlock(void) -{ - selLock.unlockWrite(); -} - - -// 2001/1/24 -// the majority of uses of this function (which used to return NULL if not found) -// did not check for NULL, so, in fact, never return NULL -// -SEL sel_getUid(const char *name) { - return __sel_registerName(name, 2, 1); // YES lock, YES copy -} - - -BOOL sel_isEqual(SEL lhs, SEL rhs) -{ - return bool(lhs == rhs); -} - - -/*********************************************************************** -* sel_init -* Initialize selector tables and register selectors used internally. -**********************************************************************/ -void sel_init(bool wantsGC, size_t selrefCount) -{ - // save this value for later - SelrefCount = selrefCount; - -#if SUPPORT_PREOPT - builtins = preoptimizedSelectors(); -#endif - - // Register selectors used by libobjc - - if (wantsGC) { - // Registering retain/release/autorelease requires GC decision first. - // sel_init doesn't actually need the wantsGC parameter, it just - // helps enforce the initialization order. - } - -#define s(x) SEL_##x = sel_registerNameNoLock(#x, NO) -#define t(x,y) SEL_##y = sel_registerNameNoLock(#x, NO) - - sel_lock(); - - s(load); - s(initialize); - t(resolveInstanceMethod:, resolveInstanceMethod); - t(resolveClassMethod:, resolveClassMethod); - t(.cxx_construct, cxx_construct); - t(.cxx_destruct, cxx_destruct); - s(retain); - s(release); - s(autorelease); - s(retainCount); - s(alloc); - t(allocWithZone:, allocWithZone); - s(dealloc); - s(copy); - s(new); - s(finalize); - t(forwardInvocation:, forwardInvocation); - t(_tryRetain, tryRetain); - t(_isDeallocating, isDeallocating); - s(retainWeakReference); - s(allowsWeakReference); - - extern SEL FwdSel; - FwdSel = sel_registerNameNoLock("forward::", NO); - - sel_unlock(); - -#undef s -#undef t -} - -__END_DECLS - -#endif diff --git a/objc/objc-runtime/runtime/objc-sel-set.h b/objc/objc-runtime/runtime/objc-sel-set.h deleted file mode 100644 index f4540db..0000000 --- a/objc/objc-runtime/runtime/objc-sel-set.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2004 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@ - */ - -/* - * objc-sel-set.h - * A set of SELs used for SEL uniquing. - */ - -#ifndef _OBJC_SEL_SET_H_ -#define _OBJC_SEL_SET_H_ - -#if !__OBJC2__ - -#include <stdint.h> -#include "objc-os.h" - -__BEGIN_DECLS - -struct __objc_sel_set; - -extern struct __objc_sel_set *__objc_sel_set_create(size_t selrefCount); -extern SEL __objc_sel_set_get(struct __objc_sel_set *sset, SEL candidate); -extern void __objc_sel_set_add(struct __objc_sel_set *sset, SEL value); - -__END_DECLS - -#endif - -#endif diff --git a/objc/objc-runtime/runtime/objc-sel-set.mm b/objc/objc-runtime/runtime/objc-sel-set.mm deleted file mode 100644 index 79ca591..0000000 --- a/objc/objc-runtime/runtime/objc-sel-set.mm +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 1999-2004,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@ - */ - -/* - * objc-sel-set.h - * A cut-down copy of CFSet used for SEL uniquing. - */ - - -// NOTE: even on a 64-bit system, the implementation is still limited -// to 32-bit integers (like, the count), but SEL can be any size. - -#include <stdint.h> -#include "objc-private.h" -#include "objc-sel-set.h" - -#if !__OBJC2__ - - -#if !SUPPORT_MOD -// mod-free power of 2 version - -#define CONSTRAIN(val, range) ((val) & ((range)-1)) -#define SIZE 27 - -static const uint32_t __objc_sel_set_capacities[SIZE+1] = { - 3, 6, 12, 24, 48, 96, 192, 384, 768, 1536, 3072, 6144, 12288, 24576, - 49152, 98304, 196608, 393216, 786432, 1572864, 3145728, 6291456, - 12582912, 25165824, 50331648, 100663296, 201326592, UINT32_MAX -}; - -static const uint32_t __objc_sel_set_buckets[SIZE] = { // powers of 2 - 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, - 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, - 16777216, 33554432, 67108864, 134217728, 268435456 -}; - -#else -// prime version - -#define CONSTRAIN(val, range) ((val) % (range)) -#define SIZE 42 - -static const uint32_t __objc_sel_set_capacities[SIZE+1] = { - 4, 8, 17, 29, 47, 76, 123, 199, 322, 521, 843, 1364, 2207, 3571, - 5778, 9349, 15127, 24476, 39603, 64079, 103682, 167761, 271443, - 439204, 710647, 1149851, 1860498, 3010349, 4870847, 7881196, 12752043, - 20633239, 33385282, 54018521, 87403803, 141422324, 228826127, 370248451, - 599074578, 969323029, 1568397607, 2537720636U, UINT32_MAX -}; - -static const uint32_t __objc_sel_set_buckets[SIZE] = { // primes - 5, 11, 23, 41, 67, 113, 199, 317, 521, 839, 1361, 2207, 3571, 5779, - 9349, 15121, 24473, 39607, 64081, 103681, 167759, 271429, 439199, - 710641, 1149857, 1860503, 3010349, 4870843, 7881193, 12752029, 20633237, - 33385273, 54018521, 87403763, 141422317, 228826121, 370248451, 599074561, - 969323023, 1568397599, 2537720629U, 4106118251U -}; - -#endif - -struct __objc_sel_set { - uint32_t _count; /* number of slots used */ - uint32_t _capacity; /* maximum number of used slots */ - uint32_t _bucketsNum; /* number of slots */ - SEL *_buckets; /* can be NULL if not allocated yet */ -}; - -struct __objc_sel_set_finds { - SEL match; - uint32_t nomatch; -}; - -// candidate may not be 0; match is 0 if not present -static struct __objc_sel_set_finds __objc_sel_set_findBuckets(struct __objc_sel_set *sset, SEL candidate) { - struct __objc_sel_set_finds ret = {0, 0xffffffff}; - uint32_t probe = CONSTRAIN((uint32_t)_objc_strhash((const char *)candidate), sset->_bucketsNum); - for (;;) { - SEL currentSel = sset->_buckets[probe]; - if (!currentSel) { - ret.nomatch = probe; - return ret; - } else if (!ret.match && 0 == strcmp((const char *)currentSel, (const char *)candidate)) { - ret.match = currentSel; - } - probe++; - if (sset->_bucketsNum <= probe) { - probe -= sset->_bucketsNum; - } - } -} - -// create a set with given starting capacity, will resize as needed -struct __objc_sel_set *__objc_sel_set_create(size_t selrefs) { - uint32_t idx; - - struct __objc_sel_set *sset = (struct __objc_sel_set *) - malloc(sizeof(struct __objc_sel_set)); - if (!sset) _objc_fatal("objc_sel_set failure"); - sset->_count = 0; - - // heuristic to convert executable's selrefs count to table size -#if TARGET_OS_IPHONE - for (idx = 0; __objc_sel_set_capacities[idx] < selrefs; idx++); - if (idx > 0 && selrefs < 1536) idx--; -#else - if (selrefs < 1024) selrefs = 1024; - for (idx = 0; __objc_sel_set_capacities[idx] < selrefs; idx++); - idx++; -#endif - - if (SIZE <= idx) _objc_fatal("objc_sel_set failure"); - sset->_capacity = __objc_sel_set_capacities[idx]; - sset->_bucketsNum = __objc_sel_set_buckets[idx]; - sset->_buckets = (SEL *)calloc(sset->_bucketsNum, sizeof(SEL)); - if (!sset->_buckets) _objc_fatal("objc_sel_set failure"); - return sset; -} - -// returns 0 on failure; candidate may not be 0 -SEL __objc_sel_set_get(struct __objc_sel_set *sset, SEL candidate) { - return __objc_sel_set_findBuckets(sset, candidate).match; -} - -// value may not be 0; should not be called unless it is known the value is not in the set -void __objc_sel_set_add(struct __objc_sel_set *sset, SEL value) { - if (sset->_count == sset->_capacity) { - SEL *oldbuckets = sset->_buckets; - uint32_t oldnbuckets = sset->_bucketsNum; - uint32_t idx, capacity = sset->_count + 1; - for (idx = 0; __objc_sel_set_capacities[idx] < capacity; idx++); - if (SIZE <= idx) _objc_fatal("objc_sel_set failure"); - sset->_capacity = __objc_sel_set_capacities[idx]; - sset->_bucketsNum = __objc_sel_set_buckets[idx]; - sset->_buckets = (SEL *) - calloc(sset->_bucketsNum, sizeof(SEL)); - if (!sset->_buckets) _objc_fatal("objc_sel_set failure"); - for (idx = 0; idx < oldnbuckets; idx++) { - SEL currentSel = oldbuckets[idx]; - if (currentSel) { - uint32_t nomatch = __objc_sel_set_findBuckets(sset, currentSel).nomatch; - sset->_buckets[nomatch] = currentSel; - } - } - free(oldbuckets); - } - { - uint32_t nomatch = __objc_sel_set_findBuckets(sset, value).nomatch; - sset->_buckets[nomatch] = value; - sset->_count++; - } -} - - -// !__OBJC2__ -#endif diff --git a/objc/objc-runtime/runtime/objc-sel-table.s b/objc/objc-runtime/runtime/objc-sel-table.s deleted file mode 100644 index 04e3cee..0000000 --- a/objc/objc-runtime/runtime/objc-sel-table.s +++ /dev/null @@ -1,64 +0,0 @@ -#include <TargetConditionals.h> -#include <mach/vm_param.h> - -#if __LP64__ -# define PTR(x) .quad x -#else -# define PTR(x) .long x -#endif - -.section __TEXT,__objc_opt_ro -.align 3 -.private_extern __objc_opt_data -__objc_opt_data: -.long 13 /* table.version */ -.long 0 /* table.selopt_offset */ -.long 0 /* table.headeropt_offset */ -.long 0 /* table.clsopt_offset */ -.space PAGE_MAX_SIZE-16 - -/* space for selopt, smax/capacity=262144, blen/mask=262143+1 */ -.space 262144 /* mask tab */ -.space 524288 /* checkbytes */ -.space 524288*4 /* offsets */ - -/* space for clsopt, smax/capacity=32768, blen/mask=16383+1 */ -.space 16384 /* mask tab */ -.space 32768 /* checkbytes */ -.space 32768*12 /* offsets to name and class and header_info */ -.space PAGE_MAX_SIZE /* some duplicate classes */ - -/* space for protocolopt, smax/capacity=8192, blen/mask=4095+1 */ -.space 4096 /* mask tab */ -.space 8192 /* checkbytes */ -.space 8192*4 /* offsets */ - - -.section __DATA,__objc_opt_rw -.align 3 -.private_extern __objc_opt_rw_data -__objc_opt_rw_data: -/* space for header_info structures */ -.space 32768 - -/* space for 8192 protocols */ -#if __LP64__ -.space 8192 * 11 * 8 -#else -.space 8192 * 11 * 4 -#endif - - -/* section of pointers that the shared cache optimizer wants to know about */ -.section __DATA,__objc_opt_ptrs -.align 3 - -#if TARGET_OS_MAC && !TARGET_OS_IPHONE && __i386__ -// old ABI -.globl .objc_class_name_Protocol -PTR(.objc_class_name_Protocol) -#else -// new ABI -.globl _OBJC_CLASS_$_Protocol -PTR(_OBJC_CLASS_$_Protocol) -#endif diff --git a/objc/objc-runtime/runtime/objc-sel.mm b/objc/objc-runtime/runtime/objc-sel.mm deleted file mode 100644 index fe87f31..0000000 --- a/objc/objc-runtime/runtime/objc-sel.mm +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) 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@ - */ - -#if __OBJC2__ - -#include "objc-private.h" -#include "objc-cache.h" - -#if SUPPORT_PREOPT -static const objc_selopt_t *builtins = NULL; -#endif - -#if SUPPORT_IGNORED_SELECTOR_CONSTANT -#error sorry -#endif - - -static size_t SelrefCount = 0; - -static NXMapTable *namedSelectors; - -static SEL search_builtins(const char *key); - - -/*********************************************************************** -* sel_init -* Initialize selector tables and register selectors used internally. -**********************************************************************/ -void sel_init(bool wantsGC, size_t selrefCount) -{ - // save this value for later - SelrefCount = selrefCount; - -#if SUPPORT_PREOPT - builtins = preoptimizedSelectors(); - - if (PrintPreopt && builtins) { - uint32_t occupied = builtins->occupied; - uint32_t capacity = builtins->capacity; - - _objc_inform("PREOPTIMIZATION: using selopt at %p", builtins); - _objc_inform("PREOPTIMIZATION: %u selectors", occupied); - _objc_inform("PREOPTIMIZATION: %u/%u (%u%%) hash table occupancy", - occupied, capacity, - (unsigned)(occupied/(double)capacity*100)); - } -#endif - - // Register selectors used by libobjc - - if (wantsGC) { - // Registering retain/release/autorelease requires GC decision first. - // sel_init doesn't actually need the wantsGC parameter, it just - // helps enforce the initialization order. - } - -#define s(x) SEL_##x = sel_registerNameNoLock(#x, NO) -#define t(x,y) SEL_##y = sel_registerNameNoLock(#x, NO) - - sel_lock(); - - s(load); - s(initialize); - t(resolveInstanceMethod:, resolveInstanceMethod); - t(resolveClassMethod:, resolveClassMethod); - t(.cxx_construct, cxx_construct); - t(.cxx_destruct, cxx_destruct); - s(retain); - s(release); - s(autorelease); - s(retainCount); - s(alloc); - t(allocWithZone:, allocWithZone); - s(dealloc); - s(copy); - s(new); - s(finalize); - t(forwardInvocation:, forwardInvocation); - t(_tryRetain, tryRetain); - t(_isDeallocating, isDeallocating); - s(retainWeakReference); - s(allowsWeakReference); - - sel_unlock(); - -#undef s -#undef t -} - - -static SEL sel_alloc(const char *name, bool copy) -{ - selLock.assertWriting(); - return (SEL)(copy ? strdup(name) : name); -} - - -const char *sel_getName(SEL sel) -{ - if (!sel) return "<null selector>"; - return (const char *)(const void*)sel; -} - - -BOOL sel_isMapped(SEL sel) -{ - if (!sel) return NO; - - const char *name = (const char *)(void *)sel; - - if (sel == search_builtins(name)) return YES; - - rwlock_reader_t lock(selLock); - if (namedSelectors) { - return (sel == (SEL)NXMapGet(namedSelectors, name)); - } - return false; -} - - -static SEL search_builtins(const char *name) -{ -#if SUPPORT_PREOPT - if (builtins) return (SEL)builtins->get(name); -#endif - return nil; -} - - -static SEL __sel_registerName(const char *name, int lock, int copy) -{ - SEL result = 0; - - if (lock) selLock.assertUnlocked(); - else selLock.assertWriting(); - - if (!name) return (SEL)0; - - result = search_builtins(name); - if (result) return result; - - if (lock) selLock.read(); - if (namedSelectors) { - result = (SEL)NXMapGet(namedSelectors, name); - } - if (lock) selLock.unlockRead(); - if (result) return result; - - // No match. Insert. - - if (lock) selLock.write(); - - if (!namedSelectors) { - namedSelectors = NXCreateMapTable(NXStrValueMapPrototype, - (unsigned)SelrefCount); - } - if (lock) { - // Rescan in case it was added while we dropped the lock - result = (SEL)NXMapGet(namedSelectors, name); - } - if (!result) { - result = sel_alloc(name, copy); - // fixme choose a better container (hash not map for starters) - NXMapInsert(namedSelectors, sel_getName(result), result); - } - - if (lock) selLock.unlockWrite(); - return result; -} - - -SEL sel_registerName(const char *name) { - return __sel_registerName(name, 1, 1); // YES lock, YES copy -} - -SEL sel_registerNameNoLock(const char *name, bool copy) { - return __sel_registerName(name, 0, copy); // NO lock, maybe copy -} - -void sel_lock(void) -{ - selLock.write(); -} - -void sel_unlock(void) -{ - selLock.unlockWrite(); -} - - -// 2001/1/24 -// the majority of uses of this function (which used to return NULL if not found) -// did not check for NULL, so, in fact, never return NULL -// -SEL sel_getUid(const char *name) { - return __sel_registerName(name, 2, 1); // YES lock, YES copy -} - - -BOOL sel_isEqual(SEL lhs, SEL rhs) -{ - return bool(lhs == rhs); -} - - -#endif diff --git a/objc/objc-runtime/runtime/objc-sync.h b/objc/objc-runtime/runtime/objc-sync.h deleted file mode 100644 index 77ecf01..0000000 --- a/objc/objc-runtime/runtime/objc-sync.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2002, 2006 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 __OBJC_SNYC_H_ -#define __OBJC_SNYC_H_ - -#include <objc/objc.h> - - -/** - * Begin synchronizing on 'obj'. - * Allocates recursive pthread_mutex associated with 'obj' if needed. - * - * @param obj The object to begin synchronizing on. - * - * @return OBJC_SYNC_SUCCESS once lock is acquired. - */ -OBJC_EXPORT int objc_sync_enter(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_2_0); - -/** - * End synchronizing on 'obj'. - * - * @param obj The objet to end synchronizing on. - * - * @return OBJC_SYNC_SUCCESS or OBJC_SYNC_NOT_OWNING_THREAD_ERROR - */ -OBJC_EXPORT int objc_sync_exit(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_2_0); - -// The wait/notify functions have never worked correctly and no longer exist. -OBJC_EXPORT int objc_sync_wait(id obj, long long milliSecondsMaxWait) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT int objc_sync_notify(id obj) - UNAVAILABLE_ATTRIBUTE; -OBJC_EXPORT int objc_sync_notifyAll(id obj) - UNAVAILABLE_ATTRIBUTE; - -enum { - OBJC_SYNC_SUCCESS = 0, - OBJC_SYNC_NOT_OWNING_THREAD_ERROR = -1, - OBJC_SYNC_TIMED_OUT = -2, - OBJC_SYNC_NOT_INITIALIZED = -3 -}; - - -#endif // __OBJC_SNYC_H_ diff --git a/objc/objc-runtime/runtime/objc-sync.mm b/objc/objc-runtime/runtime/objc-sync.mm deleted file mode 100644 index cb69981..0000000 --- a/objc/objc-runtime/runtime/objc-sync.mm +++ /dev/null @@ -1,327 +0,0 @@ -/* - * 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@ - */ - -#include "objc-private.h" -#include "objc-sync.h" - -// -// Allocate a lock only when needed. Since few locks are needed at any point -// in time, keep them on a single list. -// - - -typedef struct SyncData { - struct SyncData* nextData; - DisguisedPtr<objc_object> object; - int32_t threadCount; // number of THREADS using this block - recursive_mutex_t mutex; -} SyncData; - -typedef struct { - SyncData *data; - unsigned int lockCount; // number of times THIS THREAD locked this block -} SyncCacheItem; - -typedef struct SyncCache { - unsigned int allocated; - unsigned int used; - SyncCacheItem list[0]; -} SyncCache; - -/* - Fast cache: two fixed pthread keys store a single SyncCacheItem. - This avoids malloc of the SyncCache for threads that only synchronize - a single object at a time. - SYNC_DATA_DIRECT_KEY == SyncCacheItem.data - SYNC_COUNT_DIRECT_KEY == SyncCacheItem.lockCount - */ - -struct SyncList { - SyncData *data; - spinlock_t lock; - - SyncList() : data(nil) { } -}; - -// Use multiple parallel lists to decrease contention among unrelated objects. -#define LOCK_FOR_OBJ(obj) sDataLists[obj].lock -#define LIST_FOR_OBJ(obj) sDataLists[obj].data -static StripedMap<SyncList> sDataLists; - - -enum usage { ACQUIRE, RELEASE, CHECK }; - -static SyncCache *fetch_cache(bool create) -{ - _objc_pthread_data *data; - - data = _objc_fetch_pthread_data(create); - if (!data) return NULL; - - if (!data->syncCache) { - if (!create) { - return NULL; - } else { - int count = 4; - data->syncCache = (SyncCache *) - calloc(1, sizeof(SyncCache) + count*sizeof(SyncCacheItem)); - data->syncCache->allocated = count; - } - } - - // Make sure there's at least one open slot in the list. - if (data->syncCache->allocated == data->syncCache->used) { - data->syncCache->allocated *= 2; - data->syncCache = (SyncCache *) - realloc(data->syncCache, sizeof(SyncCache) - + data->syncCache->allocated * sizeof(SyncCacheItem)); - } - - return data->syncCache; -} - - -void _destroySyncCache(struct SyncCache *cache) -{ - if (cache) free(cache); -} - - -static SyncData* id2data(id object, enum usage why) -{ - spinlock_t *lockp = &LOCK_FOR_OBJ(object); - SyncData **listp = &LIST_FOR_OBJ(object); - SyncData* result = NULL; - -#if SUPPORT_DIRECT_THREAD_KEYS - // Check per-thread single-entry fast cache for matching object - bool fastCacheOccupied = NO; - SyncData *data = (SyncData *)tls_get_direct(SYNC_DATA_DIRECT_KEY); - if (data) { - fastCacheOccupied = YES; - - if (data->object == object) { - // Found a match in fast cache. - uintptr_t lockCount; - - result = data; - lockCount = (uintptr_t)tls_get_direct(SYNC_COUNT_DIRECT_KEY); - if (result->threadCount <= 0 || lockCount <= 0) { - _objc_fatal("id2data fastcache is buggy"); - } - - switch(why) { - case ACQUIRE: { - lockCount++; - tls_set_direct(SYNC_COUNT_DIRECT_KEY, (void*)lockCount); - break; - } - case RELEASE: - lockCount--; - tls_set_direct(SYNC_COUNT_DIRECT_KEY, (void*)lockCount); - if (lockCount == 0) { - // remove from fast cache - tls_set_direct(SYNC_DATA_DIRECT_KEY, NULL); - // atomic because may collide with concurrent ACQUIRE - OSAtomicDecrement32Barrier(&result->threadCount); - } - break; - case CHECK: - // do nothing - break; - } - - return result; - } - } -#endif - - // Check per-thread cache of already-owned locks for matching object - SyncCache *cache = fetch_cache(NO); - if (cache) { - unsigned int i; - for (i = 0; i < cache->used; i++) { - SyncCacheItem *item = &cache->list[i]; - if (item->data->object != object) continue; - - // Found a match. - result = item->data; - if (result->threadCount <= 0 || item->lockCount <= 0) { - _objc_fatal("id2data cache is buggy"); - } - - switch(why) { - case ACQUIRE: - item->lockCount++; - break; - case RELEASE: - item->lockCount--; - if (item->lockCount == 0) { - // remove from per-thread cache - cache->list[i] = cache->list[--cache->used]; - // atomic because may collide with concurrent ACQUIRE - OSAtomicDecrement32Barrier(&result->threadCount); - } - break; - case CHECK: - // do nothing - break; - } - - return result; - } - } - - // Thread cache didn't find anything. - // Walk in-use list looking for matching object - // Spinlock prevents multiple threads from creating multiple - // locks for the same new object. - // We could keep the nodes in some hash table if we find that there are - // more than 20 or so distinct locks active, but we don't do that now. - - lockp->lock(); - - { - SyncData* p; - SyncData* firstUnused = NULL; - for (p = *listp; p != NULL; p = p->nextData) { - if ( p->object == object ) { - result = p; - // atomic because may collide with concurrent RELEASE - OSAtomicIncrement32Barrier(&result->threadCount); - goto done; - } - if ( (firstUnused == NULL) && (p->threadCount == 0) ) - firstUnused = p; - } - - // no SyncData currently associated with object - if ( (why == RELEASE) || (why == CHECK) ) - goto done; - - // an unused one was found, use it - if ( firstUnused != NULL ) { - result = firstUnused; - result->object = (objc_object *)object; - result->threadCount = 1; - goto done; - } - } - - // malloc a new SyncData and add to list. - // XXX calling malloc with a global lock held is bad practice, - // might be worth releasing the lock, mallocing, and searching again. - // But since we never free these guys we won't be stuck in malloc very often. - result = (SyncData*)calloc(sizeof(SyncData), 1); - result->object = (objc_object *)object; - result->threadCount = 1; - new (&result->mutex) recursive_mutex_t(); - result->nextData = *listp; - *listp = result; - - done: - lockp->unlock(); - if (result) { - // Only new ACQUIRE should get here. - // All RELEASE and CHECK and recursive ACQUIRE are - // handled by the per-thread caches above. - if (why == RELEASE) { - // Probably some thread is incorrectly exiting - // while the object is held by another thread. - return nil; - } - if (why != ACQUIRE) _objc_fatal("id2data is buggy"); - if (result->object != object) _objc_fatal("id2data is buggy"); - -#if SUPPORT_DIRECT_THREAD_KEYS - if (!fastCacheOccupied) { - // Save in fast thread cache - tls_set_direct(SYNC_DATA_DIRECT_KEY, result); - tls_set_direct(SYNC_COUNT_DIRECT_KEY, (void*)1); - } else -#endif - { - // Save in thread cache - if (!cache) cache = fetch_cache(YES); - cache->list[cache->used].data = result; - cache->list[cache->used].lockCount = 1; - cache->used++; - } - } - - return result; -} - - -BREAKPOINT_FUNCTION( - void objc_sync_nil(void) -); - - -// Begin synchronizing on 'obj'. -// Allocates recursive mutex associated with 'obj' if needed. -// Returns OBJC_SYNC_SUCCESS once lock is acquired. -int objc_sync_enter(id obj) -{ - int result = OBJC_SYNC_SUCCESS; - - if (obj) { - SyncData* data = id2data(obj, ACQUIRE); - assert(data); - data->mutex.lock(); - } else { - // @synchronized(nil) does nothing - if (DebugNilSync) { - _objc_inform("NIL SYNC DEBUG: @synchronized(nil); set a breakpoint on objc_sync_nil to debug"); - } - objc_sync_nil(); - } - - return result; -} - - -// End synchronizing on 'obj'. -// Returns OBJC_SYNC_SUCCESS or OBJC_SYNC_NOT_OWNING_THREAD_ERROR -int objc_sync_exit(id obj) -{ - int result = OBJC_SYNC_SUCCESS; - - if (obj) { - SyncData* data = id2data(obj, RELEASE); - if (!data) { - result = OBJC_SYNC_NOT_OWNING_THREAD_ERROR; - } else { - bool okay = data->mutex.tryUnlock(); - if (!okay) { - result = OBJC_SYNC_NOT_OWNING_THREAD_ERROR; - } - } - } else { - // @synchronized(nil) does nothing - } - - - return result; -} - diff --git a/objc/objc-runtime/runtime/objc-typeencoding.mm b/objc/objc-runtime/runtime/objc-typeencoding.mm deleted file mode 100644 index 14edccb..0000000 --- a/objc/objc-runtime/runtime/objc-typeencoding.mm +++ /dev/null @@ -1,365 +0,0 @@ -/* - * 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@ - */ - -/*********************************************************************** -* objc-typeencoding.m -* Parsing of old-style type strings. -**********************************************************************/ - -#include "objc-private.h" - -/*********************************************************************** -* SubtypeUntil. -* -* Delegation. -**********************************************************************/ -static int SubtypeUntil (const char * type, - char end) -{ - int level = 0; - const char * head = type; - - // - while (*type) - { - if (!*type || (!level && (*type == end))) - return (int)(type - head); - - switch (*type) - { - case ']': case '}': case ')': level--; break; - case '[': case '{': case '(': level += 1; break; - } - - type += 1; - } - - _objc_fatal ("Object: SubtypeUntil: end of type encountered prematurely\n"); - return 0; -} - - -/*********************************************************************** -* SkipFirstType. -**********************************************************************/ -static const char * SkipFirstType (const char * type) -{ - while (1) - { - switch (*type++) - { - case 'O': /* bycopy */ - case 'n': /* in */ - case 'o': /* out */ - case 'N': /* inout */ - case 'r': /* const */ - case 'V': /* oneway */ - case '^': /* pointers */ - break; - - case '@': /* objects */ - if (type[0] == '?') type++; /* Blocks */ - return type; - - /* arrays */ - case '[': - while ((*type >= '0') && (*type <= '9')) - type += 1; - return type + SubtypeUntil (type, ']') + 1; - - /* structures */ - case '{': - return type + SubtypeUntil (type, '}') + 1; - - /* unions */ - case '(': - return type + SubtypeUntil (type, ')') + 1; - - /* basic types */ - default: - return type; - } - } -} - - -/*********************************************************************** -* encoding_getNumberOfArguments. -**********************************************************************/ -unsigned int -encoding_getNumberOfArguments(const char *typedesc) -{ - unsigned nargs; - - // First, skip the return type - typedesc = SkipFirstType (typedesc); - - // Next, skip stack size - while ((*typedesc >= '0') && (*typedesc <= '9')) - typedesc += 1; - - // Now, we have the arguments - count how many - nargs = 0; - while (*typedesc) - { - // Traverse argument type - typedesc = SkipFirstType (typedesc); - - // Skip GNU runtime's register parameter hint - if (*typedesc == '+') typedesc++; - - // Traverse (possibly negative) argument offset - if (*typedesc == '-') - typedesc += 1; - while ((*typedesc >= '0') && (*typedesc <= '9')) - typedesc += 1; - - // Made it past an argument - nargs += 1; - } - - return nargs; -} - -/*********************************************************************** -* encoding_getSizeOfArguments. -**********************************************************************/ -unsigned -encoding_getSizeOfArguments(const char *typedesc) -{ - unsigned stack_size; - - // Get our starting points - stack_size = 0; - - // Skip the return type - typedesc = SkipFirstType (typedesc); - - // Convert ASCII number string to integer - while ((*typedesc >= '0') && (*typedesc <= '9')) - stack_size = (stack_size * 10) + (*typedesc++ - '0'); - - return stack_size; -} - - -/*********************************************************************** -* encoding_getArgumentInfo. -**********************************************************************/ -unsigned int -encoding_getArgumentInfo(const char *typedesc, unsigned int arg, - const char **type, int *offset) -{ - unsigned nargs = 0; - int self_offset = 0; - bool offset_is_negative = NO; - - // First, skip the return type - typedesc = SkipFirstType (typedesc); - - // Next, skip stack size - while ((*typedesc >= '0') && (*typedesc <= '9')) - typedesc += 1; - - // Now, we have the arguments - position typedesc to the appropriate argument - while (*typedesc && nargs != arg) - { - - // Skip argument type - typedesc = SkipFirstType (typedesc); - - if (nargs == 0) - { - // Skip GNU runtime's register parameter hint - if (*typedesc == '+') typedesc++; - - // Skip negative sign in offset - if (*typedesc == '-') - { - offset_is_negative = YES; - typedesc += 1; - } - else - offset_is_negative = NO; - - while ((*typedesc >= '0') && (*typedesc <= '9')) - self_offset = self_offset * 10 + (*typedesc++ - '0'); - if (offset_is_negative) - self_offset = -(self_offset); - - } - - else - { - // Skip GNU runtime's register parameter hint - if (*typedesc == '+') typedesc++; - - // Skip (possibly negative) argument offset - if (*typedesc == '-') - typedesc += 1; - while ((*typedesc >= '0') && (*typedesc <= '9')) - typedesc += 1; - } - - nargs += 1; - } - - if (*typedesc) - { - int arg_offset = 0; - - *type = typedesc; - typedesc = SkipFirstType (typedesc); - - if (arg == 0) - { - *offset = 0; - } - - else - { - // Skip GNU register parameter hint - if (*typedesc == '+') typedesc++; - - // Pick up (possibly negative) argument offset - if (*typedesc == '-') - { - offset_is_negative = YES; - typedesc += 1; - } - else - offset_is_negative = NO; - - while ((*typedesc >= '0') && (*typedesc <= '9')) - arg_offset = arg_offset * 10 + (*typedesc++ - '0'); - if (offset_is_negative) - arg_offset = - arg_offset; - - *offset = arg_offset - self_offset; - } - - } - - else - { - *type = 0; - *offset = 0; - } - - return nargs; -} - - -void -encoding_getReturnType(const char *t, char *dst, size_t dst_len) -{ - size_t len; - const char *end; - - if (!dst) return; - if (!t) { - strncpy(dst, "", dst_len); - return; - } - - end = SkipFirstType(t); - len = end - t; - strncpy(dst, t, MIN(len, dst_len)); - if (len < dst_len) memset(dst+len, 0, dst_len - len); -} - -/*********************************************************************** -* encoding_copyReturnType. Returns the method's return type string -* on the heap. -**********************************************************************/ -char * -encoding_copyReturnType(const char *t) -{ - size_t len; - const char *end; - char *result; - - if (!t) return NULL; - - end = SkipFirstType(t); - len = end - t; - result = (char *)malloc(len + 1); - strncpy(result, t, len); - result[len] = '\0'; - return result; -} - - -void -encoding_getArgumentType(const char *t, unsigned int index, - char *dst, size_t dst_len) -{ - size_t len; - const char *end; - int offset; - - if (!dst) return; - if (!t) { - strncpy(dst, "", dst_len); - return; - } - - encoding_getArgumentInfo(t, index, &t, &offset); - - if (!t) { - strncpy(dst, "", dst_len); - return; - } - - end = SkipFirstType(t); - len = end - t; - strncpy(dst, t, MIN(len, dst_len)); - if (len < dst_len) memset(dst+len, 0, dst_len - len); -} - - -/*********************************************************************** -* encoding_copyArgumentType. Returns a single argument's type string -* on the heap. Argument 0 is `self`; argument 1 is `_cmd`. -**********************************************************************/ -char * -encoding_copyArgumentType(const char *t, unsigned int index) -{ - size_t len; - const char *end; - char *result; - int offset; - - if (!t) return NULL; - - encoding_getArgumentInfo(t, index, &t, &offset); - - if (!t) return NULL; - - end = SkipFirstType(t); - len = end - t; - result = (char *)malloc(len + 1); - strncpy(result, t, len); - result[len] = '\0'; - return result; -} diff --git a/objc/objc-runtime/runtime/objc-weak.h b/objc/objc-runtime/runtime/objc-weak.h deleted file mode 100644 index f8c9400..0000000 --- a/objc/objc-runtime/runtime/objc-weak.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2010-2011 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 _OBJC_WEAK_H_ -#define _OBJC_WEAK_H_ - -#include <objc/objc.h> -#include "objc-config.h" - -__BEGIN_DECLS - -/* -The weak table is a hash table governed by a single spin lock. -An allocated blob of memory, most often an object, but under GC any such -allocation, may have its address stored in a __weak marked storage location -through use of compiler generated write-barriers or hand coded uses of the -register weak primitive. Associated with the registration can be a callback -block for the case when one of the allocated chunks of memory is reclaimed. -The table is hashed on the address of the allocated memory. When __weak -marked memory changes its reference, we count on the fact that we can still -see its previous reference. - -So, in the hash table, indexed by the weakly referenced item, is a list of -all locations where this address is currently being stored. - -For ARR, we also keep track of whether an arbitrary object is being -deallocated by briefly placing it in the table just prior to invoking -dealloc, and removing it via objc_clear_deallocating just prior to memory -reclamation. - -*/ - -/// The address of a __weak object reference -typedef objc_object ** weak_referrer_t; - -#if __LP64__ -#define PTR_MINUS_1 63 -#else -#define PTR_MINUS_1 31 -#endif - -/** - * The internal structure stored in the weak references table. - * It maintains and stores - * a hash set of weak references pointing to an object. - * If out_of_line==0, the set is instead a small inline array. - */ -#define WEAK_INLINE_COUNT 4 -struct weak_entry_t { - DisguisedPtr<objc_object> referent; - union { - struct { - weak_referrer_t *referrers; - uintptr_t out_of_line : 1; - uintptr_t num_refs : PTR_MINUS_1; - uintptr_t mask; - uintptr_t max_hash_displacement; - }; - struct { - // out_of_line=0 is LSB of one of these (don't care which) - weak_referrer_t inline_referrers[WEAK_INLINE_COUNT]; - }; - }; -}; - -/** - * The global weak references table. Stores object ids as keys, - * and weak_entry_t structs as their values. - */ -struct weak_table_t { - weak_entry_t *weak_entries; - size_t num_entries; - uintptr_t mask; - uintptr_t max_hash_displacement; -}; - -/// Adds an (object, weak pointer) pair to the weak table. -id weak_register_no_lock(weak_table_t *weak_table, id referent, - id *referrer, bool crashIfDeallocating); - -/// Removes an (object, weak pointer) pair from the weak table. -void weak_unregister_no_lock(weak_table_t *weak_table, id referent, id *referrer); - -#if DEBUG -/// Returns true if an object is weakly referenced somewhere. -bool weak_is_registered_no_lock(weak_table_t *weak_table, id referent); -#endif - -/// Assert a weak pointer is valid and retain the object during its use. -id weak_read_no_lock(weak_table_t *weak_table, id *referrer); - -/// Called on object destruction. Sets all remaining weak pointers to nil. -void weak_clear_no_lock(weak_table_t *weak_table, id referent); - -__END_DECLS - -#endif /* _OBJC_WEAK_H_ */ diff --git a/objc/objc-runtime/runtime/objc-weak.mm b/objc/objc-runtime/runtime/objc-weak.mm deleted file mode 100644 index c822953..0000000 --- a/objc/objc-runtime/runtime/objc-weak.mm +++ /dev/null @@ -1,553 +0,0 @@ -/* - * Copyright (c) 2010-2011 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 "objc-private.h" - -#include "objc-weak.h" - -#include <stdint.h> -#include <stdbool.h> -#include <sys/types.h> -#include <libkern/OSAtomic.h> - -#define TABLE_SIZE(entry) (entry->mask ? entry->mask + 1 : 0) - -static void append_referrer(weak_entry_t *entry, objc_object **new_referrer); - -BREAKPOINT_FUNCTION( - void objc_weak_error(void) -); - -/** - * Unique hash function for object pointers only. - * - * @param key The object pointer - * - * @return Size unrestricted hash of pointer. - */ -static inline uintptr_t hash_pointer(objc_object *key) { - return ptr_hash((uintptr_t)key); -} - -/** - * Unique hash function for weak object pointers only. - * - * @param key The weak object pointer. - * - * @return Size unrestricted hash of pointer. - */ -static inline uintptr_t w_hash_pointer(objc_object **key) { - return ptr_hash((uintptr_t)key); -} - -/** - * Grow the entry's hash table of referrers. Rehashes each - * of the referrers. - * - * @param entry Weak pointer hash set for a particular object. - */ -__attribute__((noinline, used)) -static void grow_refs_and_insert(weak_entry_t *entry, - objc_object **new_referrer) -{ - assert(entry->out_of_line); - - size_t old_size = TABLE_SIZE(entry); - size_t new_size = old_size ? old_size * 2 : 8; - - size_t num_refs = entry->num_refs; - weak_referrer_t *old_refs = entry->referrers; - entry->mask = new_size - 1; - - entry->referrers = (weak_referrer_t *) - calloc(TABLE_SIZE(entry), sizeof(weak_referrer_t)); - entry->num_refs = 0; - entry->max_hash_displacement = 0; - - for (size_t i = 0; i < old_size && num_refs > 0; i++) { - if (old_refs[i] != nil) { - append_referrer(entry, old_refs[i]); - num_refs--; - } - } - // Insert - append_referrer(entry, new_referrer); - if (old_refs) free(old_refs); -} - -/** - * Add the given referrer to set of weak pointers in this entry. - * Does not perform duplicate checking (b/c weak pointers are never - * added to a set twice). - * - * @param entry The entry holding the set of weak pointers. - * @param new_referrer The new weak pointer to be added. - */ -static void append_referrer(weak_entry_t *entry, objc_object **new_referrer) -{ - if (! entry->out_of_line) { - // Try to insert inline. - for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) { - if (entry->inline_referrers[i] == nil) { - entry->inline_referrers[i] = new_referrer; - return; - } - } - - // Couldn't insert inline. Allocate out of line. - weak_referrer_t *new_referrers = (weak_referrer_t *) - calloc(WEAK_INLINE_COUNT, sizeof(weak_referrer_t)); - // This constructed table is invalid, but grow_refs_and_insert - // will fix it and rehash it. - for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) { - new_referrers[i] = entry->inline_referrers[i]; - } - entry->referrers = new_referrers; - entry->num_refs = WEAK_INLINE_COUNT; - entry->out_of_line = 1; - entry->mask = WEAK_INLINE_COUNT-1; - entry->max_hash_displacement = 0; - } - - assert(entry->out_of_line); - - if (entry->num_refs >= TABLE_SIZE(entry) * 3/4) { - return grow_refs_and_insert(entry, new_referrer); - } - size_t index = w_hash_pointer(new_referrer) & (entry->mask); - size_t hash_displacement = 0; - while (entry->referrers[index] != NULL) { - index = (index+1) & entry->mask; - hash_displacement++; - } - if (hash_displacement > entry->max_hash_displacement) { - entry->max_hash_displacement = hash_displacement; - } - weak_referrer_t &ref = entry->referrers[index]; - ref = new_referrer; - entry->num_refs++; -} - -/** - * Remove old_referrer from set of referrers, if it's present. - * Does not remove duplicates, because duplicates should not exist. - * - * @todo this is slow if old_referrer is not present. Is this ever the case? - * - * @param entry The entry holding the referrers. - * @param old_referrer The referrer to remove. - */ -static void remove_referrer(weak_entry_t *entry, objc_object **old_referrer) -{ - if (! entry->out_of_line) { - for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) { - if (entry->inline_referrers[i] == old_referrer) { - entry->inline_referrers[i] = nil; - return; - } - } - _objc_inform("Attempted to unregister unknown __weak variable " - "at %p. This is probably incorrect use of " - "objc_storeWeak() and objc_loadWeak(). " - "Break on objc_weak_error to debug.\n", - old_referrer); - objc_weak_error(); - return; - } - - size_t index = w_hash_pointer(old_referrer) & (entry->mask); - size_t hash_displacement = 0; - while (entry->referrers[index] != old_referrer) { - index = (index+1) & entry->mask; - hash_displacement++; - if (hash_displacement > entry->max_hash_displacement) { - _objc_inform("Attempted to unregister unknown __weak variable " - "at %p. This is probably incorrect use of " - "objc_storeWeak() and objc_loadWeak(). " - "Break on objc_weak_error to debug.\n", - old_referrer); - objc_weak_error(); - return; - } - } - entry->referrers[index] = nil; - entry->num_refs--; -} - -/** - * Add new_entry to the object's table of weak references. - * Does not check whether the referent is already in the table. - */ -static void weak_entry_insert(weak_table_t *weak_table, weak_entry_t *new_entry) -{ - weak_entry_t *weak_entries = weak_table->weak_entries; - assert(weak_entries != nil); - - size_t index = hash_pointer(new_entry->referent) & (weak_table->mask); - size_t hash_displacement = 0; - while (weak_entries[index].referent != nil) { - index = (index+1) & weak_table->mask; - hash_displacement++; - } - - weak_entries[index] = *new_entry; - weak_table->num_entries++; - - if (hash_displacement > weak_table->max_hash_displacement) { - weak_table->max_hash_displacement = hash_displacement; - } -} - - -static void weak_resize(weak_table_t *weak_table, size_t new_size) -{ - size_t old_size = TABLE_SIZE(weak_table); - - weak_entry_t *old_entries = weak_table->weak_entries; - weak_entry_t *new_entries = (weak_entry_t *) - calloc(new_size, sizeof(weak_entry_t)); - - weak_table->mask = new_size - 1; - weak_table->weak_entries = new_entries; - weak_table->max_hash_displacement = 0; - weak_table->num_entries = 0; // restored by weak_entry_insert below - - if (old_entries) { - weak_entry_t *entry; - weak_entry_t *end = old_entries + old_size; - for (entry = old_entries; entry < end; entry++) { - if (entry->referent) { - weak_entry_insert(weak_table, entry); - } - } - free(old_entries); - } -} - -// Grow the given zone's table of weak references if it is full. -static void weak_grow_maybe(weak_table_t *weak_table) -{ - size_t old_size = TABLE_SIZE(weak_table); - - // Grow if at least 3/4 full. - if (weak_table->num_entries >= old_size * 3 / 4) { - weak_resize(weak_table, old_size ? old_size*2 : 64); - } -} - -// Shrink the table if it is mostly empty. -static void weak_compact_maybe(weak_table_t *weak_table) -{ - size_t old_size = TABLE_SIZE(weak_table); - - // Shrink if larger than 1024 buckets and at most 1/16 full. - if (old_size >= 1024 && old_size / 16 >= weak_table->num_entries) { - weak_resize(weak_table, old_size / 8); - // leaves new table no more than 1/2 full - } -} - - -/** - * Remove entry from the zone's table of weak references. - */ -static void weak_entry_remove(weak_table_t *weak_table, weak_entry_t *entry) -{ - // remove entry - if (entry->out_of_line) free(entry->referrers); - bzero(entry, sizeof(*entry)); - - weak_table->num_entries--; - - weak_compact_maybe(weak_table); -} - - -/** - * Return the weak reference table entry for the given referent. - * If there is no entry for referent, return NULL. - * Performs a lookup. - * - * @param weak_table - * @param referent The object. Must not be nil. - * - * @return The table of weak referrers to this object. - */ -static weak_entry_t * -weak_entry_for_referent(weak_table_t *weak_table, objc_object *referent) -{ - assert(referent); - - weak_entry_t *weak_entries = weak_table->weak_entries; - - if (!weak_entries) return nil; - - size_t index = hash_pointer(referent) & weak_table->mask; - size_t hash_displacement = 0; - while (weak_table->weak_entries[index].referent != referent) { - index = (index+1) & weak_table->mask; - hash_displacement++; - if (hash_displacement > weak_table->max_hash_displacement) { - return nil; - } - } - - return &weak_table->weak_entries[index]; -} - -/** - * Unregister an already-registered weak reference. - * This is used when referrer's storage is about to go away, but referent - * isn't dead yet. (Otherwise, zeroing referrer later would be a - * bad memory access.) - * Does nothing if referent/referrer is not a currently active weak reference. - * Does not zero referrer. - * - * FIXME currently requires old referent value to be passed in (lame) - * FIXME unregistration should be automatic if referrer is collected - * - * @param weak_table The global weak table. - * @param referent The object. - * @param referrer The weak reference. - */ -void -weak_unregister_no_lock(weak_table_t *weak_table, id referent_id, - id *referrer_id) -{ - objc_object *referent = (objc_object *)referent_id; - objc_object **referrer = (objc_object **)referrer_id; - - weak_entry_t *entry; - - if (!referent) return; - - if ((entry = weak_entry_for_referent(weak_table, referent))) { - remove_referrer(entry, referrer); - bool empty = true; - if (entry->out_of_line && entry->num_refs != 0) { - empty = false; - } - else { - for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) { - if (entry->inline_referrers[i]) { - empty = false; - break; - } - } - } - - if (empty) { - weak_entry_remove(weak_table, entry); - } - } - - // Do not set *referrer = nil. objc_storeWeak() requires that the - // value not change. -} - -/** - * Registers a new (object, weak pointer) pair. Creates a new weak - * object entry if it does not exist. - * - * @param weak_table The global weak table. - * @param referent The object pointed to by the weak reference. - * @param referrer The weak pointer address. - */ -id -weak_register_no_lock(weak_table_t *weak_table, id referent_id, - id *referrer_id, bool crashIfDeallocating) -{ - objc_object *referent = (objc_object *)referent_id; - objc_object **referrer = (objc_object **)referrer_id; - - if (!referent || referent->isTaggedPointer()) return referent_id; - - // ensure that the referenced object is viable - bool deallocating; - if (!referent->ISA()->hasCustomRR()) { - deallocating = referent->rootIsDeallocating(); - } - else { - BOOL (*allowsWeakReference)(objc_object *, SEL) = - (BOOL(*)(objc_object *, SEL)) - object_getMethodImplementation((id)referent, - SEL_allowsWeakReference); - if ((IMP)allowsWeakReference == _objc_msgForward) { - return nil; - } - deallocating = - ! (*allowsWeakReference)(referent, SEL_allowsWeakReference); - } - - if (deallocating) { - if (crashIfDeallocating) { - _objc_fatal("Cannot form weak reference to instance (%p) of " - "class %s. It is possible that this object was " - "over-released, or is in the process of deallocation.", - (void*)referent, object_getClassName((id)referent)); - } else { - return nil; - } - } - - // now remember it and where it is being stored - weak_entry_t *entry; - if ((entry = weak_entry_for_referent(weak_table, referent))) { - append_referrer(entry, referrer); - } - else { - weak_entry_t new_entry; - new_entry.referent = referent; - new_entry.out_of_line = 0; - new_entry.inline_referrers[0] = referrer; - for (size_t i = 1; i < WEAK_INLINE_COUNT; i++) { - new_entry.inline_referrers[i] = nil; - } - - weak_grow_maybe(weak_table); - weak_entry_insert(weak_table, &new_entry); - } - - // Do not set *referrer. objc_storeWeak() requires that the - // value not change. - - return referent_id; -} - - -#if DEBUG -bool -weak_is_registered_no_lock(weak_table_t *weak_table, id referent_id) -{ - return weak_entry_for_referent(weak_table, (objc_object *)referent_id); -} -#endif - - -/** - * Called by dealloc; nils out all weak pointers that point to the - * provided object so that they can no longer be used. - * - * @param weak_table - * @param referent The object being deallocated. - */ -void -weak_clear_no_lock(weak_table_t *weak_table, id referent_id) -{ - objc_object *referent = (objc_object *)referent_id; - - weak_entry_t *entry = weak_entry_for_referent(weak_table, referent); - if (entry == nil) { - /// XXX shouldn't happen, but does with mismatched CF/objc - //printf("XXX no entry for clear deallocating %p\n", referent); - return; - } - - // zero out references - weak_referrer_t *referrers; - size_t count; - - if (entry->out_of_line) { - referrers = entry->referrers; - count = TABLE_SIZE(entry); - } - else { - referrers = entry->inline_referrers; - count = WEAK_INLINE_COUNT; - } - - for (size_t i = 0; i < count; ++i) { - objc_object **referrer = referrers[i]; - if (referrer) { - if (*referrer == referent) { - *referrer = nil; - } - else if (*referrer) { - _objc_inform("__weak variable at %p holds %p instead of %p. " - "This is probably incorrect use of " - "objc_storeWeak() and objc_loadWeak(). " - "Break on objc_weak_error to debug.\n", - referrer, (void*)*referrer, (void*)referent); - objc_weak_error(); - } - } - } - - weak_entry_remove(weak_table, entry); -} - - -/** - * This function gets called when the value of a weak pointer is being - * used in an expression. Called by objc_loadWeakRetained() which is - * ultimately called by objc_loadWeak(). The objective is to assert that - * there is in fact a weak pointer(s) entry for this particular object being - * stored in the weak-table, and to retain that object so it is not deallocated - * during the weak pointer's usage. - * - * @param weak_table - * @param referrer The weak pointer address. - */ -/* - Once upon a time we eagerly cleared *referrer if we saw the referent - was deallocating. This confuses code like NSPointerFunctions which - tries to pre-flight the raw storage and assumes if the storage is - zero then the weak system is done interfering. That is false: the - weak system is still going to check and clear the storage later. - This can cause objc_weak_error complaints and crashes. - So we now don't touch the storage until deallocation completes. -*/ -id -weak_read_no_lock(weak_table_t *weak_table, id *referrer_id) -{ - objc_object **referrer = (objc_object **)referrer_id; - objc_object *referent = *referrer; - if (referent->isTaggedPointer()) return (id)referent; - - weak_entry_t *entry; - if (referent == nil || - !(entry = weak_entry_for_referent(weak_table, referent))) - { - return nil; - } - - if (! referent->ISA()->hasCustomRR()) { - if (! referent->rootTryRetain()) { - return nil; - } - } - else { - BOOL (*tryRetain)(objc_object *, SEL) = (BOOL(*)(objc_object *, SEL)) - object_getMethodImplementation((id)referent, - SEL_retainWeakReference); - if ((IMP)tryRetain == _objc_msgForward) { - return nil; - } - if (! (*tryRetain)(referent, SEL_retainWeakReference)) { - return nil; - } - } - - return (id)referent; -} - diff --git a/objc/objc-runtime/runtime/objc.h b/objc/objc-runtime/runtime/objc.h deleted file mode 100644 index b0554cc..0000000 --- a/objc/objc-runtime/runtime/objc.h +++ /dev/null @@ -1,229 +0,0 @@ -/* - * 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@ - */ -/* - * objc.h - * Copyright 1988-1996, NeXT Software, Inc. - */ - -#ifndef _OBJC_OBJC_H_ -#define _OBJC_OBJC_H_ - -#include <sys/types.h> // for __DARWIN_NULL -#include <Availability.h> -#include <objc/objc-api.h> -#include <stdbool.h> - -#if !OBJC_TYPES_DEFINED -/// An opaque type that represents an Objective-C class. -typedef struct objc_class *Class; - -/// Represents an instance of a class. -struct objc_object { - Class isa OBJC_ISA_AVAILABILITY; -}; - -/// A pointer to an instance of a class. -typedef struct objc_object *id; -#endif - -/// An opaque type that represents a method selector. -typedef struct objc_selector *SEL; - -/// A pointer to the function of a method implementation. -#if !OBJC_OLD_DISPATCH_PROTOTYPES -typedef void (*IMP)(void /* id, SEL, ... */ ); -#else -typedef id (*IMP)(id, SEL, ...); -#endif - -#define OBJC_BOOL_DEFINED - -/// Type to represent a boolean value. -#if (TARGET_OS_IPHONE && __LP64__) || TARGET_OS_WATCH -#define OBJC_BOOL_IS_BOOL 1 -typedef bool BOOL; -#else -#define OBJC_BOOL_IS_CHAR 1 -typedef signed char BOOL; -// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" -// even if -funsigned-char is used. -#endif - -#if __has_feature(objc_bool) -#define YES __objc_yes -#define NO __objc_no -#else -#define YES ((BOOL)1) -#define NO ((BOOL)0) -#endif - -#ifndef Nil -# if __has_feature(cxx_nullptr) -# define Nil nullptr -# else -# define Nil __DARWIN_NULL -# endif -#endif - -#ifndef nil -# if __has_feature(cxx_nullptr) -# define nil nullptr -# else -# define nil __DARWIN_NULL -# endif -#endif - -#if ! (defined(__OBJC_GC__) || __has_feature(objc_arc)) -#define __strong /* empty */ -#endif - -#if !__has_feature(objc_arc) -#define __unsafe_unretained /* empty */ -#define __autoreleasing /* empty */ -#endif - - -/** - * Returns the name of the method specified by a given selector. - * - * @param sel A pointer of type \c SEL. Pass the selector whose name you wish to determine. - * - * @return A C string indicating the name of the selector. - */ -OBJC_EXPORT const char *sel_getName(SEL sel) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Registers a method with the Objective-C runtime system, maps the method - * name to a selector, and returns the selector value. - * - * @param str A pointer to a C string. Pass the name of the method you wish to register. - * - * @return A pointer of type SEL specifying the selector for the named method. - * - * @note You must register a method name with the Objective-C runtime system to obtain the - * method’s selector before you can add the method to a class definition. If the method name - * has already been registered, this function simply returns the selector. - */ -OBJC_EXPORT SEL sel_registerName(const char *str) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the class name of a given object. - * - * @param obj An Objective-C object. - * - * @return The name of the class of which \e obj is an instance. - */ -OBJC_EXPORT const char *object_getClassName(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a pointer to any extra bytes allocated with an instance given object. - * - * @param obj An Objective-C object. - * - * @return A pointer to any extra bytes allocated with \e obj. If \e obj was - * not allocated with any extra bytes, then dereferencing the returned pointer is undefined. - * - * @note This function returns a pointer to any extra bytes allocated with the instance - * (as specified by \c class_createInstance with extraBytes>0). This memory follows the - * object's ordinary ivars, but may not be adjacent to the last ivar. - * @note The returned pointer is guaranteed to be pointer-size aligned, even if the area following - * the object's last ivar is less aligned than that. Alignment greater than pointer-size is never - * guaranteed, even if the area following the object's last ivar is more aligned than that. - * @note In a garbage-collected environment, the memory is scanned conservatively. - */ -OBJC_EXPORT void *object_getIndexedIvars(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Identifies a selector as being valid or invalid. - * - * @param sel The selector you want to identify. - * - * @return YES if selector is valid and has a function implementation, NO otherwise. - * - * @warning On some platforms, an invalid reference (to invalid memory addresses) can cause - * a crash. - */ -OBJC_EXPORT BOOL sel_isMapped(SEL sel) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Registers a method name with the Objective-C runtime system. - * - * @param str A pointer to a C string. Pass the name of the method you wish to register. - * - * @return A pointer of type SEL specifying the selector for the named method. - * - * @note The implementation of this method is identical to the implementation of \c sel_registerName. - * @note Prior to OS X version 10.0, this method tried to find the selector mapped to the given name - * and returned \c NULL if the selector was not found. This was changed for safety, because it was - * observed that many of the callers of this function did not check the return value for \c NULL. - */ -OBJC_EXPORT SEL sel_getUid(const char *str) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - - -// Obsolete ARC conversions. Deprecation forthcoming. -// Use CFBridgingRetain, CFBridgingRelease, and __bridge casts instead. - -typedef const void* objc_objectptr_t; - -#if __has_feature(objc_arc) -# define objc_retainedObject(o) ((__bridge_transfer id)(objc_objectptr_t)(o)) -# define objc_unretainedObject(o) ((__bridge id)(objc_objectptr_t)(o)) -# define objc_unretainedPointer(o) ((__bridge objc_objectptr_t)(id)(o)) -#else -# define objc_retainedObject(o) ((id)(objc_objectptr_t)(o)) -# define objc_unretainedObject(o) ((id)(objc_objectptr_t)(o)) -# define objc_unretainedPointer(o) ((objc_objectptr_t)(id)(o)) -#endif - - -#if !__OBJC2__ - -// The following declarations are provided here for source compatibility. - -#if defined(__LP64__) - typedef long arith_t; - typedef unsigned long uarith_t; -# define ARITH_SHIFT 32 -#else - typedef int arith_t; - typedef unsigned uarith_t; -# define ARITH_SHIFT 16 -#endif - -typedef char *STR; - -#define ISSELECTOR(sel) sel_isMapped(sel) -#define SELNAME(sel) sel_getName(sel) -#define SELUID(str) sel_getUid(str) -#define NAMEOF(obj) object_getClassName(obj) -#define IV(obj) object_getIndexedIvars(obj) - -#endif - -#endif /* _OBJC_OBJC_H_ */ diff --git a/objc/objc-runtime/runtime/objcrt.c b/objc/objc-runtime/runtime/objcrt.c deleted file mode 100644 index 7570e2d..0000000 --- a/objc/objc-runtime/runtime/objcrt.c +++ /dev/null @@ -1,98 +0,0 @@ -#define WIN32_LEAN_AND_MEAN -#include <stdio.h> -#include <windows.h> -#include <stdlib.h> -#include "objcrt.h" - -// Boundary symbols for metadata sections - -#pragma section(".objc_module_info$A",long,read,write) -#pragma data_seg(".objc_module_info$A") -static uintptr_t __objc_modStart = 0; -#pragma section(".objc_module_info$C",long,read,write) -#pragma data_seg(".objc_module_info$C") -static uintptr_t __objc_modEnd = 0; - -#pragma section(".objc_protocol$A",long,read,write) -#pragma data_seg(".objc_protocol$A") -static uintptr_t __objc_protoStart = 0; -#pragma section(".objc_protocol$C",long,read,write) -#pragma data_seg(".objc_protocol$C") -static uintptr_t __objc_protoEnd = 0; - -#pragma section(".objc_image_info$A",long,read,write) -#pragma data_seg(".objc_image_info$A") -static uintptr_t __objc_iiStart = 0; -#pragma section(".objc_image_info$C",long,read,write) -#pragma data_seg(".objc_image_info$C") -static uintptr_t __objc_iiEnd = 0; - -#pragma section(".objc_message_refs$A",long,read,write) -#pragma data_seg(".objc_message_refs$A") -static uintptr_t __objc_selrefsStart = 0; -#pragma section(".objc_message_refs$C",long,read,write) -#pragma data_seg(".objc_message_refs$C") -static uintptr_t __objc_selrefsEnd = 0; - -#pragma section(".objc_class_refs$A",long,read,write) -#pragma data_seg(".objc_class_refs$A") -static uintptr_t __objc_clsrefsStart = 0; -#pragma section(".objc_class_refs$C",long,read,write) -#pragma data_seg(".objc_class_refs$C") -static uintptr_t __objc_clsrefsEnd = 0; - -#pragma data_seg() - -// Merge all metadata into .data -// fixme order these by usage? -#pragma comment(linker, "/MERGE:.objc_module_info=.data") -#pragma comment(linker, "/MERGE:.objc_protocol=.data") -#pragma comment(linker, "/MERGE:.objc_image_info=.data") -#pragma comment(linker, "/MERGE:.objc_message_refs=.data") -#pragma comment(linker, "/MERGE:.objc_class_refs=.data") - - -// Image initializers - -static void *__hinfo = NULL; // cookie from runtime -extern IMAGE_DOS_HEADER __ImageBase; // this image's header - -static int __objc_init(void) -{ - objc_sections sections = { - 5, - &__objc_modStart, &__objc_modEnd, - &__objc_protoStart, &__objc_protoEnd, - &__objc_iiStart, &__objc_iiEnd, - &__objc_selrefsStart, &__objc_selrefsEnd, - &__objc_clsrefsStart, &__objc_clsrefsEnd, - }; - __hinfo = _objc_init_image((HMODULE)&__ImageBase, §ions); - return 0; -} - -static void __objc_unload(void) -{ - _objc_unload_image((HMODULE)&__ImageBase, __hinfo); -} - -static int __objc_load(void) -{ - _objc_load_image((HMODULE)&__ImageBase, __hinfo); - return 0; -} - -// run _objc_init_image ASAP -#pragma section(".CRT$XIAA",long,read,write) -#pragma data_seg(".CRT$XIAA") -static void *__objc_init_fn = &__objc_init; - -// run _objc_load_image (+load methods) after all other initializers; -// otherwise constant NSStrings are not initialized yet -#pragma section(".CRT$XCUO",long,read,write) -#pragma data_seg(".CRT$XCUO") -static void *__objc_load_fn = &__objc_load; - -// _objc_unload_image is called by atexit(), not by an image terminator - -#pragma data_seg() diff --git a/objc/objc-runtime/runtime/objcrt.h b/objc/objc-runtime/runtime/objcrt.h deleted file mode 100644 index 4e6fefd..0000000 --- a/objc/objc-runtime/runtime/objcrt.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef _OBJC_RT_H_ -#define _OBJC_RT_H_ - -#include <objc/objc-api.h> - - -typedef struct { - int count; // number of pointer pairs that follow - void *modStart; - void *modEnd; - void *protoStart; - void *protoEnd; - void *iiStart; - void *iiEnd; - void *selrefsStart; - void *selrefsEnd; - void *clsrefsStart; - void *clsrefsEnd; -} objc_sections; - -OBJC_EXPORT void *_objc_init_image(HMODULE image, const objc_sections *sects); -OBJC_EXPORT void _objc_load_image(HMODULE image, void *hinfo); -OBJC_EXPORT void _objc_unload_image(HMODULE image, void *hinfo); - -#endif diff --git a/objc/objc-runtime/runtime/runtime.h b/objc/objc-runtime/runtime/runtime.h deleted file mode 100644 index 7c7ce6e..0000000 --- a/objc/objc-runtime/runtime/runtime.h +++ /dev/null @@ -1,1780 +0,0 @@ -/* - * 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@ - */ - -#ifndef _OBJC_RUNTIME_H -#define _OBJC_RUNTIME_H - -#include <objc/objc.h> -#include <stdarg.h> -#include <stdint.h> -#include <stddef.h> -#include <Availability.h> -#include <TargetConditionals.h> - -#if TARGET_OS_MAC -#include <sys/types.h> -#endif - - -/* Types */ - -#if !OBJC_TYPES_DEFINED - -/// An opaque type that represents a method in a class definition. -typedef struct objc_method *Method; - -/// An opaque type that represents an instance variable. -typedef struct objc_ivar *Ivar; - -/// An opaque type that represents a category. -typedef struct objc_category *Category; - -/// An opaque type that represents an Objective-C declared property. -typedef struct objc_property *objc_property_t; - -struct objc_class { - Class isa OBJC_ISA_AVAILABILITY; - -#if !__OBJC2__ - Class super_class OBJC2_UNAVAILABLE; - const char *name OBJC2_UNAVAILABLE; - long version OBJC2_UNAVAILABLE; - long info OBJC2_UNAVAILABLE; - long instance_size OBJC2_UNAVAILABLE; - struct objc_ivar_list *ivars OBJC2_UNAVAILABLE; - struct objc_method_list **methodLists OBJC2_UNAVAILABLE; - struct objc_cache *cache OBJC2_UNAVAILABLE; - struct objc_protocol_list *protocols OBJC2_UNAVAILABLE; -#endif - -} OBJC2_UNAVAILABLE; -/* Use `Class` instead of `struct objc_class *` */ - -#endif - -#ifdef __OBJC__ -@class Protocol; -#else -typedef struct objc_object Protocol; -#endif - -/// Defines a method -struct objc_method_description { - SEL name; /**< The name of the method */ - char *types; /**< The types of the method arguments */ -}; - -/// Defines a property attribute -typedef struct { - const char *name; /**< The name of the attribute */ - const char *value; /**< The value of the attribute (usually empty) */ -} objc_property_attribute_t; - - -/* Functions */ - -/* Working with Instances */ - -/** - * Returns a copy of a given object. - * - * @param obj An Objective-C object. - * @param size The size of the object \e obj. - * - * @return A copy of \e obj. - */ -OBJC_EXPORT id object_copy(id obj, size_t size) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Frees the memory occupied by a given object. - * - * @param obj An Objective-C object. - * - * @return nil - */ -OBJC_EXPORT id object_dispose(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Returns the class of an object. - * - * @param obj The object you want to inspect. - * - * @return The class object of which \e object is an instance, - * or \c Nil if \e object is \c nil. - */ -OBJC_EXPORT Class object_getClass(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the class of an object. - * - * @param obj The object to modify. - * @param cls A class object. - * - * @return The previous value of \e object's class, or \c Nil if \e object is \c nil. - */ -OBJC_EXPORT Class object_setClass(id obj, Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/** - * Returns whether an object is a class object. - * - * @param obj An Objective-C object. - * - * @return true if the object is a class or metaclass, false otherwise. - */ -OBJC_EXPORT BOOL object_isClass(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0); - - -/** - * Returns the class name of a given object. - * - * @param obj An Objective-C object. - * - * @return The name of the class of which \e obj is an instance. - */ -OBJC_EXPORT const char *object_getClassName(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a pointer to any extra bytes allocated with an instance given object. - * - * @param obj An Objective-C object. - * - * @return A pointer to any extra bytes allocated with \e obj. If \e obj was - * not allocated with any extra bytes, then dereferencing the returned pointer is undefined. - * - * @note This function returns a pointer to any extra bytes allocated with the instance - * (as specified by \c class_createInstance with extraBytes>0). This memory follows the - * object's ordinary ivars, but may not be adjacent to the last ivar. - * @note The returned pointer is guaranteed to be pointer-size aligned, even if the area following - * the object's last ivar is less aligned than that. Alignment greater than pointer-size is never - * guaranteed, even if the area following the object's last ivar is more aligned than that. - * @note In a garbage-collected environment, the memory is scanned conservatively. - */ -OBJC_EXPORT void *object_getIndexedIvars(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Reads the value of an instance variable in an object. - * - * @param obj The object containing the instance variable whose value you want to read. - * @param ivar The Ivar describing the instance variable whose value you want to read. - * - * @return The value of the instance variable specified by \e ivar, or \c nil if \e object is \c nil. - * - * @note \c object_getIvar is faster than \c object_getInstanceVariable if the Ivar - * for the instance variable is already known. - */ -OBJC_EXPORT id object_getIvar(id obj, Ivar ivar) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the value of an instance variable in an object. - * - * @param obj The object containing the instance variable whose value you want to set. - * @param ivar The Ivar describing the instance variable whose value you want to set. - * @param value The new value for the instance variable. - * - * @note \c object_setIvar is faster than \c object_setInstanceVariable if the Ivar - * for the instance variable is already known. - */ -OBJC_EXPORT void object_setIvar(id obj, Ivar ivar, id value) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Changes the value of an instance variable of a class instance. - * - * @param obj A pointer to an instance of a class. Pass the object containing - * the instance variable whose value you wish to modify. - * @param name A C string. Pass the name of the instance variable whose value you wish to modify. - * @param value The new value for the instance variable. - * - * @return A pointer to the \c Ivar data structure that defines the type and - * name of the instance variable specified by \e name. - */ -OBJC_EXPORT Ivar object_setInstanceVariable(id obj, const char *name, void *value) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Obtains the value of an instance variable of a class instance. - * - * @param obj A pointer to an instance of a class. Pass the object containing - * the instance variable whose value you wish to obtain. - * @param name A C string. Pass the name of the instance variable whose value you wish to obtain. - * @param outValue On return, contains a pointer to the value of the instance variable. - * - * @return A pointer to the \c Ivar data structure that defines the type and name of - * the instance variable specified by \e name. - */ -OBJC_EXPORT Ivar object_getInstanceVariable(id obj, const char *name, void **outValue) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - - -/* Obtaining Class Definitions */ - -/** - * Returns the class definition of a specified class. - * - * @param name The name of the class to look up. - * - * @return The Class object for the named class, or \c nil - * if the class is not registered with the Objective-C runtime. - * - * @note \c objc_getClass is different from \c objc_lookUpClass in that if the class - * is not registered, \c objc_getClass calls the class handler callback and then checks - * a second time to see whether the class is registered. \c objc_lookUpClass does - * not call the class handler callback. - * - * @warning Earlier implementations of this function (prior to OS X v10.0) - * terminate the program if the class does not exist. - */ -OBJC_EXPORT Class objc_getClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the metaclass definition of a specified class. - * - * @param name The name of the class to look up. - * - * @return The \c Class object for the metaclass of the named class, or \c nil if the class - * is not registered with the Objective-C runtime. - * - * @note If the definition for the named class is not registered, this function calls the class handler - * callback and then checks a second time to see if the class is registered. However, every class - * definition must have a valid metaclass definition, and so the metaclass definition is always returned, - * whether it’s valid or not. - */ -OBJC_EXPORT Class objc_getMetaClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the class definition of a specified class. - * - * @param name The name of the class to look up. - * - * @return The Class object for the named class, or \c nil if the class - * is not registered with the Objective-C runtime. - * - * @note \c objc_getClass is different from this function in that if the class is not - * registered, \c objc_getClass calls the class handler callback and then checks a second - * time to see whether the class is registered. This function does not call the class handler callback. - */ -OBJC_EXPORT Class objc_lookUpClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the class definition of a specified class. - * - * @param name The name of the class to look up. - * - * @return The Class object for the named class. - * - * @note This function is the same as \c objc_getClass, but kills the process if the class is not found. - * @note This function is used by ZeroLink, where failing to find a class would be a compile-time link error without ZeroLink. - */ -OBJC_EXPORT Class objc_getRequiredClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Obtains the list of registered class definitions. - * - * @param buffer An array of \c Class values. On output, each \c Class value points to - * one class definition, up to either \e bufferCount or the total number of registered classes, - * whichever is less. You can pass \c NULL to obtain the total number of registered class - * definitions without actually retrieving any class definitions. - * @param bufferCount An integer value. Pass the number of pointers for which you have allocated space - * in \e buffer. On return, this function fills in only this number of elements. If this number is less - * than the number of registered classes, this function returns an arbitrary subset of the registered classes. - * - * @return An integer value indicating the total number of registered classes. - * - * @note The Objective-C runtime library automatically registers all the classes defined in your source code. - * You can create class definitions at runtime and register them with the \c objc_addClass function. - * - * @warning You cannot assume that class objects you get from this function are classes that inherit from \c NSObject, - * so you cannot safely call any methods on such classes without detecting that the method is implemented first. - */ -OBJC_EXPORT int objc_getClassList(Class *buffer, int bufferCount) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Creates and returns a list of pointers to all registered class definitions. - * - * @param outCount An integer pointer used to store the number of classes returned by - * this function in the list. It can be \c nil. - * - * @return A nil terminated array of classes. It must be freed with \c free(). - * - * @see objc_getClassList - */ -OBJC_EXPORT Class *objc_copyClassList(unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_1); - - -/* Working with Classes */ - -/** - * Returns the name of a class. - * - * @param cls A class object. - * - * @return The name of the class, or the empty string if \e cls is \c Nil. - */ -OBJC_EXPORT const char *class_getName(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether a class object is a metaclass. - * - * @param cls A class object. - * - * @return \c YES if \e cls is a metaclass, \c NO if \e cls is a non-meta class, - * \c NO if \e cls is \c Nil. - */ -OBJC_EXPORT BOOL class_isMetaClass(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the superclass of a class. - * - * @param cls A class object. - * - * @return The superclass of the class, or \c Nil if - * \e cls is a root class, or \c Nil if \e cls is \c Nil. - * - * @note You should usually use \c NSObject's \c superclass method instead of this function. - */ -OBJC_EXPORT Class class_getSuperclass(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the superclass of a given class. - * - * @param cls The class whose superclass you want to set. - * @param newSuper The new superclass for cls. - * - * @return The old superclass for cls. - * - * @warning You should not use this function. - */ -OBJC_EXPORT Class class_setSuperclass(Class cls, Class newSuper) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_5,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); - -/** - * Returns the version number of a class definition. - * - * @param cls A pointer to a \c Class data structure. Pass - * the class definition for which you wish to obtain the version. - * - * @return An integer indicating the version number of the class definition. - * - * @see class_setVersion - */ -OBJC_EXPORT int class_getVersion(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Sets the version number of a class definition. - * - * @param cls A pointer to an Class data structure. - * Pass the class definition for which you wish to set the version. - * @param version An integer. Pass the new version number of the class definition. - * - * @note You can use the version number of the class definition to provide versioning of the - * interface that your class represents to other classes. This is especially useful for object - * serialization (that is, archiving of the object in a flattened form), where it is important to - * recognize changes to the layout of the instance variables in different class-definition versions. - * @note Classes derived from the Foundation framework \c NSObject class can set the class-definition - * version number using the \c setVersion: class method, which is implemented using the \c class_setVersion function. - */ -OBJC_EXPORT void class_setVersion(Class cls, int version) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the size of instances of a class. - * - * @param cls A class object. - * - * @return The size in bytes of instances of the class \e cls, or \c 0 if \e cls is \c Nil. - */ -OBJC_EXPORT size_t class_getInstanceSize(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the \c Ivar for a specified instance variable of a given class. - * - * @param cls The class whose instance variable you wish to obtain. - * @param name The name of the instance variable definition to obtain. - * - * @return A pointer to an \c Ivar data structure containing information about - * the instance variable specified by \e name. - */ -OBJC_EXPORT Ivar class_getInstanceVariable(Class cls, const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the Ivar for a specified class variable of a given class. - * - * @param cls The class definition whose class variable you wish to obtain. - * @param name The name of the class variable definition to obtain. - * - * @return A pointer to an \c Ivar data structure containing information about the class variable specified by \e name. - */ -OBJC_EXPORT Ivar class_getClassVariable(Class cls, const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Describes the instance variables declared by a class. - * - * @param cls The class to inspect. - * @param outCount On return, contains the length of the returned array. - * If outCount is NULL, the length is not returned. - * - * @return An array of pointers of type Ivar describing the instance variables declared by the class. - * Any instance variables declared by superclasses are not included. The array contains *outCount - * pointers followed by a NULL terminator. You must free the array with free(). - * - * If the class declares no instance variables, or cls is Nil, NULL is returned and *outCount is 0. - */ -OBJC_EXPORT Ivar *class_copyIvarList(Class cls, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a specified instance method for a given class. - * - * @param cls The class you want to inspect. - * @param name The selector of the method you want to retrieve. - * - * @return The method that corresponds to the implementation of the selector specified by - * \e name for the class specified by \e cls, or \c NULL if the specified class or its - * superclasses do not contain an instance method with the specified selector. - * - * @note This function searches superclasses for implementations, whereas \c class_copyMethodList does not. - */ -OBJC_EXPORT Method class_getInstanceMethod(Class cls, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a pointer to the data structure describing a given class method for a given class. - * - * @param cls A pointer to a class definition. Pass the class that contains the method you want to retrieve. - * @param name A pointer of type \c SEL. Pass the selector of the method you want to retrieve. - * - * @return A pointer to the \c Method data structure that corresponds to the implementation of the - * selector specified by aSelector for the class specified by aClass, or NULL if the specified - * class or its superclasses do not contain an instance method with the specified selector. - * - * @note Note that this function searches superclasses for implementations, - * whereas \c class_copyMethodList does not. - */ -OBJC_EXPORT Method class_getClassMethod(Class cls, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns the function pointer that would be called if a - * particular message were sent to an instance of a class. - * - * @param cls The class you want to inspect. - * @param name A selector. - * - * @return The function pointer that would be called if \c [object name] were called - * with an instance of the class, or \c NULL if \e cls is \c Nil. - * - * @note \c class_getMethodImplementation may be faster than \c method_getImplementation(class_getInstanceMethod(cls, name)). - * @note The function pointer returned may be a function internal to the runtime instead of - * an actual method implementation. For example, if instances of the class do not respond to - * the selector, the function pointer returned will be part of the runtime's message forwarding machinery. - */ -OBJC_EXPORT IMP class_getMethodImplementation(Class cls, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the function pointer that would be called if a particular - * message were sent to an instance of a class. - * - * @param cls The class you want to inspect. - * @param name A selector. - * - * @return The function pointer that would be called if \c [object name] were called - * with an instance of the class, or \c NULL if \e cls is \c Nil. - */ -OBJC_EXPORT IMP class_getMethodImplementation_stret(Class cls, SEL name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0) - OBJC_ARM64_UNAVAILABLE; - -/** - * Returns a Boolean value that indicates whether instances of a class respond to a particular selector. - * - * @param cls The class you want to inspect. - * @param sel A selector. - * - * @return \c YES if instances of the class respond to the selector, otherwise \c NO. - * - * @note You should usually use \c NSObject's \c respondsToSelector: or \c instancesRespondToSelector: - * methods instead of this function. - */ -OBJC_EXPORT BOOL class_respondsToSelector(Class cls, SEL sel) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Describes the instance methods implemented by a class. - * - * @param cls The class you want to inspect. - * @param outCount On return, contains the length of the returned array. - * If outCount is NULL, the length is not returned. - * - * @return An array of pointers of type Method describing the instance methods - * implemented by the class—any instance methods implemented by superclasses are not included. - * The array contains *outCount pointers followed by a NULL terminator. You must free the array with free(). - * - * If cls implements no instance methods, or cls is Nil, returns NULL and *outCount is 0. - * - * @note To get the class methods of a class, use \c class_copyMethodList(object_getClass(cls), &count). - * @note To get the implementations of methods that may be implemented by superclasses, - * use \c class_getInstanceMethod or \c class_getClassMethod. - */ -OBJC_EXPORT Method *class_copyMethodList(Class cls, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether a class conforms to a given protocol. - * - * @param cls The class you want to inspect. - * @param protocol A protocol. - * - * @return YES if cls conforms to protocol, otherwise NO. - * - * @note You should usually use NSObject's conformsToProtocol: method instead of this function. - */ -OBJC_EXPORT BOOL class_conformsToProtocol(Class cls, Protocol *protocol) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Describes the protocols adopted by a class. - * - * @param cls The class you want to inspect. - * @param outCount On return, contains the length of the returned array. - * If outCount is NULL, the length is not returned. - * - * @return An array of pointers of type Protocol* describing the protocols adopted - * by the class. Any protocols adopted by superclasses or other protocols are not included. - * The array contains *outCount pointers followed by a NULL terminator. You must free the array with free(). - * - * If cls adopts no protocols, or cls is Nil, returns NULL and *outCount is 0. - */ -OBJC_EXPORT Protocol * __unsafe_unretained *class_copyProtocolList(Class cls, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a property with a given name of a given class. - * - * @param cls The class you want to inspect. - * @param name The name of the property you want to inspect. - * - * @return A pointer of type \c objc_property_t describing the property, or - * \c NULL if the class does not declare a property with that name, - * or \c NULL if \e cls is \c Nil. - */ -OBJC_EXPORT objc_property_t class_getProperty(Class cls, const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Describes the properties declared by a class. - * - * @param cls The class you want to inspect. - * @param outCount On return, contains the length of the returned array. - * If \e outCount is \c NULL, the length is not returned. - * - * @return An array of pointers of type \c objc_property_t describing the properties - * declared by the class. Any properties declared by superclasses are not included. - * The array contains \c *outCount pointers followed by a \c NULL terminator. You must free the array with \c free(). - * - * If \e cls declares no properties, or \e cls is \c Nil, returns \c NULL and \c *outCount is \c 0. - */ -OBJC_EXPORT objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a description of the \c Ivar layout for a given class. - * - * @param cls The class to inspect. - * - * @return A description of the \c Ivar layout for \e cls. - */ -OBJC_EXPORT const uint8_t *class_getIvarLayout(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a description of the layout of weak Ivars for a given class. - * - * @param cls The class to inspect. - * - * @return A description of the layout of the weak \c Ivars for \e cls. - */ -OBJC_EXPORT const uint8_t *class_getWeakIvarLayout(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Adds a new method to a class with a given name and implementation. - * - * @param cls The class to which to add a method. - * @param name A selector that specifies the name of the method being added. - * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd. - * @param types An array of characters that describe the types of the arguments to the method. - * - * @return YES if the method was added successfully, otherwise NO - * (for example, the class already contains a method implementation with that name). - * - * @note class_addMethod will add an override of a superclass's implementation, - * but will not replace an existing implementation in this class. - * To change an existing implementation, use method_setImplementation. - */ -OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, - const char *types) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Replaces the implementation of a method for a given class. - * - * @param cls The class you want to modify. - * @param name A selector that identifies the method whose implementation you want to replace. - * @param imp The new implementation for the method identified by name for the class identified by cls. - * @param types An array of characters that describe the types of the arguments to the method. - * Since the function must take at least two arguments—self and _cmd, the second and third characters - * must be “@:” (the first character is the return type). - * - * @return The previous implementation of the method identified by \e name for the class identified by \e cls. - * - * @note This function behaves in two different ways: - * - If the method identified by \e name does not yet exist, it is added as if \c class_addMethod were called. - * The type encoding specified by \e types is used as given. - * - If the method identified by \e name does exist, its \c IMP is replaced as if \c method_setImplementation were called. - * The type encoding specified by \e types is ignored. - */ -OBJC_EXPORT IMP class_replaceMethod(Class cls, SEL name, IMP imp, - const char *types) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Adds a new instance variable to a class. - * - * @return YES if the instance variable was added successfully, otherwise NO - * (for example, the class already contains an instance variable with that name). - * - * @note This function may only be called after objc_allocateClassPair and before objc_registerClassPair. - * Adding an instance variable to an existing class is not supported. - * @note The class must not be a metaclass. Adding an instance variable to a metaclass is not supported. - * @note The instance variable's minimum alignment in bytes is 1<<align. The minimum alignment of an instance - * variable depends on the ivar's type and the machine architecture. - * For variables of any pointer type, pass log2(sizeof(pointer_type)). - */ -OBJC_EXPORT BOOL class_addIvar(Class cls, const char *name, size_t size, - uint8_t alignment, const char *types) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Adds a protocol to a class. - * - * @param cls The class to modify. - * @param protocol The protocol to add to \e cls. - * - * @return \c YES if the method was added successfully, otherwise \c NO - * (for example, the class already conforms to that protocol). - */ -OBJC_EXPORT BOOL class_addProtocol(Class cls, Protocol *protocol) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Adds a property to a class. - * - * @param cls The class to modify. - * @param name The name of the property. - * @param attributes An array of property attributes. - * @param attributeCount The number of attributes in \e attributes. - * - * @return \c YES if the property was added successfully, otherwise \c NO - * (for example, the class already has that property). - */ -OBJC_EXPORT BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Replace a property of a class. - * - * @param cls The class to modify. - * @param name The name of the property. - * @param attributes An array of property attributes. - * @param attributeCount The number of attributes in \e attributes. - */ -OBJC_EXPORT void class_replaceProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Sets the Ivar layout for a given class. - * - * @param cls The class to modify. - * @param layout The layout of the \c Ivars for \e cls. - */ -OBJC_EXPORT void class_setIvarLayout(Class cls, const uint8_t *layout) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the layout for weak Ivars for a given class. - * - * @param cls The class to modify. - * @param layout The layout of the weak Ivars for \e cls. - */ -OBJC_EXPORT void class_setWeakIvarLayout(Class cls, const uint8_t *layout) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Used by CoreFoundation's toll-free bridging. - * Return the id of the named class. - * - * @return The id of the named class, or an uninitialized class - * structure that will be used for the class when and if it does - * get loaded. - * - * @warning Do not call this function yourself. - */ -OBJC_EXPORT Class objc_getFutureClass(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - - -/* Instantiating Classes */ - -/** - * Creates an instance of a class, allocating memory for the class in the - * default malloc memory zone. - * - * @param cls The class that you wish to allocate an instance of. - * @param extraBytes An integer indicating the number of extra bytes to allocate. - * The additional bytes can be used to store additional instance variables beyond - * those defined in the class definition. - * - * @return An instance of the class \e cls. - */ -OBJC_EXPORT id class_createInstance(Class cls, size_t extraBytes) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Creates an instance of a class at the specific location provided. - * - * @param cls The class that you wish to allocate an instance of. - * @param bytes The location at which to allocate an instance of \e cls. - * Must point to at least \c class_getInstanceSize(cls) bytes of well-aligned, - * zero-filled memory. - * - * @return \e bytes on success, \c nil otherwise. (For example, \e cls or \e bytes - * might be \c nil) - * - * @see class_createInstance - */ -OBJC_EXPORT id objc_constructInstance(Class cls, void *bytes) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) - OBJC_ARC_UNAVAILABLE; - -/** - * Destroys an instance of a class without freeing memory and removes any - * associated references this instance might have had. - * - * @param obj The class instance to destroy. - * - * @return \e obj. Does nothing if \e obj is nil. - * - * @warning GC does not call this. If you edit this, also edit finalize. - * - * @note CF and other clients do call this under GC. - */ -OBJC_EXPORT void *objc_destructInstance(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0) - OBJC_ARC_UNAVAILABLE; - - -/* Adding Classes */ - -/** - * Creates a new class and metaclass. - * - * @param superclass The class to use as the new class's superclass, or \c Nil to create a new root class. - * @param name The string to use as the new class's name. The string will be copied. - * @param extraBytes The number of bytes to allocate for indexed ivars at the end of - * the class and metaclass objects. This should usually be \c 0. - * - * @return The new class, or Nil if the class could not be created (for example, the desired name is already in use). - * - * @note You can get a pointer to the new metaclass by calling \c object_getClass(newClass). - * @note To create a new class, start by calling \c objc_allocateClassPair. - * Then set the class's attributes with functions like \c class_addMethod and \c class_addIvar. - * When you are done building the class, call \c objc_registerClassPair. The new class is now ready for use. - * @note Instance methods and instance variables should be added to the class itself. - * Class methods should be added to the metaclass. - */ -OBJC_EXPORT Class objc_allocateClassPair(Class superclass, const char *name, - size_t extraBytes) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Registers a class that was allocated using \c objc_allocateClassPair. - * - * @param cls The class you want to register. - */ -OBJC_EXPORT void objc_registerClassPair(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Used by Foundation's Key-Value Observing. - * - * @warning Do not call this function yourself. - */ -OBJC_EXPORT Class objc_duplicateClass(Class original, const char *name, size_t extraBytes) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Destroy a class and its associated metaclass. - * - * @param cls The class to be destroyed. It must have been allocated with - * \c objc_allocateClassPair - * - * @warning Do not call if instances of this class or a subclass exist. - */ -OBJC_EXPORT void objc_disposeClassPair(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Working with Methods */ - -/** - * Returns the name of a method. - * - * @param m The method to inspect. - * - * @return A pointer of type SEL. - * - * @note To get the method name as a C string, call \c sel_getName(method_getName(method)). - */ -OBJC_EXPORT SEL method_getName(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the implementation of a method. - * - * @param m The method to inspect. - * - * @return A function pointer of type IMP. - */ -OBJC_EXPORT IMP method_getImplementation(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a string describing a method's parameter and return types. - * - * @param m The method to inspect. - * - * @return A C string. The string may be \c NULL. - */ -OBJC_EXPORT const char *method_getTypeEncoding(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the number of arguments accepted by a method. - * - * @param m A pointer to a \c Method data structure. Pass the method in question. - * - * @return An integer containing the number of arguments accepted by the given method. - */ -OBJC_EXPORT unsigned int method_getNumberOfArguments(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a string describing a method's return type. - * - * @param m The method to inspect. - * - * @return A C string describing the return type. You must free the string with \c free(). - */ -OBJC_EXPORT char *method_copyReturnType(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a string describing a single parameter type of a method. - * - * @param m The method to inspect. - * @param index The index of the parameter to inspect. - * - * @return A C string describing the type of the parameter at index \e index, or \c NULL - * if method has no parameter index \e index. You must free the string with \c free(). - */ -OBJC_EXPORT char *method_copyArgumentType(Method m, unsigned int index) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns by reference a string describing a method's return type. - * - * @param m The method you want to inquire about. - * @param dst The reference string to store the description. - * @param dst_len The maximum number of characters that can be stored in \e dst. - * - * @note The method's return type string is copied to \e dst. - * \e dst is filled as if \c strncpy(dst, parameter_type, dst_len) were called. - */ -OBJC_EXPORT void method_getReturnType(Method m, char *dst, size_t dst_len) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns by reference a string describing a single parameter type of a method. - * - * @param m The method you want to inquire about. - * @param index The index of the parameter you want to inquire about. - * @param dst The reference string to store the description. - * @param dst_len The maximum number of characters that can be stored in \e dst. - * - * @note The parameter type string is copied to \e dst. \e dst is filled as if \c strncpy(dst, parameter_type, dst_len) - * were called. If the method contains no parameter with that index, \e dst is filled as - * if \c strncpy(dst, "", dst_len) were called. - */ -OBJC_EXPORT void method_getArgumentType(Method m, unsigned int index, - char *dst, size_t dst_len) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); -OBJC_EXPORT struct objc_method_description *method_getDescription(Method m) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the implementation of a method. - * - * @param m The method for which to set an implementation. - * @param imp The implemention to set to this method. - * - * @return The previous implementation of the method. - */ -OBJC_EXPORT IMP method_setImplementation(Method m, IMP imp) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Exchanges the implementations of two methods. - * - * @param m1 Method to exchange with second method. - * @param m2 Method to exchange with first method. - * - * @note This is an atomic version of the following: - * \code - * IMP imp1 = method_getImplementation(m1); - * IMP imp2 = method_getImplementation(m2); - * method_setImplementation(m1, imp2); - * method_setImplementation(m2, imp1); - * \endcode - */ -OBJC_EXPORT void method_exchangeImplementations(Method m1, Method m2) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Working with Instance Variables */ - -/** - * Returns the name of an instance variable. - * - * @param v The instance variable you want to enquire about. - * - * @return A C string containing the instance variable's name. - */ -OBJC_EXPORT const char *ivar_getName(Ivar v) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the type string of an instance variable. - * - * @param v The instance variable you want to enquire about. - * - * @return A C string containing the instance variable's type encoding. - * - * @note For possible values, see Objective-C Runtime Programming Guide > Type Encodings. - */ -OBJC_EXPORT const char *ivar_getTypeEncoding(Ivar v) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the offset of an instance variable. - * - * @param v The instance variable you want to enquire about. - * - * @return The offset of \e v. - * - * @note For instance variables of type \c id or other object types, call \c object_getIvar - * and \c object_setIvar instead of using this offset to access the instance variable data directly. - */ -OBJC_EXPORT ptrdiff_t ivar_getOffset(Ivar v) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Working with Properties */ - -/** - * Returns the name of a property. - * - * @param property The property you want to inquire about. - * - * @return A C string containing the property's name. - */ -OBJC_EXPORT const char *property_getName(objc_property_t property) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the attribute string of a property. - * - * @param property A property. - * - * @return A C string containing the property's attributes. - * - * @note The format of the attribute string is described in Declared Properties in Objective-C Runtime Programming Guide. - */ -OBJC_EXPORT const char *property_getAttributes(objc_property_t property) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of property attributes for a property. - * - * @param property The property whose attributes you want copied. - * @param outCount The number of attributes returned in the array. - * - * @return An array of property attributes; must be free'd() by the caller. - */ -OBJC_EXPORT objc_property_attribute_t *property_copyAttributeList(objc_property_t property, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Returns the value of a property attribute given the attribute name. - * - * @param property The property whose attribute value you are interested in. - * @param attributeName C string representing the attribute name. - * - * @return The value string of the attribute \e attributeName if it exists in - * \e property, \c nil otherwise. - */ -OBJC_EXPORT char *property_copyAttributeValue(objc_property_t property, const char *attributeName) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - - -/* Working with Protocols */ - -/** - * Returns a specified protocol. - * - * @param name The name of a protocol. - * - * @return The protocol named \e name, or \c NULL if no protocol named \e name could be found. - * - * @note This function acquires the runtime lock. - */ -OBJC_EXPORT Protocol *objc_getProtocol(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of all the protocols known to the runtime. - * - * @param outCount Upon return, contains the number of protocols in the returned array. - * - * @return A C array of all the protocols known to the runtime. The array contains \c *outCount - * pointers followed by a \c NULL terminator. You must free the list with \c free(). - * - * @note This function acquires the runtime lock. - */ -OBJC_EXPORT Protocol * __unsafe_unretained *objc_copyProtocolList(unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether one protocol conforms to another protocol. - * - * @param proto A protocol. - * @param other A protocol. - * - * @return \c YES if \e proto conforms to \e other, otherwise \c NO. - * - * @note One protocol can incorporate other protocols using the same syntax - * that classes use to adopt a protocol: - * \code - * @protocol ProtocolName < protocol list > - * \endcode - * All the protocols listed between angle brackets are considered part of the ProtocolName protocol. - */ -OBJC_EXPORT BOOL protocol_conformsToProtocol(Protocol *proto, Protocol *other) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether two protocols are equal. - * - * @param proto A protocol. - * @param other A protocol. - * - * @return \c YES if \e proto is the same as \e other, otherwise \c NO. - */ -OBJC_EXPORT BOOL protocol_isEqual(Protocol *proto, Protocol *other) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the name of a protocol. - * - * @param p A protocol. - * - * @return The name of the protocol \e p as a C string. - */ -OBJC_EXPORT const char *protocol_getName(Protocol *p) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns a method description structure for a specified method of a given protocol. - * - * @param p A protocol. - * @param aSel A selector. - * @param isRequiredMethod A Boolean value that indicates whether aSel is a required method. - * @param isInstanceMethod A Boolean value that indicates whether aSel is an instance method. - * - * @return An \c objc_method_description structure that describes the method specified by \e aSel, - * \e isRequiredMethod, and \e isInstanceMethod for the protocol \e p. - * If the protocol does not contain the specified method, returns an \c objc_method_description structure - * with the value \c {NULL, \c NULL}. - * - * @note This function recursively searches any protocols that this protocol conforms to. - */ -OBJC_EXPORT struct objc_method_description protocol_getMethodDescription(Protocol *p, SEL aSel, BOOL isRequiredMethod, BOOL isInstanceMethod) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of method descriptions of methods meeting a given specification for a given protocol. - * - * @param p A protocol. - * @param isRequiredMethod A Boolean value that indicates whether returned methods should - * be required methods (pass YES to specify required methods). - * @param isInstanceMethod A Boolean value that indicates whether returned methods should - * be instance methods (pass YES to specify instance methods). - * @param outCount Upon return, contains the number of method description structures in the returned array. - * - * @return A C array of \c objc_method_description structures containing the names and types of \e p's methods - * specified by \e isRequiredMethod and \e isInstanceMethod. The array contains \c *outCount pointers followed - * by a \c NULL terminator. You must free the list with \c free(). - * If the protocol declares no methods that meet the specification, \c NULL is returned and \c *outCount is 0. - * - * @note Methods in other protocols adopted by this protocol are not included. - */ -OBJC_EXPORT struct objc_method_description *protocol_copyMethodDescriptionList(Protocol *p, BOOL isRequiredMethod, BOOL isInstanceMethod, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the specified property of a given protocol. - * - * @param proto A protocol. - * @param name The name of a property. - * @param isRequiredProperty A Boolean value that indicates whether name is a required property. - * @param isInstanceProperty A Boolean value that indicates whether name is a required property. - * - * @return The property specified by \e name, \e isRequiredProperty, and \e isInstanceProperty for \e proto, - * or \c NULL if none of \e proto's properties meets the specification. - */ -OBJC_EXPORT objc_property_t protocol_getProperty(Protocol *proto, const char *name, BOOL isRequiredProperty, BOOL isInstanceProperty) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of the properties declared by a protocol. - * - * @param proto A protocol. - * @param outCount Upon return, contains the number of elements in the returned array. - * - * @return A C array of pointers of type \c objc_property_t describing the properties declared by \e proto. - * Any properties declared by other protocols adopted by this protocol are not included. The array contains - * \c *outCount pointers followed by a \c NULL terminator. You must free the array with \c free(). - * If the protocol declares no properties, \c NULL is returned and \c *outCount is \c 0. - */ -OBJC_EXPORT objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns an array of the protocols adopted by a protocol. - * - * @param proto A protocol. - * @param outCount Upon return, contains the number of elements in the returned array. - * - * @return A C array of protocols adopted by \e proto. The array contains \e *outCount pointers - * followed by a \c NULL terminator. You must free the array with \c free(). - * If the protocol declares no properties, \c NULL is returned and \c *outCount is \c 0. - */ -OBJC_EXPORT Protocol * __unsafe_unretained *protocol_copyProtocolList(Protocol *proto, unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Creates a new protocol instance that cannot be used until registered with - * \c objc_registerProtocol() - * - * @param name The name of the protocol to create. - * - * @return The Protocol instance on success, \c nil if a protocol - * with the same name already exists. - * @note There is no dispose method for this. - */ -OBJC_EXPORT Protocol *objc_allocateProtocol(const char *name) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Registers a newly constructed protocol with the runtime. The protocol - * will be ready for use and is immutable after this. - * - * @param proto The protocol you want to register. - */ -OBJC_EXPORT void objc_registerProtocol(Protocol *proto) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Adds a method to a protocol. The protocol must be under construction. - * - * @param proto The protocol to add a method to. - * @param name The name of the method to add. - * @param types A C string that represents the method signature. - * @param isRequiredMethod YES if the method is not an optional method. - * @param isInstanceMethod YES if the method is an instance method. - */ -OBJC_EXPORT void protocol_addMethodDescription(Protocol *proto, SEL name, const char *types, BOOL isRequiredMethod, BOOL isInstanceMethod) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Adds an incorporated protocol to another protocol. The protocol being - * added to must still be under construction, while the additional protocol - * must be already constructed. - * - * @param proto The protocol you want to add to, it must be under construction. - * @param addition The protocol you want to incorporate into \e proto, it must be registered. - */ -OBJC_EXPORT void protocol_addProtocol(Protocol *proto, Protocol *addition) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Adds a property to a protocol. The protocol must be under construction. - * - * @param proto The protocol to add a property to. - * @param name The name of the property. - * @param attributes An array of property attributes. - * @param attributeCount The number of attributes in \e attributes. - * @param isRequiredProperty YES if the property (accessor methods) is not optional. - * @param isInstanceProperty YES if the property (accessor methods) are instance methods. - * This is the only case allowed fo a property, as a result, setting this to NO will - * not add the property to the protocol at all. - */ -OBJC_EXPORT void protocol_addProperty(Protocol *proto, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount, BOOL isRequiredProperty, BOOL isInstanceProperty) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - - -/* Working with Libraries */ - -/** - * Returns the names of all the loaded Objective-C frameworks and dynamic - * libraries. - * - * @param outCount The number of names returned. - * - * @return An array of C strings of names. Must be free()'d by caller. - */ -OBJC_EXPORT const char **objc_copyImageNames(unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the dynamic library name a class originated from. - * - * @param cls The class you are inquiring about. - * - * @return The name of the library containing this class. - */ -OBJC_EXPORT const char *class_getImageName(Class cls) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Returns the names of all the classes within a library. - * - * @param image The library or framework you are inquiring about. - * @param outCount The number of class names returned. - * - * @return An array of C strings representing the class names. - */ -OBJC_EXPORT const char **objc_copyClassNamesForImage(const char *image, - unsigned int *outCount) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Working with Selectors */ - -/** - * Returns the name of the method specified by a given selector. - * - * @param sel A pointer of type \c SEL. Pass the selector whose name you wish to determine. - * - * @return A C string indicating the name of the selector. - */ -OBJC_EXPORT const char *sel_getName(SEL sel) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Registers a method name with the Objective-C runtime system. - * - * @param str A pointer to a C string. Pass the name of the method you wish to register. - * - * @return A pointer of type SEL specifying the selector for the named method. - * - * @note The implementation of this method is identical to the implementation of \c sel_registerName. - * @note Prior to OS X version 10.0, this method tried to find the selector mapped to the given name - * and returned \c NULL if the selector was not found. This was changed for safety, because it was - * observed that many of the callers of this function did not check the return value for \c NULL. - */ -OBJC_EXPORT SEL sel_getUid(const char *str) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Registers a method with the Objective-C runtime system, maps the method - * name to a selector, and returns the selector value. - * - * @param str A pointer to a C string. Pass the name of the method you wish to register. - * - * @return A pointer of type SEL specifying the selector for the named method. - * - * @note You must register a method name with the Objective-C runtime system to obtain the - * method’s selector before you can add the method to a class definition. If the method name - * has already been registered, this function simply returns the selector. - */ -OBJC_EXPORT SEL sel_registerName(const char *str) - __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); - -/** - * Returns a Boolean value that indicates whether two selectors are equal. - * - * @param lhs The selector to compare with rhs. - * @param rhs The selector to compare with lhs. - * - * @return \c YES if \e rhs and \e rhs are equal, otherwise \c NO. - * - * @note sel_isEqual is equivalent to ==. - */ -OBJC_EXPORT BOOL sel_isEqual(SEL lhs, SEL rhs) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - - -/* Objective-C Language Features */ - -/** - * This function is inserted by the compiler when a mutation - * is detected during a foreach iteration. It gets called - * when a mutation occurs, and the enumerationMutationHandler - * is enacted if it is set up. A fatal error occurs if a handler is not set up. - * - * @param obj The object being mutated. - * - */ -OBJC_EXPORT void objc_enumerationMutation(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Sets the current mutation handler. - * - * @param handler Function pointer to the new mutation handler. - */ -OBJC_EXPORT void objc_setEnumerationMutationHandler(void (*handler)(id)) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Set the function to be called by objc_msgForward. - * - * @param fwd Function to be jumped to by objc_msgForward. - * @param fwd_stret Function to be jumped to by objc_msgForward_stret. - * - * @see message.h::_objc_msgForward - */ -OBJC_EXPORT void objc_setForwardHandler(void *fwd, void *fwd_stret) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0); - -/** - * Creates a pointer to a function that will call the block - * when the method is called. - * - * @param block The block that implements this method. Its signature should - * be: method_return_type ^(id self, method_args...). - * The selector is not available as a parameter to this block. - * The block is copied with \c Block_copy(). - * - * @return The IMP that calls this block. Must be disposed of with - * \c imp_removeBlock. - */ -OBJC_EXPORT IMP imp_implementationWithBlock(id block) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Return the block associated with an IMP that was created using - * \c imp_implementationWithBlock. - * - * @param anImp The IMP that calls this block. - * - * @return The block called by \e anImp. - */ -OBJC_EXPORT id imp_getBlock(IMP anImp) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * Disassociates a block from an IMP that was created using - * \c imp_implementationWithBlock and releases the copy of the - * block that was created. - * - * @param anImp An IMP that was created using \c imp_implementationWithBlock. - * - * @return YES if the block was released successfully, NO otherwise. - * (For example, the block might not have been used to create an IMP previously). - */ -OBJC_EXPORT BOOL imp_removeBlock(IMP anImp) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); - -/** - * This loads the object referenced by a weak pointer and returns it, after - * retaining and autoreleasing the object to ensure that it stays alive - * long enough for the caller to use it. This function would be used - * anywhere a __weak variable is used in an expression. - * - * @param location The weak pointer address - * - * @return The object pointed to by \e location, or \c nil if \e location is \c nil. - */ -OBJC_EXPORT id objc_loadWeak(id *location) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -/** - * This function stores a new value into a __weak variable. It would - * be used anywhere a __weak variable is the target of an assignment. - * - * @param location The address of the weak pointer itself - * @param obj The new object this weak ptr should now point to - * - * @return The value stored into \e location, i.e. \e obj - */ -OBJC_EXPORT id objc_storeWeak(id *location, id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - - -/* Associative References */ - -/** - * Policies related to associative references. - * These are options to objc_setAssociatedObject() - */ -typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) { - OBJC_ASSOCIATION_ASSIGN = 0, /**< Specifies a weak reference to the associated object. */ - OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. - * The association is not made atomically. */ - OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied. - * The association is not made atomically. */ - OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object. - * The association is made atomically. */ - OBJC_ASSOCIATION_COPY = 01403 /**< Specifies that the associated object is copied. - * The association is made atomically. */ -}; - -/** - * Sets an associated value for a given object using a given key and association policy. - * - * @param object The source object for the association. - * @param key The key for the association. - * @param value The value to associate with the key key for object. Pass nil to clear an existing association. - * @param policy The policy for the association. For possible values, see “Associative Object Behaviors.” - * - * @see objc_setAssociatedObject - * @see objc_removeAssociatedObjects - */ -OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); - -/** - * Returns the value associated with a given object for a given key. - * - * @param object The source object for the association. - * @param key The key for the association. - * - * @return The value associated with the key \e key for \e object. - * - * @see objc_setAssociatedObject - */ -OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); - -/** - * Removes all associations for a given object. - * - * @param object An object that maintains associated objects. - * - * @note The main purpose of this function is to make it easy to return an object - * to a "pristine state”. You should not use this function for general removal of - * associations from objects, since it also removes associations that other clients - * may have added to the object. Typically you should use \c objc_setAssociatedObject - * with a nil value to clear an association. - * - * @see objc_setAssociatedObject - * @see objc_getAssociatedObject - */ -OBJC_EXPORT void objc_removeAssociatedObjects(id object) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1); - - -#define _C_ID '@' -#define _C_CLASS '#' -#define _C_SEL ':' -#define _C_CHR 'c' -#define _C_UCHR 'C' -#define _C_SHT 's' -#define _C_USHT 'S' -#define _C_INT 'i' -#define _C_UINT 'I' -#define _C_LNG 'l' -#define _C_ULNG 'L' -#define _C_LNG_LNG 'q' -#define _C_ULNG_LNG 'Q' -#define _C_FLT 'f' -#define _C_DBL 'd' -#define _C_BFLD 'b' -#define _C_BOOL 'B' -#define _C_VOID 'v' -#define _C_UNDEF '?' -#define _C_PTR '^' -#define _C_CHARPTR '*' -#define _C_ATOM '%' -#define _C_ARY_B '[' -#define _C_ARY_E ']' -#define _C_UNION_B '(' -#define _C_UNION_E ')' -#define _C_STRUCT_B '{' -#define _C_STRUCT_E '}' -#define _C_VECTOR '!' -#define _C_CONST 'r' - - -/* Obsolete types */ - -#if !__OBJC2__ - -#define CLS_GETINFO(cls,infomask) ((cls)->info & (infomask)) -#define CLS_SETINFO(cls,infomask) ((cls)->info |= (infomask)) - -// class is not a metaclass -#define CLS_CLASS 0x1 -// class is a metaclass -#define CLS_META 0x2 -// class's +initialize method has completed -#define CLS_INITIALIZED 0x4 -// class is posing -#define CLS_POSING 0x8 -// unused -#define CLS_MAPPED 0x10 -// class and subclasses need cache flush during image loading -#define CLS_FLUSH_CACHE 0x20 -// method cache should grow when full -#define CLS_GROW_CACHE 0x40 -// unused -#define CLS_NEED_BIND 0x80 -// methodLists is array of method lists -#define CLS_METHOD_ARRAY 0x100 -// the JavaBridge constructs classes with these markers -#define CLS_JAVA_HYBRID 0x200 -#define CLS_JAVA_CLASS 0x400 -// thread-safe +initialize -#define CLS_INITIALIZING 0x800 -// bundle unloading -#define CLS_FROM_BUNDLE 0x1000 -// C++ ivar support -#define CLS_HAS_CXX_STRUCTORS 0x2000 -// Lazy method list arrays -#define CLS_NO_METHOD_ARRAY 0x4000 -// +load implementation -#define CLS_HAS_LOAD_METHOD 0x8000 -// objc_allocateClassPair API -#define CLS_CONSTRUCTING 0x10000 -// class compiled with bigger class structure -#define CLS_EXT 0x20000 - - -struct objc_method_description_list { - int count; - struct objc_method_description list[1]; -}; - - -struct objc_protocol_list { - struct objc_protocol_list *next; - long count; - Protocol *list[1]; -}; - - -struct objc_category { - char *category_name OBJC2_UNAVAILABLE; - char *class_name OBJC2_UNAVAILABLE; - struct objc_method_list *instance_methods OBJC2_UNAVAILABLE; - struct objc_method_list *class_methods OBJC2_UNAVAILABLE; - struct objc_protocol_list *protocols OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - - -struct objc_ivar { - char *ivar_name OBJC2_UNAVAILABLE; - char *ivar_type OBJC2_UNAVAILABLE; - int ivar_offset OBJC2_UNAVAILABLE; -#ifdef __LP64__ - int space OBJC2_UNAVAILABLE; -#endif -} OBJC2_UNAVAILABLE; - -struct objc_ivar_list { - int ivar_count OBJC2_UNAVAILABLE; -#ifdef __LP64__ - int space OBJC2_UNAVAILABLE; -#endif - /* variable length structure */ - struct objc_ivar ivar_list[1] OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - - -struct objc_method { - SEL method_name OBJC2_UNAVAILABLE; - char *method_types OBJC2_UNAVAILABLE; - IMP method_imp OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - -struct objc_method_list { - struct objc_method_list *obsolete OBJC2_UNAVAILABLE; - - int method_count OBJC2_UNAVAILABLE; -#ifdef __LP64__ - int space OBJC2_UNAVAILABLE; -#endif - /* variable length structure */ - struct objc_method method_list[1] OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - - -typedef struct objc_symtab *Symtab OBJC2_UNAVAILABLE; - -struct objc_symtab { - unsigned long sel_ref_cnt OBJC2_UNAVAILABLE; - SEL *refs OBJC2_UNAVAILABLE; - unsigned short cls_def_cnt OBJC2_UNAVAILABLE; - unsigned short cat_def_cnt OBJC2_UNAVAILABLE; - void *defs[1] /* variable size */ OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - - -typedef struct objc_cache *Cache OBJC2_UNAVAILABLE; - -#define CACHE_BUCKET_NAME(B) ((B)->method_name) -#define CACHE_BUCKET_IMP(B) ((B)->method_imp) -#define CACHE_BUCKET_VALID(B) (B) -#ifndef __LP64__ -#define CACHE_HASH(sel, mask) (((uintptr_t)(sel)>>2) & (mask)) -#else -#define CACHE_HASH(sel, mask) (((unsigned int)((uintptr_t)(sel)>>3)) & (mask)) -#endif -struct objc_cache { - unsigned int mask /* total = mask + 1 */ OBJC2_UNAVAILABLE; - unsigned int occupied OBJC2_UNAVAILABLE; - Method buckets[1] OBJC2_UNAVAILABLE; -}; - - -typedef struct objc_module *Module OBJC2_UNAVAILABLE; - -struct objc_module { - unsigned long version OBJC2_UNAVAILABLE; - unsigned long size OBJC2_UNAVAILABLE; - const char *name OBJC2_UNAVAILABLE; - Symtab symtab OBJC2_UNAVAILABLE; -} OBJC2_UNAVAILABLE; - -#else - -struct objc_method_list; - -#endif - - -/* Obsolete functions */ - -OBJC_EXPORT IMP class_lookupMethod(Class cls, SEL sel) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); -OBJC_EXPORT BOOL class_respondsToMethod(Class cls, SEL sel) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); -OBJC_EXPORT void _objc_flush_caches(Class cls) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_2_0,__IPHONE_2_0); - -OBJC_EXPORT id object_copyFromZone(id anObject, size_t nBytes, void *z) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_NA,__IPHONE_NA) - OBJC_ARC_UNAVAILABLE; -OBJC_EXPORT id object_realloc(id anObject, size_t nBytes) OBJC2_UNAVAILABLE; -OBJC_EXPORT id object_reallocFromZone(id anObject, size_t nBytes, void *z) OBJC2_UNAVAILABLE; - -#define OBSOLETE_OBJC_GETCLASSES 1 -OBJC_EXPORT void *objc_getClasses(void) OBJC2_UNAVAILABLE; -OBJC_EXPORT void objc_addClass(Class myClass) OBJC2_UNAVAILABLE; -OBJC_EXPORT void objc_setClassHandler(int (*)(const char *)) OBJC2_UNAVAILABLE; -OBJC_EXPORT void objc_setMultithreaded (BOOL flag) OBJC2_UNAVAILABLE; - -OBJC_EXPORT id class_createInstanceFromZone(Class, size_t idxIvars, void *z) - __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0,__MAC_10_5, __IPHONE_NA,__IPHONE_NA) - OBJC_ARC_UNAVAILABLE; - -OBJC_EXPORT void class_addMethods(Class, struct objc_method_list *) OBJC2_UNAVAILABLE; -OBJC_EXPORT void class_removeMethods(Class, struct objc_method_list *) OBJC2_UNAVAILABLE; -OBJC_EXPORT void _objc_resolve_categories_for_class(Class cls) OBJC2_UNAVAILABLE; - -OBJC_EXPORT Class class_poseAs(Class imposter, Class original) OBJC2_UNAVAILABLE; - -OBJC_EXPORT unsigned int method_getSizeOfArguments(Method m) OBJC2_UNAVAILABLE; -OBJC_EXPORT unsigned method_getArgumentInfo(struct objc_method *m, int arg, const char **type, int *offset) OBJC2_UNAVAILABLE; - -OBJC_EXPORT Class objc_getOrigClass(const char *name) OBJC2_UNAVAILABLE; -#define OBJC_NEXT_METHOD_LIST 1 -OBJC_EXPORT struct objc_method_list *class_nextMethodList(Class, void **) OBJC2_UNAVAILABLE; -// usage for nextMethodList -// -// void *iterator = 0; -// struct objc_method_list *mlist; -// while ( mlist = class_nextMethodList( cls, &iterator ) ) -// ; - -OBJC_EXPORT id (*_alloc)(Class, size_t) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_copy)(id, size_t) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_realloc)(id, size_t) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_dealloc)(id) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_zoneAlloc)(Class, size_t, void *) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_zoneRealloc)(id, size_t, void *) OBJC2_UNAVAILABLE; -OBJC_EXPORT id (*_zoneCopy)(id, size_t, void *) OBJC2_UNAVAILABLE; -OBJC_EXPORT void (*_error)(id, const char *, va_list) OBJC2_UNAVAILABLE; - -#endif diff --git a/objc/objc-runtime/test/ARRBase.h b/objc/objc-runtime/test/ARRBase.h deleted file mode 100644 index 81b8fed..0000000 --- a/objc/objc-runtime/test/ARRBase.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// ARRBase.h -// TestARRLayouts -// -// Created by Patrick Beard on 3/8/11. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import <Foundation/NSObject.h> - -@interface ARRBase : NSObject -@property long number; -@property(retain) id object; -@property void *pointer; -@property(weak) __weak id delegate; -@end diff --git a/objc/objc-runtime/test/ARRBase.m b/objc/objc-runtime/test/ARRBase.m deleted file mode 100644 index 737f1c6..0000000 --- a/objc/objc-runtime/test/ARRBase.m +++ /dev/null @@ -1,24 +0,0 @@ -// -// ARRBase.m -// TestARRLayouts -// -// Created by Patrick Beard on 3/8/11. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import "ARRBase.h" - -#if 1 -@interface ARRBase () { -@private - long number; - id object; - void *pointer; - __weak id delegate; -} -@end -#endif - -@implementation ARRBase -@synthesize number, object, pointer, delegate; -@end diff --git a/objc/objc-runtime/test/ARRLayouts.m b/objc/objc-runtime/test/ARRLayouts.m deleted file mode 100644 index 5db5213..0000000 --- a/objc/objc-runtime/test/ARRLayouts.m +++ /dev/null @@ -1,99 +0,0 @@ -/* -TEST_CONFIG MEM=arc CC=clang -TEST_BUILD - $C{COMPILE_NOLINK_NOMEM} -c $DIR/MRRBase.m - $C{COMPILE_NOLINK_NOMEM} -c $DIR/MRRARR.m - $C{COMPILE_NOLINK} -c $DIR/ARRBase.m - $C{COMPILE_NOLINK} -c $DIR/ARRMRR.m - $C{COMPILE} -fobjc-arc $DIR/ARRLayouts.m -x none MRRBase.o MRRARR.o ARRBase.o ARRMRR.o -framework Foundation -o ARRLayouts.out -END -*/ - -#include "test.h" -#import <stdio.h> -#import <Foundation/Foundation.h> -#import <objc/runtime.h> - -#import "ARRMRR.h" -#import "MRRARR.h" - -@interface NSObject (Layouts) -+ (const char *)strongLayout; -+ (const char *)weakLayout; -@end - -void printlayout(const char *name, const uint8_t *layout) -{ - if (! getenv("VERBOSE")) return; - - testprintf("%s: ", name); - - if (!layout) { - fprintf(stderr, "NULL\n"); - return; - } - - const uint8_t *c; - for (c = layout; *c; c++) { - fprintf(stderr, "%02x ", *c); - } - - fprintf(stderr, "00\n"); -} - -@implementation NSObject (Layouts) - -+ (const char *)strongLayout { - const uint8_t *layout = class_getIvarLayout(self); - printlayout("strong", layout); - return (const char *)layout; -} - -+ (const char *)weakLayout { - const uint8_t *weakLayout = class_getWeakIvarLayout(self); - printlayout("weak", weakLayout); - return (const char *)weakLayout; -} - -+ (Ivar)instanceVariable:(const char *)name { - return class_getInstanceVariable(self, name); -} - -@end - -int main (int argc __unused, const char * argv[] __unused) { - // Under ARR, layout strings are relative to the class' own ivars. - testassert(strcmp([ARRBase strongLayout], "\x11\x20") == 0); - testassert(strcmp([ARRBase weakLayout], "\x31") == 0); - testassert([MRRBase strongLayout] == NULL); - testassert([MRRBase weakLayout] == NULL); - testassert(strcmp([ARRMRR strongLayout], "\x01") == 0); - testassert([ARRMRR weakLayout] == NULL); - testassert([MRRARR strongLayout] == NULL); - testassert([MRRARR weakLayout] == NULL); - - // now check consistency between dynamic accessors and KVC, etc. - ARRMRR *am = [ARRMRR new]; - MRRARR *ma = [MRRARR new]; - - NSString *am_description = [[NSString alloc] initWithFormat:@"%s %p", "ARRMRR", am]; - NSString *ma_description = [[NSString alloc] initWithFormat:@"%s %p", "MRRARR", ma]; - - am.number = M_PI; - object_setIvar(am, [ARRMRR instanceVariable:"object"], am_description); - testassert(CFGetRetainCount(objc_unretainedPointer(am_description)) == 1); - am.pointer = @selector(ARRMRR); - object_setIvar(am, [ARRMRR instanceVariable:"delegate"], ma); - testassert(CFGetRetainCount(objc_unretainedPointer(ma)) == 1); - - ma.number = M_E; - object_setIvar(ma, [MRRARR instanceVariable:"object"], ma_description); - testassert(CFGetRetainCount(objc_unretainedPointer(ma_description)) == 2); - ma.pointer = @selector(MRRARR); - ma.delegate = am; - object_setIvar(ma, [MRRARR instanceVariable:"delegate"], am); - testassert(CFGetRetainCount(objc_unretainedPointer(am)) == 1); - - succeed(__FILE__); - return 0; -} diff --git a/objc/objc-runtime/test/ARRMRR.h b/objc/objc-runtime/test/ARRMRR.h deleted file mode 100644 index 8029eed..0000000 --- a/objc/objc-runtime/test/ARRMRR.h +++ /dev/null @@ -1,13 +0,0 @@ -// -// ARRMRR.h -// TestARRLayouts -// -// Created by Patrick Beard on 3/8/11. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import "MRRBase.h" - -@interface ARRMRR : MRRBase -@property(retain) id dataSource; -@end diff --git a/objc/objc-runtime/test/ARRMRR.m b/objc/objc-runtime/test/ARRMRR.m deleted file mode 100644 index ce0b7a6..0000000 --- a/objc/objc-runtime/test/ARRMRR.m +++ /dev/null @@ -1,11 +0,0 @@ -// -// ARRMRR.m -// - -#import "ARRMRR.h" - -@implementation ARRMRR - -@synthesize dataSource; - -@end diff --git a/objc/objc-runtime/test/MRRARR.h b/objc/objc-runtime/test/MRRARR.h deleted file mode 100644 index 275ae2f..0000000 --- a/objc/objc-runtime/test/MRRARR.h +++ /dev/null @@ -1,13 +0,0 @@ -// -// MRRARR.h -// TestARRLayouts -// -// Created by Patrick Beard on 3/8/11. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import "ARRBase.h" - -@interface MRRARR : ARRBase -@property(retain) id dataSource; -@end diff --git a/objc/objc-runtime/test/MRRARR.m b/objc/objc-runtime/test/MRRARR.m deleted file mode 100644 index fa32a34..0000000 --- a/objc/objc-runtime/test/MRRARR.m +++ /dev/null @@ -1,11 +0,0 @@ -// -// MRRARR.m -// - -#import "MRRARR.h" - -@implementation MRRARR - -@synthesize dataSource; - -@end diff --git a/objc/objc-runtime/test/MRRBase.h b/objc/objc-runtime/test/MRRBase.h deleted file mode 100644 index c339f61..0000000 --- a/objc/objc-runtime/test/MRRBase.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// MRRBase.h -// TestARRLayouts -// -// Created by Patrick Beard on 3/8/11. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import <Foundation/NSObject.h> - -@interface MRRBase : NSObject -@property double number; -@property(retain) id object; -@property void *pointer; -@property(weak) __weak id delegate; -@end diff --git a/objc/objc-runtime/test/MRRBase.m b/objc/objc-runtime/test/MRRBase.m deleted file mode 100644 index 5720dcc..0000000 --- a/objc/objc-runtime/test/MRRBase.m +++ /dev/null @@ -1,24 +0,0 @@ -// -// MRRBase.m -// TestARRLayouts -// -// Created by Patrick Beard on 3/8/11. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import "MRRBase.h" - -#if 1 -@interface MRRBase () { -@private - double number; - id object; - void *pointer; - __weak id delegate; -} -@end -#endif - -@implementation MRRBase -@synthesize number, object, pointer, delegate; -@end diff --git a/objc/objc-runtime/test/Makefile b/objc/objc-runtime/test/Makefile deleted file mode 100644 index e5852e8..0000000 --- a/objc/objc-runtime/test/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# quick test -all: - perl test.pl $(MAKEFLAGS) - -# default-arch but otherwise comprehensive test for buildbot -buildbot: - perl test.pl $(MAKEFLAGS) MEM=mrc,arc,gc CC=clang LANGUAGE=objc,objc++ - -# comprehensive tests -mac macos macosx: - perl test.pl $(MAKEFLAGS) ARCH=x86_64,i386 MEM=mrc,arc,gc CC=clang LANGUAGE=objc,objc++ - -iphonesimulator: - perl test.pl $(MAKEFLAGS) ARCH=i386 SDK=iphonesimulator MEM=mrc,arc CC=clang LANGUAGE=objc,objc++ - -iphoneos: - perl test.pl $(MAKEFLAGS) ARCH=armv6,armv7 SDK=iphoneos MEM=mrc,arc CC=clang LANGUAGE=objc,objc++ - -clean: - @ perl test.pl clean diff --git a/objc/objc-runtime/test/accessors.m b/objc/objc-runtime/test/accessors.m deleted file mode 100644 index 9111e64..0000000 --- a/objc/objc-runtime/test/accessors.m +++ /dev/null @@ -1,79 +0,0 @@ -// TEST_CFLAGS -framework Foundation - -#import <Foundation/Foundation.h> -#import <objc/runtime.h> -#import <objc/objc-abi.h> -#include "test.h" - -@interface Test : NSObject { - NSString *_value; - // _object is at the last optimized property offset - id _object __attribute__((aligned(64))); -} -@property(readonly) Class cls; -@property(copy) NSString *value; -@property(assign) id object; -@end - -typedef struct { - void *isa; - void *_value; - // _object is at the last optimized property offset - void *_object __attribute__((aligned(64))); -} TestDefs; - -@implementation Test - -// Question: why can't this code be automatically generated? - -#if !__has_feature(objc_arc) -- (void)dealloc { - self.value = nil; - self.object = nil; - [super dealloc]; -} -#endif - -- (Class)cls { return objc_getProperty(self, _cmd, 0, YES); } - -- (NSString*)value { return (NSString*) objc_getProperty(self, _cmd, offsetof(TestDefs, _value), YES); } -- (void)setValue:(NSString*)inValue { objc_setProperty(self, _cmd, offsetof(TestDefs, _value), inValue, YES, YES); } - -- (id)object { return objc_getProperty(self, _cmd, offsetof(TestDefs, _object), YES); } -- (void)setObject:(id)inObject { objc_setProperty(self, _cmd, offsetof(TestDefs, _object), inObject, YES, NO); } - -- (NSString *)description { - return [NSString stringWithFormat:@"value = %@, object = %@", self.value, self.object]; -} - -@end - -int main() { - PUSH_POOL { - - NSMutableString *value = [NSMutableString stringWithUTF8String:"test"]; - id object = [NSNumber numberWithInt:11]; - Test *t = AUTORELEASE([Test new]); - t.value = value; - [value setString:@"yuck"]; // mutate the string. - testassert(t.value != value); // must copy, since it was mutable. - testassert([t.value isEqualToString:@"test"]); - - Class testClass = [Test class]; - Class cls = t.cls; - testassert(testClass == cls); - cls = t.cls; - testassert(testClass == cls); - - t.object = object; - t.object = object; - - // NSLog(@"t.object = %@, t.value = %@", t.object, t.value); - // NSLog(@"t.object = %@, t.value = %@", t.object, t.value); // second call will optimized getters. - - } POP_POOL; - - succeed(__FILE__); - - return 0; -} diff --git a/objc/objc-runtime/test/accessors2.m b/objc/objc-runtime/test/accessors2.m deleted file mode 100644 index 3c21b9f..0000000 --- a/objc/objc-runtime/test/accessors2.m +++ /dev/null @@ -1,143 +0,0 @@ -// TEST_CONFIG MEM=mrc,arc - -#include "test.h" -#include <objc/runtime.h> -#include <objc/objc-abi.h> - -#include "testroot.i" - -@interface Base : TestRoot { - @public - id ivar; -} -@end -@implementation Base @end - -int main() -{ - SEL _cmd = @selector(foo); - Base *o = [Base new]; - ptrdiff_t offset = ivar_getOffset(class_getInstanceVariable([Base class], "ivar")); - testassert(offset == sizeof(id)); - - TestRoot *value = [TestRoot new]; - - // fixme test atomicity - - // Original setter API - - testprintf("original nonatomic retain\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty(o, _cmd, offset, value, NO/*atomic*/, NO/*copy*/); - testassert(TestRootRetain == 1); - testassert(TestRootCopyWithZone == 0); - testassert(TestRootMutableCopyWithZone == 0); - testassert(o->ivar == value); - - testprintf("original atomic retain\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty(o, _cmd, offset, value, YES/*atomic*/, NO/*copy*/); - testassert(TestRootRetain == 1); - testassert(TestRootCopyWithZone == 0); - testassert(TestRootMutableCopyWithZone == 0); - testassert(o->ivar == value); - - testprintf("original nonatomic copy\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty(o, _cmd, offset, value, NO/*atomic*/, YES/*copy*/); - testassert(TestRootRetain == 0); - testassert(TestRootCopyWithZone == 1); - testassert(TestRootMutableCopyWithZone == 0); - testassert(o->ivar && o->ivar != value); - - testprintf("original atomic copy\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty(o, _cmd, offset, value, YES/*atomic*/, YES/*copy*/); - testassert(TestRootRetain == 0); - testassert(TestRootCopyWithZone == 1); - testassert(TestRootMutableCopyWithZone == 0); - testassert(o->ivar && o->ivar != value); - - testprintf("original nonatomic mutablecopy\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty(o, _cmd, offset, value, NO/*atomic*/, 2/*copy*/); - testassert(TestRootRetain == 0); - testassert(TestRootCopyWithZone == 0); - testassert(TestRootMutableCopyWithZone == 1); - testassert(o->ivar && o->ivar != value); - - testprintf("original atomic mutablecopy\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty(o, _cmd, offset, value, YES/*atomic*/, 2/*copy*/); - testassert(TestRootRetain == 0); - testassert(TestRootCopyWithZone == 0); - testassert(TestRootMutableCopyWithZone == 1); - testassert(o->ivar && o->ivar != value); - - - // Optimized setter API - - testprintf("optimized nonatomic retain\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty_nonatomic(o, _cmd, value, offset); - testassert(TestRootRetain == 1); - testassert(TestRootCopyWithZone == 0); - testassert(TestRootMutableCopyWithZone == 0); - testassert(o->ivar == value); - - testprintf("optimized atomic retain\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty_atomic(o, _cmd, value, offset); - testassert(TestRootRetain == 1); - testassert(TestRootCopyWithZone == 0); - testassert(TestRootMutableCopyWithZone == 0); - testassert(o->ivar == value); - - testprintf("optimized nonatomic copy\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty_nonatomic_copy(o, _cmd, value, offset); - testassert(TestRootRetain == 0); - testassert(TestRootCopyWithZone == 1); - testassert(TestRootMutableCopyWithZone == 0); - testassert(o->ivar && o->ivar != value); - - testprintf("optimized atomic copy\n"); - o->ivar = nil; - TestRootRetain = 0; - TestRootCopyWithZone = 0; - TestRootMutableCopyWithZone = 0; - objc_setProperty_atomic_copy(o, _cmd, value, offset); - testassert(TestRootRetain == 0); - testassert(TestRootCopyWithZone == 1); - testassert(TestRootMutableCopyWithZone == 0); - testassert(o->ivar && o->ivar != value); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/addMethod.m b/objc/objc-runtime/test/addMethod.m deleted file mode 100644 index 0b1f96c..0000000 --- a/objc/objc-runtime/test/addMethod.m +++ /dev/null @@ -1,104 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <objc/runtime.h> - -@interface Super : TestRoot @end -@implementation Super --(int)superMethod { return 0; } --(int)bothMethod { return 0; } -@end - -@interface Sub : Super @end -@implementation Sub --(int)subMethod { return 0; } --(int)bothMethod { return 0; } -@end - -@interface Sub2 : Super @end -@implementation Sub2 --(int)subMethod { return 0; } --(int)bothMethod { return 0; } -@end - - -id fn(id self __attribute__((unused)), SEL cmd __attribute__((unused)), ...) { return nil; } - -int main() -{ - IMP superMethodFromSuper = class_getMethodImplementation([Super class], @selector(superMethod)); - IMP bothMethodFromSuper = class_getMethodImplementation([Super class], @selector(bothMethod)); - IMP subMethodFromSub = class_getMethodImplementation([Sub class], @selector(subMethod)); - IMP bothMethodFromSub = class_getMethodImplementation([Sub class], @selector(bothMethod)); - IMP subMethodFromSub2 = class_getMethodImplementation([Sub2 class], @selector(subMethod)); - IMP bothMethodFromSub2 = class_getMethodImplementation([Sub2 class], @selector(bothMethod)); - - testassert(superMethodFromSuper); - testassert(bothMethodFromSuper); - testassert(subMethodFromSub); - testassert(bothMethodFromSub); - testassert(subMethodFromSub2); - testassert(bothMethodFromSub2); - - BOOL ok; - IMP imp; - - // class_addMethod doesn't replace existing implementations - ok = class_addMethod([Super class], @selector(superMethod), (IMP)fn, NULL); - testassert(!ok); - testassert(class_getMethodImplementation([Super class], @selector(superMethod)) == superMethodFromSuper); - - // class_addMethod does override superclass implementations - ok = class_addMethod([Sub class], @selector(superMethod), (IMP)fn, NULL); - testassert(ok); - testassert(class_getMethodImplementation([Sub class], @selector(superMethod)) == (IMP)fn); - - // class_addMethod does add root implementations - ok = class_addMethod([Super class], @selector(superMethodNew2), (IMP)fn, NULL); - testassert(ok); - testassert(class_getMethodImplementation([Super class], @selector(superMethodNew2)) == (IMP)fn); - testassert(class_getMethodImplementation([Sub class], @selector(superMethodNew2)) == (IMP)fn); - - - // class_replaceMethod does add new implementations, - // returning NULL if super has an implementation - imp = class_replaceMethod([Sub2 class], @selector(superMethod), (IMP)fn, NULL); - testassert(imp == NULL); - testassert(class_getMethodImplementation([Sub2 class], @selector(superMethod)) == (IMP)fn); - - // class_replaceMethod does add new implementations, - // returning NULL if super has no implementation - imp = class_replaceMethod([Sub2 class], @selector(subMethodNew), (IMP)fn, NULL); - testassert(imp == NULL); - testassert(class_getMethodImplementation([Sub2 class], @selector(subMethodNew)) == (IMP)fn); - - // class_replaceMethod does add new implemetations - // returning NULL if there is no super class - imp = class_replaceMethod([Super class], @selector(superMethodNew), (IMP)fn, NULL); - testassert(imp == NULL); - testassert(class_getMethodImplementation([Super class], @selector(superMethodNew)) == (IMP)fn); - - - // class_replaceMethod does replace existing implementations, - // returning existing implementation (regardless of super) - imp = class_replaceMethod([Sub2 class], @selector(subMethod), (IMP)fn, NULL); - testassert(imp == subMethodFromSub2); - testassert(class_getMethodImplementation([Sub2 class], @selector(subMethod)) == (IMP)fn); - - // class_replaceMethod does replace existing implemetations, - // returning existing implementation (regardless of super) - imp = class_replaceMethod([Sub2 class], @selector(bothMethod), (IMP)fn, NULL); - testassert(imp == bothMethodFromSub2); - testassert(class_getMethodImplementation([Sub2 class], @selector(bothMethod)) == (IMP)fn); - - // class_replaceMethod does replace existing implemetations, - // returning existing implementation (regardless of super) - imp = class_replaceMethod([Super class], @selector(superMethod), (IMP)fn, NULL); - testassert(imp == superMethodFromSuper); - testassert(class_getMethodImplementation([Super class], @selector(superMethod)) == (IMP)fn); - - // fixme actually try calling them - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/addProtocol.m b/objc/objc-runtime/test/addProtocol.m deleted file mode 100644 index e95bc9a..0000000 --- a/objc/objc-runtime/test/addProtocol.m +++ /dev/null @@ -1,211 +0,0 @@ -/* -TEST_RUN_OUTPUT -objc\[\d+\]: protocol_addProtocol: added protocol 'EmptyProto' is still under construction! -objc\[\d+\]: objc_registerProtocol: protocol 'Proto1' was already registered! -objc\[\d+\]: protocol_addProtocol: modified protocol 'Proto1' is not under construction! -objc\[\d+\]: protocol_addMethodDescription: protocol 'Proto1' is not under construction! -objc\[\d+\]: objc_registerProtocol: protocol 'SuperProto' was already registered! -objc\[\d+\]: protocol_addProtocol: modified protocol 'SuperProto' is not under construction! -objc\[\d+\]: protocol_addMethodDescription: protocol 'SuperProto' is not under construction! -OK: addProtocol.m -END -*/ - -#include "test.h" - -#include <objc/runtime.h> - -@protocol SuperProto @end -@protocol SuperProto2 @end -@protocol UnrelatedProto @end - - -void Crash(id self, SEL _cmd) -{ - fail("%c[%s %s] called unexpectedly", - class_isMetaClass(object_getClass(self)) ? '+' : '-', - object_getClassName(self), sel_getName(_cmd)); -} - - -int main() -{ - Protocol *proto, *proto2; - Protocol * __unsafe_unretained *protolist; - struct objc_method_description *desclist; - objc_property_t *proplist; - unsigned int count; - - // If objc_registerProtocol() fails to preserve the retain count - // then ARC will deallocate Protocol objects too early. - class_replaceMethod(objc_getClass("Protocol"), - sel_registerName("dealloc"), (IMP)Crash, "v@:"); - class_replaceMethod(objc_getClass("__IncompleteProtocol"), - sel_registerName("dealloc"), (IMP)Crash, "v@:"); - - // make sure binary contains hard copies of these protocols - proto = @protocol(SuperProto); - proto = @protocol(SuperProto2); - - // Adding a protocol - - char *name = strdup("Proto1"); - proto = objc_allocateProtocol(name); - testassert(proto); - testassert(!objc_getProtocol(name)); - - protocol_addProtocol(proto, @protocol(SuperProto)); - protocol_addProtocol(proto, @protocol(SuperProto2)); - // no inheritance cycles - proto2 = objc_allocateProtocol("EmptyProto"); - protocol_addProtocol(proto, proto2); // fails - objc_registerProtocol(proto2); - protocol_addProtocol(proto, proto2); // succeeds - - char *types = strdup("@:"); - protocol_addMethodDescription(proto, @selector(ReqInst0), types, YES, YES); - protocol_addMethodDescription(proto, @selector(ReqInst1), types, YES, YES); - protocol_addMethodDescription(proto, @selector(ReqInst2), types, YES, YES); - protocol_addMethodDescription(proto, @selector(ReqInst3), types, YES, YES); - - protocol_addMethodDescription(proto, @selector(ReqClas0), types, YES, NO); - protocol_addMethodDescription(proto, @selector(ReqClas1), types, YES, NO); - protocol_addMethodDescription(proto, @selector(ReqClas2), types, YES, NO); - protocol_addMethodDescription(proto, @selector(ReqClas3), types, YES, NO); - - protocol_addMethodDescription(proto, @selector(OptInst0), types, NO, YES); - protocol_addMethodDescription(proto, @selector(OptInst1), types, NO, YES); - protocol_addMethodDescription(proto, @selector(OptInst2), types, NO, YES); - protocol_addMethodDescription(proto, @selector(OptInst3), types, NO, YES); - - protocol_addMethodDescription(proto, @selector(OptClas0), types, NO, NO); - protocol_addMethodDescription(proto, @selector(OptClas1), types, NO, NO); - protocol_addMethodDescription(proto, @selector(OptClas2), types, NO, NO); - protocol_addMethodDescription(proto, @selector(OptClas3), types, NO, NO); - - char *name0 = strdup("ReqInst0"); - char *name1 = strdup("ReqInst1"); - char *name2 = strdup("ReqInst2"); - char *name3 = strdup("ReqInst3"); - char *attrname = strdup("T"); - char *attrvalue = strdup("i"); - objc_property_attribute_t attrs[] = {{attrname, attrvalue}}; - int attrcount = sizeof(attrs) / sizeof(attrs[0]); - protocol_addProperty(proto, name0, attrs, attrcount, YES, YES); - protocol_addProperty(proto, name1, attrs, attrcount, YES, YES); - protocol_addProperty(proto, name2, attrs, attrcount, YES, YES); - protocol_addProperty(proto, name3, attrs, attrcount, YES, YES); - - objc_registerProtocol(proto); - testassert(0 == strcmp(protocol_getName(proto), "Proto1")); - - // Use of added protocols - - testassert(proto == objc_getProtocol("Proto1")); - strcpy(name, "XXXXXX"); // name is copied - testassert(0 == strcmp(protocol_getName(proto), "Proto1")); - - protolist = protocol_copyProtocolList(proto, &count); - testassert(protolist); - testassert(count == 3); - // note this order is not required - testassert(protolist[0] == @protocol(SuperProto) && - protolist[1] == @protocol(SuperProto2) && - protolist[2] == proto2); - free(protolist); - - testassert(protocol_conformsToProtocol(proto, proto2)); - testassert(protocol_conformsToProtocol(proto, @protocol(SuperProto))); - testassert(!protocol_conformsToProtocol(proto, @protocol(UnrelatedProto))); - - strcpy(types, "XX"); // types is copied - desclist = protocol_copyMethodDescriptionList(proto, YES, YES, &count); - testassert(desclist && count == 4); - testprintf("%p %p\n", desclist[0].name, @selector(ReqInst0)); - // testassert(desclist[0].name == @selector(ReqInst0)); - testassert(0 == strcmp(desclist[0].types, "@:")); - free(desclist); - desclist = protocol_copyMethodDescriptionList(proto, YES, NO, &count); - testassert(desclist && count == 4); - testassert(desclist[1].name == @selector(ReqClas1)); - testassert(0 == strcmp(desclist[1].types, "@:")); - free(desclist); - desclist = protocol_copyMethodDescriptionList(proto, NO, YES, &count); - testassert(desclist && count == 4); - testassert(desclist[2].name == @selector(OptInst2)); - testassert(0 == strcmp(desclist[2].types, "@:")); - free(desclist); - desclist = protocol_copyMethodDescriptionList(proto, NO, NO, &count); - testassert(desclist && count == 4); - testassert(desclist[3].name == @selector(OptClas3)); - testassert(0 == strcmp(desclist[3].types, "@:")); - free(desclist); - - strcpy(name0, "XXXXXXXX"); // name is copied - strcpy(name1, "XXXXXXXX"); // name is copied - strcpy(name2, "XXXXXXXX"); // name is copied - strcpy(name3, "XXXXXXXX"); // name is copied - strcpy(attrname, "X"); // description is copied - strcpy(attrvalue, "X"); // description is copied - memset(attrs, 'X', sizeof(attrs)); // description is copied - proplist = protocol_copyPropertyList(proto, &count); - testassert(proplist); - testassert(count == 4); - // note this order is not required - testassert(0 == strcmp(property_getName(proplist[0]), "ReqInst0")); - testassert(0 == strcmp(property_getName(proplist[1]), "ReqInst1")); - testassert(0 == strcmp(property_getName(proplist[2]), "ReqInst2")); - testassert(0 == strcmp(property_getName(proplist[3]), "ReqInst3")); - testassert(0 == strcmp(property_getAttributes(proplist[0]), "Ti")); - testassert(0 == strcmp(property_getAttributes(proplist[1]), "Ti")); - testassert(0 == strcmp(property_getAttributes(proplist[2]), "Ti")); - testassert(0 == strcmp(property_getAttributes(proplist[3]), "Ti")); - free(proplist); - - - testassert(proto2 == objc_getProtocol("EmptyProto")); - testassert(0 == strcmp(protocol_getName(proto2), "EmptyProto")); - - protolist = protocol_copyProtocolList(proto2, &count); - testassert(!protolist); - testassert(count == 0); - - testassert(!protocol_conformsToProtocol(proto2, proto)); - testassert(!protocol_conformsToProtocol(proto2,@protocol(SuperProto))); - testassert(!protocol_conformsToProtocol(proto2,@protocol(UnrelatedProto))); - - desclist = protocol_copyMethodDescriptionList(proto2, YES, YES, &count); - testassert(!desclist && count == 0); - desclist = protocol_copyMethodDescriptionList(proto2, YES, NO, &count); - testassert(!desclist && count == 0); - desclist = protocol_copyMethodDescriptionList(proto2, NO, YES, &count); - testassert(!desclist && count == 0); - desclist = protocol_copyMethodDescriptionList(proto2, NO, NO, &count); - testassert(!desclist && count == 0); - - // Immutability of existing protocols - - objc_registerProtocol(proto); - protocol_addProtocol(proto, @protocol(SuperProto2)); - protocol_addMethodDescription(proto, @selector(foo), "", YES, YES); - - objc_registerProtocol(@protocol(SuperProto)); - protocol_addProtocol(@protocol(SuperProto), @protocol(SuperProto2)); - protocol_addMethodDescription(@protocol(SuperProto), @selector(foo), "", YES, YES); - - // No duplicates - - proto = objc_allocateProtocol("SuperProto"); - testassert(!proto); - proto = objc_allocateProtocol("Proto1"); - testassert(!proto); - - // NULL protocols ignored - - protocol_addProtocol((Protocol *)objc_unretainedObject((void*)1), NULL); - protocol_addProtocol(NULL, (Protocol *)objc_unretainedObject((void*)1)); - protocol_addProtocol(NULL, NULL); - protocol_addMethodDescription(NULL, @selector(foo), "", YES, YES); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/applescriptobjc.m b/objc/objc-runtime/test/applescriptobjc.m deleted file mode 100644 index 158c301..0000000 --- a/objc/objc-runtime/test/applescriptobjc.m +++ /dev/null @@ -1,14 +0,0 @@ -// TEST_CONFIG OS=macosx -// TEST_CFLAGS -framework AppleScriptObjC -framework Foundation - -// Verify that trivial AppleScriptObjC apps run with GC off. - -#include <Foundation/Foundation.h> -#include "test.h" - -int main() -{ - [NSBundle class]; - testassert(!objc_collectingEnabled()); - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/applescriptobjc2.m b/objc/objc-runtime/test/applescriptobjc2.m deleted file mode 100644 index 832b3cd..0000000 --- a/objc/objc-runtime/test/applescriptobjc2.m +++ /dev/null @@ -1,17 +0,0 @@ -// TEST_CFLAGS -framework AppleScriptObjC -framework Foundation -// TEST_CONFIG MEM=gc - -// Verify that non-trivial AppleScriptObjC apps run with GC ON. - -#include <Foundation/Foundation.h> -#include "test.h" - -@interface NonTrivial : NSObject @end -@implementation NonTrivial @end - -int main() -{ - [NSBundle class]; - testassert(objc_collectingEnabled()); - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/arr-cast.m b/objc/objc-runtime/test/arr-cast.m deleted file mode 100644 index ddb6e21..0000000 --- a/objc/objc-runtime/test/arr-cast.m +++ /dev/null @@ -1,20 +0,0 @@ -// TEST_CONFIG - -#include "test.h" - -// objc.h redefines these calls into bridge casts. -// This test verifies that the function implementations are exported. -__BEGIN_DECLS -extern void *retainedObject(void *arg) __asm__("_objc_retainedObject"); -extern void *unretainedObject(void *arg) __asm__("_objc_unretainedObject"); -extern void *unretainedPointer(void *arg) __asm__("_objc_unretainedPointer"); -__END_DECLS - -int main() -{ - void *p = (void*)&main; - testassert(p == retainedObject(p)); - testassert(p == unretainedObject(p)); - testassert(p == unretainedPointer(p)); - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/arr-weak.m b/objc/objc-runtime/test/arr-weak.m deleted file mode 100644 index 3ea58a3..0000000 --- a/objc/objc-runtime/test/arr-weak.m +++ /dev/null @@ -1,329 +0,0 @@ -// TEST_CONFIG MEM=mrc -// TEST_CRASHES -/* -TEST_RUN_OUTPUT -objc\[\d+\]: Cannot form weak reference to instance \(0x[0-9a-f]+\) of class Crash. It is possible that this object was over-released, or is in the process of deallocation. -CRASHED: SIG(ILL|TRAP) -END -*/ - -#include "test.h" - -#include <Foundation/NSObject.h> - -static id weak; -static id weak2; -static id weak3; -static id weak4; -static bool did_dealloc; - -static int state; - -@interface NSObject (WeakInternals) --(BOOL)_tryRetain; --(BOOL)_isDeallocating; -@end - -@interface Test : NSObject @end -@implementation Test --(void)dealloc { - testprintf("Weak storeOrNil does not crash while deallocating\n"); - weak4 = (id)0x100; // old value must not be used - id result = objc_initWeakOrNil(&weak4, self); - testassert(result == nil); - testassert(weak4 == nil); - result = objc_storeWeakOrNil(&weak4, self); - testassert(result == nil); - testassert(weak4 == nil); - - // The value returned by objc_loadWeak() is now nil, - // but the storage is not yet cleared. - testassert(weak == self); - testassert(weak2 == self); - - // objc_loadWeak() does not eagerly clear the storage. - testassert(objc_loadWeakRetained(&weak) == nil); - testassert(weak != nil); - - // dealloc clears the storage. - testprintf("Weak references clear during super dealloc\n"); - testassert(weak2 != nil); - [super dealloc]; - testassert(weak == nil); - testassert(weak2 == nil); - - did_dealloc = true; -} -@end - -@interface CustomTryRetain : Test @end -@implementation CustomTryRetain --(BOOL)_tryRetain { state++; return [super _tryRetain]; } -@end - -@interface CustomIsDeallocating : Test @end -@implementation CustomIsDeallocating --(BOOL)_isDeallocating { state++; return [super _isDeallocating]; } -@end - -@interface CustomAllowsWeakReference : Test @end -@implementation CustomAllowsWeakReference --(BOOL)allowsWeakReference { state++; return [super allowsWeakReference]; } -@end - -@interface CustomRetainWeakReference : Test @end -@implementation CustomRetainWeakReference --(BOOL)retainWeakReference { state++; return [super retainWeakReference]; } -@end - -@interface Crash : NSObject @end -@implementation Crash --(void)dealloc { - testassert(weak == self); - testassert(weak2 == self); - testassert(objc_loadWeakRetained(&weak) == nil); - testassert(objc_loadWeakRetained(&weak2) == nil); - - testprintf("Weak storeOrNil does not crash while deallocating\n"); - id result = objc_storeWeakOrNil(&weak, self); - testassert(result == nil); - - testprintf("Weak store crashes while deallocating\n"); - objc_storeWeak(&weak, self); - fail("objc_storeWeak of deallocating value should have crashed"); - [super dealloc]; -} -@end - - -void cycle(Class cls, Test *obj, Test *obj2, bool storeOrNil) -{ - testprintf("Cycling class %s\n", class_getName(cls)); - - id result; - - id (*storeWeak)(id *location, id obj); - id (*initWeak)(id *location, id obj); - if (storeOrNil) { - testprintf("Using objc_storeWeakOrNil\n"); - storeWeak = objc_storeWeakOrNil; - initWeak = objc_initWeakOrNil; - } else { - testprintf("Using objc_storeWeak\n"); - storeWeak = objc_storeWeak; - initWeak = objc_initWeak; - } - - // state counts calls to custom weak methods - // Difference test classes have different expected values. - int storeTarget; - int loadTarget; - if (cls == [Test class]) { - storeTarget = 0; - loadTarget = 0; - } - else if (cls == [CustomTryRetain class] || - cls == [CustomRetainWeakReference class]) - { - storeTarget = 0; - loadTarget = 1; - } - else if (cls == [CustomIsDeallocating class] || - cls == [CustomAllowsWeakReference class]) - { - storeTarget = 1; - loadTarget = 0; - } - else fail("wut"); - - testprintf("Weak assignment\n"); - state = 0; - result = storeWeak(&weak, obj); - testassert(state == storeTarget); - testassert(result == obj); - testassert(weak == obj); - - testprintf("Weak assignment to the same value\n"); - state = 0; - result = storeWeak(&weak, obj); - testassert(state == storeTarget); - testassert(result == obj); - testassert(weak == obj); - - testprintf("Weak load\n"); - state = 0; - result = objc_loadWeakRetained(&weak); - if (state != loadTarget) testprintf("state %d target %d\n", state, loadTarget); - testassert(state == loadTarget); - testassert(result == obj); - testassert(result == weak); - [result release]; - - testprintf("Weak assignment to different value\n"); - state = 0; - result = storeWeak(&weak, obj2); - testassert(state == storeTarget); - testassert(result == obj2); - testassert(weak == obj2); - - testprintf("Weak assignment to NULL\n"); - state = 0; - result = storeWeak(&weak, NULL); - testassert(state == 0); - testassert(result == NULL); - testassert(weak == NULL); - - testprintf("Weak re-assignment to NULL\n"); - state = 0; - result = storeWeak(&weak, NULL); - testassert(state == 0); - testassert(result == NULL); - testassert(weak == NULL); - - testprintf("Weak move\n"); - state = 0; - result = storeWeak(&weak, obj); - testassert(state == storeTarget); - testassert(result == obj); - testassert(weak == obj); - weak2 = (id)(PAGE_MAX_SIZE-16); - objc_moveWeak(&weak2, &weak); - testassert(weak == nil); - testassert(weak2 == obj); - storeWeak(&weak2, NULL); - - testprintf("Weak copy\n"); - state = 0; - result = storeWeak(&weak, obj); - testassert(state == storeTarget); - testassert(result == obj); - testassert(weak == obj); - weak2 = (id)(PAGE_MAX_SIZE-16); - objc_copyWeak(&weak2, &weak); - testassert(weak == obj); - testassert(weak2 == obj); - storeWeak(&weak, NULL); - storeWeak(&weak2, NULL); - - testprintf("Weak clear\n"); - - id obj3 = [cls new]; - - state = 0; - result = storeWeak(&weak, obj3); - testassert(state == storeTarget); - testassert(result == obj3); - testassert(weak == obj3); - - state = 0; - result = storeWeak(&weak2, obj3); - testassert(state == storeTarget); - testassert(result == obj3); - testassert(weak2 == obj3); - - did_dealloc = false; - [obj3 release]; - testassert(did_dealloc); - testassert(weak == NULL); - testassert(weak2 == NULL); - - - testprintf("Weak init and destroy\n"); - - id obj4 = [cls new]; - - state = 0; - weak = (id)0x100; // old value must not be used - result = initWeak(&weak, obj4); - testassert(state == storeTarget); - testassert(result == obj4); - testassert(weak == obj4); - - state = 0; - weak2 = (id)0x100; // old value must not be used - result = initWeak(&weak2, obj4); - testassert(state == storeTarget); - testassert(result == obj4); - testassert(weak2 == obj4); - - state = 0; - weak3 = (id)0x100; // old value must not be used - result = initWeak(&weak3, obj4); - testassert(state == storeTarget); - testassert(result == obj4); - testassert(weak3 == obj4); - - state = 0; - objc_destroyWeak(&weak3); - testassert(state == 0); - testassert(weak3 == obj4); // storage is unchanged - - did_dealloc = false; - [obj4 release]; - testassert(did_dealloc); - testassert(weak == NULL); // not destroyed earlier so cleared now - testassert(weak2 == NULL); // not destroyed earlier so cleared now - testassert(weak3 == obj4); // destroyed earlier so not cleared now - - objc_destroyWeak(&weak); - objc_destroyWeak(&weak2); -} - - -void test_class(Class cls) -{ - // prime strong and weak side tables before leak checking - Test *prime[256] = {nil}; - for (size_t i = 0; i < sizeof(prime)/sizeof(prime[0]); i++) { - objc_storeWeak(&prime[i], [cls new]); - } - - Test *obj = [cls new]; - Test *obj2 = [cls new]; - - for (int i = 0; i < 100000; i++) { - cycle(cls, obj, obj2, false); - cycle(cls, obj, obj2, true); - } - leak_mark(); - for (int i = 0; i < 100000; i++) { - cycle(cls, obj, obj2, false); - cycle(cls, obj, obj2, true); - } - // allow some slop for side table expansion - // 5120 is common with this configuration - leak_check(6000); - - // rdar://14105994 - id weaks[8]; - for (size_t i = 0; i < sizeof(weaks)/sizeof(weaks[0]); i++) { - objc_storeWeak(&weaks[i], obj); - } - for (size_t i = 0; i < sizeof(weaks)/sizeof(weaks[0]); i++) { - objc_storeWeak(&weaks[i], nil); - } -} - -int main() -{ - test_class([Test class]); - test_class([CustomTryRetain class]); - test_class([CustomIsDeallocating class]); - test_class([CustomAllowsWeakReference class]); - test_class([CustomRetainWeakReference class]); - - - id result; - - Crash *obj3 = [Crash new]; - result = objc_storeWeak(&weak, obj3); - testassert(result == obj3); - testassert(weak == obj3); - - result = objc_storeWeak(&weak2, obj3); - testassert(result == obj3); - testassert(weak2 == obj3); - - [obj3 release]; - fail("should have crashed in -[Crash dealloc]"); -} diff --git a/objc/objc-runtime/test/association-cf.m b/objc/objc-runtime/test/association-cf.m deleted file mode 100644 index 5930c5c..0000000 --- a/objc/objc-runtime/test/association-cf.m +++ /dev/null @@ -1,38 +0,0 @@ -// TEST_CFLAGS -framework CoreFoundation - -#include <CoreFoundation/CoreFoundation.h> -#include <objc/runtime.h> - -#include "test.h" - -#if __has_feature(objc_arc) - -int main() -{ - testwarn("rdar://11368528 confused by Foundation"); - succeed(__FILE__); -} - -#else - -int main() -{ - // rdar://6164781 setAssociatedObject on pure-CF object crashes LP64 - - id obj; - id array = objc_retainedObject(CFArrayCreate(0, 0, 0, 0)); - testassert(array); - - testassert(! objc_getClass("NSCFArray")); - - objc_setAssociatedObject(array, (void*)1, array, OBJC_ASSOCIATION_ASSIGN); - - obj = objc_getAssociatedObject(array, (void*)1); - testassert(obj == array); - - RELEASE_VAR(array); - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/association.m b/objc/objc-runtime/test/association.m deleted file mode 100644 index 429a1c0..0000000 --- a/objc/objc-runtime/test/association.m +++ /dev/null @@ -1,145 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include <Foundation/NSObject.h> -#include <objc/runtime.h> - -static int values; -static int supers; -static int subs; - -static const char *key = "key"; - - -@interface Value : NSObject @end -@interface Super : NSObject @end -@interface Sub : NSObject @end - -@interface Super2 : NSObject @end -@interface Sub2 : NSObject @end - -@implementation Super --(id) init -{ - // rdar://8270243 don't lose associations after isa swizzling - - id value = [Value new]; - objc_setAssociatedObject(self, &key, value, OBJC_ASSOCIATION_RETAIN); - RELEASE_VAR(value); - - object_setClass(self, [Sub class]); - - return self; -} - --(void) dealloc -{ - supers++; - SUPER_DEALLOC(); -} --(void) finalize -{ - supers++; - [super finalize]; -} - -@end - -@implementation Sub --(void) dealloc -{ - subs++; - SUPER_DEALLOC(); -} --(void) finalize -{ - subs++; - [super finalize]; -} -@end - -@implementation Super2 --(id) init -{ - // rdar://9617109 don't lose associations after isa swizzling - - id value = [Value new]; - object_setClass(self, [Sub2 class]); - objc_setAssociatedObject(self, &key, value, OBJC_ASSOCIATION_RETAIN); - RELEASE_VAR(value); - object_setClass(self, [Super2 class]); - - return self; -} - --(void) dealloc -{ - supers++; - SUPER_DEALLOC(); -} --(void) finalize -{ - supers++; - [super finalize]; -} - -@end - -@implementation Sub2 --(void) dealloc -{ - subs++; - SUPER_DEALLOC(); -} --(void) finalize -{ - subs++; - [super finalize]; -} -@end - -@implementation Value --(void) dealloc { - values++; - SUPER_DEALLOC(); -} --(void) finalize { - values++; - [super finalize]; -} -@end - - -int main() -{ - testonthread(^{ - int i; - for (i = 0; i < 100; i++) { - RELEASE_VALUE([[Super alloc] init]); - } - }); - testcollect(); - - testassert(supers == 0); - testassert(subs > 0); - testassert(subs == values); - - - supers = 0; - subs = 0; - values = 0; - - testonthread(^{ - int i; - for (i = 0; i < 100; i++) { - RELEASE_VALUE([[Super2 alloc] init]); - } - }); - testcollect(); - - testassert(supers > 0); - testassert(subs == 0); - testassert(supers == values); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/atomicProperty.mm b/objc/objc-runtime/test/atomicProperty.mm deleted file mode 100644 index ea8bade..0000000 --- a/objc/objc-runtime/test/atomicProperty.mm +++ /dev/null @@ -1,41 +0,0 @@ -// TEST_CONFIG CC=clang - -#include "test.h" -#include <objc/runtime.h> -#include <objc/objc-internal.h> -#import <Foundation/NSObject.h> - -class SerialNumber { - size_t _number; -public: - SerialNumber() : _number(42) {} - SerialNumber(const SerialNumber &number) : _number(number._number + 1) {} - SerialNumber &operator=(const SerialNumber &number) { _number = number._number + 1; return *this; } - - int operator==(const SerialNumber &number) { return _number == number._number; } - int operator!=(const SerialNumber &number) { return _number != number._number; } -}; - -@interface TestAtomicProperty : NSObject { - SerialNumber number; -} -@property(atomic) SerialNumber number; -@end - -@implementation TestAtomicProperty - -@synthesize number; - -@end - -int main() -{ - PUSH_POOL { - SerialNumber number; - TestAtomicProperty *test = [TestAtomicProperty new]; - test.number = number; - testassert(test.number != number); - } POP_POOL; - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/badAltHandler.m b/objc/objc-runtime/test/badAltHandler.m deleted file mode 100644 index efee852..0000000 --- a/objc/objc-runtime/test/badAltHandler.m +++ /dev/null @@ -1,81 +0,0 @@ -// for OBJC2 mac only -/* TEST_CONFIG OS=macosx ARCH=x86_64 - TEST_CRASHES - -TEST_RUN_OUTPUT -objc\[\d+\]: objc_removeExceptionHandler\(\) called with unknown alt handler; this is probably a bug in multithreaded AppKit use. Set environment variable OBJC_DEBUG_ALT_HANDLERS=YES or break in objc_alt_handler_error\(\) to debug. -CRASHED: SIGILL -END -*/ - -#include "test.h" - -#include <objc/objc-exception.h> - -/* - rdar://6888838 - Mail installs an alt handler on one thread and deletes it on another. - This confuses the alt handler machinery, which halts the process. -*/ - -uintptr_t Token; - -void handler(id unused __unused, void *context __unused) -{ -} - -int main() -{ -#if __clang__ && __cplusplus - // alt handlers need the objc personality - // catch (id) workaround forces the objc personality - @try { - testwarn("rdar://9183014 clang uses wrong exception personality"); - } @catch (id e __unused) { - } -#endif - - @try { - // Install 4 alt handlers - uintptr_t t1, t2, t3, t4; - t1 = objc_addExceptionHandler(&handler, NULL); - t2 = objc_addExceptionHandler(&handler, NULL); - t3 = objc_addExceptionHandler(&handler, NULL); - t4 = objc_addExceptionHandler(&handler, NULL); - - // Remove 3 of them. - objc_removeExceptionHandler(t1); - objc_removeExceptionHandler(t2); - objc_removeExceptionHandler(t3); - - // Create an alt handler on another thread - // that collides with one of the removed handlers - testonthread(^{ - @try { - Token = objc_addExceptionHandler(&handler, NULL); - } @catch (...) { - } - }); - - // Incorrectly remove the other thread's handler - objc_removeExceptionHandler(Token); - // Remove the 4th handler - objc_removeExceptionHandler(t4); - - // Install 8 more handlers. - // If the other thread's handler was not ignored, - // this will fail. - objc_addExceptionHandler(&handler, NULL); - objc_addExceptionHandler(&handler, NULL); - objc_addExceptionHandler(&handler, NULL); - objc_addExceptionHandler(&handler, NULL); - objc_addExceptionHandler(&handler, NULL); - objc_addExceptionHandler(&handler, NULL); - objc_addExceptionHandler(&handler, NULL); - objc_addExceptionHandler(&handler, NULL); - } @catch (...) { - } - - // This should have crashed earlier. - fail(__FILE__); -} diff --git a/objc/objc-runtime/test/badCache.m b/objc/objc-runtime/test/badCache.m deleted file mode 100644 index 96f455b..0000000 --- a/objc/objc-runtime/test/badCache.m +++ /dev/null @@ -1,86 +0,0 @@ -/* -TEST_CRASHES -TEST_RUN_OUTPUT -objc1 -OK: badCache.m -OR -crash now -objc\[\d+\]: Method cache corrupted.* -objc\[\d+\]: .* -objc\[\d+\]: .* -objc\[\d+\]: .* -objc\[\d+\]: .* -objc\[\d+\]: Method cache corrupted\. -CRASHED: SIG(ILL|TRAP) -END -*/ - - -#include "test.h" - -#if !__OBJC2__ || __arm__ - -int main() -{ - fprintf(stderr, "objc1\n"); - succeed(__FILE__); -} - -#else - -#include "testroot.i" - -#if __LP64__ -typedef uint32_t mask_t; -#else -typedef uint16_t mask_t; -#endif - -struct bucket_t { - uintptr_t sel; - uintptr_t imp; -}; - -struct cache_t { - struct bucket_t *buckets; - mask_t mask; - mask_t occupied; -}; - -struct class_t { - void *isa; - void *supercls; - struct cache_t cache; -}; - -@interface Subclass : TestRoot @end -@implementation Subclass @end - -int main() -{ - Class cls = [TestRoot class]; - id obj = [cls new]; - [obj self]; - - struct cache_t *cache = &((__bridge struct class_t *)cls)->cache; - -# define COUNT 4 - struct bucket_t *buckets = calloc(sizeof(struct bucket_t), COUNT+1); - for (int i = 0; i < COUNT; i++) { - buckets[i].sel = ~0; - buckets[i].imp = ~0; - } - buckets[COUNT].sel = 1; - buckets[COUNT].imp = (uintptr_t)buckets; - - cache->mask = COUNT-1; - cache->occupied = 0; - cache->buckets = buckets; - - fprintf(stderr, "crash now\n"); - [obj self]; - - fail("should have crashed"); -} - -#endif diff --git a/objc/objc-runtime/test/badTagClass.m b/objc/objc-runtime/test/badTagClass.m deleted file mode 100644 index d7d10be..0000000 --- a/objc/objc-runtime/test/badTagClass.m +++ /dev/null @@ -1,42 +0,0 @@ -/* -TEST_CRASHES -TEST_RUN_OUTPUT -objc\[\d+\]: tag index 7 used for two different classes \(was 0x[0-9a-fA-F]+ NSObject, now 0x[0-9a-fA-F]+ TestRoot\) -CRASHED: SIG(ILL|TRAP) -OR -no tagged pointers -OK: badTagClass.m -END -*/ - -#include "test.h" -#include "testroot.i" - -#include <objc/objc-internal.h> -#include <objc/Protocol.h> - -#if OBJC_HAVE_TAGGED_POINTERS - -int main() -{ - // re-registration and nil registration allowed - _objc_registerTaggedPointerClass(OBJC_TAG_7, [NSObject class]); - _objc_registerTaggedPointerClass(OBJC_TAG_7, [NSObject class]); - _objc_registerTaggedPointerClass(OBJC_TAG_7, nil); - _objc_registerTaggedPointerClass(OBJC_TAG_7, [NSObject class]); - - // colliding registration disallowed - _objc_registerTaggedPointerClass(OBJC_TAG_7, [TestRoot class]); - - fail(__FILE__); -} - -#else - -int main() -{ - fprintf(stderr, "no tagged pointers\n"); - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/badTagIndex.m b/objc/objc-runtime/test/badTagIndex.m deleted file mode 100644 index 7a84b66..0000000 --- a/objc/objc-runtime/test/badTagIndex.m +++ /dev/null @@ -1,33 +0,0 @@ -/* -TEST_CRASHES -TEST_RUN_OUTPUT -objc\[\d+\]: tag index 8 is too large. -CRASHED: SIG(ILL|TRAP) -OR -no tagged pointers -OK: badTagIndex.m -END -*/ - -#include "test.h" - -#include <objc/objc-internal.h> -#include <objc/NSObject.h> - -#if OBJC_HAVE_TAGGED_POINTERS - -int main() -{ - _objc_registerTaggedPointerClass((objc_tag_index_t)8, [NSObject class]); - fail(__FILE__); -} - -#else - -int main() -{ - fprintf(stderr, "no tagged pointers\n"); - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/bigrc.m b/objc/objc-runtime/test/bigrc.m deleted file mode 100644 index f171c6e..0000000 --- a/objc/objc-runtime/test/bigrc.m +++ /dev/null @@ -1,133 +0,0 @@ -// TEST_CONFIG MEM=mrc -/* -TEST_RUN_OUTPUT -objc\[\d+\]: Deallocator object 0x[0-9a-fA-F]+ overreleased while already deallocating; break on objc_overrelease_during_dealloc_error to debug -OK: bigrc.m -OR -no overrelease enforcement -OK: bigrc.m -END - */ - -#include "test.h" -#include "testroot.i" - -static size_t LOTS; - -@interface Deallocator : TestRoot @end -@implementation Deallocator - --(void)dealloc -{ - id o = self; - size_t rc = 1; - - - testprintf("Retain a lot during dealloc\n"); - - testassert(rc == 1); - testassert([o retainCount] == rc); - do { - [o retain]; - if (rc % 0x100000 == 0) testprintf("%zx/%zx ++\n", rc, LOTS); - } while (++rc < LOTS); - - testassert([o retainCount] == rc); - - do { - [o release]; - if (rc % 0x100000 == 0) testprintf("%zx/%zx --\n", rc, LOTS); - } while (--rc > 1); - - testassert(rc == 1); - testassert([o retainCount] == rc); - - - testprintf("Overrelease during dealloc\n"); - - // Not all architectures enforce this. -#if !SUPPORT_NONPOINTER_ISA - testwarn("no overrelease enforcement"); - fprintf(stderr, "no overrelease enforcement\n"); -#endif - [o release]; - - [super dealloc]; -} - -@end - - -int main() -{ - Deallocator *o = [Deallocator new]; - size_t rc = 1; - - [o retain]; - - uintptr_t isa = *(uintptr_t *)o; - if (isa & 1) { - // Assume refcount in high bits. - LOTS = 1 << (4 + __builtin_clzll(isa)); - testprintf("LOTS %zu via cntlzw\n", LOTS); - } else { - LOTS = 0x1000000; - testprintf("LOTS %zu via guess\n", LOTS); - } - - [o release]; - - - testprintf("Retain a lot\n"); - - testassert(rc == 1); - testassert([o retainCount] == rc); - do { - [o retain]; - if (rc % 0x100000 == 0) testprintf("%zx/%zx ++\n", rc, LOTS); - } while (++rc < LOTS); - - testassert([o retainCount] == rc); - - do { - [o release]; - if (rc % 0x100000 == 0) testprintf("%zx/%zx --\n", rc, LOTS); - } while (--rc > 1); - - testassert(rc == 1); - testassert([o retainCount] == rc); - - - testprintf("tryRetain a lot\n"); - - id w; - objc_storeWeak(&w, o); - testassert(w == o); - - testassert(rc == 1); - testassert([o retainCount] == rc); - do { - objc_loadWeakRetained(&w); - if (rc % 0x100000 == 0) testprintf("%zx/%zx ++\n", rc, LOTS); - } while (++rc < LOTS); - - testassert([o retainCount] == rc); - - do { - [o release]; - if (rc % 0x100000 == 0) testprintf("%zx/%zx --\n", rc, LOTS); - } while (--rc > 1); - - testassert(rc == 1); - testassert([o retainCount] == rc); - - testprintf("dealloc\n"); - - testassert(TestRootDealloc == 0); - testassert(w != nil); - [o release]; - testassert(TestRootDealloc == 1); - testassert(w == nil); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/blocksAsImps.m b/objc/objc-runtime/test/blocksAsImps.m deleted file mode 100644 index 360321a..0000000 --- a/objc/objc-runtime/test/blocksAsImps.m +++ /dev/null @@ -1,263 +0,0 @@ -// TEST_CFLAGS -framework Foundation - -#include "test.h" -#include <objc/runtime.h> -#import <Foundation/Foundation.h> - -#include <Block_private.h> - -#if !__has_feature(objc_arc) -# define __bridge -#endif - -#if !__clang__ - // gcc and llvm-gcc will never support struct-return marking -# define STRET_OK 0 -# define STRET_SPECIAL 0 -#elif __arm64__ - // stret supported, but is identical to non-stret -# define STRET_OK 1 -# define STRET_SPECIAL 0 -#else - // stret supported and distinct from non-stret -# define STRET_OK 1 -# define STRET_SPECIAL 1 -#endif - -typedef struct BigStruct { - uintptr_t datums[200]; -} BigStruct; - -@interface Foo:NSObject -@end -@implementation Foo -- (BigStruct) methodThatReturnsBigStruct: (BigStruct) b -{ - return b; -} -@end - -@interface Foo(bar) -- (int) boo: (int) a; -- (BigStruct) structThatIsBig: (BigStruct) b; -- (BigStruct) methodThatReturnsBigStruct: (BigStruct) b; -- (float) methodThatReturnsFloat: (float) aFloat; -@end - -// This is void* instead of id to prevent interference from ARC. -typedef uintptr_t (*FuncPtr)(void *, SEL); -typedef BigStruct (*BigStructFuncPtr)(id, SEL, BigStruct); -typedef float (*FloatFuncPtr)(id, SEL, float); - -BigStruct bigfunc(BigStruct a) { - return a; -} - -@interface Deallocator : NSObject @end -@implementation Deallocator --(void) methodThatNobodyElseCalls1 { } --(void) methodThatNobodyElseCalls2 { } -id retain_imp(Deallocator *self, SEL _cmd) { - _objc_flush_caches([Deallocator class]); - [self methodThatNobodyElseCalls1]; - struct objc_super sup = { self, [[Deallocator class] superclass] }; - return ((id(*)(struct objc_super *, SEL))objc_msgSendSuper)(&sup, _cmd); -} -void dealloc_imp(Deallocator *self, SEL _cmd) { - _objc_flush_caches([Deallocator class]); - [self methodThatNobodyElseCalls2]; - struct objc_super sup = { self, [[Deallocator class] superclass] }; - ((void(*)(struct objc_super *, SEL))objc_msgSendSuper)(&sup, _cmd); -} -+(void) load { - class_addMethod(self, sel_registerName("retain"), (IMP)retain_imp, ""); - class_addMethod(self, sel_registerName("dealloc"), (IMP)dealloc_imp, ""); -} -@end - -/* Code copied from objc-block-trampolines.m to test Block innards */ -typedef enum { - ReturnValueInRegisterArgumentMode, -#if STRET_SPECIAL - ReturnValueOnStackArgumentMode, -#endif - - ArgumentModeMax -} ArgumentMode; - -static ArgumentMode _argumentModeForBlock(id block) { - ArgumentMode aMode = ReturnValueInRegisterArgumentMode; -#if STRET_SPECIAL - if ( _Block_use_stret((__bridge void *)block) ) - aMode = ReturnValueOnStackArgumentMode; -#else - testassert(!_Block_use_stret((__bridge void *)block)); -#endif - - return aMode; -} -/* End copied code */ - -int main () { - // make sure the bits are in place - int (^registerReturn)() = ^(){ return 42; }; - ArgumentMode aMode; - - aMode = _argumentModeForBlock(registerReturn); - testassert(aMode == ReturnValueInRegisterArgumentMode); - -#if STRET_OK - BigStruct (^stackReturn)() = ^() { BigStruct k; return k; }; - aMode = _argumentModeForBlock(stackReturn); -# if STRET_SPECIAL - testassert(aMode == ReturnValueOnStackArgumentMode); -# else - testassert(aMode == ReturnValueInRegisterArgumentMode); -# endif -#endif - -#define TEST_QUANTITY 100000 - static FuncPtr funcArray[TEST_QUANTITY]; - - uintptr_t i; - for(i = 0; i<TEST_QUANTITY; i++) { - uintptr_t (^block)(void *self) = ^uintptr_t(void *self) { - testassert(i == (uintptr_t)self); - return i; - }; - block = (__bridge id)_Block_copy((__bridge void *)block); - - funcArray[i] = (FuncPtr) imp_implementationWithBlock(block); - - testassert(block((void *)i) == i); - - id blockFromIMPResult = imp_getBlock((IMP)funcArray[i]); - testassert(blockFromIMPResult == (id)block); - - _Block_release((__bridge void *)block); - } - - for(i = 0; i<TEST_QUANTITY; i++) { - uintptr_t result = funcArray[i]((void *)i, 0); - testassert(i == result); - } - - for(i = 0; i < TEST_QUANTITY; i= i + 3) { - imp_removeBlock((IMP)funcArray[i]); - id shouldBeNull = imp_getBlock((IMP)funcArray[i]); - testassert(shouldBeNull == NULL); - } - - for(i = 0; i < TEST_QUANTITY; i= i + 3) { - uintptr_t j = i * i; - - uintptr_t (^block)(void *) = ^uintptr_t(void *self) { - testassert(j == (uintptr_t)self); - return j; - }; - funcArray[i] = (FuncPtr) imp_implementationWithBlock(block); - - testassert(block((void *)j) == j); - testassert(funcArray[i]((void *)j, 0) == j); - } - - for(i = 0; i < TEST_QUANTITY; i= i + 3) { - uintptr_t j = i * i; - uintptr_t result = funcArray[i]((void *)j, 0); - testassert(j == result); - } - - int (^implBlock)(id, int); - - implBlock = ^(id self __attribute__((unused)), int a){ - return -1 * a; - }; - - PUSH_POOL { - - IMP methodImp = imp_implementationWithBlock(implBlock); - - BOOL success = class_addMethod([Foo class], @selector(boo:), methodImp, "i@:i"); - testassert(success); - - Foo *f = [Foo new]; - int (*impF)(id self, SEL _cmd, int x) = (int(*)(id, SEL, int)) [Foo instanceMethodForSelector: @selector(boo:)]; - - int x = impF(f, @selector(boo:), -42); - - testassert(x == 42); - testassert([f boo: -42] == 42); - -#if STRET_OK - BigStruct a; - for(i=0; i<200; i++) - a.datums[i] = i; - - // slightly more straightforward here - __block unsigned int state = 0; - BigStruct (^structBlock)(id, BigStruct) = ^BigStruct(id self __attribute__((unused)), BigStruct c) { - state++; - return c; - }; - BigStruct blockDirect = structBlock(nil, a); - testassert(!memcmp(&a, &blockDirect, sizeof(BigStruct))); - testassert(state==1); - - IMP bigStructIMP = imp_implementationWithBlock(structBlock); - - class_addMethod([Foo class], @selector(structThatIsBig:), bigStructIMP, "oh, type strings, how I hate thee. Fortunately, the runtime doesn't generally care."); - - BigStruct b; - - BigStructFuncPtr bFunc; - - b = bigfunc(a); - testassert(!memcmp(&a, &b, sizeof(BigStruct))); - b = bigfunc(a); - testassert(!memcmp(&a, &b, sizeof(BigStruct))); - - bFunc = (BigStructFuncPtr) [Foo instanceMethodForSelector: @selector(methodThatReturnsBigStruct:)]; - - b = bFunc(f, @selector(methodThatReturnsBigStruct:), a); - testassert(!memcmp(&a, &b, sizeof(BigStruct))); - - b = [f methodThatReturnsBigStruct: a]; - testassert(!memcmp(&a, &b, sizeof(BigStruct))); - - bFunc = (BigStructFuncPtr) [Foo instanceMethodForSelector: @selector(structThatIsBig:)]; - - b = bFunc(f, @selector(structThatIsBig:), a); - testassert(!memcmp(&a, &b, sizeof(BigStruct))); - testassert(state==2); - - b = [f structThatIsBig: a]; - testassert(!memcmp(&a, &b, sizeof(BigStruct))); - testassert(state==3); - // STRET_OK -#endif - - - IMP floatIMP = imp_implementationWithBlock(^float (id self __attribute__((unused)), float aFloat ) { - return aFloat; - }); - class_addMethod([Foo class], @selector(methodThatReturnsFloat:), floatIMP, "ooh.. type string unspecified again... oh noe... runtime might punish. not."); - - float e = (float)0.001; - float retF = (float)[f methodThatReturnsFloat: 37.1212f]; - testassert( ((retF - e) < 37.1212) && ((retF + e) > 37.1212) ); - - -#if !__has_feature(objc_arc) - // Make sure imp_implementationWithBlock() and imp_removeBlock() - // don't deadlock while calling Block_copy() and Block_release() - Deallocator *dead = [[Deallocator alloc] init]; - IMP deadlockImp = imp_implementationWithBlock(^{ [dead self]; }); - [dead release]; - imp_removeBlock(deadlockImp); -#endif - - } POP_POOL; - - succeed(__FILE__); -} - diff --git a/objc/objc-runtime/test/cacheflush.h b/objc/objc-runtime/test/cacheflush.h deleted file mode 100644 index 5553dbb..0000000 --- a/objc/objc-runtime/test/cacheflush.h +++ /dev/null @@ -1,7 +0,0 @@ -#include <objc/objc.h> -#include "test.h" - -@interface TestRoot(cat) -+(int)classMethod; --(int)instanceMethod; -@end diff --git a/objc/objc-runtime/test/cacheflush.m b/objc/objc-runtime/test/cacheflush.m deleted file mode 100644 index 85136d7..0000000 --- a/objc/objc-runtime/test/cacheflush.m +++ /dev/null @@ -1,61 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/cacheflush0.m -o cacheflush0.dylib -dynamiclib - $C{COMPILE} $DIR/cacheflush2.m -x none cacheflush0.dylib -o cacheflush2.dylib -dynamiclib - $C{COMPILE} $DIR/cacheflush3.m -x none cacheflush0.dylib -o cacheflush3.dylib -dynamiclib - $C{COMPILE} $DIR/cacheflush.m -x none cacheflush0.dylib -o cacheflush.out -END -*/ - -#include "test.h" -#include <objc/runtime.h> -#include <dlfcn.h> - -#include "cacheflush.h" - -@interface Sub : TestRoot @end -@implementation Sub @end - - -int main() -{ - TestRoot *sup = [TestRoot new]; - Sub *sub = [Sub new]; - - // Fill method cache - testassert(1 == [TestRoot classMethod]); - testassert(1 == [sup instanceMethod]); - testassert(1 == [TestRoot classMethod]); - testassert(1 == [sup instanceMethod]); - - testassert(1 == [Sub classMethod]); - testassert(1 == [sub instanceMethod]); - testassert(1 == [Sub classMethod]); - testassert(1 == [sub instanceMethod]); - - // Dynamically load a category - dlopen("cacheflush2.dylib", 0); - - // Make sure old cache results are gone - testassert(2 == [TestRoot classMethod]); - testassert(2 == [sup instanceMethod]); - - testassert(2 == [Sub classMethod]); - testassert(2 == [sub instanceMethod]); - - // Dynamically load another category - dlopen("cacheflush3.dylib", 0); - - // Make sure old cache results are gone - testassert(3 == [TestRoot classMethod]); - testassert(3 == [sup instanceMethod]); - - testassert(3 == [Sub classMethod]); - testassert(3 == [sub instanceMethod]); - - // fixme test subclasses - - // fixme test objc_flush_caches(), class_addMethod(), class_addMethods() - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/cacheflush0.m b/objc/objc-runtime/test/cacheflush0.m deleted file mode 100644 index 8536071..0000000 --- a/objc/objc-runtime/test/cacheflush0.m +++ /dev/null @@ -1,7 +0,0 @@ -#include "cacheflush.h" -#include "testroot.i" - -@implementation TestRoot(cat) -+(int)classMethod { return 1; } --(int)instanceMethod { return 1; } -@end diff --git a/objc/objc-runtime/test/cacheflush2.m b/objc/objc-runtime/test/cacheflush2.m deleted file mode 100644 index 0337e3f..0000000 --- a/objc/objc-runtime/test/cacheflush2.m +++ /dev/null @@ -1,6 +0,0 @@ -#include "cacheflush.h" - -@implementation TestRoot (Category2) -+(int)classMethod { return 2; } --(int)instanceMethod { return 2; } -@end diff --git a/objc/objc-runtime/test/cacheflush3.m b/objc/objc-runtime/test/cacheflush3.m deleted file mode 100644 index c180e98..0000000 --- a/objc/objc-runtime/test/cacheflush3.m +++ /dev/null @@ -1,6 +0,0 @@ -#include "cacheflush.h" - -@implementation TestRoot (Category3) -+(int)classMethod { return 3; } --(int)instanceMethod { return 3; } -@end diff --git a/objc/objc-runtime/test/category.m b/objc/objc-runtime/test/category.m deleted file mode 100644 index 3e55a15..0000000 --- a/objc/objc-runtime/test/category.m +++ /dev/null @@ -1,105 +0,0 @@ -// TEST_CFLAGS -Wl,-no_objc_category_merging - -#include "test.h" -#include "testroot.i" -#include <string.h> -#include <objc/runtime.h> - -static int state = 0; - -@interface Super : TestRoot @end -@implementation Super --(void)instancemethod { fail("-instancemethod not overridden by category"); } -+(void)method { fail("+method not overridden by category"); } -@end - -@interface Super (Category) @end -@implementation Super (Category) -+(void)method { - testprintf("in [Super(Category) method]\n"); - testassert(self == [Super class]); - testassert(state == 0); - state = 1; -} --(void)instancemethod { - testprintf("in [Super(Category) instancemethod]\n"); - testassert(object_getClass(self) == [Super class]); - testassert(state == 1); - state = 2; -} -@end - -@interface Super (PropertyCategory) -@property int i; -@end -@implementation Super (PropertyCategory) -- (int)i { return 0; } -- (void)setI:(int)value { (void)value; } -@end - -// rdar://5086110 memory smasher in category with class method and property -@interface Super (r5086110) -@property int property5086110; -@end -@implementation Super (r5086110) -+(void)method5086110 { - fail("method method5086110 called!"); -} -- (int)property5086110 { fail("property5086110 called!"); return 0; } -- (void)setProperty5086110:(int)value { fail("setProperty5086110 called!"); (void)value; } -@end - - -@interface PropertyClass : Super { - int q; -} -@property(readonly) int q; -@end -@implementation PropertyClass -@synthesize q; -@end - -@interface PropertyClass (PropertyCategory) -@property int q; -@end -@implementation PropertyClass (PropertyCategory) -@dynamic q; -@end - - -int main() -{ - // methods introduced by category - state = 0; - [Super method]; - [[Super new] instancemethod]; - testassert(state == 2); - - // property introduced by category - objc_property_t p = class_getProperty([Super class], "i"); - testassert(p); - testassert(0 == strcmp(property_getName(p), "i")); - testassert(property_getAttributes(p)); - - // methods introduced by category's property - Method m; - m = class_getInstanceMethod([Super class], @selector(i)); - testassert(m); - m = class_getInstanceMethod([Super class], @selector(setI:)); - testassert(m); - - // class's property shadowed by category's property - objc_property_t *plist = class_copyPropertyList([PropertyClass class], NULL); - testassert(plist); - testassert(plist[0]); - testassert(0 == strcmp(property_getName(plist[0]), "q")); - testassert(0 == strcmp(property_getAttributes(plist[0]), "Ti,D")); - testassert(plist[1]); - testassert(0 == strcmp(property_getName(plist[1]), "q")); - testassert(0 == strcmp(property_getAttributes(plist[1]), "Ti,R,Vq")); - testassert(!plist[2]); - free(plist); - - succeed(__FILE__); -} - diff --git a/objc/objc-runtime/test/cdtors.mm b/objc/objc-runtime/test/cdtors.mm deleted file mode 100644 index c91e738..0000000 --- a/objc/objc-runtime/test/cdtors.mm +++ /dev/null @@ -1,311 +0,0 @@ -// TEST_CONFIG - -#if USE_FOUNDATION -#include <Foundation/Foundation.h> -#define SUPERCLASS NSObject -#define FILENAME "nscdtors.mm" -#else -#define SUPERCLASS TestRoot -#define FILENAME "cdtors.mm" -#endif - -#include "test.h" - -#include <pthread.h> -#include "objc/objc-internal.h" -#include "testroot.i" - -static unsigned ctors1 = 0; -static unsigned dtors1 = 0; -static unsigned ctors2 = 0; -static unsigned dtors2 = 0; - -class cxx1 { - unsigned & ctors; - unsigned& dtors; - - public: - cxx1() : ctors(ctors1), dtors(dtors1) { ctors++; } - - ~cxx1() { dtors++; } -}; -class cxx2 { - unsigned& ctors; - unsigned& dtors; - - public: - cxx2() : ctors(ctors2), dtors(dtors2) { ctors++; } - - ~cxx2() { dtors++; } -}; - -/* - Class hierarchy: - TestRoot - CXXBase - NoCXXSub - CXXSub - - This has two cxx-wielding classes, and a class in between without cxx. -*/ - - -@interface CXXBase : SUPERCLASS { - cxx1 baseIvar; -} -@end -@implementation CXXBase @end - -@interface NoCXXSub : CXXBase { - int nocxxIvar; -} -@end -@implementation NoCXXSub @end - -@interface CXXSub : NoCXXSub { - cxx2 subIvar; -} -@end -@implementation CXXSub @end - - -void test_single(void) -{ - // Single allocation - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - testonthread(^{ - id o = [TestRoot new]; - testassert(ctors1 == 0 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - testassert([o class] == [TestRoot class]); - RELEASE_VAR(o); - }); - testcollect(); - testassert(ctors1 == 0 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - testonthread(^{ - id o = [CXXBase new]; - testassert(ctors1 == 1 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - testassert([o class] == [CXXBase class]); - RELEASE_VAR(o); - }); - testcollect(); - testassert(ctors1 == 1 && dtors1 == 1 && - ctors2 == 0 && dtors2 == 0); - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - testonthread(^{ - id o = [NoCXXSub new]; - testassert(ctors1 == 1 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - testassert([o class] == [NoCXXSub class]); - RELEASE_VAR(o); - }); - testcollect(); - testassert(ctors1 == 1 && dtors1 == 1 && - ctors2 == 0 && dtors2 == 0); - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - testonthread(^{ - id o = [CXXSub new]; - testassert(ctors1 == 1 && dtors1 == 0 && - ctors2 == 1 && dtors2 == 0); - testassert([o class] == [CXXSub class]); - RELEASE_VAR(o); - }); - testcollect(); - testassert(ctors1 == 1 && dtors1 == 1 && - ctors2 == 1 && dtors2 == 1); -} - -void test_inplace(void) -{ - __unsafe_unretained volatile id o; - char o2[64]; - - id (*objc_constructInstance_fn)(Class, void*) = (id(*)(Class, void*))dlsym(RTLD_DEFAULT, "objc_constructInstance"); - void (*objc_destructInstance_fn)(id) = (void(*)(id))dlsym(RTLD_DEFAULT, "objc_destructInstance"); - - // In-place allocation - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - o = objc_constructInstance_fn([TestRoot class], o2); - testassert(ctors1 == 0 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - testassert([o class] == [TestRoot class]); - objc_destructInstance_fn(o), o = nil; - testcollect(); - testassert(ctors1 == 0 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - o = objc_constructInstance_fn([CXXBase class], o2); - testassert(ctors1 == 1 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - testassert([o class] == [CXXBase class]); - objc_destructInstance_fn(o), o = nil; - testcollect(); - testassert(ctors1 == 1 && dtors1 == 1 && - ctors2 == 0 && dtors2 == 0); - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - o = objc_constructInstance_fn([NoCXXSub class], o2); - testassert(ctors1 == 1 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - testassert([o class] == [NoCXXSub class]); - objc_destructInstance_fn(o), o = nil; - testcollect(); - testassert(ctors1 == 1 && dtors1 == 1 && - ctors2 == 0 && dtors2 == 0); - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - o = objc_constructInstance_fn([CXXSub class], o2); - testassert(ctors1 == 1 && dtors1 == 0 && - ctors2 == 1 && dtors2 == 0); - testassert([o class] == [CXXSub class]); - objc_destructInstance_fn(o), o = nil; - testcollect(); - testassert(ctors1 == 1 && dtors1 == 1 && - ctors2 == 1 && dtors2 == 1); -} - - -#if __has_feature(objc_arc) - -void test_batch(void) -{ - // not converted to ARC yet - return; -} - -#else - -// Like class_createInstances(), but refuses to accept zero allocations -static unsigned -reallyCreateInstances(Class cls, size_t extraBytes, id *dst, unsigned want) -{ - unsigned count; - while (0 == (count = class_createInstances(cls, extraBytes, dst, want))) { - testprintf("class_createInstances created nothing; retrying\n"); - RELEASE_VALUE([[TestRoot alloc] init]); - } - return count; -} - -void test_batch(void) -{ - id o2[100]; - unsigned int count, i; - - // Batch allocation - - for (i = 0; i < 100; i++) { - o2[i] = (id)malloc(class_getInstanceSize([TestRoot class])); - } - for (i = 0; i < 100; i++) { - free(o2[i]); - } - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - count = reallyCreateInstances([TestRoot class], 0, o2, 10); - testassert(count > 0); - testassert(ctors1 == 0 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - for (i = 0; i < count; i++) testassert([o2[i] class] == [TestRoot class]); - for (i = 0; i < count; i++) object_dispose(o2[i]), o2[i] = nil; - testcollect(); - testassert(ctors1 == 0 && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - - for (i = 0; i < 100; i++) { - // prime batch allocator - free(malloc(class_getInstanceSize([TestRoot class]))); - } - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - count = reallyCreateInstances([CXXBase class], 0, o2, 10); - testassert(count > 0); - testassert(ctors1 == count && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - for (i = 0; i < count; i++) testassert([o2[i] class] == [CXXBase class]); - for (i = 0; i < count; i++) object_dispose(o2[i]), o2[i] = nil; - testcollect(); - testassert(ctors1 == count && dtors1 == count && - ctors2 == 0 && dtors2 == 0); - - for (i = 0; i < 100; i++) { - // prime batch allocator - free(malloc(class_getInstanceSize([TestRoot class]))); - } - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - count = reallyCreateInstances([NoCXXSub class], 0, o2, 10); - testassert(count > 0); - testassert(ctors1 == count && dtors1 == 0 && - ctors2 == 0 && dtors2 == 0); - for (i = 0; i < count; i++) testassert([o2[i] class] == [NoCXXSub class]); - for (i = 0; i < count; i++) object_dispose(o2[i]), o2[i] = nil; - testcollect(); - testassert(ctors1 == count && dtors1 == count && - ctors2 == 0 && dtors2 == 0); - - for (i = 0; i < 100; i++) { - // prime batch allocator - free(malloc(class_getInstanceSize([TestRoot class]))); - } - - ctors1 = dtors1 = ctors2 = dtors2 = 0; - count = reallyCreateInstances([CXXSub class], 0, o2, 10); - testassert(count > 0); - testassert(ctors1 == count && dtors1 == 0 && - ctors2 == count && dtors2 == 0); - for (i = 0; i < count; i++) testassert([o2[i] class] == [CXXSub class]); - for (i = 0; i < count; i++) object_dispose(o2[i]), o2[i] = nil; - testcollect(); - testassert(ctors1 == count && dtors1 == count && - ctors2 == count && dtors2 == count); -} - -// not ARC -#endif - - -int main() -{ - if (objc_collectingEnabled()) { - testwarn("rdar://19042235 test disabled in GC because it is slow"); - succeed(FILENAME); - } - - for (int i = 0; i < 1000; i++) { - testonthread(^{ test_single(); }); - testonthread(^{ test_inplace(); }); - testonthread(^{ test_batch(); }); - } - - testonthread(^{ test_single(); }); - testonthread(^{ test_inplace(); }); - testonthread(^{ test_batch(); }); - - leak_mark(); - - for (int i = 0; i < 1000; i++) { - testonthread(^{ test_single(); }); - testonthread(^{ test_inplace(); }); - testonthread(^{ test_batch(); }); - } - - leak_check(0); - - // fixme ctor exceptions aren't caught inside .cxx_construct ? - // Single allocation, ctors fail - // In-place allocation, ctors fail - // Batch allocation, ctors fail for every object - // Batch allocation, ctors fail for every other object - - succeed(FILENAME); -} diff --git a/objc/objc-runtime/test/classgetclass.m b/objc/objc-runtime/test/classgetclass.m deleted file mode 100644 index 70686eb..0000000 --- a/objc/objc-runtime/test/classgetclass.m +++ /dev/null @@ -1,20 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include <objc/objc-runtime.h> -#include <objc/objc-gdb.h> -#import <Foundation/NSObject.h> - -@interface Foo:NSObject -@end -@implementation Foo -@end - -int main() -{ -#if __OBJC2__ - testassert(gdb_class_getClass([Foo class]) == [Foo class]); -#endif - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/classname.m b/objc/objc-runtime/test/classname.m deleted file mode 100644 index 7234641..0000000 --- a/objc/objc-runtime/test/classname.m +++ /dev/null @@ -1,39 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <string.h> -#include <objc/runtime.h> - -@interface Fake : TestRoot @end -@implementation Fake @end - -int main() -{ - TestRoot *obj = [TestRoot new]; - Class __unsafe_unretained * buf = (Class *)objc_unretainedPointer(obj); - *buf = [Fake class]; - - testassert(object_getClass(obj) == [Fake class]); - testassert(object_setClass(obj, [TestRoot class]) == [Fake class]); - testassert(object_getClass(obj) == [TestRoot class]); - testassert(object_setClass(nil, [TestRoot class]) == nil); - - testassert(malloc_size(buf) >= sizeof(id)); - bzero(buf, malloc_size(buf)); - testassert(object_setClass(obj, [TestRoot class]) == nil); - - testassert(object_getClass(obj) == [TestRoot class]); - testassert(object_getClass([TestRoot class]) == object_getClass([TestRoot class])); - testassert(object_getClass(nil) == Nil); - - testassert(0 == strcmp(object_getClassName(obj), "TestRoot")); - testassert(0 == strcmp(object_getClassName([TestRoot class]), "TestRoot")); - testassert(0 == strcmp(object_getClassName(nil), "nil")); - - testassert(0 == strcmp(class_getName([TestRoot class]), "TestRoot")); - testassert(0 == strcmp(class_getName(object_getClass([TestRoot class])), "TestRoot")); - testassert(0 == strcmp(class_getName(nil), "nil")); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/classpair.m b/objc/objc-runtime/test/classpair.m deleted file mode 100644 index c30733b..0000000 --- a/objc/objc-runtime/test/classpair.m +++ /dev/null @@ -1,376 +0,0 @@ -// TEST_CFLAGS -Wno-deprecated-declarations - -#include "test.h" - -#include "testroot.i" -#include <objc/runtime.h> -#include <string.h> -#ifndef OBJC_NO_GC -#include <objc/objc-auto.h> -#include <auto_zone.h> -#endif - -@protocol Proto --(void) instanceMethod; -+(void) classMethod; -@optional --(void) instanceMethod2; -+(void) classMethod2; -@end - -@protocol Proto2 --(void) instanceMethod; -+(void) classMethod; -@optional --(void) instanceMethod2; -+(void) classMethod_that_does_not_exist; -@end - -@protocol Proto3 --(void) instanceMethod; -+(void) classMethod_that_does_not_exist; -@optional --(void) instanceMethod2; -+(void) classMethod2; -@end - -static int super_initialize; - -@interface Super : TestRoot -@property int superProp; -@end -@implementation Super -@dynamic superProp; -+(void)initialize { super_initialize++; } - -+(void) classMethod { fail("+[Super classMethod] called"); } -+(void) classMethod2 { fail("+[Super classMethod2] called"); } --(void) instanceMethod { fail("-[Super instanceMethod] called"); } --(void) instanceMethod2 { fail("-[Super instanceMethod2] called"); } -@end - -@interface WeakSuper : Super { __weak id weakIvar; } @end -@implementation WeakSuper @end - -static int state; - -static void instance_fn(id self, SEL _cmd __attribute__((unused))) -{ - testassert(!class_isMetaClass(object_getClass(self))); - state++; -} - -static void class_fn(id self, SEL _cmd __attribute__((unused))) -{ - testassert(class_isMetaClass(object_getClass(self))); - state++; -} - -static void fail_fn(id self __attribute__((unused)), SEL _cmd) -{ - fail("fail_fn '%s' called", sel_getName(_cmd)); -} - - -static void cycle(void) -{ - Class cls; - BOOL ok; - objc_property_t prop; - char namebuf[256]; - - testassert(!objc_getClass("Sub")); - testassert([Super class]); - - // Test subclass with bells and whistles - - cls = objc_allocateClassPair([Super class], "Sub", 0); - testassert(cls); -#ifndef OBJC_NO_GC - if (objc_collectingEnabled()) { - testassert(auto_zone_size(objc_collectableZone(), objc_unretainedPointer(cls))); - testassert(auto_zone_size(objc_collectableZone(), objc_unretainedPointer(object_getClass(cls)))); - } -#endif - - class_addMethod(cls, @selector(instanceMethod), - (IMP)&instance_fn, "v@:"); - class_addMethod(object_getClass(cls), @selector(classMethod), - (IMP)&class_fn, "v@:"); - class_addMethod(object_getClass(cls), @selector(initialize), - (IMP)&class_fn, "v@:"); - class_addMethod(object_getClass(cls), @selector(load), - (IMP)&fail_fn, "v@:"); - - ok = class_addProtocol(cls, @protocol(Proto)); - testassert(ok); - ok = class_addProtocol(cls, @protocol(Proto)); - testassert(!ok); - - char attrname[2]; - char attrvalue[2]; - objc_property_attribute_t attrs[1]; - unsigned int attrcount = sizeof(attrs) / sizeof(attrs[0]); - - attrs[0].name = attrname; - attrs[0].value = attrvalue; - strcpy(attrname, "T"); - strcpy(attrvalue, "x"); - - strcpy(namebuf, "subProp"); - ok = class_addProperty(cls, namebuf, attrs, attrcount); - testassert(ok); - strcpy(namebuf, "subProp"); - ok = class_addProperty(cls, namebuf, attrs, attrcount); - testassert(!ok); - strcpy(attrvalue, "i"); - class_replaceProperty(cls, namebuf, attrs, attrcount); - strcpy(namebuf, "superProp"); - ok = class_addProperty(cls, namebuf, attrs, attrcount); - testassert(!ok); - bzero(namebuf, sizeof(namebuf)); - bzero(attrs, sizeof(attrs)); - bzero(attrname, sizeof(attrname)); - bzero(attrvalue, sizeof(attrvalue)); - -#ifndef __LP64__ -# define size 4 -# define align 2 -#else -#define size 8 -# define align 3 -#endif - - /* - { - int ivar; - id ivarid; - id* ivaridstar; - Block_t ivarblock; - } - */ - ok = class_addIvar(cls, "ivar", 4, 2, "i"); - testassert(ok); - ok = class_addIvar(cls, "ivarid", size, align, "@"); - testassert(ok); - ok = class_addIvar(cls, "ivaridstar", size, align, "^@"); - testassert(ok); - ok = class_addIvar(cls, "ivarblock", size, align, "@?"); - testassert(ok); - - ok = class_addIvar(cls, "ivar", 4, 2, "i"); - testassert(!ok); - ok = class_addIvar(object_getClass(cls), "classvar", 4, 2, "i"); - testassert(!ok); - - objc_registerClassPair(cls); - - // should call cls's +initialize, not super's - // Provoke +initialize using class_getMethodImplementation(class method) - // in order to test getNonMetaClass's slow case - super_initialize = 0; - state = 0; - class_getMethodImplementation(object_getClass(cls), @selector(class)); - testassert(super_initialize == 0); - testassert(state == 1); - - testassert(cls == [cls class]); - testassert(cls == objc_getClass("Sub")); - - testassert(!class_isMetaClass(cls)); - testassert(class_isMetaClass(object_getClass(cls))); - - testassert(class_getSuperclass(cls) == [Super class]); - testassert(class_getSuperclass(object_getClass(cls)) == object_getClass([Super class])); - - testassert(class_getInstanceSize(cls) >= sizeof(Class) + 4 + 3*size); - testassert(class_conformsToProtocol(cls, @protocol(Proto))); - - if (objc_collectingEnabled()) { - testassert(0 == strcmp((char *)class_getIvarLayout(cls), "\x01\x13")); - testassert(NULL == class_getWeakIvarLayout(cls)); - } - - class_addMethod(cls, @selector(instanceMethod2), - (IMP)&instance_fn, "v@:"); - class_addMethod(object_getClass(cls), @selector(classMethod2), - (IMP)&class_fn, "v@:"); - - ok = class_addIvar(cls, "ivar2", 4, 4, "i"); - testassert(!ok); - ok = class_addIvar(object_getClass(cls), "classvar2", 4, 4, "i"); - testassert(!ok); - - ok = class_addProtocol(cls, @protocol(Proto2)); - testassert(ok); - ok = class_addProtocol(cls, @protocol(Proto2)); - testassert(!ok); - ok = class_addProtocol(cls, @protocol(Proto)); - testassert(!ok); - - attrs[0].name = attrname; - attrs[0].value = attrvalue; - strcpy(attrname, "T"); - strcpy(attrvalue, "i"); - - strcpy(namebuf, "subProp2"); - ok = class_addProperty(cls, namebuf, attrs, attrcount); - testassert(ok); - strcpy(namebuf, "subProp"); - ok = class_addProperty(cls, namebuf, attrs, attrcount); - testassert(!ok); - strcpy(namebuf, "superProp"); - ok = class_addProperty(cls, namebuf, attrs, attrcount); - testassert(!ok); - bzero(namebuf, sizeof(namebuf)); - bzero(attrs, sizeof(attrs)); - bzero(attrname, sizeof(attrname)); - bzero(attrvalue, sizeof(attrvalue)); - - prop = class_getProperty(cls, "subProp"); - testassert(prop); - testassert(0 == strcmp(property_getName(prop), "subProp")); - testassert(0 == strcmp(property_getAttributes(prop), "Ti")); - prop = class_getProperty(cls, "subProp2"); - testassert(prop); - testassert(0 == strcmp(property_getName(prop), "subProp2")); - testassert(0 == strcmp(property_getAttributes(prop), "Ti")); - - // note: adding more methods here causes a false leak check failure - state = 0; - [cls classMethod]; - [cls classMethod2]; - testassert(state == 2); - - // put instance tests on a separate thread so they - // are reliably GC'd before class destruction - testonthread(^{ - id obj = [cls new]; - state = 0; - [obj instanceMethod]; - [obj instanceMethod2]; - testassert(state == 2); - RELEASE_VAR(obj); - }); - - // Test ivar layouts of sub-subclass - Class cls2 = objc_allocateClassPair(cls, "SubSub", 0); - testassert(cls2); - - /* - { - id ivarid2; - id idarray[16]; - void* ptrarray[16]; - char a; - char b; - char c; - } - */ - ok = class_addIvar(cls2, "ivarid2", size, align, "@"); - testassert(ok); - ok = class_addIvar(cls2, "idarray", 16*sizeof(id), align, "[16@]"); - testassert(ok); - ok = class_addIvar(cls2, "ptrarray", 16*sizeof(void*), align, "[16^]"); - testassert(ok); - ok = class_addIvar(cls2, "a", 1, 0, "c"); - testassert(ok); - ok = class_addIvar(cls2, "b", 1, 0, "c"); - testassert(ok); - ok = class_addIvar(cls2, "c", 1, 0, "c"); - testassert(ok); - - objc_registerClassPair(cls2); - - if (objc_collectingEnabled()) { - testassert(0 == strcmp((char *)class_getIvarLayout(cls2), "\x01\x1f\x05\xf0\x10")); - testassert(NULL == class_getWeakIvarLayout(cls2)); - } - - // 1-byte ivars should be well packed - testassert(ivar_getOffset(class_getInstanceVariable(cls2, "b")) == - ivar_getOffset(class_getInstanceVariable(cls2, "a")) + 1); - testassert(ivar_getOffset(class_getInstanceVariable(cls2, "c")) == - ivar_getOffset(class_getInstanceVariable(cls2, "b")) + 1); - - testcollect(); // GC: finalize "obj" above before disposing its class - objc_disposeClassPair(cls2); - objc_disposeClassPair(cls); - - testassert(!objc_getClass("Sub")); - - - // Test unmodified ivar layouts - - cls = objc_allocateClassPair([Super class], "Sub2", 0); - testassert(cls); - objc_registerClassPair(cls); - if (objc_collectingEnabled()) { - const char *l1, *l2; - l1 = (char *)class_getIvarLayout([Super class]); - l2 = (char *)class_getIvarLayout(cls); - testassert(l1 == l2 || 0 == strcmp(l1, l2)); - l1 = (char *)class_getWeakIvarLayout([Super class]); - l2 = (char *)class_getWeakIvarLayout(cls); - testassert(l1 == l2 || 0 == strcmp(l1, l2)); - } - objc_disposeClassPair(cls); - - cls = objc_allocateClassPair([WeakSuper class], "Sub3", 0); - testassert(cls); - objc_registerClassPair(cls); - if (objc_collectingEnabled()) { - const char *l1, *l2; - l1 = (char *)class_getIvarLayout([WeakSuper class]); - l2 = (char *)class_getIvarLayout(cls); - testassert(l1 == l2 || 0 == strcmp(l1, l2)); - l1 = (char *)class_getWeakIvarLayout([WeakSuper class]); - l2 = (char *)class_getWeakIvarLayout(cls); - testassert(l1 == l2 || 0 == strcmp(l1, l2)); - } - objc_disposeClassPair(cls); - - // Test layout setters - if (objc_collectingEnabled()) { - cls = objc_allocateClassPair([Super class], "Sub4", 0); - testassert(cls); - class_setIvarLayout(cls, (uint8_t *)"foo"); - class_setWeakIvarLayout(cls, NULL); - objc_registerClassPair(cls); - testassert(0 == strcmp("foo", (char *)class_getIvarLayout(cls))); - testassert(NULL == class_getWeakIvarLayout(cls)); - objc_disposeClassPair(cls); - - cls = objc_allocateClassPair([Super class], "Sub5", 0); - testassert(cls); - class_setIvarLayout(cls, NULL); - class_setWeakIvarLayout(cls, (uint8_t *)"bar"); - objc_registerClassPair(cls); - testassert(NULL == class_getIvarLayout(cls)); - testassert(0 == strcmp("bar", (char *)class_getWeakIvarLayout(cls))); - objc_disposeClassPair(cls); - } -} - -int main() -{ - int count = 1000; - - testonthread(^{ cycle(); }); - testonthread(^{ cycle(); }); - testonthread(^{ cycle(); }); - - leak_mark(); - while (count--) { - testonthread(^{ cycle(); }); - } -#if __OBJC_GC__ - testwarn("rdar://19042235 possible leaks suppressed under GC"); - leak_check(16000); -#else - leak_check(0); -#endif - - succeed(__FILE__); -} - diff --git a/objc/objc-runtime/test/classversion.m b/objc/objc-runtime/test/classversion.m deleted file mode 100644 index c34b98e..0000000 --- a/objc/objc-runtime/test/classversion.m +++ /dev/null @@ -1,19 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <objc/runtime.h> - -int main() -{ - Class cls = [TestRoot class]; - testassert(class_getVersion(cls) == 0); - testassert(class_getVersion(object_getClass(cls)) > 5); - class_setVersion(cls, 100); - testassert(class_getVersion(cls) == 100); - - testassert(class_getVersion(Nil) == 0); - class_setVersion(Nil, 100); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/concurrentcat.m b/objc/objc-runtime/test/concurrentcat.m deleted file mode 100644 index 0f6ef69..0000000 --- a/objc/objc-runtime/test/concurrentcat.m +++ /dev/null @@ -1,129 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/concurrentcat.m -o concurrentcat.out -framework Foundation - - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc1 -o cc1.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc2 -o cc2.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc3 -o cc3.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc4 -o cc4.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc5 -o cc5.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc6 -o cc6.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc7 -o cc7.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc8 -o cc8.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc9 -o cc9.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc10 -o cc10.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc11 -o cc11.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc12 -o cc12.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc13 -o cc13.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc14 -o cc14.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/concurrentcat_category.m -DTN=cc15 -o cc15.dylib -END -*/ - -#include "test.h" -#include <objc/runtime.h> -#include <objc/objc-auto.h> -#include <dlfcn.h> -#include <unistd.h> -#include <pthread.h> -#include <Foundation/Foundation.h> - -@interface TargetClass : NSObject -@end - -@interface TargetClass(LoadedMethods) -- (void) m0; -- (void) m1; -- (void) m2; -- (void) m3; -- (void) m4; -- (void) m5; -- (void) m6; -- (void) m7; -- (void) m8; -- (void) m9; -- (void) m10; -- (void) m11; -- (void) m12; -- (void) m13; -- (void) m14; -- (void) m15; -@end - -@implementation TargetClass -- (void) m0 { fail("shoulda been loaded!"); } -- (void) m1 { fail("shoulda been loaded!"); } -- (void) m2 { fail("shoulda been loaded!"); } -- (void) m3 { fail("shoulda been loaded!"); } -- (void) m4 { fail("shoulda been loaded!"); } -- (void) m5 { fail("shoulda been loaded!"); } -- (void) m6 { fail("shoulda been loaded!"); } -@end - -void *threadFun(void *aTargetClassName) { - const char *className = (const char *)aTargetClassName; - - objc_registerThreadWithCollector(); - - PUSH_POOL { - - Class targetSubclass = objc_getClass(className); - testassert(targetSubclass); - - id target = [targetSubclass new]; - testassert(target); - - while(1) { - [target m0]; - RETAIN(target); - [target addObserver: target forKeyPath: @"m3" options: 0 context: NULL]; - [target addObserver: target forKeyPath: @"m4" options: 0 context: NULL]; - [target m1]; - RELEASE_VALUE(target); - [target m2]; - AUTORELEASE(target); - [target m3]; - RETAIN(target); - [target removeObserver: target forKeyPath: @"m4"]; - [target addObserver: target forKeyPath: @"m5" options: 0 context: NULL]; - [target m4]; - RETAIN(target); - [target m5]; - AUTORELEASE(target); - [target m6]; - [target m7]; - [target m8]; - [target m9]; - [target m10]; - [target m11]; - [target m12]; - [target m13]; - [target m14]; - [target m15]; - [target removeObserver: target forKeyPath: @"m3"]; - [target removeObserver: target forKeyPath: @"m5"]; - } - } POP_POOL; - return NULL; -} - -int main() -{ - int i; - - void *dylib; - - for(i=1; i<16; i++) { - pthread_t t; - char dlName[100]; - sprintf(dlName, "cc%d.dylib", i); - dylib = dlopen(dlName, RTLD_LAZY); - char className[100]; - sprintf(className, "cc%d", i); - pthread_create(&t, NULL, threadFun, strdup(className)); - testassert(dylib); - } - sleep(1); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/concurrentcat_category.m b/objc/objc-runtime/test/concurrentcat_category.m deleted file mode 100644 index c59f663..0000000 --- a/objc/objc-runtime/test/concurrentcat_category.m +++ /dev/null @@ -1,70 +0,0 @@ -#include <stdio.h> -#include <objc/runtime.h> -#import <Foundation/Foundation.h> - -@interface TargetClass : NSObject -@end - -@interface TargetClass(LoadedMethods) -- (void) m0; -- (void) m1; -- (void) m2; -- (void) m3; -- (void) m4; -- (void) m5; -- (void) m6; -- (void) m7; -- (void) m8; -- (void) m9; -- (void) m10; -- (void) m11; -- (void) m12; -- (void) m13; -- (void) m14; -- (void) m15; -@end - -@interface TN:TargetClass -@end - -@implementation TN -- (void) m1 { [super m1]; } -- (void) m3 { [self m1]; } - -- (void) m2 -{ - [self willChangeValueForKey: @"m4"]; - [self didChangeValueForKey: @"m4"]; -} - -- (void)observeValueForKeyPath:(NSString *) keyPath - ofObject:(id)object - change:(NSDictionary *)change - context:(void *)context -{ - // suppress warning - keyPath = nil; - object = nil; - change = nil; - context = NULL; -} -@end - -@implementation TargetClass(LoadedMethods) -- (void) m0 { ; } -- (void) m1 { ; } -- (void) m2 { ; } -- (void) m3 { ; } -- (void) m4 { ; } -- (void) m5 { ; } -- (void) m6 { ; } -- (void) m7 { ; } -- (void) m8 { ; } -- (void) m9 { ; } -- (void) m10 { ; } -- (void) m11 { ; } -- (void) m12 { ; } -- (void) m13 { ; } -- (void) m14 { ; } -- (void) m15 { ; } -@end diff --git a/objc/objc-runtime/test/copyIvarList.m b/objc/objc-runtime/test/copyIvarList.m deleted file mode 100644 index b924108..0000000 --- a/objc/objc-runtime/test/copyIvarList.m +++ /dev/null @@ -1,115 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include <string.h> -#include <malloc/malloc.h> -#include <objc/objc-runtime.h> - -OBJC_ROOT_CLASS -@interface SuperIvars { - id isa; - int ivar1; - int ivar2; -} @end -@implementation SuperIvars @end - -@interface SubIvars : SuperIvars { - int ivar3; - int ivar4; -} @end -@implementation SubIvars @end - -OBJC_ROOT_CLASS -@interface FourIvars { - int ivar1; - int ivar2; - int ivar3; - int ivar4; -} @end -@implementation FourIvars @end - -OBJC_ROOT_CLASS -@interface NoIvars { } @end -@implementation NoIvars @end - -static int isNamed(Ivar iv, const char *name) -{ - return (0 == strcmp(name, ivar_getName(iv))); -} - -int main() -{ - Ivar *ivars; - unsigned int count; - Class cls; - - cls = objc_getClass("SubIvars"); - testassert(cls); - - count = 100; - ivars = class_copyIvarList(cls, &count); - testassert(ivars); - testassert(count == 2); - testassert(isNamed(ivars[0], "ivar3")); - testassert(isNamed(ivars[1], "ivar4")); - // ivars[] should be null-terminated - testassert(ivars[2] == NULL); - free(ivars); - - cls = objc_getClass("SuperIvars"); - testassert(cls); - - count = 100; - ivars = class_copyIvarList(cls, &count); - testassert(ivars); - testassert(count == 3); - testassert(isNamed(ivars[0], "isa")); - testassert(isNamed(ivars[1], "ivar1")); - testassert(isNamed(ivars[2], "ivar2")); - // ivars[] should be null-terminated - testassert(ivars[3] == NULL); - free(ivars); - - // Check null-termination - this ivar list block would be 16 bytes - // if it weren't for the terminator - cls = objc_getClass("FourIvars"); - testassert(cls); - - count = 100; - ivars = class_copyIvarList(cls, &count); - testassert(ivars); - testassert(count == 4); - testassert(malloc_size(ivars) >= 5 * sizeof(Ivar)); - testassert(ivars[3] != NULL); - testassert(ivars[4] == NULL); - free(ivars); - - // Check NULL count parameter - ivars = class_copyIvarList(cls, NULL); - testassert(ivars); - testassert(ivars[4] == NULL); - testassert(ivars[3] != NULL); - free(ivars); - - // Check NULL class parameter - count = 100; - ivars = class_copyIvarList(NULL, &count); - testassert(!ivars); - testassert(count == 0); - - // Check NULL class and count - ivars = class_copyIvarList(NULL, NULL); - testassert(!ivars); - - // Check class with no ivars - cls = objc_getClass("NoIvars"); - testassert(cls); - - count = 100; - ivars = class_copyIvarList(cls, &count); - testassert(!ivars); - testassert(count == 0); - - succeed(__FILE__); - return 0; -} diff --git a/objc/objc-runtime/test/copyMethodList.m b/objc/objc-runtime/test/copyMethodList.m deleted file mode 100644 index 18a0d6c..0000000 --- a/objc/objc-runtime/test/copyMethodList.m +++ /dev/null @@ -1,155 +0,0 @@ -// TEST_CFLAGS -Wl,-no_objc_category_merging - -#include "test.h" -#include "testroot.i" -#include <malloc/malloc.h> -#include <objc/runtime.h> - -@interface SuperMethods : TestRoot { } @end -@implementation SuperMethods -+(BOOL)SuperMethodClass { return NO; } -+(BOOL)SuperMethodClass2 { return NO; } --(BOOL)SuperMethodInstance { return NO; } --(BOOL)SuperMethodInstance2 { return NO; } -@end - -@interface SubMethods : SuperMethods { } @end -@implementation SubMethods -+(BOOL)SubMethodClass { return NO; } -+(BOOL)SubMethodClass2 { return NO; } --(BOOL)SubMethodInstance { return NO; } --(BOOL)SubMethodInstance2 { return NO; } -@end - -@interface SuperMethods (Category) @end -@implementation SuperMethods (Category) -+(BOOL)SuperMethodClass { return YES; } -+(BOOL)SuperMethodClass2 { return YES; } --(BOOL)SuperMethodInstance { return YES; } --(BOOL)SuperMethodInstance2 { return YES; } -@end - -@interface SubMethods (Category) @end -@implementation SubMethods (Category) -+(BOOL)SubMethodClass { return YES; } -+(BOOL)SubMethodClass2 { return YES; } --(BOOL)SubMethodInstance { return YES; } --(BOOL)SubMethodInstance2 { return YES; } -@end - - -@interface FourMethods : TestRoot @end -@implementation FourMethods --(void)one { } --(void)two { } --(void)three { } --(void)four { } -@end - -@interface NoMethods : TestRoot @end -@implementation NoMethods @end - -static void checkReplacement(Method *list, const char *name) -{ - Method first = NULL, second = NULL; - SEL sel = sel_registerName(name); - int i; - - testassert(list); - - // Find the methods. There should be two. - for (i = 0; list[i]; i++) { - if (method_getName(list[i]) == sel) { - if (!first) first = list[i]; - else if (!second) second = list[i]; - else testassert(0); - } - } - - // Call the methods. The first should be the category (returns YES). - BOOL isCat; - isCat = ((BOOL(*)(id, Method))method_invoke)(NULL, first); - testassert(isCat); - isCat = ((BOOL(*)(id, Method))method_invoke)(NULL, second); - testassert(! isCat); -} - -int main() -{ - // Class SubMethods has not yet been touched, so runtime must attach - // the lazy categories - Method *methods; - unsigned int count; - Class cls; - - cls = objc_getClass("SubMethods"); - testassert(cls); - - testprintf("calling class_copyMethodList(SubMethods) (should be unmethodized)\n"); - - count = 100; - methods = class_copyMethodList(cls, &count); - testassert(methods); - testassert(count == 4); - // methods[] should be null-terminated - testassert(methods[4] == NULL); - // Class and category methods may be mixed in the method list thanks - // to linker / shared cache sorting, but a category's replacement should - // always precede the class's implementation. - checkReplacement(methods, "SubMethodInstance"); - checkReplacement(methods, "SubMethodInstance2"); - free(methods); - - testprintf("calling class_copyMethodList(SubMethods(meta)) (should be unmethodized)\n"); - - count = 100; - methods = class_copyMethodList(object_getClass(cls), &count); - testassert(methods); - testassert(count == 4); - // methods[] should be null-terminated - testassert(methods[4] == NULL); - // Class and category methods may be mixed in the method list thanks - // to linker / shared cache sorting, but a category's replacement should - // always precede the class's implementation. - checkReplacement(methods, "SubMethodClass"); - checkReplacement(methods, "SubMethodClass2"); - free(methods); - - // Check null-termination - this method list block would be 16 bytes - // if it weren't for the terminator - count = 100; - cls = objc_getClass("FourMethods"); - methods = class_copyMethodList(cls, &count); - testassert(methods); - testassert(count == 4); - testassert(malloc_size(methods) >= (4+1) * sizeof(Method)); - testassert(methods[3] != NULL); - testassert(methods[4] == NULL); - free(methods); - - // Check NULL count parameter - methods = class_copyMethodList(cls, NULL); - testassert(methods); - testassert(methods[4] == NULL); - testassert(methods[3] != NULL); - free(methods); - - // Check NULL class parameter - count = 100; - methods = class_copyMethodList(NULL, &count); - testassert(!methods); - testassert(count == 0); - - // Check NULL class and count - methods = class_copyMethodList(NULL, NULL); - testassert(!methods); - - // Check class with no methods - count = 100; - cls = objc_getClass("NoMethods"); - methods = class_copyMethodList(cls, &count); - testassert(!methods); - testassert(count == 0); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/copyPropertyList.m b/objc/objc-runtime/test/copyPropertyList.m deleted file mode 100644 index 40dbec2..0000000 --- a/objc/objc-runtime/test/copyPropertyList.m +++ /dev/null @@ -1,124 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include <string.h> -#include <malloc/malloc.h> -#include <objc/objc-runtime.h> - -OBJC_ROOT_CLASS -@interface SuperProps { id isa; int prop1; int prop2; } -@property int prop1; -@property int prop2; -@end -@implementation SuperProps -@synthesize prop1; -@synthesize prop2; -@end - -@interface SubProps : SuperProps { int prop3; int prop4; } -@property int prop3; -@property int prop4; -@end -@implementation SubProps -@synthesize prop3; -@synthesize prop4; -@end - -OBJC_ROOT_CLASS -@interface FourProps { int prop1; int prop2; int prop3; int prop4; } -@property int prop1; -@property int prop2; -@property int prop3; -@property int prop4; -@end -@implementation FourProps -@synthesize prop1; -@synthesize prop2; -@synthesize prop3; -@synthesize prop4; -@end - -OBJC_ROOT_CLASS -@interface NoProps @end -@implementation NoProps @end - -static int isNamed(objc_property_t p, const char *name) -{ - return (0 == strcmp(name, property_getName(p))); -} - -int main() -{ - objc_property_t *props; - unsigned int count; - Class cls; - - cls = objc_getClass("SubProps"); - testassert(cls); - - count = 100; - props = class_copyPropertyList(cls, &count); - testassert(props); - testassert(count == 2); - testassert((isNamed(props[0], "prop3") && isNamed(props[1], "prop4")) || - (isNamed(props[1], "prop3") && isNamed(props[0], "prop4"))); - // props[] should be null-terminated - testassert(props[2] == NULL); - free(props); - - cls = objc_getClass("SuperProps"); - testassert(cls); - - count = 100; - props = class_copyPropertyList(cls, &count); - testassert(props); - testassert(count == 2); - testassert((isNamed(props[0], "prop1") && isNamed(props[1], "prop2")) || - (isNamed(props[1], "prop1") && isNamed(props[0], "prop2"))); - // props[] should be null-terminated - testassert(props[2] == NULL); - free(props); - - // Check null-termination - this property list block would be 16 bytes - // if it weren't for the terminator - cls = objc_getClass("FourProps"); - testassert(cls); - - count = 100; - props = class_copyPropertyList(cls, &count); - testassert(props); - testassert(count == 4); - testassert(malloc_size(props) >= 5 * sizeof(objc_property_t)); - testassert(props[3] != NULL); - testassert(props[4] == NULL); - free(props); - - // Check NULL count parameter - props = class_copyPropertyList(cls, NULL); - testassert(props); - testassert(props[4] == NULL); - testassert(props[3] != NULL); - free(props); - - // Check NULL class parameter - count = 100; - props = class_copyPropertyList(NULL, &count); - testassert(!props); - testassert(count == 0); - - // Check NULL class and count - props = class_copyPropertyList(NULL, NULL); - testassert(!props); - - // Check class with no properties - cls = objc_getClass("NoProps"); - testassert(cls); - - count = 100; - props = class_copyPropertyList(cls, &count); - testassert(!props); - testassert(count == 0); - - succeed(__FILE__); - return 0; -} diff --git a/objc/objc-runtime/test/createInstance.m b/objc/objc-runtime/test/createInstance.m deleted file mode 100644 index e53e20a..0000000 --- a/objc/objc-runtime/test/createInstance.m +++ /dev/null @@ -1,63 +0,0 @@ -// TEST_CONFIG MEM=mrc,gc -// TEST_CFLAGS -Wno-deprecated-declarations - -#import <objc/runtime.h> -#import <objc/objc-auto.h> -#ifndef OBJC_NO_GC -#include <auto_zone.h> -#else -static BOOL auto_zone_is_valid_pointer(void *a, void *b) { return a||b; } -#endif -#include "test.h" - -OBJC_ROOT_CLASS -@interface Super { @public id isa; } @end -@implementation Super -+(void) initialize { } -+(Class) class { return self; } -@end - -@interface Sub : Super { int array[128]; } @end -@implementation Sub @end - -int main() -{ - Super *s; - - s = class_createInstance([Super class], 0); - testassert(s); - testassert(object_getClass(s) == [Super class]); - testassert(malloc_size(s) >= class_getInstanceSize([Super class])); - if (objc_collectingEnabled()) testassert(auto_zone_is_valid_pointer(objc_collectableZone(), s)); - - object_dispose(s); - - s = class_createInstance([Sub class], 0); - testassert(s); - testassert(object_getClass(s) == [Sub class]); - testassert(malloc_size(s) >= class_getInstanceSize([Sub class])); - if (objc_collectingEnabled()) testassert(auto_zone_is_valid_pointer(objc_collectableZone(), s)); - - object_dispose(s); - - s = class_createInstance([Super class], 100); - testassert(s); - testassert(object_getClass(s) == [Super class]); - testassert(malloc_size(s) >= class_getInstanceSize([Super class]) + 100); - if (objc_collectingEnabled()) testassert(auto_zone_is_valid_pointer(objc_collectableZone(), s)); - - object_dispose(s); - - s = class_createInstance([Sub class], 100); - testassert(s); - testassert(object_getClass(s) == [Sub class]); - testassert(malloc_size(s) >= class_getInstanceSize([Sub class]) + 100); - if (objc_collectingEnabled()) testassert(auto_zone_is_valid_pointer(objc_collectableZone(), s)); - - object_dispose(s); - - s = class_createInstance(Nil, 0); - testassert(!s); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/customrr-cat1.m b/objc/objc-runtime/test/customrr-cat1.m deleted file mode 100644 index 823238d..0000000 --- a/objc/objc-runtime/test/customrr-cat1.m +++ /dev/null @@ -1,7 +0,0 @@ -@interface InheritingSubCat @end - -@interface InheritingSubCat (NonClobberingCategory) @end - -@implementation InheritingSubCat (NonClobberingCategory) --(id) unrelatedMethod { return self; } -@end diff --git a/objc/objc-runtime/test/customrr-cat2.m b/objc/objc-runtime/test/customrr-cat2.m deleted file mode 100644 index 55c96df..0000000 --- a/objc/objc-runtime/test/customrr-cat2.m +++ /dev/null @@ -1,7 +0,0 @@ -@interface InheritingSubCat @end - -@interface InheritingSubCat (ClobberingCategory) @end - -@implementation InheritingSubCat (ClobberingCategory) --(int) retainCount { return 1; } -@end diff --git a/objc/objc-runtime/test/customrr-nsobject-awz.m b/objc/objc-runtime/test/customrr-nsobject-awz.m deleted file mode 100644 index b788729..0000000 --- a/objc/objc-runtime/test/customrr-nsobject-awz.m +++ /dev/null @@ -1,16 +0,0 @@ -/* - -TEST_CONFIG MEM=mrc -TEST_ENV OBJC_PRINT_CUSTOM_RR=YES OBJC_PRINT_CUSTOM_AWZ=YES - -TEST_BUILD - $C{COMPILE} $DIR/customrr-nsobject.m -o customrr-nsobject-awz.out -DSWIZZLE_AWZ=1 -END - -TEST_RUN_OUTPUT -objc\[\d+\]: CUSTOM AWZ: NSObject \(meta\) -OK: customrr-nsobject-awz.out -END - -*/ - diff --git a/objc/objc-runtime/test/customrr-nsobject-none.m b/objc/objc-runtime/test/customrr-nsobject-none.m deleted file mode 100644 index fb20f24..0000000 --- a/objc/objc-runtime/test/customrr-nsobject-none.m +++ /dev/null @@ -1,15 +0,0 @@ -/* - -TEST_CONFIG MEM=mrc -TEST_ENV OBJC_PRINT_CUSTOM_RR=YES OBJC_PRINT_CUSTOM_AWZ=YES - -TEST_BUILD - $C{COMPILE} $DIR/customrr-nsobject.m -o customrr-nsobject-none.out -END - -TEST_RUN_OUTPUT -OK: customrr-nsobject-none.out -END - -*/ - diff --git a/objc/objc-runtime/test/customrr-nsobject-rr.m b/objc/objc-runtime/test/customrr-nsobject-rr.m deleted file mode 100644 index 859d155..0000000 --- a/objc/objc-runtime/test/customrr-nsobject-rr.m +++ /dev/null @@ -1,16 +0,0 @@ -/* - -TEST_CONFIG MEM=mrc -TEST_ENV OBJC_PRINT_CUSTOM_RR=YES OBJC_PRINT_CUSTOM_AWZ=YES - -TEST_BUILD - $C{COMPILE} $DIR/customrr-nsobject.m -o customrr-nsobject-rr.out -DSWIZZLE_RELEASE=1 -END - -TEST_RUN_OUTPUT -objc\[\d+\]: CUSTOM RR: NSObject -OK: customrr-nsobject-rr.out -END - -*/ - diff --git a/objc/objc-runtime/test/customrr-nsobject-rrawz.m b/objc/objc-runtime/test/customrr-nsobject-rrawz.m deleted file mode 100644 index b0e546c..0000000 --- a/objc/objc-runtime/test/customrr-nsobject-rrawz.m +++ /dev/null @@ -1,17 +0,0 @@ -/* - -TEST_CONFIG MEM=mrc -TEST_ENV OBJC_PRINT_CUSTOM_RR=YES OBJC_PRINT_CUSTOM_AWZ=YES - -TEST_BUILD - $C{COMPILE} $DIR/customrr-nsobject.m -o customrr-nsobject-rrawz.out -DSWIZZLE_RELEASE=1 -DSWIZZLE_AWZ=1 -END - -TEST_RUN_OUTPUT -objc\[\d+\]: CUSTOM AWZ: NSObject \(meta\) -objc\[\d+\]: CUSTOM RR: NSObject -OK: customrr-nsobject-rrawz.out -END - -*/ - diff --git a/objc/objc-runtime/test/customrr-nsobject.m b/objc/objc-runtime/test/customrr-nsobject.m deleted file mode 100644 index d055f70..0000000 --- a/objc/objc-runtime/test/customrr-nsobject.m +++ /dev/null @@ -1,154 +0,0 @@ -// This file is used in the customrr-nsobject-*.m tests - -#include "test.h" -#include <objc/NSObject.h> - -#if __OBJC2__ -# define BYPASS 1 -#else -// old ABI does not implement the optimization -# define BYPASS 0 -#endif - -static int Retains; -static int Releases; -static int Autoreleases; -static int PlusInitializes; -static int Allocs; -static int AllocWithZones; - -id (*RealRetain)(id self, SEL _cmd); -void (*RealRelease)(id self, SEL _cmd); -id (*RealAutorelease)(id self, SEL _cmd); -id (*RealAlloc)(id self, SEL _cmd); -id (*RealAllocWithZone)(id self, SEL _cmd, void *zone); - -id HackRetain(id self, SEL _cmd) { Retains++; return RealRetain(self, _cmd); } -void HackRelease(id self, SEL _cmd) { Releases++; return RealRelease(self, _cmd); } -id HackAutorelease(id self, SEL _cmd) { Autoreleases++; return RealAutorelease(self, _cmd); } - -id HackAlloc(Class self, SEL _cmd) { Allocs++; return RealAlloc(self, _cmd); } -id HackAllocWithZone(Class self, SEL _cmd, void *zone) { AllocWithZones++; return RealAllocWithZone(self, _cmd, zone); } - -void HackPlusInitialize(id self __unused, SEL _cmd __unused) { PlusInitializes++; } - - -int main(int argc __unused, char **argv) -{ - Class cls = objc_getClass("NSObject"); - Method meth; - - meth = class_getClassMethod(cls, @selector(initialize)); - method_setImplementation(meth, (IMP)HackPlusInitialize); - - // We either swizzle the method normally (testing that it properly - // disables optimizations), or we hack the implementation into place - // behind objc's back (so we can see whether it got called with the - // optimizations still enabled). - - meth = class_getClassMethod(cls, @selector(allocWithZone:)); - RealAllocWithZone = (typeof(RealAllocWithZone))method_getImplementation(meth); -#if SWIZZLE_AWZ - method_setImplementation(meth, (IMP)HackAllocWithZone); -#else - ((IMP *)meth)[2] = (IMP)HackAllocWithZone; -#endif - - meth = class_getInstanceMethod(cls, @selector(release)); - RealRelease = (typeof(RealRelease))method_getImplementation(meth); -#if SWIZZLE_RELEASE - method_setImplementation(meth, (IMP)HackRelease); -#else - ((IMP *)meth)[2] = (IMP)HackRelease; -#endif - - // These other methods get hacked for counting purposes only - - meth = class_getInstanceMethod(cls, @selector(retain)); - RealRetain = (typeof(RealRetain))method_getImplementation(meth); - ((IMP *)meth)[2] = (IMP)HackRetain; - - meth = class_getInstanceMethod(cls, @selector(autorelease)); - RealAutorelease = (typeof(RealAutorelease))method_getImplementation(meth); - ((IMP *)meth)[2] = (IMP)HackAutorelease; - - meth = class_getClassMethod(cls, @selector(alloc)); - RealAlloc = (typeof(RealAlloc))method_getImplementation(meth); - ((IMP *)meth)[2] = (IMP)HackAlloc; - - // Verify that the swizzles occurred before +initialize by provoking it now - testassert(PlusInitializes == 0); - [NSObject self]; - testassert(PlusInitializes == 1); - -#if !__OBJC2__ - // hack: fool the expected output because old ABI doesn't optimize this -# if SWIZZLE_AWZ - fprintf(stderr, "objc[1234]: CUSTOM AWZ: NSObject (meta)\n"); -# endif -# if SWIZZLE_RELEASE - fprintf(stderr, "objc[1234]: CUSTOM RR: NSObject\n"); -# endif -#endif - - id obj; - - Allocs = 0; - AllocWithZones = 0; - obj = objc_alloc(cls); -#if SWIZZLE_AWZ || !BYPASS - testprintf("swizzled AWZ should be called\n"); - testassert(Allocs == 1); - testassert(AllocWithZones == 1); -#else - testprintf("unswizzled AWZ should be bypassed\n"); - testassert(Allocs == 0); - testassert(AllocWithZones == 0); -#endif - - Allocs = 0; - AllocWithZones = 0; - obj = [NSObject alloc]; -#if SWIZZLE_AWZ || !BYPASS - testprintf("swizzled AWZ should be called\n"); - testassert(Allocs == 1); - testassert(AllocWithZones == 1); -#else - testprintf("unswizzled AWZ should be bypassed\n"); - testassert(Allocs == 1); - testassert(AllocWithZones == 0); -#endif - - Retains = 0; - objc_retain(obj); -#if SWIZZLE_RELEASE || !BYPASS - testprintf("swizzled release should force retain\n"); - testassert(Retains == 1); -#else - testprintf("unswizzled release should bypass retain\n"); - testassert(Retains == 0); -#endif - - Releases = 0; - Autoreleases = 0; - PUSH_POOL { - objc_autorelease(obj); -#if SWIZZLE_RELEASE || !BYPASS - testprintf("swizzled release should force autorelease\n"); - testassert(Autoreleases == 1); -#else - testprintf("unswizzled release should bypass autorelease\n"); - testassert(Autoreleases == 0); -#endif - } POP_POOL - -#if SWIZZLE_RELEASE || !BYPASS - testprintf("swizzled release should be called\n"); - testassert(Releases == 1); -#else - testprintf("unswizzled release should be bypassed\n"); - testassert(Releases == 0); -#endif - - succeed(basename(argv[0])); -} diff --git a/objc/objc-runtime/test/customrr.m b/objc/objc-runtime/test/customrr.m deleted file mode 100644 index 7fa21ae..0000000 --- a/objc/objc-runtime/test/customrr.m +++ /dev/null @@ -1,904 +0,0 @@ -// These options must match customrr2.m -// TEST_CONFIG MEM=mrc -/* -TEST_BUILD - $C{COMPILE} $DIR/customrr.m -fvisibility=default -o customrr.out - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/customrr-cat1.m -o customrr-cat1.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/customrr-cat2.m -o customrr-cat2.dylib -END -*/ - - -#include "test.h" -#include <dlfcn.h> -#include <Foundation/NSObject.h> - -#if !__OBJC2__ - -// pacify exported symbols list -OBJC_ROOT_CLASS -@interface InheritingSubCat @end -@implementation InheritingSubCat @end - -int main(int argc __unused, char **argv) -{ - succeed(basename(argv[0])); -} - -#else - -static int Retains; -static int Releases; -static int Autoreleases; -static int RetainCounts; -static int PlusRetains; -static int PlusReleases; -static int PlusAutoreleases; -static int PlusRetainCounts; -static int Allocs; -static int AllocWithZones; - -static int SubRetains; -static int SubReleases; -static int SubAutoreleases; -static int SubRetainCounts; -static int SubPlusRetains; -static int SubPlusReleases; -static int SubPlusAutoreleases; -static int SubPlusRetainCounts; -static int SubAllocs; -static int SubAllocWithZones; - -static int Imps; - -static id imp_fn(id self, SEL _cmd __unused, ...) -{ - Imps++; - return self; -} - -static void zero(void) { - Retains = 0; - Releases = 0; - Autoreleases = 0; - RetainCounts = 0; - PlusRetains = 0; - PlusReleases = 0; - PlusAutoreleases = 0; - PlusRetainCounts = 0; - Allocs = 0; - AllocWithZones = 0; - - SubRetains = 0; - SubReleases = 0; - SubAutoreleases = 0; - SubRetainCounts = 0; - SubPlusRetains = 0; - SubPlusReleases = 0; - SubPlusAutoreleases = 0; - SubPlusRetainCounts = 0; - SubAllocs = 0; - SubAllocWithZones = 0; - - Imps = 0; -} - - -id HackRetain(id self, SEL _cmd __unused) { Retains++; return self; } -void HackRelease(id self __unused, SEL _cmd __unused) { Releases++; } -id HackAutorelease(id self, SEL _cmd __unused) { Autoreleases++; return self; } -NSUInteger HackRetainCount(id self __unused, SEL _cmd __unused) { RetainCounts++; return 1; } -id HackPlusRetain(id self, SEL _cmd __unused) { PlusRetains++; return self; } -void HackPlusRelease(id self __unused, SEL _cmd __unused) { PlusReleases++; } -id HackPlusAutorelease(id self, SEL _cmd __unused) { PlusAutoreleases++; return self; } -NSUInteger HackPlusRetainCount(id self __unused, SEL _cmd __unused) { PlusRetainCounts++; return 1; } -id HackAlloc(Class self, SEL _cmd __unused) { Allocs++; return class_createInstance(self, 0); } -id HackAllocWithZone(Class self, SEL _cmd __unused) { AllocWithZones++; return class_createInstance(self, 0); } - - -@interface OverridingSub : NSObject @end -@implementation OverridingSub - --(id) retain { SubRetains++; return self; } -+(id) retain { SubPlusRetains++; return self; } --(oneway void) release { SubReleases++; } -+(oneway void) release { SubPlusReleases++; } --(id) autorelease { SubAutoreleases++; return self; } -+(id) autorelease { SubPlusAutoreleases++; return self; } --(NSUInteger) retainCount { SubRetainCounts++; return 1; } -+(NSUInteger) retainCount { SubPlusRetainCounts++; return 1; } - -@end - -@interface OverridingASub : NSObject @end -@implementation OverridingASub -+(id) alloc { SubAllocs++; return class_createInstance(self, 0); } -@end - -@interface OverridingAWZSub : NSObject @end -@implementation OverridingAWZSub -+(id) allocWithZone:(NSZone * __unused)z { SubAllocWithZones++; return class_createInstance(self, 0); } -@end - -@interface OverridingAAWZSub : NSObject @end -@implementation OverridingAAWZSub -+(id) alloc { SubAllocs++; return class_createInstance(self, 0); } -+(id) allocWithZone:(NSZone * __unused)z { SubAllocWithZones++; return class_createInstance(self, 0); } -@end - - -@interface InheritingSub : NSObject @end -@implementation InheritingSub @end - -@interface InheritingSub2 : NSObject @end -@implementation InheritingSub2 @end -@interface InheritingSub2_2 : InheritingSub2 @end -@implementation InheritingSub2_2 @end - -@interface InheritingSub3 : NSObject @end -@implementation InheritingSub3 @end -@interface InheritingSub3_2 : InheritingSub3 @end -@implementation InheritingSub3_2 @end - -@interface InheritingSub4 : NSObject @end -@implementation InheritingSub4 @end -@interface InheritingSub4_2 : InheritingSub4 @end -@implementation InheritingSub4_2 @end - -@interface InheritingSub5 : NSObject @end -@implementation InheritingSub5 @end -@interface InheritingSub5_2 : InheritingSub5 @end -@implementation InheritingSub5_2 @end - -@interface InheritingSub6 : NSObject @end -@implementation InheritingSub6 @end -@interface InheritingSub6_2 : InheritingSub6 @end -@implementation InheritingSub6_2 @end - -@interface InheritingSub7 : NSObject @end -@implementation InheritingSub7 @end -@interface InheritingSub7_2 : InheritingSub7 @end -@implementation InheritingSub7_2 @end - -@interface InheritingSubCat : NSObject @end -@implementation InheritingSubCat @end -@interface InheritingSubCat_2 : InheritingSubCat @end -@implementation InheritingSubCat_2 @end - - -extern uintptr_t OBJC_CLASS_$_UnrealizedSubA1; -@interface UnrealizedSubA1 : NSObject @end -@implementation UnrealizedSubA1 @end -extern uintptr_t OBJC_CLASS_$_UnrealizedSubA2; -@interface UnrealizedSubA2 : NSObject @end -@implementation UnrealizedSubA2 @end -extern uintptr_t OBJC_CLASS_$_UnrealizedSubA3; -@interface UnrealizedSubA3 : NSObject @end -@implementation UnrealizedSubA3 @end - -extern uintptr_t OBJC_CLASS_$_UnrealizedSubB1; -@interface UnrealizedSubB1 : NSObject @end -@implementation UnrealizedSubB1 @end -extern uintptr_t OBJC_CLASS_$_UnrealizedSubB2; -@interface UnrealizedSubB2 : NSObject @end -@implementation UnrealizedSubB2 @end -extern uintptr_t OBJC_CLASS_$_UnrealizedSubB3; -@interface UnrealizedSubB3 : NSObject @end -@implementation UnrealizedSubB3 @end - -extern uintptr_t OBJC_CLASS_$_UnrealizedSubC1; -@interface UnrealizedSubC1 : NSObject @end -@implementation UnrealizedSubC1 @end -extern uintptr_t OBJC_CLASS_$_UnrealizedSubC2; -@interface UnrealizedSubC2 : NSObject @end -@implementation UnrealizedSubC2 @end -extern uintptr_t OBJC_CLASS_$_UnrealizedSubC3; -@interface UnrealizedSubC3 : NSObject @end -@implementation UnrealizedSubC3 @end - - -int main(int argc __unused, char **argv) -{ - objc_autoreleasePoolPush(); - - // Hack NSObject's RR methods. - // Don't use runtime functions to do this - - // we want the runtime to think that these are NSObject's real code - { - Class cls = [NSObject class]; - IMP *m; - IMP imp; - imp = class_getMethodImplementation(cls, @selector(retain)); - m = (IMP *)class_getInstanceMethod(cls, @selector(retain)); - testassert(m[2] == imp); // verify Method struct is as we expect - - m = (IMP *)class_getInstanceMethod(cls, @selector(retain)); - m[2] = (IMP)HackRetain; - m = (IMP *)class_getInstanceMethod(cls, @selector(release)); - m[2] = (IMP)HackRelease; - m = (IMP *)class_getInstanceMethod(cls, @selector(autorelease)); - m[2] = (IMP)HackAutorelease; - m = (IMP *)class_getInstanceMethod(cls, @selector(retainCount)); - m[2] = (IMP)HackRetainCount; - m = (IMP *)class_getClassMethod(cls, @selector(retain)); - m[2] = (IMP)HackPlusRetain; - m = (IMP *)class_getClassMethod(cls, @selector(release)); - m[2] = (IMP)HackPlusRelease; - m = (IMP *)class_getClassMethod(cls, @selector(autorelease)); - m[2] = (IMP)HackPlusAutorelease; - m = (IMP *)class_getClassMethod(cls, @selector(retainCount)); - m[2] = (IMP)HackPlusRetainCount; - m = (IMP *)class_getClassMethod(cls, @selector(alloc)); - m[2] = (IMP)HackAlloc; - m = (IMP *)class_getClassMethod(cls, @selector(allocWithZone:)); - m[2] = (IMP)HackAllocWithZone; - - _objc_flush_caches(cls); - - imp = class_getMethodImplementation(cls, @selector(retain)); - testassert(imp == (IMP)HackRetain); // verify hack worked - } - - Class cls = [NSObject class]; - Class icl = [InheritingSub class]; - Class ocl = [OverridingSub class]; - /* - Class oa1 = [OverridingASub class]; - Class oa2 = [OverridingAWZSub class]; - Class oa3 = [OverridingAAWZSub class]; - */ - NSObject *obj = [NSObject new]; - InheritingSub *inh = [InheritingSub new]; - OverridingSub *ovr = [OverridingSub new]; - - Class ccc; - id ooo; - Class cc2; - id oo2; - - void *dlh; - - -#if __x86_64__ - // vtable dispatch can introduce bypass just like the ARC entrypoints -#else - testprintf("method dispatch does not bypass\n"); - zero(); - - [obj retain]; - testassert(Retains == 1); - [obj release]; - testassert(Releases == 1); - [obj autorelease]; - testassert(Autoreleases == 1); - - [cls retain]; - testassert(PlusRetains == 1); - [cls release]; - testassert(PlusReleases == 1); - [cls autorelease]; - testassert(PlusAutoreleases == 1); - - [inh retain]; - testassert(Retains == 2); - [inh release]; - testassert(Releases == 2); - [inh autorelease]; - testassert(Autoreleases == 2); - - [icl retain]; - testassert(PlusRetains == 2); - [icl release]; - testassert(PlusReleases == 2); - [icl autorelease]; - testassert(PlusAutoreleases == 2); - - [ovr retain]; - testassert(SubRetains == 1); - [ovr release]; - testassert(SubReleases == 1); - [ovr autorelease]; - testassert(SubAutoreleases == 1); - - [ocl retain]; - testassert(SubPlusRetains == 1); - [ocl release]; - testassert(SubPlusReleases == 1); - [ocl autorelease]; - testassert(SubPlusAutoreleases == 1); - - [UnrealizedSubA1 retain]; - testassert(PlusRetains == 3); - [UnrealizedSubA2 release]; - testassert(PlusReleases == 3); - [UnrealizedSubA3 autorelease]; - testassert(PlusAutoreleases == 3); -#endif - - - testprintf("objc_msgSend() does not bypass\n"); - zero(); - - id (*retain_fn)(id, SEL) = (id(*)(id, SEL))objc_msgSend; - void (*release_fn)(id, SEL) = (void(*)(id, SEL))objc_msgSend; - id (*autorelease_fn)(id, SEL) = (id(*)(id, SEL))objc_msgSend; - - retain_fn(obj, @selector(retain)); - testassert(Retains == 1); - release_fn(obj, @selector(release)); - testassert(Releases == 1); - autorelease_fn(obj, @selector(autorelease)); - testassert(Autoreleases == 1); - - retain_fn(cls, @selector(retain)); - testassert(PlusRetains == 1); - release_fn(cls, @selector(release)); - testassert(PlusReleases == 1); - autorelease_fn(cls, @selector(autorelease)); - testassert(PlusAutoreleases == 1); - - retain_fn(inh, @selector(retain)); - testassert(Retains == 2); - release_fn(inh, @selector(release)); - testassert(Releases == 2); - autorelease_fn(inh, @selector(autorelease)); - testassert(Autoreleases == 2); - - retain_fn(icl, @selector(retain)); - testassert(PlusRetains == 2); - release_fn(icl, @selector(release)); - testassert(PlusReleases == 2); - autorelease_fn(icl, @selector(autorelease)); - testassert(PlusAutoreleases == 2); - - retain_fn(ovr, @selector(retain)); - testassert(SubRetains == 1); - release_fn(ovr, @selector(release)); - testassert(SubReleases == 1); - autorelease_fn(ovr, @selector(autorelease)); - testassert(SubAutoreleases == 1); - - retain_fn(ocl, @selector(retain)); - testassert(SubPlusRetains == 1); - release_fn(ocl, @selector(release)); - testassert(SubPlusReleases == 1); - autorelease_fn(ocl, @selector(autorelease)); - testassert(SubPlusAutoreleases == 1); - -#if __OBJC2__ - retain_fn((Class)&OBJC_CLASS_$_UnrealizedSubB1, @selector(retain)); - testassert(PlusRetains == 3); - release_fn((Class)&OBJC_CLASS_$_UnrealizedSubB2, @selector(release)); - testassert(PlusReleases == 3); - autorelease_fn((Class)&OBJC_CLASS_$_UnrealizedSubB3, @selector(autorelease)); - testassert(PlusAutoreleases == 3); -#endif - - - testprintf("arc function bypasses instance but not class or override\n"); - zero(); - - objc_retain(obj); - testassert(Retains == 0); - objc_release(obj); - testassert(Releases == 0); - objc_autorelease(obj); - testassert(Autoreleases == 0); - - objc_retain(cls); - testassert(PlusRetains == 1); - objc_release(cls); - testassert(PlusReleases == 1); - objc_autorelease(cls); - testassert(PlusAutoreleases == 1); - - objc_retain(inh); - testassert(Retains == 0); - objc_release(inh); - testassert(Releases == 0); - objc_autorelease(inh); - testassert(Autoreleases == 0); - - objc_retain(icl); - testassert(PlusRetains == 2); - objc_release(icl); - testassert(PlusReleases == 2); - objc_autorelease(icl); - testassert(PlusAutoreleases == 2); - - objc_retain(ovr); - testassert(SubRetains == 1); - objc_release(ovr); - testassert(SubReleases == 1); - objc_autorelease(ovr); - testassert(SubAutoreleases == 1); - - objc_retain(ocl); - testassert(SubPlusRetains == 1); - objc_release(ocl); - testassert(SubPlusReleases == 1); - objc_autorelease(ocl); - testassert(SubPlusAutoreleases == 1); - -#if __OBJC2__ - objc_retain((Class)&OBJC_CLASS_$_UnrealizedSubC1); - testassert(PlusRetains == 3); - objc_release((Class)&OBJC_CLASS_$_UnrealizedSubC2); - testassert(PlusReleases == 3); - objc_autorelease((Class)&OBJC_CLASS_$_UnrealizedSubC3); - testassert(PlusAutoreleases == 3); -#endif - - - testprintf("unrelated addMethod does not clobber\n"); - zero(); - - class_addMethod(cls, @selector(unrelatedMethod), (IMP)imp_fn, ""); - - objc_retain(obj); - testassert(Retains == 0); - objc_release(obj); - testassert(Releases == 0); - objc_autorelease(obj); - testassert(Autoreleases == 0); - - - testprintf("add class method does not clobber\n"); - zero(); - - objc_retain(obj); - testassert(Retains == 0); - objc_release(obj); - testassert(Releases == 0); - objc_autorelease(obj); - testassert(Autoreleases == 0); - - class_addMethod(object_getClass(cls), @selector(retain), (IMP)imp_fn, ""); - - objc_retain(obj); - testassert(Retains == 0); - objc_release(obj); - testassert(Releases == 0); - objc_autorelease(obj); - testassert(Autoreleases == 0); - - - testprintf("addMethod clobbers (InheritingSub2, retain)\n"); - zero(); - - ccc = [InheritingSub2 class]; - ooo = [ccc new]; - cc2 = [InheritingSub2_2 class]; - oo2 = [cc2 new]; - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - class_addMethod(ccc, @selector(retain), (IMP)imp_fn, ""); - - objc_retain(ooo); - testassert(Retains == 0); - testassert(Imps == 1); - objc_release(ooo); - testassert(Releases == 1); - objc_autorelease(ooo); - testassert(Autoreleases == 1); - - objc_retain(oo2); - testassert(Retains == 0); - testassert(Imps == 2); - objc_release(oo2); - testassert(Releases == 2); - objc_autorelease(oo2); - testassert(Autoreleases == 2); - - - testprintf("addMethod clobbers (InheritingSub3, release)\n"); - zero(); - - ccc = [InheritingSub3 class]; - ooo = [ccc new]; - cc2 = [InheritingSub3_2 class]; - oo2 = [cc2 new]; - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - class_addMethod(ccc, @selector(release), (IMP)imp_fn, ""); - - objc_retain(ooo); - testassert(Retains == 1); - objc_release(ooo); - testassert(Releases == 0); - testassert(Imps == 1); - objc_autorelease(ooo); - testassert(Autoreleases == 1); - - objc_retain(oo2); - testassert(Retains == 2); - objc_release(oo2); - testassert(Releases == 0); - testassert(Imps == 2); - objc_autorelease(oo2); - testassert(Autoreleases == 2); - - - testprintf("addMethod clobbers (InheritingSub4, autorelease)\n"); - zero(); - - ccc = [InheritingSub4 class]; - ooo = [ccc new]; - cc2 = [InheritingSub4_2 class]; - oo2 = [cc2 new]; - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - class_addMethod(ccc, @selector(autorelease), (IMP)imp_fn, ""); - - objc_retain(ooo); - testassert(Retains == 1); - objc_release(ooo); - testassert(Releases == 1); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - testassert(Imps == 1); - - objc_retain(oo2); - testassert(Retains == 2); - objc_release(oo2); - testassert(Releases == 2); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - testassert(Imps == 2); - - - testprintf("addMethod clobbers (InheritingSub5, retainCount)\n"); - zero(); - - ccc = [InheritingSub5 class]; - ooo = [ccc new]; - cc2 = [InheritingSub5_2 class]; - oo2 = [cc2 new]; - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - class_addMethod(ccc, @selector(retainCount), (IMP)imp_fn, ""); - - objc_retain(ooo); - testassert(Retains == 1); - objc_release(ooo); - testassert(Releases == 1); - objc_autorelease(ooo); - testassert(Autoreleases == 1); - // no bypassing call for -retainCount - - objc_retain(oo2); - testassert(Retains == 2); - objc_release(oo2); - testassert(Releases == 2); - objc_autorelease(oo2); - testassert(Autoreleases == 2); - // no bypassing call for -retainCount - - - testprintf("setSuperclass to clean super does not clobber (InheritingSub6)\n"); - zero(); - - ccc = [InheritingSub6 class]; - ooo = [ccc new]; - cc2 = [InheritingSub6_2 class]; - oo2 = [cc2 new]; - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - class_setSuperclass(ccc, [InheritingSub class]); - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - - testprintf("setSuperclass to dirty super clobbers (InheritingSub7)\n"); - zero(); - - ccc = [InheritingSub7 class]; - ooo = [ccc new]; - cc2 = [InheritingSub7_2 class]; - oo2 = [cc2 new]; - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - class_setSuperclass(ccc, [OverridingSub class]); - - objc_retain(ooo); - testassert(SubRetains == 1); - objc_release(ooo); - testassert(SubReleases == 1); - objc_autorelease(ooo); - testassert(SubAutoreleases == 1); - - objc_retain(oo2); - testassert(SubRetains == 2); - objc_release(oo2); - testassert(SubReleases == 2); - objc_autorelease(oo2); - testassert(SubAutoreleases == 2); - - - testprintf("category replacement of unrelated method does not clobber (InheritingSubCat)\n"); - zero(); - - ccc = [InheritingSubCat class]; - ooo = [ccc new]; - cc2 = [InheritingSubCat_2 class]; - oo2 = [cc2 new]; - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - dlh = dlopen("customrr-cat1.dylib", RTLD_LAZY); - testassert(dlh); - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - - testprintf("category replacement clobbers (InheritingSubCat)\n"); - zero(); - - ccc = [InheritingSubCat class]; - ooo = [ccc new]; - cc2 = [InheritingSubCat_2 class]; - oo2 = [cc2 new]; - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - objc_retain(oo2); - testassert(Retains == 0); - objc_release(oo2); - testassert(Releases == 0); - objc_autorelease(oo2); - testassert(Autoreleases == 0); - - dlh = dlopen("customrr-cat2.dylib", RTLD_LAZY); - testassert(dlh); - - objc_retain(ooo); - testassert(Retains == 1); - objc_release(ooo); - testassert(Releases == 1); - objc_autorelease(ooo); - testassert(Autoreleases == 1); - - objc_retain(oo2); - testassert(Retains == 2); - objc_release(oo2); - testassert(Releases == 2); - objc_autorelease(oo2); - testassert(Autoreleases == 2); - - - testprintf("allocateClassPair with clean super does not clobber\n"); - zero(); - - objc_retain(inh); - testassert(Retains == 0); - objc_release(inh); - testassert(Releases == 0); - objc_autorelease(inh); - testassert(Autoreleases == 0); - - ccc = objc_allocateClassPair([InheritingSub class], "CleanClassPair", 0); - objc_registerClassPair(ccc); - ooo = [ccc new]; - - objc_retain(inh); - testassert(Retains == 0); - objc_release(inh); - testassert(Releases == 0); - objc_autorelease(inh); - testassert(Autoreleases == 0); - - objc_retain(ooo); - testassert(Retains == 0); - objc_release(ooo); - testassert(Releases == 0); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - - - testprintf("allocateClassPair with clobbered super clobbers\n"); - zero(); - - ccc = objc_allocateClassPair([OverridingSub class], "DirtyClassPair", 0); - objc_registerClassPair(ccc); - ooo = [ccc new]; - - objc_retain(ooo); - testassert(SubRetains == 1); - objc_release(ooo); - testassert(SubReleases == 1); - objc_autorelease(ooo); - testassert(SubAutoreleases == 1); - - - testprintf("allocateClassPair with clean super and override clobbers\n"); - zero(); - - ccc = objc_allocateClassPair([InheritingSub class], "Dirty2ClassPair", 0); - class_addMethod(ccc, @selector(autorelease), (IMP)imp_fn, ""); - objc_registerClassPair(ccc); - ooo = [ccc new]; - - objc_retain(ooo); - testassert(Retains == 1); - objc_release(ooo); - testassert(Releases == 1); - objc_autorelease(ooo); - testassert(Autoreleases == 0); - testassert(Imps == 1); - - - // method_setImplementation and method_exchangeImplementations only - // clobber when manipulating NSObject. We can only test one at a time. - // To test both, we need two tests: customrr and customrr2. - - // These tests also check recursive clobber. - -#if TEST_EXCHANGEIMPLEMENTATIONS - testprintf("exchangeImplementations clobbers (recursive)\n"); -#else - testprintf("setImplementation clobbers (recursive)\n"); -#endif - zero(); - - objc_retain(obj); - testassert(Retains == 0); - objc_release(obj); - testassert(Releases == 0); - objc_autorelease(obj); - testassert(Autoreleases == 0); - - objc_retain(inh); - testassert(Retains == 0); - objc_release(inh); - testassert(Releases == 0); - objc_autorelease(inh); - testassert(Autoreleases == 0); - - Method meth = class_getInstanceMethod(cls, @selector(retainCount)); - testassert(meth); -#if TEST_EXCHANGEIMPLEMENTATIONS - method_exchangeImplementations(meth, meth); -#else - method_setImplementation(meth, (IMP)imp_fn); -#endif - - objc_retain(obj); - testassert(Retains == 1); - objc_release(obj); - testassert(Releases == 1); - objc_autorelease(obj); - testassert(Autoreleases == 1); - - objc_retain(inh); - testassert(Retains == 2); - objc_release(inh); - testassert(Releases == 2); - objc_autorelease(inh); - testassert(Autoreleases == 2); - - - // do not add more tests here - the recursive test must be LAST - - succeed(basename(argv[0])); -} - -#endif diff --git a/objc/objc-runtime/test/customrr2.m b/objc/objc-runtime/test/customrr2.m deleted file mode 100644 index cd49f38..0000000 --- a/objc/objc-runtime/test/customrr2.m +++ /dev/null @@ -1,9 +0,0 @@ -// These options must match customrr.m -// TEST_CONFIG MEM=mrc -/* -TEST_BUILD - $C{COMPILE} $DIR/customrr.m -fvisibility=default -o customrr2.out -DTEST_EXCHANGEIMPLEMENTATIONS=1 - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/customrr-cat1.m -o customrr-cat1.dylib - $C{COMPILE} -undefined dynamic_lookup -dynamiclib $DIR/customrr-cat2.m -o customrr-cat2.dylib -END -*/ diff --git a/objc/objc-runtime/test/definitions.c b/objc/objc-runtime/test/definitions.c deleted file mode 100644 index c351234..0000000 --- a/objc/objc-runtime/test/definitions.c +++ /dev/null @@ -1,56 +0,0 @@ -// TEST_CONFIG - -// DO NOT include anything else here -#include <objc/objc.h> -// DO NOT include anything else here -Class c = Nil; -SEL s; -IMP i; -id o = nil; -BOOL b = YES; -BOOL b2 = NO; -#if !__has_feature(objc_arc) -__strong void *p; -#endif -id __unsafe_unretained u; -id __weak w; - -void fn(void) __unused; -void fn(void) { - id __autoreleasing a __unused; -} - -#if __llvm__ && !__clang__ -// llvm-gcc defines _NSConcreteGlobalBlock wrong -#else -// rdar://10118972 wrong type inference for blocks returning YES and NO -BOOL (^block1)(void) = ^{ return YES; }; -BOOL (^block2)(void) = ^{ return NO; }; -#endif - -#include "test.h" - -int main() -{ - testassert(YES); - testassert(!NO); -#if __cplusplus - testwarn("rdar://12371870 -Wnull-conversion"); - testassert(!(bool)nil); - testassert(!(bool)Nil); -#else - testassert(!nil); - testassert(!Nil); -#endif - -#if __has_feature(objc_bool) - // YES[array] is disallowed for objc just as true[array] is for C++ -#else - // this will fail if YES and NO do not have enough parentheses - int array[2] = { 888, 999 }; - testassert(NO[array] == 888); - testassert(YES[array] == 999); -#endif - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/designatedinit.m b/objc/objc-runtime/test/designatedinit.m deleted file mode 100644 index 232625f..0000000 --- a/objc/objc-runtime/test/designatedinit.m +++ /dev/null @@ -1,26 +0,0 @@ -// TEST_CONFIG -/* TEST_BUILD_OUTPUT -.*designatedinit.m:\d+:\d+: warning: designated initializer should only invoke a designated initializer on 'super'.* -.*designatedinit.m:\d+:\d+: note: .* -.*designatedinit.m:\d+:\d+: warning: method override for the designated initializer of the superclass '-init' not found.* -.*NSObject.h:\d+:\d+: note: .* -END */ - -#define NS_ENFORCE_NSOBJECT_DESIGNATED_INITIALIZER 1 -#include "test.h" -#include <objc/NSObject.h> - -@interface C : NSObject --(id) initWithInt:(int)i NS_DESIGNATED_INITIALIZER; -@end - -@implementation C --(id) initWithInt:(int)__unused i { - return [self init]; -} -@end - -int main() -{ - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/duplicateClass.m b/objc/objc-runtime/test/duplicateClass.m deleted file mode 100644 index 0ac2671..0000000 --- a/objc/objc-runtime/test/duplicateClass.m +++ /dev/null @@ -1,164 +0,0 @@ -// TEST_CFLAGS -Wno-deprecated-declarations -Wl,-no_objc_category_merging - -#include "test.h" -#include "testroot.i" -#include <objc/runtime.h> -#ifndef OBJC_NO_GC -#include <objc/objc-auto.h> -#include <auto_zone.h> -#endif - -static int state; - -@protocol Proto -+(void)classMethod; --(void)instanceMethod; -@end - -@interface Super : TestRoot <Proto> { - int i; -} -@property int i; -@end - -@implementation Super -@synthesize i; - -+(void)classMethod { - state = 1; -} - --(void)instanceMethod { - state = 3; -} - -@end - - -#if __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation" -#endif - -@implementation Super (Category) - -+(void)classMethod { - state = 2; -} - --(void)instanceMethod { - state = 4; -} - -@end - -#if __clang__ -#pragma clang diagnostic pop -#endif - - -int main() -{ - Class clone; - Class cls; - Method *m1, *m2; - int i; - - cls = [Super class]; - clone = objc_duplicateClass(cls, "Super_copy", 0); -#ifndef OBJC_NO_GC - if (objc_collectingEnabled()) { - testassert(auto_zone_size(objc_collectableZone(), objc_unretainedPointer(clone))); - // objc_duplicateClass() doesn't duplicate the metaclass - // no: testassert(auto_zone_size(objc_collectableZone(), clone->isa)); - } -#endif - - testassert(clone != cls); - testassert(object_getClass(clone) == object_getClass(cls)); - testassert(class_getSuperclass(clone) == class_getSuperclass(cls)); - testassert(class_getVersion(clone) == class_getVersion(cls)); - testassert(class_isMetaClass(clone) == class_isMetaClass(cls)); - testassert(class_getIvarLayout(clone) == class_getIvarLayout(cls)); - testassert(class_getWeakIvarLayout(clone) == class_getWeakIvarLayout(cls)); -#if !__OBJC2__ - testassert((clone->info & (CLS_CLASS|CLS_META)) == (cls->info & (CLS_CLASS|CLS_META))); -#endif - - // Check method list - - m1 = class_copyMethodList(cls, NULL); - m2 = class_copyMethodList(clone, NULL); - testassert(m1); - testassert(m2); - for (i = 0; m1[i] && m2[i]; i++) { - testassert(m1[i] != m2[i]); // method list must be deep-copied - testassert(method_getName(m1[i]) == method_getName(m2[i])); - testassert(method_getImplementation(m1[i]) == method_getImplementation(m2[i])); - testassert(method_getTypeEncoding(m1[i]) == method_getTypeEncoding(m2[i])); - } - testassert(m1[i] == NULL && m2[i] == NULL); - free(m1); - free(m2); - - // Check ivar list - Ivar *i1 = class_copyIvarList(cls, NULL); - Ivar *i2 = class_copyIvarList(clone, NULL); - testassert(i1); - testassert(i2); - for (i = 0; i1[i] && i2[i]; i++) { - testassert(i1[i] == i2[i]); // ivars are not deep-copied - } - testassert(i1[i] == NULL && i2[i] == NULL); - free(i1); - free(i2); - - // Check protocol list - Protocol * __unsafe_unretained *p1 = class_copyProtocolList(cls, NULL); - Protocol * __unsafe_unretained *p2 = class_copyProtocolList(clone, NULL); - testassert(p1); - testassert(p2); - for (i = 0; p1[i] && p2[i]; i++) { - testassert(p1[i] == p2[i]); // protocols are not deep-copied - } - testassert(p1[i] == NULL && p2[i] == NULL); - free(p1); - free(p2); - - // Check property list - objc_property_t *o1 = class_copyPropertyList(cls, NULL); - objc_property_t *o2 = class_copyPropertyList(clone, NULL); - testassert(o1); - testassert(o2); - for (i = 0; o1[i] && o2[i]; i++) { - testassert(o1[i] == o2[i]); // properties are not deep-copied - } - testassert(o1[i] == NULL && o2[i] == NULL); - free(o1); - free(o2); - - // Check method calls - - state = 0; - [cls classMethod]; - testassert(state == 2); - state = 0; - [clone classMethod]; - testassert(state == 2); - - // #4511660 Make sure category implementation is still the preferred one - id obj; - obj = [cls new]; - state = 0; - [obj instanceMethod]; - testassert(state == 4); - RELEASE_VAR(obj); - - obj = [clone new]; - state = 0; - [obj instanceMethod]; - testassert(state == 4); - RELEASE_VAR(obj); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/duplicatedClasses.m b/objc/objc-runtime/test/duplicatedClasses.m deleted file mode 100644 index 991b133..0000000 --- a/objc/objc-runtime/test/duplicatedClasses.m +++ /dev/null @@ -1,27 +0,0 @@ -// TEST_ENV OBJC_DEBUG_DUPLICATE_CLASSES=YES -// TEST_CRASHES -/* -TEST_RUN_OUTPUT -objc\[\d+\]: Class GKScore is implemented in both [^\s]+ and [^\s]+ One of the two will be used. Which one is undefined. -CRASHED: SIG(ILL|TRAP) -OR -OK: duplicatedClasses.m -END - */ - -#include "test.h" -#include "testroot.i" - -@interface GKScore : TestRoot @end -@implementation GKScore @end - -int main() -{ - if (objc_collectingEnabled()) { - testwarn("rdar://19042235 test disabled because GameKit is not GC"); - succeed(__FILE__); - } - void *dl = dlopen("/System/Library/Frameworks/GameKit.framework/GameKit", RTLD_LAZY); - if (!dl) fail("couldn't open GameKit"); - fail("should have crashed already"); -} diff --git a/objc/objc-runtime/test/evil-category-0.m b/objc/objc-runtime/test/evil-category-0.m deleted file mode 100644 index a0d6060..0000000 --- a/objc/objc-runtime/test/evil-category-0.m +++ /dev/null @@ -1,18 +0,0 @@ -/* -rdar://8553305 - -TEST_BUILD - $C{COMPILE} $DIR/evil-category-0.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none -DNOT_EVIL libevil.dylib -o evil-category-0.out -END -*/ - -// NOT EVIL version - -#define EVIL_INSTANCE_METHOD 0 -#define EVIL_CLASS_METHOD 0 - -#define OMIT_CAT 0 -#define OMIT_NL_CAT 0 - -#include "evil-category-def.m" diff --git a/objc/objc-runtime/test/evil-category-00.m b/objc/objc-runtime/test/evil-category-00.m deleted file mode 100644 index 4bc050d..0000000 --- a/objc/objc-runtime/test/evil-category-00.m +++ /dev/null @@ -1,24 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-category-00.m $DIR/evil-main.m -o evil-category-00.out -END - -TEST_RUN_OUTPUT -CRASHED: SIGSEGV -END -*/ - -// NOT EVIL version: apps are allowed through (then crash in +load) - -#define EVIL_INSTANCE_METHOD 1 -#define EVIL_CLASS_METHOD 1 - -#define OMIT_CAT 0 -#define OMIT_NL_CAT 0 - -#include "evil-category-def.m" diff --git a/objc/objc-runtime/test/evil-category-000.m b/objc/objc-runtime/test/evil-category-000.m deleted file mode 100644 index e451706..0000000 --- a/objc/objc-runtime/test/evil-category-000.m +++ /dev/null @@ -1,18 +0,0 @@ -/* -rdar://8553305 - -TEST_BUILD - $C{COMPILE} $DIR/evil-category-000.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none -DNOT_EVIL libevil.dylib -o evil-category-000.out -END -*/ - -// NOT EVIL version: category omitted from all lists - -#define EVIL_INSTANCE_METHOD 1 -#define EVIL_CLASS_METHOD 1 - -#define OMIT_CAT 1 -#define OMIT_NL_CAT 1 - -#include "evil-category-def.m" diff --git a/objc/objc-runtime/test/evil-category-1.m b/objc/objc-runtime/test/evil-category-1.m deleted file mode 100644 index 7a84f84..0000000 --- a/objc/objc-runtime/test/evil-category-1.m +++ /dev/null @@ -1,24 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-category-1.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none libevil.dylib -o evil-category-1.out -END - -TEST_RUN_OUTPUT -objc\[\d+\]: bad method implementation \(0x[0-9a-f]+ at 0x[0-9a-f]+\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#define EVIL_INSTANCE_METHOD 1 -#define EVIL_CLASS_METHOD 0 - -#define OMIT_CAT 0 -#define OMIT_NL_CAT 0 - -#include "evil-category-def.m" diff --git a/objc/objc-runtime/test/evil-category-2.m b/objc/objc-runtime/test/evil-category-2.m deleted file mode 100644 index 65f7e3b..0000000 --- a/objc/objc-runtime/test/evil-category-2.m +++ /dev/null @@ -1,24 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-category-2.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none libevil.dylib -o evil-category-2.out -END - -TEST_RUN_OUTPUT -objc\[\d+\]: bad method implementation \(0x[0-9a-f]+ at 0x[0-9a-f]+\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#define EVIL_INSTANCE_METHOD 0 -#define EVIL_CLASS_METHOD 1 - -#define OMIT_CAT 0 -#define OMIT_NL_CAT 0 - -#include "evil-category-def.m" diff --git a/objc/objc-runtime/test/evil-category-3.m b/objc/objc-runtime/test/evil-category-3.m deleted file mode 100644 index 6be6d0b..0000000 --- a/objc/objc-runtime/test/evil-category-3.m +++ /dev/null @@ -1,24 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-category-3.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none libevil.dylib -o evil-category-3.out -END - -TEST_RUN_OUTPUT -objc\[\d+\]: bad method implementation \(0x[0-9a-f]+ at 0x[0-9a-f]+\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#define EVIL_INSTANCE_METHOD 0 -#define EVIL_CLASS_METHOD 1 - -#define OMIT_CAT 1 -#define OMIT_NL_CAT 0 - -#include "evil-category-def.m" diff --git a/objc/objc-runtime/test/evil-category-4.m b/objc/objc-runtime/test/evil-category-4.m deleted file mode 100644 index 4f0a9eb..0000000 --- a/objc/objc-runtime/test/evil-category-4.m +++ /dev/null @@ -1,24 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-category-4.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none libevil.dylib -o evil-category-4.out -END - -TEST_RUN_OUTPUT -objc\[\d+\]: bad method implementation \(0x[0-9a-f]+ at 0x[0-9a-f]+\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#define EVIL_INSTANCE_METHOD 0 -#define EVIL_CLASS_METHOD 1 - -#define OMIT_CAT 0 -#define OMIT_NL_CAT 1 - -#include "evil-category-def.m" diff --git a/objc/objc-runtime/test/evil-category-def.m b/objc/objc-runtime/test/evil-category-def.m deleted file mode 100644 index a4bd1dc..0000000 --- a/objc/objc-runtime/test/evil-category-def.m +++ /dev/null @@ -1,72 +0,0 @@ - -#if __OBJC2__ - -#include <mach/shared_region.h> - -#if __LP64__ -# define PTR " .quad " -#else -# define PTR " .long " -#endif - -#define str(x) #x -#define str2(x) str(x) - -__BEGIN_DECLS -void nop(void) { } -__END_DECLS - -asm( - ".section __DATA,__objc_data \n" - ".align 3 \n" - "L_category: \n" - PTR "L_cat_name \n" - PTR "_OBJC_CLASS_$_NSObject \n" -#if EVIL_INSTANCE_METHOD - PTR "L_evil_methods \n" -#else - PTR "L_good_methods \n" -#endif -#if EVIL_CLASS_METHOD - PTR "L_evil_methods \n" -#else - PTR "L_good_methods \n" -#endif - PTR "0 \n" - PTR "0 \n" - - "L_evil_methods: \n" - ".long 24 \n" - ".long 1 \n" - PTR "L_load \n" - PTR "L_load \n" - PTR str2(SHARED_REGION_BASE+SHARED_REGION_SIZE-PAGE_MAX_SIZE) " \n" - - "L_good_methods: \n" - ".long 24 \n" - ".long 1 \n" - PTR "L_load \n" - PTR "L_load \n" - PTR "_nop \n" - - ".cstring \n" - "L_cat_name: .ascii \"Evil\\0\" \n" - "L_load: .ascii \"load\\0\" \n" - - ".section __DATA,__objc_catlist \n" -#if !OMIT_CAT - PTR "L_category \n" -#endif - - ".section __DATA,__objc_nlcatlist \n" -#if !OMIT_NL_CAT - PTR "L_category \n" -#endif - - ".text \n" - ); - -// __OBJC2__ -#endif - -void fn(void) { } diff --git a/objc/objc-runtime/test/evil-class-0.m b/objc/objc-runtime/test/evil-class-0.m deleted file mode 100644 index 7d35ad8..0000000 --- a/objc/objc-runtime/test/evil-class-0.m +++ /dev/null @@ -1,22 +0,0 @@ -/* -rdar://8553305 - -TEST_BUILD - $C{COMPILE} $DIR/evil-class-0.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none -DNOT_EVIL libevil.dylib -o evil-class-0.out -END -*/ - -// NOT EVIL version - -#define EVIL_SUPER 0 -#define EVIL_SUPER_META 0 -#define EVIL_SUB 0 -#define EVIL_SUB_META 0 - -#define OMIT_SUPER 0 -#define OMIT_NL_SUPER 0 -#define OMIT_SUB 0 -#define OMIT_NL_SUB 0 - -#include "evil-class-def.m" diff --git a/objc/objc-runtime/test/evil-class-00.m b/objc/objc-runtime/test/evil-class-00.m deleted file mode 100644 index 335675e..0000000 --- a/objc/objc-runtime/test/evil-class-00.m +++ /dev/null @@ -1,28 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-class-00.m $DIR/evil-main.m -o evil-class-00.out -END - -TEST_RUN_OUTPUT -CRASHED: SIGSEGV -END -*/ - -// NOT EVIL version: apps are allowed through (then crash in +load) - -#define EVIL_SUPER 0 -#define EVIL_SUPER_META 1 -#define EVIL_SUB 0 -#define EVIL_SUB_META 0 - -#define OMIT_SUPER 1 -#define OMIT_NL_SUPER 1 -#define OMIT_SUB 1 -#define OMIT_NL_SUB 0 - -#include "evil-class-def.m" diff --git a/objc/objc-runtime/test/evil-class-000.m b/objc/objc-runtime/test/evil-class-000.m deleted file mode 100644 index 003d4d4..0000000 --- a/objc/objc-runtime/test/evil-class-000.m +++ /dev/null @@ -1,22 +0,0 @@ -/* -rdar://8553305 - -TEST_BUILD - $C{COMPILE} $DIR/evil-class-000.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none -DNOT_EVIL libevil.dylib -o evil-class-000.out -END -*/ - -// NOT EVIL version: all classes omitted from all lists - -#define EVIL_SUPER 1 -#define EVIL_SUPER_META 1 -#define EVIL_SUB 1 -#define EVIL_SUB_META 1 - -#define OMIT_SUPER 1 -#define OMIT_NL_SUPER 1 -#define OMIT_SUB 1 -#define OMIT_NL_SUB 1 - -#include "evil-class-def.m" diff --git a/objc/objc-runtime/test/evil-class-1.m b/objc/objc-runtime/test/evil-class-1.m deleted file mode 100644 index 9266a79..0000000 --- a/objc/objc-runtime/test/evil-class-1.m +++ /dev/null @@ -1,28 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-class-1.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none libevil.dylib -o evil-class-1.out -END - -TEST_RUN_OUTPUT -objc\[\d+\]: bad method implementation \(0x[0-9a-f]+ at 0x[0-9a-f]+\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#define EVIL_SUPER 1 -#define EVIL_SUPER_META 0 -#define EVIL_SUB 0 -#define EVIL_SUB_META 0 - -#define OMIT_SUPER 0 -#define OMIT_NL_SUPER 0 -#define OMIT_SUB 0 -#define OMIT_NL_SUB 0 - -#include "evil-class-def.m" diff --git a/objc/objc-runtime/test/evil-class-2.m b/objc/objc-runtime/test/evil-class-2.m deleted file mode 100644 index 47aa3e2..0000000 --- a/objc/objc-runtime/test/evil-class-2.m +++ /dev/null @@ -1,28 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-class-2.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none libevil.dylib -o evil-class-2.out -END - -TEST_RUN_OUTPUT -objc\[\d+\]: bad method implementation \(0x[0-9a-f]+ at 0x[0-9a-f]+\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#define EVIL_SUPER 0 -#define EVIL_SUPER_META 1 -#define EVIL_SUB 0 -#define EVIL_SUB_META 0 - -#define OMIT_SUPER 0 -#define OMIT_NL_SUPER 0 -#define OMIT_SUB 0 -#define OMIT_NL_SUB 0 - -#include "evil-class-def.m" diff --git a/objc/objc-runtime/test/evil-class-3.m b/objc/objc-runtime/test/evil-class-3.m deleted file mode 100644 index 1d2e213..0000000 --- a/objc/objc-runtime/test/evil-class-3.m +++ /dev/null @@ -1,28 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-class-3.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none libevil.dylib -o evil-class-3.out -END - -TEST_RUN_OUTPUT -objc\[\d+\]: bad method implementation \(0x[0-9a-f]+ at 0x[0-9a-f]+\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#define EVIL_SUPER 0 -#define EVIL_SUPER_META 0 -#define EVIL_SUB 1 -#define EVIL_SUB_META 0 - -#define OMIT_SUPER 0 -#define OMIT_NL_SUPER 0 -#define OMIT_SUB 0 -#define OMIT_NL_SUB 0 - -#include "evil-class-def.m" diff --git a/objc/objc-runtime/test/evil-class-4.m b/objc/objc-runtime/test/evil-class-4.m deleted file mode 100644 index 8aef1f5..0000000 --- a/objc/objc-runtime/test/evil-class-4.m +++ /dev/null @@ -1,28 +0,0 @@ -/* -rdar://8553305 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-class-4.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none libevil.dylib -o evil-class-4.out -END - -TEST_RUN_OUTPUT -objc\[\d+\]: bad method implementation \(0x[0-9a-f]+ at 0x[0-9a-f]+\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#define EVIL_SUPER 0 -#define EVIL_SUPER_META 0 -#define EVIL_SUB 0 -#define EVIL_SUB_META 1 - -#define OMIT_SUPER 0 -#define OMIT_NL_SUPER 0 -#define OMIT_SUB 0 -#define OMIT_NL_SUB 0 - -#include "evil-class-def.m" diff --git a/objc/objc-runtime/test/evil-class-5.m b/objc/objc-runtime/test/evil-class-5.m deleted file mode 100644 index d8146f6..0000000 --- a/objc/objc-runtime/test/evil-class-5.m +++ /dev/null @@ -1,30 +0,0 @@ -/* -rdar://8553305 - -TEST_DISABLED rdar://19200100 - -TEST_CONFIG OS=iphoneos -TEST_CRASHES - -TEST_BUILD - $C{COMPILE} $DIR/evil-class-5.m -dynamiclib -o libevil.dylib - $C{COMPILE} $DIR/evil-main.m -x none libevil.dylib -o evil-class-5.out -END - -TEST_RUN_OUTPUT -objc\[\d+\]: bad method implementation \(0x[0-9a-f]+ at 0x[0-9a-f]+\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#define EVIL_SUPER 0 -#define EVIL_SUPER_META 1 -#define EVIL_SUB 0 -#define EVIL_SUB_META 0 - -#define OMIT_SUPER 1 -#define OMIT_NL_SUPER 1 -#define OMIT_SUB 1 -#define OMIT_NL_SUB 0 - -#include "evil-class-def.m" diff --git a/objc/objc-runtime/test/evil-class-def.m b/objc/objc-runtime/test/evil-class-def.m deleted file mode 100644 index 25ec45a..0000000 --- a/objc/objc-runtime/test/evil-class-def.m +++ /dev/null @@ -1,319 +0,0 @@ -#if __OBJC2__ - -#include <mach/shared_region.h> - -#if __LP64__ -# define PTR " .quad " -# define PTRSIZE "8" -# define LOGPTRSIZE "3" -#else -# define PTR " .long " -# define PTRSIZE "4" -# define LOGPTRSIZE "2" -#endif - -#define str(x) #x -#define str2(x) str(x) - -__BEGIN_DECLS -// not id to avoid ARC operations because the class doesn't implement RR methods -void* nop(void* self) { return self; } -__END_DECLS - -asm( - ".globl _OBJC_CLASS_$_Super \n" - ".section __DATA,__objc_data \n" - ".align 3 \n" - "_OBJC_CLASS_$_Super: \n" - PTR "_OBJC_METACLASS_$_Super \n" - PTR "0 \n" - PTR "__objc_empty_cache \n" - PTR "0 \n" - PTR "L_ro \n" - // pad to OBJC_MAX_CLASS_SIZE - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - "" - "_OBJC_METACLASS_$_Super: \n" - PTR "_OBJC_METACLASS_$_Super \n" - PTR "_OBJC_CLASS_$_Super \n" - PTR "__objc_empty_cache \n" - PTR "0 \n" - PTR "L_meta_ro \n" - // pad to OBJC_MAX_CLASS_SIZE - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - "" - "L_ro: \n" - ".long 2 \n" - ".long 0 \n" - ".long "PTRSIZE" \n" -#if __LP64__ - ".long 0 \n" -#endif - PTR "0 \n" - PTR "L_super_name \n" -#if EVIL_SUPER - PTR "L_evil_methods \n" -#else - PTR "L_good_methods \n" -#endif - PTR "0 \n" - PTR "L_super_ivars \n" - PTR "0 \n" - PTR "0 \n" - "" - "L_meta_ro: \n" - ".long 3 \n" - ".long 40 \n" - ".long 40 \n" -#if __LP64__ - ".long 0 \n" -#endif - PTR "0 \n" - PTR "L_super_name \n" -#if EVIL_SUPER_META - PTR "L_evil_methods \n" -#else - PTR "L_good_methods \n" -#endif - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - - ".globl _OBJC_CLASS_$_Sub \n" - ".section __DATA,__objc_data \n" - ".align 3 \n" - "_OBJC_CLASS_$_Sub: \n" - PTR "_OBJC_METACLASS_$_Sub \n" - PTR "_OBJC_CLASS_$_Super \n" - PTR "__objc_empty_cache \n" - PTR "0 \n" - PTR "L_sub_ro \n" - // pad to OBJC_MAX_CLASS_SIZE - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - "" - "_OBJC_METACLASS_$_Sub: \n" - PTR "_OBJC_METACLASS_$_Super \n" - PTR "_OBJC_METACLASS_$_Super \n" - PTR "__objc_empty_cache \n" - PTR "0 \n" - PTR "L_sub_meta_ro \n" - // pad to OBJC_MAX_CLASS_SIZE - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - "" - "L_sub_ro: \n" - ".long 2 \n" - ".long 0 \n" - ".long "PTRSIZE" \n" -#if __LP64__ - ".long 0 \n" -#endif - PTR "0 \n" - PTR "L_sub_name \n" -#if EVIL_SUB - PTR "L_evil_methods \n" -#else - PTR "L_good_methods \n" -#endif - PTR "0 \n" - PTR "L_sub_ivars \n" - PTR "0 \n" - PTR "0 \n" - "" - "L_sub_meta_ro: \n" - ".long 3 \n" - ".long 40 \n" - ".long 40 \n" -#if __LP64__ - ".long 0 \n" -#endif - PTR "0 \n" - PTR "L_sub_name \n" -#if EVIL_SUB_META - PTR "L_evil_methods \n" -#else - PTR "L_good_methods \n" -#endif - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - PTR "0 \n" - - "L_evil_methods: \n" - ".long 3*"PTRSIZE" \n" - ".long 1 \n" - PTR "L_load \n" - PTR "L_load \n" - PTR str2(SHARED_REGION_BASE+SHARED_REGION_SIZE-PAGE_MAX_SIZE) " \n" - - "L_good_methods: \n" - ".long 3*"PTRSIZE" \n" - ".long 2 \n" - PTR "L_load \n" - PTR "L_load \n" - PTR "_nop \n" - PTR "L_self \n" - PTR "L_self \n" - PTR "_nop \n" - - "L_super_ivars: \n" - ".long 4*"PTRSIZE" \n" - ".long 1 \n" - PTR "L_super_ivar_offset \n" - PTR "L_super_ivar_name \n" - PTR "L_super_ivar_type \n" - ".long "LOGPTRSIZE" \n" - ".long "PTRSIZE" \n" - - "L_sub_ivars: \n" - ".long 4*"PTRSIZE" \n" - ".long 1 \n" - PTR "L_sub_ivar_offset \n" - PTR "L_sub_ivar_name \n" - PTR "L_sub_ivar_type \n" - ".long "LOGPTRSIZE" \n" - ".long "PTRSIZE" \n" - - "L_super_ivar_offset: \n" - ".long 0 \n" - "L_sub_ivar_offset: \n" - ".long "PTRSIZE" \n" - - ".cstring \n" - "L_super_name: .ascii \"Super\\0\" \n" - "L_sub_name: .ascii \"Sub\\0\" \n" - "L_load: .ascii \"load\\0\" \n" - "L_self: .ascii \"self\\0\" \n" - "L_super_ivar_name: .ascii \"super_ivar\\0\" \n" - "L_super_ivar_type: .ascii \"c\\0\" \n" - "L_sub_ivar_name: .ascii \"sub_ivar\\0\" \n" - "L_sub_ivar_type: .ascii \"@\\0\" \n" - - - ".section __DATA,__objc_classlist \n" -#if !OMIT_SUPER - PTR "_OBJC_CLASS_$_Super \n" -#endif -#if !OMIT_SUB - PTR "_OBJC_CLASS_$_Sub \n" -#endif - - ".section __DATA,__objc_nlclslist \n" -#if !OMIT_NL_SUPER - PTR "_OBJC_CLASS_$_Super \n" -#endif -#if !OMIT_NL_SUB - PTR "_OBJC_CLASS_$_Sub \n" -#endif - - ".text \n" -); - -// __OBJC2__ -#endif - -void fn(void) { } diff --git a/objc/objc-runtime/test/evil-main.m b/objc/objc-runtime/test/evil-main.m deleted file mode 100644 index aa6a124..0000000 --- a/objc/objc-runtime/test/evil-main.m +++ /dev/null @@ -1,15 +0,0 @@ -#include "test.h" - -extern void fn(void); - -int main(int argc __unused, char **argv) -{ - fn(); - -#if TARGET_OS_EMBEDDED && !defined(NOT_EVIL) -#pragma unused (argv) - fail("All that is necessary for the triumph of evil is that good men do nothing."); -#else - succeed(basename(argv[0])); -#endif -} diff --git a/objc/objc-runtime/test/exc.m b/objc/objc-runtime/test/exc.m deleted file mode 100644 index 4f25b75..0000000 --- a/objc/objc-runtime/test/exc.m +++ /dev/null @@ -1,888 +0,0 @@ -/* -need exception-safe ARC for exception deallocation tests -need F/CF for testonthread() in GC mode -TEST_CFLAGS -fobjc-arc-exceptions -framework Foundation - -llvm-gcc unavoidably warns about our deliberately out-of-order handlers - -TEST_BUILD_OUTPUT -.*exc.m: In function .* -.*exc.m:\d+: warning: exception of type .* will be caught -.*exc.m:\d+: warning: by earlier handler for .* -.*exc.m:\d+: warning: exception of type .* will be caught -.*exc.m:\d+: warning: by earlier handler for .* -.*exc.m:\d+: warning: exception of type .* will be caught -.*exc.m:\d+: warning: by earlier handler for .* -OR -END -*/ - -#include "test.h" -#include "testroot.i" -#include <objc/runtime.h> -#include <objc/objc-exception.h> - -static volatile int state = 0; -static volatile int dealloced = 0; -#define BAD 1000000 - -#if defined(USE_FOUNDATION) - -#include <Foundation/Foundation.h> - -@interface Super : NSException @end -@implementation Super -+(id)exception { return AUTORELEASE([[self alloc] initWithName:@"Super" reason:@"reason" userInfo:nil]); } --(void)check { state++; } -+(void)check { testassert(!"caught class object, not instance"); } --(void)dealloc { dealloced++; SUPER_DEALLOC(); } --(void)finalize { dealloced++; [super finalize]; } -@end - -#define FILENAME "nsexc.m" - -#else - -@interface Super : TestRoot @end -@implementation Super -+(id)exception { return AUTORELEASE([self new]); } --(void)check { state++; } -+(void)check { testassert(!"caught class object, not instance"); } --(void)dealloc { dealloced++; SUPER_DEALLOC(); } --(void)finalize { dealloced++; [super finalize]; } -@end - -#define FILENAME "exc.m" - -#endif - -@interface Sub : Super @end -@implementation Sub -@end - - -#if __OBJC2__ && !TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE -void altHandlerFail(id unused __unused, void *context __unused) -{ - fail("altHandlerFail called"); -} - -#define ALT_HANDLER(n) \ - void altHandler##n(id unused __unused, void *context) \ - { \ - testassert(context == (void*)&altHandler##n); \ - testassert(state == n); \ - state++; \ - } - -ALT_HANDLER(1) -ALT_HANDLER(2) -ALT_HANDLER(3) -ALT_HANDLER(4) -ALT_HANDLER(5) -ALT_HANDLER(6) -ALT_HANDLER(7) - - -static void throwWithAltHandler(void) __attribute__((noinline)); -static void throwWithAltHandler(void) -{ - @try { - state++; - uintptr_t token = objc_addExceptionHandler(altHandler3, (void*)altHandler3); - // state++ inside alt handler - @throw [Super exception]; - state = BAD; - objc_removeExceptionHandler(token); - } - @catch (Sub *e) { - state = BAD; - } - state = BAD; -} - - -static void throwWithAltHandlerAndRethrow(void) __attribute__((noinline)); -static void throwWithAltHandlerAndRethrow(void) -{ - @try { - state++; - uintptr_t token = objc_addExceptionHandler(altHandler3, (void*)altHandler3); - // state++ inside alt handler - @throw [Super exception]; - state = BAD; - objc_removeExceptionHandler(token); - } - @catch (...) { - testassert(state == 4); - state++; - @throw; - } - state = BAD; -} - -#endif - -#if __cplusplus && __OBJC2__ -#include <exception> -void terminator() { - succeed(FILENAME); -} -#endif - - -#define TEST(code) \ - do { \ - testonthread(^{ PUSH_POOL { code } POP_POOL; }); \ - testcollect(); \ - } while (0) - - - -int main() -{ - testprintf("try-catch-finally, exception caught exactly\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (Super *e) { - state++; - [e check]; // state++ - } - @finally { - state++; - } - state++; - } - @catch (...) { - state = BAD; - } - }); - testassert(state == 6); - testassert(dealloced == 1); - - - testprintf("try-finally, no exception thrown\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - } - @finally { - state++; - } - state++; - } - @catch (...) { - state = BAD; - } - }); - testassert(state == 4); - testassert(dealloced == 0); - - - testprintf("try-finally, with exception\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @finally { - state++; - } - state = BAD; - } - @catch (id e) { - state++; - [e check]; // state++ - } - }); - testassert(state == 5); - testassert(dealloced == 1); - - -#if __OBJC2__ - testprintf("try-finally, with autorelease pool pop during unwind\n"); - // Popping an autorelease pool during unwind used to deallocate the - // exception object, but now we retain them while in flight. - - // This use-after-free is undetected without MallocScribble or guardmalloc. - if (!getenv("MallocScribble") && - (!getenv("DYLD_INSERT_LIBRARIES") || - !strstr(getenv("DYLD_INSERT_LIBRARIES"), "libgmalloc"))) - { - testwarn("MallocScribble not set"); - } - - TEST({ - state = 0; - dealloced = 0; - @try { - void *pool2 = objc_autoreleasePoolPush(); - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @finally { - state++; - objc_autoreleasePoolPop(pool2); - } - state = BAD; - } - @catch (id e) { - state++; - [e check]; // state++ - } - }); - testassert(state == 5); - testassert(dealloced == 1); -#endif - - - testprintf("try-catch-finally, no exception\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - } - @catch (...) { - state = BAD; - } - @finally { - state++; - } - state++; - } @catch (...) { - state = BAD; - } - }); - testassert(state == 4); - testassert(dealloced == 0); - - - testprintf("try-catch-finally, exception not caught\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (Sub *e) { - state = BAD; - } - @finally { - state++; - } - state = BAD; - } - @catch (id e) { - state++; - [e check]; // state++ - } - }); - testassert(state == 5); - testassert(dealloced == 1); - - - testprintf("try-catch-finally, exception caught exactly, rethrown\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (Super *e) { - state++; - [e check]; // state++ - @throw; - state = BAD; - } - @finally { - state++; - } - state = BAD; - } - @catch (id e) { - state++; - [e check]; // state++ - } - }); - testassert(state == 7); - testassert(dealloced == 1); - - - testprintf("try-catch, no exception\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - } - @catch (...) { - state = BAD; - } - state++; - } @catch (...) { - state = BAD; - } - }); - testassert(state == 3); - testassert(dealloced == 0); - - - testprintf("try-catch, exception not caught\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (Sub *e) { - state = BAD; - } - state = BAD; - } - @catch (id e) { - state++; - [e check]; // state++ - } - }); - testassert(state == 4); - testassert(dealloced == 1); - - - testprintf("try-catch, exception caught exactly\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (Super *e) { - state++; - [e check]; // state++ - } - state++; - } - @catch (...) { - state = BAD; - } - }); - testassert(state == 5); - testassert(dealloced == 1); - - - testprintf("try-catch, exception caught exactly, rethrown\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (Super *e) { - state++; - [e check]; // state++ - @throw; - state = BAD; - } - state = BAD; - } - @catch (id e) { - state++; - [e check]; // state++ - } - }); - testassert(state == 6); - testassert(dealloced == 1); - - - testprintf("try-catch, exception caught exactly, thrown again explicitly\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (Super *e) { - state++; - [e check]; // state++ - @throw e; - state = BAD; - } - state = BAD; - } - @catch (id e) { - state++; - [e check]; // state++ - } - }); - testassert(state == 6); - testassert(dealloced == 1); - - - testprintf("try-catch, default catch, rethrown\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (...) { - state++; - @throw; - state = BAD; - } - state = BAD; - } - @catch (id e) { - state++; - [e check]; // state++ - } - }); - testassert(state == 5); - testassert(dealloced == 1); - - - testprintf("try-catch, default catch, rethrown and caught inside nested handler\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (...) { - state++; - - @try { - state++; - @throw; - state = BAD; - } @catch (Sub *e) { - state = BAD; - } @catch (Super *e) { - state++; - [e check]; // state++ - } @catch (...) { - state = BAD; - } @finally { - state++; - } - - state++; - } - state++; - } - @catch (...) { - state = BAD; - } - }); - testassert(state == 9); - testassert(dealloced == 1); - - - testprintf("try-catch, default catch, rethrown inside nested handler but not caught\n"); - - TEST({ - state = 0; - dealloced = 0; - @try { - state++; - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (...) { - state++; - - @try { - state++; - @throw; - state = BAD; - } - @catch (Sub *e) { - state = BAD; - } - @finally { - state++; - } - - state = BAD; - } - state = BAD; - } - @catch (id e) { - state++; - [e check]; // state++ - } - }); - testassert(state == 7); - testassert(dealloced == 1); - - -#if __cplusplus && __OBJC2__ - testprintf("C++ try/catch, Objective-C exception superclass\n"); - - TEST({ - state = 0; - dealloced = 0; - try { - state++; - try { - state++; - try { - state++; - @throw [Super exception]; - state = BAD; - } catch (...) { - state++; - throw; - state = BAD; - } - state = BAD; - } catch (void *e) { - state = BAD; - } catch (int e) { - state = BAD; - } catch (Sub *e) { - state = BAD; - } catch (Super *e) { - state++; - [e check]; // state++ - throw; - } catch (...) { - state = BAD; - } - } catch (id e) { - state++; - [e check]; // state++; - } - }); - testassert(state == 8); - testassert(dealloced == 1); - - - testprintf("C++ try/catch, Objective-C exception subclass\n"); - - TEST({ - state = 0; - dealloced = 0; - try { - state++; - try { - state++; - try { - state++; - @throw [Sub exception]; - state = BAD; - } catch (...) { - state++; - throw; - state = BAD; - } - state = BAD; - } catch (void *e) { - state = BAD; - } catch (int e) { - state = BAD; - } catch (Super *e) { - state++; - [e check]; // state++ - throw; - } catch (Sub *e) { - state = BAD; - } catch (...) { - state = BAD; - } - } catch (id e) { - state++; - [e check]; // state++; - } - }); - testassert(state == 8); - testassert(dealloced == 1); - -#endif - - -#if !__OBJC2__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE - // alt handlers for modern Mac OS only - -#else - { - // alt handlers - // run a lot to catch failed unregistration (runtime complains at 1000) -#define ALT_HANDLER_REPEAT 2000 - - testprintf("alt handler, no exception\n"); - - TEST({ - dealloced = 0; - for (int i = 0; i < ALT_HANDLER_REPEAT; i++) { - state = 0; - @try { - state++; - @try { - uintptr_t token = objc_addExceptionHandler(altHandlerFail, 0); - state++; - objc_removeExceptionHandler(token); - } - @catch (...) { - state = BAD; - } - state++; - } @catch (...) { - state = BAD; - } - testassert(state == 3); - } - }); - testassert(dealloced == 0); - - - testprintf("alt handler, exception thrown through\n"); - - TEST({ - dealloced = 0; - for (int i = 0; i < ALT_HANDLER_REPEAT; i++) { - state = 0; - @try { - state++; - @try { - state++; - uintptr_t token = objc_addExceptionHandler(altHandler2, (void*)altHandler2); - // state++ inside alt handler - @throw [Super exception]; - state = BAD; - objc_removeExceptionHandler(token); - } - @catch (Sub *e) { - state = BAD; - } - state = BAD; - } - @catch (id e) { - testassert(state == 3); - state++; - [e check]; // state++ - } - testassert(state == 5); - } - }); - testassert(dealloced == ALT_HANDLER_REPEAT); - - - testprintf("alt handler, nested\n"); - - TEST({ - dealloced = 0; - for (int i = 0; i < ALT_HANDLER_REPEAT; i++) { - state = 0; - @try { - state++; - @try { - state++; - // same-level handlers called in FIFO order (not stack-like) - uintptr_t token = objc_addExceptionHandler(altHandler4, (void*)altHandler4); - // state++ inside alt handler - uintptr_t token2 = objc_addExceptionHandler(altHandler5, (void*)altHandler5); - // state++ inside alt handler - throwWithAltHandler(); // state += 2 inside - state = BAD; - objc_removeExceptionHandler(token); - objc_removeExceptionHandler(token2); - } - @catch (id e) { - testassert(state == 6); - state++; - [e check]; // state++; - } - state++; - } - @catch (...) { - state = BAD; - } - testassert(state == 9); - } - }); - testassert(dealloced == ALT_HANDLER_REPEAT); - - - testprintf("alt handler, nested, rethrows in between\n"); - - TEST({ - dealloced = 0; - for (int i = 0; i < ALT_HANDLER_REPEAT; i++) { - state = 0; - @try { - state++; - @try { - state++; - // same-level handlers called in FIFO order (not stack-like) - uintptr_t token = objc_addExceptionHandler(altHandler5, (void*)altHandler5); - // state++ inside alt handler - uintptr_t token2 = objc_addExceptionHandler(altHandler6, (void*)altHandler6); - // state++ inside alt handler - throwWithAltHandlerAndRethrow(); // state += 3 inside - state = BAD; - objc_removeExceptionHandler(token); - objc_removeExceptionHandler(token2); - } - @catch (...) { - testassert(state == 7); - state++; - @throw; - } - state = BAD; - } - @catch (id e) { - testassert(state == 8); - state++; - [e check]; // state++ - } - testassert(state == 10); - } - }); - testassert(dealloced == ALT_HANDLER_REPEAT); - - - testprintf("alt handler, exception thrown and caught inside\n"); - - TEST({ - dealloced = 0; - for (int i = 0; i < ALT_HANDLER_REPEAT; i++) { - state = 0; - @try { - state++; - uintptr_t token = objc_addExceptionHandler(altHandlerFail, 0); - @try { - state++; - @throw [Super exception]; - state = BAD; - } - @catch (Super *e) { - state++; - [e check]; // state++ - } - state++; - objc_removeExceptionHandler(token); - } - @catch (...) { - state = BAD; - } - testassert(state == 5); - } - }); - testassert(dealloced == ALT_HANDLER_REPEAT); - - -#if defined(USE_FOUNDATION) - testprintf("alt handler, rdar://10055775\n"); - - TEST({ - dealloced = 0; - for (int i = 0; i < ALT_HANDLER_REPEAT; i++) { - state = 0; - @try { - uintptr_t token = objc_addExceptionHandler(altHandler1, (void*)altHandler1); - { - id x = [NSArray array]; - x = [NSArray array]; - } - state++; - // state++ inside alt handler - [Super raise:@"foo" format:@"bar"]; - state = BAD; - objc_removeExceptionHandler(token); - } @catch (id e) { - state++; - testassert(state == 3); - } - testassert(state == 3); - } - }); - testassert(dealloced == ALT_HANDLER_REPEAT); - -// defined(USE_FOUNDATION) -#endif - - } -// alt handlers -#endif - -#if __cplusplus && __OBJC2__ - std::set_terminate(terminator); - objc_terminate(); - fail("should not have returned from objc_terminate()"); -#else - succeed(FILENAME); -#endif -} - diff --git a/objc/objc-runtime/test/exchangeImp.m b/objc/objc-runtime/test/exchangeImp.m deleted file mode 100644 index 12f81e4..0000000 --- a/objc/objc-runtime/test/exchangeImp.m +++ /dev/null @@ -1,87 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <objc/runtime.h> - -static int state; - -#define ONE 1 -#define TWO 2 -#define LENGTH 3 -#define COUNT 4 - -@interface Super : TestRoot @end -@implementation Super -+(void) one { state = ONE; } -+(void) two { state = TWO; } -+(void) length { state = LENGTH; } -+(void) count { state = COUNT; } -@end - -#define checkExchange(s1, v1, s2, v2) \ - do { \ - Method m1, m2; \ - \ - testprintf("Check unexchanged version\n"); \ - state = 0; \ - [Super s1]; \ - testassert(state == v1); \ - state = 0; \ - [Super s2]; \ - testassert(state == v2); \ - \ - testprintf("Exchange\n"); \ - m1 = class_getClassMethod([Super class], @selector(s1)); \ - m2 = class_getClassMethod([Super class], @selector(s2)); \ - testassert(m1); \ - testassert(m2); \ - method_exchangeImplementations(m1, m2); \ - \ - testprintf("Check exchanged version\n"); \ - state = 0; \ - [Super s1]; \ - testassert(state == v2); \ - state = 0; \ - [Super s2]; \ - testassert(state == v1); \ - \ - testprintf("NULL should do nothing\n"); \ - method_exchangeImplementations(m1, NULL); \ - method_exchangeImplementations(NULL, m2); \ - method_exchangeImplementations(NULL, NULL); \ - \ - testprintf("Make sure NULL did nothing\n"); \ - state = 0; \ - [Super s1]; \ - testassert(state == v2); \ - state = 0; \ - [Super s2]; \ - testassert(state == v1); \ - \ - testprintf("Put them back\n"); \ - method_exchangeImplementations(m1, m2); \ - \ - testprintf("Check restored version\n"); \ - state = 0; \ - [Super s1]; \ - testassert(state == v1); \ - state = 0; \ - [Super s2]; \ - testassert(state == v2); \ - } while (0) - -int main() -{ - // Check ordinary selectors - checkExchange(one, ONE, two, TWO); - - // Check vtable selectors - checkExchange(length, LENGTH, count, COUNT); - - // Check ordinary<->vtable and vtable<->ordinary - checkExchange(count, COUNT, one, ONE); - checkExchange(two, TWO, length, LENGTH); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/foreach.m b/objc/objc-runtime/test/foreach.m deleted file mode 100644 index 4386db3..0000000 --- a/objc/objc-runtime/test/foreach.m +++ /dev/null @@ -1,227 +0,0 @@ -// TEST_CFLAGS -framework Foundation - -#include "test.h" -#import <Foundation/Foundation.h> - -/* foreach tester */ - -int Errors = 0; - -bool testHandwritten(const char *style, const char *test, const char *message, id collection, NSSet *reference) { - unsigned int counter = 0; - bool result = true; - testprintf("testing: %s %s %s\n", style, test, message); -/* - for (id elem in collection) - if ([reference member:elem]) ++counter; - */ - NSFastEnumerationState state; - id __unsafe_unretained buffer[4]; - state.state = 0; - NSUInteger limit = [collection countByEnumeratingWithState:&state objects:buffer count:4]; - if (limit != 0) { - unsigned long mutationsPtr = *state.mutationsPtr; - do { - unsigned long innerCounter = 0; - do { - if (mutationsPtr != *state.mutationsPtr) objc_enumerationMutation(collection); - id elem = state.itemsPtr[innerCounter++]; - - if ([reference member:elem]) ++counter; - - } while (innerCounter < limit); - } while ((limit = [collection countByEnumeratingWithState:&state objects:buffer count:4])); - } - - - - if (counter == [reference count]) { - testprintf("success: %s %s %s\n", style, test, message); - } - else { - result = false; - printf("** failed: %s %s %s (%d vs %d)\n", style, test, message, counter, (int)[reference count]); - ++Errors; - } - return result; -} - -bool testCompiler(const char *style, const char *test, const char *message, id collection, NSSet *reference) { - unsigned int counter = 0; - bool result = true; - testprintf("testing: %s %s %s\n", style, test, message); - for (id elem in collection) - if ([reference member:elem]) ++counter; - if (counter == [reference count]) { - testprintf("success: %s %s %s\n", style, test, message); - } - else { - result = false; - printf("** failed: %s %s %s (%d vs %d)\n", style, test, message, counter, (int)[reference count]); - ++Errors; - } - return result; -} - -void testContinue(NSArray *array) { - bool broken = false; - testprintf("testing: continue statements\n"); - for (id __unused elem in array) { - if ([array count]) - continue; - broken = true; - } - if (broken) { - printf("** continue statement did not work\n"); - ++Errors; - } -} - - -// array is filled with NSNumbers, in order, from 0 - N -bool testBreak(unsigned int where, NSArray *array) { - PUSH_POOL { - unsigned int counter = 0; - id enumerator = [array objectEnumerator]; - for (id __unused elem in enumerator) { - if (++counter == where) - break; - } - if (counter != where) { - ++Errors; - printf("*** break at %d didn't work (actual was %d)\n", where, counter); - return false; - } - for (id __unused elem in enumerator) - ++counter; - if (counter != [array count]) { - ++Errors; - printf("*** break at %d didn't finish (actual was %d)\n", where, counter); - return false; - } - } POP_POOL; - return true; -} - -bool testBreaks(NSArray *array) { - bool result = true; - testprintf("testing breaks\n"); - unsigned int counter = 0; - for (counter = 1; counter < [array count]; ++counter) { - result = testBreak(counter, array) && result; - } - return result; -} - -bool testCompleteness(const char *test, const char *message, id collection, NSSet *reference) { - bool result = true; - result = result && testHandwritten("handwritten", test, message, collection, reference); - result = result && testCompiler("compiler", test, message, collection, reference); - return result; -} - -bool testEnumerator(const char *test, const char *message, id collection, NSSet *reference) { - bool result = true; - result = result && testHandwritten("handwritten", test, message, [collection objectEnumerator], reference); - result = result && testCompiler("compiler", test, message, [collection objectEnumerator], reference); - return result; -} - -NSMutableSet *ReferenceSet = nil; -NSMutableArray *ReferenceArray = nil; - -void makeReferences(int n) { - if (!ReferenceSet) { - int i; - ReferenceSet = [[NSMutableSet alloc] init]; - ReferenceArray = [[NSMutableArray alloc] init]; - for (i = 0; i < n; ++i) { - NSNumber *number = [[NSNumber alloc] initWithInt:i]; - [ReferenceSet addObject:number]; - [ReferenceArray addObject:number]; - RELEASE_VAR(number); - } - } -} - -void testCollections(const char *test, NSArray *array, NSSet *set) { - PUSH_POOL { - id collection; - collection = [NSMutableArray arrayWithArray:array]; - testCompleteness(test, "mutable array", collection, set); - testEnumerator(test, "mutable array enumerator", collection, set); - collection = [NSArray arrayWithArray:array]; - testCompleteness(test, "immutable array", collection, set); - testEnumerator(test, "immutable array enumerator", collection, set); - collection = set; - testCompleteness(test, "immutable set", collection, set); - testEnumerator(test, "immutable set enumerator", collection, set); - collection = [NSMutableSet setWithArray:array]; - testCompleteness(test, "mutable set", collection, set); - testEnumerator(test, "mutable set enumerator", collection, set); - } POP_POOL; -} - -void testInnerDecl(const char *test, const char *message, id collection) { - unsigned int counter = 0; - for (id __unused x in collection) - ++counter; - if (counter != [collection count]) { - printf("** failed: %s %s\n", test, message); - ++Errors; - } -} - - -void testOuterDecl(const char *test, const char *message, id collection) { - unsigned int counter = 0; - id x; - for (x in collection) - ++counter; - if (counter != [collection count]) { - printf("** failed: %s %s\n", test, message); - ++Errors; - } -} -void testInnerExpression(const char *test, const char *message, id collection) { - unsigned int counter = 0; - for (id __unused x in [collection self]) - ++counter; - if (counter != [collection count]) { - printf("** failed: %s %s\n", test, message); - ++Errors; - } -} -void testOuterExpression(const char *test, const char *message, id collection) { - unsigned int counter = 0; - id x; - for (x in [collection self]) - ++counter; - if (counter != [collection count]) { - printf("** failed: %s %s\n", test, message); - ++Errors; - } -} - -void testExpressions(const char *message, id collection) { - testInnerDecl("inner", message, collection); - testOuterDecl("outer", message, collection); - testInnerExpression("outer expression", message, collection); - testOuterExpression("outer expression", message, collection); -} - - -int main() { - PUSH_POOL { - testCollections("nil", nil, nil); - testCollections("empty", [NSArray array], [NSSet set]); - makeReferences(100); - testCollections("100 item", ReferenceArray, ReferenceSet); - testExpressions("array", ReferenceArray); - testBreaks(ReferenceArray); - testContinue(ReferenceArray); - if (Errors == 0) succeed(__FILE__); - else fail("foreach %d errors detected\n", Errors); - } POP_POOL; - exit(Errors); -} diff --git a/objc/objc-runtime/test/forward.m b/objc/objc-runtime/test/forward.m deleted file mode 100644 index 5f3ba1a..0000000 --- a/objc/objc-runtime/test/forward.m +++ /dev/null @@ -1,1002 +0,0 @@ -// TEST_CONFIG MEM=mrc,gc -// TEST_CFLAGS -Wno-deprecated-declarations - -#include "test.h" - -#if __cplusplus && !__clang__ - -int main() -{ - // llvm-g++ is confused by @selector(foo::) and will never be fixed - succeed(__FILE__); -} - -#else - -#include <objc/runtime.h> -#include <objc/message.h> - -id ID_RESULT = (id)0x12345678; -long long LL_RESULT = __LONG_LONG_MAX__ - 2LL*__INT_MAX__; -double FP_RESULT = __DBL_MIN__ + __DBL_EPSILON__; -long double LFP_RESULT = __LDBL_MIN__ + __LDBL_EPSILON__; -// STRET_RESULT in test.h - - -static int state = 0; -static id receiver; - -OBJC_ROOT_CLASS -@interface Super { id isa; } @end - -@interface Super (Forwarded) -+(id)idret: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(id)idre2: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(id)idre3: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(long long)llret: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(long long)llre2: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(long long)llre3: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(struct stret)stret: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(struct stret)stre2: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(struct stret)stre3: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(double)fpret: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(double)fpre2: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -+(double)fpre3: - (long)i1 :(long)i2 :(long)i3 :(long)i4 :(long)i5 :(long)i6 :(long)i7 :(long)i8 :(long)i9 :(long)i10 :(long)i11 :(long)i12 :(long)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -@end - - -long long forward_handler(id self, SEL _cmd, long i1, long i2, long i3, long i4, long i5, long i6, long i7, long i8, long i9, long i10, long i11, long i12, long i13, double f1, double f2, double f3, double f4, double f5, double f6, double f7, double f8, double f9, double f10, double f11, double f12, double f13, double f14, double f15) -{ -#if __arm64__ - void *struct_addr; - __asm__ volatile("mov %0, x8" : "=r" (struct_addr) : : "x8"); -#endif - - testassert(self == receiver); - - testassert(i1 == 1); - testassert(i2 == 2); - testassert(i3 == 3); - testassert(i4 == 4); - testassert(i5 == 5); - testassert(i6 == 6); - testassert(i7 == 7); - testassert(i8 == 8); - testassert(i9 == 9); - testassert(i10 == 10); - testassert(i11 == 11); - testassert(i12 == 12); - testassert(i13 == 13); - - testassert(f1 == 1.0); - testassert(f2 == 2.0); - testassert(f3 == 3.0); - testassert(f4 == 4.0); - testassert(f5 == 5.0); - testassert(f6 == 6.0); - testassert(f7 == 7.0); - testassert(f8 == 8.0); - testassert(f9 == 9.0); - testassert(f10 == 10.0); - testassert(f11 == 11.0); - testassert(f12 == 12.0); - testassert(f13 == 13.0); - testassert(f14 == 14.0); - testassert(f15 == 15.0); - - if (_cmd == @selector(idret::::::::::::::::::::::::::::) || - _cmd == @selector(idre2::::::::::::::::::::::::::::) || - _cmd == @selector(idre3::::::::::::::::::::::::::::)) - { - union { - id idval; - long long llval; - } result; - testassert(state == 11); - state = 12; - result.idval = ID_RESULT; - return result.llval; - } - else if (_cmd == @selector(llret::::::::::::::::::::::::::::) || - _cmd == @selector(llre2::::::::::::::::::::::::::::) || - _cmd == @selector(llre3::::::::::::::::::::::::::::)) - { - testassert(state == 13); - state = 14; - return LL_RESULT; - } - else if (_cmd == @selector(fpret::::::::::::::::::::::::::::) || - _cmd == @selector(fpre2::::::::::::::::::::::::::::) || - _cmd == @selector(fpre3::::::::::::::::::::::::::::)) - { - testassert(state == 15); - state = 16; -#if defined(__i386__) - __asm__ volatile("fldl %0" : : "m" (FP_RESULT)); -#elif defined(__x86_64__) - __asm__ volatile("movsd %0, %%xmm0" : : "m" (FP_RESULT)); -#elif defined(__arm__) - union { - double fpval; - long long llval; - } result; - result.fpval = FP_RESULT; - return result.llval; -#elif defined(__arm64__) - __asm__ volatile("ldr d0, %0" : : "m" (FP_RESULT)); -#else -# error unknown architecture -#endif - return 0; - } - else if (_cmd == @selector(stret::::::::::::::::::::::::::::) || - _cmd == @selector(stre2::::::::::::::::::::::::::::) || - _cmd == @selector(stre3::::::::::::::::::::::::::::)) - { -#if __i386__ || __x86_64__ || __arm__ - fail("stret message sent to non-stret forward_handler"); -#elif __arm64__ - testassert(state == 17); - state = 18; - memcpy(struct_addr, &STRET_RESULT, sizeof(STRET_RESULT)); - return 0; -#else -# error unknown architecture -#endif - } - else { - fail("unknown selector %s in forward_handler", sel_getName(_cmd)); - } -} - - -struct stret forward_stret_handler(id self, SEL _cmd, long i1, long i2, long i3, long i4, long i5, long i6, long i7, long i8, long i9, long i10, long i11, long i12, long i13, double f1, double f2, double f3, double f4, double f5, double f6, double f7, double f8, double f9, double f10, double f11, double f12, double f13, double f14, double f15) -{ - testassert(self == receiver); - - testassert(i1 == 1); - testassert(i2 == 2); - testassert(i3 == 3); - testassert(i4 == 4); - testassert(i5 == 5); - testassert(i6 == 6); - testassert(i7 == 7); - testassert(i8 == 8); - testassert(i9 == 9); - testassert(i10 == 10); - testassert(i11 == 11); - testassert(i12 == 12); - testassert(i13 == 13); - - testassert(f1 == 1.0); - testassert(f2 == 2.0); - testassert(f3 == 3.0); - testassert(f4 == 4.0); - testassert(f5 == 5.0); - testassert(f6 == 6.0); - testassert(f7 == 7.0); - testassert(f8 == 8.0); - testassert(f9 == 9.0); - testassert(f10 == 10.0); - testassert(f11 == 11.0); - testassert(f12 == 12.0); - testassert(f13 == 13.0); - testassert(f14 == 14.0); - testassert(f15 == 15.0); - - if (_cmd == @selector(idret::::::::::::::::::::::::::::) || - _cmd == @selector(idre2::::::::::::::::::::::::::::) || - _cmd == @selector(idre3::::::::::::::::::::::::::::) || - _cmd == @selector(llret::::::::::::::::::::::::::::) || - _cmd == @selector(llre2::::::::::::::::::::::::::::) || - _cmd == @selector(llre3::::::::::::::::::::::::::::) || - _cmd == @selector(fpret::::::::::::::::::::::::::::) || - _cmd == @selector(fpre2::::::::::::::::::::::::::::) || - _cmd == @selector(fpre3::::::::::::::::::::::::::::)) - { - fail("non-stret selector %s sent to forward_stret_handler", sel_getName(_cmd)); - } - else if (_cmd == @selector(stret::::::::::::::::::::::::::::) || - _cmd == @selector(stre2::::::::::::::::::::::::::::) || - _cmd == @selector(stre3::::::::::::::::::::::::::::)) - { - testassert(state == 17); - state = 18; - return STRET_RESULT; - } - else { - fail("unknown selector %s in forward_stret_handler", sel_getName(_cmd)); - } - -} - - -@implementation Super -+(void)initialize { } -+(id)class { return self; } - -#if __OBJC2__ -// forward:: not supported -#else --(long long) forward:(SEL)sel :(marg_list)args -{ - char *p; - uintptr_t *gp; - double *fp; - struct stret *struct_addr; - -#if defined(__i386__) - struct_addr = ((struct stret **)args)[-1]; -#elif defined(__x86_64__) - struct_addr = *(struct stret **)((char *)args + 8*16+4*8); -#elif defined(__arm__) - struct_addr = *(struct stret **)((char *)args + 0); -#else -# error unknown architecture -#endif - - testassert(self == receiver); - testassert(_cmd == sel_registerName("forward::")); - - p = (char *)args; -#if defined(__x86_64__) - p += 8*16 + 4*8; // skip over xmm and linkage - if (sel == @selector(stret::::::::::::::::::::::::::::) || - sel == @selector(stre2::::::::::::::::::::::::::::) || - sel == @selector(stre3::::::::::::::::::::::::::::)) - { - p += sizeof(void *); // struct return - } -#elif defined(__i386__) - // nothing to do -#elif defined(__arm__) - if (sel == @selector(stret::::::::::::::::::::::::::::) || - sel == @selector(stre2::::::::::::::::::::::::::::) || - sel == @selector(stre3::::::::::::::::::::::::::::)) - { - p += sizeof(void *); // struct return; - } -#else -# error unknown architecture -#endif - gp = (uintptr_t *)p; - testassert(*gp++ == (uintptr_t)self); - testassert(*gp++ == (uintptr_t)(void *)sel); - testassert(*gp++ == 1); - testassert(*gp++ == 2); - testassert(*gp++ == 3); - testassert(*gp++ == 4); - testassert(*gp++ == 5); - testassert(*gp++ == 6); - testassert(*gp++ == 7); - testassert(*gp++ == 8); - testassert(*gp++ == 9); - testassert(*gp++ == 10); - testassert(*gp++ == 11); - testassert(*gp++ == 12); - testassert(*gp++ == 13); - -#if defined(__i386__) || defined(__arm__) - - fp = (double *)gp; - testassert(*fp++ == 1.0); - testassert(*fp++ == 2.0); - testassert(*fp++ == 3.0); - testassert(*fp++ == 4.0); - testassert(*fp++ == 5.0); - testassert(*fp++ == 6.0); - testassert(*fp++ == 7.0); - testassert(*fp++ == 8.0); - testassert(*fp++ == 9.0); - testassert(*fp++ == 10.0); - testassert(*fp++ == 11.0); - testassert(*fp++ == 12.0); - testassert(*fp++ == 13.0); - testassert(*fp++ == 14.0); - testassert(*fp++ == 15.0); - -#elif defined(__x86_64__) - - fp = (double *)args; // xmm, double-wide - testassert(*fp++ == 1.0); fp++; - testassert(*fp++ == 2.0); fp++; - testassert(*fp++ == 3.0); fp++; - testassert(*fp++ == 4.0); fp++; - testassert(*fp++ == 5.0); fp++; - testassert(*fp++ == 6.0); fp++; - testassert(*fp++ == 7.0); fp++; - testassert(*fp++ == 8.0); fp++; - fp = (double *)gp; - testassert(*fp++ == 9.0); - testassert(*fp++ == 10.0); - testassert(*fp++ == 11.0); - testassert(*fp++ == 12.0); - testassert(*fp++ == 13.0); - testassert(*fp++ == 14.0); - testassert(*fp++ == 15.0); - -#else -# error unknown architecture -#endif - - if (sel == @selector(idret::::::::::::::::::::::::::::) || - sel == @selector(idre2::::::::::::::::::::::::::::) || - sel == @selector(idre3::::::::::::::::::::::::::::)) - { - union { - id idval; - long long llval; - } result; - testassert(state == 1); - state = 2; - result.idval = ID_RESULT; - return result.llval; - } else if (sel == @selector(llret::::::::::::::::::::::::::::) || - sel == @selector(llre2::::::::::::::::::::::::::::) || - sel == @selector(llre3::::::::::::::::::::::::::::)) - { - testassert(state == 3); - state = 4; - return LL_RESULT; - } else if (sel == @selector(fpret::::::::::::::::::::::::::::) || - sel == @selector(fpre2::::::::::::::::::::::::::::) || - sel == @selector(fpre3::::::::::::::::::::::::::::)) - { - testassert(state == 5); - state = 6; -#if defined(__i386__) - __asm__ volatile("fldl %0" : : "m" (FP_RESULT)); -#elif defined(__x86_64__) - __asm__ volatile("movsd %0, %%xmm0" : : "m" (FP_RESULT)); -#elif defined(__arm__) - union { - double fpval; - long long llval; - } result; - result.fpval = FP_RESULT; - return result.llval; -#else -# error unknown architecture -#endif - return 0; - } else if (sel == @selector(stret::::::::::::::::::::::::::::) || - sel == @selector(stre2::::::::::::::::::::::::::::) || - sel == @selector(stre3::::::::::::::::::::::::::::)) - { - testassert(state == 7); - state = 8; - *struct_addr = STRET_RESULT; - return 0; - } else { - fail("unknown selector %s in forward::", sel_getName(sel)); - } - return 0; -} - -#endif - -@end - -typedef id (*id_fn_t)(id self, SEL _cmd, long i1, long i2, long i3, long i4, long i5, long i6, long i7, long i8, long i9, long i10, long i11, long i12, long i13, double f1, double f2, double f3, double f4, double f5, double f6, double f7, double f8, double f9, double f10, double f11, double f12, double f13, double f14, double f15); - -typedef long long (*ll_fn_t)(id self, SEL _cmd, long i1, long i2, long i3, long i4, long i5, long i6, long i7, long i8, long i9, long i10, long i11, long i12, long i13, double f1, double f2, double f3, double f4, double f5, double f6, double f7, double f8, double f9, double f10, double f11, double f12, double f13, double f14, double f15); - -typedef double (*fp_fn_t)(id self, SEL _cmd, long i1, long i2, long i3, long i4, long i5, long i6, long i7, long i8, long i9, long i10, long i11, long i12, long i13, double f1, double f2, double f3, double f4, double f5, double f6, double f7, double f8, double f9, double f10, double f11, double f12, double f13, double f14, double f15); - -typedef struct stret (*st_fn_t)(id self, SEL _cmd, long i1, long i2, long i3, long i4, long i5, long i6, long i7, long i8, long i9, long i10, long i11, long i12, long i13, double f1, double f2, double f3, double f4, double f5, double f6, double f7, double f8, double f9, double f10, double f11, double f12, double f13, double f14, double f15); - -#if __x86_64__ -typedef struct stret * (*fake_st_fn_t)(struct stret *, id self, SEL _cmd, long i1, long i2, long i3, long i4, long i5, long i6, long i7, long i8, long i9, long i10, long i11, long i12, long i13, double f1, double f2, double f3, double f4, double f5, double f6, double f7, double f8, double f9, double f10, double f11, double f12, double f13, double f14, double f15); -#endif - -__BEGIN_DECLS -extern void *getSP(void); -__END_DECLS - -#if defined(__x86_64__) - asm(".text \n _getSP: movq %rsp, %rax \n retq \n"); -#elif defined(__i386__) - asm(".text \n _getSP: movl %esp, %eax \n ret \n"); -#elif defined(__arm__) - asm(".text \n .thumb \n .thumb_func _getSP \n " - "_getSP: mov r0, sp \n bx lr \n"); -#elif defined(__arm64__) - asm(".text \n _getSP: mov x0, sp \n ret \n"); -#else -# error unknown architecture -#endif - -int main() -{ - id idval; - long long llval; - struct stret stval; -#if __x86_64__ - struct stret *stptr; -#endif - double fpval; - void *sp1 = (void*)1; - void *sp2 = (void*)2; - - st_fn_t stret_fwd; -#if __arm64__ - stret_fwd = (st_fn_t)_objc_msgForward; -#else - stret_fwd = (st_fn_t)_objc_msgForward_stret; -#endif - - receiver = [Super class]; - -#if __OBJC2__ - // forward:: not supported -#else - // Test default forward handler - - state = 1; - sp1 = getSP(); - idval = [Super idret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 2); - testassert(idval == ID_RESULT); - - state = 3; - sp1 = getSP(); - llval = [Super llret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 4); - testassert(llval == LL_RESULT); - - state = 5; - sp1 = getSP(); - fpval = [Super fpret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 6); - testassert(fpval == FP_RESULT); - - state = 7; - sp1 = getSP(); - stval = [Super stret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - -#if __x86_64__ - // check stret return register - state = 7; - sp1 = getSP(); - stptr = ((fake_st_fn_t)objc_msgSend_stret)(&stval, [Super class], @selector(stret::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - testassert(stptr == &stval); -#endif - - - // Test default forward handler, cached - - state = 1; - sp1 = getSP(); - idval = [Super idret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 2); - testassert(idval == ID_RESULT); - - state = 3; - sp1 = getSP(); - llval = [Super llret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 4); - testassert(llval == LL_RESULT); - - state = 5; - sp1 = getSP(); - fpval = [Super fpret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 6); - testassert(fpval == FP_RESULT); - - state = 7; - sp1 = getSP(); - stval = [Super stret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - -#if __x86_64__ - // check stret return register - state = 7; - sp1 = getSP(); - stptr = ((fake_st_fn_t)objc_msgSend_stret)(&stval, [Super class], @selector(stret::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - testassert(stptr == &stval); -#endif - - - // Test default forward handler, uncached but fixed-up - - _objc_flush_caches(nil); - - state = 1; - sp1 = getSP(); - idval = [Super idret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 2); - testassert(idval == ID_RESULT); - - state = 3; - sp1 = getSP(); - llval = [Super llret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 4); - testassert(llval == LL_RESULT); - - state = 5; - sp1 = getSP(); - fpval = [Super fpret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 6); - testassert(fpval == FP_RESULT); - - state = 7; - sp1 = getSP(); - stval = [Super stret:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - -#if __x86_64__ - // check stret return register - state = 7; - sp1 = getSP(); - stptr = ((fake_st_fn_t)objc_msgSend_stret)(&stval, [Super class], @selector(stret::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - testassert(stptr == &stval); -#endif - - - // Test manual forwarding - - state = 1; - sp1 = getSP(); - idval = ((id_fn_t)_objc_msgForward)(receiver, @selector(idre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 2); - testassert(idval == ID_RESULT); - - state = 3; - sp1 = getSP(); - llval = ((ll_fn_t)_objc_msgForward)(receiver, @selector(llre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 4); - testassert(llval == LL_RESULT); - - state = 5; - sp1 = getSP(); - fpval = ((fp_fn_t)_objc_msgForward)(receiver, @selector(fpre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 6); - testassert(fpval == FP_RESULT); - - state = 7; - sp1 = getSP(); - stval = stret_fwd(receiver, @selector(stre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - -#if __x86_64__ - // check stret return register - state = 7; - sp1 = getSP(); - stptr = ((fake_st_fn_t)_objc_msgForward_stret)(&stval, receiver, @selector(stre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - testassert(stptr == &stval); -#endif - - - // Test manual forwarding, cached - - state = 1; - sp1 = getSP(); - idval = ((id_fn_t)_objc_msgForward)(receiver, @selector(idre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 2); - testassert(idval == ID_RESULT); - - state = 3; - sp1 = getSP(); - llval = ((ll_fn_t)_objc_msgForward)(receiver, @selector(llre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 4); - testassert(llval == LL_RESULT); - - state = 5; - sp1 = getSP(); - fpval = ((fp_fn_t)_objc_msgForward)(receiver, @selector(fpre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 6); - testassert(fpval == FP_RESULT); - - state = 7; - sp1 = getSP(); - stval = stret_fwd(receiver, @selector(stre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - -#if __x86_64__ - // check stret return register - state = 7; - sp1 = getSP(); - stptr = ((fake_st_fn_t)_objc_msgForward_stret)(&stval, receiver, @selector(stre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - testassert(stptr == &stval); -#endif - - - // Test manual forwarding, uncached but fixed-up - - _objc_flush_caches(nil); - - state = 1; - sp1 = getSP(); - idval = ((id_fn_t)_objc_msgForward)(receiver, @selector(idre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 2); - testassert(idval == ID_RESULT); - - state = 3; - sp1 = getSP(); - llval = ((ll_fn_t)_objc_msgForward)(receiver, @selector(llre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 4); - testassert(llval == LL_RESULT); - - state = 5; - sp1 = getSP(); - fpval = ((fp_fn_t)_objc_msgForward)(receiver, @selector(fpre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 6); - testassert(fpval == FP_RESULT); - - state = 7; - sp1 = getSP(); - stval = stret_fwd(receiver, @selector(stre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - -#if __x86_64__ - // check stret return register - state = 7; - sp1 = getSP(); - stptr = ((fake_st_fn_t)_objc_msgForward_stret)(&stval, receiver, @selector(stre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 8); - testassert(stret_equal(stval, STRET_RESULT)); - testassert(stptr == &stval); -#endif - -// !__OBJC2__ -#endif - - - // Test user-defined forward handler - - objc_setForwardHandler((void*)&forward_handler, (void*)&forward_stret_handler); - - state = 11; - sp1 = getSP(); - idval = [Super idre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 12); - testassert(idval == ID_RESULT); - - state = 13; - sp1 = getSP(); - llval = [Super llre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 14); - testassert(llval == LL_RESULT); - - state = 15; - sp1 = getSP(); - fpval = [Super fpre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 16); - testassert(fpval == FP_RESULT); - - state = 17; - sp1 = getSP(); - stval = [Super stre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 18); - testassert(stret_equal(stval, STRET_RESULT)); - -#if __x86_64__ - // check stret return register - state = 17; - sp1 = getSP(); - stptr = ((fake_st_fn_t)objc_msgSend_stret)(&stval, [Super class], @selector(stre3::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 18); - testassert(stret_equal(stval, STRET_RESULT)); - testassert(stptr == &stval); -#endif - - - // Test user-defined forward handler, cached - - state = 11; - sp1 = getSP(); - idval = [Super idre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 12); - testassert(idval == ID_RESULT); - - state = 13; - sp1 = getSP(); - llval = [Super llre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 14); - testassert(llval == LL_RESULT); - - state = 15; - sp1 = getSP(); - fpval = [Super fpre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 16); - testassert(fpval == FP_RESULT); - - state = 17; - sp1 = getSP(); - stval = [Super stre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 18); - testassert(stret_equal(stval, STRET_RESULT)); - -#if __x86_64__ - // check stret return register - state = 17; - sp1 = getSP(); - stptr = ((fake_st_fn_t)objc_msgSend_stret)(&stval, [Super class], @selector(stre3::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 18); - testassert(stret_equal(stval, STRET_RESULT)); - testassert(stptr == &stval); -#endif - - - // Test user-defined forward handler, uncached but fixed-up - - _objc_flush_caches(nil); - - state = 11; - sp1 = getSP(); - idval = [Super idre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 12); - testassert(idval == ID_RESULT); - - state = 13; - sp1 = getSP(); - llval = [Super llre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 14); - testassert(llval == LL_RESULT); - - state = 15; - sp1 = getSP(); - fpval = [Super fpre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 16); - testassert(fpval == FP_RESULT); - - state = 17; - sp1 = getSP(); - stval = [Super stre3:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 18); - testassert(stret_equal(stval, STRET_RESULT)); - -#if __x86_64__ - // check stret return register - state = 17; - sp1 = getSP(); - stptr = ((fake_st_fn_t)objc_msgSend_stret)(&stval, [Super class], @selector(stre3::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 18); - testassert(stret_equal(stval, STRET_RESULT)); - testassert(stptr == &stval); -#endif - - - - // Test user-defined forward handler, manual forwarding - - state = 11; - sp1 = getSP(); - idval = ((id_fn_t)_objc_msgForward)(receiver, @selector(idre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 12); - testassert(idval == ID_RESULT); - - state = 13; - sp1 = getSP(); - llval = ((ll_fn_t)_objc_msgForward)(receiver, @selector(llre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 14); - testassert(llval == LL_RESULT); - - state = 15; - sp1 = getSP(); - fpval = ((fp_fn_t)_objc_msgForward)(receiver, @selector(fpre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 16); - testassert(fpval == FP_RESULT); - - state = 17; - sp1 = getSP(); - stval = stret_fwd(receiver, @selector(stre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 18); - testassert(stret_equal(stval, STRET_RESULT)); - - - // Test user-defined forward handler, manual forwarding, cached - - state = 11; - sp1 = getSP(); - idval = ((id_fn_t)_objc_msgForward)(receiver, @selector(idre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 12); - testassert(idval == ID_RESULT); - - state = 13; - sp1 = getSP(); - llval = ((ll_fn_t)_objc_msgForward)(receiver, @selector(llre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 14); - testassert(llval == LL_RESULT); - - state = 15; - sp1 = getSP(); - fpval = ((fp_fn_t)_objc_msgForward)(receiver, @selector(fpre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 16); - testassert(fpval == FP_RESULT); - - state = 17; - sp1 = getSP(); - stval = stret_fwd(receiver, @selector(stre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 18); - testassert(stret_equal(stval, STRET_RESULT)); - - - // Test user-defined forward handler, manual forwarding, uncached but fixed-up - - _objc_flush_caches(nil); - - state = 11; - sp1 = getSP(); - idval = ((id_fn_t)_objc_msgForward)(receiver, @selector(idre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 12); - testassert(idval == ID_RESULT); - - state = 13; - sp1 = getSP(); - llval = ((ll_fn_t)_objc_msgForward)(receiver, @selector(llre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 14); - testassert(llval == LL_RESULT); - - state = 15; - sp1 = getSP(); - fpval = ((fp_fn_t)_objc_msgForward)(receiver, @selector(fpre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 16); - testassert(fpval == FP_RESULT); - - state = 17; - sp1 = getSP(); - stval = stret_fwd(receiver, @selector(stre2::::::::::::::::::::::::::::), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - sp2 = getSP(); - testassert(sp1 == sp2); - testassert(state == 18); - testassert(stret_equal(stval, STRET_RESULT)); - - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/forwardDefault.m b/objc/objc-runtime/test/forwardDefault.m deleted file mode 100644 index 2d8b968..0000000 --- a/objc/objc-runtime/test/forwardDefault.m +++ /dev/null @@ -1,31 +0,0 @@ -/* -no arc, rdar://11368528 confused by Foundation -TEST_CONFIG MEM=mrc,gc -TEST_CRASHES -TEST_RUN_OUTPUT -objc\[\d+\]: \+\[NSObject fakeorama\]: unrecognized selector sent to instance 0x[0-9a-fA-F]+ \(no message forward handler is installed\) -CRASHED: SIG(ILL|TRAP) -OR -not OBJC2 -objc\[\d+\]: NSObject: Does not recognize selector forward:: \(while forwarding fakeorama\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#include "test.h" - -#include <objc/NSObject.h> - -@interface NSObject (Fake) --(void)fakeorama; -@end - -int main() -{ -#if !__OBJC2__ - fprintf(stderr, "not OBJC2\n"); -#endif - [NSObject fakeorama]; - fail("should have crashed"); -} - diff --git a/objc/objc-runtime/test/forwardDefaultStret.m b/objc/objc-runtime/test/forwardDefaultStret.m deleted file mode 100644 index 6c6229d..0000000 --- a/objc/objc-runtime/test/forwardDefaultStret.m +++ /dev/null @@ -1,31 +0,0 @@ -/* -no arc, rdar://11368528 confused by Foundation -TEST_CONFIG MEM=mrc,gc -TEST_CRASHES -TEST_RUN_OUTPUT -objc\[\d+\]: \+\[NSObject fakeorama\]: unrecognized selector sent to instance 0x[0-9a-fA-F]+ \(no message forward handler is installed\) -CRASHED: SIG(ILL|TRAP) -OR -not OBJC2 -objc\[\d+\]: NSObject: Does not recognize selector forward:: \(while forwarding fakeorama\) -CRASHED: SIG(ILL|TRAP) -END -*/ - -#include "test.h" - -#include <objc/NSObject.h> - -@interface NSObject (Fake) --(struct stret)fakeorama; -@end - -int main() -{ -#if !__OBJC2__ - fprintf(stderr, "not OBJC2\n"); -#endif - [NSObject fakeorama]; - fail("should have crashed"); -} - diff --git a/objc/objc-runtime/test/future.h b/objc/objc-runtime/test/future.h deleted file mode 100644 index a48dc9a..0000000 --- a/objc/objc-runtime/test/future.h +++ /dev/null @@ -1,15 +0,0 @@ -#include "test.h" - -@interface Sub1 : TestRoot -+(int)method; -+(Class)classref; -@end - -@interface Sub2 : TestRoot -+(int)method; -+(Class)classref; -@end - -@interface SubSub1 : Sub1 @end - -@interface SubSub2 : Sub2 @end diff --git a/objc/objc-runtime/test/future.m b/objc/objc-runtime/test/future.m deleted file mode 100644 index e36f2f6..0000000 --- a/objc/objc-runtime/test/future.m +++ /dev/null @@ -1,82 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/future0.m -o future0.dylib -dynamiclib - $C{COMPILE} $DIR/future2.m -x none future0.dylib -o future2.dylib -dynamiclib - $C{COMPILE} $DIR/future.m -x none future0.dylib -o future.out -END -*/ - -#include "test.h" - -#if __has_feature(objc_arc) - -int main() -{ - testwarn("rdar://10041403 future class API is not ARC-compatible"); - succeed(__FILE__); -} - - -#else - -#include <objc/runtime.h> -#include <malloc/malloc.h> -#include <string.h> -#include <dlfcn.h> -#include "future.h" - -@implementation Sub2 -+(int)method { - return 2; -} -+(Class)classref { - return [Sub2 class]; -} -@end - -@implementation SubSub2 -+(int)method { - return 1 + [super method]; -} -@end - -int main() -{ - Class oldTestRoot; - Class oldSub1; - Class newSub1; - - // objc_getFutureClass with existing class - oldTestRoot = objc_getFutureClass("TestRoot"); - testassert(oldTestRoot == [TestRoot class]); - testassert(! _class_isFutureClass(oldTestRoot)); - - // objc_getFutureClass with missing class - oldSub1 = objc_getFutureClass("Sub1"); - testassert(oldSub1); - testassert(malloc_size(objc_unretainedPointer(oldSub1)) > 0); - testassert(objc_getClass("Sub1") == Nil); - testassert(_class_isFutureClass(oldSub1)); - testassert(0 == strcmp(class_getName(oldSub1), "Sub1")); - testassert(object_getClass(oldSub1) == Nil); // CF expects this - - // objc_getFutureClass a second time - testassert(oldSub1 == objc_getFutureClass("Sub1")); - - // Load class Sub1 - dlopen("future2.dylib", 0); - - // Verify use of future class - newSub1 = objc_getClass("Sub1"); - testassert(oldSub1 == newSub1); - testassert(newSub1 == [newSub1 classref]); - testassert(newSub1 == class_getSuperclass(objc_getClass("SubSub1"))); - testassert(! _class_isFutureClass(newSub1)); - - testassert(1 == [oldSub1 method]); - testassert(1 == [newSub1 method]); - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/future0.m b/objc/objc-runtime/test/future0.m deleted file mode 100644 index 4dd3146..0000000 --- a/objc/objc-runtime/test/future0.m +++ /dev/null @@ -1,2 +0,0 @@ -#include "future.h" -#include "testroot.i" diff --git a/objc/objc-runtime/test/future2.m b/objc/objc-runtime/test/future2.m deleted file mode 100644 index c5ebb58..0000000 --- a/objc/objc-runtime/test/future2.m +++ /dev/null @@ -1,17 +0,0 @@ -#include "future.h" - - -@implementation Sub1 -+(Class)classref { - return [Sub1 class]; -} -+(int)method { - return 1; -} -@end - -@implementation SubSub1 -+(int)method { - return 1 + [super method]; -} -@end diff --git a/objc/objc-runtime/test/gc-main.m b/objc/objc-runtime/test/gc-main.m deleted file mode 100644 index 44f7476..0000000 --- a/objc/objc-runtime/test/gc-main.m +++ /dev/null @@ -1,10 +0,0 @@ -#include "test.h" - -OBJC_ROOT_CLASS -@interface Main @end -@implementation Main @end - -int main(int argc __attribute__((unused)), char **argv) -{ - succeed(basename(argv[0])); -} diff --git a/objc/objc-runtime/test/gc.c b/objc/objc-runtime/test/gc.c deleted file mode 100644 index dab0f7b..0000000 --- a/objc/objc-runtime/test/gc.c +++ /dev/null @@ -1 +0,0 @@ -int GC(void) { return 42; } diff --git a/objc/objc-runtime/test/gc.m b/objc/objc-runtime/test/gc.m deleted file mode 100644 index 65ba5f9..0000000 --- a/objc/objc-runtime/test/gc.m +++ /dev/null @@ -1,8 +0,0 @@ -#import <objc/objc-api.h> - -OBJC_ROOT_CLASS -@interface GC @end -@implementation GC @end - -// silence "no debug symbols in executable" warning -void foo(void) { } diff --git a/objc/objc-runtime/test/gcenforcer-nogc-1.m b/objc/objc-runtime/test/gcenforcer-nogc-1.m deleted file mode 100644 index d72212b..0000000 --- a/objc/objc-runtime/test/gcenforcer-nogc-1.m +++ /dev/null @@ -1,15 +0,0 @@ -// gc-off app loading gc-off dylib: should work - -/* -TEST_CONFIG MEM=mrc,arc OS=macosx - -TEST_BUILD - $C{COMPILE_C} $DIR/gc.c -dynamiclib -o libnoobjc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libnogc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libsupportsgc.dylib -fobjc-gc - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.dylib -fobjc-gc-only - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.fake.dylib -fobjc-gc -install_name librequiresgc.dylib - - $C{COMPILE} $DIR/gc-main.m -x none libnogc.dylib -o gcenforcer-nogc-1.out -END -*/ diff --git a/objc/objc-runtime/test/gcenforcer-nogc-2.m b/objc/objc-runtime/test/gcenforcer-nogc-2.m deleted file mode 100644 index 75146fe..0000000 --- a/objc/objc-runtime/test/gcenforcer-nogc-2.m +++ /dev/null @@ -1,22 +0,0 @@ -// gc-on app loading gc-off dylib: should crash - -/* -TEST_CONFIG MEM=gc OS=macosx -TEST_CRASHES - -TEST_RUN_OUTPUT -objc\[\d+\]: '.*libnogc.dylib' was not compiled with -fobjc-gc or -fobjc-gc-only, but the application requires GC -objc\[\d+\]: \*\*\* GC capability of application and some libraries did not match -CRASHED: SIGILL -END - -TEST_BUILD - $C{COMPILE_C} $DIR/gc.c -dynamiclib -o libnoobjc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libnogc.dylib - $C{COMPILE} $DIR/gc.m -dynamiclib -o libsupportsgc.dylib -fobjc-gc - $C{COMPILE} $DIR/gc.m -dynamiclib -o librequiresgc.dylib -fobjc-gc-only - $C{COMPILE} $DIR/gc.m -dynamiclib -o librequiresgc.fake.dylib -fobjc-gc -install_name librequiresgc.dylib - - $C{COMPILE} $DIR/gc-main.m -x none libnogc.dylib -o gcenforcer-nogc-2.out -END -*/ diff --git a/objc/objc-runtime/test/gcenforcer-noobjc.m b/objc/objc-runtime/test/gcenforcer-noobjc.m deleted file mode 100644 index f37c9ba..0000000 --- a/objc/objc-runtime/test/gcenforcer-noobjc.m +++ /dev/null @@ -1,13 +0,0 @@ -/* -TEST_CONFIG OS=macosx - -TEST_BUILD - $C{COMPILE_C} $DIR/gc.c -dynamiclib -o libnoobjc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libnogc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libsupportsgc.dylib -fobjc-gc - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.dylib -fobjc-gc-only - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.fake.dylib -fobjc-gc -install_name librequiresgc.dylib - - $C{COMPILE} $DIR/gc-main.m -x none libnoobjc.dylib -o gcenforcer-noobjc.out -END -*/ diff --git a/objc/objc-runtime/test/gcenforcer-requiresgc-1.m b/objc/objc-runtime/test/gcenforcer-requiresgc-1.m deleted file mode 100644 index 132e672..0000000 --- a/objc/objc-runtime/test/gcenforcer-requiresgc-1.m +++ /dev/null @@ -1,23 +0,0 @@ -// gc-off app loading gc-required dylib: should crash -// linker sees librequiresgc.fake.dylib, runtime uses librequiresgc.dylib - -/* -TEST_CONFIG MEM=mrc,arc OS=macosx -TEST_CRASHES - -TEST_RUN_OUTPUT -objc\[\d+\]: '.*librequiresgc.dylib' was compiled with -fobjc-gc-only, but the application does not support GC -objc\[\d+\]: \*\*\* GC capability of application and some libraries did not match -CRASHED: SIGILL -END - -TEST_BUILD - $C{COMPILE_C} $DIR/gc.c -dynamiclib -o libnoobjc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libnogc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libsupportsgc.dylib -fobjc-gc - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.dylib -fobjc-gc-only - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.fake.dylib -fobjc-gc -install_name librequiresgc.dylib - - $C{COMPILE} $DIR/gc-main.m -x none librequiresgc.fake.dylib -o gcenforcer-requiresgc-1.out -END -*/ diff --git a/objc/objc-runtime/test/gcenforcer-requiresgc-2.m b/objc/objc-runtime/test/gcenforcer-requiresgc-2.m deleted file mode 100644 index 530891a..0000000 --- a/objc/objc-runtime/test/gcenforcer-requiresgc-2.m +++ /dev/null @@ -1,16 +0,0 @@ -// gc-off app loading gc-required dylib: should crash -// linker sees librequiresgc.fake.dylib, runtime uses librequiresgc.dylib - -/* -TEST_CONFIG MEM=gc OS=macosx - -TEST_BUILD - $C{COMPILE_C} $DIR/gc.c -dynamiclib -o libnoobjc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libnogc.dylib - $C{COMPILE} $DIR/gc.m -dynamiclib -o libsupportsgc.dylib -fobjc-gc - $C{COMPILE} $DIR/gc.m -dynamiclib -o librequiresgc.dylib -fobjc-gc-only - $C{COMPILE} $DIR/gc.m -dynamiclib -o librequiresgc.fake.dylib -fobjc-gc -install_name librequiresgc.dylib - - $C{COMPILE} $DIR/gc-main.m -x none librequiresgc.fake.dylib -o gcenforcer-requiresgc-2.out -END -*/ diff --git a/objc/objc-runtime/test/gcenforcer-supportsgc.m b/objc/objc-runtime/test/gcenforcer-supportsgc.m deleted file mode 100644 index 9551483..0000000 --- a/objc/objc-runtime/test/gcenforcer-supportsgc.m +++ /dev/null @@ -1,13 +0,0 @@ -/* -TEST_CONFIG OS=macosx - -TEST_BUILD - $C{COMPILE_C} $DIR/gc.c -dynamiclib -o libnoobjc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libnogc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libsupportsgc.dylib -fobjc-gc - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.dylib -fobjc-gc-only - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.fake.dylib -fobjc-gc -install_name librequiresgc.dylib - - $C{COMPILE} $DIR/gc-main.m -x none libsupportsgc.dylib -o gcenforcer-supportsgc.out -END -*/ diff --git a/objc/objc-runtime/test/gcenforcer.m b/objc/objc-runtime/test/gcenforcer.m deleted file mode 100644 index 66d66e9..0000000 --- a/objc/objc-runtime/test/gcenforcer.m +++ /dev/null @@ -1,36 +0,0 @@ -/* -TEST_CONFIG OS=macosx - -TEST_BUILD - $C{COMPILE_C} $DIR/gc.c -dynamiclib -o libnoobjc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libnogc.dylib - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o libsupportsgc.dylib -fobjc-gc - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.dylib -fobjc-gc-only - $C{COMPILE_NOMEM} $DIR/gc.m -dynamiclib -o librequiresgc.fake.dylib -fobjc-gc -install_name librequiresgc.dylib - - $C{COMPILE} $DIR/gcenforcer.m -o gcenforcer.out -END -*/ - -#include "test.h" -#include <objc/objc-auto.h> -#include <dlfcn.h> - -int main() -{ - int i; - for (i = 0; i < 1000; i++) { - testassert(dlopen_preflight("libsupportsgc.dylib")); - testassert(dlopen_preflight("libnoobjc.dylib")); - - if (objc_collectingEnabled()) { - testassert(dlopen_preflight("librequiresgc.dylib")); - testassert(! dlopen_preflight("libnogc.dylib")); - } else { - testassert(! dlopen_preflight("librequiresgc.dylib")); - testassert(dlopen_preflight("libnogc.dylib")); - } - } - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/gdb.m b/objc/objc-runtime/test/gdb.m deleted file mode 100644 index a5f571a..0000000 --- a/objc/objc-runtime/test/gdb.m +++ /dev/null @@ -1,59 +0,0 @@ -// TEST_CFLAGS -Wno-deprecated-declarations - -#include "test.h" - -#if TARGET_OS_IPHONE - -int main() -{ - succeed(__FILE__); -} - -#else - -#include "testroot.i" -#include <objc/objc-gdb.h> -#include <objc/runtime.h> - -int main() -{ - // Class hashes -#if __OBJC2__ - - Class result; - - // Class should not be realized yet - // fixme not true during class hash rearrangement - // result = NXMapGet(gdb_objc_realized_classes, "TestRoot"); - // testassert(!result); - - [TestRoot class]; - // Now class should be realized - - result = (Class)objc_unretainedObject(NXMapGet(gdb_objc_realized_classes, "TestRoot")); - testassert(result); - testassert(result == [TestRoot class]); - - result = (Class)objc_unretainedObject(NXMapGet(gdb_objc_realized_classes, "DoesNotExist")); - testassert(!result); - -#else - - struct objc_class query; - Class result; - - query.name = "TestRoot"; - result = (Class)NXHashGet(_objc_debug_class_hash, &query); - testassert(result); - testassert((id)result == [TestRoot class]); - - query.name = "DoesNotExist"; - result = (Class)NXHashGet(_objc_debug_class_hash, &query); - testassert(!result); - -#endif - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/getMethod.m b/objc/objc-runtime/test/getMethod.m deleted file mode 100644 index 84408a8..0000000 --- a/objc/objc-runtime/test/getMethod.m +++ /dev/null @@ -1,130 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <objc/runtime.h> -#include <objc/message.h> - -static int state = 0; - -@interface Super : TestRoot @end -@implementation Super -+(void)classMethod { state = 1; } --(void)instanceMethod { state = 4; } -+(void)classMethodSuperOnly { state = 3; } --(void)instanceMethodSuperOnly { state = 6; } -@end - -@interface Sub : Super @end -@implementation Sub -+(void)classMethod { state = 2; } --(void)instanceMethod { state = 5; } -@end - -typedef void (*imp_t)(id, SEL); - -int main() -{ - Class Super_cls, Sub_cls; - Class buf[10]; - Method m; - SEL sel; - IMP imp; - - // don't use [Super class] to check laziness handing - Super_cls = objc_getClass("Super"); - Sub_cls = objc_getClass("Sub"); - - sel = sel_registerName("classMethod"); - m = class_getClassMethod(Super_cls, sel); - testassert(m); - testassert(sel == method_getName(m)); - imp = method_getImplementation(m); - testassert(imp == class_getMethodImplementation(object_getClass(Super_cls), sel)); - testassert(imp == object_getMethodImplementation(Super_cls, sel)); - state = 0; - (*(imp_t)imp)(Super_cls, sel); - testassert(state == 1); - - sel = sel_registerName("classMethod"); - m = class_getClassMethod(Sub_cls, sel); - testassert(m); - testassert(sel == method_getName(m)); - imp = method_getImplementation(m); - testassert(imp == class_getMethodImplementation(object_getClass(Sub_cls), sel)); - testassert(imp == object_getMethodImplementation(Sub_cls, sel)); - state = 0; - (*(imp_t)imp)(Sub_cls, sel); - testassert(state == 2); - - sel = sel_registerName("classMethodSuperOnly"); - m = class_getClassMethod(Sub_cls, sel); - testassert(m); - testassert(sel == method_getName(m)); - imp = method_getImplementation(m); - testassert(imp == class_getMethodImplementation(object_getClass(Sub_cls), sel)); - testassert(imp == object_getMethodImplementation(Sub_cls, sel)); - state = 0; - (*(imp_t)imp)(Sub_cls, sel); - testassert(state == 3); - - sel = sel_registerName("instanceMethod"); - m = class_getInstanceMethod(Super_cls, sel); - testassert(m); - testassert(sel == method_getName(m)); - imp = method_getImplementation(m); - testassert(imp == class_getMethodImplementation(Super_cls, sel)); - buf[0] = Super_cls; - testassert(imp == object_getMethodImplementation(objc_unretainedObject(buf), sel)); - state = 0; - (*(imp_t)imp)(objc_unretainedObject(buf), sel); - testassert(state == 4); - - sel = sel_registerName("instanceMethod"); - m = class_getInstanceMethod(Sub_cls, sel); - testassert(m); - testassert(sel == method_getName(m)); - imp = method_getImplementation(m); - testassert(imp == class_getMethodImplementation(Sub_cls, sel)); - buf[0] = Sub_cls; - testassert(imp == object_getMethodImplementation(objc_unretainedObject(buf), sel)); - state = 0; - (*(imp_t)imp)(objc_unretainedObject(buf), sel); - testassert(state == 5); - - sel = sel_registerName("instanceMethodSuperOnly"); - m = class_getInstanceMethod(Sub_cls, sel); - testassert(m); - testassert(sel == method_getName(m)); - imp = method_getImplementation(m); - testassert(imp == class_getMethodImplementation(Sub_cls, sel)); - buf[0] = Sub_cls; - testassert(imp == object_getMethodImplementation(objc_unretainedObject(buf), sel)); - state = 0; - (*(imp_t)imp)(objc_unretainedObject(buf), sel); - testassert(state == 6); - - // check class_getClassMethod(cls) == class_getInstanceMethod(cls->isa) - sel = sel_registerName("classMethod"); - testassert(class_getClassMethod(Sub_cls, sel) == class_getInstanceMethod(object_getClass(Sub_cls), sel)); - - sel = sel_registerName("nonexistent"); - testassert(! class_getInstanceMethod(Sub_cls, sel)); - testassert(! class_getClassMethod(Sub_cls, sel)); - testassert(class_getMethodImplementation(Sub_cls, sel) == (IMP)&_objc_msgForward); - buf[0] = Sub_cls; - testassert(object_getMethodImplementation(objc_unretainedObject(buf), sel) == (IMP)&_objc_msgForward); -#if !__arm64__ - testassert(class_getMethodImplementation_stret(Sub_cls, sel) == (IMP)&_objc_msgForward_stret); - testassert(object_getMethodImplementation_stret(objc_unretainedObject(buf), sel) == (IMP)&_objc_msgForward_stret); -#endif - - testassert(! class_getInstanceMethod(NULL, NULL)); - testassert(! class_getInstanceMethod(NULL, sel)); - testassert(! class_getInstanceMethod(Sub_cls, NULL)); - testassert(! class_getClassMethod(NULL, NULL)); - testassert(! class_getClassMethod(NULL, sel)); - testassert(! class_getClassMethod(Sub_cls, NULL)); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/ignoredSelector.m b/objc/objc-runtime/test/ignoredSelector.m deleted file mode 100644 index 733da6a..0000000 --- a/objc/objc-runtime/test/ignoredSelector.m +++ /dev/null @@ -1,350 +0,0 @@ -// TEST_CONFIG MEM=mrc,gc -// TEST_CFLAGS -Wno-deprecated-declarations - -#include "test.h" -#include <objc/runtime.h> -#include <objc/message.h> -#include <objc/objc-auto.h> - -static int state = 0; - -OBJC_ROOT_CLASS -@interface Super { id isa; } @end -@implementation Super -+(id)class { return self; } -+(void)initialize { } - -+(id)ordinary { state = 1; return self; } -+(id)ordinary2 { testassert(0); } -+(id)retain { state = 2; return self; } -+(void)release { state = 3; } -+(id)autorelease { state = 4; return self; } -+(void)dealloc { state = 5; } -+(uintptr_t)retainCount { state = 6; return 6; } -@end - -@interface Sub : Super @end -@implementation Sub @end - -@interface Sub2 : Super @end -@implementation Sub2 @end - -OBJC_ROOT_CLASS -@interface Empty { id isa; } @end -@implementation Empty -+(id)class { return self; } -+(void)initialize { } -@end - -void *forward_handler(id obj, SEL _cmd) { - testassert(obj == [Empty class]); - testassert(_cmd == @selector(ordinary)); - state = 1; - return nil; -} - -@interface Empty (Unimplemented) -+(id)ordinary; -+(id)retain; -+(void)release; -+(id)autorelease; -+(void)dealloc; -+(uintptr_t)retainCount; -@end - - -#define getImp(sel) \ - do { \ - sel##Method = class_getClassMethod(cls, @selector(sel)); \ - testassert(sel##Method); \ - testassert(@selector(sel) == method_getName(sel##Method)); \ - sel = method_getImplementation(sel##Method); \ - } while (0) - - -static IMP ordinary, ordinary2, retain, release, autorelease, dealloc, retainCount; -static Method ordinaryMethod, ordinary2Method, retainMethod, releaseMethod, autoreleaseMethod, deallocMethod, retainCountMethod; - -void cycle(Class cls) -{ - id idVal; - uintptr_t intVal; - -#if defined(__i386__) - if (objc_collectingEnabled()) { - // i386 GC: all ignored selectors are identical - testassert(@selector(retain) == @selector(release) && - @selector(retain) == @selector(autorelease) && - @selector(retain) == @selector(dealloc) && - @selector(retain) == @selector(retainCount) ); - } - else -#endif - { - // x86_64 GC or no GC: all ignored selectors are distinct - testassert(@selector(retain) != @selector(release) && - @selector(retain) != @selector(autorelease) && - @selector(retain) != @selector(dealloc) && - @selector(retain) != @selector(retainCount) ); - } - - // no ignored selector matches a real selector - testassert(@selector(ordinary) != @selector(retain) && - @selector(ordinary) != @selector(release) && - @selector(ordinary) != @selector(autorelease) && - @selector(ordinary) != @selector(dealloc) && - @selector(ordinary) != @selector(retainCount) ); - - getImp(ordinary); - getImp(ordinary2); - getImp(retain); - getImp(release); - getImp(autorelease); - getImp(dealloc); - getImp(retainCount); - - if (objc_collectingEnabled()) { - // GC: all ignored selector IMPs are identical - testassert(retain == release && - retain == autorelease && - retain == dealloc && - retain == retainCount ); - } - else { - // no GC: all ignored selector IMPs are distinct - testassert(retain != release && - retain != autorelease && - retain != dealloc && - retain != retainCount ); - } - - // no ignored selector IMP matches a real selector IMP - testassert(ordinary != retain && - ordinary != release && - ordinary != autorelease && - ordinary != dealloc && - ordinary != retainCount ); - - // Test calls via method_invoke - - idVal = ((id(*)(id, Method))method_invoke)(cls, ordinaryMethod); - testassert(state == 1); - testassert(idVal == cls); - - state = 0; - idVal = ((id(*)(id, Method))method_invoke)(cls, retainMethod); - testassert(state == (objc_collectingEnabled() ? 0 : 2)); - testassert(idVal == cls); - - (void) ((void(*)(id, Method))method_invoke)(cls, releaseMethod); - testassert(state == (objc_collectingEnabled() ? 0 : 3)); - - idVal = ((id(*)(id, Method))method_invoke)(cls, autoreleaseMethod); - testassert(state == (objc_collectingEnabled() ? 0 : 4)); - testassert(idVal == cls); - - (void) ((void(*)(id, Method))method_invoke)(cls, deallocMethod); - testassert(state == (objc_collectingEnabled() ? 0 : 5)); - - intVal = ((uintptr_t(*)(id, Method))method_invoke)(cls, retainCountMethod); - testassert(state == (objc_collectingEnabled() ? 0 : 6)); - testassert(intVal == (objc_collectingEnabled() ? (uintptr_t)cls : 6)); - - - // Test calls via compiled objc_msgSend - - state = 0; - idVal = [cls ordinary]; - testassert(state == 1); - testassert(idVal == cls); - - state = 0; - idVal = [cls retain]; - testassert(state == (objc_collectingEnabled() ? 0 : 2)); - testassert(idVal == cls); - - (void) [cls release]; - testassert(state == (objc_collectingEnabled() ? 0 : 3)); - - idVal = [cls autorelease]; - testassert(state == (objc_collectingEnabled() ? 0 : 4)); - testassert(idVal == cls); - - (void) [cls dealloc]; - testassert(state == (objc_collectingEnabled() ? 0 : 5)); - - intVal = [cls retainCount]; - testassert(state == (objc_collectingEnabled() ? 0 : 6)); - testassert(intVal == (objc_collectingEnabled() ? (uintptr_t)cls : 6)); - - // Test calls via handwritten objc_msgSend - - state = 0; - idVal = ((id(*)(id,SEL))objc_msgSend)(cls, @selector(ordinary)); - testassert(state == 1); - testassert(idVal == cls); - - state = 0; - idVal = ((id(*)(id,SEL))objc_msgSend)(cls, @selector(retain)); - testassert(state == (objc_collectingEnabled() ? 0 : 2)); - testassert(idVal == cls); - - (void) ((void(*)(id,SEL))objc_msgSend)(cls, @selector(release)); - testassert(state == (objc_collectingEnabled() ? 0 : 3)); - - idVal = ((id(*)(id,SEL))objc_msgSend)(cls, @selector(autorelease)); - testassert(state == (objc_collectingEnabled() ? 0 : 4)); - testassert(idVal == cls); - - (void) ((void(*)(id,SEL))objc_msgSend)(cls, @selector(dealloc)); - testassert(state == (objc_collectingEnabled() ? 0 : 5)); - - intVal = ((uintptr_t(*)(id,SEL))objc_msgSend)(cls, @selector(retainCount)); - testassert(state == (objc_collectingEnabled() ? 0 : 6)); - testassert(intVal == (objc_collectingEnabled() ? (uintptr_t)cls : 6)); -} - -int main() -{ - Class cls; - - objc_setForwardHandler((void*)&forward_handler, nil); - - // Test selector API - - testassert(sel_registerName("retain") == @selector(retain)); - testassert(sel_getUid("retain") == @selector(retain)); -#if defined(__i386__) - if (objc_collectingEnabled()) { - // only i386's GC currently remaps these - testassert(0 == strcmp(sel_getName(@selector(retain)), "<ignored selector>")); - } else -#endif - { - testassert(0 == strcmp(sel_getName(@selector(retain)), "retain")); - } -#if !__OBJC2__ - testassert(sel_isMapped(@selector(retain))); -#endif - - cls = [Sub class]; - testassert(cls); - cycle(cls); - - cls = [Super class]; - testassert(cls); - cycle(cls); - - if (objc_collectingEnabled()) { - // rdar://6200570 Method manipulation shouldn't affect ignored methods. - - cls = [Super class]; - testassert(cls); - cycle(cls); - - method_setImplementation(retainMethod, (IMP)1); - method_setImplementation(releaseMethod, (IMP)1); - method_setImplementation(autoreleaseMethod, (IMP)1); - method_setImplementation(deallocMethod, (IMP)1); - method_setImplementation(retainCountMethod, (IMP)1); - cycle(cls); - - testassert(ordinary2 != retainCount); - method_exchangeImplementations(retainMethod, autoreleaseMethod); - method_exchangeImplementations(deallocMethod, releaseMethod); - method_exchangeImplementations(retainCountMethod, ordinary2Method); - cycle(cls); - // ordinary2 exchanged with ignored method is now ignored too - testassert(ordinary2 == retainCount); - - // replace == replace existing - class_replaceMethod(cls, @selector(retain), (IMP)1, ""); - class_replaceMethod(cls, @selector(release), (IMP)1, ""); - class_replaceMethod(cls, @selector(autorelease), (IMP)1, ""); - class_replaceMethod(cls, @selector(dealloc), (IMP)1, ""); - class_replaceMethod(cls, @selector(retainCount), (IMP)1, ""); - cycle(cls); - - cls = [Sub class]; - testassert(cls); - cycle(cls); - - // replace == add override - class_replaceMethod(cls, @selector(retain), (IMP)1, ""); - class_replaceMethod(cls, @selector(release), (IMP)1, ""); - class_replaceMethod(cls, @selector(autorelease), (IMP)1, ""); - class_replaceMethod(cls, @selector(dealloc), (IMP)1, ""); - class_replaceMethod(cls, @selector(retainCount), (IMP)1, ""); - cycle(cls); - - cls = [Sub2 class]; - testassert(cls); - cycle(cls); - - class_addMethod(cls, @selector(retain), (IMP)1, ""); - class_addMethod(cls, @selector(release), (IMP)1, ""); - class_addMethod(cls, @selector(autorelease), (IMP)1, ""); - class_addMethod(cls, @selector(dealloc), (IMP)1, ""); - class_addMethod(cls, @selector(retainCount), (IMP)1, ""); - cycle(cls); - } - - // Test calls via objc_msgSend - ignored selectors are ignored - // under GC even if the class provides no implementation for them - if (objc_collectingEnabled()) { - Class cls; - id idVal; - uintptr_t intVal; - - cls = [Empty class]; - state = 0; - - idVal = [Empty retain]; - testassert(state == 0); - testassert(idVal == cls); - - (void) [Empty release]; - testassert(state == 0); - - idVal = [Empty autorelease]; - testassert(state == 0); - testassert(idVal == cls); - - (void) [Empty dealloc]; - testassert(state == 0); - - intVal = [Empty retainCount]; - testassert(state == 0); - testassert(intVal == (uintptr_t)cls); - - idVal = [Empty ordinary]; - testassert(state == 1); - testassert(idVal == nil); - - state = 0; - - idVal = ((id(*)(id,SEL))objc_msgSend)(cls, @selector(retain)); - testassert(state == 0); - testassert(idVal == cls); - - (void) ((void(*)(id,SEL))objc_msgSend)(cls, @selector(release)); - testassert(state == 0); - - idVal = ((id(*)(id,SEL))objc_msgSend)(cls, @selector(autorelease)); - testassert(state == 0); - testassert(idVal == cls); - - (void) ((void(*)(id,SEL))objc_msgSend)(cls, @selector(dealloc)); - testassert(state == 0); - - intVal = ((uintptr_t(*)(id,SEL))objc_msgSend)(cls, @selector(retainCount)); - testassert(state == 0); - testassert(intVal == (uintptr_t)cls); - - idVal = ((id(*)(id,SEL))objc_msgSend)(cls, @selector(ordinary)); - testassert(state == 1); - testassert(idVal == nil); - } - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/ignoredSelector2.m b/objc/objc-runtime/test/ignoredSelector2.m deleted file mode 100644 index d0a24c8..0000000 --- a/objc/objc-runtime/test/ignoredSelector2.m +++ /dev/null @@ -1,37 +0,0 @@ -// TEST_CONFIG MEM=gc -// TEST_CFLAGS -framework Foundation - -// This test must use CF and test ignoredSelector must not use CF. - -#include "test.h" -#include <objc/NSObject.h> - -int main() -{ - if (objc_collectingEnabled()) { - // ARC RR functions don't retain and don't hit the side table. - __block int count; - testblock_t testblock = ^{ - for (int i = 0; i < count; i++) { - id obj = [NSObject new]; - objc_retain(obj); - objc_retain(obj); - objc_release(obj); - } - }; - count = 100; - testonthread(testblock); - testonthread(testblock); - leak_mark(); - count = 10000000; - testonthread(testblock); -#if __OBJC_GC__ - testwarn("rdar://19042235 possible leaks suppressed under GC"); - leak_check(2000); -#else - leak_check(0); -#endif - } - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/imageorder.h b/objc/objc-runtime/test/imageorder.h deleted file mode 100644 index 654e48e..0000000 --- a/objc/objc-runtime/test/imageorder.h +++ /dev/null @@ -1,20 +0,0 @@ -extern int state; -extern int cstate; - -OBJC_ROOT_CLASS -@interface Super { id isa; } -+(void) method; -+(void) method0; -@end - -@interface Super (cat1) -+(void) method1; -@end - -@interface Super (cat2) -+(void) method2; -@end - -@interface Super (cat3) -+(void) method3; -@end diff --git a/objc/objc-runtime/test/imageorder.m b/objc/objc-runtime/test/imageorder.m deleted file mode 100644 index f417eb5..0000000 --- a/objc/objc-runtime/test/imageorder.m +++ /dev/null @@ -1,41 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/imageorder1.m -o imageorder1.dylib -dynamiclib - $C{COMPILE} $DIR/imageorder2.m -x none imageorder1.dylib -o imageorder2.dylib -dynamiclib - $C{COMPILE} $DIR/imageorder3.m -x none imageorder2.dylib imageorder1.dylib -o imageorder3.dylib -dynamiclib - $C{COMPILE} $DIR/imageorder.m -x none imageorder3.dylib imageorder2.dylib imageorder1.dylib -o imageorder.out -END -*/ - -#include "test.h" -#include "imageorder.h" -#include <objc/runtime.h> -#include <dlfcn.h> - -int main() -{ - // +load methods and C static initializers - testassert(state == 3); - testassert(cstate == 3); - - Class cls = objc_getClass("Super"); - testassert(cls); - - // make sure all categories arrived - state = -1; - [Super method0]; - testassert(state == 0); - [Super method1]; - testassert(state == 1); - [Super method2]; - testassert(state == 2); - [Super method3]; - testassert(state == 3); - - // make sure imageorder3.dylib is the last category to attach - state = 0; - [Super method]; - testassert(state == 3); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/imageorder1.m b/objc/objc-runtime/test/imageorder1.m deleted file mode 100644 index 2cc1d80..0000000 --- a/objc/objc-runtime/test/imageorder1.m +++ /dev/null @@ -1,52 +0,0 @@ -#include "test.h" -#include "imageorder.h" - -int state = -1; -int cstate = 0; - -static void c1(void) __attribute__((constructor)); -static void c1(void) -{ - testassert(state == 1); // +load before C/C++ - testassert(cstate == 0); - cstate = 1; -} - - -#if __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation" -#endif - -@implementation Super (cat1) -+(void) method { - fail("+[Super(cat1) method] not replaced!"); -} -+(void) method1 { - state = 1; -} -+(void) load { - testassert(state == 0); - state = 1; -} -@end - -#if __clang__ -#pragma clang diagnostic pop -#endif - - -@implementation Super -+(void) initialize { } -+(void) method { - fail("+[Super method] not replaced!"); -} -+(void) method0 { - state = 0; -} -+(void) load { - testassert(state == -1); - state = 0; -} -@end - diff --git a/objc/objc-runtime/test/imageorder2.m b/objc/objc-runtime/test/imageorder2.m deleted file mode 100644 index e4d690b..0000000 --- a/objc/objc-runtime/test/imageorder2.m +++ /dev/null @@ -1,33 +0,0 @@ -#include "test.h" -#include "imageorder.h" - -static void c2(void) __attribute__((constructor)); -static void c2(void) -{ - testassert(state == 2); // +load before C/C++ - testassert(cstate == 1); - cstate = 2; -} - - -#if __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation" -#endif - -@implementation Super (cat2) -+(void) method { - fail("+[Super(cat2) method] not replaced!"); -} -+(void) method2 { - state = 2; -} -+(void) load { - testassert(state == 1); - state = 2; -} -@end - -#if __clang__ -#pragma clang diagnostic pop -#endif diff --git a/objc/objc-runtime/test/imageorder3.m b/objc/objc-runtime/test/imageorder3.m deleted file mode 100644 index 217130f..0000000 --- a/objc/objc-runtime/test/imageorder3.m +++ /dev/null @@ -1,33 +0,0 @@ -#include "test.h" -#include "imageorder.h" - -static void c3(void) __attribute__((constructor)); -static void c3(void) -{ - testassert(state == 3); // +load before C/C++ - testassert(cstate == 2); - cstate = 3; -} - - -#if __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation" -#endif - -@implementation Super (cat3) -+(void) method { - state = 3; -} -+(void) method3 { - state = 3; -} -+(void) load { - testassert(state == 2); - state = 3; -} -@end - -#if __clang__ -#pragma clang diagnostic pop -#endif diff --git a/objc/objc-runtime/test/includes.c b/objc/objc-runtime/test/includes.c deleted file mode 100644 index 01c1686..0000000 --- a/objc/objc-runtime/test/includes.c +++ /dev/null @@ -1,38 +0,0 @@ -// TEST_CONFIG - -// Verify that all headers can be included in any language. - -#include <objc/objc.h> - -#include <objc/List.h> -#include <objc/NSObjCRuntime.h> -#include <objc/NSObject.h> -#include <objc/Object.h> -#include <objc/Protocol.h> -#include <objc/message.h> -#include <objc/objc-api.h> -#include <objc/objc-auto.h> -#include <objc/objc-class.h> -#include <objc/objc-exception.h> -#include <objc/objc-load.h> -#include <objc/objc-runtime.h> -#include <objc/objc-sync.h> -#include <objc/runtime.h> - -#include <objc/objc-abi.h> -#include <objc/objc-auto-dump.h> -#include <objc/objc-gdb.h> -#include <objc/objc-internal.h> - -#if !TARGET_OS_IPHONE -#include <objc/hashtable.h> -#include <objc/hashtable2.h> -#include <objc/maptable.h> -#endif - -#include "test.h" - -int main() -{ - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/initialize.m b/objc/objc-runtime/test/initialize.m deleted file mode 100644 index c3bced1..0000000 --- a/objc/objc-runtime/test/initialize.m +++ /dev/null @@ -1,277 +0,0 @@ -// TEST_CONFIG - -// initialize.m -// Test basic +initialize behavior -// * +initialize before class method -// * superclass +initialize before subclass +initialize -// * subclass inheritance of superclass implementation -// * messaging during +initialize -// * +initialize provoked by class_getMethodImplementation -// * +initialize not provoked by objc_getClass -#include "test.h" -#include "testroot.i" - -int state = 0; - -@interface Super0 : TestRoot @end -@implementation Super0 -+(void)initialize { - fail("objc_getClass() must not trigger +initialize"); -} -@end - -@interface Super : TestRoot @end -@implementation Super -+(void)initialize { - testprintf("in [Super initialize]\n"); - testassert(state == 0); - state = 1; -} -+(void)method { - fail("[Super method] shouldn't be called"); -} -@end - -@interface Sub : Super @end -@implementation Sub -+(void)initialize { - testprintf("in [Sub initialize]\n"); - testassert(state == 1); - state = 2; -} -+(void)method { - testprintf("in [Sub method]\n"); - testassert(state == 2); - state = 3; -} -@end - - -@interface Super2 : TestRoot @end -@interface Sub2 : Super2 @end - -@implementation Super2 -+(void)initialize { - if (self == objc_getClass("Sub2")) { - testprintf("in [Super2 initialize] of Sub2\n"); - testassert(state == 1); - state = 2; - } else if (self == objc_getClass("Super2")) { - testprintf("in [Super2 initialize] of Super2\n"); - testassert(state == 0); - state = 1; - } else { - fail("in [Super2 initialize] of unknown class"); - } -} -+(void)method { - testprintf("in [Super2 method]\n"); - testassert(state == 2); - state = 3; -} -@end - -@implementation Sub2 -// nothing here -@end - - -@interface Super3 : TestRoot @end -@interface Sub3 : Super3 @end - -@implementation Super3 -+(void)initialize { - if (self == [Sub3 class]) { // this message triggers [Sub3 initialize] - testprintf("in [Super3 initialize] of Sub3\n"); - testassert(state == 0); - state = 1; - } else if (self == [Super3 class]) { - testprintf("in [Super3 initialize] of Super3\n"); - testassert(state == 1); - state = 2; - } else { - fail("in [Super3 initialize] of unknown class"); - } -} -+(void)method { - testprintf("in [Super3 method]\n"); - testassert(state == 2); - state = 3; -} -@end - -@implementation Sub3 -// nothing here -@end - - -@interface Super4 : TestRoot @end -@implementation Super4 --(void)instanceMethod { - testassert(state == 1); - state = 2; -} -+(void)initialize { - testprintf("in [Super4 initialize]\n"); - testassert(state == 0); - state = 1; - id x = [[self alloc] init]; - [x instanceMethod]; - RELEASE_VALUE(x); -} -@end - - -@interface Super5 : TestRoot @end -@implementation Super5 --(void)instanceMethod { -} -+(void)classMethod { - testassert(state == 1); - state = 2; -} -+(void)initialize { - testprintf("in [Super5 initialize]\n"); - testassert(state == 0); - state = 1; - class_getMethodImplementation(self, @selector(instanceMethod)); - // this is the "memoized" case for getNonMetaClass - class_getMethodImplementation(object_getClass(self), @selector(classMethod)); - [self classMethod]; -} -@end - - -@interface Super6 : TestRoot @end -@interface Sub6 : Super6 @end -@implementation Super6 -+(void)initialize { - static bool once; - bool wasOnce; - testprintf("in [Super6 initialize] (#%d)\n", 1+(int)once); - if (!once) { - once = true; - wasOnce = true; - testassert(state == 0); - state = 1; - } else { - wasOnce = false; - testassert(state == 2); - state = 3; - } - [Sub6 class]; - if (wasOnce) { - testassert(state == 5); - state = 6; - } else { - testassert(state == 3); - state = 4; - } -} -@end -@implementation Sub6 -+(void)initialize { - testprintf("in [Sub6 initialize]\n"); - testassert(state == 1); - state = 2; - [super initialize]; - testassert(state == 4); - state = 5; -} -@end - - -@interface Super7 : TestRoot @end -@interface Sub7 : Super7 @end -@implementation Super7 -+(void)initialize { - static bool once; - bool wasOnce; - testprintf("in [Super7 initialize] (#%d)\n", 1+(int)once); - if (!once) { - once = true; - wasOnce = true; - testassert(state == 0); - state = 1; - } else { - wasOnce = false; - testassert(state == 2); - state = 3; - } - [Sub7 class]; - if (wasOnce) { - testassert(state == 5); - state = 6; - } else { - testassert(state == 3); - state = 4; - } -} -@end -@implementation Sub7 -+(void)initialize { - testprintf("in [Sub7 initialize]\n"); - testassert(state == 1); - state = 2; - [super initialize]; - testassert(state == 4); - state = 5; -} -@end - - -int main() -{ - Class cls; - - // objc_getClass() must not +initialize anything - state = 0; - objc_getClass("Super0"); - testassert(state == 0); - - // initialize superclass, then subclass - state = 0; - [Sub method]; - testassert(state == 3); - - // check subclass's inheritance of superclass initialize - state = 0; - [Sub2 method]; - testassert(state == 3); - - // check subclass method called from superclass initialize - state = 0; - [Sub3 method]; - testassert(state == 3); - - // check class_getMethodImplementation (instance method) - state = 0; - cls = objc_getClass("Super4"); - testassert(state == 0); - class_getMethodImplementation(cls, @selector(classMethod)); - testassert(state == 2); - - // check class_getMethodImplementation (class method) - // this is the "slow" case for getNonMetaClass - state = 0; - cls = objc_getClass("Super5"); - testassert(state == 0); - class_getMethodImplementation(object_getClass(cls), @selector(instanceMethod)); - testassert(state == 2); - - // check +initialize cycles - // this is the "cls is a subclass" case for getNonMetaClass - state = 0; - [Super6 class]; - testassert(state == 6); - - // check +initialize cycles - // this is the "cls is a subclass" case for getNonMetaClass - state = 0; - [Sub7 class]; - testassert(state == 6); - - succeed(__FILE__); - - return 0; -} diff --git a/objc/objc-runtime/test/initializeVersusWeak.m b/objc/objc-runtime/test/initializeVersusWeak.m deleted file mode 100644 index c7a0e36..0000000 --- a/objc/objc-runtime/test/initializeVersusWeak.m +++ /dev/null @@ -1,129 +0,0 @@ -// TEST_CONFIG MEM=arc -// TEST_CFLAGS -framework Foundation - -// Problem: If weak reference operations provoke +initialize, the runtime -// can deadlock (recursive weak lock, or lock inversion between weak lock -// and +initialize lock). -// Solution: object_setClass() and objc_storeWeak() perform +initialize -// if needed so that no weakly-referenced object can ever have an -// un-+initialized isa. - -#include <Foundation/Foundation.h> -#include <objc/objc-internal.h> -#include "test.h" - -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#pragma clang diagnostic ignored "-Warc-unsafe-retained-assign" - -// This is StripedMap's pointer hash -uintptr_t hash(id obj) { - uintptr_t addr = (uintptr_t)obj; - return ((addr >> 4) ^ (addr >> 9)) % 64; -} - -bool sameAlignment(id o1, id o2) -{ - return hash(o1) == hash(o2); -} - -// Return a new string object that uses the same striped weak locks as `obj`. -NSMutableString *newAlignedString(id obj) -{ - NSMutableArray *strings = [NSMutableArray new]; - NSMutableString *result; - do { - result = [NSMutableString new]; - [strings addObject:result]; - } while (!sameAlignment(obj, result)); - return result; -} - - -__weak NSObject *weak1; -__weak NSMutableString *weak2; -NSMutableString *strong2; - -@interface A : NSObject @end -@implementation A -+(void)initialize { - weak2 = strong2; // weak store #2 - strong2 = nil; -} -@end - -void testA() -{ - // Weak store #1 provokes +initialize which performs weak store #2. - // Solution: weak store #1 runs +initialize if needed - // without holding locks. - @autoreleasepool { - A *obj = [A new]; - strong2 = newAlignedString(obj); - [obj addObserver:obj forKeyPath:@"foo" options:0 context:0]; - weak1 = obj; // weak store #1 - [obj removeObserver:obj forKeyPath:@"foo"]; - obj = nil; - } -} - - -__weak NSObject *weak3; -__weak NSMutableString *weak4; -NSMutableString *strong4; - -@interface B : NSObject @end -@implementation B -+(void)initialize { - weak4 = strong4; // weak store #4 - strong4 = nil; -} -@end - - -void testB() -{ - // Weak load #3 provokes +initialize which performs weak store #4. - // Solution: object_setClass() runs +initialize if needed - // without holding locks. - @autoreleasepool { - B *obj = [B new]; - strong4 = newAlignedString(obj); - weak3 = obj; - [obj addObserver:obj forKeyPath:@"foo" options:0 context:0]; - [weak3 self]; // weak load #3 - [obj removeObserver:obj forKeyPath:@"foo"]; - obj = nil; - } -} - - -__weak id weak5; - -@interface C : NSObject @end -@implementation C -+(void)initialize { - weak5 = [self new]; -} -@end - -void testC() -{ - // +initialize performs a weak store of itself. - // Make sure the retry in objc_storeWeak() doesn't spin. - @autoreleasepool { - [C self]; - } -} - - -int main() -{ - alarm(10); // replace hangs with crashes - - testA(); - testB(); - testC(); - - succeed(__FILE__); -} - diff --git a/objc/objc-runtime/test/instanceSize.m b/objc/objc-runtime/test/instanceSize.m deleted file mode 100644 index 8034a5c..0000000 --- a/objc/objc-runtime/test/instanceSize.m +++ /dev/null @@ -1,59 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <objc/runtime.h> - - -@interface Sub1 : TestRoot { - // id isa; // 0..4 - BOOL b; // 4..5 -} -@end - -@implementation Sub1 @end - -@interface Sub2 : Sub1 { - // id isa // 0..4 0..8 - // BOOL b // 4..5 8..9 - BOOL b2; // 5..6 9..10 - id o; // 8..12 16..24 -} -@end -@implementation Sub2 @end - -@interface Sub3 : Sub1 { - // id isa; // 0..4 0..8 - // BOOL b; // 4..5 8..9 - id o; // 8..12 16..24 - BOOL b2; // 12..13 24..25 -} -@end -@implementation Sub3 @end - -int main() -{ - testassert(sizeof(id) == class_getInstanceSize([TestRoot class])); - testassert(2*sizeof(id) == class_getInstanceSize([Sub1 class])); - testassert(3*sizeof(id) == class_getInstanceSize([Sub2 class])); - testassert(4*sizeof(id) == class_getInstanceSize([Sub3 class])); - -#if !__has_feature(objc_arc) - id o; - - o = [TestRoot new]; - testassert(object_getIndexedIvars(o) == (char *)o + class_getInstanceSize(object_getClass(o))); - RELEASE_VAR(o); - o = [Sub1 new]; - testassert(object_getIndexedIvars(o) == (char *)o + class_getInstanceSize(object_getClass(o))); - RELEASE_VAR(o); - o = [Sub2 new]; - testassert(object_getIndexedIvars(o) == (char *)o + class_getInstanceSize(object_getClass(o))); - RELEASE_VAR(o); - o = [Sub3 new]; - testassert(object_getIndexedIvars(o) == (char *)o + class_getInstanceSize(object_getClass(o))); - RELEASE_VAR(o); -#endif - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/ismeta.m b/objc/objc-runtime/test/ismeta.m deleted file mode 100644 index d0e580d..0000000 --- a/objc/objc-runtime/test/ismeta.m +++ /dev/null @@ -1,13 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <objc/objc-runtime.h> - -int main() -{ - testassert(!class_isMetaClass([TestRoot class])); - testassert(class_isMetaClass(object_getClass([TestRoot class]))); - testassert(!class_isMetaClass(nil)); - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/ivar.m b/objc/objc-runtime/test/ivar.m deleted file mode 100644 index 84bda90..0000000 --- a/objc/objc-runtime/test/ivar.m +++ /dev/null @@ -1,110 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <stdint.h> -#include <string.h> -#include <objc/objc-runtime.h> - -@interface Super : TestRoot { - @public - char superIvar; -} -@end - -@interface Sub : Super { - @public - id subIvar; -} -@end - -@implementation Super @end -@implementation Sub @end - - -int main() -{ - /* - Runtime layout of Sub: - [0] isa - [1] superIvar - [2] subIvar - */ - - Ivar ivar; - Sub *sub = [Sub new]; - sub->subIvar = [Sub class]; - testassert(((Class *)objc_unretainedPointer(sub))[2] == [Sub class]); - - ivar = class_getInstanceVariable([Sub class], "subIvar"); - testassert(ivar); - testassert(2*sizeof(intptr_t) == (size_t)ivar_getOffset(ivar)); - testassert(0 == strcmp(ivar_getName(ivar), "subIvar")); - testassert(0 == strcmp(ivar_getTypeEncoding(ivar), "@")); - - ivar = class_getInstanceVariable([Super class], "superIvar"); - testassert(ivar); - testassert(sizeof(intptr_t) == (size_t)ivar_getOffset(ivar)); - testassert(0 == strcmp(ivar_getName(ivar), "superIvar")); - testassert(0 == strcmp(ivar_getTypeEncoding(ivar), "c")); - testassert(ivar == class_getInstanceVariable([Sub class], "superIvar")); - - ivar = class_getInstanceVariable([Super class], "subIvar"); - testassert(!ivar); - - ivar = class_getInstanceVariable(object_getClass([Sub class]), "subIvar"); - testassert(!ivar); - - ivar = class_getInstanceVariable([Sub class], "subIvar"); - object_setIvar(sub, ivar, sub); - testassert(sub->subIvar == sub); - testassert(sub == object_getIvar(sub, ivar)); - - testassert(NULL == class_getInstanceVariable(NULL, "foo")); - testassert(NULL == class_getInstanceVariable([Sub class], NULL)); - testassert(NULL == class_getInstanceVariable(NULL, NULL)); - - testassert(NULL == object_getIvar(sub, NULL)); - testassert(NULL == object_getIvar(NULL, ivar)); - testassert(NULL == object_getIvar(NULL, NULL)); - - object_setIvar(sub, NULL, NULL); - object_setIvar(NULL, ivar, NULL); - object_setIvar(NULL, NULL, NULL); - -#if !__has_feature(objc_arc) - - uintptr_t value; - - sub->subIvar = (id)10; - value = 0; - object_getInstanceVariable(sub, "subIvar", (void **)&value); - testassert(value == 10); - - object_setInstanceVariable(sub, "subIvar", (id)11); - testassert(sub->subIvar == (id)11); - - ivar = class_getInstanceVariable([Sub class], "subIvar"); - testassert(ivar == object_getInstanceVariable(sub, "subIvar", NULL)); - - testassert(NULL == object_getInstanceVariable(sub, NULL, NULL)); - testassert(NULL == object_getInstanceVariable(NULL, "foo", NULL)); - testassert(NULL == object_getInstanceVariable(NULL, NULL, NULL)); - value = 10; - testassert(NULL == object_getInstanceVariable(sub, NULL, (void **)&value)); - testassert(value == 0); - value = 10; - testassert(NULL == object_getInstanceVariable(NULL, "foo", (void **)&value)); - testassert(value == 0); - value = 10; - testassert(NULL == object_getInstanceVariable(NULL, NULL, (void **)&value)); - testassert(value == 0); - - testassert(NULL == object_setInstanceVariable(sub, NULL, NULL)); - testassert(NULL == object_setInstanceVariable(NULL, "foo", NULL)); - testassert(NULL == object_setInstanceVariable(NULL, NULL, NULL)); -#endif - - succeed(__FILE__); - return 0; -} diff --git a/objc/objc-runtime/test/ivarSlide.h b/objc/objc-runtime/test/ivarSlide.h deleted file mode 100644 index d4e89ca..0000000 --- a/objc/objc-runtime/test/ivarSlide.h +++ /dev/null @@ -1,110 +0,0 @@ -@interface Super : TestRoot { - @public -#if OLD - // nothing -#else - char superIvar; -#endif -} -@end - - -@interface ShrinkingSuper : TestRoot { - @public -#if OLD - id superIvar[5]; - __weak id superIvar2[5]; -#else - // nothing -#endif -} -@end; - - -@interface MoreStrongSuper : TestRoot { - @public -#if OLD - void *superIvar; -#else - id superIvar; -#endif -} -@end; - - -@interface MoreWeakSuper : TestRoot { - @public -#if OLD - id superIvar; -#else - __weak id superIvar; -#endif -} -@end; - -@interface MoreWeak2Super : TestRoot { - @public -#if OLD - void *superIvar; -#else - __weak id superIvar; -#endif -} -@end; - -@interface LessStrongSuper : TestRoot { - @public -#if OLD - id superIvar; -#else - void *superIvar; -#endif -} -@end; - -@interface LessWeakSuper : TestRoot { - @public -#if OLD - __weak id superIvar; -#else - id superIvar; -#endif -} -@end; - -@interface LessWeak2Super : TestRoot { - @public -#if OLD - __weak id superIvar; -#else - void *superIvar; -#endif -} -@end; - -@interface NoGCChangeSuper : TestRoot { - @public - intptr_t d; - char superc1; -#if OLD - // nothing -#else - char superc2; -#endif -} -@end - -@interface RunsOf15 : TestRoot { - @public - id scan1; - intptr_t skip15[15]; - id scan15[15]; - intptr_t skip15_2[15]; - id scan15_2[15]; -#if OLD - // nothing -#else - intptr_t skip1; -#endif -} -@end diff --git a/objc/objc-runtime/test/ivarSlide.m b/objc/objc-runtime/test/ivarSlide.m deleted file mode 100644 index 43c3660..0000000 --- a/objc/objc-runtime/test/ivarSlide.m +++ /dev/null @@ -1,533 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/ivarSlide1.m $DIR/ivarSlide.m -o ivarSlide.out -END -*/ - -#include "test.h" -#include <string.h> -#include <stdint.h> -#include <objc/objc-runtime.h> -#include <objc/objc-auto.h> - -// ARC doesn't like __strong void* or __weak void* -#if __OBJC_GC__ -# define gc_weak __weak -# define gc_strong __strong -#else -# define gc_weak -# define gc_strong -#endif - -#define OLD 1 -#include "ivarSlide.h" - -#define ustrcmp(a, b) strcmp((char *)a, (char *)b) - -#ifdef __cplusplus -class CXX { - public: - static uintptr_t count; - uintptr_t magic; - CXX() : magic(1) { } - ~CXX() { count += magic; } -}; -uintptr_t CXX::count; -#endif - -@interface Bitfields : Super { - uint8_t uint8_ivar; - uint8_t uint8_bitfield1 :7; - uint8_t uint8_bitfield2 :1; - - id id_ivar; - - uintptr_t uintptr_ivar; - uintptr_t /*uintptr_bitfield1*/ :31; // anonymous (rdar://5723893) - uintptr_t uintptr_bitfield2 :1; - - id id_ivar2; -} -@end - -@implementation Bitfields @end - - -@interface Sub : Super { - @public - uintptr_t subIvar; - gc_strong void* subIvar2; - gc_weak void* subIvar3; -#ifdef __cplusplus - CXX cxx; -#else - // same layout as cxx - uintptr_t cxx_magic; -#endif -} -@end - -@implementation Sub @end - - -@interface Sub2 : ShrinkingSuper { - @public - gc_weak void* subIvar; - gc_strong void* subIvar2; -} -@end - -@implementation Sub2 @end - -@interface MoreStrongSub : MoreStrongSuper { id subIvar; } @end -@interface LessStrongSub : LessStrongSuper { id subIvar; } @end -@interface MoreWeakSub : MoreWeakSuper { id subIvar; } @end -@interface MoreWeak2Sub : MoreWeak2Super { id subIvar; } @end -@interface LessWeakSub : LessWeakSuper { id subIvar; } @end -@interface LessWeak2Sub : LessWeak2Super { id subIvar; } @end - -@implementation MoreStrongSub @end -@implementation LessStrongSub @end -@implementation MoreWeakSub @end -@implementation MoreWeak2Sub @end -@implementation LessWeakSub @end -@implementation LessWeak2Sub @end - -@interface NoGCChangeSub : NoGCChangeSuper { - @public - char subc3; -} -@end -@implementation NoGCChangeSub @end - -@interface RunsOf15Sub : RunsOf15 { - @public - char sub; -} -@end -@implementation RunsOf15Sub @end - - -int main(int argc __attribute__((unused)), char **argv) -{ -#if __OBJC2__ - -#if __has_feature(objc_arc) - testwarn("fixme check ARC layouts too"); -#endif - - /* - Bitfield ivars. - rdar://5723893 anonymous bitfield ivars crash when slid - rdar://5724385 bitfield ivar alignment incorrect - - Compile-time layout of Bitfields: - [0 scan] isa - [1 skip] uint8_ivar, uint8_bitfield - [2 scan] id_ivar - [3 skip] uintptr_ivar - [4 skip] uintptr_bitfield - [5 scan] id_ivar2 - - Runtime layout of Bitfields: - [0 scan] isa - [1 skip] superIvar - [2 skip] uint8_ivar, uint8_bitfield - [3 scan] id_ivar - [4 skip] uintptr_ivar - [5 skip] uintptr_bitfield - [6 scan] id_ivar2 - */ - - [Bitfields class]; - - testassert(class_getInstanceSize([Bitfields class]) == 7*sizeof(void*)); - - if (objc_collectingEnabled()) { - const uint8_t *bitfieldlayout; - bitfieldlayout = class_getIvarLayout([Bitfields class]); - testassert(0 == ustrcmp(bitfieldlayout, "\x01\x21\x21")); - - bitfieldlayout = class_getWeakIvarLayout([Bitfields class]); - testassert(bitfieldlayout == NULL); - } - - /* - Compile-time layout of Sub: - [0 scan] isa - [1 skip] subIvar - [2 scan] subIvar2 - [3 weak] subIvar3 - [6 skip] cxx - - Runtime layout of Sub: - [0 scan] isa - [1 skip] superIvar - [2 skip] subIvar - [3 scan] subIvar2 - [4 weak] subIvar3 - [6 skip] cxx - - Also, superIvar is only one byte, so subIvar's alignment must - be handled correctly. - - fixme test more layouts - */ - - Ivar ivar; - static Sub * volatile sub; - sub = [Sub new]; - sub->subIvar = 10; - testassert(((uintptr_t *)objc_unretainedPointer(sub))[2] == 10); - -#ifdef __cplusplus - testassert(((uintptr_t *)objc_unretainedPointer(sub))[5] == 1); - testassert(sub->cxx.magic == 1); - sub->cxx.magic++; - testassert(((uintptr_t *)objc_unretainedPointer(sub))[5] == 2); - testassert(sub->cxx.magic == 2); -# if __has_feature(objc_arc) - sub = nil; -# else - if (! objc_collectingEnabled()) { - [sub dealloc]; - } else { - // hack - can't get collector to reliably delete the object - object_dispose(sub); - } -# endif - testassert(CXX::count == 2); -#endif - - testassert(class_getInstanceSize([Sub class]) == 6*sizeof(void*)); - - ivar = class_getInstanceVariable([Sub class], "subIvar"); - testassert(ivar); - testassert(2*sizeof(void*) == (size_t)ivar_getOffset(ivar)); - testassert(0 == strcmp(ivar_getName(ivar), "subIvar")); - // rdar://7466570 clang miscompiles assert(#if __LP64__ ... #endif) -#if __LP64__ - testassert(0 == strcmp(ivar_getTypeEncoding(ivar), "Q")); -#elif __clang__ - testassert(0 == strcmp(ivar_getTypeEncoding(ivar), "L")); -#else - testassert(0 == strcmp(ivar_getTypeEncoding(ivar), "I")); -#endif - -#ifdef __cplusplus - ivar = class_getInstanceVariable([Sub class], "cxx"); - testassert(ivar); -#endif - - ivar = class_getInstanceVariable([Super class], "superIvar"); - testassert(ivar); - testassert(sizeof(void*) == (size_t)ivar_getOffset(ivar)); - testassert(0 == strcmp(ivar_getName(ivar), "superIvar")); - testassert(0 == strcmp(ivar_getTypeEncoding(ivar), "c")); - - ivar = class_getInstanceVariable([Super class], "subIvar"); - testassert(!ivar); - - if (objc_collectingEnabled()) { - const uint8_t *superlayout; - const uint8_t *sublayout; - superlayout = class_getIvarLayout([Super class]); - sublayout = class_getIvarLayout([Sub class]); - testassert(0 == ustrcmp(superlayout, "\x01\x10")); - testassert(0 == ustrcmp(sublayout, "\x01\x21\x20")); - - superlayout = class_getWeakIvarLayout([Super class]); - sublayout = class_getWeakIvarLayout([Sub class]); - testassert(superlayout == NULL); - testassert(0 == ustrcmp(sublayout, "\x41\x10")); - } - - /* - Shrinking superclass. - Subclass ivars do not compact, but the GC layout needs to - update, including the gap that the superclass no longer spans. - - Compile-time layout of Sub2: - [0 scan] isa - [1-5 scan] superIvar - [6-10 weak] superIvar2 - [11 weak] subIvar - [12 scan] subIvar2 - - Runtime layout of Sub2: - [0 scan] isa - [1-10 skip] was superIvar - [11 weak] subIvar - [12 scan] subIvar2 - */ - - Sub2 *sub2 = [Sub2 new]; - sub2->subIvar = (void *)10; - testassert(((uintptr_t *)objc_unretainedPointer(sub2))[11] == 10); - - testassert(class_getInstanceSize([Sub2 class]) == 13*sizeof(void*)); - - ivar = class_getInstanceVariable([Sub2 class], "subIvar"); - testassert(ivar); - testassert(11*sizeof(void*) == (size_t)ivar_getOffset(ivar)); - testassert(0 == strcmp(ivar_getName(ivar), "subIvar")); - - ivar = class_getInstanceVariable([ShrinkingSuper class], "superIvar"); - testassert(!ivar); - - if (objc_collectingEnabled()) { - const uint8_t *superlayout; - const uint8_t *sublayout; - superlayout = class_getIvarLayout([ShrinkingSuper class]); - sublayout = class_getIvarLayout([Sub2 class]); - // only `isa` is left; superIvar[] and superIvar2[] are gone - testassert(superlayout == NULL || 0 == ustrcmp(superlayout, "\x01")); - testassert(0 == ustrcmp(sublayout, "\x01\xb1")); - - superlayout = class_getWeakIvarLayout([ShrinkingSuper class]); - sublayout = class_getWeakIvarLayout([Sub2 class]); - testassert(superlayout == NULL); - testassert(0 == ustrcmp(sublayout, "\xb1\x10")); - } - - /* - Ivars slide but GC layouts stay the same - Here, the last word of the superclass is misaligned, but - its GC layout includes a bit for that whole word. - Additionally, all of the subclass ivars fit into that word too, - both before and after sliding. - The runtime will try to slide the GC layout and must not be - confused (rdar://6851700). Note that the second skip-word may or may - not actually be included, because it crosses the end of the object. - - - Compile-time layout of NoGCChangeSub: - [0 scan] isa - [1 skip] d - [2 skip] superc1, subc3 - - Runtime layout of NoGCChangeSub: - [0 scan] isa - [1 skip] d - [2 skip] superc1, superc2, subc3 - */ - if (objc_collectingEnabled()) { - Ivar ivar1 = class_getInstanceVariable([NoGCChangeSub class], "superc1"); - testassert(ivar1); - Ivar ivar2 = class_getInstanceVariable([NoGCChangeSub class], "superc2"); - testassert(ivar2); - Ivar ivar3 = class_getInstanceVariable([NoGCChangeSub class], "subc3"); - testassert(ivar3); - testassert(ivar_getOffset(ivar1) != ivar_getOffset(ivar2) && - ivar_getOffset(ivar1) != ivar_getOffset(ivar3) && - ivar_getOffset(ivar2) != ivar_getOffset(ivar3)); - } - - /* Ivar layout includes runs of 15 words. - rdar://6859875 this would generate a truncated GC layout. - */ - if (objc_collectingEnabled()) { - const uint8_t *layout = - class_getIvarLayout(objc_getClass("RunsOf15Sub")); - testassert(layout); - int totalSkip = 0; - int totalScan = 0; - // should find 30+ each of skip and scan - uint8_t c; - while ((c = *layout++)) { - totalSkip += c>>4; - totalScan += c&0xf; - } - testassert(totalSkip >= 30); - testassert(totalScan >= 30); - } - -// __OBJC2__ -#endif - - - /* - Non-strong -> strong - Classes do not change size, but GC layouts must be updated. - Both new and old ABI detect this case (rdar://5774578) - - Compile-time layout of MoreStrongSub: - [0 scan] isa - [1 skip] superIvar - [2 scan] subIvar - - Runtime layout of MoreStrongSub: - [0 scan] isa - [1 scan] superIvar - [2 scan] subIvar - */ - testassert(class_getInstanceSize([MoreStrongSub class]) == 3*sizeof(void*)); - if (objc_collectingEnabled()) { - const uint8_t *layout; - layout = class_getIvarLayout([MoreStrongSub class]); - testassert(layout == NULL); - - layout = class_getWeakIvarLayout([MoreStrongSub class]); - testassert(layout == NULL); - } - - - /* - Strong -> weak - Classes do not change size, but GC layouts must be updated. - Old ABI intentionally does not detect this case (rdar://5774578) - - Compile-time layout of MoreWeakSub: - [0 scan] isa - [1 scan] superIvar - [2 scan] subIvar - - Runtime layout of MoreWeakSub: - [0 scan] isa - [1 weak] superIvar - [2 scan] subIvar - */ - testassert(class_getInstanceSize([MoreWeakSub class]) == 3*sizeof(void*)); - if (objc_collectingEnabled()) { - const uint8_t *layout; - layout = class_getIvarLayout([MoreWeakSub class]); -#if __OBJC2__ - // fixed version: scan / weak / scan - testassert(0 == ustrcmp(layout, "\x01\x11")); -#else - // unfixed version: scan / scan / scan - testassert(layout == NULL || 0 == ustrcmp(layout, "\x03")); -#endif - - layout = class_getWeakIvarLayout([MoreWeakSub class]); -#if __OBJC2__ - testassert(0 == ustrcmp(layout, "\x11\x10")); -#else - testassert(layout == NULL); -#endif - } - - - /* - Non-strong -> weak - Classes do not change size, but GC layouts must be updated. - Old ABI intentionally does not detect this case (rdar://5774578) - - Compile-time layout of MoreWeak2Sub: - [0 scan] isa - [1 skip] superIvar - [2 scan] subIvar - - Runtime layout of MoreWeak2Sub: - [0 scan] isa - [1 weak] superIvar - [2 scan] subIvar - */ - testassert(class_getInstanceSize([MoreWeak2Sub class]) == 3*sizeof(void*)); - if (objc_collectingEnabled()) { - const uint8_t *layout; - layout = class_getIvarLayout([MoreWeak2Sub class]); - testassert(0 == ustrcmp(layout, "\x01\x11") || - 0 == ustrcmp(layout, "\x01\x10\x01")); - - layout = class_getWeakIvarLayout([MoreWeak2Sub class]); -#if __OBJC2__ - testassert(0 == ustrcmp(layout, "\x11\x10")); -#else - testassert(layout == NULL); -#endif - } - - - /* - Strong -> non-strong - Classes do not change size, but GC layouts must be updated. - Old ABI intentionally does not detect this case (rdar://5774578) - - Compile-time layout of LessStrongSub: - [0 scan] isa - [1 scan] superIvar - [2 scan] subIvar - - Runtime layout of LessStrongSub: - [0 scan] isa - [1 skip] superIvar - [2 scan] subIvar - */ - testassert(class_getInstanceSize([LessStrongSub class]) == 3*sizeof(void*)); - if (objc_collectingEnabled()) { - const uint8_t *layout; - layout = class_getIvarLayout([LessStrongSub class]); -#if __OBJC2__ - // fixed version: scan / skip / scan - testassert(0 == ustrcmp(layout, "\x01\x11")); -#else - // unfixed version: scan / scan / scan - testassert(layout == NULL || 0 == ustrcmp(layout, "\x03")); -#endif - - layout = class_getWeakIvarLayout([LessStrongSub class]); - testassert(layout == NULL); - } - - - /* - Weak -> strong - Classes do not change size, but GC layouts must be updated. - Both new and old ABI detect this case (rdar://5774578 rdar://6924114) - - Compile-time layout of LessWeakSub: - [0 scan] isa - [1 weak] superIvar - [2 scan] subIvar - - Runtime layout of LessWeakSub: - [0 scan] isa - [1 scan] superIvar - [2 scan] subIvar - */ - testassert(class_getInstanceSize([LessWeakSub class]) == 3*sizeof(void*)); - if (objc_collectingEnabled()) { - const uint8_t *layout; - layout = class_getIvarLayout([LessWeakSub class]); - testassert(layout == NULL); - - layout = class_getWeakIvarLayout([LessWeakSub class]); - testassert(layout == NULL); - } - - - /* - Weak -> non-strong - Classes do not change size, but GC layouts must be updated. - Old ABI intentionally does not detect this case (rdar://5774578) - - Compile-time layout of LessWeak2Sub: - [0 scan] isa - [1 weak] superIvar - [2 scan] subIvar - - Runtime layout of LessWeak2Sub: - [0 scan] isa - [1 skip] superIvar - [2 scan] subIvar - */ - testassert(class_getInstanceSize([LessWeak2Sub class]) == 3*sizeof(void*)); - if (objc_collectingEnabled()) { - const uint8_t *layout; - layout = class_getIvarLayout([LessWeak2Sub class]); - testassert(0 == ustrcmp(layout, "\x01\x11") || - 0 == ustrcmp(layout, "\x01\x10\x01")); - - layout = class_getWeakIvarLayout([LessWeak2Sub class]); -#if __OBJC2__ - testassert(layout == NULL); -#else - testassert(0 == ustrcmp(layout, "\x11\x10")); -#endif - } - - - succeed(basename(argv[0])); - return 0; -} diff --git a/objc/objc-runtime/test/ivarSlide1.m b/objc/objc-runtime/test/ivarSlide1.m deleted file mode 100644 index 47b2e63..0000000 --- a/objc/objc-runtime/test/ivarSlide1.m +++ /dev/null @@ -1,21 +0,0 @@ -#include "test.h" -#include <stdint.h> -#include <objc/runtime.h> - -#define OLD 0 -#include "ivarSlide.h" - -#include "testroot.i" - -@implementation Super @end - -@implementation ShrinkingSuper @end - -@implementation MoreStrongSuper @end -@implementation LessStrongSuper @end -@implementation MoreWeakSuper @end -@implementation MoreWeak2Super @end -@implementation LessWeakSuper @end -@implementation LessWeak2Super @end -@implementation NoGCChangeSuper @end -@implementation RunsOf15 @end diff --git a/objc/objc-runtime/test/layout.m b/objc/objc-runtime/test/layout.m deleted file mode 100644 index 6c220fb..0000000 --- a/objc/objc-runtime/test/layout.m +++ /dev/null @@ -1,97 +0,0 @@ -// TEST_CONFIG MEM=gc OS=macosx - -#include "test.h" -#include <string.h> -#include <objc/objc-runtime.h> - -@class NSObject; - -void printlayout(const char *name, const uint8_t *layout) -{ - testprintf("%s: ", name); - - if (!layout) { - testprintf("NULL\n"); - return; - } - - const uint8_t *c; - for (c = layout; *c; c++) { - testprintf("%02x ", *c); - } - - testprintf("00\n"); -} - -OBJC_ROOT_CLASS -@interface Super { id isa; } @end -@implementation Super @end - - -// strong: 0c 00 (0a00 without structs) -// weak: NULL -@interface AllScanned : Super { - id id1; - NSObject *o1; - __strong void *v1; - __strong intptr_t *i1; - __strong long *l1; - /* fixme - struct { - id id1; - id id2; - } str; - */ - id arr1[4]; -} -@end -@implementation AllScanned @end - -// strong: 00 -// weak: 1b 00 (18 00 without structs) -@interface AllWeak : Super { - __weak id id1; - __weak NSObject *o1; - __weak void *v1; - __weak intptr_t *i1; - __weak long *l1; - /* fixme - struct { - __weak id id1; - __weak id id2; - } str; - */ - __weak id arr1[4]; -} -@end -@implementation AllWeak @end - -// strong: "" -// weak: NULL -OBJC_ROOT_CLASS -@interface NoScanned { long i; } @end -@implementation NoScanned @end - -int main() -{ - const uint8_t *layout; - - layout = class_getIvarLayout(objc_getClass("AllScanned")); - printlayout("AllScanned", layout); - layout = class_getWeakIvarLayout(objc_getClass("AllScanned")); - printlayout("AllScanned weak", layout); - // testassert(0 == strcmp(layout, "\x0a")); - - layout = class_getIvarLayout(objc_getClass("AllWeak")); - printlayout("AllWeak", layout); - layout = class_getWeakIvarLayout(objc_getClass("AllWeak")); - printlayout("AllWeak weak", layout); - // testassert(0 == strcmp(layout, "")); - - layout = class_getIvarLayout(objc_getClass("NoScanned")); - printlayout("NoScanned", layout); - // testassert(0 == strcmp(layout, "")); - - succeed(__FILE__); - return 0; -} diff --git a/objc/objc-runtime/test/literals.m b/objc/objc-runtime/test/literals.m deleted file mode 100644 index 17fffd2..0000000 --- a/objc/objc-runtime/test/literals.m +++ /dev/null @@ -1,56 +0,0 @@ -// TEST_CONFIG MEM=arc,mrc CC=clang LANGUAGE=objc,objc++ -// TEST_CFLAGS -framework Foundation - -#import <Foundation/Foundation.h> -#import <Foundation/NSDictionary.h> -#import <objc/runtime.h> -#import <objc/objc-abi.h> -#import <math.h> -#include "test.h" - -int main() { - PUSH_POOL { - -#if __has_feature(objc_bool) // placeholder until we get a more precise macro. - NSArray *array = @[ @1, @2, @YES, @NO, @"Hello", @"World" ]; - testassert([array count] == 6); - NSDictionary *dict = @{ @"Name" : @"John Q. Public", @"Age" : @42 }; - testassert([dict count] == 2); - NSDictionary *numbers = @{ @"π" : @M_PI, @"e" : @M_E }; - testassert([[numbers objectForKey:@"π"] doubleValue] == M_PI); - testassert([[numbers objectForKey:@"e"] doubleValue] == M_E); - - BOOL yesBool = YES; - BOOL noBool = NO; - array = @[ - @(true), - @(YES), - [NSNumber numberWithBool:YES], - @YES, - @(yesBool), - @((BOOL)YES), - - @(false), - @(NO), - [NSNumber numberWithBool:NO], - @NO, - @(noBool), - @((BOOL)NO), - ]; - NSData * jsonData = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil]; - NSString * string = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; -#if __cplusplus - testassert([string isEqualToString:@"[true,true,true,true,true,true,false,false,false,false,false,false]"]); -#else - // C99 @(true) and @(false) evaluate to @(1) and @(0). - testassert([string isEqualToString:@"[1,true,true,true,true,true,0,false,false,false,false,false]"]); -#endif - -#endif - - } POP_POOL; - - succeed(__FILE__); - - return 0; -} diff --git a/objc/objc-runtime/test/load-noobjc.m b/objc/objc-runtime/test/load-noobjc.m deleted file mode 100644 index e877e17..0000000 --- a/objc/objc-runtime/test/load-noobjc.m +++ /dev/null @@ -1,52 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/load-noobjc.m -o load-noobjc.out - $C{COMPILE} $DIR/load-noobjc2.m -o libload-noobjc2.dylib -bundle -bundle_loader load-noobjc.out - $C{COMPILE} $DIR/load-noobjc3.m -o libload-noobjc3.dylib -bundle -bundle_loader load-noobjc.out -END -*/ - -#include "test.h" - -#if !__OBJC2__ -// old runtime can't fix this deadlock - -int main() -{ - succeed(__FILE__); -} - -#else - -#include <dlfcn.h> - -int state = 0; -semaphore_t go; - -void *thread(void *arg __unused) -{ - objc_registerThreadWithCollector(); - dlopen("libload-noobjc2.dylib", RTLD_LAZY); - fail("dlopen should not have returned"); -} - -int main() -{ - semaphore_create(mach_task_self(), &go, SYNC_POLICY_FIFO, 0); - - pthread_t th; - pthread_create(&th, nil, &thread, nil); - - // Wait for thread to stop in libload-noobjc2's +load method. - semaphore_wait(go); - - // run nooobjc3's constructor function. - // There's no objc code here so it shouldn't require the +load lock. - void *dlh = dlopen("libload-noobjc3.dylib", RTLD_LAZY); - testassert(dlh); - testassert(state == 1); - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/load-noobjc2.m b/objc/objc-runtime/test/load-noobjc2.m deleted file mode 100644 index e8cf37d..0000000 --- a/objc/objc-runtime/test/load-noobjc2.m +++ /dev/null @@ -1,16 +0,0 @@ -#include "test.h" -#if __OBJC2__ - -extern semaphore_t go; - -OBJC_ROOT_CLASS -@interface noobjc @end -@implementation noobjc -+(void)load -{ - semaphore_signal(go); - while (1) sleep(1); -} -@end - -#endif diff --git a/objc/objc-runtime/test/load-noobjc3.m b/objc/objc-runtime/test/load-noobjc3.m deleted file mode 100644 index fc7cdb6..0000000 --- a/objc/objc-runtime/test/load-noobjc3.m +++ /dev/null @@ -1,13 +0,0 @@ -#include "test.h" - -#if __OBJC2__ - -extern int state; - -__attribute__((constructor)) -static void ctor(void) -{ - state = 1; -} - -#endif diff --git a/objc/objc-runtime/test/load-order.m b/objc/objc-runtime/test/load-order.m deleted file mode 100644 index fd09370..0000000 --- a/objc/objc-runtime/test/load-order.m +++ /dev/null @@ -1,18 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/load-order3.m -o load-order3.dylib -dynamiclib - $C{COMPILE} $DIR/load-order2.m -o load-order2.dylib -x none load-order3.dylib -dynamiclib - $C{COMPILE} $DIR/load-order1.m -o load-order1.dylib -x none load-order3.dylib load-order2.dylib -dynamiclib - $C{COMPILE} $DIR/load-order.m -o load-order.out -x none load-order3.dylib load-order2.dylib load-order1.dylib -END -*/ - -#include "test.h" - -extern int state1, state2, state3; - -int main() -{ - testassert(state1 == 1 && state2 == 2 && state3 == 3); - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/load-order1.m b/objc/objc-runtime/test/load-order1.m deleted file mode 100644 index cdfa075..0000000 --- a/objc/objc-runtime/test/load-order1.m +++ /dev/null @@ -1,15 +0,0 @@ -#include "test.h" - -extern int state2, state3; - -int state1 = 0; - -OBJC_ROOT_CLASS -@interface One @end -@implementation One -+(void)load -{ - testassert(state2 == 2 && state3 == 3); - state1 = 1; -} -@end diff --git a/objc/objc-runtime/test/load-order2.m b/objc/objc-runtime/test/load-order2.m deleted file mode 100644 index 7537754..0000000 --- a/objc/objc-runtime/test/load-order2.m +++ /dev/null @@ -1,15 +0,0 @@ -#include "test.h" - -extern int state3; - -int state2 = 0; - -OBJC_ROOT_CLASS -@interface Two @end -@implementation Two -+(void)load -{ - testassert(state3 == 3); - state2 = 2; -} -@end diff --git a/objc/objc-runtime/test/load-order3.m b/objc/objc-runtime/test/load-order3.m deleted file mode 100644 index 7c34d5a..0000000 --- a/objc/objc-runtime/test/load-order3.m +++ /dev/null @@ -1,12 +0,0 @@ -#include "test.h" - -int state3 = 0; - -OBJC_ROOT_CLASS -@interface Three @end -@implementation Three -+(void)load -{ - state3 = 3; -} -@end diff --git a/objc/objc-runtime/test/load-parallel.m b/objc/objc-runtime/test/load-parallel.m deleted file mode 100644 index f050ea5..0000000 --- a/objc/objc-runtime/test/load-parallel.m +++ /dev/null @@ -1,65 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/load-parallel00.m -o load-parallel00.dylib -dynamiclib - $C{COMPILE} $DIR/load-parallel.m -x none load-parallel00.dylib -o load-parallel.out -DCOUNT=10 - - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel0.dylib -dynamiclib -DN=0 - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel1.dylib -dynamiclib -DN=1 - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel2.dylib -dynamiclib -DN=2 - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel3.dylib -dynamiclib -DN=3 - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel4.dylib -dynamiclib -DN=4 - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel5.dylib -dynamiclib -DN=5 - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel6.dylib -dynamiclib -DN=6 - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel7.dylib -dynamiclib -DN=7 - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel8.dylib -dynamiclib -DN=8 - $C{COMPILE} $DIR/load-parallel0.m -x none load-parallel00.dylib -o load-parallel9.dylib -dynamiclib -DN=9 -END -*/ - -#include "test.h" - -#include <dlfcn.h> -#include <pthread.h> - -#ifndef COUNT -#error -DCOUNT=c missing -#endif - -extern int state; - -void *thread(void *arg) -{ - uintptr_t num = (uintptr_t)arg; - char *buf; - - objc_registerThreadWithCollector(); - - asprintf(&buf, "load-parallel%lu.dylib", (unsigned long)num); - testprintf("%s\n", buf); - void *dlh = dlopen(buf, RTLD_LAZY); - if (!dlh) { - fail("dlopen failed: %s", dlerror()); - } - free(buf); - - return NULL; -} - -int main() -{ - pthread_t t[COUNT]; - uintptr_t i; - - for (i = 0; i < COUNT; i++) { - pthread_create(&t[i], NULL, thread, (void *)i); - } - - for (i = 0; i < COUNT; i++) { - pthread_join(t[i], NULL); - } - - testprintf("loaded %d/%d\n", state, COUNT*26); - testassert(state == COUNT*26); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/load-parallel0.m b/objc/objc-runtime/test/load-parallel0.m deleted file mode 100644 index 9f3a3e1..0000000 --- a/objc/objc-runtime/test/load-parallel0.m +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef N -#error -DN=n missing -#endif - -#import <objc/objc-api.h> -#include <stdio.h> -#include <sched.h> -#include <unistd.h> -#include <libkern/OSAtomic.h> -extern int state; - -#define CLASS0(n,nn) \ - OBJC_ROOT_CLASS \ - @interface C_##n##_##nn @end \ - @implementation C_##n##_##nn \ - +(void)load { OSAtomicIncrement32(&state); usleep(10); } \ - @end - -#define CLASS(n,nn) CLASS0(n,nn) - -CLASS(a,N) -CLASS(b,N) -CLASS(c,N) -CLASS(d,N) -CLASS(e,N) -CLASS(f,N) -CLASS(g,N) -CLASS(h,N) -CLASS(i,N) -CLASS(j,N) -CLASS(k,N) -CLASS(l,N) -CLASS(m,N) -CLASS(n,N) -CLASS(o,N) -CLASS(p,N) -CLASS(q,N) -CLASS(r,N) -CLASS(s,N) -CLASS(t,N) -CLASS(u,N) -CLASS(v,N) -CLASS(w,N) -CLASS(x,N) -CLASS(y,N) -CLASS(z,N) diff --git a/objc/objc-runtime/test/load-parallel00.m b/objc/objc-runtime/test/load-parallel00.m deleted file mode 100644 index 4bef2b6..0000000 --- a/objc/objc-runtime/test/load-parallel00.m +++ /dev/null @@ -1 +0,0 @@ -int state = 0; diff --git a/objc/objc-runtime/test/load-reentrant.m b/objc/objc-runtime/test/load-reentrant.m deleted file mode 100644 index 25caf77..0000000 --- a/objc/objc-runtime/test/load-reentrant.m +++ /dev/null @@ -1,36 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/load-reentrant.m -o load-reentrant.out - $C{COMPILE} $DIR/load-reentrant2.m -o libload-reentrant2.dylib -bundle -bundle_loader load-reentrant.out -END -*/ - -#include "test.h" -#include <dlfcn.h> - -int state1 = 0; -int *state2_p; - -OBJC_ROOT_CLASS -@interface One @end -@implementation One -+(void)load -{ - state1 = 111; - - // Re-entrant +load doesn't get to complete until we do - void *dlh = dlopen("libload-reentrant2.dylib", RTLD_LAZY); - testassert(dlh); - state2_p = (int *)dlsym(dlh, "state2"); - testassert(state2_p); - testassert(*state2_p == 0); - - state1 = 1; -} -@end - -int main() -{ - testassert(state1 == 1 && state2_p && *state2_p == 2); - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/load-reentrant2.m b/objc/objc-runtime/test/load-reentrant2.m deleted file mode 100644 index 0cc6a40..0000000 --- a/objc/objc-runtime/test/load-reentrant2.m +++ /dev/null @@ -1,23 +0,0 @@ -#include "test.h" - -int state2 = 0; -extern int state1; - -static void ctor(void) __attribute__((constructor)); -static void ctor(void) -{ - // should be called during One's dlopen(), before Two's +load - testassert(state1 == 111); - testassert(state2 == 0); -} - -OBJC_ROOT_CLASS -@interface Two @end -@implementation Two -+(void) load -{ - // Does not run until One's +load completes - testassert(state1 == 1); - state2 = 2; -} -@end diff --git a/objc/objc-runtime/test/load.m b/objc/objc-runtime/test/load.m deleted file mode 100644 index 92bcdfe..0000000 --- a/objc/objc-runtime/test/load.m +++ /dev/null @@ -1,106 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" - -int state = 0; -int catstate = 0; -int deallocstate = 0; - -@interface Deallocator : TestRoot @end -@implementation Deallocator --(id)init { - self = [super init]; - if (objc_collectingEnabled()) { - deallocstate = 1; - } - return self; -} --(void)dealloc { - deallocstate = 1; - SUPER_DEALLOC(); -} -@end - - -@interface Super : TestRoot @end -@implementation Super -+(void)initialize { - if (self == [Super class]) { - testprintf("in +[Super initialize]\n"); - testassert(state == 2); - state = 3; - } else { - testprintf("in +[Super initialize] on behalf of Sub\n"); - testassert(state == 3); - state = 4; - } -} --(void)load { fail("-[Super load] called!"); } -+(void)load { - testprintf("in +[Super load]\n"); - testassert(state == 0); - state = 1; -} -@end - -@interface Sub : Super { } @end -@implementation Sub -+(void)load { - testprintf("in +[Sub load]\n"); - testassert(state == 1); - state = 2; -} --(void)load { fail("-[Sub load] called!"); } -@end - -@interface SubNoLoad : Super { } @end -@implementation SubNoLoad @end - -@interface Super (Category) @end -@implementation Super (Category) --(void)load { fail("-[Super(Category) load called!"); } -+(void)load { - testprintf("in +[Super(Category) load]\n"); - testassert(state >= 1); - catstate++; -} -@end - - -@interface Sub (Category) @end -@implementation Sub (Category) --(void)load { fail("-[Sub(Category) load called!"); } -+(void)load { - testprintf("in +[Sub(Category) load]\n"); - testassert(state >= 2); - catstate++; - - // test autorelease pool - __autoreleasing id x; - x = AUTORELEASE([Deallocator new]); -} -@end - - -@interface SubNoLoad (Category) @end -@implementation SubNoLoad (Category) --(void)load { fail("-[SubNoLoad(Category) load called!"); } -+(void)load { - testprintf("in +[SubNoLoad(Category) load]\n"); - testassert(state >= 1); - catstate++; -} -@end - -int main() -{ - testassert(state == 2); - testassert(catstate == 3); - testassert(deallocstate == 1); - [Sub class]; - testassert(state == 4); - testassert(catstate == 3); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/methodArgs.m b/objc/objc-runtime/test/methodArgs.m deleted file mode 100644 index 8948e9a..0000000 --- a/objc/objc-runtime/test/methodArgs.m +++ /dev/null @@ -1,166 +0,0 @@ -// TEST_CFLAGS -Wno-deprecated-declarations - -#include "test.h" -#include "testroot.i" -#include <string.h> -#include <objc/objc-runtime.h> - -@interface Super : TestRoot @end -@implementation Super -+(id)method:(int)__unused arg :(void(^)(void)) __unused arg2 { - return 0; -} -@end - - -int main() -{ - char buf[128]; - char *arg; - struct objc_method_description *desc; - Method m = class_getClassMethod([Super class], sel_registerName("method::")); - testassert(m); - - testassert(method_getNumberOfArguments(m) == 4); -#if !__OBJC2__ - testassert(method_getSizeOfArguments(m) == 16); -#endif - - arg = method_copyArgumentType(m, 0); - testassert(arg); - testassert(0 == strcmp(arg, "@")); - memset(buf, 1, 128); - method_getArgumentType(m, 0, buf, 1+strlen(arg)); - testassert(0 == strcmp(arg, buf)); - testassert(buf[1+strlen(arg)] == 1); - memset(buf, 1, 128); - method_getArgumentType(m, 0, buf, 2); - testassert(0 == strncmp(arg, buf, 2)); - testassert(buf[2] == 1); - free(arg); - - arg = method_copyArgumentType(m, 1); - testassert(arg); - testassert(0 == strcmp(arg, ":")); - memset(buf, 1, 128); - method_getArgumentType(m, 1, buf, 1+strlen(arg)); - testassert(0 == strcmp(arg, buf)); - testassert(buf[1+strlen(arg)] == 1); - memset(buf, 1, 128); - method_getArgumentType(m, 1, buf, 2); - testassert(0 == strncmp(arg, buf, 2)); - testassert(buf[2] == 1); - free(arg); - - arg = method_copyArgumentType(m, 2); - testassert(arg); - testassert(0 == strcmp(arg, "i")); - memset(buf, 1, 128); - method_getArgumentType(m, 2, buf, 1+strlen(arg)); - testassert(0 == strcmp(arg, buf)); - testassert(buf[1+strlen(arg)] == 1); - memset(buf, 1, 128); - method_getArgumentType(m, 2, buf, 2); - testassert(0 == strncmp(arg, buf, 2)); - testassert(buf[2] == 1); - free(arg); - - arg = method_copyArgumentType(m, 3); - testassert(arg); - testassert(0 == strcmp(arg, "@?")); - memset(buf, 1, 128); - method_getArgumentType(m, 3, buf, 1+strlen(arg)); - testassert(0 == strcmp(arg, buf)); - testassert(buf[1+strlen(arg)] == 1); - memset(buf, 1, 128); - method_getArgumentType(m, 3, buf, 2); - testassert(0 == strncmp(arg, buf, 2)); - testassert(buf[2] == 1); - memset(buf, 1, 128); - method_getArgumentType(m, 3, buf, 3); - testassert(0 == strncmp(arg, buf, 3)); - testassert(buf[3] == 1); - free(arg); - - arg = method_copyArgumentType(m, 4); - testassert(!arg); - - arg = method_copyArgumentType(m, -1); - testassert(!arg); - - memset(buf, 1, 128); - method_getArgumentType(m, 4, buf, 127); - testassert(buf[0] == 0); - testassert(buf[1] == 0); - testassert(buf[127] == 1); - - memset(buf, 1, 128); - method_getArgumentType(m, -1, buf, 127); - testassert(buf[0] == 0); - testassert(buf[1] == 0); - testassert(buf[127] == 1); - - arg = method_copyReturnType(m); - testassert(arg); - testassert(0 == strcmp(arg, "@")); - memset(buf, 1, 128); - method_getReturnType(m, buf, 1+strlen(arg)); - testassert(0 == strcmp(arg, buf)); - testassert(buf[1+strlen(arg)] == 1); - memset(buf, 1, 128); - method_getReturnType(m, buf, 2); - testassert(0 == strncmp(arg, buf, 2)); - testassert(buf[2] == 1); - free(arg); - - desc = method_getDescription(m); - testassert(desc); - testassert(desc->name == sel_registerName("method::")); -#if __LP64__ - testassert(0 == strcmp(desc->types, "@28@0:8i16@?20")); -#else - testassert(0 == strcmp(desc->types, "@16@0:4i8@?12")); -#endif - - testassert(0 == method_getNumberOfArguments(NULL)); -#if !__OBJC2__ - testassert(0 == method_getSizeOfArguments(NULL)); -#endif - testassert(NULL == method_copyArgumentType(NULL, 10)); - testassert(NULL == method_copyReturnType(NULL)); - testassert(NULL == method_getDescription(NULL)); - - memset(buf, 1, 128); - method_getArgumentType(NULL, 1, buf, 127); - testassert(buf[0] == 0); - testassert(buf[1] == 0); - testassert(buf[127] == 1); - - memset(buf, 1, 128); - method_getArgumentType(NULL, 1, buf, 0); - testassert(buf[0] == 1); - testassert(buf[1] == 1); - - method_getArgumentType(m, 1, NULL, 128); - method_getArgumentType(m, 1, NULL, 0); - method_getArgumentType(NULL, 1, NULL, 128); - method_getArgumentType(NULL, 1, NULL, 0); - - memset(buf, 1, 128); - method_getReturnType(NULL, buf, 127); - testassert(buf[0] == 0); - testassert(buf[1] == 0); - testassert(buf[127] == 1); - - memset(buf, 1, 128); - method_getReturnType(NULL, buf, 0); - testassert(buf[0] == 1); - testassert(buf[1] == 1); - - method_getReturnType(m, NULL, 128); - method_getReturnType(m, NULL, 0); - method_getReturnType(NULL, NULL, 128); - method_getReturnType(NULL, NULL, 0); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/methodListSize.m b/objc/objc-runtime/test/methodListSize.m deleted file mode 100644 index 3821844..0000000 --- a/objc/objc-runtime/test/methodListSize.m +++ /dev/null @@ -1,56 +0,0 @@ -// TEST_CONFIG -// rdar://8052003 rdar://8077031 - -#include "test.h" - -#include <malloc/malloc.h> -#include <objc/runtime.h> - -// add SELCOUNT methods to each of CLASSCOUNT classes -#define CLASSCOUNT 100 -#define SELCOUNT 200 - -int main() -{ - int i, j; - malloc_statistics_t start, end; - - Class root; - root = objc_allocateClassPair(NULL, "Root", 0); - objc_registerClassPair(root); - - Class classes[CLASSCOUNT]; - for (i = 0; i < CLASSCOUNT; i++) { - char *classname; - asprintf(&classname, "GrP_class_%d", i); - classes[i] = objc_allocateClassPair(root, classname, 0); - objc_registerClassPair(classes[i]); - free(classname); - } - - SEL selectors[SELCOUNT]; - for (i = 0; i < SELCOUNT; i++) { - char *selname; - asprintf(&selname, "GrP_sel_%d", i); - selectors[i] = sel_registerName(selname); - free(selname); - } - - malloc_zone_statistics(NULL, &start); - - for (i = 0; i < CLASSCOUNT; i++) { - for (j = 0; j < SELCOUNT; j++) { - class_addMethod(classes[i], selectors[j], (IMP)main, ""); - } - } - - malloc_zone_statistics(NULL, &end); - - // expected: 3-word method struct plus two other words - ssize_t expected = (sizeof(void*) * (3+2)) * SELCOUNT * CLASSCOUNT; - ssize_t actual = end.size_in_use - start.size_in_use; - testassert(actual < expected * 3); // allow generous fudge factor - - succeed(__FILE__); -} - diff --git a/objc/objc-runtime/test/method_getName.m b/objc/objc-runtime/test/method_getName.m deleted file mode 100644 index f3f7413..0000000 --- a/objc/objc-runtime/test/method_getName.m +++ /dev/null @@ -1,27 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include <Foundation/NSObject.h> -#include <objc/runtime.h> - -#undef SUPPORT_NONPOINTER_ISA // remove test.h's definition -#include "../runtime/objc-config.h" - -int main() { - unsigned i; - Class c = [NSObject class]; - unsigned numMethods; - Method *methods = class_copyMethodList(c, &numMethods); - - for (i=0; i<numMethods; ++i) { - // <rdar://problem/6190950> method_getName crash on NSObject method when GC is enabled - SEL aMethod; - aMethod = method_getName(methods[i]); -#if defined(kIgnore) - if (aMethod == (SEL)kIgnore) - fail(__FILE__); -#endif - } - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/msgSend.m b/objc/objc-runtime/test/msgSend.m deleted file mode 100644 index bd3e9b1..0000000 --- a/objc/objc-runtime/test/msgSend.m +++ /dev/null @@ -1,2278 +0,0 @@ -// TEST_CFLAGS -Wno-unused-parameter -Wundeclared-selector - -#include "test.h" -#include "testroot.i" - -#if __cplusplus && !__clang__ - -int main() -{ - // llvm-g++ is confused by @selector(foo::) and will never be fixed - succeed(__FILE__); -} - -#else - -#include <objc/objc.h> -#include <objc/runtime.h> -#include <objc/objc-internal.h> -#include <objc/objc-abi.h> -#include <simd/simd.h> - -// rdar://21694990 simd.h should have a vector_equal(a, b) function -static bool vector_equal(vector_ulong2 lhs, vector_ulong2 rhs) { - return vector_all(lhs == rhs); -} - -#if __arm64__ - // no stret dispatchers -# define SUPPORT_STRET 0 -# define objc_msgSend_stret objc_msgSend -# define objc_msgSendSuper2_stret objc_msgSendSuper2 -# define objc_msgSend_stret_debug objc_msgSend_debug -# define objc_msgSendSuper2_stret_debug objc_msgSendSuper2_debug -# define method_invoke_stret method_invoke -#else -# define SUPPORT_STRET 1 -#endif - - -#if defined(__arm__) -// rdar://8331406 -# define ALIGN_() -#else -# define ALIGN_() asm(".align 4"); -#endif - -@interface Super : TestRoot @end - -@interface Sub : Super @end - -static int state = 0; - -static id SELF; - -// for typeof() shorthand only -id (*idmsg0)(id, SEL) __attribute__((unused)); -long long (*llmsg0)(id, SEL) __attribute__((unused)); -// struct stret (*stretmsg0)(id, SEL) __attribute__((unused)); -double (*fpmsg0)(id, SEL) __attribute__((unused)); -long double (*lfpmsg0)(id, SEL) __attribute__((unused)); -vector_ulong2 (*vecmsg0)(id, SEL) __attribute__((unused)); - -#define VEC1 ((vector_ulong2){1, 1}) -#define VEC2 ((vector_ulong2){2, 2}) -#define VEC3 ((vector_ulong2){3, 3}) -#define VEC4 ((vector_ulong2){4, 4}) -#define VEC5 ((vector_ulong2){5, 5}) -#define VEC6 ((vector_ulong2){6, 6}) -#define VEC7 ((vector_ulong2){7, 7}) -#define VEC8 ((vector_ulong2){8, 8}) - -#define CHECK_ARGS(sel) \ -do { \ - testassert(self == SELF); \ - testassert(_cmd == sel_registerName(#sel "::::::::::::::::::::::::::::::::::::"));\ - testassert(vector_all(v1 == 1)); \ - testassert(vector_all(v2 == 2)); \ - testassert(vector_all(v3 == 3)); \ - testassert(vector_all(v4 == 4)); \ - testassert(vector_all(v5 == 5)); \ - testassert(vector_all(v6 == 6)); \ - testassert(vector_all(v7 == 7)); \ - testassert(vector_all(v8 == 8)); \ - testassert(i1 == 1); \ - testassert(i2 == 2); \ - testassert(i3 == 3); \ - testassert(i4 == 4); \ - testassert(i5 == 5); \ - testassert(i6 == 6); \ - testassert(i7 == 7); \ - testassert(i8 == 8); \ - testassert(i9 == 9); \ - testassert(i10 == 10); \ - testassert(i11 == 11); \ - testassert(i12 == 12); \ - testassert(i13 == 13); \ - testassert(f1 == 1.0); \ - testassert(f2 == 2.0); \ - testassert(f3 == 3.0); \ - testassert(f4 == 4.0); \ - testassert(f5 == 5.0); \ - testassert(f6 == 6.0); \ - testassert(f7 == 7.0); \ - testassert(f8 == 8.0); \ - testassert(f9 == 9.0); \ - testassert(f10 == 10.0); \ - testassert(f11 == 11.0); \ - testassert(f12 == 12.0); \ - testassert(f13 == 13.0); \ - testassert(f14 == 14.0); \ - testassert(f15 == 15.0); \ -} while (0) - -#define CHECK_ARGS_NOARG(sel) \ -do { \ - testassert(self == SELF); \ - testassert(_cmd == sel_registerName(#sel "_noarg"));\ -} while (0) - -id NIL_RECEIVER; -id ID_RESULT; -long long LL_RESULT = __LONG_LONG_MAX__ - 2LL*__INT_MAX__; -double FP_RESULT = __DBL_MIN__ + __DBL_EPSILON__; -long double LFP_RESULT = __LDBL_MIN__ + __LDBL_EPSILON__; -vector_ulong2 VEC_RESULT = { 0x1234567890abcdefULL, 0xfedcba0987654321ULL }; -// STRET_RESULT in test.h - -static struct stret zero; - -struct stret_i1 { - uintptr_t i1; -}; -struct stret_i2 { - uintptr_t i1; - uintptr_t i2; -}; -struct stret_i3 { - uintptr_t i1; - uintptr_t i2; - uintptr_t i3; -}; -struct stret_i4 { - uintptr_t i1; - uintptr_t i2; - uintptr_t i3; -}; -struct stret_i5 { - uintptr_t i1; - uintptr_t i2; - uintptr_t i3; - uintptr_t i4; - uintptr_t i5; -}; -struct stret_i6 { - uintptr_t i1; - uintptr_t i2; - uintptr_t i3; - uintptr_t i4; - uintptr_t i5; - uintptr_t i6; -}; -struct stret_i7 { - uintptr_t i1; - uintptr_t i2; - uintptr_t i3; - uintptr_t i4; - uintptr_t i5; - uintptr_t i6; - uintptr_t i7; -}; -struct stret_i8 { - uintptr_t i1; - uintptr_t i2; - uintptr_t i3; - uintptr_t i4; - uintptr_t i5; - uintptr_t i8; - uintptr_t i9; -}; -struct stret_i9 { - uintptr_t i1; - uintptr_t i2; - uintptr_t i3; - uintptr_t i4; - uintptr_t i5; - uintptr_t i6; - uintptr_t i7; - uintptr_t i8; - uintptr_t i9; -}; - -struct stret_d1 { - double d1; -}; -struct stret_d2 { - double d1; - double d2; -}; -struct stret_d3 { - double d1; - double d2; - double d3; -}; -struct stret_d4 { - double d1; - double d2; - double d3; -}; -struct stret_d5 { - double d1; - double d2; - double d3; - double d4; - double d5; -}; -struct stret_d6 { - double d1; - double d2; - double d3; - double d4; - double d5; - double d6; -}; -struct stret_d7 { - double d1; - double d2; - double d3; - double d4; - double d5; - double d6; - double d7; -}; -struct stret_d8 { - double d1; - double d2; - double d3; - double d4; - double d5; - double d8; - double d9; -}; -struct stret_d9 { - double d1; - double d2; - double d3; - double d4; - double d5; - double d6; - double d7; - double d8; - double d9; -}; - - -@interface Super (Prototypes) - -// Method prototypes to pacify -Wundeclared-selector. - --(id)idret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - --(long long)llret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - --(struct stret)stret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - --(double)fpret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - --(long double)lfpret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - --(vector_ulong2)vecret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15; - -@end - - -// Zero all volatile registers. -#if __cplusplus -extern "C" -#endif -void stomp(void); - -#if __x86_64__ -asm("\n .text" - "\n .globl _stomp" - "\n _stomp:" - "\n mov $0, %rax" - "\n mov $0, %rcx" - "\n mov $0, %rdx" - "\n mov $0, %rsi" - "\n mov $0, %rdi" - "\n mov $0, %r8" - "\n mov $0, %r9" - "\n mov $0, %r10" - "\n mov $0, %r11" - "\n xorps %xmm0, %xmm0" - "\n xorps %xmm1, %xmm1" - "\n xorps %xmm2, %xmm2" - "\n xorps %xmm3, %xmm3" - "\n xorps %xmm4, %xmm4" - "\n xorps %xmm5, %xmm5" - "\n xorps %xmm6, %xmm6" - "\n xorps %xmm7, %xmm7" - "\n xorps %xmm8, %xmm8" - "\n xorps %xmm9, %xmm9" - "\n xorps %xmm10, %xmm10" - "\n xorps %xmm11, %xmm11" - "\n xorps %xmm12, %xmm12" - "\n xorps %xmm13, %xmm13" - "\n xorps %xmm14, %xmm14" - "\n xorps %xmm15, %xmm15" - "\n ret"); - -#elif __i386__ -asm("\n .text" - "\n .globl _stomp" - "\n _stomp:" - "\n mov $0, %eax" - "\n mov $0, %ecx" - "\n mov $0, %edx" - "\n xorps %xmm0, %xmm0" - "\n xorps %xmm1, %xmm1" - "\n xorps %xmm2, %xmm2" - "\n xorps %xmm3, %xmm3" - "\n xorps %xmm4, %xmm4" - "\n xorps %xmm5, %xmm5" - "\n xorps %xmm6, %xmm6" - "\n xorps %xmm7, %xmm7" - "\n ret"); - -#elif __arm64__ -asm("\n .text" - "\n .globl _stomp" - "\n _stomp:" - "\n mov x0, #0" - "\n mov x1, #0" - "\n mov x2, #0" - "\n mov x3, #0" - "\n mov x4, #0" - "\n mov x5, #0" - "\n mov x6, #0" - "\n mov x7, #0" - "\n mov x8, #0" - "\n mov x9, #0" - "\n mov x10, #0" - "\n mov x11, #0" - "\n mov x12, #0" - "\n mov x13, #0" - "\n mov x14, #0" - "\n mov x15, #0" - "\n mov x16, #0" - "\n mov x17, #0" - "\n movi d0, #0" - "\n movi d1, #0" - "\n movi d2, #0" - "\n movi d3, #0" - "\n movi d4, #0" - "\n movi d5, #0" - "\n movi d6, #0" - "\n movi d7, #0" - "\n ret" - ); - -#elif __arm__ -asm("\n .text" - "\n .globl _stomp" - "\n .thumb_func _stomp" - "\n _stomp:" - "\n mov r0, #0" - "\n mov r1, #0" - "\n mov r2, #0" - "\n mov r3, #0" - "\n mov r9, #0" - "\n mov r12, #0" - "\n vmov.i32 q0, #0" - "\n vmov.i32 q1, #0" - "\n vmov.i32 q2, #0" - "\n vmov.i32 q3, #0" - "\n vmov.i32 q4, #0" - "\n vmov.i32 q5, #0" - "\n vmov.i32 q6, #0" - "\n vmov.i32 q7, #0" - "\n vmov.i32 q8, #0" - "\n vmov.i32 q9, #0" - "\n vmov.i32 q10, #0" - "\n vmov.i32 q11, #0" - "\n vmov.i32 q12, #0" - "\n vmov.i32 q13, #0" - "\n vmov.i32 q14, #0" - "\n vmov.i32 q15, #0" - "\n bx lr" - ); - -#else -# error unknown architecture -#endif - - -@implementation Super --(struct stret)stret { return STRET_RESULT; } - -// The IMPL_ methods are not called directly. Instead the non IMPL_ name is -// called. The resolver function installs the real method. This allows -// the resolver function to stomp on registers to help test register -// preservation in the uncached path. - -+(BOOL) resolveInstanceMethod:(SEL)sel -{ - const char *name = sel_getName(sel); - if (! strstr(name, "::::::::")) return false; - - testprintf("resolving %s\n", name); - - stomp(); - char *realName; - asprintf(&realName, "IMPL_%s", name); - SEL realSel = sel_registerName(realName); - free(realName); - - IMP imp = class_getMethodImplementation(self, realSel); - if (imp == &_objc_msgForward) return false; - return class_addMethod(self, sel, imp, ""); -} - --(id)IMPL_idret: -(vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - CHECK_ARGS(idret); - state = 1; - return ID_RESULT; -} - --(long long)IMPL_llret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - CHECK_ARGS(llret); - state = 2; - return LL_RESULT; -} - --(struct stret)IMPL_stret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - CHECK_ARGS(stret); - state = 3; - return STRET_RESULT; -} - --(double)IMPL_fpret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - CHECK_ARGS(fpret); - state = 4; - return FP_RESULT; -} - --(long double)IMPL_lfpret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - CHECK_ARGS(lfpret); - state = 5; - return LFP_RESULT; -} - --(vector_ulong2)IMPL_vecret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - CHECK_ARGS(vecret); - state = 6; - return VEC_RESULT; -} - - --(id)idret_noarg -{ - CHECK_ARGS_NOARG(idret); - state = 11; - return ID_RESULT; -} - --(long long)llret_noarg -{ - CHECK_ARGS_NOARG(llret); - state = 12; - return LL_RESULT; -} - --(struct stret)stret_noarg -{ - CHECK_ARGS_NOARG(stret); - state = 13; - return STRET_RESULT; -} - --(double)fpret_noarg -{ - CHECK_ARGS_NOARG(fpret); - state = 14; - return FP_RESULT; -} - --(long double)lfpret_noarg -{ - CHECK_ARGS_NOARG(lfpret); - state = 15; - return LFP_RESULT; -} - --(vector_ulong2)vecret_noarg -{ - CHECK_ARGS_NOARG(vecret); - state = 16; - return VEC_RESULT; -} - - --(void)voidret_nop -{ - return; -} - --(void)voidret_nop2 -{ - return; -} - --(id)idret_nop -{ - return ID_RESULT; -} - --(long long)llret_nop -{ - return LL_RESULT; -} - --(struct stret)stret_nop -{ - return STRET_RESULT; -} - --(double)fpret_nop -{ - return FP_RESULT; -} - --(long double)lfpret_nop -{ - return LFP_RESULT; -} - --(vector_ulong2)vecret_nop -{ - return VEC_RESULT; -} - -#define STRET_IMP(n) \ -+(struct stret_##n)stret_##n##_zero \ -{ \ - struct stret_##n ret; \ - bzero(&ret, sizeof(ret)); \ - return ret; \ -} \ -+(struct stret_##n)stret_##n##_nonzero \ -{ \ - struct stret_##n ret; \ - memset(&ret, 0xff, sizeof(ret)); \ - return ret; \ -} - -STRET_IMP(i1) -STRET_IMP(i2) -STRET_IMP(i3) -STRET_IMP(i4) -STRET_IMP(i5) -STRET_IMP(i6) -STRET_IMP(i7) -STRET_IMP(i8) -STRET_IMP(i9) - -STRET_IMP(d1) -STRET_IMP(d2) -STRET_IMP(d3) -STRET_IMP(d4) -STRET_IMP(d5) -STRET_IMP(d6) -STRET_IMP(d7) -STRET_IMP(d8) -STRET_IMP(d9) - - -+(id)idret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - fail("+idret called instead of -idret"); - CHECK_ARGS(idret); -} - -+(long long)llret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - fail("+llret called instead of -llret"); - CHECK_ARGS(llret); -} - -+(struct stret)stret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - fail("+stret called instead of -stret"); - CHECK_ARGS(stret); -} - -+(double)fpret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - fail("+fpret called instead of -fpret"); - CHECK_ARGS(fpret); -} - -+(long double)lfpret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - fail("+lfpret called instead of -lfpret"); - CHECK_ARGS(lfpret); -} - -+(id)idret_noarg -{ - fail("+idret_noarg called instead of -idret_noarg"); - CHECK_ARGS_NOARG(idret); -} - -+(long long)llret_noarg -{ - fail("+llret_noarg called instead of -llret_noarg"); - CHECK_ARGS_NOARG(llret); -} - -+(struct stret)stret_noarg -{ - fail("+stret_noarg called instead of -stret_noarg"); - CHECK_ARGS_NOARG(stret); -} - -+(double)fpret_noarg -{ - fail("+fpret_noarg called instead of -fpret_noarg"); - CHECK_ARGS_NOARG(fpret); -} - -+(long double)lfpret_noarg -{ - fail("+lfpret_noarg called instead of -lfpret_noarg"); - CHECK_ARGS_NOARG(lfpret); -} - -+(vector_ulong2)vecret_noarg -{ - fail("+vecret_noarg called instead of -vecret_noarg"); - CHECK_ARGS_NOARG(vecret); -} - -@end - - -@implementation Sub - --(id)IMPL_idret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - id result; - CHECK_ARGS(idret); - state = 100; - result = [super idret:v1:v2:v3:v4:v5:v6:v7:v8:i1:i2:i3:i4:i5:i6:i7:i8:i9:i10:i11:i12:i13:f1:f2:f3:f4:f5:f6:f7:f8:f9:f10:f11:f12:f13:f14:f15]; - testassert(state == 1); - testassert(result == ID_RESULT); - state = 101; - return result; -} - --(long long)IMPL_llret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - long long result; - CHECK_ARGS(llret); - state = 100; - result = [super llret:v1:v2:v3:v4:v5:v6:v7:v8:i1:i2:i3:i4:i5:i6:i7:i8:i9:i10:i11:i12:i13:f1:f2:f3:f4:f5:f6:f7:f8:f9:f10:f11:f12:f13:f14:f15]; - testassert(state == 2); - testassert(result == LL_RESULT); - state = 102; - return result; -} - --(struct stret)IMPL_stret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - struct stret result; - CHECK_ARGS(stret); - state = 100; - result = [super stret:v1:v2:v3:v4:v5:v6:v7:v8:i1:i2:i3:i4:i5:i6:i7:i8:i9:i10:i11:i12:i13:f1:f2:f3:f4:f5:f6:f7:f8:f9:f10:f11:f12:f13:f14:f15]; - testassert(state == 3); - testassert(stret_equal(result, STRET_RESULT)); - state = 103; - return result; -} - --(double)IMPL_fpret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - double result; - CHECK_ARGS(fpret); - state = 100; - result = [super fpret:v1:v2:v3:v4:v5:v6:v7:v8:i1:i2:i3:i4:i5:i6:i7:i8:i9:i10:i11:i12:i13:f1:f2:f3:f4:f5:f6:f7:f8:f9:f10:f11:f12:f13:f14:f15]; - testassert(state == 4); - testassert(result == FP_RESULT); - state = 104; - return result; -} - --(long double)IMPL_lfpret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - long double result; - CHECK_ARGS(lfpret); - state = 100; - result = [super lfpret:v1:v2:v3:v4:v5:v6:v7:v8:i1:i2:i3:i4:i5:i6:i7:i8:i9:i10:i11:i12:i13:f1:f2:f3:f4:f5:f6:f7:f8:f9:f10:f11:f12:f13:f14:f15]; - testassert(state == 5); - testassert(result == LFP_RESULT); - state = 105; - return result; -} - --(vector_ulong2)IMPL_vecret: - (vector_ulong2)v1 :(vector_ulong2)v2 :(vector_ulong2)v3 :(vector_ulong2)v4 :(vector_ulong2)v5 :(vector_ulong2)v6 :(vector_ulong2)v7 :(vector_ulong2)v8 :(int)i1 :(int)i2 :(int)i3 :(int)i4 :(int)i5 :(int)i6 :(int)i7 :(int)i8 :(int)i9 :(int)i10 :(int)i11 :(int)i12 :(int)i13 :(double)f1 :(double)f2 :(double)f3 :(double)f4 :(double)f5 :(double)f6 :(double)f7 :(double)f8 :(double)f9 :(double)f10 :(double)f11 :(double)f12 :(double)f13 :(double)f14 :(double)f15 -{ - vector_ulong2 result; - CHECK_ARGS(vecret); - state = 100; - result = [super vecret:v1:v2:v3:v4:v5:v6:v7:v8:i1:i2:i3:i4:i5:i6:i7:i8:i9:i10:i11:i12:i13:f1:f2:f3:f4:f5:f6:f7:f8:f9:f10:f11:f12:f13:f14:f15]; - testassert(state == 6); - testassert(vector_equal(result, VEC_RESULT)); - state = 106; - return result; -} - - --(id)idret_noarg -{ - id result; - CHECK_ARGS_NOARG(idret); - state = 100; - result = [super idret_noarg]; - testassert(state == 11); - testassert(result == ID_RESULT); - state = 111; - return result; -} - --(long long)llret_noarg -{ - long long result; - CHECK_ARGS_NOARG(llret); - state = 100; - result = [super llret_noarg]; - testassert(state == 12); - testassert(result == LL_RESULT); - state = 112; - return result; -} - --(struct stret)stret_noarg -{ - struct stret result; - CHECK_ARGS_NOARG(stret); - state = 100; - result = [super stret_noarg]; - testassert(state == 13); - testassert(stret_equal(result, STRET_RESULT)); - state = 113; - return result; -} - --(double)fpret_noarg -{ - double result; - CHECK_ARGS_NOARG(fpret); - state = 100; - result = [super fpret_noarg]; - testassert(state == 14); - testassert(result == FP_RESULT); - state = 114; - return result; -} - --(long double)lfpret_noarg -{ - long double result; - CHECK_ARGS_NOARG(lfpret); - state = 100; - result = [super lfpret_noarg]; - testassert(state == 15); - testassert(result == LFP_RESULT); - state = 115; - return result; -} - --(vector_ulong2)vecret_noarg -{ - vector_ulong2 result; - CHECK_ARGS_NOARG(vecret); - state = 100; - result = [super vecret_noarg]; - testassert(state == 16); - testassert(vector_equal(result, VEC_RESULT)); - state = 116; - return result; -} - -@end - - -#if OBJC_HAVE_TAGGED_POINTERS - -@interface TaggedSub : Sub @end - -@implementation TaggedSub : Sub - -+(void)initialize -{ - _objc_registerTaggedPointerClass(OBJC_TAG_7, self); -} - -@end - -#endif - - -// DWARF checking machinery - -#if TARGET_OS_WIN32 -// unimplemented on this platform -#elif !__OBJC2__ -// 32-bit Mac doesn't use DWARF unwind -#elif TARGET_OS_IPHONE && __arm__ -// 32-bit iOS device doesn't use DWARF unwind -#elif __has_feature(objc_arc) -// ARC's extra RR calls hit the traps at the wrong times -#else - -#define TEST_DWARF 1 - -// Classes with no implementations and no cache contents from elsewhere. -@interface SuperDW : TestRoot @end -@implementation SuperDW @end - -@interface Sub0DW : SuperDW @end -@implementation Sub0DW @end - -@interface SubDW : Sub0DW @end -@implementation SubDW @end - -#include <dlfcn.h> -#include <signal.h> -#include <sys/mman.h> -#include <libunwind.h> - -#define UNW_STEP_SUCCESS 1 -#define UNW_STEP_END 0 - -bool caught = false; -uintptr_t clobbered; - -__BEGIN_DECLS -extern void callit(void *obj, void *sel, void *fn); -extern struct stret callit_stret(void *obj, void *sel, void *fn); -__END_DECLS - -#if __x86_64__ - -#define OTOOL "/usr/bin/xcrun otool -arch x86_64 " - -typedef uint8_t insn_t; -#define BREAK_INSN ((insn_t)0xcc) // int3 - -uintptr_t r12 = 0; -uintptr_t r13 = 0; -uintptr_t r14 = 0; -uintptr_t r15 = 0; -uintptr_t rbx = 0; -uintptr_t rbp = 0; -uintptr_t rsp = 0; -uintptr_t rip = 0; - -void handle_exception(x86_thread_state64_t *state) -{ - unw_cursor_t curs; - unw_word_t reg; - int err; - int step; - - err = unw_init_local(&curs, (unw_context_t *)state); - testassert(!err); - - step = unw_step(&curs); - testassert(step == UNW_STEP_SUCCESS); - - err = unw_get_reg(&curs, UNW_X86_64_R12, ®); - testassert(!err); - testassert(reg == r12); - - err = unw_get_reg(&curs, UNW_X86_64_R13, ®); - testassert(!err); - testassert(reg == r13); - - err = unw_get_reg(&curs, UNW_X86_64_R14, ®); - testassert(!err); - testassert(reg == r14); - - err = unw_get_reg(&curs, UNW_X86_64_R15, ®); - testassert(!err); - testassert(reg == r15); - - err = unw_get_reg(&curs, UNW_X86_64_RBX, ®); - testassert(!err); - testassert(reg == rbx); - - err = unw_get_reg(&curs, UNW_X86_64_RBP, ®); - testassert(!err); - testassert(reg == rbp); - - err = unw_get_reg(&curs, UNW_X86_64_RSP, ®); - testassert(!err); - testassert(reg == rsp); - - err = unw_get_reg(&curs, UNW_REG_IP, ®); - testassert(!err); - testassert(reg == rip); - - - // set thread state to unwound state - state->__r12 = r12; - state->__r13 = r13; - state->__r14 = r14; - state->__r15 = r15; - state->__rbx = rbx; - state->__rbp = rbp; - state->__rsp = rsp; - state->__rip = rip; - - caught = true; -} - - -void sigtrap(int sig, siginfo_t *info, void *cc) -{ - ucontext_t *uc = (ucontext_t *)cc; - mcontext_t mc = (mcontext_t)uc->uc_mcontext; - - testprintf(" handled\n"); - - testassert(sig == SIGTRAP); - testassert((uintptr_t)info->si_addr-1 == clobbered); - - handle_exception(&mc->__ss); - // handle_exception changed register state for continuation -} - -__asm__( -"\n .text" -"\n .globl _callit" -"\n _callit:" -// save sp and return address to variables -"\n movq (%rsp), %r10" -"\n movq %r10, _rip(%rip)" -"\n movq %rsp, _rsp(%rip)" -"\n addq $8, _rsp(%rip)" // rewind to pre-call value -// save other non-volatile registers to variables -"\n movq %rbx, _rbx(%rip)" -"\n movq %rbp, _rbp(%rip)" -"\n movq %r12, _r12(%rip)" -"\n movq %r13, _r13(%rip)" -"\n movq %r14, _r14(%rip)" -"\n movq %r15, _r15(%rip)" -"\n jmpq *%rdx" - ); - -__asm__( -"\n .text" -"\n .globl _callit_stret" -"\n _callit_stret:" -// save sp and return address to variables -"\n movq (%rsp), %r10" -"\n movq %r10, _rip(%rip)" -"\n movq %rsp, _rsp(%rip)" -"\n addq $8, _rsp(%rip)" // rewind to pre-call value -// save other non-volatile registers to variables -"\n movq %rbx, _rbx(%rip)" -"\n movq %rbp, _rbp(%rip)" -"\n movq %r12, _r12(%rip)" -"\n movq %r13, _r13(%rip)" -"\n movq %r14, _r14(%rip)" -"\n movq %r15, _r15(%rip)" -"\n jmpq *%rcx" - ); - - -// x86_64 - -#elif __i386__ - -#define OTOOL "/usr/bin/xcrun otool -arch i386 " - -typedef uint8_t insn_t; -#define BREAK_INSN ((insn_t)0xcc) // int3 - -uintptr_t eip = 0; -uintptr_t esp = 0; -uintptr_t ebx = 0; -uintptr_t ebp = 0; -uintptr_t edi = 0; -uintptr_t esi = 0; -uintptr_t espfix = 0; - -void handle_exception(i386_thread_state_t *state) -{ - unw_cursor_t curs; - unw_word_t reg; - int err; - int step; - - err = unw_init_local(&curs, (unw_context_t *)state); - testassert(!err); - - step = unw_step(&curs); - testassert(step == UNW_STEP_SUCCESS); - - err = unw_get_reg(&curs, UNW_REG_IP, ®); - testassert(!err); - testassert(reg == eip); - - err = unw_get_reg(&curs, UNW_X86_ESP, ®); - testassert(!err); - testassert(reg == esp); - - err = unw_get_reg(&curs, UNW_X86_EBX, ®); - testassert(!err); - testassert(reg == ebx); - - err = unw_get_reg(&curs, UNW_X86_EBP, ®); - testassert(!err); - testassert(reg == ebp); - - err = unw_get_reg(&curs, UNW_X86_EDI, ®); - testassert(!err); - testassert(reg == edi); - - err = unw_get_reg(&curs, UNW_X86_ESI, ®); - testassert(!err); - testassert(reg == esi); - - - // set thread state to unwound state - state->__eip = eip; - state->__esp = esp + espfix; - state->__ebx = ebx; - state->__ebp = ebp; - state->__edi = edi; - state->__esi = esi; - - caught = true; -} - - -void sigtrap(int sig, siginfo_t *info, void *cc) -{ - ucontext_t *uc = (ucontext_t *)cc; - mcontext_t mc = (mcontext_t)uc->uc_mcontext; - - testprintf(" handled\n"); - - testassert(sig == SIGTRAP); - testassert((uintptr_t)info->si_addr-1 == clobbered); - - handle_exception(&mc->__ss); - // handle_exception changed register state for continuation -} - -__asm__( -"\n .text" -"\n .globl _callit" -"\n _callit:" -// save sp and return address to variables -"\n call 1f" -"\n 1: popl %edx" -"\n movl (%esp), %eax" -"\n movl %eax, _eip-1b(%edx)" -"\n movl %esp, _esp-1b(%edx)" -"\n addl $4, _esp-1b(%edx)" // rewind to pre-call value -"\n movl $0, _espfix-1b(%edx)" -// save other non-volatile registers to variables -"\n movl %ebx, _ebx-1b(%edx)" -"\n movl %ebp, _ebp-1b(%edx)" -"\n movl %edi, _edi-1b(%edx)" -"\n movl %esi, _esi-1b(%edx)" -"\n jmpl *12(%esp)" - ); - -__asm__( -"\n .text" -"\n .globl _callit_stret" -"\n _callit_stret:" -// save sp and return address to variables -"\n call 1f" -"\n 1: popl %edx" -"\n movl (%esp), %eax" -"\n movl %eax, _eip-1b(%edx)" -"\n movl %esp, _esp-1b(%edx)" -"\n addl $4, _esp-1b(%edx)" // rewind to pre-call value -"\n movl $4, _espfix-1b(%edx)" -// save other non-volatile registers to variables -"\n movl %ebx, _ebx-1b(%edx)" -"\n movl %ebp, _ebp-1b(%edx)" -"\n movl %edi, _edi-1b(%edx)" -"\n movl %esi, _esi-1b(%edx)" -"\n jmpl *16(%esp)" - ); - - -// i386 -#elif __arm64__ - -#include <sys/ucontext.h> - -// runs on iOS device, no xcrun command present -#define OTOOL "/usr/bin/otool -arch arm64 " - -typedef uint32_t insn_t; -#define BREAK_INSN ((insn_t)0xd4200020) // brk #1 - -uintptr_t x19 = 0; -uintptr_t x20 = 0; -uintptr_t x21 = 0; -uintptr_t x22 = 0; -uintptr_t x23 = 0; -uintptr_t x24 = 0; -uintptr_t x25 = 0; -uintptr_t x26 = 0; -uintptr_t x27 = 0; -uintptr_t x28 = 0; -uintptr_t fp = 0; -uintptr_t sp = 0; -uintptr_t pc = 0; - -void handle_exception(arm_thread_state64_t *state) -{ - unw_cursor_t curs; - unw_word_t reg; - int err; - int step; - - err = unw_init_local(&curs, (unw_context_t *)state); - testassert(!err); - - step = unw_step(&curs); - testassert(step == UNW_STEP_SUCCESS); - - err = unw_get_reg(&curs, UNW_ARM64_X19, ®); - testassert(!err); - testassert(reg == x19); - - err = unw_get_reg(&curs, UNW_ARM64_X20, ®); - testassert(!err); - testassert(reg == x20); - - err = unw_get_reg(&curs, UNW_ARM64_X21, ®); - testassert(!err); - testassert(reg == x21); - - err = unw_get_reg(&curs, UNW_ARM64_X22, ®); - testassert(!err); - testassert(reg == x22); - - err = unw_get_reg(&curs, UNW_ARM64_X23, ®); - testassert(!err); - testassert(reg == x23); - - err = unw_get_reg(&curs, UNW_ARM64_X24, ®); - testassert(!err); - testassert(reg == x24); - - err = unw_get_reg(&curs, UNW_ARM64_X25, ®); - testassert(!err); - testassert(reg == x25); - - err = unw_get_reg(&curs, UNW_ARM64_X26, ®); - testassert(!err); - testassert(reg == x26); - - err = unw_get_reg(&curs, UNW_ARM64_X27, ®); - testassert(!err); - testassert(reg == x27); - - err = unw_get_reg(&curs, UNW_ARM64_X28, ®); - testassert(!err); - testassert(reg == x28); - - err = unw_get_reg(&curs, UNW_ARM64_FP, ®); - testassert(!err); - testassert(reg == fp); - - err = unw_get_reg(&curs, UNW_ARM64_SP, ®); - testassert(!err); - testassert(reg == sp); - - err = unw_get_reg(&curs, UNW_REG_IP, ®); - testassert(!err); - testassert(reg == pc); - - // libunwind restores PC into LR and doesn't track LR - // err = unw_get_reg(&curs, UNW_ARM64_LR, ®); - // testassert(!err); - // testassert(reg == lr); - - // set thread state to unwound state - state->__x[19] = x19; - state->__x[20] = x20; - state->__x[20] = x21; - state->__x[22] = x22; - state->__x[23] = x23; - state->__x[24] = x24; - state->__x[25] = x25; - state->__x[26] = x26; - state->__x[27] = x27; - state->__x[28] = x28; - state->__fp = fp; - state->__lr = pc; // libunwind restores PC into LR - state->__sp = sp; - state->__pc = pc; - - caught = true; -} - - -void sigtrap(int sig, siginfo_t *info, void *cc) -{ - ucontext_t *uc = (ucontext_t *)cc; - struct __darwin_mcontext64 *mc = (struct __darwin_mcontext64 *)uc->uc_mcontext; - - testprintf(" handled\n"); - - testassert(sig == SIGTRAP); - testassert((uintptr_t)info->si_addr == clobbered); - - handle_exception(&mc->__ss); - // handle_exception changed register state for continuation -} - - -__asm__( -"\n .text" -"\n .globl _callit" -"\n _callit:" -// save sp and return address to variables -"\n mov x16, sp" -"\n adrp x17, _sp@PAGE" -"\n str x16, [x17, _sp@PAGEOFF]" -"\n adrp x17, _pc@PAGE" -"\n str lr, [x17, _pc@PAGEOFF]" -// save other non-volatile registers to variables -"\n adrp x17, _x19@PAGE" -"\n str x19, [x17, _x19@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str x20, [x17, _x20@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str x21, [x17, _x21@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str x22, [x17, _x22@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str x23, [x17, _x23@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str x24, [x17, _x24@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str x25, [x17, _x25@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str x26, [x17, _x26@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str x27, [x17, _x27@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str x28, [x17, _x28@PAGEOFF]" -"\n adrp x17, _x19@PAGE" -"\n str fp, [x17, _fp@PAGEOFF]" -"\n br x2" - ); - - -// arm64 -#else - -#error unknown architecture - -#endif - - -insn_t set(uintptr_t dst, insn_t newvalue) -{ - uintptr_t start = dst & ~(PAGE_MAX_SIZE-1); - mprotect((void*)start, PAGE_MAX_SIZE, PROT_READ|PROT_WRITE); - insn_t oldvalue = *(insn_t *)dst; - *(insn_t *)dst = newvalue; - mprotect((void*)start, PAGE_MAX_SIZE, PROT_READ|PROT_EXEC); - return oldvalue; -} - -insn_t clobber(void *fn, uintptr_t offset) -{ - clobbered = (uintptr_t)fn + offset; - return set((uintptr_t)fn + offset, BREAK_INSN); -} - -void unclobber(void *fn, uintptr_t offset, insn_t oldvalue) -{ - set((uintptr_t)fn + offset, oldvalue); -} - - -uintptr_t *getOffsets(void *symbol, const char *symname, uintptr_t *outBase) -{ - uintptr_t *result = (uintptr_t *)malloc(1000 * sizeof(uintptr_t)); - uintptr_t *end = result + 1000; - uintptr_t *p = result; - - // find library - Dl_info dl; - dladdr(symbol, &dl); - - // call `otool` on library - unsetenv("DYLD_LIBRARY_PATH"); - unsetenv("DYLD_ROOT_PATH"); - unsetenv("DYLD_INSERT_LIBRARIES"); - unsetenv("DYLD_SHARED_REGION"); - unsetenv("DYLD_SHARED_CACHE_DIR"); - unsetenv("DYLD_SHARED_CACHE_DONT_VALIDATE"); - char *cmd; - asprintf(&cmd, OTOOL "-tv -p _%s %s", - symname, dl.dli_fname); - testprintf("%s\n", cmd); - FILE *disa = popen(cmd, "r"); - free(cmd); - testassert(disa); - - // read past "_symname:" line - char *line; - size_t len; - while ((line = fgetln(disa, &len))) { - if (0 == strncmp(1+line, symname, MIN(len-1, strlen(symname)))) break; - } - - // read instructions and save offsets - char op[128]; - long base = 0; - long addr; - while (2 == fscanf(disa, "%lx%s%*[^\n]\n", &addr, op)) { - if (base == 0) base = addr; - if (0 != strncmp(op, "nop", 3)) { - testassert(p < end); - *p++ = addr - base; - } else { - // assume nops are unreached (e.g. alignment padding) - } - } - pclose(disa); - -#if __arm64__ - // Also add breakpoints in _objc_msgSend_uncached_impcache - // (which is the slow path and has a frame to unwind) - if (0 != strcmp(symname, "_objc_msgSend_uncached_impcache")) { - uintptr_t base2; - uintptr_t *more_offsets = getOffsets(symbol, "_objc_msgSend_uncached_impcache", &base2); - uintptr_t *q = more_offsets; - // Skip prologue because it's imprecisely modeled in compact unwind - testassert(*q != ~0UL); - q++; - testassert(*q != ~0UL); - q++; - while (*q != ~0UL) *p++ = *q++ + base2 - base; - // Skip return because it's imprecisely modeled in compact unwind - p--; - free(more_offsets); - } -#endif - - testassert(p > result); - testassert(p < end); - *p = ~0UL; -#if __x86_64__ - // hack: skip last instruction because libunwind blows up if it's - // one byte long and followed by the next function with no NOPs first - p[-1] = ~0UL; -#endif - if (outBase) *outBase = base; - return result; -} - -void CALLIT(void *o, void *sel_arg, SEL s, void *f, bool stret) __attribute__((noinline)); -void CALLIT(void *o, void *sel_arg, SEL s, void *f, bool stret) -{ - uintptr_t message_ref[2]; - if (sel_arg != s) { - // fixup dispatch - // copy to a local buffer to keep sel_arg un-fixed-up - memcpy(message_ref, sel_arg, sizeof(message_ref)); - sel_arg = message_ref; - } - if (!stret) callit(o, sel_arg, f); -#if SUPPORT_STRET - else callit_stret(o, sel_arg, f); -#else - else fail("stret?"); -#endif -} - -void test_dw_forward(void) -{ - return; -} - -struct stret test_dw_forward_stret(void) -{ - return zero; -} - -// sub = ordinary receiver object -// tagged = tagged receiver object -// SEL = selector to send -// sub_arg = arg to pass in receiver register (may be objc_super struct) -// tagged_arg = arg to pass in receiver register (may be objc_super struct) -// sel_arg = arg to pass in sel register (may be message_ref) -// uncaughtAllowed is the number of acceptable unreachable instructions -// (for example, the ones that handle the corrupt-cache-error case) -void test_dw(const char *name, id sub, id tagged, bool stret, - int uncaughtAllowed) -{ - - testprintf("DWARF FOR %s%s\n", name, stret ? " (stret)" : ""); - - // We need 2 SELs of each alignment so we can generate hash collisions. - // sel_registerName() never returns those alignments because they - // differ from malloc's alignment. So we create lots of compiled-in - // SELs here and hope something fits. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wundeclared-selector" - SEL sel = @selector(a); - SEL lotsOfSels[] = { - @selector(a1), @selector(a2), @selector(a3), @selector(a4), - @selector(a5), @selector(a6), @selector(a7), @selector(a8), - @selector(aa), @selector(ab), @selector(ac), @selector(ad), - @selector(ae), @selector(af), @selector(ag), @selector(ah), - @selector(A1), @selector(A2), @selector(A3), @selector(A4), - @selector(A5), @selector(A6), @selector(A7), @selector(A8), - @selector(AA), @selector(Ab), @selector(Ac), @selector(Ad), - @selector(Ae), @selector(Af), @selector(Ag), @selector(Ah), - @selector(bb1), @selector(bb2), @selector(bb3), @selector(bb4), - @selector(bb5), @selector(bb6), @selector(bb7), @selector(bb8), - @selector(bba), @selector(bbb), @selector(bbc), @selector(bbd), - @selector(bbe), @selector(bbf), @selector(bbg), @selector(bbh), - @selector(BB1), @selector(BB2), @selector(BB3), @selector(BB4), - @selector(BB5), @selector(BB6), @selector(BB7), @selector(BB8), - @selector(BBa), @selector(BBb), @selector(BBc), @selector(BBd), - @selector(BBe), @selector(BBf), @selector(BBg), @selector(BBh), - @selector(ccc1), @selector(ccc2), @selector(ccc3), @selector(ccc4), - @selector(ccc5), @selector(ccc6), @selector(ccc7), @selector(ccc8), - @selector(ccca), @selector(cccb), @selector(cccc), @selector(cccd), - @selector(ccce), @selector(cccf), @selector(cccg), @selector(ccch), - @selector(CCC1), @selector(CCC2), @selector(CCC3), @selector(CCC4), - @selector(CCC5), @selector(CCC6), @selector(CCC7), @selector(CCC8), - @selector(CCCa), @selector(CCCb), @selector(CCCc), @selector(CCCd), - @selector(CCCe), @selector(CCCf), @selector(CCCg), @selector(CCCh), - }; -#pragma clang diagnostic pop - - { - IMP imp = stret ? (IMP)test_dw_forward_stret : (IMP)test_dw_forward; - Class cls = object_getClass(sub); - Class tagcls = object_getClass(tagged); - class_replaceMethod(cls, sel, imp, ""); - class_replaceMethod(tagcls, sel, imp, ""); - for (size_t i = 0; i < sizeof(lotsOfSels)/sizeof(lotsOfSels[0]); i++) { - class_replaceMethod(cls, lotsOfSels[i], imp, ""); - class_replaceMethod(tagcls, lotsOfSels[i], imp, ""); - } - } - - #define ALIGNCOUNT 16 - SEL sels[ALIGNCOUNT][2] = {{0}}; - for (int align = 0; align < ALIGNCOUNT; align++) { - for (size_t i = 0; i < sizeof(lotsOfSels)/sizeof(lotsOfSels[0]); i++) { - if ((uintptr_t)(void*)lotsOfSels[i] % ALIGNCOUNT == align) { - if (sels[align][0]) { - sels[align][1] = lotsOfSels[i]; - } else { - sels[align][0] = lotsOfSels[i]; - } - } - } - if (!sels[align][0]) fail("no SEL with alignment %d", align); - if (!sels[align][1]) fail("only one SEL with alignment %d", align); - } - - void *fn = dlsym(RTLD_DEFAULT, name); - testassert(fn); - - // argument substitutions - - void *sub_arg = (void*)objc_unretainedPointer(sub); - void *tagged_arg = (void*)objc_unretainedPointer(tagged); - void *sel_arg = (void*)sel; - - struct objc_super sup_st = { sub, object_getClass(sub) }; - struct objc_super tagged_sup_st = { tagged, object_getClass(tagged) }; - struct { void *imp; SEL sel; } message_ref = { fn, sel }; - - Class cache_cls = object_getClass(sub); - - if (strstr(name, "Super")) { - // super version - replace receiver with objc_super - // clear caches of superclass - cache_cls = class_getSuperclass(cache_cls); - sub_arg = &sup_st; - tagged_arg = &tagged_sup_st; - } - - if (strstr(name, "_fixup")) { - // fixup version - replace sel with message_ref - sel_arg = &message_ref; - } - - - uintptr_t *insnOffsets = getOffsets(fn, name, nil); - uintptr_t offset; - int uncaughtCount = 0; - for (int oo = 0; insnOffsets[oo] != ~0UL; oo++) { - offset = insnOffsets[oo]; - testprintf("OFFSET %lu\n", offset); - - insn_t saved_insn = clobber(fn, offset); - caught = false; - - // nil - if ((void*)objc_unretainedPointer(sub) == sub_arg) { - SELF = nil; - testprintf(" nil\n"); - CALLIT(nil, sel_arg, sel, fn, stret); - CALLIT(nil, sel_arg, sel, fn, stret); - } - - // uncached - SELF = sub; - testprintf(" uncached\n"); - _objc_flush_caches(cache_cls); - CALLIT(sub_arg, sel_arg, sel, fn, stret); - _objc_flush_caches(cache_cls); - CALLIT(sub_arg, sel_arg, sel, fn, stret); - - // cached - SELF = sub; - testprintf(" cached\n"); - CALLIT(sub_arg, sel_arg, sel, fn, stret); - CALLIT(sub_arg, sel_arg, sel, fn, stret); - - // uncached,tagged - SELF = tagged; - testprintf(" uncached,tagged\n"); - _objc_flush_caches(cache_cls); - CALLIT(tagged_arg, sel_arg, sel, fn, stret); - _objc_flush_caches(cache_cls); - CALLIT(tagged_arg, sel_arg, sel, fn, stret); - - // cached,tagged - SELF = tagged; - testprintf(" cached,tagged\n"); - CALLIT(tagged_arg, sel_arg, sel, fn, stret); - CALLIT(tagged_arg, sel_arg, sel, fn, stret); - - // multiple SEL alignments, collisions, wraps - SELF = sub; - for (int a = 0; a < ALIGNCOUNT; a++) { - testprintf(" cached, SEL alignment %d\n", a); - - // Count both up and down to be independent of - // implementation's cache scan direction - - _objc_flush_caches(cache_cls); - for (int x2 = 0; x2 < 8; x2++) { - for (int s = 0; s < 4; s++) { - int align = (a+s) % ALIGNCOUNT; - CALLIT(sub_arg, sels[align][0], sels[align][0], fn, stret); - CALLIT(sub_arg, sels[align][1], sels[align][1], fn, stret); - } - } - - _objc_flush_caches(cache_cls); - for (int x2 = 0; x2 < 8; x2++) { - for (int s = 0; s < 4; s++) { - int align = abs(a-s) % ALIGNCOUNT; - CALLIT(sub_arg, sels[align][0], sels[align][0], fn, stret); - CALLIT(sub_arg, sels[align][1], sels[align][1], fn, stret); - } - } - } - - unclobber(fn, offset, saved_insn); - - // remember offsets that were caught by none of the above - if (caught) { - insnOffsets[oo] = 0; - } else { - uncaughtCount++; - testprintf("offset %s+%lu not caught (%d/%d)\n", - name, offset, uncaughtCount, uncaughtAllowed); - } - } - - // Complain if too many offsets went uncaught. - // Acceptably-uncaught offsets include the corrupt-cache-error handler. - if (uncaughtCount != uncaughtAllowed) { - for (int oo = 0; insnOffsets[oo] != ~0UL; oo++) { - if (insnOffsets[oo]) { - fprintf(stderr, "BAD: offset %s+%lu not caught\n", - name, insnOffsets[oo]); - } - } - fail("wrong instructions not reached for %s (missed %d, expected %d)", - name, uncaughtCount, uncaughtAllowed); - } - - free(insnOffsets); -} - - -// TEST_DWARF -#endif - - -void test_basic(id receiver) -{ - id idval; - long long llval; - struct stret stretval; - double fpval; - long double lfpval; - vector_ulong2 vecval; - - // message uncached - // message uncached long long - // message uncached stret - // message uncached fpret - // message uncached fpret long double - // message uncached noarg (as above) - // message cached - // message cached long long - // message cached stret - // message cached fpret - // message cached fpret long double - // message cached noarg (as above) - // fixme verify that uncached lookup didn't happen the 2nd time? - SELF = receiver; - for (int i = 0; i < 5; i++) { - testprintf("idret\n"); - state = 0; - idval = nil; - idval = [receiver idret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 101); - testassert(idval == ID_RESULT); - - testprintf("llret\n"); - llval = 0; - llval = [receiver llret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 102); - testassert(llval == LL_RESULT); - - testprintf("stret\n"); - stretval = zero; - stretval = [receiver stret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 103); - testassert(stret_equal(stretval, STRET_RESULT)); - - testprintf("fpret\n"); - fpval = 0; - fpval = [receiver fpret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 104); - testassert(fpval == FP_RESULT); - - testprintf("lfpret\n"); - lfpval = 0; - lfpval = [receiver lfpret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 105); - testassert(lfpval == LFP_RESULT); - - testprintf("vecret\n"); - vecval = 0; - vecval = [receiver vecret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 106); - testassert(vector_equal(vecval, VEC_RESULT)); - -#if __OBJC2__ - // explicitly call noarg messenger, even if compiler doesn't emit it - state = 0; - testprintf("idret noarg\n"); - idval = nil; - idval = ((typeof(idmsg0))objc_msgSend_noarg)(receiver, @selector(idret_noarg)); - testassert(state == 111); - testassert(idval == ID_RESULT); - - testprintf("llret noarg\n"); - llval = 0; - llval = ((typeof(llmsg0))objc_msgSend_noarg)(receiver, @selector(llret_noarg)); - testassert(state == 112); - testassert(llval == LL_RESULT); - /* - no objc_msgSend_stret_noarg - stretval = zero; - stretval = ((typeof(stretmsg0))objc_msgSend_stret_noarg)(receiver, @selector(stret_noarg)); - stretval = [receiver stret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 113); - testassert(stret_equal(stretval, STRET_RESULT)); - */ -# if !__i386__ - testprintf("fpret noarg\n"); - fpval = 0; - fpval = ((typeof(fpmsg0))objc_msgSend_noarg)(receiver, @selector(fpret_noarg)); - testassert(state == 114); - testassert(fpval == FP_RESULT); - - testprintf("vecret noarg\n"); - vecval = 0; - vecval = ((typeof(vecmsg0))objc_msgSend_noarg)(receiver, @selector(vecret_noarg)); - testassert(state == 116); - testassert(vector_equal(vecval, VEC_RESULT)); -# endif -# if !__i386__ && !__x86_64__ - testprintf("lfpret noarg\n"); - lfpval = 0; - lfpval = ((typeof(lfpmsg0))objc_msgSend_noarg)(receiver, @selector(lfpret_noarg)); - testassert(state == 115); - testassert(lfpval == LFP_RESULT); -# endif -#endif - } - - testprintf("basic done\n"); -} - -int main() -{ - PUSH_POOL { - int i; - - id idval; - long long llval; - struct stret stretval; - double fpval; - long double lfpval; - vector_ulong2 vecval; - -#if __x86_64__ - struct stret *stretptr; -#endif - - uint64_t startTime; - uint64_t totalTime; - uint64_t targetTime; - - Method idmethod; - Method llmethod; - Method stretmethod; - Method fpmethod; - Method lfpmethod; - Method vecmethod; - - id (*idfn)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double); - long long (*llfn)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double); - struct stret (*stretfn)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double); - double (*fpfn)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double); - long double (*lfpfn)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double); - vector_ulong2 (*vecfn)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double); - - id (*idmsg)(id, SEL, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double) __attribute__((unused)); - id (*idmsgsuper)(struct objc_super *, SEL, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double) __attribute__((unused)); - long long (*llmsg)(id, SEL, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double) __attribute__((unused)); - struct stret (*stretmsg)(id, SEL, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double) __attribute__((unused)); - struct stret (*stretmsgsuper)(struct objc_super *, SEL, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double) __attribute__((unused)); - double (*fpmsg)(id, SEL, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double) __attribute__((unused)); - long double (*lfpmsg)(id, SEL, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double) __attribute__((unused)); - vector_ulong2 (*vecmsg)(id, SEL, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double) __attribute__((unused)); - - // get +initialize out of the way - [Sub class]; -#if OBJC_HAVE_TAGGED_POINTERS - [TaggedSub class]; -#endif - - ID_RESULT = [Super new]; - - Sub *sub = [Sub new]; - Super *sup = [Super new]; -#if OBJC_HAVE_TAGGED_POINTERS - TaggedSub *tagged = objc_unretainedObject(_objc_makeTaggedPointer(OBJC_TAG_7, 999)); -#endif - - // Basic cached and uncached dispatch. - // Do this first before anything below caches stuff. - testprintf("basic\n"); - test_basic(sub); -#if OBJC_HAVE_TAGGED_POINTERS - testprintf("basic tagged\n"); - test_basic(tagged); -#endif - - idmethod = class_getInstanceMethod([Super class], @selector(idret::::::::::::::::::::::::::::::::::::)); - testassert(idmethod); - llmethod = class_getInstanceMethod([Super class], @selector(llret::::::::::::::::::::::::::::::::::::)); - testassert(llmethod); - stretmethod = class_getInstanceMethod([Super class], @selector(stret::::::::::::::::::::::::::::::::::::)); - testassert(stretmethod); - fpmethod = class_getInstanceMethod([Super class], @selector(fpret::::::::::::::::::::::::::::::::::::)); - testassert(fpmethod); - lfpmethod = class_getInstanceMethod([Super class], @selector(lfpret::::::::::::::::::::::::::::::::::::)); - testassert(lfpmethod); - vecmethod = class_getInstanceMethod([Super class], @selector(vecret::::::::::::::::::::::::::::::::::::)); - testassert(vecmethod); - - idfn = (id (*)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double)) method_invoke; - llfn = (long long (*)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double)) method_invoke; - stretfn = (struct stret (*)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double)) method_invoke_stret; - fpfn = (double (*)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double)) method_invoke; - lfpfn = (long double (*)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double)) method_invoke; - vecfn = (vector_ulong2 (*)(id, Method, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, vector_ulong2, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double)) method_invoke; - - // cached message performance - // catches failure to cache or (abi=2) failure to fixup (#5584187) - // fixme unless they all fail - // `.align 4` matches loop alignment to make -O0 work - // fill cache first - testprintf("time checks\n"); - - SELF = sub; - [sub voidret_nop]; - [sub voidret_nop2]; - [sub llret_nop]; - [sub stret_nop]; - [sub fpret_nop]; - [sub lfpret_nop]; - [sub vecret_nop]; - [sub voidret_nop]; - [sub voidret_nop2]; - [sub llret_nop]; - [sub stret_nop]; - [sub fpret_nop]; - [sub lfpret_nop]; - [sub vecret_nop]; - [sub voidret_nop]; - [sub voidret_nop2]; - [sub llret_nop]; - [sub stret_nop]; - [sub fpret_nop]; - [sub lfpret_nop]; - [sub vecret_nop]; - - // Some of these times have high variance on some compilers. - // The errors we're trying to catch should be catastrophically slow, - // so the margins here are generous to avoid false failures. - - // Use voidret because id return is too slow for perf test with ARC. - - // Pick smallest of voidret_nop and voidret_nop2 time - // in the hopes that one of them didn't collide in the method cache. - -#define COUNT 1000000 - - startTime = mach_absolute_time(); - ALIGN_(); - for (i = 0; i < COUNT; i++) { - [sub voidret_nop]; - } - totalTime = mach_absolute_time() - startTime; - testprintf("time: voidret %llu\n", totalTime); - targetTime = totalTime; - - startTime = mach_absolute_time(); - ALIGN_(); - for (i = 0; i < COUNT; i++) { - [sub voidret_nop2]; - } - totalTime = mach_absolute_time() - startTime; - testprintf("time: voidret2 %llu\n", totalTime); - if (totalTime < targetTime) targetTime = totalTime; - - startTime = mach_absolute_time(); - ALIGN_(); - for (i = 0; i < COUNT; i++) { - [sub llret_nop]; - } - totalTime = mach_absolute_time() - startTime; - timecheck("llret ", totalTime, targetTime * 0.7, targetTime * 2.0); - - startTime = mach_absolute_time(); - ALIGN_(); - for (i = 0; i < COUNT; i++) { - [sub stret_nop]; - } - totalTime = mach_absolute_time() - startTime; - timecheck("stret ", totalTime, targetTime * 0.7, targetTime * 5.0); - - startTime = mach_absolute_time(); - ALIGN_(); - for (i = 0; i < COUNT; i++) { - [sub fpret_nop]; - } - totalTime = mach_absolute_time() - startTime; - timecheck("fpret ", totalTime, targetTime * 0.7, targetTime * 4.0); - - startTime = mach_absolute_time(); - ALIGN_(); - for (i = 0; i < COUNT; i++) { - [sub lfpret_nop]; - } - totalTime = mach_absolute_time() - startTime; - timecheck("lfpret", totalTime, targetTime * 0.7, targetTime * 4.0); - - startTime = mach_absolute_time(); - ALIGN_(); - for (i = 0; i < COUNT; i++) { - [sub vecret_nop]; - } - totalTime = mach_absolute_time() - startTime; - timecheck("vecret", totalTime, targetTime * 0.7, targetTime * 4.0); - -#if __arm64__ - // Removing this testwarn(), or changing voidret_nop to nop;ret, - // changes the voidret_nop and stret_nop times above by a factor of 2. - testwarn("rdar://13896922 nop;ret is faster than ret?"); -#endif - -#undef COUNT - - // method_invoke - // method_invoke long long - // method_invoke_stret stret - // method_invoke_stret fpret - // method_invoke fpret long double - testprintf("method_invoke\n"); - - SELF = sup; - - state = 0; - idval = nil; - idval = (*idfn)(sup, idmethod, VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 1); - testassert(idval == ID_RESULT); - - llval = 0; - llval = (*llfn)(sup, llmethod, VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 2); - testassert(llval == LL_RESULT); - - stretval = zero; - stretval = (*stretfn)(sup, stretmethod, VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 3); - testassert(stret_equal(stretval, STRET_RESULT)); - - fpval = 0; - fpval = (*fpfn)(sup, fpmethod, VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 4); - testassert(fpval == FP_RESULT); - - lfpval = 0; - lfpval = (*lfpfn)(sup, lfpmethod, VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 5); - testassert(lfpval == LFP_RESULT); - - vecval = 0; - vecval = (*vecfn)(sup, vecmethod, VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 6); - testassert(vector_equal(vecval, VEC_RESULT)); - - - // message to nil - // message to nil long long - // message to nil stret - // message to nil fpret - // message to nil fpret long double - // Use NIL_RECEIVER to avoid compiler optimizations. - testprintf("message to nil\n"); - - state = 0; - idval = ID_RESULT; - idval = [(id)NIL_RECEIVER idret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 0); - testassert(idval == nil); - - state = 0; - llval = LL_RESULT; - llval = [(id)NIL_RECEIVER llret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 0); - testassert(llval == 0LL); - - state = 0; - stretval = zero; - stretval = [(id)NIL_RECEIVER stret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 0); -#if __clang__ - testassert(0 == memcmp(&stretval, &zero, sizeof(stretval))); -#else - // no stret result guarantee -#endif - -#if __x86_64__ - // check stret return register - state = 0; - stretval = zero; - stretptr = ((struct stret *(*)(struct stret *, id, SEL))objc_msgSend_stret) - (&stretval, nil, @selector(stret_nop)); - testassert(stretptr == &stretval); - testassert(state == 0); - // no stret result guarantee for hand-written calls, even with clang -#endif - -#if __i386__ - // check struct-return address stack pop - for (int i = 0; i < 10000000; i++) { - state = 0; - ((struct stret (*)(id, SEL))objc_msgSend_stret) - (nil, @selector(stret_nop)); - } -#endif - - state = 0; - fpval = FP_RESULT; - fpval = [(id)NIL_RECEIVER fpret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 0); - testassert(fpval == 0.0); - - state = 0; - lfpval = LFP_RESULT; - lfpval = [(id)NIL_RECEIVER lfpret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 0); - testassert(lfpval == 0.0); - - state = 0; - vecval = VEC_RESULT; - vecval = [(id)NIL_RECEIVER vecret :VEC1:VEC2:VEC3:VEC4:VEC5:VEC6:VEC7:VEC8:1:2:3:4:5:6:7:8:9:10:11:12:13:1.0:2.0:3.0:4.0:5.0:6.0:7.0:8.0:9.0:10.0:11.0:12.0:13.0:14.0:15.0]; - testassert(state == 0); - testassert(vector_all(vecval == 0)); - - // message to nil, different struct types - // This verifies that ordinary objc_msgSend() erases enough registers - // for structs that return in registers. -#define TEST_NIL_STRUCT(i,n) \ - do { \ - struct stret_##i##n z; \ - bzero(&z, sizeof(z)); \ - [Super stret_i##n##_nonzero]; \ - [Super stret_d##n##_nonzero]; \ - struct stret_##i##n val = [(id)NIL_RECEIVER stret_##i##n##_zero]; \ - testassert(0 == memcmp(&z, &val, sizeof(val))); \ - } while (0) - - TEST_NIL_STRUCT(i,1); - TEST_NIL_STRUCT(i,2); - TEST_NIL_STRUCT(i,3); - TEST_NIL_STRUCT(i,4); - TEST_NIL_STRUCT(i,5); - TEST_NIL_STRUCT(i,6); - TEST_NIL_STRUCT(i,7); - TEST_NIL_STRUCT(i,8); - TEST_NIL_STRUCT(i,9); - -#if __i386__ - testwarn("rdar://16267205 i386 struct{float} and struct{double}"); -#else - TEST_NIL_STRUCT(d,1); -#endif - TEST_NIL_STRUCT(d,2); - TEST_NIL_STRUCT(d,3); - TEST_NIL_STRUCT(d,4); - TEST_NIL_STRUCT(d,5); - TEST_NIL_STRUCT(d,6); - TEST_NIL_STRUCT(d,7); - TEST_NIL_STRUCT(d,8); - TEST_NIL_STRUCT(d,9); - - -#if __OBJC2__ - // message to nil noarg - // explicitly call noarg messenger, even if compiler doesn't emit it - state = 0; - idval = ID_RESULT; - idval = ((typeof(idmsg0))objc_msgSend_noarg)(nil, @selector(idret_noarg)); - testassert(state == 0); - testassert(idval == nil); - - state = 0; - llval = LL_RESULT; - llval = ((typeof(llmsg0))objc_msgSend_noarg)(nil, @selector(llret_noarg)); - testassert(state == 0); - testassert(llval == 0LL); - - // no stret_noarg messenger - -# if !__i386__ - state = 0; - fpval = FP_RESULT; - fpval = ((typeof(fpmsg0))objc_msgSend_noarg)(nil, @selector(fpret_noarg)); - testassert(state == 0); - testassert(fpval == 0.0); - - state = 0; - vecval = VEC_RESULT; - vecval = ((typeof(vecmsg0))objc_msgSend_noarg)(nil, @selector(vecret_noarg)); - testassert(state == 0); - testassert(vector_all(vecval == 0)); -# endif -# if !__i386__ && !__x86_64__ - state = 0; - lfpval = LFP_RESULT; - lfpval = ((typeof(lfpmsg0))objc_msgSend_noarg)(nil, @selector(lfpret_noarg)); - testassert(state == 0); - testassert(lfpval == 0.0); -# endif -#endif - - -#if __OBJC2__ - // rdar://8271364 objc_msgSendSuper2 must not change objc_super - testprintf("super struct\n"); - struct objc_super sup_st = { - sub, - object_getClass(sub), - }; - - SELF = sub; - - state = 100; - idval = nil; - idval = ((id(*)(struct objc_super *, SEL, vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2, int,int,int,int,int,int,int,int,int,int,int,int,int, double,double,double,double,double,double,double,double,double,double,double,double,double,double,double))objc_msgSendSuper2) (&sup_st, @selector(idret::::::::::::::::::::::::::::::::::::), VEC1,VEC2,VEC3,VEC4,VEC5,VEC6,VEC7,VEC8, 1,2,3,4,5,6,7,8,9,10,11,12,13, 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0); - testassert(state == 1); - testassert(idval == ID_RESULT); - testassert(sup_st.receiver == sub); - testassert(sup_st.super_class == object_getClass(sub)); - - state = 100; - stretval = zero; - stretval = ((struct stret(*)(struct objc_super *, SEL, vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2,vector_ulong2, int,int,int,int,int,int,int,int,int,int,int,int,int, double,double,double,double,double,double,double,double,double,double,double,double,double,double,double))objc_msgSendSuper2_stret) (&sup_st, @selector(stret::::::::::::::::::::::::::::::::::::), VEC1,VEC2,VEC3,VEC4,VEC5,VEC6,VEC7,VEC8, 1,2,3,4,5,6,7,8,9,10,11,12,13, 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0); - testassert(state == 3); - testassert(stret_equal(stretval, STRET_RESULT)); - testassert(sup_st.receiver == sub); - testassert(sup_st.super_class == object_getClass(sub)); -#endif - -#if __OBJC2__ && !__arm64__ - // Debug messengers. - testprintf("debug messengers\n"); - - state = 0; - idmsg = (typeof(idmsg))objc_msgSend_debug; - idval = nil; - idval = (*idmsg)(sub, @selector(idret::::::::::::::::::::::::::::::::::::), VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 101); - testassert(idval == ID_RESULT); - - state = 0; - llmsg = (typeof(llmsg))objc_msgSend_debug; - llval = 0; - llval = (*llmsg)(sub, @selector(llret::::::::::::::::::::::::::::::::::::), VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 102); - testassert(llval == LL_RESULT); - - state = 0; - stretmsg = (typeof(stretmsg))objc_msgSend_stret_debug; - stretval = zero; - stretval = (*stretmsg)(sub, @selector(stret::::::::::::::::::::::::::::::::::::), VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 103); - testassert(stret_equal(stretval, STRET_RESULT)); - - state = 100; - sup_st.receiver = sub; - sup_st.super_class = object_getClass(sub); - idmsgsuper = (typeof(idmsgsuper))objc_msgSendSuper2_debug; - idval = nil; - idval = (*idmsgsuper)(&sup_st, @selector(idret::::::::::::::::::::::::::::::::::::), VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 1); - testassert(idval == ID_RESULT); - - state = 100; - sup_st.receiver = sub; - sup_st.super_class = object_getClass(sub); - stretmsgsuper = (typeof(stretmsgsuper))objc_msgSendSuper2_stret_debug; - stretval = zero; - stretval = (*stretmsgsuper)(&sup_st, @selector(stret::::::::::::::::::::::::::::::::::::), VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 3); - testassert(stret_equal(stretval, STRET_RESULT)); - -#if __i386__ - state = 0; - fpmsg = (typeof(fpmsg))objc_msgSend_fpret_debug; - fpval = 0; - fpval = (*fpmsg)(sub, @selector(fpret::::::::::::::::::::::::::::::::::::), VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 104); - testassert(fpval == FP_RESULT); -#endif -#if __x86_64__ - state = 0; - lfpmsg = (typeof(lfpmsg))objc_msgSend_fpret_debug; - lfpval = 0; - lfpval = (*lfpmsg)(sub, @selector(lfpret::::::::::::::::::::::::::::::::::::), VEC1, VEC2, VEC3, VEC4, VEC5, VEC6, VEC7, VEC8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0); - testassert(state == 105); - testassert(lfpval == LFP_RESULT); - - // fixme fp2ret -#endif - -// debug messengers -#endif - - -#if !TEST_DWARF - testwarn("no unwind tables in this configuration"); -#else - // DWARF unwind tables - testprintf("unwind tables\n"); - - // install exception handler - struct sigaction act; - act.sa_sigaction = sigtrap; - act.sa_mask = 0; - act.sa_flags = SA_SIGINFO; - sigaction(SIGTRAP, &act, NULL); - - SubDW *dw = [[SubDW alloc] init]; - - objc_setForwardHandler((void*)test_dw_forward, (void*)test_dw_forward_stret); - -# if __x86_64__ - test_dw("objc_msgSend", dw, tagged, false, 0); - test_dw("objc_msgSend_stret", dw, tagged, true, 0); - test_dw("objc_msgSend_fpret", dw, tagged, false, 0); - test_dw("objc_msgSend_fp2ret", dw, tagged, false, 0); - test_dw("objc_msgSendSuper", dw, tagged, false, 0); - test_dw("objc_msgSendSuper2", dw, tagged, false, 0); - test_dw("objc_msgSendSuper_stret", dw, tagged, true, 0); - test_dw("objc_msgSendSuper2_stret", dw, tagged, true, 0); -# elif __i386__ - test_dw("objc_msgSend", dw, dw, false, 0); - test_dw("objc_msgSend_stret", dw, dw, true, 0); - test_dw("objc_msgSend_fpret", dw, dw, false, 0); - test_dw("objc_msgSendSuper", dw, dw, false, 0); - test_dw("objc_msgSendSuper2", dw, dw, false, 0); - test_dw("objc_msgSendSuper_stret", dw, dw, true, 0); - test_dw("objc_msgSendSuper2_stret", dw, dw, true, 0); -# elif __arm64__ - test_dw("objc_msgSend", dw, tagged, false, 1); - test_dw("objc_msgSendSuper", dw, tagged, false, 1); - test_dw("objc_msgSendSuper2", dw, tagged, false, 1); -# else -# error unknown architecture -# endif - - // DWARF unwind tables -#endif - - } POP_POOL; - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/nilAPIArgs.m b/objc/objc-runtime/test/nilAPIArgs.m deleted file mode 100644 index a133451..0000000 --- a/objc/objc-runtime/test/nilAPIArgs.m +++ /dev/null @@ -1,13 +0,0 @@ -// TEST_CONFIG - -#include "test.h" - -#import <objc/runtime.h> - -int main() { - // ensure various bits of API don't crash when tossed nil parameters - class_conformsToProtocol(nil, nil); - method_setImplementation(nil, NULL); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/nonpointerisa.m b/objc/objc-runtime/test/nonpointerisa.m deleted file mode 100644 index 1fe2a70..0000000 --- a/objc/objc-runtime/test/nonpointerisa.m +++ /dev/null @@ -1,223 +0,0 @@ -// TEST_CFLAGS -framework Foundation -// TEST_CONFIG MEM=mrc - -#include "test.h" - -#if !__OBJC2__ - -int main() -{ - succeed(__FILE__); -} - -#else - -#include <dlfcn.h> - -#include <objc/objc-gdb.h> -#include <Foundation/Foundation.h> - -#define ISA(x) (*((uintptr_t *)(x))) -#define INDEXED(x) (ISA(x) & 1) - -#if SUPPORT_NONPOINTER_ISA -# if __x86_64__ -# define RC_ONE (1ULL<<56) -# elif __arm64__ -# define RC_ONE (1ULL<<45) -# else -# error unknown architecture -# endif -#endif - - -void check_unindexed(id obj, Class cls) -{ - testassert(object_getClass(obj) == cls); - testassert(!INDEXED(obj)); - - uintptr_t isa = ISA(obj); - testassert((Class)isa == cls); - testassert((Class)(isa & objc_debug_isa_class_mask) == cls); - testassert((Class)(isa & ~objc_debug_isa_class_mask) == 0); - - CFRetain(obj); - testassert(ISA(obj) == isa); - testassert([obj retainCount] == 2); - [obj retain]; - testassert(ISA(obj) == isa); - testassert([obj retainCount] == 3); - CFRelease(obj); - testassert(ISA(obj) == isa); - testassert([obj retainCount] == 2); - [obj release]; - testassert(ISA(obj) == isa); - testassert([obj retainCount] == 1); -} - - -#if ! SUPPORT_NONPOINTER_ISA - -int main() -{ - testprintf("Isa with index\n"); - id index_o = [NSObject new]; - check_unindexed(index_o, [NSObject class]); - - // These variables DO exist even without non-pointer isa support - testassert(dlsym(RTLD_DEFAULT, "objc_debug_isa_class_mask")); - testassert(dlsym(RTLD_DEFAULT, "objc_debug_isa_magic_mask")); - testassert(dlsym(RTLD_DEFAULT, "objc_debug_isa_magic_value")); - - succeed(__FILE__); -} - -#else -// SUPPORT_NONPOINTER_ISA - -void check_indexed(id obj, Class cls) -{ - testassert(object_getClass(obj) == cls); - testassert(INDEXED(obj)); - - uintptr_t isa = ISA(obj); - testassert((Class)(isa & objc_debug_isa_class_mask) == cls); - testassert((Class)(isa & ~objc_debug_isa_class_mask) != 0); - testassert((isa & objc_debug_isa_magic_mask) == objc_debug_isa_magic_value); - - CFRetain(obj); - testassert(ISA(obj) == isa + RC_ONE); - testassert([obj retainCount] == 2); - [obj retain]; - testassert(ISA(obj) == isa + RC_ONE*2); - testassert([obj retainCount] == 3); - CFRelease(obj); - testassert(ISA(obj) == isa + RC_ONE); - testassert([obj retainCount] == 2); - [obj release]; - testassert(ISA(obj) == isa); - testassert([obj retainCount] == 1); -} - - -@interface OS_object <NSObject> -+(id)new; -@end - -@interface Fake_OS_object : NSObject { - int refcnt; - int xref_cnt; -} -@end - -@implementation Fake_OS_object -+(void)initialize { - static bool initialized; - if (!initialized) { - initialized = true; - testprintf("Indexed during +initialize\n"); - testassert(INDEXED(self)); - id o = [Fake_OS_object new]; - check_indexed(o, self); - [o release]; - } -} -@end - -@interface Sub_OS_object : OS_object @end - -@implementation Sub_OS_object -@end - - - -int main() -{ - uintptr_t isa; - - testprintf("Isa with index\n"); - id index_o = [Fake_OS_object new]; - check_indexed(index_o, [Fake_OS_object class]); - - testprintf("Weakly referenced\n"); - isa = ISA(index_o); - id weak; - objc_storeWeak(&weak, index_o); - testassert(__builtin_popcountl(isa ^ ISA(index_o)) == 1); - - testprintf("Has associated references\n"); - id assoc = @"thing"; - isa = ISA(index_o); - objc_setAssociatedObject(index_o, assoc, assoc, OBJC_ASSOCIATION_ASSIGN); - testassert(__builtin_popcountl(isa ^ ISA(index_o)) == 1); - - - testprintf("Isa without index\n"); - id unindex_o = [OS_object new]; - check_unindexed(unindex_o, [OS_object class]); - - - id buf[4]; - id bufo = (id)buf; - - testprintf("Change isa 0 -> unindexed\n"); - bzero(buf, sizeof(buf)); - object_setClass(bufo, [OS_object class]); - check_unindexed(bufo, [OS_object class]); - - testprintf("Change isa 0 -> indexed\n"); - bzero(buf, sizeof(buf)); - object_setClass(bufo, [NSObject class]); - check_indexed(bufo, [NSObject class]); - - testprintf("Change isa indexed -> indexed\n"); - testassert(INDEXED(bufo)); - _objc_rootRetain(bufo); - testassert(_objc_rootRetainCount(bufo) == 2); - object_setClass(bufo, [Fake_OS_object class]); - testassert(_objc_rootRetainCount(bufo) == 2); - _objc_rootRelease(bufo); - testassert(_objc_rootRetainCount(bufo) == 1); - check_indexed(bufo, [Fake_OS_object class]); - - testprintf("Change isa indexed -> unindexed\n"); - // Retain count must be preserved. - // Use root* to avoid OS_object's overrides. - testassert(INDEXED(bufo)); - _objc_rootRetain(bufo); - testassert(_objc_rootRetainCount(bufo) == 2); - object_setClass(bufo, [OS_object class]); - testassert(_objc_rootRetainCount(bufo) == 2); - _objc_rootRelease(bufo); - testassert(_objc_rootRetainCount(bufo) == 1); - check_unindexed(bufo, [OS_object class]); - - testprintf("Change isa unindexed -> indexed (doesn't happen)\n"); - testassert(!INDEXED(bufo)); - _objc_rootRetain(bufo); - testassert(_objc_rootRetainCount(bufo) == 2); - object_setClass(bufo, [Fake_OS_object class]); - testassert(_objc_rootRetainCount(bufo) == 2); - _objc_rootRelease(bufo); - testassert(_objc_rootRetainCount(bufo) == 1); - check_unindexed(bufo, [Fake_OS_object class]); - - testprintf("Change isa unindexed -> unindexed\n"); - testassert(!INDEXED(bufo)); - _objc_rootRetain(bufo); - testassert(_objc_rootRetainCount(bufo) == 2); - object_setClass(bufo, [Sub_OS_object class]); - testassert(_objc_rootRetainCount(bufo) == 2); - _objc_rootRelease(bufo); - testassert(_objc_rootRetainCount(bufo) == 1); - check_unindexed(bufo, [Sub_OS_object class]); - - - succeed(__FILE__); -} - -// SUPPORT_NONPOINTER_ISA -#endif - -// __OBJC2__ -#endif diff --git a/objc/objc-runtime/test/nopool.m b/objc/objc-runtime/test/nopool.m deleted file mode 100644 index 57e8fcb..0000000 --- a/objc/objc-runtime/test/nopool.m +++ /dev/null @@ -1,38 +0,0 @@ -// TEST_CONFIG MEM=mrc - -#include "test.h" -#include "testroot.i" - -@implementation TestRoot (Loader) -+(void)load -{ - [[TestRoot new] autorelease]; - testassert(TestRootAutorelease == 1); - testassert(TestRootDealloc == 0); -} -@end - -int main() -{ - // +load's autoreleased object should have deallocated - testassert(TestRootDealloc == 1); - - [[TestRoot new] autorelease]; - testassert(TestRootAutorelease == 2); - - objc_autoreleasePoolPop(objc_autoreleasePoolPush()); - - [[TestRoot new] autorelease]; - testassert(TestRootAutorelease == 3); - - testonthread(^{ - [[TestRoot new] autorelease]; - testassert(TestRootAutorelease == 4); - testassert(TestRootDealloc == 1); - }); - - // thread's autoreleased object should have deallocated - testassert(TestRootDealloc == 2); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/nscdtors.mm b/objc/objc-runtime/test/nscdtors.mm deleted file mode 100644 index 876f6b0..0000000 --- a/objc/objc-runtime/test/nscdtors.mm +++ /dev/null @@ -1,6 +0,0 @@ -// TEST_CONFIG -// test cdtors, with NSObject instead of TestRoot as the root class - -#define USE_FOUNDATION 1 -#include "cdtors.mm" - diff --git a/objc/objc-runtime/test/nsexc.m b/objc/objc-runtime/test/nsexc.m deleted file mode 100644 index 4884345..0000000 --- a/objc/objc-runtime/test/nsexc.m +++ /dev/null @@ -1,21 +0,0 @@ -/* -need exception-safe ARC for exception deallocation tests -TEST_CFLAGS -fobjc-arc-exceptions -framework Foundation - -llvm-gcc unavoidably warns about our deliberately out-of-order handlers - -TEST_BUILD_OUTPUT -In file included from .* -.*exc.m: In function .* -.*exc.m:\d+: warning: exception of type .* will be caught -.*exc.m:\d+: warning: by earlier handler for .* -.*exc.m:\d+: warning: exception of type .* will be caught -.*exc.m:\d+: warning: by earlier handler for .* -.*exc.m:\d+: warning: exception of type .* will be caught -.*exc.m:\d+: warning: by earlier handler for .* -OR -END -*/ - -#define USE_FOUNDATION 1 -#include "exc.m" diff --git a/objc/objc-runtime/test/nsobject.m b/objc/objc-runtime/test/nsobject.m deleted file mode 100644 index 4a79f32..0000000 --- a/objc/objc-runtime/test/nsobject.m +++ /dev/null @@ -1,114 +0,0 @@ -// TEST_CONFIG MEM=mrc,gc - -#include "test.h" - -#import <Foundation/NSObject.h> - -@interface Sub : NSObject @end -@implementation Sub -+(id)allocWithZone:(NSZone *)zone { - testprintf("in +[Sub alloc]\n"); - return [super allocWithZone:zone]; - } --(void)dealloc { - testprintf("in -[Sub dealloc]\n"); - [super dealloc]; -} -@end - - -// These declarations and definitions can be used -// to check the compile-time type of an object. -@interface NSObject (Checker) -// fixme this isn't actually enforced -+(void)NSObjectInstance __attribute__((unavailable)); -@end -@implementation NSObject (Checker) --(void)NSObjectInstance { } -+(void)NSObjectClass { } -@end -@interface Sub (Checker) --(void)NSObjectInstance __attribute__((unavailable)); -+(void)NSObjectClass __attribute__((unavailable)); -@end -@implementation Sub (Checker) --(void)SubInstance { } -+(void)SubClass { } -@end - -int main() -{ - PUSH_POOL { - [[Sub new] autorelease]; - } POP_POOL; - - // Verify that dot syntax on class objects works with some instance methods - // (void)NSObject.self; fixme - (void)NSObject.class; - (void)NSObject.superclass; - (void)NSObject.hash; - (void)NSObject.description; - (void)NSObject.debugDescription; - - // Verify that some methods return the correct type. - Class cls; - NSObject *nsobject = nil; - Sub *subobject = nil; - - cls = [NSObject self]; - cls = [Sub self]; - nsobject = [nsobject self]; - subobject = [subobject self]; - [[NSObject self] NSObjectClass]; - [[nsobject self] NSObjectInstance]; - [[Sub self] SubClass]; - [[subobject self] SubInstance]; - - // fixme - // cls = NSObject.self; - // cls = Sub.self; - // [NSObject.self NSObjectClass]; - // [nsobject.self NSObjectInstance]; - // [Sub.self SubClass]; - // [subobject.self SubInstance]; - - cls = [NSObject class]; - cls = [nsobject class]; - cls = [Sub class]; - cls = [subobject class]; - [[NSObject class] NSObjectClass]; - [[nsobject class] NSObjectClass]; - [[Sub class] SubClass]; - [[subobject class] SubClass]; - - cls = NSObject.class; - cls = nsobject.class; - cls = Sub.class; - cls = subobject.class; - [NSObject.class NSObjectClass]; - [nsobject.class NSObjectClass]; - [Sub.class SubClass]; - [subobject.class SubClass]; - - - cls = [NSObject superclass]; - cls = [nsobject superclass]; - cls = [Sub superclass]; - cls = [subobject superclass]; - [[NSObject superclass] NSObjectClass]; - [[nsobject superclass] NSObjectClass]; - [[Sub superclass] NSObjectClass]; - [[subobject superclass] NSObjectClass]; - - cls = NSObject.superclass; - cls = nsobject.superclass; - cls = Sub.superclass; - cls = subobject.superclass; - [NSObject.superclass NSObjectClass]; - [nsobject.superclass NSObjectClass]; - [Sub.superclass NSObjectClass]; - [subobject.superclass NSObjectClass]; - - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/nsprotocol.m b/objc/objc-runtime/test/nsprotocol.m deleted file mode 100644 index 8305cc8..0000000 --- a/objc/objc-runtime/test/nsprotocol.m +++ /dev/null @@ -1,47 +0,0 @@ -// TEST_CONFIG - -#include "test.h" - -#if __OBJC2__ - -#include <objc/Protocol.h> - -int main() -{ - // Class Protocol is always a subclass of NSObject - - testassert(objc_getClass("NSObject")); - - Class cls = objc_getClass("Protocol"); - testassert(class_getInstanceMethod(cls, sel_registerName("isProxy"))); - testassert(class_getSuperclass(cls) == objc_getClass("NSObject")); - - succeed(__FILE__); -} - -#else - -#include <dlfcn.h> -#include <objc/Protocol.h> - -int main() -{ - // Class Protocol is never a subclass of NSObject - // CoreFoundation adds NSObject methods to Protocol when it loads - - testassert(objc_getClass("NSObject")); - - Class cls = objc_getClass("Protocol"); - testassert(!class_getInstanceMethod(cls, sel_registerName("isProxy"))); - testassert(class_getSuperclass(cls) != objc_getClass("NSObject")); - - void *dl = dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", RTLD_LAZY); - testassert(dl); - - testassert(class_getInstanceMethod(cls, sel_registerName("isProxy"))); - testassert(class_getSuperclass(cls) != objc_getClass("NSObject")); - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/objectCopy.m b/objc/objc-runtime/test/objectCopy.m deleted file mode 100644 index 275466c..0000000 --- a/objc/objc-runtime/test/objectCopy.m +++ /dev/null @@ -1,37 +0,0 @@ -// TEST_CONFIG MEM=mrc,gc - -#include "test.h" -#include <objc/NSObject.h> - -@interface Test : NSObject { -@public - char bytes[32-sizeof(void*)]; -} -@end -@implementation Test -@end - - -int main() -{ - Test *o0 = [Test new]; - [o0 retain]; - Test *o1 = class_createInstance([Test class], 32); - [o1 retain]; - id o2 = object_copy(o0, 0); - id o3 = object_copy(o1, 0); - id o4 = object_copy(o1, 32); - testassert(malloc_size(o0) == 32); - testassert(malloc_size(o1) == 64); - testassert(malloc_size(o2) == 32); - testassert(malloc_size(o3) == 32); - testassert(malloc_size(o4) == 64); - if (!objc_collecting_enabled()) { - testassert([o0 retainCount] == 2); - testassert([o1 retainCount] == 2); - testassert([o2 retainCount] == 1); - testassert([o3 retainCount] == 1); - testassert([o4 retainCount] == 1); - } - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/property.m b/objc/objc-runtime/test/property.m deleted file mode 100644 index fbcabdd..0000000 --- a/objc/objc-runtime/test/property.m +++ /dev/null @@ -1,65 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <stdint.h> -#include <string.h> -#include <objc/objc-runtime.h> - -@interface Super : TestRoot { - @public - char superIvar; -} - -@property(readonly) char superProp; -@end - -@implementation Super -@synthesize superProp = superIvar; -@end - - -@interface Sub : Super { - @public - uintptr_t subIvar; -} -@property(readonly) uintptr_t subProp; -@end - -@implementation Sub -@synthesize subProp = subIvar; -@end - - -int main() -{ - /* - Runtime layout of Sub: - [0] isa - [1] superIvar - [2] subIvar - */ - - objc_property_t prop; - - prop = class_getProperty([Sub class], "subProp"); - testassert(prop); - - prop = class_getProperty([Super class], "superProp"); - testassert(prop); - testassert(prop == class_getProperty([Sub class], "superProp")); - - prop = class_getProperty([Super class], "subProp"); - testassert(!prop); - - prop = class_getProperty(object_getClass([Sub class]), "subProp"); - testassert(!prop); - - - testassert(NULL == class_getProperty(NULL, "foo")); - testassert(NULL == class_getProperty([Sub class], NULL)); - testassert(NULL == class_getProperty(NULL, NULL)); - - succeed(__FILE__); - return 0; -} diff --git a/objc/objc-runtime/test/propertyDesc.m b/objc/objc-runtime/test/propertyDesc.m deleted file mode 100644 index 2a81655..0000000 --- a/objc/objc-runtime/test/propertyDesc.m +++ /dev/null @@ -1,323 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <stdint.h> -#include <string.h> -#include <objc/runtime.h> - -struct objc_property { - const char *name; - const char *attr; -}; - -#define checkattrlist(attrs, attrcount, target) \ - do { \ - if (target > 0) { \ - testassert(attrs); \ - testassert(attrcount == target); \ - testassert(malloc_size(attrs) >= \ - (1+target) * sizeof(objc_property_attribute_t)); \ - testassert(attrs[target].name == NULL); \ - testassert(attrs[target].value == NULL); \ - } else { \ - testassert(!attrs); \ - testassert(attrcount == 0); \ - } \ - } while (0) - -#define checkattr(attrs, i, n, v) \ - do { \ - char *attrsstart = (char *)attrs; \ - char *attrsend = (char *)attrs + malloc_size(attrs); \ - testassert((char*)(attrs+i+1) <= attrsend); \ - testassert(attrs[i].name >= attrsstart); \ - testassert(attrs[i].value >= attrsstart); \ - testassert(attrs[i].name + strlen(attrs[i].name) + 1 <= attrsend); \ - testassert(attrs[i].value + strlen(attrs[i].value) + 1 <= attrsend); \ - if (n) testassert(0 == strcmp(attrs[i].name, n)); \ - else testassert(attrs[i].name == NULL); \ - if (v) testassert(0 == strcmp(attrs[i].value, v)); \ - else testassert(attrs[i].value == NULL); \ - } while (0) - -int main() -{ - char *value; - objc_property_attribute_t *attrs; - unsigned int attrcount; - - // STRING TO ATTRIBUTE LIST (property_copyAttributeList) - - struct objc_property prop; - prop.name = "test"; - - // null property - attrcount = 42; - attrs = property_copyAttributeList(NULL, &attrcount); - testassert(!attrs); - testassert(attrcount == 0); - attrs = property_copyAttributeList(NULL, NULL); - testassert(!attrs); - - // null attributes - attrcount = 42; - prop.attr = NULL; - attrs = property_copyAttributeList(&prop, &attrcount); - checkattrlist(attrs, attrcount, 0); - attrs = property_copyAttributeList(&prop, NULL); - testassert(!attrs); - - // empty attributes - attrcount = 42; - prop.attr = ""; - attrs = property_copyAttributeList(&prop, &attrcount); - checkattrlist(attrs, attrcount, 0); - attrs = property_copyAttributeList(&prop, NULL); - testassert(!attrs); - - // commas only - attrcount = 42; - prop.attr = ",,,"; - attrs = property_copyAttributeList(&prop, &attrcount); - checkattrlist(attrs, attrcount, 0); - attrs = property_copyAttributeList(&prop, NULL); - testassert(!attrs); - - // long and short names, with and without values - attrcount = 42; - prop.attr = "?XX,',\"?!?!\"YY,\"''''\""; - attrs = property_copyAttributeList(&prop, &attrcount); - checkattrlist(attrs, attrcount, 4); - checkattr(attrs, 0, "?", "XX"); - checkattr(attrs, 1, "'", ""); - checkattr(attrs, 2, "?!?!", "YY"); - checkattr(attrs, 3, "''''", ""); - free(attrs); - - // all recognized attributes simultaneously, values with quotes - attrcount = 42; - prop.attr = "T11,V2222,S333333\",G\"44444444,W,P,D,R,N,C,&"; - attrs = property_copyAttributeList(&prop, &attrcount); - checkattrlist(attrs, attrcount, 11); - checkattr(attrs, 0, "T", "11"); - checkattr(attrs, 1, "V", "2222"); - checkattr(attrs, 2, "S", "333333\""); - checkattr(attrs, 3, "G", "\"44444444"); - checkattr(attrs, 4, "W", ""); - checkattr(attrs, 5, "P", ""); - checkattr(attrs, 6, "D", ""); - checkattr(attrs, 7, "R", ""); - checkattr(attrs, 8, "N", ""); - checkattr(attrs, 9, "C", ""); - checkattr(attrs,10, "&", ""); - free(attrs); - - // kitchen sink - attrcount = 42; - prop.attr = "W,T11,P,?XX,D,V2222,R,',N,S333333\",C,\"?!?!\"YY,&,G\"44444444,\"''''\""; - attrs = property_copyAttributeList(&prop, &attrcount); - checkattrlist(attrs, attrcount, 15); - checkattr(attrs, 0, "W", ""); - checkattr(attrs, 1, "T", "11"); - checkattr(attrs, 2, "P", ""); - checkattr(attrs, 3, "?", "XX"); - checkattr(attrs, 4, "D", ""); - checkattr(attrs, 5, "V", "2222"); - checkattr(attrs, 6, "R", ""); - checkattr(attrs, 7, "'", ""); - checkattr(attrs, 8, "N", ""); - checkattr(attrs, 9, "S", "333333\""); - checkattr(attrs,10, "C", ""); - checkattr(attrs,11, "?!?!", "YY"); - checkattr(attrs,12, "&", ""); - checkattr(attrs,13, "G", "\"44444444"); - checkattr(attrs,14, "''''", ""); - free(attrs); - - // SEARCH ATTRIBUTE LIST (property_copyAttributeValue) - - // null property, null name, empty name - value = property_copyAttributeValue(NULL, NULL); - testassert(!value); - value = property_copyAttributeValue(NULL, "foo"); - testassert(!value); - value = property_copyAttributeValue(NULL, ""); - testassert(!value); - value = property_copyAttributeValue(&prop, NULL); - testassert(!value); - value = property_copyAttributeValue(&prop, ""); - testassert(!value); - - // null attributes, empty attributes - prop.attr = NULL; - value = property_copyAttributeValue(&prop, "foo"); - testassert(!value); - prop.attr = ""; - value = property_copyAttributeValue(&prop, "foo"); - testassert(!value); - - // long and short names, with and without values - prop.attr = "?XX,',\"?!?!\"YY,\"''''\""; - value = property_copyAttributeValue(&prop, "missing"); - testassert(!value); - value = property_copyAttributeValue(&prop, "X"); - testassert(!value); - value = property_copyAttributeValue(&prop, "\""); - testassert(!value); - value = property_copyAttributeValue(&prop, "'''"); - testassert(!value); - value = property_copyAttributeValue(&prop, "'''''"); - testassert(!value); - - value = property_copyAttributeValue(&prop, "?"); - testassert(0 == strcmp(value, "XX")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "'"); - testassert(0 == strcmp(value, "")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "?!?!"); - testassert(0 == strcmp(value, "YY")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "''''"); - testassert(0 == strcmp(value, "")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - - // all recognized attributes simultaneously, values with quotes - prop.attr = "T11,V2222,S333333\",G\"44444444,W,P,D,R,N,C,&"; - value = property_copyAttributeValue(&prop, "T"); - testassert(0 == strcmp(value, "11")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "V"); - testassert(0 == strcmp(value, "2222")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "S"); - testassert(0 == strcmp(value, "333333\"")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "G"); - testassert(0 == strcmp(value, "\"44444444")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "W"); - testassert(0 == strcmp(value, "")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "P"); - testassert(0 == strcmp(value, "")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "D"); - testassert(0 == strcmp(value, "")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "R"); - testassert(0 == strcmp(value, "")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "N"); - testassert(0 == strcmp(value, "")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "C"); - testassert(0 == strcmp(value, "")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - value = property_copyAttributeValue(&prop, "&"); - testassert(0 == strcmp(value, "")); - testassert(malloc_size(value) >= 1 + strlen(value)); - free(value); - - // ATTRIBUTE LIST TO STRING (class_addProperty) - - BOOL ok; - objc_property_t prop2; - - // null name - ok = class_addProperty([TestRoot class], NULL, (objc_property_attribute_t *)1, 1); - testassert(!ok); - - // null description - ok = class_addProperty([TestRoot class], "test-null-desc", NULL, 0); - testassert(ok); - prop2 = class_getProperty([TestRoot class], "test-null-desc"); - testassert(prop2); - testassert(0 == strcmp(property_getAttributes(prop2), "")); - - // empty description - ok = class_addProperty([TestRoot class], "test-empty-desc", (objc_property_attribute_t*)1, 0); - testassert(ok); - prop2 = class_getProperty([TestRoot class], "test-empty-desc"); - testassert(prop2); - testassert(0 == strcmp(property_getAttributes(prop2), "")); - - // long and short names, with and without values - objc_property_attribute_t attrs2[] = { - { "!", NULL }, - { "?", "XX" }, - { "'", "" }, - { "?!?!", "YY" }, - { "''''", "" } - }; - ok = class_addProperty([TestRoot class], "test-unrecognized", attrs2, 5); - testassert(ok); - prop2 = class_getProperty([TestRoot class], "test-unrecognized"); - testassert(prop2); - testassert(0 == strcmp(property_getAttributes(prop2), "?XX,',\"?!?!\"YY,\"''''\"")); - - // all recognized attributes simultaneously, values with quotes - objc_property_attribute_t attrs3[] = { - { "&", "" }, - { "C", "" }, - { "N", "" }, - { "R", "" }, - { "D", "" }, - { "P", "" }, - { "W", "" }, - { "G", "\"44444444" }, - { "S", "333333\"" }, - { "V", "2222" }, - { "T", "11" }, - }; - ok = class_addProperty([TestRoot class], "test-recognized", attrs3, 11); - testassert(ok); - prop2 = class_getProperty([TestRoot class], "test-recognized"); - testassert(prop2); - testassert(0 == strcmp(property_getAttributes(prop2), - "&,C,N,R,D,P,W,G\"44444444,S333333\",V2222,T11")); - - // kitchen sink - objc_property_attribute_t attrs4[] = { - { "&", "" }, - { "C", "" }, - { "N", "" }, - { "R", "" }, - { "D", "" }, - { "P", "" }, - { "W", "" }, - { "!", NULL }, - { "G", "\"44444444" }, - { "S", "333333\"" }, - { "V", "2222" }, - { "T", "11" }, - { "?", "XX" }, - { "'", "" }, - { "?!?!", "YY" }, - { "''''", "" } - }; - ok = class_addProperty([TestRoot class], "test-sink", attrs4, 16); - testassert(ok); - prop2 = class_getProperty([TestRoot class], "test-sink"); - testassert(prop2); - testassert(0 == strcmp(property_getAttributes(prop2), - "&,C,N,R,D,P,W,G\"44444444,S333333\",V2222,T11," - "?XX,',\"?!?!\"YY,\"''''\"")); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/protocol.m b/objc/objc-runtime/test/protocol.m deleted file mode 100644 index c68bd33..0000000 --- a/objc/objc-runtime/test/protocol.m +++ /dev/null @@ -1,320 +0,0 @@ -// TEST_CFLAGS -framework Foundation -Wno-deprecated-declarations -// need Foundation to get NSObject compatibility additions for class Protocol -// because ARC calls [protocol retain] - -#include "test.h" -#include "testroot.i" -#include <string.h> -#include <objc/runtime.h> -#include <objc/objc-internal.h> - -#if !__OBJC2__ -#include <objc/Protocol.h> -#endif - -@protocol Proto1 -+(id)proto1ClassMethod; --(id)proto1InstanceMethod; -@end - -@protocol Proto2 -+(id)proto2ClassMethod; --(id)proto2InstanceMethod; -@end - -@protocol Proto3 <Proto2> -+(id)proto3ClassMethod; --(id)proto3InstanceMethod; -@end - -@protocol Proto4 -@property int i; -@end - -// Force some of Proto5's selectors out of address order rdar://10582325 -SEL fn(int x) { if (x) return @selector(m12:); else return @selector(m22:); } - -// This declaration order deliberately looks weird because it determines the -// selector address order on some architectures rdar://10582325 -@protocol Proto5 --(id)m11:(id<Proto1>)a; --(void)m12:(id<Proto1>)a; --(int)m13:(id<Proto1>)a; -+(void)m22:(TestRoot<Proto1>*)a; -+(int)m23:(TestRoot<Proto1>*)a; -+(TestRoot*)m21:(TestRoot<Proto1>*)a; -@optional --(id(^)(id))m31:(id<Proto1>(^)(id<Proto1>))a; --(void)m32:(id<Proto1>(^)(id<Proto1>))a; --(int)m33:(id<Proto1>(^)(id<Proto1>))a; -+(void)m42:(TestRoot<Proto1>*(^)(TestRoot<Proto1>*))a; -+(int)m43:(TestRoot<Proto1>*(^)(TestRoot<Proto1>*))a; -+(TestRoot*(^)(TestRoot*))m41:(TestRoot<Proto1>*(^)(TestRoot<Proto1>*))a; -@end - -@protocol Proto6 <Proto5> -@optional -+(TestRoot*(^)(TestRoot*))n41:(TestRoot<Proto1>*(^)(TestRoot<Proto1>*))a; -@end - -@protocol ProtoEmpty -@end - -#if __OBJC2__ -#define TEST_SWIFT 1 -#define SwiftV1MangledName "_TtP6Module15SwiftV1Protocol_" -#endif - -#if TEST_SWIFT -__attribute__((objc_runtime_name(SwiftV1MangledName))) -@protocol SwiftV1Protocol -@end -#endif - -@interface Super : TestRoot <Proto1> @end -@implementation Super -+(id)proto1ClassMethod { return self; } --(id)proto1InstanceMethod { return self; } -@end - -@interface SubNoProtocols : Super @end -@implementation SubNoProtocols @end - -@interface SuperNoProtocols : TestRoot @end -@implementation SuperNoProtocols -@end - -@interface SubProp : Super <Proto4> { int i; } @end -@implementation SubProp -@synthesize i; -@end - - -int main() -{ - Class cls; - Protocol * __unsafe_unretained *list; - Protocol *protocol, *empty; -#if !__OBJC2__ - struct objc_method_description *desc; -#endif - struct objc_method_description desc2; - objc_property_t *proplist; - unsigned int count; - - protocol = @protocol(Proto3); - empty = @protocol(ProtoEmpty); - testassert(protocol); - testassert(empty); - -#if !__OBJC2__ - testassert([protocol isKindOf:[Protocol class]]); - testassert([empty isKindOf:[Protocol class]]); - testassert(0 == strcmp([protocol name], "Proto3")); - testassert(0 == strcmp([empty name], "ProtoEmpty")); -#endif - testassert(0 == strcmp(protocol_getName(protocol), "Proto3")); - testassert(0 == strcmp(protocol_getName(empty), "ProtoEmpty")); - - testassert(class_conformsToProtocol([Super class], @protocol(Proto1))); - testassert(!class_conformsToProtocol([SubProp class], @protocol(Proto1))); - testassert(class_conformsToProtocol([SubProp class], @protocol(Proto4))); - testassert(!class_conformsToProtocol([SubProp class], @protocol(Proto3))); - testassert(!class_conformsToProtocol([Super class], @protocol(Proto3))); - - testassert(!protocol_conformsToProtocol(@protocol(Proto1), @protocol(Proto2))); - testassert(protocol_conformsToProtocol(@protocol(Proto3), @protocol(Proto2))); - testassert(!protocol_conformsToProtocol(@protocol(Proto2), @protocol(Proto3))); - -#if !__OBJC2__ - testassert([@protocol(Proto1) isEqual:@protocol(Proto1)]); - testassert(! [@protocol(Proto1) isEqual:@protocol(Proto2)]); -#endif - testassert(protocol_isEqual(@protocol(Proto1), @protocol(Proto1))); - testassert(! protocol_isEqual(@protocol(Proto1), @protocol(Proto2))); - -#if !__OBJC2__ - desc = [protocol descriptionForInstanceMethod:@selector(proto3InstanceMethod)]; - testassert(desc); - testassert(desc->name == @selector(proto3InstanceMethod)); - desc = [protocol descriptionForClassMethod:@selector(proto3ClassMethod)]; - testassert(desc); - testassert(desc->name == @selector(proto3ClassMethod)); - desc = [protocol descriptionForClassMethod:@selector(proto2ClassMethod)]; - testassert(desc); - testassert(desc->name == @selector(proto2ClassMethod)); - - desc = [protocol descriptionForInstanceMethod:@selector(proto3ClassMethod)]; - testassert(!desc); - desc = [protocol descriptionForClassMethod:@selector(proto3InstanceMethod)]; - testassert(!desc); - desc = [empty descriptionForInstanceMethod:@selector(proto3ClassMethod)]; - testassert(!desc); - desc = [empty descriptionForClassMethod:@selector(proto3InstanceMethod)]; - testassert(!desc); -#endif - desc2 = protocol_getMethodDescription(protocol, @selector(proto3InstanceMethod), YES, YES); - testassert(desc2.name && desc2.types); - testassert(desc2.name == @selector(proto3InstanceMethod)); - desc2 = protocol_getMethodDescription(protocol, @selector(proto3ClassMethod), YES, NO); - testassert(desc2.name && desc2.types); - testassert(desc2.name == @selector(proto3ClassMethod)); - desc2 = protocol_getMethodDescription(protocol, @selector(proto2ClassMethod), YES, NO); - testassert(desc2.name && desc2.types); - testassert(desc2.name == @selector(proto2ClassMethod)); - - desc2 = protocol_getMethodDescription(protocol, @selector(proto3ClassMethod), YES, YES); - testassert(!desc2.name && !desc2.types); - desc2 = protocol_getMethodDescription(protocol, @selector(proto3InstanceMethod), YES, NO); - testassert(!desc2.name && !desc2.types); - desc2 = protocol_getMethodDescription(empty, @selector(proto3ClassMethod), YES, YES); - testassert(!desc2.name && !desc2.types); - desc2 = protocol_getMethodDescription(empty, @selector(proto3InstanceMethod), YES, NO); - testassert(!desc2.name && !desc2.types); - - count = 100; - list = protocol_copyProtocolList(@protocol(Proto2), &count); - testassert(!list); - testassert(count == 0); - count = 100; - list = protocol_copyProtocolList(@protocol(Proto3), &count); - testassert(list); - testassert(count == 1); - testassert(protocol_isEqual(list[0], @protocol(Proto2))); - testassert(!list[1]); - free(list); - - count = 100; - cls = objc_getClass("Super"); - testassert(cls); - list = class_copyProtocolList(cls, &count); - testassert(list); - testassert(list[count] == NULL); - testassert(count == 1); - testassert(0 == strcmp(protocol_getName(list[0]), "Proto1")); - free(list); - - count = 100; - cls = objc_getClass("SuperNoProtocols"); - testassert(cls); - list = class_copyProtocolList(cls, &count); - testassert(!list); - testassert(count == 0); - - count = 100; - cls = objc_getClass("SubNoProtocols"); - testassert(cls); - list = class_copyProtocolList(cls, &count); - testassert(!list); - testassert(count == 0); - - - cls = objc_getClass("SuperNoProtocols"); - testassert(cls); - list = class_copyProtocolList(cls, NULL); - testassert(!list); - - cls = objc_getClass("Super"); - testassert(cls); - list = class_copyProtocolList(cls, NULL); - testassert(list); - free(list); - - count = 100; - list = class_copyProtocolList(NULL, &count); - testassert(!list); - testassert(count == 0); - - - // Check property added by protocol - cls = objc_getClass("SubProp"); - testassert(cls); - - count = 100; - list = class_copyProtocolList(cls, &count); - testassert(list); - testassert(count == 1); - testassert(0 == strcmp(protocol_getName(list[0]), "Proto4")); - testassert(list[1] == NULL); - free(list); - - count = 100; - proplist = class_copyPropertyList(cls, &count); - testassert(proplist); - testassert(count == 1); - testassert(0 == strcmp(property_getName(proplist[0]), "i")); - testassert(proplist[1] == NULL); - free(proplist); - - // Check extended type encodings - testassert(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(DoesNotExist), true, true) == NULL); - testassert(_protocol_getMethodTypeEncoding(NULL, @selector(m11), true, true) == NULL); - testassert(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m11), true, false) == NULL); - testassert(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m11), false, false) == NULL); - testassert(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m11), false, true) == NULL); - testassert(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m21), true, true) == NULL); -#if __LP64__ - const char *types11 = "@24@0:8@\"<Proto1>\"16"; - const char *types12 = "v24@0:8@\"<Proto1>\"16"; - const char *types13 = "i24@0:8@\"<Proto1>\"16"; - const char *types21 = "@\"TestRoot\"24@0:8@\"TestRoot<Proto1>\"16"; - const char *types22 = "v24@0:8@\"TestRoot<Proto1>\"16"; - const char *types23 = "i24@0:8@\"TestRoot<Proto1>\"16"; - const char *types31 = "@?<@@?@>24@0:8@?<@\"<Proto1>\"@?@\"<Proto1>\">16"; - const char *types32 = "v24@0:8@?<@\"<Proto1>\"@?@\"<Proto1>\">16"; - const char *types33 = "i24@0:8@?<@\"<Proto1>\"@?@\"<Proto1>\">16"; - const char *types41 = "@?<@\"TestRoot\"@?@\"TestRoot\">24@0:8@?<@\"TestRoot<Proto1>\"@?@\"TestRoot<Proto1>\">16"; - const char *types42 = "v24@0:8@?<@\"TestRoot<Proto1>\"@?@\"TestRoot<Proto1>\">16"; - const char *types43 = "i24@0:8@?<@\"TestRoot<Proto1>\"@?@\"TestRoot<Proto1>\">16"; -#else - const char *types11 = "@12@0:4@\"<Proto1>\"8"; - const char *types12 = "v12@0:4@\"<Proto1>\"8"; - const char *types13 = "i12@0:4@\"<Proto1>\"8"; - const char *types21 = "@\"TestRoot\"12@0:4@\"TestRoot<Proto1>\"8"; - const char *types22 = "v12@0:4@\"TestRoot<Proto1>\"8"; - const char *types23 = "i12@0:4@\"TestRoot<Proto1>\"8"; - const char *types31 = "@?<@@?@>12@0:4@?<@\"<Proto1>\"@?@\"<Proto1>\">8"; - const char *types32 = "v12@0:4@?<@\"<Proto1>\"@?@\"<Proto1>\">8"; - const char *types33 = "i12@0:4@?<@\"<Proto1>\"@?@\"<Proto1>\">8"; - const char *types41 = "@?<@\"TestRoot\"@?@\"TestRoot\">12@0:4@?<@\"TestRoot<Proto1>\"@?@\"TestRoot<Proto1>\">8"; - const char *types42 = "v12@0:4@?<@\"TestRoot<Proto1>\"@?@\"TestRoot<Proto1>\">8"; - const char *types43 = "i12@0:4@?<@\"TestRoot<Proto1>\"@?@\"TestRoot<Proto1>\">8"; -#endif - - // Make sure some of Proto5's selectors are out of order rdar://10582325 - // These comparisons deliberately look weird because they determine the - // selector order on some architectures. - testassert(sel_registerName("m11:") > sel_registerName("m12:") || - sel_registerName("m21:") > sel_registerName("m22:") || - sel_registerName("m32:") < sel_registerName("m31:") || - sel_registerName("m42:") < sel_registerName("m41:") ); - - if (!_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m11:), true, true)) { - fail("rdar://10492418 extended type encodings not present (is compiler old?)"); - } else { - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m11:), true, true), types11)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m12:), true, true), types12)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m13:), true, true), types13)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m21:), true, false), types21)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m22:), true, false), types22)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m23:), true, false), types23)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m31:), false, true), types31)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m32:), false, true), types32)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m33:), false, true), types33)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m41:), false, false), types41)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m42:), false, false), types42)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto5), @selector(m43:), false, false), types43)); - - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto6), @selector(n41:), false, false), types41)); - testassert(0 == strcmp(_protocol_getMethodTypeEncoding(@protocol(Proto6), @selector(m41:), false, false), types41)); - } - -#if TEST_SWIFT - testassert(@protocol(SwiftV1Protocol) == objc_getProtocol("Module.SwiftV1Protocol")); - testassert(@protocol(SwiftV1Protocol) == objc_getProtocol(SwiftV1MangledName)); - testassert(0 == strcmp(protocol_getName(@protocol(SwiftV1Protocol)), "Module.SwiftV1Protocol")); - testassert(!objc_getProtocol("SwiftV1Protocol")); -#endif - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/protocol_copyMethodList.m b/objc/objc-runtime/test/protocol_copyMethodList.m deleted file mode 100644 index 53bf445..0000000 --- a/objc/objc-runtime/test/protocol_copyMethodList.m +++ /dev/null @@ -1,146 +0,0 @@ -// TEST_CFLAGS -framework Foundation -// need Foundation to get NSObject compatibility additions for class Protocol -// because ARC calls [protocol retain] - - -#include "test.h" -#include <malloc/malloc.h> -#include <objc/objc-runtime.h> - -@protocol SuperMethods -+(void)SuperMethodClass; -+(void)SuperMethodClass2; --(void)SuperMethodInstance; --(void)SuperMethodInstance2; -@end - -@protocol SubMethods -+(void)SubMethodClass; -+(void)SubMethodClass2; --(void)SubMethodInstance; --(void)SubMethodInstance2; -@end - -@protocol SuperOptionalMethods -@optional -+(void)SuperOptMethodClass; -+(void)SuperOptMethodClass2; --(void)SuperOptMethodInstance; --(void)SuperOptMethodInstance2; -@end - -@protocol SubOptionalMethods <SuperOptionalMethods> -@optional -+(void)SubOptMethodClass; -+(void)SubOptMethodClass2; --(void)SubOptMethodInstance; --(void)SubOptMethodInstance2; -@end - -@protocol NoMethods @end - -static int isNamed(struct objc_method_description m, const char *name) -{ - return (m.name == sel_registerName(name)); -} - -int main() -{ - struct objc_method_description *methods; - unsigned int count; - Protocol *proto; - - proto = @protocol(SubMethods); - testassert(proto); - - // Check required methods - count = 999; - methods = protocol_copyMethodDescriptionList(proto, YES, YES, &count); - testassert(methods); - testassert(count == 2); - testassert((isNamed(methods[0], "SubMethodInstance") && - isNamed(methods[1], "SubMethodInstance2")) - || - (isNamed(methods[1], "SubMethodInstance") && - isNamed(methods[0], "SubMethodInstance2"))); - free(methods); - - count = 999; - methods = protocol_copyMethodDescriptionList(proto, YES, NO, &count); - testassert(methods); - testassert(count == 2); - testassert((isNamed(methods[0], "SubMethodClass") && - isNamed(methods[1], "SubMethodClass2")) - || - (isNamed(methods[1], "SubMethodClass") && - isNamed(methods[0], "SubMethodClass2"))); - free(methods); - - // Check lack of optional methods - count = 999; - methods = protocol_copyMethodDescriptionList(proto, NO, YES, &count); - testassert(!methods); - testassert(count == 0); - count = 999; - methods = protocol_copyMethodDescriptionList(proto, NO, NO, &count); - testassert(!methods); - testassert(count == 0); - - - proto = @protocol(SubOptionalMethods); - testassert(proto); - - // Check optional methods - count = 999; - methods = protocol_copyMethodDescriptionList(proto, NO, YES, &count); - testassert(methods); - testassert(count == 2); - testassert((isNamed(methods[0], "SubOptMethodInstance") && - isNamed(methods[1], "SubOptMethodInstance2")) - || - (isNamed(methods[1], "SubOptMethodInstance") && - isNamed(methods[0], "SubOptMethodInstance2"))); - free(methods); - - count = 999; - methods = protocol_copyMethodDescriptionList(proto, NO, NO, &count); - testassert(methods); - testassert(count == 2); - testassert((isNamed(methods[0], "SubOptMethodClass") && - isNamed(methods[1], "SubOptMethodClass2")) - || - (isNamed(methods[1], "SubOptMethodClass") && - isNamed(methods[0], "SubOptMethodClass2"))); - free(methods); - - // Check lack of required methods - count = 999; - methods = protocol_copyMethodDescriptionList(proto, YES, YES, &count); - testassert(!methods); - testassert(count == 0); - count = 999; - methods = protocol_copyMethodDescriptionList(proto, YES, NO, &count); - testassert(!methods); - testassert(count == 0); - - - // Check NULL protocol parameter - count = 999; - methods = protocol_copyMethodDescriptionList(NULL, YES, YES, &count); - testassert(!methods); - testassert(count == 0); - count = 999; - methods = protocol_copyMethodDescriptionList(NULL, YES, NO, &count); - testassert(!methods); - testassert(count == 0); - count = 999; - methods = protocol_copyMethodDescriptionList(NULL, NO, YES, &count); - testassert(!methods); - testassert(count == 0); - count = 999; - methods = protocol_copyMethodDescriptionList(NULL, NO, NO, &count); - testassert(!methods); - testassert(count == 0); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/protocol_copyPropertyList.m b/objc/objc-runtime/test/protocol_copyPropertyList.m deleted file mode 100644 index 406a0bd..0000000 --- a/objc/objc-runtime/test/protocol_copyPropertyList.m +++ /dev/null @@ -1,109 +0,0 @@ -// TEST_CFLAGS -framework Foundation -// need Foundation to get NSObject compatibility additions for class Protocol -// because ARC calls [protocol retain] - -#include "test.h" -#include <string.h> -#include <malloc/malloc.h> -#include <objc/runtime.h> - -@protocol SuperProps -@property int prop1; -@property int prop2; -@end - -@protocol SubProps <SuperProps> -@property int prop3; -@property int prop4; -@end - - -@protocol FourProps -@property int prop1; -@property int prop2; -@property int prop3; -@property int prop4; -@end - -@protocol NoProps @end - -static int isNamed(objc_property_t p, const char *name) -{ - return (0 == strcmp(name, property_getName(p))); -} - -int main() -{ - objc_property_t *props; - unsigned int count; - Protocol *proto; - - proto = @protocol(SubProps); - testassert(proto); - - count = 100; - props = protocol_copyPropertyList(proto, &count); - testassert(props); - testassert(count == 2); - testassert((isNamed(props[0], "prop4") && isNamed(props[1], "prop3")) || - (isNamed(props[0], "prop3") && isNamed(props[1], "prop4"))); - // props[] should be null-terminated - testassert(props[2] == NULL); - free(props); - - proto = @protocol(SuperProps); - testassert(proto); - - count = 100; - props = protocol_copyPropertyList(proto, &count); - testassert(props); - testassert(count == 2); - testassert((isNamed(props[0], "prop1") && isNamed(props[1], "prop2")) || - (isNamed(props[0], "prop2") && isNamed(props[1], "prop1"))); - // props[] should be null-terminated - testassert(props[2] == NULL); - free(props); - - // Check null-termination - this property list block would be 16 bytes - // if it weren't for the terminator - proto = @protocol(FourProps); - testassert(proto); - - count = 100; - props = protocol_copyPropertyList(proto, &count); - testassert(props); - testassert(count == 4); - testassert(malloc_size(props) >= 5 * sizeof(objc_property_t)); - testassert(props[3] != NULL); - testassert(props[4] == NULL); - free(props); - - // Check NULL count parameter - props = protocol_copyPropertyList(proto, NULL); - testassert(props); - testassert(props[4] == NULL); - testassert(props[3] != NULL); - free(props); - - // Check NULL protocol parameter - count = 100; - props = protocol_copyPropertyList(NULL, &count); - testassert(!props); - testassert(count == 0); - - // Check NULL protocol and count - props = protocol_copyPropertyList(NULL, NULL); - testassert(!props); - - // Check protocol with no properties - proto = @protocol(NoProps); - testassert(proto); - - count = 100; - props = protocol_copyPropertyList(proto, &count); - testassert(!props); - testassert(count == 0); - - succeed(__FILE__); - return 0; -} diff --git a/objc/objc-runtime/test/protocol_cw.m b/objc/objc-runtime/test/protocol_cw.m deleted file mode 100644 index a82f991..0000000 --- a/objc/objc-runtime/test/protocol_cw.m +++ /dev/null @@ -1,40 +0,0 @@ -// TEST_CFLAGS -Wno-deprecated-declarations - -#include "test.h" - -#if __OBJC2__ - -int main() -{ - succeed(__FILE__); -} - -#else - -// rdar://4951638 - -#include <string.h> -#include <objc/Protocol.h> - -char Protocol_name[] __attribute__((section("__OBJC,__class_names"))) = "Protocol"; - -struct st { - void *isa; - const char *protocol_name; - void *protocol_list; - void *instance_methods; - void *class_methods; -}; - -struct st Foo_protocol __attribute__((section("__OBJC,__protocol"))) = { Protocol_name, "Foo", 0, 0, 0 }; - -int main() -{ - Protocol *foo = objc_getProtocol("Foo"); - - testassert(foo == (Protocol *)&Foo_protocol); - testassert(0 == strcmp("Foo", [foo name])); - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/rawisa.m b/objc/objc-runtime/test/rawisa.m deleted file mode 100644 index 3d36ed5..0000000 --- a/objc/objc-runtime/test/rawisa.m +++ /dev/null @@ -1,27 +0,0 @@ -/* -TEST_CFLAGS -Xlinker -sectcreate -Xlinker __DATA -Xlinker __objc_rawisa -Xlinker /dev/null -TEST_ENV OBJC_PRINT_RAW_ISA=YES - -TEST_RUN_OUTPUT -objc\[\d+\]: RAW ISA: disabling non-pointer isa because the app has a __DATA,__objc_rawisa section -(.* RAW ISA: .*\n)* -OK: rawisa.m -OR -(.* RAW ISA: .*\n)* -no __DATA,__rawisa support -OK: rawisa.m -END -*/ - -#include "test.h" - -int main() -{ - fprintf(stderr, "\n"); -#if ! (SUPPORT_NONPOINTER_ISA && TARGET_OS_MAC && !TARGET_OS_IPHONE) - // only 64-bit Mac supports this - fprintf(stderr, "no __DATA,__rawisa support\n"); -#endif - succeed(__FILE__); -} - diff --git a/objc/objc-runtime/test/readClassPair.m b/objc/objc-runtime/test/readClassPair.m deleted file mode 100644 index 5a6b9e4..0000000 --- a/objc/objc-runtime/test/readClassPair.m +++ /dev/null @@ -1,77 +0,0 @@ -// TEST_CONFIG - -#include "test.h" - -#if !__OBJC2__ - -int main() -{ - succeed(__FILE__); -} - -#else - -#include <objc/objc-internal.h> - -// Reuse evil-class-def.m as a non-evil class definition. - -#define EVIL_SUPER 0 -#define EVIL_SUPER_META 0 -#define EVIL_SUB 0 -#define EVIL_SUB_META 0 - -#define OMIT_SUPER 1 -#define OMIT_NL_SUPER 1 -#define OMIT_SUB 1 -#define OMIT_NL_SUB 1 - -#include "evil-class-def.m" - -int main() -{ - // This definition is ABI and is never allowed to change. - testassert(OBJC_MAX_CLASS_SIZE == 32*sizeof(void*)); - - struct objc_image_info ii = { 0, 0 }; - - // Read a root class. - testassert(!objc_getClass("Super")); - - extern intptr_t OBJC_CLASS_$_Super[OBJC_MAX_CLASS_SIZE/sizeof(void*)]; - Class Super = objc_readClassPair((__bridge Class)(void*)&OBJC_CLASS_$_Super, &ii); - testassert(Super); - - testassert(objc_getClass("Super") == Super); - testassert(0 == strcmp(class_getName(Super), "Super")); - testassert(class_getSuperclass(Super) == nil); - testassert(class_getClassMethod(Super, @selector(load))); - testassert(class_getInstanceMethod(Super, @selector(load))); - testassert(class_getInstanceVariable(Super, "super_ivar")); - testassert(class_getInstanceSize(Super) == sizeof(void*)); - [Super load]; - - // Read a non-root class. - testassert(!objc_getClass("Sub")); - - extern intptr_t OBJC_CLASS_$_Sub[OBJC_MAX_CLASS_SIZE/sizeof(void*)]; - intptr_t Sub2_buf[OBJC_MAX_CLASS_SIZE/sizeof(void*)]; - memcpy(Sub2_buf, &OBJC_CLASS_$_Sub, sizeof(Sub2_buf)); - Class Sub = objc_readClassPair((__bridge Class)(void*)&OBJC_CLASS_$_Sub, &ii); - testassert(Sub); - - testassert(0 == strcmp(class_getName(Sub), "Sub")); - testassert(objc_getClass("Sub") == Sub); - testassert(class_getSuperclass(Sub) == Super); - testassert(class_getClassMethod(Sub, @selector(load))); - testassert(class_getInstanceMethod(Sub, @selector(load))); - testassert(class_getInstanceVariable(Sub, "sub_ivar")); - testassert(class_getInstanceSize(Sub) == 2*sizeof(void*)); - [Sub load]; - - // Reading a class whose name already exists fails. - testassert(! objc_readClassPair((__bridge Class)(void*)Sub2_buf, &ii)); - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/resolve.m b/objc/objc-runtime/test/resolve.m deleted file mode 100644 index ba6fdd6..0000000 --- a/objc/objc-runtime/test/resolve.m +++ /dev/null @@ -1,298 +0,0 @@ -/* resolve.m - * Test +resolveClassMethod: and +resolveInstanceMethod: - */ - -// TEST_CFLAGS -Wno-deprecated-declarations - -#include "test.h" -#include "testroot.i" -#include <objc/objc.h> -#include <objc/objc-runtime.h> -#include <unistd.h> - -#if __has_feature(objc_arc) - -int main() -{ - testwarn("rdar://11368528 confused by Foundation"); - succeed(__FILE__); -} - -#else - -static int state = 0; - -@interface Super : TestRoot @end -@interface Sub : Super @end - - -@implementation Super -+(void)initialize { - if (self == [Super class]) { - testassert(state == 1); - state = 2; - } -} -@end - -static id forward_handler(id self, SEL sel) -{ - if (class_isMetaClass(object_getClass(self))) { - // self is a class object - if (sel == @selector(missingClassMethod)) { - testassert(state == 21 || state == 25 || state == 80); - if (state == 21) state = 22; - if (state == 25) state = 26; - if (state == 80) state = 81;; - return nil; - } else if (sel == @selector(lyingClassMethod)) { - testassert(state == 31 || state == 35); - if (state == 31) state = 32; - if (state == 35) state = 36; - return nil; - } - fail("+forward:: shouldn't be called with sel %s", sel_getName(sel)); - return nil; - } - else { - // self is not a class object - if (sel == @selector(missingInstanceMethod)) { - testassert(state == 61 || state == 65); - if (state == 61) state = 62; - if (state == 65) state = 66; - return nil; - } else if (sel == @selector(lyingInstanceMethod)) { - testassert(state == 71 || state == 75); - if (state == 71) state = 72; - if (state == 75) state = 76; - return nil; - } - fail("-forward:: shouldn't be called with sel %s", sel_getName(sel)); - return nil; - } -} - - -static id classMethod_c(id __unused self, SEL __unused sel) -{ - testassert(state == 4 || state == 10); - if (state == 4) state = 5; - if (state == 10) state = 11; - return [Super class]; -} - -static id instanceMethod_c(id __unused self, SEL __unused sel) -{ - testassert(state == 41 || state == 50); - if (state == 41) state = 42; - if (state == 50) state = 51; - return [Sub class]; -} - - -@implementation Sub - -+(void)method2 { } -+(void)method3 { } -+(void)method4 { } -+(void)method5 { } - -+(void)initialize { - if (self == [Sub class]) { - testassert(state == 2); - state = 3; - } -} - -+(BOOL)resolveClassMethod:(SEL)sel -{ - if (sel == @selector(classMethod)) { - testassert(state == 3); - state = 4; - class_addMethod(object_getClass(self), sel, (IMP)&classMethod_c, ""); - return YES; - } else if (sel == @selector(missingClassMethod)) { - testassert(state == 20); - state = 21; - return NO; - } else if (sel == @selector(lyingClassMethod)) { - testassert(state == 30); - state = 31; - return YES; // lie - } else { - fail("+resolveClassMethod: called incorrectly (sel %s)", - sel_getName(sel)); - return NO; - } -} - -+(BOOL)resolveInstanceMethod:(SEL)sel -{ - if (sel == @selector(instanceMethod)) { - testassert(state == 40); - state = 41; - class_addMethod(self, sel, (IMP)instanceMethod_c, ""); - return YES; - } else if (sel == @selector(missingInstanceMethod)) { - testassert(state == 60); - state = 61; - return NO; - } else if (sel == @selector(lyingInstanceMethod)) { - testassert(state == 70); - state = 71; - return YES; // lie - } else { - fail("+resolveInstanceMethod: called incorrectly (sel %s)", - sel_getName(sel)); - return NO; - } -} - -@end - -@interface Super (MissingMethods) -+(id)missingClassMethod; -@end - -@interface Sub (ResolvedMethods) -+(id)classMethod; --(id)instanceMethod; -+(id)missingClassMethod; --(id)missingInstanceMethod; -+(id)lyingClassMethod; --(id)lyingInstanceMethod; -@end - - -int main() -{ - Sub *s; - id ret; - - objc_setForwardHandler((void*)&forward_handler, NULL); - - // Be ready for ARC to retain the class object and call +initialize early - state = 1; - - Class dup = objc_duplicateClass(objc_getClass("Sub"), "Sub_copy", 0); - - // Resolve a class method - // +initialize should fire first (if it hasn't already) - ret = [Sub classMethod]; - testassert(state == 5); - testassert(ret == [Super class]); - - // Call it again, cached - // Resolver shouldn't be called again. - state = 10; - ret = [Sub classMethod]; - testassert(state == 11); - testassert(ret == [Super class]); - - _objc_flush_caches(object_getClass([Sub class])); - - // Call a method that won't get resolved - state = 20; - ret = [Sub missingClassMethod]; - testassert(state == 22); - testassert(ret == nil); - - // Call it again, cached - // Resolver shouldn't be called again. - state = 25; - ret = [Sub missingClassMethod]; - testassert(state == 26); - testassert(ret == nil); - - _objc_flush_caches(object_getClass([Sub class])); - - // Call a method that won't get resolved but the resolver lies about it - state = 30; - ret = [Sub lyingClassMethod]; - testassert(state == 32); - testassert(ret == nil); - - // Call it again, cached - // Resolver shouldn't be called again. - state = 35; - ret = [Sub lyingClassMethod]; - testassert(state == 36); - testassert(ret == nil); - - _objc_flush_caches(object_getClass([Sub class])); - - - // Resolve an instance method - s = [Sub new]; - state = 40; - ret = [s instanceMethod]; - testassert(state == 42); - testassert(ret == [Sub class]); - - // Call it again, cached - // Resolver shouldn't be called again. - state = 50; - ret = [s instanceMethod]; - testassert(state == 51); - testassert(ret == [Sub class]); - - _objc_flush_caches([Sub class]); - - // Call a method that won't get resolved - state = 60; - ret = [s missingInstanceMethod]; - testassert(state == 62); - testassert(ret == nil); - - // Call it again, cached - // Resolver shouldn't be called again. - state = 65; - ret = [s missingInstanceMethod]; - testassert(state == 66); - testassert(ret == nil); - - _objc_flush_caches([Sub class]); - - // Call a method that won't get resolved but the resolver lies about it - state = 70; - ret = [s lyingInstanceMethod]; - testassert(state == 72); - testassert(ret == nil); - - // Call it again, cached - // Resolver shouldn't be called again. - state = 75; - ret = [s lyingInstanceMethod]; - testassert(state == 76); - testassert(ret == nil); - - _objc_flush_caches([Sub class]); - - // Call a missing method on a class that doesn't support resolving - state = 80; - ret = [Super missingClassMethod]; - testassert(state == 81); - testassert(ret == nil); - RELEASE_VAR(s); - - // Resolve an instance method on a class duplicated before resolving - s = [dup new]; - state = 40; - ret = [s instanceMethod]; - testassert(state == 42); - testassert(ret == [Sub class]); - - // Call it again, cached - // Resolver shouldn't be called again. - state = 50; - ret = [s instanceMethod]; - testassert(state == 51); - testassert(ret == [Sub class]); - RELEASE_VAR(s); - - succeed(__FILE__); - return 0; -} - -#endif - diff --git a/objc/objc-runtime/test/rr-autorelease-fast.m b/objc/objc-runtime/test/rr-autorelease-fast.m deleted file mode 100644 index f44b88d..0000000 --- a/objc/objc-runtime/test/rr-autorelease-fast.m +++ /dev/null @@ -1,317 +0,0 @@ -// TEST_CONFIG CC=clang MEM=mrc -// TEST_CFLAGS -Os - -#include "test.h" -#include "testroot.i" - -#if __i386__ - -int main() -{ - // no optimization on i386 (neither Mac nor Simulator) - succeed(__FILE__); -} - -#else - -#include <objc/objc-internal.h> -#include <objc/objc-abi.h> -#include <Foundation/Foundation.h> - -@interface TestObject : TestRoot @end -@implementation TestObject @end - - -#ifdef __arm__ -# define MAGIC asm volatile("mov r7, r7") -# define NOT_MAGIC asm volatile("mov r6, r6") -#elif __arm64__ -# define MAGIC asm volatile("mov x29, x29") -# define NOT_MAGIC asm volatile("mov x28, x28") -#elif __x86_64__ -# define MAGIC asm volatile("") -# define NOT_MAGIC asm volatile("nop") -#else -# error unknown architecture -#endif - - -int -main() -{ - TestObject *tmp, *obj; - -#ifdef __x86_64__ - // need to get DYLD to resolve the stubs on x86 - PUSH_POOL { - TestObject *warm_up = [[TestObject alloc] init]; - testassert(warm_up); - warm_up = objc_retainAutoreleasedReturnValue(warm_up); - warm_up = objc_unsafeClaimAutoreleasedReturnValue(warm_up); - [warm_up release]; - warm_up = nil; - } POP_POOL; -#endif - - testprintf(" Successful +1 -> +1 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - tmp = objc_autoreleaseReturnValue(obj); - MAGIC; - tmp = objc_retainAutoreleasedReturnValue(tmp); - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 0); - - [tmp release]; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 0); - - } POP_POOL; - - testprintf("Unsuccessful +1 -> +1 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - tmp = objc_autoreleaseReturnValue(obj); - NOT_MAGIC; - tmp = objc_retainAutoreleasedReturnValue(tmp); - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 1); - - [tmp release]; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 1); - - } POP_POOL; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 2); - testassert(TestRootAutorelease == 1); - - - testprintf(" Successful +0 -> +1 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - tmp = objc_retainAutoreleaseReturnValue(obj); - MAGIC; - tmp = objc_retainAutoreleasedReturnValue(tmp); - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 0); - - [tmp release]; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 0); - - [tmp release]; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 2); - testassert(TestRootAutorelease == 0); - - } POP_POOL; - - testprintf("Unsuccessful +0 -> +1 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - tmp = objc_retainAutoreleaseReturnValue(obj); - NOT_MAGIC; - tmp = objc_retainAutoreleasedReturnValue(tmp); - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 2); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 1); - - [tmp release]; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 2); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 1); - - [tmp release]; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 2); - testassert(TestRootRelease == 2); - testassert(TestRootAutorelease == 1); - - } POP_POOL; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 2); - testassert(TestRootRelease == 3); - testassert(TestRootAutorelease == 1); - - - testprintf(" Successful +1 -> +0 handshake\n"); - - PUSH_POOL { - obj = [[[TestObject alloc] init] retain]; - testassert(obj); - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - tmp = objc_autoreleaseReturnValue(obj); - MAGIC; - tmp = objc_unsafeClaimAutoreleasedReturnValue(tmp); - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 0); - - [tmp release]; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 2); - testassert(TestRootAutorelease == 0); - - } POP_POOL; - - testprintf("Unsuccessful +1 -> +0 handshake\n"); - - PUSH_POOL { - obj = [[[TestObject alloc] init] retain]; - testassert(obj); - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - tmp = objc_autoreleaseReturnValue(obj); - NOT_MAGIC; - tmp = objc_unsafeClaimAutoreleasedReturnValue(tmp); - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 1); - - [tmp release]; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 1); - - } POP_POOL; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 2); - testassert(TestRootAutorelease == 1); - - - testprintf(" Successful +0 -> +0 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - tmp = objc_retainAutoreleaseReturnValue(obj); - MAGIC; - tmp = objc_unsafeClaimAutoreleasedReturnValue(tmp); - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 0); - - [tmp release]; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 0); - - } POP_POOL; - - testprintf("Unsuccessful +0 -> +0 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - tmp = objc_retainAutoreleaseReturnValue(obj); - NOT_MAGIC; - tmp = objc_unsafeClaimAutoreleasedReturnValue(tmp); - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 1); - - [tmp release]; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 1); - - } POP_POOL; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 2); - testassert(TestRootAutorelease == 1); - - succeed(__FILE__); - - return 0; -} - - -#endif diff --git a/objc/objc-runtime/test/rr-autorelease-fastarc.m b/objc/objc-runtime/test/rr-autorelease-fastarc.m deleted file mode 100644 index 364b30d..0000000 --- a/objc/objc-runtime/test/rr-autorelease-fastarc.m +++ /dev/null @@ -1,231 +0,0 @@ -// TEST_CFLAGS -Os -framework Foundation -// TEST_DISABLED pending clang support for rdar://20530049 - -#include "test.h" -#include "testroot.i" - -#if __i386__ - -int main() -{ - // no optimization on i386 (neither Mac nor Simulator) - succeed(__FILE__); -} - -#else - -#include <objc/objc-internal.h> -#include <objc/objc-abi.h> -#include <Foundation/Foundation.h> - -@interface TestObject : TestRoot @end -@implementation TestObject @end - - -#ifdef __arm__ -# define MAGIC asm volatile("mov r7, r7") -# define NOT_MAGIC asm volatile("mov r6, r6") -#elif __arm64__ -# define MAGIC asm volatile("mov x29, x29") -# define NOT_MAGIC asm volatile("mov x28, x28") -#elif __x86_64__ -# define MAGIC asm volatile("") -# define NOT_MAGIC asm volatile("nop") -#else -# error unknown architecture -#endif - - -@interface Tester : NSObject @end -@implementation Tester { -@public - id ivar; -} - --(id) return0 { - return ivar; -} --(id) return1 { - id x = ivar; - [x self]; - return x; -} - -@end - -OBJC_EXPORT -id -objc_retainAutoreleasedReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0); - -// Accept a value returned through a +0 autoreleasing convention for use at +0. -OBJC_EXPORT -id -objc_unsafeClaimAutoreleasedReturnValue(id obj) - __OSX_AVAILABLE_STARTING(__MAC_10_11, __IPHONE_9_0); - - -int -main() -{ - TestObject *obj; - Tester *tt = [Tester new]; - -#ifdef __x86_64__ - // need to get DYLD to resolve the stubs on x86 - PUSH_POOL { - TestObject *warm_up = [[TestObject alloc] init]; - testassert(warm_up); - warm_up = objc_retainAutoreleasedReturnValue(warm_up); - warm_up = objc_unsafeClaimAutoreleasedReturnValue(warm_up); - warm_up = nil; - } POP_POOL; -#endif - - testprintf(" Successful +1 -> +1 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - tt->ivar = obj; - obj = nil; - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - TestObject *tmp = [tt return1]; - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 0); - - tt->ivar = nil; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 0); - - tmp = nil; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 2); - testassert(TestRootAutorelease == 0); - - } POP_POOL; - - testprintf(" Successful +0 -> +0 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - tt->ivar = obj; - obj = nil; - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - __unsafe_unretained TestObject *tmp = [tt return0]; - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 0); - - tmp = nil; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 0); - - tt->ivar = nil; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 0); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 0); - - } POP_POOL; - - - testprintf(" Successful +1 -> +0 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - tt->ivar = obj; - obj = nil; - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - __unsafe_unretained TestObject *tmp = [tt return1]; - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 0); - - tmp = nil; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 0); - - tt->ivar = nil; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 2); - testassert(TestRootAutorelease == 0); - - } POP_POOL; - - - testprintf(" Successful +0 -> +1 handshake\n"); - - PUSH_POOL { - obj = [[TestObject alloc] init]; - testassert(obj); - tt->ivar = obj; - obj = nil; - - TestRootRetain = 0; - TestRootRelease = 0; - TestRootAutorelease = 0; - TestRootDealloc = 0; - - TestObject *tmp = [tt return0]; - - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 0); - testassert(TestRootAutorelease == 0); - - tmp = nil; - testassert(TestRootDealloc == 0); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 1); - testassert(TestRootAutorelease == 0); - - tt->ivar = nil; - testassert(TestRootDealloc == 1); - testassert(TestRootRetain == 1); - testassert(TestRootRelease == 2); - testassert(TestRootAutorelease == 0); - - } POP_POOL; - - - - succeed(__FILE__); - - return 0; -} - - -#endif diff --git a/objc/objc-runtime/test/rr-autorelease-stacklogging.m b/objc/objc-runtime/test/rr-autorelease-stacklogging.m deleted file mode 100644 index 40aa039..0000000 --- a/objc/objc-runtime/test/rr-autorelease-stacklogging.m +++ /dev/null @@ -1,12 +0,0 @@ -// Test OBJC_DEBUG_POOL_ALLOCATION (which is also enabled by MallocStackLogging) - -// TEST_ENV OBJC_DEBUG_POOL_ALLOCATION=YES -// TEST_CFLAGS -framework Foundation -// TEST_CONFIG MEM=mrc - -#include "test.h" - -#define FOUNDATION 0 -#define NAME "rr-autorelease-stacklogging" - -#include "rr-autorelease2.m" diff --git a/objc/objc-runtime/test/rr-autorelease.m b/objc/objc-runtime/test/rr-autorelease.m deleted file mode 100644 index 01eb89e..0000000 --- a/objc/objc-runtime/test/rr-autorelease.m +++ /dev/null @@ -1,9 +0,0 @@ -// TEST_CFLAGS -framework Foundation -// TEST_CONFIG MEM=mrc - -#include "test.h" - -#define FOUNDATION 0 -#define NAME "rr-autorelease" - -#include "rr-autorelease2.m" diff --git a/objc/objc-runtime/test/rr-autorelease2.m b/objc/objc-runtime/test/rr-autorelease2.m deleted file mode 100644 index d68bd54..0000000 --- a/objc/objc-runtime/test/rr-autorelease2.m +++ /dev/null @@ -1,364 +0,0 @@ -// Define FOUNDATION=1 for NSObject and NSAutoreleasePool -// Define FOUNDATION=0 for _objc_root* and _objc_autoreleasePool* - -#include "test.h" - -#if FOUNDATION -# define RR_PUSH() [[NSAutoreleasePool alloc] init] -# define RR_POP(p) [(id)p release] -# define RR_RETAIN(o) [o retain] -# define RR_RELEASE(o) [o release] -# define RR_AUTORELEASE(o) [o autorelease] -# define RR_RETAINCOUNT(o) [o retainCount] -#else -# define RR_PUSH() _objc_autoreleasePoolPush() -# define RR_POP(p) _objc_autoreleasePoolPop(p) -# define RR_RETAIN(o) _objc_rootRetain((id)o) -# define RR_RELEASE(o) _objc_rootRelease((id)o) -# define RR_AUTORELEASE(o) _objc_rootAutorelease((id)o) -# define RR_RETAINCOUNT(o) _objc_rootRetainCount((id)o) -#endif - -#include <objc/objc-internal.h> -#include <Foundation/Foundation.h> - -static int state; -static pthread_attr_t smallstack; - -#define NESTED_COUNT 8 - -@interface Deallocator : NSObject @end -@implementation Deallocator --(void) dealloc -{ - // testprintf("-[Deallocator %p dealloc]\n", self); - state++; - [super dealloc]; -} -@end - -@interface AutoreleaseDuringDealloc : NSObject @end -@implementation AutoreleaseDuringDealloc --(void) dealloc -{ - state++; - RR_AUTORELEASE([[Deallocator alloc] init]); - [super dealloc]; -} -@end - -@interface AutoreleasePoolDuringDealloc : NSObject @end -@implementation AutoreleasePoolDuringDealloc --(void) dealloc -{ - // caller's pool - for (int i = 0; i < NESTED_COUNT; i++) { - RR_AUTORELEASE([[Deallocator alloc] init]); - } - - // local pool, popped - void *pool = RR_PUSH(); - for (int i = 0; i < NESTED_COUNT; i++) { - RR_AUTORELEASE([[Deallocator alloc] init]); - } - RR_POP(pool); - - // caller's pool again - for (int i = 0; i < NESTED_COUNT; i++) { - RR_AUTORELEASE([[Deallocator alloc] init]); - } - -#if FOUNDATION - { - static bool warned; - if (!warned) testwarn("rdar://7138159 NSAutoreleasePool leaks"); - warned = true; - } - state += NESTED_COUNT; -#else - // local pool, not popped - RR_PUSH(); - for (int i = 0; i < NESTED_COUNT; i++) { - RR_AUTORELEASE([[Deallocator alloc] init]); - } -#endif - - [super dealloc]; -} -@end - -void *autorelease_lots_fn(void *singlePool) -{ - // Enough to blow out the stack if AutoreleasePoolPage is recursive. - const int COUNT = 1024*1024; - state = 0; - - int p = 0; - void **pools = (void**)malloc((COUNT+1) * sizeof(void*)); - pools[p++] = RR_PUSH(); - - id obj = RR_AUTORELEASE([[Deallocator alloc] init]); - - // last pool has only 1 autorelease in it - pools[p++] = RR_PUSH(); - - for (int i = 0; i < COUNT; i++) { - if (rand() % 1000 == 0 && !singlePool) { - pools[p++] = RR_PUSH(); - } else { - RR_AUTORELEASE(RR_RETAIN(obj)); - } - } - - testassert(state == 0); - while (--p) { - RR_POP(pools[p]); - } - testassert(state == 0); - testassert(RR_RETAINCOUNT(obj) == 1); - RR_POP(pools[0]); - testassert(state == 1); - free(pools); - - return NULL; -} - -void *nsthread_fn(void *arg __unused) -{ - [NSThread currentThread]; - void *pool = RR_PUSH(); - RR_AUTORELEASE([[Deallocator alloc] init]); - RR_POP(pool); - return NULL; -} - -void cycle(void) -{ - // Normal autorelease. - testprintf("-- Normal autorelease.\n"); - { - void *pool = RR_PUSH(); - state = 0; - RR_AUTORELEASE([[Deallocator alloc] init]); - testassert(state == 0); - RR_POP(pool); - testassert(state == 1); - } - - // Autorelease during dealloc during autoreleasepool-pop. - // That autorelease is handled by the popping pool, not the one above it. - testprintf("-- Autorelease during dealloc during autoreleasepool-pop.\n"); - { - void *pool = RR_PUSH(); - state = 0; - RR_AUTORELEASE([[AutoreleaseDuringDealloc alloc] init]); - testassert(state == 0); - RR_POP(pool); - testassert(state == 2); - } - - // Autorelease pool during dealloc during autoreleasepool-pop. - testprintf("-- Autorelease pool during dealloc during autoreleasepool-pop.\n"); - { - void *pool = RR_PUSH(); - state = 0; - RR_AUTORELEASE([[AutoreleasePoolDuringDealloc alloc] init]); - testassert(state == 0); - RR_POP(pool); - testassert(state == 4 * NESTED_COUNT); - } - - // Top-level thread pool popped normally. - testprintf("-- Thread-level pool popped normally.\n"); - { - state = 0; - testonthread(^{ - void *pool = RR_PUSH(); - RR_AUTORELEASE([[Deallocator alloc] init]); - RR_POP(pool); - }); - testassert(state == 1); - } - - - // Autorelease with no pool. - testprintf("-- Autorelease with no pool.\n"); - { - state = 0; - testonthread(^{ - RR_AUTORELEASE([[Deallocator alloc] init]); - }); - testassert(state == 1); - } - - // Autorelease with no pool after popping the top-level pool. - testprintf("-- Autorelease with no pool after popping the last pool.\n"); - { - state = 0; - testonthread(^{ - void *pool = RR_PUSH(); - RR_AUTORELEASE([[Deallocator alloc] init]); - RR_POP(pool); - RR_AUTORELEASE([[Deallocator alloc] init]); - }); - testassert(state == 2); - } - - // Top-level thread pool not popped. - // The runtime should clean it up. -#if FOUNDATION - { - static bool warned; - if (!warned) testwarn("rdar://7138159 NSAutoreleasePool leaks"); - warned = true; - } -#else - testprintf("-- Thread-level pool not popped.\n"); - { - state = 0; - testonthread(^{ - RR_PUSH(); - RR_AUTORELEASE([[Deallocator alloc] init]); - // pool not popped - }); - testassert(state == 1); - } -#endif - - // Intermediate pool not popped. - // Popping the containing pool should clean up the skipped pool first. -#if FOUNDATION - { - static bool warned; - if (!warned) testwarn("rdar://7138159 NSAutoreleasePool leaks"); - warned = true; - } -#else - testprintf("-- Intermediate pool not popped.\n"); - { - void *pool = RR_PUSH(); - void *pool2 = RR_PUSH(); - RR_AUTORELEASE([[Deallocator alloc] init]); - state = 0; - (void)pool2; // pool2 not popped - RR_POP(pool); - testassert(state == 1); - } -#endif -} - - -static void -slow_cycle(void) -{ - // Large autorelease stack. - // Do this only once because it's slow. - testprintf("-- Large autorelease stack.\n"); - { - // limit stack size: autorelease pop should not be recursive - pthread_t th; - pthread_create(&th, &smallstack, &autorelease_lots_fn, NULL); - pthread_join(th, NULL); - } - - // Single large autorelease pool. - // Do this only once because it's slow. - testprintf("-- Large autorelease pool.\n"); - { - // limit stack size: autorelease pop should not be recursive - pthread_t th; - pthread_create(&th, &smallstack, &autorelease_lots_fn, (void*)1); - pthread_join(th, NULL); - } -} - - -int main() -{ - pthread_attr_init(&smallstack); - pthread_attr_setstacksize(&smallstack, 16384); - - // inflate the refcount side table so it doesn't show up in leak checks - { - int count = 10000; - id *objs = (id *)malloc(count*sizeof(id)); - for (int i = 0; i < count; i++) { - objs[i] = RR_RETAIN([NSObject new]); - } - for (int i = 0; i < count; i++) { - RR_RELEASE(objs[i]); - RR_RELEASE(objs[i]); - } - free(objs); - } - -#if FOUNDATION - // inflate NSAutoreleasePool's instance cache - { - int count = 32; - id *objs = (id *)malloc(count * sizeof(id)); - for (int i = 0; i < count; i++) { - objs[i] = [[NSAutoreleasePool alloc] init]; - } - for (int i = 0; i < count; i++) { - [objs[count-i-1] release]; - } - - free(objs); - } -#endif - - // preheat - { - for (int i = 0; i < 100; i++) { - cycle(); - } - - slow_cycle(); - } - - // check for leaks using top-level pools - { - leak_mark(); - - for (int i = 0; i < 1000; i++) { - cycle(); - } - - leak_check(0); - - slow_cycle(); - - leak_check(0); - } - - // check for leaks using pools not at top level - void *pool = RR_PUSH(); - { - leak_mark(); - - for (int i = 0; i < 1000; i++) { - cycle(); - } - - leak_check(0); - - slow_cycle(); - - leak_check(0); - } - RR_POP(pool); - - // NSThread. - // Can't leak check this because it's too noisy. - testprintf("-- NSThread.\n"); - { - pthread_t th; - pthread_create(&th, &smallstack, &nsthread_fn, 0); - pthread_join(th, NULL); - } - - // NO LEAK CHECK HERE - - succeed(NAME); -} diff --git a/objc/objc-runtime/test/rr-nsautorelease.m b/objc/objc-runtime/test/rr-nsautorelease.m deleted file mode 100644 index 095ec36..0000000 --- a/objc/objc-runtime/test/rr-nsautorelease.m +++ /dev/null @@ -1,7 +0,0 @@ -// TEST_CFLAGS -framework Foundation -// TEST_CONFIG MEM=mrc - -#define FOUNDATION 1 -#define NAME "rr-nsautorelease" - -#include "rr-autorelease2.m" diff --git a/objc/objc-runtime/test/rr-sidetable.m b/objc/objc-runtime/test/rr-sidetable.m deleted file mode 100644 index daa4090..0000000 --- a/objc/objc-runtime/test/rr-sidetable.m +++ /dev/null @@ -1,59 +0,0 @@ -// TEST_CFLAGS -framework Foundation -// TEST_CONFIG MEM=mrc ARCH=x86_64 - -// Stress-test nonpointer isa's side table retain count transfers. - -// x86_64 only. arm64's side table limit is high enough that bugs -// are harder to reproduce. - -#include "test.h" -#import <Foundation/Foundation.h> - -#define OBJECTS 1 -#define LOOPS 256 -#define THREADS 16 -#if __x86_64__ -# define RC_HALF (1ULL<<7) -#else -# error sorry -#endif -#define RC_DELTA RC_HALF - -static bool Deallocated = false; -@interface Deallocator : NSObject @end -@implementation Deallocator --(void)dealloc { - Deallocated = true; - [super dealloc]; -} -@end - -// This is global to avoid extra retains by the dispatch block objects. -static Deallocator *obj; - -int main() { - dispatch_queue_t queue = - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - - for (size_t i = 0; i < OBJECTS; i++) { - obj = [Deallocator new]; - - dispatch_apply(THREADS, queue, ^(size_t i __unused) { - for (size_t a = 0; a < LOOPS; a++) { - for (size_t b = 0; b < RC_DELTA; b++) { - [obj retain]; - } - for (size_t b = 0; b < RC_DELTA; b++) { - [obj release]; - } - } - }); - - testassert(!Deallocated); - [obj release]; - testassert(Deallocated); - Deallocated = false; - } - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/runtime.m b/objc/objc-runtime/test/runtime.m deleted file mode 100644 index b4a592c..0000000 --- a/objc/objc-runtime/test/runtime.m +++ /dev/null @@ -1,216 +0,0 @@ -/* -TEST_RUN_OUTPUT -objc\[\d+\]: class `SwiftV1Class\' not linked into application -objc\[\d+\]: class `DoesNotExist\' not linked into application -OK: runtime.m -OR -confused by Foundation -OK: runtime.m -END -*/ - - -#include "test.h" -#include "testroot.i" -#include <string.h> -#include <dlfcn.h> -#include <mach-o/ldsyms.h> -#include <objc/objc-runtime.h> - -#if __has_feature(objc_arc) - -int main() -{ - testwarn("rdar://11368528 confused by Foundation"); - fprintf(stderr, "confused by Foundation\n"); - succeed(__FILE__); -} - -#else - -@interface Sub : TestRoot @end -@implementation Sub @end - -#if __OBJC2__ -# define TEST_SWIFT 1 -#else -# define TEST_SWIFT 0 -#endif - -#define SwiftV1MangledName "_TtC6Module12SwiftV1Class" -#define SwiftV1MangledName2 "_TtC2Sw13SwiftV1Class2" -#define SwiftV1MangledName3 "_TtCSs13SwiftV1Class3" -#define SwiftV1MangledName4 "_TtC6Swiftt13SwiftV1Class4" - -#if TEST_SWIFT -__attribute__((objc_runtime_name(SwiftV1MangledName))) -@interface SwiftV1Class : TestRoot @end -@implementation SwiftV1Class @end - -__attribute__((objc_runtime_name(SwiftV1MangledName2))) -@interface SwiftV1Class2 : TestRoot @end -@implementation SwiftV1Class2 @end - -__attribute__((objc_runtime_name(SwiftV1MangledName3))) -@interface SwiftV1Class3 : TestRoot @end -@implementation SwiftV1Class3 @end - -__attribute__((objc_runtime_name(SwiftV1MangledName4))) -@interface SwiftV1Class4 : TestRoot @end -@implementation SwiftV1Class4 @end -#endif - - -int main() -{ - Class list[100]; - Class *list2; - unsigned int count, count0, count2; - unsigned int i; - int foundTestRoot; - int foundSub; - int foundSwiftV1; - int foundSwiftV1class2; - int foundSwiftV1class3; - int foundSwiftV1class4; - const char **names; - Dl_info info; - - [TestRoot class]; - - // This shouldn't touch any classes. - dladdr(&_mh_execute_header, &info); - names = objc_copyClassNamesForImage(info.dli_fname, &count); - testassert(names); -#if TEST_SWIFT - testassert(count == 6); -#else - testassert(count == 2); -#endif - testassert(names[count] == NULL); - foundTestRoot = 0; - foundSub = 0; - foundSwiftV1 = 0; - foundSwiftV1class2 = 0; - foundSwiftV1class3 = 0; - foundSwiftV1class4 = 0; - for (i = 0; i < count; i++) { - if (0 == strcmp(names[i], "TestRoot")) foundTestRoot++; - if (0 == strcmp(names[i], "Sub")) foundSub++; - if (0 == strcmp(names[i], "Module.SwiftV1Class")) foundSwiftV1++; - if (0 == strcmp(names[i], "Sw.SwiftV1Class2")) foundSwiftV1class2++; - if (0 == strcmp(names[i], "Swift.SwiftV1Class3")) foundSwiftV1class3++; - if (0 == strcmp(names[i], "Swiftt.SwiftV1Class4")) foundSwiftV1class4++; - } - testassert(foundTestRoot == 1); - testassert(foundSub == 1); -#if TEST_SWIFT - testassert(foundSwiftV1 == 1); - testassert(foundSwiftV1class2 == 1); - testassert(foundSwiftV1class3 == 1); - testassert(foundSwiftV1class4 == 1); -#endif - - - // class Sub hasn't been touched - make sure it's in the class list too - count0 = objc_getClassList(NULL, 0); - testassert(count0 >= 2 && count0 < 100); - - list[count0-1] = NULL; - count = objc_getClassList(list, count0-1); - testassert(list[count0-1] == NULL); - testassert(count == count0); - - count = objc_getClassList(list, count0); - testassert(count == count0); - - for (i = 0; i < count; i++) { - testprintf("%s\n", class_getName(list[i])); - } - - foundTestRoot = 0; - foundSub = 0; - foundSwiftV1 = 0; - foundSwiftV1class2 = 0; - foundSwiftV1class3 = 0; - foundSwiftV1class4 = 0; - for (i = 0; i < count; i++) { - if (0 == strcmp(class_getName(list[i]), "TestRoot")) foundTestRoot++; - if (0 == strcmp(class_getName(list[i]), "Sub")) foundSub++; - if (0 == strcmp(class_getName(list[i]), "Module.SwiftV1Class")) foundSwiftV1++; - if (0 == strcmp(class_getName(list[i]), "Sw.SwiftV1Class2")) foundSwiftV1class2++; - if (0 == strcmp(class_getName(list[i]), "Swift.SwiftV1Class3")) foundSwiftV1class3++; - if (0 == strcmp(class_getName(list[i]), "Swiftt.SwiftV1Class4")) foundSwiftV1class4++; - // list should be non-meta classes only - testassert(!class_isMetaClass(list[i])); - } - testassert(foundTestRoot == 1); - testassert(foundSub == 1); -#if TEST_SWIFT - testassert(foundSwiftV1 == 1); - testassert(foundSwiftV1class2 == 1); - testassert(foundSwiftV1class3 == 1); - testassert(foundSwiftV1class4 == 1); -#endif - - // fixme check class handler - testassert(objc_getClass("TestRoot") == [TestRoot class]); -#if TEST_SWIFT - testassert(objc_getClass("Module.SwiftV1Class") == [SwiftV1Class class]); - testassert(objc_getClass(SwiftV1MangledName) == [SwiftV1Class class]); - testassert(objc_getClass("Sw.SwiftV1Class2") == [SwiftV1Class2 class]); - testassert(objc_getClass(SwiftV1MangledName2) == [SwiftV1Class2 class]); - testassert(objc_getClass("Swift.SwiftV1Class3") == [SwiftV1Class3 class]); - testassert(objc_getClass(SwiftV1MangledName3) == [SwiftV1Class3 class]); - testassert(objc_getClass("Swiftt.SwiftV1Class4") == [SwiftV1Class4 class]); - testassert(objc_getClass(SwiftV1MangledName4) == [SwiftV1Class4 class]); -#endif - testassert(objc_getClass("SwiftV1Class") == nil); - testassert(objc_getClass("DoesNotExist") == nil); - testassert(objc_getClass(NULL) == nil); - - testassert(objc_getMetaClass("TestRoot") == object_getClass([TestRoot class])); -#if TEST_SWIFT - testassert(objc_getMetaClass("Module.SwiftV1Class") == object_getClass([SwiftV1Class class])); - testassert(objc_getMetaClass(SwiftV1MangledName) == object_getClass([SwiftV1Class class])); -#endif - testassert(objc_getMetaClass("SwiftV1Class") == nil); - testassert(objc_getMetaClass("DoesNotExist") == nil); - testassert(objc_getMetaClass(NULL) == nil); - - // fixme check class no handler - testassert(objc_lookUpClass("TestRoot") == [TestRoot class]); -#if TEST_SWIFT - testassert(objc_lookUpClass("Module.SwiftV1Class") == [SwiftV1Class class]); - testassert(objc_lookUpClass(SwiftV1MangledName) == [SwiftV1Class class]); -#endif - testassert(objc_lookUpClass("SwiftV1Class") == nil); - testassert(objc_lookUpClass("DoesNotExist") == nil); - testassert(objc_lookUpClass(NULL) == nil); - - testassert(! object_isClass(nil)); - testassert(! object_isClass([TestRoot new])); - testassert(object_isClass([TestRoot class])); - testassert(object_isClass(object_getClass([TestRoot class]))); - testassert(object_isClass([Sub class])); - testassert(object_isClass(object_getClass([Sub class]))); -#if TEST_SWIFT - testassert(object_isClass([SwiftV1Class class])); - testassert(object_isClass(object_getClass([SwiftV1Class class]))); -#endif - - list2 = objc_copyClassList(&count2); - testassert(count2 == count); - testassert(list2); - testassert(malloc_size(list2) >= (1+count2) * sizeof(Class)); - for (i = 0; i < count; i++) { - testassert(list[i] == list2[i]); - } - testassert(list2[count] == NULL); - free(list2); - free(objc_copyClassList(NULL)); - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/sel.m b/objc/objc-runtime/test/sel.m deleted file mode 100644 index 44618c5..0000000 --- a/objc/objc-runtime/test/sel.m +++ /dev/null @@ -1,45 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include <string.h> -#include <objc/objc-runtime.h> -#include <objc/objc-auto.h> - -int main() -{ - // Make sure @selector values are correctly fixed up - testassert(@selector(foo) == sel_registerName("foo")); - - // sel_getName recognizes the zero SEL - testassert(0 == strcmp("<null selector>", sel_getName(0))); - - // GC-ignored selectors. -#if __has_feature(objc_arc) - - // ARC dislikes `@selector(retain)` - -#else - -# if defined(__i386__) - // sel_getName recognizes GC-ignored SELs - if (objc_collectingEnabled()) { - testassert(0 == strcmp("<ignored selector>", - sel_getName(@selector(retain)))); - } else { - testassert(0 == strcmp("retain", - sel_getName(@selector(retain)))); - } - - // _objc_search_builtins() shouldn't crash on GC-ignored SELs - union { - SEL sel; - const char *ptr; - } u; - u.sel = @selector(retain); - testassert(@selector(retain) == sel_registerName(u.ptr)); -# endif - -#endif - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/setSuper.m b/objc/objc-runtime/test/setSuper.m deleted file mode 100644 index 7ce6dee..0000000 --- a/objc/objc-runtime/test/setSuper.m +++ /dev/null @@ -1,44 +0,0 @@ -// TEST_CFLAGS -Wno-deprecated-declarations - -#include "test.h" -#include "testroot.i" -#include <objc/runtime.h> - -@interface Super1 : TestRoot @end -@implementation Super1 -+(int)classMethod { return 1; } --(int)instanceMethod { return 10000; } -@end - -@interface Super2 : TestRoot @end -@implementation Super2 -+(int)classMethod { return 2; } --(int)instanceMethod { return 20000; } -@end - -@interface Sub : Super1 @end -@implementation Sub -+(int)classMethod { return [super classMethod] + 100; } --(int)instanceMethod { - return [super instanceMethod] + 1000000; -} -@end - -int main() -{ - Class cls; - Sub *obj = [Sub new]; - - testassert(101 == [[Sub class] classMethod]); - testassert(1010000 == [obj instanceMethod]); - - cls = class_setSuperclass([Sub class], [Super2 class]); - - testassert(cls == [Super1 class]); - testassert(object_getClass(cls) == object_getClass([Super1 class])); - - testassert(102 == [[Sub class] classMethod]); - testassert(1020000 == [obj instanceMethod]); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/subscripting.m b/objc/objc-runtime/test/subscripting.m deleted file mode 100644 index e05a370..0000000 --- a/objc/objc-runtime/test/subscripting.m +++ /dev/null @@ -1,154 +0,0 @@ -// TEST_CONFIG MEM=arc,mrc CC=clang LANGUAGE=objc,objc++ -// TEST_CFLAGS -framework Foundation - -#if !__OBJC2__ - -#include "test.h" - -int main() -{ - succeed(__FILE__); -} - -#else - -#import <Foundation/Foundation.h> -#import <Foundation/NSDictionary.h> -#import <objc/runtime.h> -#import <objc/objc-abi.h> -#include "test.h" - -@interface TestIndexed : NSObject <NSFastEnumeration> { - NSMutableArray *indexedValues; -} -@property(readonly) NSUInteger count; -- (id)objectAtIndexedSubscript:(NSUInteger)index; -- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index; -@end - -@implementation TestIndexed - -- (id)init { - if ((self = [super init])) { - indexedValues = [NSMutableArray new]; - } - return self; -} - -#if !__has_feature(objc_arc) -- (void)dealloc { - [indexedValues release]; - [super dealloc]; -} -#endif - -- (NSUInteger)count { return [indexedValues count]; } -- (id)objectAtIndexedSubscript:(NSUInteger)index { return [indexedValues objectAtIndex:index]; } -- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index { - if (index == NSNotFound) - [indexedValues addObject:object]; - else - [indexedValues replaceObjectAtIndex:index withObject:object]; -} - -- (NSString *)description { - return [NSString stringWithFormat:@"indexedValues = %@", indexedValues]; -} - -- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len { - return [indexedValues countByEnumeratingWithState:state objects:buffer count:len]; -} - - -@end - -@interface TestKeyed : NSObject <NSFastEnumeration> { - NSMutableDictionary *keyedValues; -} -@property(readonly) NSUInteger count; -- (id)objectForKeyedSubscript:(id)key; -- (void)setObject:(id)object forKeyedSubscript:(id)key; -@end - -@implementation TestKeyed - -- (id)init { - if ((self = [super init])) { - keyedValues = [NSMutableDictionary new]; - } - return self; -} - -#if !__has_feature(objc_arc) -- (void)dealloc { - [keyedValues release]; - [super dealloc]; -} -#endif - -- (NSUInteger)count { return [keyedValues count]; } -- (id)objectForKeyedSubscript:(id)key { return [keyedValues objectForKey:key]; } -- (void)setObject:(id)object forKeyedSubscript:(id)key { - [keyedValues setObject:object forKey:key]; -} - -- (NSString *)description { - return [NSString stringWithFormat:@"keyedValues = %@", keyedValues]; -} - -- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len { - return [keyedValues countByEnumeratingWithState:state objects:buffer count:len]; -} - -@end - -int main() { - PUSH_POOL { - -#if __has_feature(objc_bool) // placeholder until we get a more precise macro. - TestIndexed *testIndexed = [TestIndexed new]; - id objects[] = { @1, @2, @3, @4, @5 }; - size_t i, count = sizeof(objects) / sizeof(id); - for (i = 0; i < count; ++i) { - testIndexed[NSNotFound] = objects[i]; - } - for (i = 0; i < count; ++i) { - id object = testIndexed[i]; - testassert(object == objects[i]); - } - if (getenv("VERBOSE")) { - i = 0; - for (id object in testIndexed) { - NSString *message = [NSString stringWithFormat:@"testIndexed[%zu] = %@\n", i++, object]; - testprintf([message UTF8String]); - } - } - - TestKeyed *testKeyed = [TestKeyed new]; - id keys[] = { @"One", @"Two", @"Three", @"Four", @"Five" }; - for (i = 0; i < count; ++i) { - id key = keys[i]; - testKeyed[key] = objects[i]; - } - for (i = 0; i < count; ++i) { - id key = keys[i]; - id object = testKeyed[key]; - testassert(object == objects[i]); - } - if (getenv("VERBOSE")) { - for (id key in testKeyed) { - NSString *message = [NSString stringWithFormat:@"testKeyed[@\"%@\"] = %@\n", key, testKeyed[key]]; - testprintf([message UTF8String]); - } - } -#endif - - } POP_POOL; - - succeed(__FILE__); - - return 0; -} - -// __OBJC2__ -#endif diff --git a/objc/objc-runtime/test/super.m b/objc/objc-runtime/test/super.m deleted file mode 100644 index ff169f7..0000000 --- a/objc/objc-runtime/test/super.m +++ /dev/null @@ -1,21 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include "testroot.i" -#include <objc/objc-runtime.h> - -@interface Sub : TestRoot @end -@implementation Sub @end - -int main() -{ - // [super ...] messages are tested in msgSend.m - - testassert(class_getSuperclass([Sub class]) == [TestRoot class]); - testassert(class_getSuperclass(object_getClass([Sub class])) == object_getClass([TestRoot class])); - testassert(class_getSuperclass([TestRoot class]) == Nil); - testassert(class_getSuperclass(object_getClass([TestRoot class])) == [TestRoot class]); - testassert(class_getSuperclass(Nil) == Nil); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/synchronized-counter.m b/objc/objc-runtime/test/synchronized-counter.m deleted file mode 100644 index 7f6bd19..0000000 --- a/objc/objc-runtime/test/synchronized-counter.m +++ /dev/null @@ -1,90 +0,0 @@ -// TEST_CONFIG - -#include "test.h" - -#include <stdlib.h> -#include <pthread.h> -#include <objc/runtime.h> -#include <objc/objc-sync.h> -#include <Foundation/NSObject.h> -#include <System/pthread_machdep.h> - -// synchronized stress test -// Single locked counter incremented by many threads. - -#if defined(__arm__) -#define THREADS 16 -#define COUNT 1024*24 -#else -// 64 / 1024*24 test takes about 20s on 4x2.6GHz Mac Pro -#define THREADS 64 -#define COUNT 1024*24 -#endif - -static id lock; -static int count; - -static void *threadfn(void *arg) -{ - int n, d; - int depth = 1 + (int)(intptr_t)arg % 4; - - objc_registerThreadWithCollector(); - - for (n = 0; n < COUNT; n++) { - // Lock - for (d = 0; d < depth; d++) { - int err = objc_sync_enter(lock); - testassert(err == OBJC_SYNC_SUCCESS); - } - - // Increment - count++; - - // Unlock - for (d = 0; d < depth; d++) { - int err = objc_sync_exit(lock); - testassert(err == OBJC_SYNC_SUCCESS); - } - } - - // Verify lack of objc pthread data (should have used sync fast cache) -#ifdef __PTK_FRAMEWORK_OBJC_KEY0 - testassert(! pthread_getspecific(__PTK_FRAMEWORK_OBJC_KEY0)); -#endif - - return NULL; -} - -int main() -{ - pthread_t threads[THREADS]; - int t; - int err; - - lock = [[NSObject alloc] init]; - - // Verify objc pthread data on this thread (from +initialize) - // Worker threads shouldn't have any because of sync fast cache. -#ifdef __PTK_FRAMEWORK_OBJC_KEY0 - testassert(pthread_getspecific(__PTK_FRAMEWORK_OBJC_KEY0)); -#endif - - // Start the threads - for (t = 0; t < THREADS; t++) { - pthread_create(&threads[t], NULL, &threadfn, (void*)(intptr_t)t); - } - - // Wait for threads to finish - for (t = 0; t < THREADS; t++) { - pthread_join(threads[t], NULL); - } - - // Verify lock: should be available - // Verify count: should be THREADS*COUNT - err = objc_sync_enter(lock); - testassert(err == OBJC_SYNC_SUCCESS); - testassert(count == THREADS*COUNT); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/synchronized-grid.m b/objc/objc-runtime/test/synchronized-grid.m deleted file mode 100644 index 64c99f4..0000000 --- a/objc/objc-runtime/test/synchronized-grid.m +++ /dev/null @@ -1,114 +0,0 @@ -// TEST_CONFIG - -#include "test.h" - -#include <stdlib.h> -#include <pthread.h> -#include <objc/runtime.h> -#include <objc/objc-sync.h> -#include <Foundation/NSObject.h> - -// synchronized stress test -// 2-D grid of counters and locks. -// Each thread increments all counters some number of times. -// To increment: -// * thread picks a target [row][col] -// * thread locks all locks [row][0] to [row][col], possibly recursively -// * thread increments counter [row][col] -// * thread unlocks all of the locks - -#if defined(__arm__) -// 16 / 4 / 3 / 1024*8 test takes about 30s on 2nd gen iPod touch -#define THREADS 16 -#define ROWS 4 -#define COLS 3 -#define COUNT 1024*8 -#else -// 64 / 4 / 3 / 1024*8 test takes about 20s on 4x2.6GHz Mac Pro -#define THREADS 64 -#define ROWS 4 -#define COLS 3 -#define COUNT 1024*8 -#endif - -static id locks[ROWS][COLS]; -static int counts[ROWS][COLS]; - - -static void *threadfn(void *arg) -{ - int n, d; - int depth = 1 + (int)(intptr_t)arg % 4; - - objc_registerThreadWithCollector(); - - for (n = 0; n < COUNT; n++) { - int rrr = rand() % ROWS; - int ccc = rand() % COLS; - int rr, cc; - for (rr = 0; rr < ROWS; rr++) { - int r = (rrr+rr) % ROWS; - for (cc = 0; cc < COLS; cc++) { - int c = (ccc+cc) % COLS; - int l; - - // Lock [r][0..c] - // ... in that order to prevent deadlock - for (l = 0; l <= c; l++) { - for (d = 0; d < depth; d++) { - int err = objc_sync_enter(locks[r][l]); - testassert(err == OBJC_SYNC_SUCCESS); - } - } - - // Increment count [r][c] - counts[r][c]++; - - // Unlock [r][0..c] - // ... in that order to increase contention - for (l = 0; l <= c; l++) { - for (d = 0; d < depth; d++) { - int err = objc_sync_exit(locks[r][l]); - testassert(err == OBJC_SYNC_SUCCESS); - } - } - } - } - } - - return NULL; -} - -int main() -{ - pthread_t threads[THREADS]; - int r, c, t; - - for (r = 0; r < ROWS; r++) { - for (c = 0; c < COLS; c++) { - locks[r][c] = [[NSObject alloc] init]; - } - } - - // Start the threads - for (t = 0; t < THREADS; t++) { - pthread_create(&threads[t], NULL, &threadfn, (void*)(intptr_t)t); - } - - // Wait for threads to finish - for (t = 0; t < THREADS; t++) { - pthread_join(threads[t], NULL); - } - - // Verify locks: all should be available - // Verify counts: all should be THREADS*COUNT - for (r = 0; r < ROWS; r++) { - for (c = 0; c < COLS; c++) { - int err = objc_sync_enter(locks[r][c]); - testassert(err == OBJC_SYNC_SUCCESS); - testassert(counts[r][c] == THREADS*COUNT); - } - } - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/synchronized.m b/objc/objc-runtime/test/synchronized.m deleted file mode 100644 index 11922be..0000000 --- a/objc/objc-runtime/test/synchronized.m +++ /dev/null @@ -1,104 +0,0 @@ -// TEST_CONFIG - -#include "test.h" - -#include <Foundation/NSObject.h> -#include <mach/mach.h> -#include <pthread.h> -#include <sys/time.h> -#include <objc/runtime.h> -#include <objc/objc-sync.h> - -// Basic @synchronized tests. - - -#define WAIT_SEC 3 - -static id obj; -static semaphore_t go; -static semaphore_t stop; - -void *thread(void *arg __unused) -{ - int err; - - objc_registerThreadWithCollector(); - - // non-blocking sync_enter - err = objc_sync_enter(obj); - testassert(err == OBJC_SYNC_SUCCESS); - - semaphore_signal(go); - // main thread: sync_exit of object locked on some other thread - semaphore_wait(stop); - - err = objc_sync_exit(obj); - testassert(err == OBJC_SYNC_SUCCESS); - err = objc_sync_enter(obj); - testassert(err == OBJC_SYNC_SUCCESS); - - semaphore_signal(go); - // main thread: blocking sync_enter - testassert(WAIT_SEC/3*3 == WAIT_SEC); - sleep(WAIT_SEC/3); - // recursive enter while someone waits - err = objc_sync_enter(obj); - testassert(err == OBJC_SYNC_SUCCESS); - sleep(WAIT_SEC/3); - // recursive exit while someone waits - err = objc_sync_exit(obj); - testassert(err == OBJC_SYNC_SUCCESS); - sleep(WAIT_SEC/3); - // sync_exit while someone waits - err = objc_sync_exit(obj); - testassert(err == OBJC_SYNC_SUCCESS); - - return NULL; -} - -int main() -{ - pthread_t th; - int err; - struct timeval start, end; - - obj = [[NSObject alloc] init]; - - // sync_exit of never-locked object - err = objc_sync_exit(obj); - testassert(err == OBJC_SYNC_NOT_OWNING_THREAD_ERROR); - - semaphore_create(mach_task_self(), &go, 0, 0); - semaphore_create(mach_task_self(), &stop, 0, 0); - pthread_create(&th, NULL, &thread, NULL); - semaphore_wait(go); - - // sync_exit of object locked on some other thread - err = objc_sync_exit(obj); - testassert(err == OBJC_SYNC_NOT_OWNING_THREAD_ERROR); - - semaphore_signal(stop); - semaphore_wait(go); - - // blocking sync_enter - gettimeofday(&start, NULL); - err = objc_sync_enter(obj); - gettimeofday(&end, NULL); - testassert(err == OBJC_SYNC_SUCCESS); - // should have waited more than WAIT_SEC but less than WAIT_SEC+1 - // fixme hack: sleep(1) is ending 500 usec too early on x86_64 buildbot - // (rdar://6456975) - testassert(end.tv_sec*1000000LL+end.tv_usec >= - start.tv_sec*1000000LL+start.tv_usec + WAIT_SEC*1000000LL - - 3*500 /*hack*/); - testassert(end.tv_sec*1000000LL+end.tv_usec < - start.tv_sec*1000000LL+start.tv_usec + (1+WAIT_SEC)*1000000LL); - - err = objc_sync_exit(obj); - testassert(err == OBJC_SYNC_SUCCESS); - - err = objc_sync_exit(obj); - testassert(err == OBJC_SYNC_NOT_OWNING_THREAD_ERROR); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/taggedNSPointers.m b/objc/objc-runtime/test/taggedNSPointers.m deleted file mode 100644 index f8b5732..0000000 --- a/objc/objc-runtime/test/taggedNSPointers.m +++ /dev/null @@ -1,80 +0,0 @@ -// TEST_CFLAGS -framework Foundation - -#include "test.h" -#include <objc/runtime.h> -#import <Foundation/Foundation.h> - -#if OBJC_HAVE_TAGGED_POINTERS - -void testTaggedNumber() -{ - NSNumber *taggedNS = [NSNumber numberWithInt: 1234]; - CFNumberRef taggedCF = (CFNumberRef)objc_unretainedPointer(taggedNS); - int result; - - testassert( CFGetTypeID(taggedCF) == CFNumberGetTypeID() ); - testassert(_objc_getClassForTag(OBJC_TAG_NSNumber) == [taggedNS class]); - - CFNumberGetValue(taggedCF, kCFNumberIntType, &result); - testassert(result == 1234); - - testassert(_objc_isTaggedPointer(taggedCF)); - testassert(_objc_getTaggedPointerTag(taggedCF) == OBJC_TAG_NSNumber); - testassert(_objc_makeTaggedPointer(_objc_getTaggedPointerTag(taggedCF), _objc_getTaggedPointerValue(taggedCF)) == taggedCF); - - // do some generic object-y things to the taggedPointer instance - CFRetain(taggedCF); - CFRelease(taggedCF); - - NSMutableDictionary *dict = [NSMutableDictionary dictionary]; - [dict setObject: taggedNS forKey: @"fred"]; - testassert(taggedNS == [dict objectForKey: @"fred"]); - [dict setObject: @"bob" forKey: taggedNS]; - testassert([@"bob" isEqualToString: [dict objectForKey: taggedNS]]); - - NSNumber *iM88 = [NSNumber numberWithInt:-88]; - NSNumber *i12346 = [NSNumber numberWithInt: 12346]; - NSNumber *i12347 = [NSNumber numberWithInt: 12347]; - - NSArray *anArray = [NSArray arrayWithObjects: iM88, i12346, i12347, nil]; - testassert([anArray count] == 3); - testassert([anArray indexOfObject: i12346] == 1); - - NSSet *aSet = [NSSet setWithObjects: iM88, i12346, i12347, nil]; - testassert([aSet count] == 3); - testassert([aSet containsObject: i12346]); - - [taggedNS performSelector: @selector(intValue)]; - testassert(![taggedNS isProxy]); - testassert([taggedNS isKindOfClass: [NSNumber class]]); - testassert([taggedNS respondsToSelector: @selector(intValue)]); - - (void)[taggedNS description]; -} - -int main() -{ - PUSH_POOL { - testTaggedNumber(); // should be tested by CF... our tests are wrong, wrong, wrong. - } POP_POOL; - - succeed(__FILE__); -} - -// OBJC_HAVE_TAGGED_POINTERS -#else -// not OBJC_HAVE_TAGGED_POINTERS - -// Tagged pointers not supported. Crash if an NSNumber actually -// is a tagged pointer (which means this test is out of date). - -int main() -{ - PUSH_POOL { - testassert(*(void **)objc_unretainedPointer([NSNumber numberWithInt:1234])); - } POP_POOL; - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/taggedPointers.m b/objc/objc-runtime/test/taggedPointers.m deleted file mode 100644 index ae4e994..0000000 --- a/objc/objc-runtime/test/taggedPointers.m +++ /dev/null @@ -1,322 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include <objc/runtime.h> -#include <objc/objc-internal.h> -#include <objc/objc-gdb.h> -#include <dlfcn.h> -#import <Foundation/NSObject.h> - -#if OBJC_HAVE_TAGGED_POINTERS - -#if !__OBJC2__ || (!__x86_64__ && !__arm64__) -#error wrong architecture for tagged pointers -#endif - -static BOOL didIt; - -@interface WeakContainer : NSObject -{ - @public - __weak id weaks[10000]; -} -@end -@implementation WeakContainer --(void) dealloc { - for (unsigned int i = 0; i < sizeof(weaks)/sizeof(weaks[0]); i++) { - testassert(weaks[i] == nil); - } - SUPER_DEALLOC(); -} --(void) finalize { - for (unsigned int i = 0; i < sizeof(weaks)/sizeof(weaks[0]); i++) { - testassert(weaks[i] == nil); - } - [super finalize]; -} -@end - -OBJC_ROOT_CLASS -@interface TaggedBaseClass -@end - -@implementation TaggedBaseClass --(id) self { return self; } - -+ (void) initialize { -} - -- (void) instanceMethod { - didIt = YES; -} - -- (uintptr_t) taggedValue { - return _objc_getTaggedPointerValue(objc_unretainedPointer(self)); -} - -- (struct stret) stret: (struct stret) aStruct { - return aStruct; -} - -- (long double) fpret: (long double) aValue { - return aValue; -} - - --(void) dealloc { - fail("TaggedBaseClass dealloc called!"); -} - -static void * -retain_fn(void *self, SEL _cmd __unused) { - void * (*fn)(void *) = (typeof(fn))_objc_rootRetain; - return fn(self); -} - -static void -release_fn(void *self, SEL _cmd __unused) { - void (*fn)(void *) = (typeof(fn))_objc_rootRelease; - fn(self); -} - -static void * -autorelease_fn(void *self, SEL _cmd __unused) { - void * (*fn)(void *) = (typeof(fn))_objc_rootAutorelease; - return fn(self); -} - -static unsigned long -retaincount_fn(void *self, SEL _cmd __unused) { - unsigned long (*fn)(void *) = (typeof(fn))_objc_rootRetainCount; - return fn(self); -} - -+(void) load { - class_addMethod(self, sel_registerName("retain"), (IMP)retain_fn, ""); - class_addMethod(self, sel_registerName("release"), (IMP)release_fn, ""); - class_addMethod(self, sel_registerName("autorelease"), (IMP)autorelease_fn, ""); - class_addMethod(self, sel_registerName("retainCount"), (IMP)retaincount_fn, ""); -} - -@end - -@interface TaggedSubclass: TaggedBaseClass -@end - -@implementation TaggedSubclass - -- (void) instanceMethod { - return [super instanceMethod]; -} - -- (uintptr_t) taggedValue { - return [super taggedValue]; -} - -- (struct stret) stret: (struct stret) aStruct { - return [super stret: aStruct]; -} - -- (long double) fpret: (long double) aValue { - return [super fpret: aValue]; -} -@end - -@interface TaggedNSObjectSubclass : NSObject -@end - -@implementation TaggedNSObjectSubclass - -- (void) instanceMethod { - didIt = YES; -} - -- (uintptr_t) taggedValue { - return _objc_getTaggedPointerValue(objc_unretainedPointer(self)); -} - -- (struct stret) stret: (struct stret) aStruct { - return aStruct; -} - -- (long double) fpret: (long double) aValue { - return aValue; -} -@end - -void testTaggedPointerValue(Class cls, objc_tag_index_t tag, uintptr_t value) -{ - void *taggedAddress = _objc_makeTaggedPointer(tag, value); - testprintf("obj %p, tag %p, value %p\n", - taggedAddress, (void*)tag, (void*)value); - - // _objc_makeTaggedPointer must quietly mask out of range values for now - value = (value << 4) >> 4; - - testassert(_objc_isTaggedPointer(taggedAddress)); - testassert(_objc_getTaggedPointerTag(taggedAddress) == tag); - testassert(_objc_getTaggedPointerValue(taggedAddress) == value); - - testassert((uintptr_t)taggedAddress & objc_debug_taggedpointer_mask); - uintptr_t slot = ((uintptr_t)taggedAddress >> objc_debug_taggedpointer_slot_shift) & objc_debug_taggedpointer_slot_mask; - testassert(objc_debug_taggedpointer_classes[slot] == cls); - testassert((((uintptr_t)taggedAddress << objc_debug_taggedpointer_payload_lshift) >> objc_debug_taggedpointer_payload_rshift) == value); - - id taggedPointer = objc_unretainedObject(taggedAddress); - testassert(!object_isClass(taggedPointer)); - testassert(object_getClass(taggedPointer) == cls); - testassert([taggedPointer taggedValue] == value); - - didIt = NO; - [taggedPointer instanceMethod]; - testassert(didIt); - - struct stret orig = STRET_RESULT; - testassert(stret_equal(orig, [taggedPointer stret: orig])); - - long double dblvalue = 3.14156789; - testassert(dblvalue == [taggedPointer fpret: dblvalue]); - - objc_setAssociatedObject(taggedPointer, (__bridge void *)taggedPointer, taggedPointer, OBJC_ASSOCIATION_RETAIN); - testassert(objc_getAssociatedObject(taggedPointer, (__bridge void *)taggedPointer) == taggedPointer); - objc_setAssociatedObject(taggedPointer, (__bridge void *)taggedPointer, nil, OBJC_ASSOCIATION_RETAIN); - testassert(objc_getAssociatedObject(taggedPointer, (__bridge void *)taggedPointer) == nil); -} - -void testGenericTaggedPointer(objc_tag_index_t tag, Class cls) -{ - testassert(cls); - testprintf("%s\n", class_getName(cls)); - - testTaggedPointerValue(cls, tag, 0); - testTaggedPointerValue(cls, tag, 1UL << 0); - testTaggedPointerValue(cls, tag, 1UL << 1); - testTaggedPointerValue(cls, tag, 1UL << 58); - testTaggedPointerValue(cls, tag, 1UL << 59); - testTaggedPointerValue(cls, tag, ~0UL >> 4); - testTaggedPointerValue(cls, tag, ~0UL); - - // Tagged pointers should bypass refcount tables and autorelease pools - // and weak reference tables - WeakContainer *w = [WeakContainer new]; -#if !__has_feature(objc_arc) - // prime method caches before leak checking - id taggedPointer = (id)_objc_makeTaggedPointer(tag, 1234); - [taggedPointer retain]; - [taggedPointer release]; - [taggedPointer autorelease]; -#endif - leak_mark(); - for (uintptr_t i = 0; i < sizeof(w->weaks)/sizeof(w->weaks[0]); i++) { - id o = objc_unretainedObject(_objc_makeTaggedPointer(tag, i)); - testassert(object_getClass(o) == cls); - - id result = WEAK_STORE(w->weaks[i], o); - testassert(result == o); - testassert(w->weaks[i] == o); - - result = WEAK_LOAD(w->weaks[i]); - testassert(result == o); - - if (!objc_collectingEnabled()) { - uintptr_t rc = _objc_rootRetainCount(o); - testassert(rc != 0); - _objc_rootRelease(o); testassert(_objc_rootRetainCount(o) == rc); - _objc_rootRelease(o); testassert(_objc_rootRetainCount(o) == rc); - _objc_rootRetain(o); testassert(_objc_rootRetainCount(o) == rc); - _objc_rootRetain(o); testassert(_objc_rootRetainCount(o) == rc); - _objc_rootRetain(o); testassert(_objc_rootRetainCount(o) == rc); -#if !__has_feature(objc_arc) - [o release]; testassert(_objc_rootRetainCount(o) == rc); - [o release]; testassert(_objc_rootRetainCount(o) == rc); - [o retain]; testassert(_objc_rootRetainCount(o) == rc); - [o retain]; testassert(_objc_rootRetainCount(o) == rc); - [o retain]; testassert(_objc_rootRetainCount(o) == rc); - objc_release(o); testassert(_objc_rootRetainCount(o) == rc); - objc_release(o); testassert(_objc_rootRetainCount(o) == rc); - objc_retain(o); testassert(_objc_rootRetainCount(o) == rc); - objc_retain(o); testassert(_objc_rootRetainCount(o) == rc); - objc_retain(o); testassert(_objc_rootRetainCount(o) == rc); -#endif - PUSH_POOL { - testassert(_objc_rootRetainCount(o) == rc); - _objc_rootAutorelease(o); - testassert(_objc_rootRetainCount(o) == rc); -#if !__has_feature(objc_arc) - [o autorelease]; - testassert(_objc_rootRetainCount(o) == rc); - objc_autorelease(o); - testassert(_objc_rootRetainCount(o) == rc); - objc_retainAutorelease(o); - testassert(_objc_rootRetainCount(o) == rc); - objc_autoreleaseReturnValue(o); - testassert(_objc_rootRetainCount(o) == rc); - objc_retainAutoreleaseReturnValue(o); - testassert(_objc_rootRetainCount(o) == rc); - objc_retainAutoreleasedReturnValue(o); - testassert(_objc_rootRetainCount(o) == rc); -#endif - } POP_POOL; - testassert(_objc_rootRetainCount(o) == rc); - } - } - leak_check(0); - for (uintptr_t i = 0; i < 10000; i++) { - testassert(w->weaks[i] != NULL); - WEAK_STORE(w->weaks[i], NULL); - testassert(w->weaks[i] == NULL); - testassert(WEAK_LOAD(w->weaks[i]) == NULL); - } - RELEASE_VAR(w); -} - -int main() -{ - if (objc_collecting_enabled()) { - // GC's block objects crash without this - dlopen("/System/Library/Frameworks/Foundation.framework/Foundation", RTLD_LAZY); - } - - testassert(objc_debug_taggedpointer_mask != 0); - testassert(_objc_taggedPointersEnabled()); - - PUSH_POOL { - // Avoid CF's tagged pointer tags because of rdar://11368528 - - _objc_registerTaggedPointerClass(OBJC_TAG_1, - objc_getClass("TaggedBaseClass")); - testGenericTaggedPointer(OBJC_TAG_1, - objc_getClass("TaggedBaseClass")); - - _objc_registerTaggedPointerClass(OBJC_TAG_7, - objc_getClass("TaggedSubclass")); - testGenericTaggedPointer(OBJC_TAG_7, - objc_getClass("TaggedSubclass")); - - _objc_registerTaggedPointerClass(OBJC_TAG_NSManagedObjectID, - objc_getClass("TaggedNSObjectSubclass")); - testGenericTaggedPointer(OBJC_TAG_NSManagedObjectID, - objc_getClass("TaggedNSObjectSubclass")); - } POP_POOL; - - succeed(__FILE__); -} - -// OBJC_HAVE_TAGGED_POINTERS -#else -// not OBJC_HAVE_TAGGED_POINTERS - -// Tagged pointers not supported. - -int main() -{ -#if __OBJC2__ - testassert(objc_debug_taggedpointer_mask == 0); -#else - testassert(!dlsym(RTLD_DEFAULT, "objc_debug_taggedpointer_mask")); -#endif - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/taggedPointersDisabled.m b/objc/objc-runtime/test/taggedPointersDisabled.m deleted file mode 100644 index 5e1ce59..0000000 --- a/objc/objc-runtime/test/taggedPointersDisabled.m +++ /dev/null @@ -1,31 +0,0 @@ -// TEST_ENV OBJC_DISABLE_TAGGED_POINTERS=YES -// TEST_CRASHES -/* -TEST_RUN_OUTPUT -objc\[\d+\]: tagged pointers are disabled -CRASHED: SIG(ILL|TRAP) -OR -OK: taggedPointersDisabled.m -END -*/ - -#include "test.h" -#include <objc/objc-internal.h> - -#if !OBJC_HAVE_TAGGED_POINTERS - -int main() -{ - succeed(__FILE__); -} - -#else - -int main() -{ - testassert(!_objc_taggedPointersEnabled()); - _objc_registerTaggedPointerClass((objc_tag_index_t)0, nil); - fail("should have crashed in _objc_registerTaggedPointerClass()"); -} - -#endif diff --git a/objc/objc-runtime/test/tbi.c b/objc/objc-runtime/test/tbi.c deleted file mode 100644 index 93c2022..0000000 --- a/objc/objc-runtime/test/tbi.c +++ /dev/null @@ -1,14 +0,0 @@ -// TEST_CONFIG OS=iphoneos ARCH=arm64 - -#include "test.h" - -#ifndef __arm64__ -#error wrong architecture for TBI hardware feature -#endif - -volatile int x = 123456; - -int main(void) { - testassert(*(int *)((unsigned long)&x | 0xFF00000000000000ul) == 123456); - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/test.h b/objc/objc-runtime/test/test.h deleted file mode 100644 index 232b04b..0000000 --- a/objc/objc-runtime/test/test.h +++ /dev/null @@ -1,475 +0,0 @@ -// test.h -// Common definitions for trivial test harness - - -#ifndef TEST_H -#define TEST_H - -#include <stdio.h> -#include <dlfcn.h> -#include <stdlib.h> -#include <stdarg.h> -#include <string.h> -#include <libgen.h> -#include <unistd.h> -#include <pthread.h> -#include <sys/param.h> -#include <malloc/malloc.h> -#include <mach/mach.h> -#include <mach/vm_param.h> -#include <mach/mach_time.h> -#include <objc/objc.h> -#include <objc/runtime.h> -#include <objc/message.h> -#include <objc/objc-abi.h> -#include <objc/objc-auto.h> -#include <objc/objc-internal.h> -#include <TargetConditionals.h> - -#if TARGET_OS_EMBEDDED || TARGET_IPHONE_SIMULATOR -static OBJC_INLINE malloc_zone_t *objc_collectableZone(void) { return nil; } -#endif - - -// Configuration macros - -#if !__LP64__ || TARGET_OS_WIN32 || __OBJC_GC__ || TARGET_IPHONE_SIMULATOR -# define SUPPORT_NONPOINTER_ISA 0 -#elif __x86_64__ -# define SUPPORT_NONPOINTER_ISA 1 -#elif __arm64__ -# define SUPPORT_NONPOINTER_ISA 1 -#else -# error unknown architecture -#endif - - -// Test output - -static inline void succeed(const char *name) __attribute__((noreturn)); -static inline void succeed(const char *name) -{ - if (name) { - char path[MAXPATHLEN+1]; - strcpy(path, name); - fprintf(stderr, "OK: %s\n", basename(path)); - } else { - fprintf(stderr, "OK\n"); - } - exit(0); -} - -static inline void fail(const char *msg, ...) __attribute__((noreturn)); -static inline void fail(const char *msg, ...) -{ - if (msg) { - char *msg2; - asprintf(&msg2, "BAD: %s\n", msg); - va_list v; - va_start(v, msg); - vfprintf(stderr, msg2, v); - va_end(v); - free(msg2); - } else { - fprintf(stderr, "BAD\n"); - } - exit(1); -} - -#define testassert(cond) \ - ((void) (((cond) != 0) ? (void)0 : __testassert(#cond, __FILE__, __LINE__))) -#define __testassert(cond, file, line) \ - (fail("failed assertion '%s' at %s:%u", cond, __FILE__, __LINE__)) - -/* time-sensitive assertion, disabled under valgrind */ -#define timecheck(name, time, fast, slow) \ - if (getenv("VALGRIND") && 0 != strcmp(getenv("VALGRIND"), "NO")) { \ - /* valgrind; do nothing */ \ - } else if (time > slow) { \ - fprintf(stderr, "SLOW: %s %llu, expected %llu..%llu\n", \ - name, (uint64_t)(time), (uint64_t)(fast), (uint64_t)(slow)); \ - } else if (time < fast) { \ - fprintf(stderr, "FAST: %s %llu, expected %llu..%llu\n", \ - name, (uint64_t)(time), (uint64_t)(fast), (uint64_t)(slow)); \ - } else { \ - testprintf("time: %s %llu, expected %llu..%llu\n", \ - name, (uint64_t)(time), (uint64_t)(fast), (uint64_t)(slow)); \ - } - - -static inline void testprintf(const char *msg, ...) -{ - static int verbose = -1; - if (verbose < 0) verbose = atoi(getenv("VERBOSE") ?: "0"); - - // VERBOSE=1 prints test harness info only - if (msg && verbose >= 2) { - char *msg2; - asprintf(&msg2, "VERBOSE: %s", msg); - va_list v; - va_start(v, msg); - vfprintf(stderr, msg2, v); - va_end(v); - free(msg2); - } -} - -// complain to output, but don't fail the test -// Use when warning that some test is being temporarily skipped -// because of something like a compiler bug. -static inline void testwarn(const char *msg, ...) -{ - if (msg) { - char *msg2; - asprintf(&msg2, "WARN: %s\n", msg); - va_list v; - va_start(v, msg); - vfprintf(stderr, msg2, v); - va_end(v); - free(msg2); - } -} - -static inline void testnoop() { } - -// Run GC. This is a macro to reach as high in the stack as possible. -#ifndef OBJC_NO_GC - -# if __OBJC2__ -# define testexc() -# else -# include <objc/objc-exception.h> -# define testexc() \ - do { \ - objc_exception_functions_t table = {0,0,0,0,0,0}; \ - objc_exception_get_functions(&table); \ - if (!table.throw_exc) { \ - table.throw_exc = (typeof(table.throw_exc))abort; \ - table.try_enter = (typeof(table.try_enter))testnoop; \ - table.try_exit = (typeof(table.try_exit))testnoop; \ - table.extract = (typeof(table.extract))abort; \ - table.match = (typeof(table.match))abort; \ - objc_exception_set_functions(&table); \ - } \ - } while (0) -# endif - -# define testcollect() \ - do { \ - if (objc_collectingEnabled()) { \ - testexc(); \ - objc_clear_stack(0); \ - objc_collect(OBJC_COLLECT_IF_NEEDED|OBJC_WAIT_UNTIL_DONE); \ - objc_collect(OBJC_EXHAUSTIVE_COLLECTION|OBJC_WAIT_UNTIL_DONE);\ - objc_collect(OBJC_EXHAUSTIVE_COLLECTION|OBJC_WAIT_UNTIL_DONE);\ - } \ - _objc_flush_caches(NULL); \ - } while (0) - -#else - -# define testcollect() \ - do { \ - _objc_flush_caches(NULL); \ - } while (0) - -#endif - - -// Synchronously run test code on another thread. -// This can help force GC to kill objects promptly, which some tests depend on. - -// The block object is unsafe_unretained because we must not allow -// ARC to retain them in non-Foundation tests -typedef void(^testblock_t)(void); -static __unsafe_unretained testblock_t testcodehack; -static inline void *_testthread(void *arg __unused) -{ - objc_registerThreadWithCollector(); - testcodehack(); - return NULL; -} -static inline void testonthread(__unsafe_unretained testblock_t code) -{ - // GC crashes without Foundation because the block object classes - // are insufficiently initialized. - if (objc_collectingEnabled()) { - static bool foundationified = false; - if (!foundationified) { - dlopen("/System/Library/Frameworks/Foundation.framework/Foundation", RTLD_LAZY); - foundationified = true; - } - } - - pthread_t th; - testcodehack = code; // force GC not-thread-local, avoid ARC void* casts - pthread_create(&th, NULL, _testthread, NULL); - pthread_join(th, NULL); -} - -/* Make sure libobjc does not call global operator new. - Any test that DOES need to call global operator new must - `#define TEST_CALLS_OPERATOR_NEW` before including test.h. - */ -#if __cplusplus && !defined(TEST_CALLS_OPERATOR_NEW) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Winline-new-delete" -#import <new> -inline void* operator new(std::size_t) throw (std::bad_alloc) { fail("called global operator new"); } -inline void* operator new[](std::size_t) throw (std::bad_alloc) { fail("called global operator new[]"); } -inline void* operator new(std::size_t, const std::nothrow_t&) throw() { fail("called global operator new(nothrow)"); } -inline void* operator new[](std::size_t, const std::nothrow_t&) throw() { fail("called global operator new[](nothrow)"); } -inline void operator delete(void*) throw() { fail("called global operator delete"); } -inline void operator delete[](void*) throw() { fail("called global operator delete[]"); } -inline void operator delete(void*, const std::nothrow_t&) throw() { fail("called global operator delete(nothrow)"); } -inline void operator delete[](void*, const std::nothrow_t&) throw() { fail("called global operator delete[](nothrow)"); } -#pragma clang diagnostic pop -#endif - - -/* Leak checking - Fails if total malloc memory in use at leak_check(n) - is more than n bytes above that at leak_mark(). -*/ - -static inline void leak_recorder(task_t task __unused, void *ctx, unsigned type __unused, vm_range_t *ranges, unsigned count) -{ - size_t *inuse = (size_t *)ctx; - while (count--) { - *inuse += ranges[count].size; - } -} - -static inline size_t leak_inuse(void) -{ - size_t total = 0; - vm_address_t *zones; - unsigned count; - malloc_get_all_zones(mach_task_self(), NULL, &zones, &count); - for (unsigned i = 0; i < count; i++) { - size_t inuse = 0; - malloc_zone_t *zone = (malloc_zone_t *)zones[i]; - if (!zone->introspect || !zone->introspect->enumerator) continue; - - // skip DispatchContinuations because it sometimes claims to be - // using lots of memory that then goes away later - if (0 == strcmp(zone->zone_name, "DispatchContinuations")) continue; - - zone->introspect->enumerator(mach_task_self(), &inuse, MALLOC_PTR_IN_USE_RANGE_TYPE, (vm_address_t)zone, NULL, leak_recorder); - // fprintf(stderr, "%zu in use for zone %s\n", inuse, zone->zone_name); - total += inuse; - } - - return total; -} - - -static inline void leak_dump_heap(const char *msg) -{ - fprintf(stderr, "%s\n", msg); - - // Make `heap` write to stderr - int outfd = dup(STDOUT_FILENO); - dup2(STDERR_FILENO, STDOUT_FILENO); - pid_t pid = getpid(); - char cmd[256]; - // environment variables reset for iOS simulator use - sprintf(cmd, "DYLD_LIBRARY_PATH= DYLD_ROOT_PATH= /usr/bin/heap -addresses all %d", (int)pid); - - system(cmd); - - dup2(outfd, STDOUT_FILENO); - close(outfd); -} - -static size_t _leak_start; -static inline void leak_mark(void) -{ - testcollect(); - if (getenv("LEAK_HEAP")) { - leak_dump_heap("HEAP AT leak_mark"); - } - _leak_start = leak_inuse(); -} - -#define leak_check(n) \ - do { \ - const char *_check = getenv("LEAK_CHECK"); \ - size_t inuse; \ - if (_check && 0 == strcmp(_check, "NO")) break; \ - testcollect(); \ - if (getenv("LEAK_HEAP")) { \ - leak_dump_heap("HEAP AT leak_check"); \ - } \ - inuse = leak_inuse(); \ - if (inuse > _leak_start + n) { \ - if (getenv("HANG_ON_LEAK")) { \ - printf("leaks %d\n", getpid()); \ - while (1) sleep(1); \ - } \ - fprintf(stderr, "BAD: %zu bytes leaked at %s:%u\n", \ - inuse - _leak_start, __FILE__, __LINE__); \ - } \ - } while (0) - -static inline bool is_guardmalloc(void) -{ - const char *env = getenv("GUARDMALLOC"); - return (env && 0 == strcmp(env, "YES")); -} - - -/* Memory management compatibility macros */ - -static id self_fn(id x) __attribute__((used)); -static id self_fn(id x) { return x; } - -#if __has_feature(objc_arc) - // ARC -# define RELEASE_VAR(x) x = nil -# define WEAK_STORE(dst, val) (dst = (val)) -# define WEAK_LOAD(src) (src) -# define SUPER_DEALLOC() -# define RETAIN(x) (self_fn(x)) -# define RELEASE_VALUE(x) ((void)self_fn(x)) -# define AUTORELEASE(x) (self_fn(x)) - -#elif defined(__OBJC_GC__) - // GC -# define RELEASE_VAR(x) x = nil -# define WEAK_STORE(dst, val) (dst = (val)) -# define WEAK_LOAD(src) (src) -# define SUPER_DEALLOC() [super dealloc] -# define RETAIN(x) [x self] -# define RELEASE_VALUE(x) (void)[x self] -# define AUTORELEASE(x) [x self] - -#else - // MRC -# define RELEASE_VAR(x) do { [x release]; x = nil; } while (0) -# define WEAK_STORE(dst, val) objc_storeWeak((id *)&dst, val) -# define WEAK_LOAD(src) objc_loadWeak((id *)&src) -# define SUPER_DEALLOC() [super dealloc] -# define RETAIN(x) [x retain] -# define RELEASE_VALUE(x) [x release] -# define AUTORELEASE(x) [x autorelease] -#endif - -/* gcc compatibility macros */ -/* <rdar://problem/9412038> @autoreleasepool should generate objc_autoreleasePoolPush/Pop on 10.7/5.0 */ -//#if !defined(__clang__) -# define PUSH_POOL { void *pool = objc_autoreleasePoolPush(); -# define POP_POOL objc_autoreleasePoolPop(pool); } -//#else -//# define PUSH_POOL @autoreleasepool -//# define POP_POOL -//#endif - -#if __OBJC__ - -/* General purpose root class */ - -OBJC_ROOT_CLASS -@interface TestRoot { - @public - Class isa; -} - -+(void) load; -+(void) initialize; - --(id) self; --(Class) class; --(Class) superclass; - -+(id) new; -+(id) alloc; -+(id) allocWithZone:(void*)zone; --(id) copy; --(id) mutableCopy; --(id) init; --(void) dealloc; --(void) finalize; -@end -@interface TestRoot (RR) --(id) retain; --(oneway void) release; --(id) autorelease; --(unsigned long) retainCount; --(id) copyWithZone:(void *)zone; --(id) mutableCopyWithZone:(void*)zone; -@end - -// incremented for each call of TestRoot's methods -extern int TestRootLoad; -extern int TestRootInitialize; -extern int TestRootAlloc; -extern int TestRootAllocWithZone; -extern int TestRootCopy; -extern int TestRootCopyWithZone; -extern int TestRootMutableCopy; -extern int TestRootMutableCopyWithZone; -extern int TestRootInit; -extern int TestRootDealloc; -extern int TestRootFinalize; -extern int TestRootRetain; -extern int TestRootRelease; -extern int TestRootAutorelease; -extern int TestRootRetainCount; -extern int TestRootTryRetain; -extern int TestRootIsDeallocating; -extern int TestRootPlusRetain; -extern int TestRootPlusRelease; -extern int TestRootPlusAutorelease; -extern int TestRootPlusRetainCount; - -#endif - - -// Struct that does not return in registers on any architecture - -struct stret { - int a; - int b; - int c; - int d; - int e; - int f; - int g; - int h; - int i; - int j; -}; - -static inline BOOL stret_equal(struct stret a, struct stret b) -{ - return (a.a == b.a && - a.b == b.b && - a.c == b.c && - a.d == b.d && - a.e == b.e && - a.f == b.f && - a.g == b.g && - a.h == b.h && - a.i == b.i && - a.j == b.j); -} - -static struct stret STRET_RESULT __attribute__((used)) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - - -#if TARGET_IPHONE_SIMULATOR -// Force cwd to executable's directory during launch. -// sim used to do this but simctl does not. -#include <crt_externs.h> - __attribute__((constructor)) -static void hack_cwd(void) -{ - if (!getenv("HACKED_CWD")) { - chdir(dirname((*_NSGetArgv())[0])); - setenv("HACKED_CWD", "1", 1); - } -} -#endif - -#endif diff --git a/objc/objc-runtime/test/test.pl b/objc/objc-runtime/test/test.pl deleted file mode 100755 index dda6bfa..0000000 --- a/objc/objc-runtime/test/test.pl +++ /dev/null @@ -1,1477 +0,0 @@ -#!/usr/bin/perl - -# test.pl -# Run unit tests. - -use strict; -use File::Basename; - -chdir dirname $0; -chomp (my $DIR = `pwd`); - -my $TESTLIBNAME = "libobjc.A.dylib"; -my $TESTLIBPATH = "/usr/lib/$TESTLIBNAME"; - -my $BUILDDIR = "/tmp/test-$TESTLIBNAME-build"; - -# xterm colors -my $red = "\e[41;37m"; -my $yellow = "\e[43;30m"; -my $nocolor = "\e[0m"; - -# clean, help -if (scalar(@ARGV) == 1) { - my $arg = $ARGV[0]; - if ($arg eq "clean") { - my $cmd = "rm -rf $BUILDDIR *~"; - print "$cmd\n"; - `$cmd`; - exit 0; - } - elsif ($arg eq "-h" || $arg eq "-H" || $arg eq "-help" || $arg eq "help") { - print(<<END); -usage: $0 [options] [testname ...] - $0 clean - $0 help - -testname: - `testname` runs a specific test. If no testnames are given, runs all tests. - -options: - ARCH=<arch> - OS=<sdk name>[sdk version][-<deployment target>[-<run target>]] - ROOT=/path/to/project.roots/ - - CC=<compiler name> - - LANGUAGE=c,c++,objective-c,objective-c++,swift - MEM=mrc,arc,gc - STDLIB=libc++,libstdc++ - GUARDMALLOC=0|1|before|after - - BUILD=0|1 - RUN=0|1 - VERBOSE=0|1|2 - -examples: - - test installed library, x86_64, no gc - $0 - - test buildit-built root, i386 and x86_64, MRC and ARC and GC, clang compiler - $0 ARCH=i386,x86_64 ROOT=/tmp/libclosure.roots MEM=mrc,arc,gc CC=clang - - test buildit-built root with iOS simulator, deploy to iOS 7, run on iOS 8 - $0 ARCH=i386 ROOT=/tmp/libclosure.roots OS=iphonesimulator-7.0-8.0 - - test buildit-built root on attached iOS device - $0 ARCH=armv7 ROOT=/tmp/libclosure.roots OS=iphoneos -END - exit 0; - } -} - -######################################################################### -## Tests - -my %ALL_TESTS; - -######################################################################### -## Variables for use in complex build and run rules - -# variable # example value - -# things you can multiplex on the command line -# ARCH=i386,x86_64,armv6,armv7 -# OS=macosx,iphoneos,iphonesimulator (plus sdk/deployment/run versions) -# LANGUAGE=c,c++,objective-c,objective-c++,swift -# CC=clang,gcc-4.2,llvm-gcc-4.2 -# MEM=mrc,arc,gc -# STDLIB=libc++,libstdc++ -# GUARDMALLOC=0,1,before,after - -# things you can set once on the command line -# ROOT=/path/to/project.roots -# BUILD=0|1 -# RUN=0|1 -# VERBOSE=0|1|2 - - - -my $BUILD; -my $RUN; -my $VERBOSE; - -my $crashcatch = <<'END'; -// interpose-able code to catch crashes, print, and exit cleanly -#include <signal.h> -#include <string.h> -#include <unistd.h> - -// from dyld-interposing.h -#define DYLD_INTERPOSE(_replacement,_replacee) __attribute__((used)) static struct{ const void* replacement; const void* replacee; } _interpose_##_replacee __attribute__ ((section ("__DATA,__interpose"))) = { (const void*)(unsigned long)&_replacement, (const void*)(unsigned long)&_replacee }; - -static void catchcrash(int sig) -{ - const char *msg; - switch (sig) { - case SIGILL: msg = "CRASHED: SIGILL\\n"; break; - case SIGBUS: msg = "CRASHED: SIGBUS\\n"; break; - case SIGSYS: msg = "CRASHED: SIGSYS\\n"; break; - case SIGSEGV: msg = "CRASHED: SIGSEGV\\n"; break; - case SIGTRAP: msg = "CRASHED: SIGTRAP\\n"; break; - case SIGABRT: msg = "CRASHED: SIGABRT\\n"; break; - default: msg = "SIG\?\?\?\?\\n"; break; - } - write(STDERR_FILENO, msg, strlen(msg)); - _exit(0); -} - -static void setupcrash(void) __attribute__((constructor)); -static void setupcrash(void) -{ - signal(SIGILL, &catchcrash); - signal(SIGBUS, &catchcrash); - signal(SIGSYS, &catchcrash); - signal(SIGSEGV, &catchcrash); - signal(SIGTRAP, &catchcrash); - signal(SIGABRT, &catchcrash); -} - - -static int hacked = 0; -ssize_t hacked_write(int fildes, const void *buf, size_t nbyte) -{ - if (!hacked) { - setupcrash(); - hacked = 1; - } - return write(fildes, buf, nbyte); -} - -DYLD_INTERPOSE(hacked_write, write); - -END - - -######################################################################### -## Harness - - -# map language to buildable extensions for that language -my %extensions_for_language = ( - "c" => ["c"], - "objective-c" => ["c", "m"], - "c++" => ["c", "cc", "cp", "cpp", "cxx", "c++"], - "objective-c++" => ["c", "m", "cc", "cp", "cpp", "cxx", "c++", "mm"], - "swift" => ["swift"], - - "any" => ["c", "m", "cc", "cp", "cpp", "cxx", "c++", "mm", "swift"], - ); - -# map extension to languages -my %languages_for_extension = ( - "c" => ["c", "objective-c", "c++", "objective-c++"], - "m" => ["objective-c", "objective-c++"], - "mm" => ["objective-c++"], - "cc" => ["c++", "objective-c++"], - "cp" => ["c++", "objective-c++"], - "cpp" => ["c++", "objective-c++"], - "cxx" => ["c++", "objective-c++"], - "c++" => ["c++", "objective-c++"], - "swift" => ["swift"], - ); - -# Run some newline-separated commands like `make` would, stopping if any fail -# run("cmd1 \n cmd2 \n cmd3") -sub make { - my $output = ""; - my @cmds = split("\n", $_[0]); - die if scalar(@cmds) == 0; - $? = 0; - foreach my $cmd (@cmds) { - chomp $cmd; - next if $cmd =~ /^\s*$/; - $cmd .= " 2>&1"; - print "$cmd\n" if $VERBOSE; - $output .= `$cmd`; - last if $?; - } - print "$output\n" if $VERBOSE; - return $output; -} - -sub chdir_verbose { - my $dir = shift; - print "cd $dir\n" if $VERBOSE; - chdir $dir || die; -} - - -# Return test names from the command line. -# Returns all tests if no tests were named. -sub gettests { - my @tests; - - foreach my $arg (@ARGV) { - push @tests, $arg if ($arg !~ /=/ && $arg !~ /^-/); - } - - opendir(my $dir, $DIR) || die; - while (my $file = readdir($dir)) { - my ($name, $ext) = ($file =~ /^([^.]+)\.([^.]+)$/); - next if ! $languages_for_extension{$ext}; - - open(my $in, "< $file") || die "$file"; - my $contents = join "", <$in>; - if (defined $ALL_TESTS{$name}) { - print "${yellow}SKIP: multiple tests named '$name'; skipping file '$file'.${nocolor}\n"; - } else { - $ALL_TESTS{$name} = $ext if ($contents =~ m#^[/*\s]*TEST_#m); - } - close($in); - } - closedir($dir); - - if (scalar(@tests) == 0) { - @tests = keys %ALL_TESTS; - } - - @tests = sort @tests; - - return @tests; -} - - -# Turn a C compiler name into a C++ compiler name. -sub cplusplus { - my ($c) = @_; - if ($c =~ /cc/) { - $c =~ s/cc/\+\+/; - return $c; - } - return $c . "++"; # e.g. clang => clang++ -} - -# Turn a C compiler name into a Swift compiler name -sub swift { - my ($c) = @_; - $c =~ s#[^/]*$#swift#; - return $c; -} - -# Returns an array of all sdks from `xcodebuild -showsdks` -my @sdks_memo; -sub getsdks { - if (!@sdks_memo) { - @sdks_memo = (`xcodebuild -showsdks` =~ /-sdk (.+)$/mg); - } - return @sdks_memo; -} - -my %sdk_path_memo = {}; -sub getsdkpath { - my ($sdk) = @_; - if (!defined $sdk_path_memo{$sdk}) { - ($sdk_path_memo{$sdk}) = (`xcodebuild -version -sdk '$sdk' Path` =~ /^\s*(.+?)\s*$/); - } - return $sdk_path_memo{$sdk}; -} - -# Extract a version number from a string. -# Ignore trailing "internal". -sub versionsuffix { - my ($str) = @_; - my ($vers) = ($str =~ /([0-9]+\.[0-9]+)(?:\.?internal)?$/); - return $vers; -} -sub majorversionsuffix { - my ($str) = @_; - my ($vers) = ($str =~ /([0-9]+)\.[0-9]+(?:\.?internal)?$/); - return $vers; -} -sub minorversionsuffix { - my ($str) = @_; - my ($vers) = ($str =~ /[0-9]+\.([0-9]+)(?:\.?internal)?$/); - return $vers; -} - -# Compares two SDK names and returns the newer one. -# Assumes the two SDKs are the same OS. -sub newersdk { - my ($lhs, $rhs) = @_; - - # Major version wins. - my $lhsMajor = majorversionsuffix($lhs); - my $rhsMajor = majorversionsuffix($rhs); - if ($lhsMajor > $rhsMajor) { return $lhs; } - if ($lhsMajor < $rhsMajor) { return $rhs; } - - # Minor version wins. - my $lhsMinor = minorversionsuffix($lhs); - my $rhsMinor = minorversionsuffix($rhs); - if ($lhsMinor > $rhsMinor) { return $lhs; } - if ($lhsMinor < $rhsMinor) { return $rhs; } - - # Lexically-last wins (i.e. internal is better than not internal) - if ($lhs gt $rhs) { return $lhs; } - return $rhs; -} - -# Returns whether the given sdk supports -lauto -sub supportslibauto { - my ($sdk) = @_; - return 1 if $sdk =~ /^macosx/; - return 0; -} - -# print text with a colored prefix on each line -sub colorprint { - my $color = shift; - while (my @lines = split("\n", shift)) { - for my $line (@lines) { - chomp $line; - print "$color $nocolor$line\n"; - } - } -} - -sub rewind { - seek($_[0], 0, 0); -} - -# parse name=value,value pairs -sub readconditions { - my ($conditionstring) = @_; - - my %results; - my @conditions = ($conditionstring =~ /\w+=(?:[^\s,]+,?)+/g); - for my $condition (@conditions) { - my ($name, $values) = ($condition =~ /(\w+)=(.+)/); - $results{$name} = [split ',', $values]; - } - - return %results; -} - -sub check_output { - my %C = %{shift()}; - my $name = shift; - my @output = @_; - - my %T = %{$C{"TEST_$name"}}; - - # Quietly strip MallocScribble before saving the "original" output - # because it is distracting. - filter_malloc(\@output); - - my @original_output = @output; - - # Run result-checking passes, reducing @output each time - my $xit = 1; - my $bad = ""; - my $warn = ""; - my $runerror = $T{TEST_RUN_OUTPUT}; - filter_hax(\@output); - filter_verbose(\@output); - filter_simulator(\@output); - $warn = filter_warn(\@output); - $bad |= filter_guardmalloc(\@output) if ($C{GUARDMALLOC}); - $bad |= filter_valgrind(\@output) if ($C{VALGRIND}); - $bad = filter_expected(\@output, \%C, $name) if ($bad eq ""); - $bad = filter_bad(\@output) if ($bad eq ""); - - # OK line should be the only one left - $bad = "(output not 'OK: $name')" if ($bad eq "" && (scalar(@output) != 1 || $output[0] !~ /^OK: $name/)); - - if ($bad ne "") { - print "${red}FAIL: /// test '$name' \\\\\\$nocolor\n"; - colorprint($red, @original_output); - print "${red}FAIL: \\\\\\ test '$name' ///$nocolor\n"; - print "${red}FAIL: $name: $bad$nocolor\n"; - $xit = 0; - } - elsif ($warn ne "") { - print "${yellow}PASS: /// test '$name' \\\\\\$nocolor\n"; - colorprint($yellow, @original_output); - print "${yellow}PASS: \\\\\\ test '$name' ///$nocolor\n"; - print "PASS: $name (with warnings)\n"; - } - else { - print "PASS: $name\n"; - } - return $xit; -} - -sub filter_expected -{ - my $outputref = shift; - my %C = %{shift()}; - my $name = shift; - - my %T = %{$C{"TEST_$name"}}; - my $runerror = $T{TEST_RUN_OUTPUT} || return ""; - - my $bad = ""; - - my $output = join("\n", @$outputref) . "\n"; - if ($output !~ /$runerror/) { - $bad = "(run output does not match TEST_RUN_OUTPUT)"; - @$outputref = ("FAIL: $name"); - } else { - @$outputref = ("OK: $name"); # pacify later filter - } - - return $bad; -} - -sub filter_bad -{ - my $outputref = shift; - my $bad = ""; - - my @new_output; - for my $line (@$outputref) { - if ($line =~ /^BAD: (.*)/) { - $bad = "(failed)"; - } else { - push @new_output, $line; - } - } - - @$outputref = @new_output; - return $bad; -} - -sub filter_warn -{ - my $outputref = shift; - my $warn = ""; - - my @new_output; - for my $line (@$outputref) { - if ($line !~ /^WARN: (.*)/) { - push @new_output, $line; - } else { - $warn = "(warned)"; - } - } - - @$outputref = @new_output; - return $warn; -} - -sub filter_verbose -{ - my $outputref = shift; - - my @new_output; - for my $line (@$outputref) { - if ($line !~ /^VERBOSE: (.*)/) { - push @new_output, $line; - } - } - - @$outputref = @new_output; -} - -sub filter_simulator -{ - my $outputref = shift; - - my @new_output; - for my $line (@$outputref) { - if ($line !~ /No simulator devices appear to be running/) { - push @new_output, $line; - } - } - - @$outputref = @new_output; -} - -sub filter_simulator -{ - my $outputref = shift; - - my @new_output; - for my $line (@$outputref) { - if ($line !~ /No simulator devices appear to be running/) { - push @new_output, $line; - } - } - - @$outputref = @new_output; -} - -sub filter_hax -{ - my $outputref = shift; - - my @new_output; - for my $line (@$outputref) { - if ($line !~ /Class OS_tcp_/) { - push @new_output, $line; - } - } - - @$outputref = @new_output; -} - -sub filter_valgrind -{ - my $outputref = shift; - my $errors = 0; - my $leaks = 0; - - my @new_output; - for my $line (@$outputref) { - if ($line =~ /^Approx: do_origins_Dirty\([RW]\): missed \d bytes$/) { - # --track-origins warning (harmless) - next; - } - if ($line =~ /^UNKNOWN __disable_threadsignal is unsupported. This warning will not be repeated.$/) { - # signals unsupported (harmless) - next; - } - if ($line =~ /^UNKNOWN __pthread_sigmask is unsupported. This warning will not be repeated.$/) { - # signals unsupported (harmless) - next; - } - if ($line !~ /^^\.*==\d+==/) { - # not valgrind output - push @new_output, $line; - next; - } - - my ($errcount) = ($line =~ /==\d+== ERROR SUMMARY: (\d+) errors/); - if (defined $errcount && $errcount > 0) { - $errors = 1; - } - - (my $leakcount) = ($line =~ /==\d+==\s+(?:definitely|possibly) lost:\s+([0-9,]+)/); - if (defined $leakcount && $leakcount > 0) { - $leaks = 1; - } - } - - @$outputref = @new_output; - - my $bad = ""; - $bad .= "(valgrind errors)" if ($errors); - $bad .= "(valgrind leaks)" if ($leaks); - return $bad; -} - - - -sub filter_malloc -{ - my $outputref = shift; - my $errors = 0; - - my @new_output; - my $count = 0; - for my $line (@$outputref) { - # Ignore MallocScribble prologue. - # Ignore MallocStackLogging prologue. - if ($line =~ /malloc: enabling scribbling to detect mods to free/ || - $line =~ /Deleted objects will be dirtied by the collector/ || - $line =~ /malloc: stack logs being written into/ || - $line =~ /malloc: stack logs deleted from/ || - $line =~ /malloc: process \d+ no longer exists/ || - $line =~ /malloc: recording malloc and VM allocation stacks/) - { - next; - } - - # not malloc output - push @new_output, $line; - - } - - @$outputref = @new_output; -} - -sub filter_guardmalloc -{ - my $outputref = shift; - my $errors = 0; - - my @new_output; - my $count = 0; - for my $line (@$outputref) { - if ($line !~ /^GuardMalloc\[[^\]]+\]: /) { - # not guardmalloc output - push @new_output, $line; - next; - } - - # Ignore 4 lines of guardmalloc prologue. - # Anything further is a guardmalloc error. - if (++$count > 4) { - $errors = 1; - } - } - - @$outputref = @new_output; - - my $bad = ""; - $bad .= "(guardmalloc errors)" if ($errors); - return $bad; -} - -# TEST_SOMETHING -# text -# text -# END -sub extract_multiline { - my ($flag, $contents, $name) = @_; - if ($contents =~ /$flag\n/) { - my ($output) = ($contents =~ /$flag\n(.*?\n)END[ *\/]*\n/s); - die "$name used $flag without END\n" if !defined($output); - return $output; - } - return undef; -} - - -# TEST_SOMETHING -# text -# OR -# text -# END -sub extract_multiple_multiline { - my ($flag, $contents, $name) = @_; - if ($contents =~ /$flag\n/) { - my ($output) = ($contents =~ /$flag\n(.*?\n)END[ *\/]*\n/s); - die "$name used $flag without END\n" if !defined($output); - - $output =~ s/\nOR\n/\n|/sg; - $output = "^(" . $output . ")\$"; - return $output; - } - return undef; -} - - -sub gather_simple { - my $CREF = shift; - my %C = %{$CREF}; - my $name = shift; - chdir_verbose $DIR; - - my $ext = $ALL_TESTS{$name}; - my $file = "$name.$ext"; - return 0 if !$file; - - # search file for 'TEST_CONFIG' or '#include "test.h"' - # also collect other values: - # TEST_DISABLED disable test with an optional message - # TEST_CRASHES test is expected to crash - # TEST_CONFIG test conditions - # TEST_ENV environment prefix - # TEST_CFLAGS compile flags - # TEST_BUILD build instructions - # TEST_BUILD_OUTPUT expected build stdout/stderr - # TEST_RUN_OUTPUT expected run stdout/stderr - open(my $in, "< $file") || die; - my $contents = join "", <$in>; - - my $test_h = ($contents =~ /^\s*#\s*(include|import)\s*"test\.h"/m); - my ($disabled) = ($contents =~ /\b(TEST_DISABLED\b.*)$/m); - my $crashes = ($contents =~ /\bTEST_CRASHES\b/m); - my ($conditionstring) = ($contents =~ /\bTEST_CONFIG\b(.*)$/m); - my ($envstring) = ($contents =~ /\bTEST_ENV\b(.*)$/m); - my ($cflags) = ($contents =~ /\bTEST_CFLAGS\b(.*)$/m); - my ($buildcmd) = extract_multiline("TEST_BUILD", $contents, $name); - my ($builderror) = extract_multiple_multiline("TEST_BUILD_OUTPUT", $contents, $name); - my ($runerror) = extract_multiple_multiline("TEST_RUN_OUTPUT", $contents, $name); - - return 0 if !$test_h && !$disabled && !$crashes && !defined($conditionstring) && !defined($envstring) && !defined($cflags) && !defined($buildcmd) && !defined($builderror) && !defined($runerror); - - if ($disabled) { - print "${yellow}SKIP: $name (disabled by $disabled)$nocolor\n"; - return 0; - } - - # check test conditions - - my $run = 1; - my %conditions = readconditions($conditionstring); - if (! $conditions{LANGUAGE}) { - # implicit language restriction from file extension - $conditions{LANGUAGE} = $languages_for_extension{$ext}; - } - for my $condkey (keys %conditions) { - my @condvalues = @{$conditions{$condkey}}; - - # special case: RUN=0 does not affect build - if ($condkey eq "RUN" && @condvalues == 1 && $condvalues[0] == 0) { - $run = 0; - next; - } - - my $testvalue = $C{$condkey}; - next if !defined($testvalue); - # testvalue is the configuration being run now - # condvalues are the allowed values for this test - - my $ok = 0; - for my $condvalue (@condvalues) { - - # special case: objc and objc++ - if ($condkey eq "LANGUAGE") { - $condvalue = "objective-c" if $condvalue eq "objc"; - $condvalue = "objective-c++" if $condvalue eq "objc++"; - } - - $ok = 1 if ($testvalue eq $condvalue); - - # special case: CC and CXX allow substring matches - if ($condkey eq "CC" || $condkey eq "CXX") { - $ok = 1 if ($testvalue =~ /$condvalue/); - } - - last if $ok; - } - - if (!$ok) { - my $plural = (@condvalues > 1) ? "one of: " : ""; - print "SKIP: $name ($condkey=$testvalue, but test requires $plural", join(' ', @condvalues), ")\n"; - return 0; - } - } - - # save some results for build and run phases - $$CREF{"TEST_$name"} = { - TEST_BUILD => $buildcmd, - TEST_BUILD_OUTPUT => $builderror, - TEST_CRASHES => $crashes, - TEST_RUN_OUTPUT => $runerror, - TEST_CFLAGS => $cflags, - TEST_ENV => $envstring, - TEST_RUN => $run, - }; - - return 1; -} - -# Builds a simple test -sub build_simple { - my %C = %{shift()}; - my $name = shift; - my %T = %{$C{"TEST_$name"}}; - chdir_verbose "$C{DIR}/$name.build"; - - my $ext = $ALL_TESTS{$name}; - my $file = "$DIR/$name.$ext"; - - if ($T{TEST_CRASHES}) { - `echo '$crashcatch' > crashcatch.c`; - make("$C{COMPILE_C} -dynamiclib -o libcrashcatch.dylib -x c crashcatch.c"); - die "$?" if $?; - } - - my $cmd = $T{TEST_BUILD} ? eval "return \"$T{TEST_BUILD}\"" : "$C{COMPILE} $T{TEST_CFLAGS} $file -o $name.out"; - - my $output = make($cmd); - - # rdar://10163155 - $output =~ s/ld: warning: could not create compact unwind for [^\n]+: does not use standard frame\n//g; - - my $ok; - if (my $builderror = $T{TEST_BUILD_OUTPUT}) { - # check for expected output and ignore $? - if ($output =~ /$builderror/) { - $ok = 1; - } else { - print "${red}FAIL: /// test '$name' \\\\\\$nocolor\n"; - colorprint $red, $output; - print "${red}FAIL: \\\\\\ test '$name' ///$nocolor\n"; - print "${red}FAIL: $name (build output does not match TEST_BUILD_OUTPUT)$nocolor\n"; - $ok = 0; - } - } elsif ($?) { - print "${red}FAIL: /// test '$name' \\\\\\$nocolor\n"; - colorprint $red, $output; - print "${red}FAIL: \\\\\\ test '$name' ///$nocolor\n"; - print "${red}FAIL: $name (build failed)$nocolor\n"; - $ok = 0; - } elsif ($output ne "") { - print "${red}FAIL: /// test '$name' \\\\\\$nocolor\n"; - colorprint $red, $output; - print "${red}FAIL: \\\\\\ test '$name' ///$nocolor\n"; - print "${red}FAIL: $name (unexpected build output)$nocolor\n"; - $ok = 0; - } else { - $ok = 1; - } - - - if ($ok) { - foreach my $file (glob("*.out *.dylib *.bundle")) { - make("dsymutil $file"); - } - } - - return $ok; -} - -# Run a simple test (testname.out, with error checking of stdout and stderr) -sub run_simple { - my %C = %{shift()}; - my $name = shift; - my %T = %{$C{"TEST_$name"}}; - - if (! $T{TEST_RUN}) { - print "PASS: $name (build only)\n"; - return 1; - } - - my $testdir = "$C{DIR}/$name.build"; - chdir_verbose $testdir; - - my $env = "$C{ENV} $T{TEST_ENV}"; - - my $output; - - if ($C{ARCH} =~ /^arm/ && `unamep -p` !~ /^arm/) { - # run on iOS or watchos device - - my $remotedir = "/var/root/objctest/" . basename($C{DIR}) . "/$name.build"; - - # Add test dir and libobjc's dir to DYLD_LIBRARY_PATH. - # Insert libcrashcatch.dylib if necessary. - $env .= " DYLD_LIBRARY_PATH=$remotedir"; - $env .= ":/var/root/objctest/" if ($C{TESTLIB} ne $TESTLIBPATH); - if ($T{TEST_CRASHES}) { - $env .= " DYLD_INSERT_LIBRARIES=$remotedir/libcrashcatch.dylib"; - } - - my $cmd = "ssh iphone 'cd $remotedir && env $env ./$name.out'"; - $output = make("$cmd"); - } - elsif ($C{OS} =~ /simulator/) { - # run locally in an iOS simulator - # fixme appletvsimulator and watchsimulator - # fixme SDK - my $sim = "xcrun -sdk iphonesimulator simctl spawn 'iPhone 6'"; - - # Add test dir and libobjc's dir to DYLD_LIBRARY_PATH. - # Insert libcrashcatch.dylib if necessary. - $env .= " DYLD_LIBRARY_PATH=$testdir"; - $env .= ":" . dirname($C{TESTLIB}) if ($C{TESTLIB} ne $TESTLIBPATH); - if ($T{TEST_CRASHES}) { - $env .= " DYLD_INSERT_LIBRARIES=$testdir/libcrashcatch.dylib"; - } - - my $simenv = ""; - foreach my $keyvalue (split(' ', $env)) { - $simenv .= "SIMCTL_CHILD_$keyvalue "; - } - # Use the full path here so hack_cwd in test.h works. - $output = make("env $simenv $sim $testdir/$name.out"); - } - else { - # run locally - - # Add test dir and libobjc's dir to DYLD_LIBRARY_PATH. - # Insert libcrashcatch.dylib if necessary. - $env .= " DYLD_LIBRARY_PATH=$testdir"; - $env .= ":" . dirname($C{TESTLIB}) if ($C{TESTLIB} ne $TESTLIBPATH); - if ($T{TEST_CRASHES}) { - $env .= " DYLD_INSERT_LIBRARIES=$testdir/libcrashcatch.dylib"; - } - - $output = make("sh -c '$env ./$name.out'"); - } - - return check_output(\%C, $name, split("\n", $output)); -} - - -my %compiler_memo; -sub find_compiler { - my ($cc, $toolchain, $sdk_path) = @_; - - # memoize - my $key = $cc . ':' . $toolchain; - my $result = $compiler_memo{$key}; - return $result if defined $result; - - $result = make("xcrun -toolchain $toolchain -find $cc 2>/dev/null"); - - chomp $result; - $compiler_memo{$key} = $result; - return $result; -} - -sub make_one_config { - my $configref = shift; - my $root = shift; - my %C = %{$configref}; - - # Aliases - $C{LANGUAGE} = "objective-c" if $C{LANGUAGE} eq "objc"; - $C{LANGUAGE} = "objective-c++" if $C{LANGUAGE} eq "objc++"; - - # Interpret OS version string from command line. - my ($sdk_arg, $deployment_arg, $run_arg, undef) = split('-', $C{OSVERSION}); - delete $C{OSVERSION}; - my ($os_arg) = ($sdk_arg =~ /^([^\.0-9]+)/); - $deployment_arg = "default" if !defined($deployment_arg); - $run_arg = "default" if !defined($run_arg); - - - die "unknown OS '$os_arg' (expected iphoneos or iphonesimulator or watchos or watchsimulator or macosx)\n" if ($os_arg ne "iphoneos" && $os_arg ne "iphonesimulator" && $os_arg ne "watchos" && $os_arg ne "watchsimulator" && $os_arg ne "macosx"); - - $C{OS} = $os_arg; - - if ($os_arg eq "iphoneos" || $os_arg eq "iphonesimulator") { - $C{TOOLCHAIN} = "ios"; - } elsif ($os_arg eq "watchos" || $os_arg eq "watchsimulator") { - $C{TOOLCHAIN} = "watchos"; - } elsif ($os_arg eq "macosx") { - $C{TOOLCHAIN} = "osx"; - } else { - print "${yellow}WARN: don't know toolchain for OS $C{OS}${nocolor}\n"; - $C{TOOLCHAIN} = "default"; - } - - # Look up SDK - # Try exact match first. - # Then try lexically-last prefix match (so "macosx" => "macosx10.7internal") - my @sdks = getsdks(); - if ($VERBOSE) { - print "note: Installed SDKs: @sdks\n"; - } - my $exactsdk = undef; - my $prefixsdk = undef; - foreach my $sdk (@sdks) { - $exactsdk = $sdk if ($sdk eq $sdk_arg); - $prefixsdk = newersdk($sdk, $prefixsdk) if ($sdk =~ /^$sdk_arg/); - } - - my $sdk; - if ($exactsdk) { - $sdk = $exactsdk; - } elsif ($prefixsdk) { - $sdk = $prefixsdk; - } else { - die "unknown SDK '$sdk_arg'\nInstalled SDKs: @sdks\n"; - } - - # Set deployment target and run target. - # fixme can't enforce version when run_arg eq "default" - # because we don't know it yet - $deployment_arg = versionsuffix($sdk) if $deployment_arg eq "default"; - if ($run_arg ne "default") { - die "Deployment target '$deployment_arg' is newer than run target '$run_arg'\n" if $deployment_arg > $run_arg; - } - $C{DEPLOYMENT_TARGET} = $deployment_arg; - $C{RUN_TARGET} = $run_arg; - - # set the config name now, after massaging the language and OS versions, - # but before adding other settings - my $configname = config_name(%C); - die if ($configname =~ /'/); - die if ($configname =~ / /); - ($C{NAME} = $configname) =~ s/~/ /g; - (my $configdir = $configname) =~ s#/##g; - $C{DIR} = "$BUILDDIR/$configdir"; - - $C{SDK_PATH} = getsdkpath($sdk); - - # Look up test library (possible in root or SDK_PATH) - - my $rootarg = $root; - my $symroot; - my @sympaths = ( (glob "$root/*~sym")[0], - (glob "$root/BuildRecords/*_install/Symbols")[0], - "$root/Symbols" ); - my @dstpaths = ( (glob "$root/*~dst")[0], - (glob "$root/BuildRecords/*_install/Root")[0], - "$root/Root" ); - for(my $i = 0; $i < scalar(@sympaths); $i++) { - if (-e $sympaths[$i] && -e $dstpaths[$i]) { - $symroot = $sympaths[$i]; - $root = $dstpaths[$i]; - last; - } - } - - if ($root ne "" && -e "$root$C{SDK_PATH}$TESTLIBPATH") { - $C{TESTLIB} = "$root$C{SDK_PATH}$TESTLIBPATH"; - } elsif (-e "$root$TESTLIBPATH") { - $C{TESTLIB} = "$root$TESTLIBPATH"; - } elsif (-e "$root/$TESTLIBNAME") { - $C{TESTLIB} = "$root/$TESTLIBNAME"; - } else { - die "No $TESTLIBNAME in root '$rootarg' for sdk '$C{SDK_PATH}'\n" - # . join("\n", @dstpaths) . "\n" - ; - } - - if (-e "$symroot/$TESTLIBNAME.dSYM") { - $C{TESTDSYM} = "$symroot/$TESTLIBNAME.dSYM"; - } - - if ($VERBOSE) { - my @uuids = `/usr/bin/dwarfdump -u '$C{TESTLIB}'`; - while (my $uuid = shift @uuids) { - print "note: $uuid"; - } - } - - # Look up compilers - my $cc = $C{CC}; - my $cxx = cplusplus($C{CC}); - my $swift = swift($C{CC}); - if (! $BUILD) { - $C{CC} = $cc; - $C{CXX} = $cxx; - $C{SWIFT} = $swift - } else { - $C{CC} = find_compiler($cc, $C{TOOLCHAIN}, $C{SDK_PATH}); - $C{CXX} = find_compiler($cxx, $C{TOOLCHAIN}, $C{SDK_PATH}); - $C{SWIFT} = find_compiler($swift, $C{TOOLCHAIN}, $C{SDK_PATH}); - - die "No compiler '$cc' ('$C{CC}') in toolchain '$C{TOOLCHAIN}'\n" if !-e $C{CC}; - die "No compiler '$cxx' ('$C{CXX}') in toolchain '$C{TOOLCHAIN}'\n" if !-e $C{CXX}; - die "No compiler '$swift' ('$C{SWIFT}') in toolchain '$C{TOOLCHAIN}'\n" if !-e $C{SWIFT}; - } - - # Populate cflags - - # save-temps so dsymutil works so debug info works - my $cflags = "-I$DIR -W -Wall -Wno-deprecated-declarations -Wshorten-64-to-32 -g -save-temps -Os -arch $C{ARCH} "; - my $objcflags = ""; - my $swiftflags = "-g "; - - $cflags .= " -isysroot '$C{SDK_PATH}'"; - $cflags .= " '-Wl,-syslibroot,$C{SDK_PATH}'"; - $swiftflags .= " -sdk '$C{SDK_PATH}'"; - - # Set deployment target cflags - my $target = undef; - die "No deployment target" if $C{DEPLOYMENT_TARGET} eq ""; - if ($C{OS} eq "iphoneos") { - $cflags .= " -mios-version-min=$C{DEPLOYMENT_TARGET}"; - $target = "$C{ARCH}-apple-ios$C{DEPLOYMENT_TARGET}"; - } - elsif ($C{OS} eq "iphonesimulator") { - $cflags .= " -mios-simulator-version-min=$C{DEPLOYMENT_TARGET}"; - $target = "$C{ARCH}-apple-ios$C{DEPLOYMENT_TARGET}"; - } - elsif ($C{OS} eq "watchos") { - $cflags .= " -mwatchos-version-min=$C{DEPLOYMENT_TARGET}"; - $target = "$C{ARCH}-apple-watchos$C{DEPLOYMENT_TARGET}"; - } - elsif ($C{OS} eq "watchsimulator") { - $cflags .= " -mwatch-simulator-version-min=$C{DEPLOYMENT_TARGET}"; - $target = "$C{ARCH}-apple-watchos$C{DEPLOYMENT_TARGET}"; - } - else { - $cflags .= " -mmacosx-version-min=$C{DEPLOYMENT_TARGET}"; - $target = "$C{ARCH}-apple-macosx$C{DEPLOYMENT_TARGET}"; - } - $swiftflags .= " -target $target"; - - # fixme still necessary? - if ($C{OS} eq "iphonesimulator" && $C{ARCH} eq "i386") { - $objcflags .= " -fobjc-abi-version=2 -fobjc-legacy-dispatch"; - } - - if ($root ne "") { - my $library_path = dirname($C{TESTLIB}); - $cflags .= " -L$library_path"; - $cflags .= " -I '$root/usr/include'"; - $cflags .= " -I '$root/usr/local/include'"; - - if ($C{SDK_PATH} ne "/") { - $cflags .= " -I '$root$C{SDK_PATH}/usr/include'"; - $cflags .= " -I '$root$C{SDK_PATH}/usr/local/include'"; - } - } - - if ($C{CC} =~ /clang/) { - $cflags .= " -Qunused-arguments -fno-caret-diagnostics"; - $cflags .= " -stdlib=$C{STDLIB}"; # fixme -fno-objc-link-runtime" - $cflags .= " -Wl,-segalign,0x4000 "; - } - - - # Populate objcflags - - $objcflags .= " -lobjc"; - if ($C{MEM} eq "gc") { - $objcflags .= " -fobjc-gc"; - } - elsif ($C{MEM} eq "arc") { - $objcflags .= " -fobjc-arc"; - } - elsif ($C{MEM} eq "mrc") { - # nothing - } - else { - die "unrecognized MEM '$C{MEM}'\n"; - } - - if (supportslibauto($C{OS})) { - # do this even for non-GC tests - $objcflags .= " -lauto"; - } - - # Populate ENV_PREFIX - $C{ENV} = "LANG=C MallocScribble=1"; - $C{ENV} .= " VERBOSE=$VERBOSE" if $VERBOSE; - if ($root ne "") { - die "no spaces allowed in root" if dirname($C{TESTLIB}) =~ /\s+/; - } - if ($C{GUARDMALLOC}) { - $ENV{GUARDMALLOC} = "1"; # checked by tests and errcheck.pl - $C{ENV} .= " DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib"; - if ($C{GUARDMALLOC} eq "before") { - $C{ENV} .= " MALLOC_PROTECT_BEFORE=1"; - } elsif ($C{GUARDMALLOC} eq "after") { - # protect after is the default - } else { - die "Unknown guard malloc mode '$C{GUARDMALLOC}'\n"; - } - } - - # Populate compiler commands - $C{COMPILE_C} = "env LANG=C '$C{CC}' $cflags -x c -std=gnu99"; - $C{COMPILE_CXX} = "env LANG=C '$C{CXX}' $cflags -x c++"; - $C{COMPILE_M} = "env LANG=C '$C{CC}' $cflags $objcflags -x objective-c -std=gnu99"; - $C{COMPILE_MM} = "env LANG=C '$C{CXX}' $cflags $objcflags -x objective-c++"; - $C{COMPILE_SWIFT} = "env LANG=C '$C{SWIFT}' $swiftflags"; - - $C{COMPILE} = $C{COMPILE_C} if $C{LANGUAGE} eq "c"; - $C{COMPILE} = $C{COMPILE_CXX} if $C{LANGUAGE} eq "c++"; - $C{COMPILE} = $C{COMPILE_M} if $C{LANGUAGE} eq "objective-c"; - $C{COMPILE} = $C{COMPILE_MM} if $C{LANGUAGE} eq "objective-c++"; - $C{COMPILE} = $C{COMPILE_SWIFT} if $C{LANGUAGE} eq "swift"; - die "unknown language '$C{LANGUAGE}'\n" if !defined $C{COMPILE}; - - ($C{COMPILE_NOMEM} = $C{COMPILE}) =~ s/ -fobjc-(?:gc|arc)\S*//g; - ($C{COMPILE_NOLINK} = $C{COMPILE}) =~ s/ '?-(?:Wl,|l)\S*//g; - ($C{COMPILE_NOLINK_NOMEM} = $C{COMPILE_NOMEM}) =~ s/ '?-(?:Wl,|l)\S*//g; - - - # Reject some self-inconsistent configurations - if ($C{MEM} !~ /^(mrc|arc|gc)$/) { - die "unknown MEM=$C{MEM} (expected one of mrc arc gc)\n"; - } - - if ($C{MEM} eq "gc" && $C{OS} !~ /^macosx/) { - print "note: skipping configuration $C{NAME}\n"; - print "note: because OS=$C{OS} does not support MEM=$C{MEM}\n"; - return 0; - } - if ($C{MEM} eq "gc" && $C{ARCH} eq "x86_64h") { - print "note: skipping configuration $C{NAME}\n"; - print "note: because ARCH=$C{ARCH} does not support MEM=$C{MEM}\n"; - return 0; - } - if ($C{MEM} eq "arc" && $C{OS} =~ /^macosx/ && $C{ARCH} eq "i386") { - print "note: skipping configuration $C{NAME}\n"; - print "note: because 32-bit Mac does not support MEM=$C{MEM}\n"; - return 0; - } - if ($C{MEM} eq "arc" && $C{CC} !~ /clang/) { - print "note: skipping configuration $C{NAME}\n"; - print "note: because CC=$C{CC} does not support MEM=$C{MEM}\n"; - return 0; - } - - if ($C{STDLIB} ne "libstdc++" && $C{CC} !~ /clang/) { - print "note: skipping configuration $C{NAME}\n"; - print "note: because CC=$C{CC} does not support STDLIB=$C{STDLIB}\n"; - return 0; - } - - # fixme - if ($C{LANGUAGE} eq "swift" && $C{ARCH} =~ /^arm/) { - print "note: skipping configuration $C{NAME}\n"; - print "note: because ARCH=$C{ARCH} does not support LANGUAGE=SWIFT\n"; - return 0; - } - - # fixme unimplemented run targets - if ($C{RUN_TARGET} ne "default" && $C{OS} !~ /simulator/) { - print "${yellow}WARN: skipping configuration $C{NAME}${nocolor}\n"; - print "${yellow}WARN: because OS=$C{OS} does not yet implement RUN_TARGET=$C{RUN_TARGET}${nocolor}\n"; - } - - %$configref = %C; -} - -sub make_configs { - my ($root, %args) = @_; - - my @results = ({}); # start with one empty config - - for my $key (keys %args) { - my @newresults; - my @values = @{$args{$key}}; - for my $configref (@results) { - my %config = %{$configref}; - for my $value (@values) { - my %newconfig = %config; - $newconfig{$key} = $value; - push @newresults, \%newconfig; - } - } - @results = @newresults; - } - - my @newresults; - for my $configref(@results) { - if (make_one_config($configref, $root)) { - push @newresults, $configref; - } - } - - return @newresults; -} - -sub config_name { - my %config = @_; - my $name = ""; - for my $key (sort keys %config) { - $name .= '~' if $name ne ""; - $name .= "$key=$config{$key}"; - } - return $name; -} - -sub run_one_config { - my %C = %{shift()}; - my @tests = @_; - - # Build and run - my $testcount = 0; - my $failcount = 0; - - my @gathertests; - foreach my $test (@tests) { - if ($VERBOSE) { - print "\nGATHER $test\n"; - } - - if ($ALL_TESTS{$test}) { - gather_simple(\%C, $test) || next; # not pass, not fail - push @gathertests, $test; - } else { - die "No test named '$test'\n"; - } - } - - my @builttests; - if (!$BUILD) { - @builttests = @gathertests; - $testcount = scalar(@gathertests); - } else { - my $configdir = $C{DIR}; - print $configdir, "\n" if $VERBOSE; - mkdir $configdir || die; - - foreach my $test (@gathertests) { - if ($VERBOSE) { - print "\nBUILD $test\n"; - } - mkdir "$configdir/$test.build" || die; - - if ($ALL_TESTS{$test}) { - $testcount++; - if (!build_simple(\%C, $test)) { - $failcount++; - } else { - push @builttests, $test; - } - } else { - die "No test named '$test'\n"; - } - } - } - - if (!$RUN || !scalar(@builttests)) { - # nothing to do - } - else { - if ($C{ARCH} =~ /^arm/ && `unamep -p` !~ /^arm/) { - # upload all tests to iOS device - make("RSYNC_PASSWORD=alpine rsync -av $C{DIR} rsync://root\@localhost:10873/root/var/root/objctest/"); - die "Couldn't rsync tests to device\n" if ($?); - - # upload library to iOS device - if ($C{TESTLIB} ne $TESTLIBPATH) { - make("RSYNC_PASSWORD=alpine rsync -av $C{TESTLIB} rsync://root\@localhost:10873/root/var/root/objctest/"); - die "Couldn't rsync $C{TESTLIB} to device\n" if ($?); - make("RSYNC_PASSWORD=alpine rsync -av $C{TESTDSYM} rsync://root\@localhost:10873/root/var/root/objctest/"); - } - } - - foreach my $test (@builttests) { - print "\nRUN $test\n" if ($VERBOSE); - - if ($ALL_TESTS{$test}) - { - if (!run_simple(\%C, $test)) { - $failcount++; - } - } else { - die "No test named '$test'\n"; - } - } - } - - return ($testcount, $failcount); -} - - - -# Return value if set by "$argname=value" on the command line -# Return $default if not set. -sub getargs { - my ($argname, $default) = @_; - - foreach my $arg (@ARGV) { - my ($value) = ($arg =~ /^$argname=(.+)$/); - return [split ',', $value] if defined $value; - } - - return [split ',', $default]; -} - -# Return 1 or 0 if set by "$argname=1" or "$argname=0" on the -# command line. Return $default if not set. -sub getbools { - my ($argname, $default) = @_; - - my @values = @{getargs($argname, $default)}; - return [( map { ($_ eq "0") ? 0 : 1 } @values )]; -} - -# Return an integer if set by "$argname=value" on the -# command line. Return $default if not set. -sub getints { - my ($argname, $default) = @_; - - my @values = @{getargs($argname, $default)}; - return [( map { int($_) } @values )]; -} - -sub getarg { - my ($argname, $default) = @_; - my @values = @{getargs($argname, $default)}; - die "Only one value allowed for $argname\n" if @values > 1; - return $values[0]; -} - -sub getbool { - my ($argname, $default) = @_; - my @values = @{getbools($argname, $default)}; - die "Only one value allowed for $argname\n" if @values > 1; - return $values[0]; -} - -sub getint { - my ($argname, $default) = @_; - my @values = @{getints($argname, $default)}; - die "Only one value allowed for $argname\n" if @values > 1; - return $values[0]; -} - - -# main -my %args; - - -my $default_arch = (`/usr/sbin/sysctl hw.optional.x86_64` eq "hw.optional.x86_64: 1\n") ? "x86_64" : "i386"; -$args{ARCH} = getargs("ARCH", 0); -$args{ARCH} = getargs("ARCHS", $default_arch) if !@{$args{ARCH}}[0]; - -$args{OSVERSION} = getargs("OS", "macosx-default-default"); - -$args{MEM} = getargs("MEM", "mrc"); -$args{LANGUAGE} = [ map { lc($_) } @{getargs("LANGUAGE", "objective-c,swift")} ]; -$args{STDLIB} = getargs("STDLIB", "libc++"); - -$args{CC} = getargs("CC", "clang"); - -{ - my $guardmalloc = getargs("GUARDMALLOC", 0); - # GUARDMALLOC=1 is the same as GUARDMALLOC=before,after - my @guardmalloc2 = (); - for my $arg (@$guardmalloc) { - if ($arg == 1) { push @guardmalloc2, "before"; - push @guardmalloc2, "after"; } - else { push @guardmalloc2, $arg } - } - $args{GUARDMALLOC} = \@guardmalloc2; -} - -$BUILD = getbool("BUILD", 1); -$RUN = getbool("RUN", 1); -$VERBOSE = getint("VERBOSE", 0); - -my $root = getarg("ROOT", ""); -$root =~ s#/*$##; - -my @tests = gettests(); - -print "note: -----\n"; -print "note: testing root '$root'\n"; - -my @configs = make_configs($root, %args); - -print "note: -----\n"; -print "note: testing ", scalar(@configs), " configurations:\n"; -for my $configref (@configs) { - my $configname = $$configref{NAME}; - print "note: configuration $configname\n"; -} - -if ($BUILD) { - `rm -rf '$BUILDDIR'`; - mkdir "$BUILDDIR" || die; -} - -my $failed = 0; - -my $testconfigs = @configs; -my $failconfigs = 0; -my $testcount = 0; -my $failcount = 0; -for my $configref (@configs) { - my $configname = $$configref{NAME}; - print "note: -----\n"; - print "note: \nnote: $configname\nnote: \n"; - - (my $t, my $f) = eval { run_one_config($configref, @tests); }; - if ($@) { - chomp $@; - print "${red}FAIL: $configname${nocolor}\n"; - print "${red}FAIL: $@${nocolor}\n"; - $failconfigs++; - } else { - my $color = ($f ? $red : ""); - print "note:\n"; - print "${color}note: $configname$nocolor\n"; - print "${color}note: $t tests, $f failures$nocolor\n"; - $testcount += $t; - $failcount += $f; - $failconfigs++ if ($f); - } -} - -print "note: -----\n"; -my $color = ($failconfigs ? $red : ""); -print "${color}note: $testconfigs configurations, $failconfigs with failures$nocolor\n"; -print "${color}note: $testcount tests, $failcount failures$nocolor\n"; - -$failed = ($failconfigs ? 1 : 0); - -exit ($failed ? 1 : 0); diff --git a/objc/objc-runtime/test/testroot.i b/objc/objc-runtime/test/testroot.i deleted file mode 100644 index 118c438..0000000 --- a/objc/objc-runtime/test/testroot.i +++ /dev/null @@ -1,229 +0,0 @@ -// testroot.i -// Implementation of class TestRoot -// Include this file into your main test file to use it. - -#include "test.h" -#include <dlfcn.h> -#include <objc/objc-internal.h> - -int TestRootLoad = 0; -int TestRootInitialize = 0; -int TestRootAlloc = 0; -int TestRootAllocWithZone = 0; -int TestRootCopy = 0; -int TestRootCopyWithZone = 0; -int TestRootMutableCopy = 0; -int TestRootMutableCopyWithZone = 0; -int TestRootInit = 0; -int TestRootDealloc = 0; -int TestRootFinalize = 0; -int TestRootRetain = 0; -int TestRootRelease = 0; -int TestRootAutorelease = 0; -int TestRootRetainCount = 0; -int TestRootTryRetain = 0; -int TestRootIsDeallocating = 0; -int TestRootPlusRetain = 0; -int TestRootPlusRelease = 0; -int TestRootPlusAutorelease = 0; -int TestRootPlusRetainCount = 0; - - -@implementation TestRoot - -// These all use void* pending rdar://9310005. - -static void * -retain_fn(void *self, SEL _cmd __unused) { - OSAtomicIncrement32(&TestRootRetain); - void * (*fn)(void *) = (typeof(fn))_objc_rootRetain; - return fn(self); -} - -static void -release_fn(void *self, SEL _cmd __unused) { - OSAtomicIncrement32(&TestRootRelease); - void (*fn)(void *) = (typeof(fn))_objc_rootRelease; - fn(self); -} - -static void * -autorelease_fn(void *self, SEL _cmd __unused) { - OSAtomicIncrement32(&TestRootAutorelease); - void * (*fn)(void *) = (typeof(fn))_objc_rootAutorelease; - return fn(self); -} - -static unsigned long -retaincount_fn(void *self, SEL _cmd __unused) { - OSAtomicIncrement32(&TestRootRetainCount); - unsigned long (*fn)(void *) = (typeof(fn))_objc_rootRetainCount; - return fn(self); -} - -static void * -copywithzone_fn(void *self, SEL _cmd __unused, void *zone) { - OSAtomicIncrement32(&TestRootCopyWithZone); - void * (*fn)(void *, void *) = (typeof(fn))dlsym(RTLD_DEFAULT, "object_copy"); - return fn(self, zone); -} - -static void * -plusretain_fn(void *self __unused, SEL _cmd __unused) { - OSAtomicIncrement32(&TestRootPlusRetain); - return self; -} - -static void -plusrelease_fn(void *self __unused, SEL _cmd __unused) { - OSAtomicIncrement32(&TestRootPlusRelease); -} - -static void * -plusautorelease_fn(void *self, SEL _cmd __unused) { - OSAtomicIncrement32(&TestRootPlusAutorelease); - return self; -} - -static unsigned long -plusretaincount_fn(void *self __unused, SEL _cmd __unused) { - OSAtomicIncrement32(&TestRootPlusRetainCount); - return ULONG_MAX; -} - -+(void) load { - OSAtomicIncrement32(&TestRootLoad); - - // install methods that ARR refuses to compile - class_addMethod(self, sel_registerName("retain"), (IMP)retain_fn, ""); - class_addMethod(self, sel_registerName("release"), (IMP)release_fn, ""); - class_addMethod(self, sel_registerName("autorelease"), (IMP)autorelease_fn, ""); - class_addMethod(self, sel_registerName("retainCount"), (IMP)retaincount_fn, ""); - class_addMethod(self, sel_registerName("copyWithZone:"), (IMP)copywithzone_fn, ""); - - class_addMethod(object_getClass(self), sel_registerName("retain"), (IMP)plusretain_fn, ""); - class_addMethod(object_getClass(self), sel_registerName("release"), (IMP)plusrelease_fn, ""); - class_addMethod(object_getClass(self), sel_registerName("autorelease"), (IMP)plusautorelease_fn, ""); - class_addMethod(object_getClass(self), sel_registerName("retainCount"), (IMP)plusretaincount_fn, ""); -} - - -+(void) initialize { - OSAtomicIncrement32(&TestRootInitialize); -} - --(id) self { - return self; -} - -+(Class) class { - return self; -} - --(Class) class { - return object_getClass(self); -} - -+(Class) superclass { - return class_getSuperclass(self); -} - --(Class) superclass { - return class_getSuperclass([self class]); -} - -+(id) new { - return [[self alloc] init]; -} - -+(id) alloc { - OSAtomicIncrement32(&TestRootAlloc); - void * (*fn)(id __unsafe_unretained) = (typeof(fn))_objc_rootAlloc; - return objc_retainedObject(fn(self)); -} - -+(id) allocWithZone:(void *)zone { - OSAtomicIncrement32(&TestRootAllocWithZone); - void * (*fn)(id __unsafe_unretained, void *) = (typeof(fn))_objc_rootAllocWithZone; - return objc_retainedObject(fn(self, zone)); -} - -+(id) copy { - return self; -} - -+(id) copyWithZone:(void *) __unused zone { - return self; -} - --(id) copy { - OSAtomicIncrement32(&TestRootCopy); - return [self copyWithZone:NULL]; -} - -+(id) mutableCopyWithZone:(void *) __unused zone { - fail("+mutableCopyWithZone: called"); -} - --(id) mutableCopy { - OSAtomicIncrement32(&TestRootMutableCopy); - return [self mutableCopyWithZone:NULL]; -} - --(id) mutableCopyWithZone:(void *) __unused zone { - OSAtomicIncrement32(&TestRootMutableCopyWithZone); - void * (*fn)(id __unsafe_unretained) = (typeof(fn))_objc_rootAlloc; - return objc_retainedObject(fn(object_getClass(self))); -} - --(id) init { - OSAtomicIncrement32(&TestRootInit); - return _objc_rootInit(self); -} - -+(void) dealloc { - fail("+dealloc called"); -} - --(void) dealloc { - OSAtomicIncrement32(&TestRootDealloc); - _objc_rootDealloc(self); -} - -+(void) finalize { - fail("+finalize called"); -} - --(void) finalize { - OSAtomicIncrement32(&TestRootFinalize); - _objc_rootFinalize(self); -} - -+(BOOL) _tryRetain { - return YES; -} - --(BOOL) _tryRetain { - OSAtomicIncrement32(&TestRootTryRetain); - return _objc_rootTryRetain(self); -} - -+(BOOL) _isDeallocating { - return NO; -} - --(BOOL) _isDeallocating { - OSAtomicIncrement32(&TestRootIsDeallocating); - return _objc_rootIsDeallocating(self); -} - --(BOOL) allowsWeakReference { - return ! [self _isDeallocating]; -} - --(BOOL) retainWeakReference { - return [self _tryRetain]; -} - - -@end diff --git a/objc/objc-runtime/test/unload.h b/objc/objc-runtime/test/unload.h deleted file mode 100644 index 5287fe9..0000000 --- a/objc/objc-runtime/test/unload.h +++ /dev/null @@ -1,6 +0,0 @@ -#include "test.h" - -@interface SmallClass : TestRoot @end - -@interface BigClass : TestRoot @end - diff --git a/objc/objc-runtime/test/unload.m b/objc/objc-runtime/test/unload.m deleted file mode 100644 index 5b9c76b..0000000 --- a/objc/objc-runtime/test/unload.m +++ /dev/null @@ -1,174 +0,0 @@ -// xpc leaks memory in dlopen(). Disable it. -// TEST_ENV XPC_SERVICES_UNAVAILABLE=1 -/* -TEST_BUILD - $C{COMPILE} $DIR/unload4.m -o unload4.dylib -dynamiclib - $C{COMPILE_C} $DIR/unload3.c -o unload3.dylib -dynamiclib - $C{COMPILE} $DIR/unload2.m -o unload2.bundle -bundle - $C{COMPILE} $DIR/unload.m -o unload.out -END - */ - -#include "test.h" -#include <objc/runtime.h> -#include <dlfcn.h> -#include <unistd.h> - -#include "unload.h" - -#if __has_feature(objc_arc) - -int main() -{ - testwarn("rdar://11368528 confused by Foundation"); - succeed(__FILE__); -} - -#else - -static id forward_handler(void) -{ - return 0; -} - -static BOOL hasName(const char * const *names, const char *query) -{ - const char *name; - while ((name = *names++)) { - if (strstr(name, query)) return YES; - } - - return NO; -} - -void cycle(void) -{ - int i; - char buf[100]; - unsigned int imageCount, imageCount0; - const char **names; - const char *name; - - names = objc_copyImageNames(&imageCount0); - testassert(names); - free(names); - - void *bundle = dlopen("unload2.bundle", RTLD_LAZY); - testassert(bundle); - - names = objc_copyImageNames(&imageCount); - testassert(names); - testassert(imageCount == imageCount0 + 1); - testassert(hasName(names, "unload2.bundle")); - free(names); - - Class small = objc_getClass("SmallClass"); - Class big = objc_getClass("BigClass"); - testassert(small); - testassert(big); - - name = class_getImageName(small); - testassert(name); - testassert(strstr(name, "unload2.bundle")); - name = class_getImageName(big); - testassert(name); - testassert(strstr(name, "unload2.bundle")); - - id o1 = [small new]; - id o2 = [big new]; - testassert(o1); - testassert(o2); - - // give BigClass and BigClass->isa large method caches (4692641) - // Flush caches part way through to test large empty caches. - for (i = 0; i < 3000; i++) { - sprintf(buf, "method_%d", i); - SEL sel = sel_registerName(buf); - ((void(*)(id, SEL))objc_msgSend)(o2, sel); - ((void(*)(id, SEL))objc_msgSend)(object_getClass(o2), sel); - } - _objc_flush_caches(object_getClass(o2)); - for (i = 0; i < 17000; i++) { - sprintf(buf, "method_%d", i); - SEL sel = sel_registerName(buf); - ((void(*)(id, SEL))objc_msgSend)(o2, sel); - ((void(*)(id, SEL))objc_msgSend)(object_getClass(o2), sel); - } - - RELEASE_VAR(o1); - RELEASE_VAR(o2); - - testcollect(); - - int err = dlclose(bundle); - testassert(err == 0); - err = dlclose(bundle); - testassert(err == -1); // already closed - - testassert(objc_getClass("SmallClass") == NULL); - testassert(objc_getClass("BigClass") == NULL); - - names = objc_copyImageNames(&imageCount); - testassert(names); - testassert(imageCount == imageCount0); - testassert(! hasName(names, "unload2.bundle")); - free(names); - - // these selectors came from the bundle - testassert(0 == strcmp("unload2_instance_method", sel_getName(sel_registerName("unload2_instance_method")))); - testassert(0 == strcmp("unload2_category_method", sel_getName(sel_registerName("unload2_category_method")))); - - // This protocol came from the bundle. - // It isn't unloaded cleanly (rdar://20664713), but neither - // may it cause the protocol table to crash after unloading. - testassert(objc_getProtocol("SmallProtocol")); -} - - -int main() -{ - // fixme object_dispose() not aggressive enough? - if (objc_collectingEnabled()) succeed(__FILE__); - - objc_setForwardHandler((void*)&forward_handler, (void*)&forward_handler); - -#if defined(__arm__) || defined(__arm64__) - int count = 10; -#else - int count = is_guardmalloc() ? 10 : 100; -#endif - - cycle(); -#if __LP64__ - // fixme heap use goes up 512 bytes after the 2nd cycle only - bad or not? - cycle(); -#endif - - leak_mark(); - while (count--) { - cycle(); - } - leak_check(0); - - // 5359412 Make sure dylibs with nothing other than image_info can close - void *dylib = dlopen("unload3.dylib", RTLD_LAZY); - testassert(dylib); - int err = dlclose(dylib); - testassert(err == 0); - err = dlclose(dylib); - testassert(err == -1); // already closed - - // Make sure dylibs with real objc content cannot close - dylib = dlopen("unload4.dylib", RTLD_LAZY); - testassert(dylib); - err = dlclose(dylib); - testassert(err == 0); - err = dlclose(dylib); - testassert(err == 0); // dlopen from libobjc itself - err = dlclose(dylib); - testassert(err == -1); // already closed - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/unload2.m b/objc/objc-runtime/test/unload2.m deleted file mode 100644 index 16ac0ca..0000000 --- a/objc/objc-runtime/test/unload2.m +++ /dev/null @@ -1,26 +0,0 @@ -#include "unload.h" -#include "testroot.i" -#import <objc/objc-api.h> - -@implementation SmallClass : TestRoot --(void)unload2_instance_method { } -@end - - -@implementation BigClass : TestRoot -@end - -OBJC_ROOT_CLASS -@interface UnusedClass { id isa; } @end -@implementation UnusedClass @end - - -@protocol SmallProtocol --(void)unload2_category_method; -@end - -@interface SmallClass (Category) <SmallProtocol> @end - -@implementation SmallClass (Category) --(void)unload2_category_method { } -@end diff --git a/objc/objc-runtime/test/unload3.c b/objc/objc-runtime/test/unload3.c deleted file mode 100644 index 8cdb51f..0000000 --- a/objc/objc-runtime/test/unload3.c +++ /dev/null @@ -1,17 +0,0 @@ -// unload3: contains imageinfo but no other objc metadata -// libobjc must not keep it open -// DO NOT USE __OBJC2__; this is a C file. - -#include <TargetConditionals.h> - -#if TARGET_OS_WIN32 || (TARGET_OS_MAC && TARGET_CPU_X86 && !TARGET_IPHONE_SIMULATOR) -// old ABI -int fake[2] __attribute__((section("__OBJC,__image_info"))) -#else -// new ABI -int fake[2] __attribute__((section("__DATA,__objc_imageinfo"))) -#endif - = { 0, TARGET_IPHONE_SIMULATOR ? (1<<5) : 0 }; - -// silence "no debug symbols in executable" warning -void fn(void) { } diff --git a/objc/objc-runtime/test/unload4.m b/objc/objc-runtime/test/unload4.m deleted file mode 100644 index 94dd034..0000000 --- a/objc/objc-runtime/test/unload4.m +++ /dev/null @@ -1,11 +0,0 @@ -// unload4: contains some objc metadata other than imageinfo -// libobjc must keep it open - -#if __OBJC2__ -int fake2 __attribute__((section("__DATA,__objc_foo"))) = 0; -#else -int fake2 __attribute__((section("__OBJC,__foo"))) = 0; -#endif - -// getsectiondata() falls over if __TEXT has no contents -const char *unload4 = "unload4"; diff --git a/objc/objc-runtime/test/unwind.m b/objc/objc-runtime/test/unwind.m deleted file mode 100644 index 7fa1159..0000000 --- a/objc/objc-runtime/test/unwind.m +++ /dev/null @@ -1,93 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include <objc/objc-exception.h> -#include <Foundation/NSObject.h> - -#if !defined(__OBJC2__) - -int main() -{ - succeed(__FILE__); -} - -#else - -static int state; - -@interface Foo : NSObject @end -@interface Bar : NSObject @end - -@interface Foo (Unimplemented) -+(void)method; -@end - -@implementation Bar @end - -@implementation Foo - --(void)check { state++; } -+(void)check { testassert(!"caught class object, not instance"); } - -static id exc; - -static void handler(id unused, void *ctx) __attribute__((used)); -static void handler(id unused __unused, void *ctx __unused) -{ - testassert(state == 3); state++; -} - -+(BOOL) resolveClassMethod:(SEL)__unused name -{ - testassert(state == 1); state++; -#if !TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR - objc_addExceptionHandler(&handler, 0); - testassert(state == 2); -#else - state++; // handler would have done this -#endif - state++; - exc = [Foo new]; - @throw exc; -} - - -@end - -int main() -{ - int i; - - // unwind exception and alt handler through objc_msgSend() - - PUSH_POOL { - - state = 0; - for (i = 0; i < 100000; i++) { - @try { - testassert(state == 0); state++; - [Foo method]; - testassert(0); - } @catch (Bar *e) { - testassert(0); - } @catch (Foo *e) { - testassert(e == exc); - testassert(state == 4); state++; - testassert(state == 5); [e check]; // state++ - RELEASE_VAR(exc); - } @catch (id e) { - testassert(0); - } @catch (...) { - testassert(0); - } @finally { - testassert(state == 6); state++; - } - testassert(state == 7); state = 0; - } - - } POP_POOL; - - succeed(__FILE__); -} - -#endif diff --git a/objc/objc-runtime/test/verify-exports.pl b/objc/objc-runtime/test/verify-exports.pl deleted file mode 100755 index dc544ff..0000000 --- a/objc/objc-runtime/test/verify-exports.pl +++ /dev/null @@ -1,254 +0,0 @@ -#!/usr/bin/perl - -# verify-exports.pl -# Check exports in a library vs. declarations in header files. -# usage: verify-exports.pl /path/to/dylib /glob/path/to/headers decl-prefix [-arch <arch>] [/path/to/project~dst] -# example: verify-exports.pl /usr/lib/libobjc.A.dylib '/usr/{local/,}include/objc/*' OBJC_EXPORT -arch x86_64 /tmp/objc-test.roots/objc-test~dst - -# requirements: -# - every export must have an @interface or specially-marked declaration -# - every @interface or specially-marked declaration must have an availability macro -# - no C++ exports allowed - -use strict; -use File::Basename; -use File::Glob ':glob'; - -my $bad = 0; - -$0 = basename($0, ".pl"); -my $usage = "/path/to/dylib /glob/path/to/headers decl-prefix [-arch <arch>] [-sdk sdkname] [/path/to/project~dst]"; - -my $lib_arg = shift || die "$usage"; -die "$usage" unless ($lib_arg =~ /^\//); -my $headers_arg = shift || die "$usage"; -my $export_arg = shift || die "$usage"; - -my $arch = "x86_64"; -if ($ARGV[0] eq "-arch") { - shift; - $arch = shift || die "$0: -arch requires an architecture"; -} -my $sdk = "system"; -if ($ARGV[0] eq "-sdk") { - shift; - $sdk = shift || die "$0: -sdk requires an SDK name"; -} - -my $root = shift || ""; - - -# Collect symbols from dylib. -my $lib_path = "$root$lib_arg"; -die "$0: file not found: $lib_path\n" unless -e $lib_path; - -my %symbols; -my @symbollines = `nm -arch $arch '$lib_path'`; -die "$0: nm failed: (arch $arch) $lib_path\n" if ($?); -for my $line (@symbollines) { - chomp $line; - (my $type, my $name) = ($line =~ /^[[:xdigit:]]*\s+(.) (.*)$/); - if ($type =~ /^[A-TV-Z]$/) { - $symbols{$name} = 1; - } else { - # undefined (U) or non-external - ignore - } -} - -# Complain about C++ exports -for my $symbol (keys %symbols) { - if ($symbol =~ /^__Z/) { - print "BAD: C++ export '$symbol'\n"; $bad++; - } -} - - -# Translate arch to unifdef(1) parameters: archnames, __LP64__, __OBJC2__ -my @archnames = ("x86_64", "i386", "arm", "armv6", "armv7"); -my %archOBJC1 = (i386 => 1); -my %archLP64 = (x86_64 => 1); -my @archparams; - -my $OBJC1 = ($archOBJC1{$arch} && $sdk !~ /^iphonesimulator/); - -if ($OBJC1) { - push @archparams, "-U__OBJC2__"; -} else { - push @archparams, "-D__OBJC2__=1"; -} - -if ($archLP64{$arch}) { push @archparams, "-D__LP64__=1"; } -else { push @archparams, "-U__LP64__"; } - -for my $archname (@archnames) { - if ($archname eq $arch) { - push @archparams, "-D__${archname}__=1"; - push @archparams, "-D__$archname=1"; - } else { - push @archparams, "-U__${archname}__"; - push @archparams, "-U__$archname"; - } -} - -# TargetConditionals.h -# fixme iphone and simulator -push @archparams, "-DTARGET_OS_WIN32=0"; -push @archparams, "-DTARGET_OS_EMBEDDED=0"; -push @archparams, "-DTARGET_OS_IPHONE=0"; -push @archparams, "-DTARGET_OS_MAC=1"; - -# Gather declarations from header files -# A C declaration starts with $export_arg and ends with ';' -# A class declaration is @interface plus the line before it. -my $unifdef_cmd = "/usr/bin/unifdef " . join(" ", @archparams); -my @cdecls; -my @classdecls; -for my $header_path(bsd_glob("$root$headers_arg",GLOB_BRACE)) { - my $header; - # feed through unifdef(1) first to strip decls from other archs - # fixme strip other SDKs as well - open($header, "$unifdef_cmd < '$header_path' |"); - my $header_contents = join("", <$header>); - - # C decls - push @cdecls, ($header_contents =~ /^\s*$export_arg\s+([^;]*)/msg); - - # ObjC classes, but not categories. - # fixme ivars - push @classdecls, ($header_contents =~ /^([^\n]*\n\s*\@interface\s+[^(\n]+\n)/mg); -} - -# Find name and availability of C declarations -my %declarations; -for my $cdecl (@cdecls) { - $cdecl =~ s/\n/ /mg; # strip newlines - - # Pull availability macro off the end: - # __OSX_AVAILABLE_*(*) - # AVAILABLE_MAC_OS_X_VERSION_* - # OBJC2_UNAVAILABLE - # OBJC_HASH_AVAILABILITY - # OBJC_MAP_AVAILABILITY - # UNAVAILABLE_ATTRIBUTE - # (DEPRECATED_ATTRIBUTE is not good enough. Be specific.) - my $avail = undef; - my $cdecl2; - ($cdecl2, $avail) = ($cdecl =~ /^(.*)\s+(__OSX_AVAILABLE_\w+\([a-zA-Z0-9_, ]+\))\s*$/) if (!defined $avail); - ($cdecl2, $avail) = ($cdecl =~ /^(.*)\s+(AVAILABLE_MAC_OS_X_VERSION_\w+)\s*$/) if (!defined $avail); - ($cdecl2, $avail) = ($cdecl =~ /^(.*)\s+(OBJC2_UNAVAILABLE)\s*$/) if (!defined $avail); - ($cdecl2, $avail) = ($cdecl =~ /^(.*)\s+(OBJC_GC_UNAVAILABLE)\s*$/) if (!defined $avail); - ($cdecl2, $avail) = ($cdecl =~ /^(.*)\s+(OBJC_ARC_UNAVAILABLE)\s*$/) if (!defined $avail); - ($cdecl2, $avail) = ($cdecl =~ /^(.*)\s+(OBJC_HASH_AVAILABILITY)\s*$/) if (!defined $avail); - ($cdecl2, $avail) = ($cdecl =~ /^(.*)\s+(OBJC_MAP_AVAILABILITY)\s*$/) if (!defined $avail); - ($cdecl2, $avail) = ($cdecl =~ /^(.*)\s+(UNAVAILABLE_ATTRIBUTE)\s*$/) if (!defined $avail); - # ($cdecl2, $avail) = ($cdecl =~ /^(.*)\s+(DEPRECATED_\w+)\s*$/) if (!defined $avail); - $cdecl2 = $cdecl if (!defined $cdecl2); - - # Extract declaration name (assumes availability macro is already gone): - # `(*xxx)` (function pointer) - # `xxx(` (function) - # `xxx`$` or `xxx[nnn]$` (variable or array variable) - my $name = undef; - ($name) = ($cdecl2 =~ /^[^(]*\(\s*\*\s*(\w+)\s*\)/) if (!defined $name); - ($name) = ($cdecl2 =~ /(\w+)\s*\(/) if (!defined $name); - ($name) = ($cdecl2 =~ /(\w+)\s*(?:\[\d*\]\s*)*$/) if (!defined $name); - - if (!defined $name) { - print "BAD: unintellible declaration:\n $cdecl\n"; $bad++; - } elsif (!defined $avail) { - print "BAD: no availability on declaration of '$name':\n $cdecl\n"; $bad++; - } - - if ($avail eq "UNAVAILABLE_ATTRIBUTE") - { - $declarations{$name} = "unavailable"; - } elsif ($avail eq "OBJC2_UNAVAILABLE" && ! $OBJC1) { - # fixme OBJC2_UNAVAILABLE may or may not have an exported symbol - # $declarations{$name} = "unavailable"; - } else { - $declarations{"_$name"} = "available"; - } -} - -# Find name and availability of Objective-C classes -for my $classdecl (@classdecls) { - $classdecl =~ s/\n/ /mg; # strip newlines - - # Pull availability macro off the front: - # __OSX_AVAILABLE_*(*) - # AVAILABLE_MAC_OS_X_VERSION_* - # OBJC2_UNAVAILABLE - # OBJC_HASH_AVAILABILITY - # OBJC_MAP_AVAILABILITY - # UNAVAILABLE_ATTRIBUTE - # (DEPRECATED_ATTRIBUTE is not good enough. Be specific.) - my $avail = undef; - my $classdecl2; - ($avail, $classdecl2) = ($classdecl =~ /^\s*(__OSX_AVAILABLE_\w+\([a-zA-Z0-9_, ]+\))\s*(.*)$/) if (!defined $avail); - ($avail, $classdecl2) = ($classdecl =~ /^\s*(AVAILABLE_MAC_OS_X_VERSION_\w+)\s*(.*)$/) if (!defined $avail); - ($avail, $classdecl2) = ($classdecl =~ /^\s*(OBJC2_UNAVAILABLE)\s*(.*)$/) if (!defined $avail); - ($avail, $classdecl2) = ($classdecl =~ /^\s*(OBJC_HASH_AVAILABILITY)\s*(.*)$/) if (!defined $avail); - ($avail, $classdecl2) = ($classdecl =~ /^\s*(OBJC_MAP_AVAILABILITY)\s*(.*)$/) if (!defined $avail); - ($avail, $classdecl2) = ($classdecl =~ /^\s*(UNAVAILABLE_ATTRIBUTE)\s*(.*)$/) if (!defined $avail); - # ($avail, $classdecl2) = ($classdecl =~ /^\s*(DEPRECATED_\w+)\s*(.*)$/) if (!defined $avail); - $classdecl2 = $classdecl if (!defined $classdecl2); - - # Extract class name. - my $name = undef; - ($name) = ($classdecl2 =~ /\@interface\s+(\w+)/); - - if (!defined $name) { - print "BAD: unintellible declaration:\n $classdecl\n"; $bad++; - } elsif (!defined $avail) { - print "BAD: no availability on declaration of '$name':\n $classdecl\n"; $bad++; - } - - my $availability; - if ($avail eq "UNAVAILABLE_ATTRIBUTE") { - $availability = "unavailable"; - } elsif ($avail eq "OBJC2_UNAVAILABLE" && ! $OBJC1) { - # fixme OBJC2_UNAVAILABLE may or may not have an exported symbol - # $declarations{$name} = "unavailable"; - $availability = undef; - } else { - $availability = "available"; - } - - if (! $OBJC1) { - $declarations{"_OBJC_CLASS_\$_$name"} = $availability; - $declarations{"_OBJC_METACLASS_\$_$name"} = $availability; - # fixme ivars - $declarations{"_OBJC_IVAR_\$_$name.isa"} = $availability if ($name eq "Object"); - } else { - $declarations{".objc_class_name_$name"} = $availability; - } -} - -# All exported symbols must have an export declaration -my @missing_symbols; -for my $name (keys %symbols) { - my $avail = $declarations{$name}; - if ($avail eq "unavailable" || !defined $avail) { - push @missing_symbols, $name; - } -} -for my $symbol (sort @missing_symbols) { - print "BAD: symbol $symbol has no export declaration\n"; $bad++; -} - - -# All export declarations must have an exported symbol -my @missing_decls; -for my $name (keys %declarations) { - my $avail = $declarations{$name}; - my $hasSymbol = exists $symbols{$name}; - if ($avail ne "unavailable" && !$hasSymbol) { - push @missing_decls, $name; - } -} -for my $decl (sort @missing_decls) { - print "BAD: declaration $decl has no exported symbol\n"; $bad++; -} - -print "OK: verify-exports\n" unless $bad; -exit ($bad ? 1 : 0); diff --git a/objc/objc-runtime/test/weak.h b/objc/objc-runtime/test/weak.h deleted file mode 100644 index 6bae410..0000000 --- a/objc/objc-runtime/test/weak.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - To test -weak-l or -weak-framework: - * -DWEAK_IMPORT= - * -DWEAK_FRAMEWORK=1 - * -UEMPTY when building the weak-not-missing library - * -DEMPTY= when building the weak-missing library - - To test attribute((weak_import)): - * -DWEAK_IMPORT=__attribute__((weak_import)) - * -UWEAK_FRAMEWORK - * -UEMPTY when building the weak-not-missing library - * -DEMPTY= when building the weak-missing library - -*/ - -#include "test.h" -#include <objc/runtime.h> - -extern int state; - -WEAK_IMPORT OBJC_ROOT_CLASS -@interface MissingRoot { - id isa; -} -+(void) initialize; -+(Class) class; -+(id) alloc; --(id) init; --(void) dealloc; -+(int) method; -@end - -@interface MissingRoot (RR) --(id) retain; --(void) release; -@end - -WEAK_IMPORT -@interface MissingSuper : MissingRoot { - @public - int ivar; -} -@end - -OBJC_ROOT_CLASS -@interface NotMissingRoot { - id isa; -} -+(void) initialize; -+(Class) class; -+(id) alloc; --(id) init; --(void) dealloc; -+(int) method; -@end - -@interface NotMissingRoot (RR) --(id) retain; --(void) release; -@end - -@interface NotMissingSuper : NotMissingRoot { - @public - int unused[100]; - int ivar; -} -@end diff --git a/objc/objc-runtime/test/weak.m b/objc/objc-runtime/test/weak.m deleted file mode 100644 index 3d1fa10..0000000 --- a/objc/objc-runtime/test/weak.m +++ /dev/null @@ -1,316 +0,0 @@ -// See instructions in weak.h - -#include "test.h" -#include "weak.h" - -// Subclass of superclass that isn't there -@interface MyMissingSuper : MissingSuper -+(int) method; -@end -@implementation MyMissingSuper -+(int) method { return 1+[super method]; } -+(void) load { state++; } -@end - -// Subclass of subclass of superclass that isn't there -@interface MyMissingSub : MyMissingSuper -+(int) method; -@end -@implementation MyMissingSub -+(int) method { return 1+[super method]; } -+(void) load { state++; } -@end - -// Subclass of real superclass -@interface MyNotMissingSuper : NotMissingSuper -+(int) method; -@end -@implementation MyNotMissingSuper -+(int) method { return 1+[super method]; } -+(void) load { state++; } -@end - -// Subclass of subclass of superclass that isn't there -@interface MyNotMissingSub : MyNotMissingSuper -+(int) method; -@end -@implementation MyNotMissingSub -+(int) method { return 1+[super method]; } -+(void) load { state++; } -@end - -// Categories on all of the above -@interface MissingRoot (MissingRootExtras) -+(void)load; -+(int) cat_method; -@end -@implementation MissingRoot (MissingRootExtras) -+(void)load { state++; } -+(int) cat_method { return 40; } -@end - -@interface MissingSuper (MissingSuperExtras) -+(void)load; -+(int) cat_method; -@end -@implementation MissingSuper (MissingSuperExtras) -+(void)load { state++; } -+(int) cat_method { return 1+[super cat_method]; } -@end - -@interface MyMissingSuper (MyMissingSuperExtras) -+(void)load; -+(int) cat_method; -@end -@implementation MyMissingSuper (MyMissingSuperExtras) -+(void)load { state++; } -+(int) cat_method { return 1+[super cat_method]; } -@end - -@interface MyMissingSub (MyMissingSubExtras) -+(void)load; -+(int) cat_method; -@end -@implementation MyMissingSub (MyMissingSubExtras) -+(void)load { state++; } -+(int) cat_method { return 1+[super cat_method]; } -@end - - -@interface NotMissingRoot (NotMissingRootExtras) -+(void)load; -+(int) cat_method; -@end -@implementation NotMissingRoot (NotMissingRootExtras) -+(void)load { state++; } -+(int) cat_method { return 30; } -@end - -@interface NotMissingSuper (NotMissingSuperExtras) -+(void)load; -+(int) cat_method; -@end -@implementation NotMissingSuper (NotMissingSuperExtras) -+(void)load { state++; } -+(int) cat_method { return 1+[super cat_method]; } -@end - -@interface MyNotMissingSuper (MyNotMissingSuperExtras) -+(void)load; -+(int) cat_method; -@end -@implementation MyNotMissingSuper (MyNotMissingSuperExtras) -+(void)load { state++; } -+(int) cat_method { return 1+[super cat_method]; } -@end - -@interface MyNotMissingSub (MyNotMissingSubExtras) -+(void)load; -+(int) cat_method; -@end -@implementation MyNotMissingSub (MyNotMissingSubExtras) -+(void)load { state++; } -+(int) cat_method { return 1+[super cat_method]; } -@end - - -#if WEAK_FRAMEWORK -# define TESTIVAR(cond) testassert(cond) -#else -# define TESTIVAR(cond) /* rdar */ -#endif - -static BOOL classInList(__unsafe_unretained Class classes[], const char *name) -{ - for (int i = 0; classes[i] != nil; i++) { - if (0 == strcmp(class_getName(classes[i]), name)) return YES; - } - return NO; -} - -static BOOL classInNameList(const char **names, const char *name) -{ - const char **cp; - for (cp = names; *cp; cp++) { - if (0 == strcmp(*cp, name)) return YES; - } - return NO; -} - -int main(int argc __unused, char **argv) -{ - BOOL weakMissing; - if (strstr(argv[0], "-not-missing.out")) { - weakMissing = NO; - } else if (strstr(argv[0], "-missing.out")) { - weakMissing = YES; - } else { - fail("executable name must be weak*-missing.out or weak*-not-missing.out"); - } - - // class and category +load methods - if (weakMissing) testassert(state == 8); - else testassert(state == 16); - state = 0; - - // classes - testassert([NotMissingRoot class]); - testassert([NotMissingSuper class]); - testassert([MyNotMissingSuper class]); - testassert([MyNotMissingSub class]); - if (weakMissing) { - testassert([MissingRoot class] == nil); - testassert([MissingSuper class] == nil); - testassert([MyMissingSuper class] == nil); - testassert([MyMissingSub class] == nil); - } else { - testassert([MissingRoot class]); - testassert([MissingSuper class]); - testassert([MyMissingSuper class]); - testassert([MyMissingSub class]); - } - - // objc_getClass - testassert(objc_getClass("NotMissingRoot")); - testassert(objc_getClass("NotMissingSuper")); - testassert(objc_getClass("MyNotMissingSuper")); - testassert(objc_getClass("MyNotMissingSub")); - if (weakMissing) { - testassert(objc_getClass("MissingRoot") == nil); - testassert(objc_getClass("MissingSuper") == nil); - testassert(objc_getClass("MyMissingSuper") == nil); - testassert(objc_getClass("MyMissingSub") == nil); - } else { - testassert(objc_getClass("MissingRoot")); - testassert(objc_getClass("MissingSuper")); - testassert(objc_getClass("MyMissingSuper")); - testassert(objc_getClass("MyMissingSub")); - } - - // class list - union { - Class *c; - void *v; - } classes; - classes.c = objc_copyClassList(NULL); - testassert(classInList(classes.c, "NotMissingRoot")); - testassert(classInList(classes.c, "NotMissingSuper")); - testassert(classInList(classes.c, "MyNotMissingSuper")); - testassert(classInList(classes.c, "MyNotMissingSub")); - if (weakMissing) { - testassert(! classInList(classes.c, "MissingRoot")); - testassert(! classInList(classes.c, "MissingSuper")); - testassert(! classInList(classes.c, "MyMissingSuper")); - testassert(! classInList(classes.c, "MyMissingSub")); - } else { - testassert(classInList(classes.c, "MissingRoot")); - testassert(classInList(classes.c, "MissingSuper")); - testassert(classInList(classes.c, "MyMissingSuper")); - testassert(classInList(classes.c, "MyMissingSub")); - } - free(classes.v); - - // class name list - const char *image = class_getImageName(objc_getClass("NotMissingRoot")); - testassert(image); - const char **names = objc_copyClassNamesForImage(image, NULL); - testassert(names); - testassert(classInNameList(names, "NotMissingRoot")); - testassert(classInNameList(names, "NotMissingSuper")); - if (weakMissing) { - testassert(! classInNameList(names, "MissingRoot")); - testassert(! classInNameList(names, "MissingSuper")); - } else { - testassert(classInNameList(names, "MissingRoot")); - testassert(classInNameList(names, "MissingSuper")); - } - free(names); - - image = class_getImageName(objc_getClass("MyNotMissingSub")); - testassert(image); - names = objc_copyClassNamesForImage(image, NULL); - testassert(names); - testassert(classInNameList(names, "MyNotMissingSuper")); - testassert(classInNameList(names, "MyNotMissingSub")); - if (weakMissing) { - testassert(! classInNameList(names, "MyMissingSuper")); - testassert(! classInNameList(names, "MyMissingSub")); - } else { - testassert(classInNameList(names, "MyMissingSuper")); - testassert(classInNameList(names, "MyMissingSub")); - } - free(names); - - // methods - testassert(20 == [NotMissingRoot method]); - testassert(21 == [NotMissingSuper method]); - testassert(22 == [MyNotMissingSuper method]); - testassert(23 == [MyNotMissingSub method]); - if (weakMissing) { - testassert(0 == [MissingRoot method]); - testassert(0 == [MissingSuper method]); - testassert(0 == [MyMissingSuper method]); - testassert(0 == [MyMissingSub method]); - } else { - testassert(10 == [MissingRoot method]); - testassert(11 == [MissingSuper method]); - testassert(12 == [MyMissingSuper method]); - testassert(13 == [MyMissingSub method]); - } - - // category methods - testassert(30 == [NotMissingRoot cat_method]); - testassert(31 == [NotMissingSuper cat_method]); - testassert(32 == [MyNotMissingSuper cat_method]); - testassert(33 == [MyNotMissingSub cat_method]); - if (weakMissing) { - testassert(0 == [MissingRoot cat_method]); - testassert(0 == [MissingSuper cat_method]); - testassert(0 == [MyMissingSuper cat_method]); - testassert(0 == [MyMissingSub cat_method]); - } else { - testassert(40 == [MissingRoot cat_method]); - testassert(41 == [MissingSuper cat_method]); - testassert(42 == [MyMissingSuper cat_method]); - testassert(43 == [MyMissingSub cat_method]); - } - - // allocations and ivars - id obj; - NotMissingSuper *obj2; - MissingSuper *obj3; - testassert((obj = [[NotMissingRoot alloc] init])); - RELEASE_VAR(obj); - testassert((obj2 = [[NotMissingSuper alloc] init])); - TESTIVAR(obj2->ivar == 200); - RELEASE_VAR(obj2); - testassert((obj2 = [[MyNotMissingSuper alloc] init])); - TESTIVAR(obj2->ivar == 200); - RELEASE_VAR(obj2); - testassert((obj2 = [[MyNotMissingSub alloc] init])); - TESTIVAR(obj2->ivar == 200); - RELEASE_VAR(obj2); - if (weakMissing) { - testassert([[MissingRoot alloc] init] == nil); - testassert([[MissingSuper alloc] init] == nil); - testassert([[MyMissingSuper alloc] init] == nil); - testassert([[MyMissingSub alloc] init] == nil); - } else { - testassert((obj = [[MissingRoot alloc] init])); - RELEASE_VAR(obj); - testassert((obj3 = [[MissingSuper alloc] init])); - TESTIVAR(obj3->ivar == 100); - RELEASE_VAR(obj3); - testassert((obj3 = [[MyMissingSuper alloc] init])); - TESTIVAR(obj3->ivar == 100); - RELEASE_VAR(obj3); - testassert((obj3 = [[MyMissingSub alloc] init])); - TESTIVAR(obj3->ivar == 100); - RELEASE_VAR(obj3); - } - - *strrchr(argv[0], '.') = 0; - succeed(basename(argv[0])); - return 0; -} - diff --git a/objc/objc-runtime/test/weak2.m b/objc/objc-runtime/test/weak2.m deleted file mode 100644 index 394363f..0000000 --- a/objc/objc-runtime/test/weak2.m +++ /dev/null @@ -1,82 +0,0 @@ -// See instructions in weak.h - -#include "test.h" -#include "weak.h" -#include <objc/objc-internal.h> - -int state = 0; - -static void *noop_fn(void *self, SEL _cmd __unused) { - return self; -} -static void *retain_fn(void *self, SEL _cmd __unused) { - void * (*fn)(void *) = (typeof(fn))_objc_rootRetain; - return fn(self); -} -static void release_fn(void *self, SEL _cmd __unused) { - void (*fn)(void *) = (typeof(fn))_objc_rootRelease; - fn(self); -} -static void *autorelease_fn(void *self, SEL _cmd __unused) { - void * (*fn)(void *) = (typeof(fn))_objc_rootAutorelease; - return fn(self); -} - -#if !defined(EMPTY) - -@implementation MissingRoot -+(void) initialize { } -+(Class) class { return self; } -+(id) alloc { return _objc_rootAlloc(self); } -+(id) allocWithZone:(void*)zone { return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone); } --(id) init { return self; } --(void) dealloc { _objc_rootDealloc(self); } -+(int) method { return 10; } -+(void) load { - class_addMethod(self, sel_registerName("retain"), (IMP)retain_fn, ""); - class_addMethod(self, sel_registerName("release"), (IMP)release_fn, ""); - class_addMethod(self, sel_registerName("autorelease"), (IMP)autorelease_fn, ""); - - class_addMethod(object_getClass(self), sel_registerName("retain"), (IMP)noop_fn, ""); - class_addMethod(object_getClass(self), sel_registerName("release"), (IMP)noop_fn, ""); - class_addMethod(object_getClass(self), sel_registerName("autorelease"), (IMP)noop_fn, ""); - - state++; -} -@end - -@implementation MissingSuper -+(int) method { return 1+[super method]; } --(id) init { self = [super init]; ivar = 100; return self; } -+(void) load { state++; } -@end - -#endif - -@implementation NotMissingRoot -+(void) initialize { } -+(Class) class { return self; } -+(id) alloc { return _objc_rootAlloc(self); } -+(id) allocWithZone:(void*)zone { return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone); } --(id) init { return self; } --(void) dealloc { _objc_rootDealloc(self); } -+(int) method { return 20; } -+(void) load { - class_addMethod(self, sel_registerName("retain"), (IMP)retain_fn, ""); - class_addMethod(self, sel_registerName("release"), (IMP)release_fn, ""); - class_addMethod(self, sel_registerName("autorelease"), (IMP)autorelease_fn, ""); - - class_addMethod(object_getClass(self), sel_registerName("retain"), (IMP)noop_fn, ""); - class_addMethod(object_getClass(self), sel_registerName("release"), (IMP)noop_fn, ""); - class_addMethod(object_getClass(self), sel_registerName("autorelease"), (IMP)noop_fn, ""); - - state++; -} -@end - -@implementation NotMissingSuper -+(int) method { return 1+[super method]; } --(id) init { self = [super init]; ivar = 200; return self; } -+(void) load { state++; } -@end - diff --git a/objc/objc-runtime/test/weakcopy.m b/objc/objc-runtime/test/weakcopy.m deleted file mode 100644 index 1ffdd8f..0000000 --- a/objc/objc-runtime/test/weakcopy.m +++ /dev/null @@ -1,84 +0,0 @@ -// TEST_CONFIG - -#include "test.h" - -#if __OBJC_GC__ && __cplusplus && __i386__ - -int main() -{ - testwarn("rdar://19042235 test disabled for 32-bit objc++ GC because of unknown bit rot"); - succeed(__FILE__); -} - -#else - -#include "testroot.i" -#include <stdint.h> -#include <string.h> -#include <objc/objc-runtime.h> - -@interface Weak : TestRoot { - @public - __weak id value; -} -@end -@implementation Weak -@end - -Weak *oldObject; -Weak *newObject; - -void *fn(void *arg __unused) -{ - objc_registerThreadWithCollector(); - - return NULL; -} - -int main() -{ - testonthread(^{ - TestRoot *value; - - PUSH_POOL { - value = [TestRoot new]; - testassert(value); - oldObject = [Weak new]; - testassert(oldObject); - - oldObject->value = value; - testassert(oldObject->value == value); - - newObject = [oldObject copy]; - testassert(newObject); - testassert(newObject->value == oldObject->value); - - newObject->value = nil; - testassert(newObject->value == nil); - testassert(oldObject->value == value); - } POP_POOL; - - testcollect(); - TestRootDealloc = 0; - TestRootFinalize = 0; - RELEASE_VAR(value); - }); - - testcollect(); - testassert(TestRootDealloc || TestRootFinalize); - -#if defined(__OBJC_GC__) || __has_feature(objc_arc) - testassert(oldObject->value == nil); -#else - testassert(oldObject->value != nil); -#endif - testassert(newObject->value == nil); - - RELEASE_VAR(newObject); - RELEASE_VAR(oldObject); - - succeed(__FILE__); - return 0; -} - -#endif diff --git a/objc/objc-runtime/test/weakframework-missing.m b/objc/objc-runtime/test/weakframework-missing.m deleted file mode 100644 index 43de10b..0000000 --- a/objc/objc-runtime/test/weakframework-missing.m +++ /dev/null @@ -1,14 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/weak2.m -DWEAK_FRAMEWORK=1 -DWEAK_IMPORT= -UEMPTY -dynamiclib -o libweakframework.dylib - - $C{COMPILE} $DIR/weakframework-missing.m -L. -weak-lweakframework -o weakframework-missing.out - - $C{COMPILE} $DIR/weak2.m -DWEAK_FRAMEWORK=1 -DWEAK_IMPORT= -DEMPTY= -dynamiclib -o libweakframework.dylib - -END -*/ - -#define WEAK_FRAMEWORK 1 -#define WEAK_IMPORT -#include "weak.m" diff --git a/objc/objc-runtime/test/weakframework-not-missing.m b/objc/objc-runtime/test/weakframework-not-missing.m deleted file mode 100644 index 2a11104..0000000 --- a/objc/objc-runtime/test/weakframework-not-missing.m +++ /dev/null @@ -1,11 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/weak2.m -DWEAK_FRAMEWORK=1 -DWEAK_IMPORT= -UEMPTY -dynamiclib -o libweakframework.dylib - - $C{COMPILE} $DIR/weakframework-not-missing.m -L. -weak-lweakframework -o weakframework-not-missing.out -END -*/ - -#define WEAK_FRAMEWORK 1 -#define WEAK_IMPORT -#include "weak.m" diff --git a/objc/objc-runtime/test/weakimport-missing.m b/objc/objc-runtime/test/weakimport-missing.m deleted file mode 100644 index bd86f43..0000000 --- a/objc/objc-runtime/test/weakimport-missing.m +++ /dev/null @@ -1,13 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/weak2.m -UWEAK_FRAMEWORK -DWEAK_IMPORT=__attribute__\\(\\(weak_import\\)\\) -UEMPTY -dynamiclib -o libweakimport.dylib - - $C{COMPILE} $DIR/weakimport-missing.m -L. -weak-lweakimport -o weakimport-missing.out - - $C{COMPILE} $DIR/weak2.m -UWEAK_FRAMEWORK -DWEAK_IMPORT=__attribute__\\(\\(weak_import\\)\\) -DEMPTY= -dynamiclib -o libweakimport.dylib -END -*/ - -// #define WEAK_FRAMEWORK -#define WEAK_IMPORT __attribute__((weak_import)) -#include "weak.m" diff --git a/objc/objc-runtime/test/weakimport-not-missing.m b/objc/objc-runtime/test/weakimport-not-missing.m deleted file mode 100644 index 440f79e..0000000 --- a/objc/objc-runtime/test/weakimport-not-missing.m +++ /dev/null @@ -1,11 +0,0 @@ -/* -TEST_BUILD - $C{COMPILE} $DIR/weak2.m -UWEAK_FRAMEWORK -DWEAK_IMPORT=__attribute__\\(\\(weak_import\\)\\) -UEMPTY -dynamiclib -o libweakimport.dylib - - $C{COMPILE} $DIR/weakimport-not-missing.m -L. -weak-lweakimport -o weakimport-not-missing.out -END -*/ - -// #define WEAK_FRAMEWORK -#define WEAK_IMPORT __attribute__((weak_import)) -#include "weak.m" diff --git a/objc/objc-runtime/test/weakrace.m b/objc/objc-runtime/test/weakrace.m deleted file mode 100644 index 2ff2ea9..0000000 --- a/objc/objc-runtime/test/weakrace.m +++ /dev/null @@ -1,76 +0,0 @@ -// TEST_CONFIG MEM=mrc - -#include "test.h" -#include <objc/NSObject.h> - -static semaphore_t go1; -static semaphore_t go2; -static semaphore_t done; - -#define VARCOUNT 100000 -static id obj; -static id vars[VARCOUNT]; - - -void *destroyer(void *arg __unused) -{ - while (1) { - semaphore_wait(go1); - for (int i = 0; i < VARCOUNT; i++) { - objc_destroyWeak(&vars[i]); - } - semaphore_signal(done); - } -} - - -void *deallocator(void *arg __unused) -{ - while (1) { - semaphore_wait(go2); - [obj release]; - semaphore_signal(done); - } -} - - -void cycle(void) -{ - // rdar://12896779 objc_destroyWeak() versus weak clear in dealloc - - // Clean up from previous cycle - objc_destroyWeak() doesn't set var to nil - for (int i = 0; i < VARCOUNT; i++) { - vars[i] = nil; - } - - obj = [NSObject new]; - for (int i = 0; i < VARCOUNT; i++) { - objc_storeWeak(&vars[i], obj); - } - - // let destroyer start before deallocator runs - semaphore_signal(go1); - sched_yield(); - semaphore_signal(go2); - - semaphore_wait(done); - semaphore_wait(done); -} - - -int main() -{ - semaphore_create(mach_task_self(), &go1, 0, 0); - semaphore_create(mach_task_self(), &go2, 0, 0); - semaphore_create(mach_task_self(), &done, 0, 0); - - pthread_t th[2]; - pthread_create(&th[1], NULL, deallocator, NULL); - pthread_create(&th[1], NULL, destroyer, NULL); - - for (int i = 0; i < 100; i++) { - cycle(); - } - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/xref.m b/objc/objc-runtime/test/xref.m deleted file mode 100644 index 6418e3f..0000000 --- a/objc/objc-runtime/test/xref.m +++ /dev/null @@ -1,32 +0,0 @@ -// TEST_CFLAGS - -#include <Foundation/NSObject.h> -#include <objc/runtime.h> -#include <objc/objc-internal.h> - -#include "test.h" - -int main() -{ - // rdar://8350188 External references (handles) - - id object = [NSObject new]; - testassert(object); - - // STRONG - objc_xref_t xref = _object_addExternalReference(object, OBJC_XREF_STRONG); - testassert(xref); - testassert(_object_readExternalReference(xref) == object); - _object_removeExternalReference(xref); - // TODO: expect a crash if a stale xref is used. - - // WEAK - xref = _object_addExternalReference(object, OBJC_XREF_WEAK); - testassert(xref); - testassert(_object_readExternalReference(xref) == object); - _object_removeExternalReference(xref); - - RELEASE_VAR(object); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/test/zone.m b/objc/objc-runtime/test/zone.m deleted file mode 100644 index 46ec5ea..0000000 --- a/objc/objc-runtime/test/zone.m +++ /dev/null @@ -1,40 +0,0 @@ -// TEST_CONFIG - -#include "test.h" -#include <mach/mach.h> -#include <malloc/malloc.h> - -// Look for malloc zone "ObjC" iff OBJC_USE_INTERNAL_ZONE is set. -// This fails if objc tries to allocate before checking its own -// environment variables (rdar://6688423) - -int main() -{ - if (is_guardmalloc()) { - // guard malloc confuses this test - succeed(__FILE__); - } - - kern_return_t kr; - vm_address_t *zones; - unsigned int count, i; - BOOL has_objc = NO, want_objc = NO; - - want_objc = (getenv("OBJC_USE_INTERNAL_ZONE") != NULL) ? YES : NO; - testprintf("want objc %s\n", want_objc ? "YES" : "NO"); - - kr = malloc_get_all_zones(mach_task_self(), NULL, &zones, &count); - testassert(!kr); - for (i = 0; i < count; i++) { - const char *name = malloc_get_zone_name((malloc_zone_t *)zones[i]); - if (name) { - BOOL is_objc = (0 == strcmp(name, "ObjC_Internal")) ? YES : NO; - if (is_objc) has_objc = YES; - testprintf("zone %s\n", name); - } - } - - testassert(want_objc == has_objc); - - succeed(__FILE__); -} diff --git a/objc/objc-runtime/unexported_symbols b/objc/objc-runtime/unexported_symbols deleted file mode 100644 index 73f77a8..0000000 --- a/objc/objc-runtime/unexported_symbols +++ /dev/null @@ -1,17 +0,0 @@ -.objc_class_name___IncompleteProtocol -__Znam -__ZnamRKSt9nothrow_t -__Znwm -__ZnwmRKSt9nothrow_t -__ZdaPv -__ZdaPvRKSt9nothrow_t -__ZdlPv -__ZdlPvRKSt9nothrow_t -__ZTISt9bad_alloc -__ZTISt9exception -__ZTISt11logic_error -__ZTISt12length_error -__ZTSSt9bad_alloc -__ZTSSt9exception -__ZTSSt11logic_error -__ZTSSt12length_error diff --git a/objc/objc-runtime/version.bat b/objc/objc-runtime/version.bat deleted file mode 100755 index 7df1c3a..0000000 --- a/objc/objc-runtime/version.bat +++ /dev/null @@ -1,29 +0,0 @@ -:: version.bat -:: Writes version numbers from B&I into version.h for use by version.rc. - -@ECHO OFF - -:: Set default values for environment variables if not set by B&I -IF "%OBJROOT%"=="" SET OBJROOT=. -IF "%RC_PROJECTSOURCEVERSION%"=="" SET RC_PROJECTSOURCEVERSION=0.0 -IF "%RC_PROJECTBUILDVERSION%"=="" SET RC_PROJECTBUILDVERSION=0 - -:: Get version numbers from environment variables -SET major=1 -SET patch=0 -FOR /F "tokens=1* eol= delims=." %%i IN ("%RC_PROJECTSOURCEVERSION%") DO ( - SET minor=%%i - IF NOT "%%j"=="" SET patch=%%j -) -SET build=%RC_PROJECTBUILDVERSION% - -ECHO version %major% . %minor% . %patch% . %build% - -:: Write version.h -ECHO // This file is automatically generated by version.bat. > "%OBJROOT%\version.h" -ECHO // DO NOT EDIT >> "%OBJROOT%\version.h" -ECHO #define major %major% >> "%OBJROOT%\version.h" -ECHO #define minor %minor% >> "%OBJROOT%\version.h" -ECHO #define patch %patch% >> "%OBJROOT%\version.h" -ECHO #define build %build% >> "%OBJROOT%\version.h" -ECHO #define string "%major%,%minor%,%patch%,%build%" >> "%OBJROOT%\version.h" diff --git a/objc/objc-runtime/version.rc b/objc/objc-runtime/version.rc deleted file mode 100644 index 709d0a4..0000000 --- a/objc/objc-runtime/version.rc +++ /dev/null @@ -1,38 +0,0 @@ -#include "Winver.h" - -// built by version.bat; sets variables major, minor, patch, build, string -#include "version.h" - -VS_VERSION_INFO VERSIONINFO - FILEVERSION major,minor,patch,build - PRODUCTVERSION major,minor,patch,build - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS_NT_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE VFT2_UNKNOWN -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "Apple Inc." - VALUE "FileDescription", "Objective-C Runtime Library" - VALUE "FileVersion", string - VALUE "ProductVersion", string - VALUE "ProductName", "objc4" - VALUE "InternalName", "objc4" - VALUE "LegalCopyright", "Copyright (C) 2007-2009, Apple Inc." - VALUE "OriginalFilename", "objc.dll" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END -