对苹果“五仁”编程语言Swift的简单分析
苹果在昨天的WWDC上,公布了新的编程语言Swift。这两天开发社区都在讨论这个语言,从语言的特性上大家发现了好多语言的影子,这种情况能够说是集大成,也能够说是“五仁”。每一个人看问题的角度都不同,以下从个人的角度来看看这门语言涉及到的工具链及其对越狱开发的影响。
因为刚刚公布。针对相关工具的介绍差点儿没有,那我们就从xcode中寻找。在shell中运行:
find /Applications/Xcode6-Beta.app/Contents/ -name "*swift*"
能够找到swift相关的文件,简单过滤后,例如以下的文件比較重要:
/Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-demangle /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-ide-test /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-stdlib-tool /Applications/Xcode6-Beta.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources/repl_swift /Applications/Xcode6-Beta.app/Contents//Developer/Toolchains/XcodeDefault.xctoolchain/usr/share/man/man1/swift.1
从找到的文件里我们能够看到包括 man 手冊文件。我们首先看看手冊的内容:
swift(1) Swift Documentation swift(1) NAME swift - <strong>the amazingly new programming language</strong> SYNOPSIS swift [-emit-object|-emit-assembly|-emit-library|-i] [-help] -o output-file input-filenames The full list of supported options is available via "swift -help". DESCRIPTION Swift is a new, high performance systems programming language. It has a clean and modern syntax, and offers seamless access to existing C and Objective-C code and frameworks, and is memory safe (by default). Although inspired by Objective-C and many other languages, Swift is not itself a C-derived language. As a complete and independent language, Swift packages core features like flow control, data structures, and functions, with high-level constructs like objects, protocols, closures, and generics. Swift embraces modules, eliminating the need for headers and the code duplication they entail. 2014-05-17 swift(1)
OVERVIEW: Swift compiler USAGE: swift [options] <inputs> MODES: -dump-ast Parse and type-check input file(s) and dump AST(s) -dump-parse Parse input file(s) and dump AST(s) -emit-assembly Emit assembly file(s) (-S) -emit-bc Emit LLVM BC file(s) -emit-executable Emit a linked executable -emit-ir Emit LLVM IR file(s) -emit-library Emit a linked library -emit-object Emit object file(s) (-c) -emit-silgen Emit raw SIL file(s) -emit-sil Emit canonical SIL file(s) -integrated-repl Integrated REPL mode -i Immediate mode -lldb-repl LLDB-enhanced REPL mode -parse Parse input file(s) -print-ast Parse and type-check input file(s) and pretty print AST(s) -repl REPL mode OPTIONS: -application-extension Restrict code to those available for App Extensions -arch <arch> Compile for architecture <arch> -assert-config <value> Specify the assert_configuration replacement. Possible values are Debug, Release, Replacement. -D <value> Specifies one or more build configuration options -emit-dependencies Emit Make-compatible dependencies files -emit-module-path <path> Emit an importable module to <path> -emit-module Emit an importable module -emit-objc-header-path <path> Emit an Objective-C header file to <path> -emit-objc-header Emit an Objective-C header file -framework <value> Specifies a framework which should be linked against -F <value> Add directory to framework search path -g Emit debug info -help Display available options -import-underlying-module Implicitly imports the Objective-C half of a module -I <value> Add directory to the import search path -j <n> Number of commands to execute in parallel -L <value> Add directory to library link search path -l<value> Specifies a library which should be linked against -module-cache-path <value> Specifies the Clang module cache path -module-link-name <value> Library to link against when using this module -module-name <value> Name of the module to build -nostdimport Don't search the standard library import path for modules -output-file-map <path> A file which specifies the location of outputs -o <file> Write output to <file> -parse-as-library Parse the input file(s) as libraries, not scripts -parse-sil Parse the input file as SIL code, not Swift source -save-temps Save intermediate compilation results -sdk <sdk> Compile against <sdk> -serialize-diagnostics Serialize diagnostics in a binary format -target-cpu <value> Generate code for a particular CPU variant -target-feature [+-]<feature-name> Generate code with a particular CPU feature enabled or disabled -target <value> Generate code for the given target -version Print version information and exit -v Show commands to run and use verbose output -Xcc <arg> Pass <arg> to the C/C++/Objective-C compiler -Xfrontend <arg> Pass <arg> to the Swift frontend -Xlinker <value> Specifies an option which should be passed to the linker -Xllvm <arg> Pass <arg> to LLVM.
这么多參数究竟怎么用呢?。我们一起来看看 xcode 是怎么使用的。
打开xcode6新建一个空project,取名“FuckSwift”:因此,在iOS8之下的设备上,程序打包的时候带上了必要的执行库。
对于iOS8,眼下还没法解开 dyld cache 也就无法知道设备上是否带了这些库,只是应该会带。
接上文,我们建立測试project的目的是为了看看 xcode 怎样使用 swift 编译工具,xcoce编译时的相关參数例如以下:/Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -target armv7-apple-ios5.0 -module-name FuckSwift -O0 -sdk /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.0.sdk -g -module-cache-path /Users/proteas/Library/Developer/Xcode/DerivedData/ModuleCache -I /Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Products/Debug-iphoneos -F /Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Products/Debug-iphoneos -parse-as-library -c -j8 /Users/proteas/Desktop/FuckSwift/FuckSwift/AppDelegate.swift -output-file-map /Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Intermediates/FuckSwift.build/Debug-iphoneos/FuckSwift.build/Objects-normal/armv7/FuckSwift-OutputFileMap.json -serialize-diagnostics -emit-dependencies -emit-module -emit-module-path /Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Intermediates/FuckSwift.build/Debug-iphoneos/FuckSwift.build/Objects-normal/armv7/FuckSwift.swiftmodule -Xcc -iquote -Xcc /Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Intermediates/FuckSwift.build/Debug-iphoneos/FuckSwift.build/FuckSwift-generated-files.hmap -Xcc -I/Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Intermediates/FuckSwift.build/Debug-iphoneos/FuckSwift.build/FuckSwift-own-target-headers.hmap -Xcc -I/Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Intermediates/FuckSwift.build/Debug-iphoneos/FuckSwift.build/FuckSwift-all-target-headers.hmap -Xcc -iquote -Xcc /Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Intermediates/FuckSwift.build/Debug-iphoneos/FuckSwift.build/FuckSwift-project-headers.hmap -Xcc -I/Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Products/Debug-iphoneos/include -Xcc -I/Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Xcc -I/Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Intermediates/FuckSwift.build/Debug-iphoneos/FuckSwift.build/DerivedSources/armv7 -Xcc -I/Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Intermediates/FuckSwift.build/Debug-iphoneos/FuckSwift.build/DerivedSources -Xcc -DDEBUG=1 -emit-objc-header -emit-objc-header-path /Users/proteas/Library/Developer/Xcode/DerivedData/FuckSwift-czflmbyelvdrnvaxblvpkcrhfbie/Build/Intermediates/FuckSwift.build/Debug-iphoneos/FuckSwift.build/Objects-normal/armv7/FuckSwift-Swift.h
參数还是太多。继续精简,把去掉绝对路径:
swift -target armv7-apple-ios5.0 -module-name FuckSwift -O0 -sdk iPhoneOS8.0.sdk -g -module-cache-path ModuleCache -I Debug-iphoneos -F Debug-iphoneos -parse-as-library -c -j8 AppDelegate.swift -output-file-map FuckSwift-OutputFileMap.json -serialize-diagnostics -emit-dependencies -emit-module -emit-module-path FuckSwift.swiftmodule -Xcc -iquote -Xcc FuckSwift-generated-files.hmap -Xcc -IFuckSwift-own-target-headers.hmap -Xcc -IFuckSwift-all-target-headers.hmap -Xcc -iquote -Xcc FuckSwift-project-headers.hmap -Xcc -Iinclude -Xcc -I/usr/include -Xcc -Iarmv7 -Xcc -IDerivedSources -Xcc -DDEBUG=1 <strong>-emit-objc-header -emit-objc-header-path FuckSwift-Swift.h</strong>
这样就相对清晰了。这里面的參数大家能够对比上述的帮助查看。这里我们一起看两点:
1、Xcc <arg>:Pass <arg> to the C/C++/Objective-C compiler,这里我们能够得到:swift代码非常可能终于被转变成C/C++/Objective-C代码进行静态编译。
2、会生成FuckSwift-Swift.h头文件,对照下这个文件与swift文件。
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow?func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { } func applicationWillEnterForeground(application: UIApplication) { } func applicationDidBecomeActive(application: UIApplication) { } func applicationWillTerminate(application: UIApplication) { } }
SWIFT_CLASS("_TtC9FuckSwift11AppDelegate") @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (nonatomic) UIWindow * window; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions; - (void)applicationWillResignActive:(UIApplication *)application; - (void)applicationDidEnterBackground:(UIApplication *)application; - (void)applicationWillEnterForeground:(UIApplication *)application; - (void)applicationDidBecomeActive:(UIApplication *)application; - (void)applicationWillTerminate:(UIApplication *)application; - (instancetype)init OBJC_DESIGNATED_INITIALIZER; @end
能够看到swift程序是被转换了的,可是是不是转换成了Objective-C程序呢?还须要进一步分析。
打开IDA,载入測试程序的MachO:
我们重点看下函数窗体:
从函数名上我们能够得到例如以下结论:
1、能够看到函数名被“改编”了。
2、swift代码并非被简单得编译成了ObjC代码
3、swift代码终于被编译成了纯C代码,相对于ObjC来说省去了执行时查表进行函数调用的开销,执行效率应该比ObjC要高。
4、从文档上看swfit相对于ObjC来说是更加动态的语言,开发效率也应该比ObjC高
5、对于越狱开发来说,我们仅仅要像Hook C函数那样来Hook swift 函数就能够了。因此MobileSubstrate还是能够工作的。
6、生成的代码还是要遵循 ARM 的ABI标准
就像C++的名称改编一样。改编后的名称尽管能够手工还原可是太麻烦。最好找到工具来做这一件事。前文,我们在查找swift相关的文件时看到一个工具:swift-demangle,以下我们就用它来demangle改编后的名称,看看能够得到什么。
首先,我们切换命令行到xcode6的命令行工具:
sudo xcode-select --switch /Applications/Xcode6-Beta.app/Contents/Developer
然后,我们看看swift-demangle的命令行參数:
USAGE: swift-demangle [options] [mangled name...] OPTIONS: -compact - Compact mode (only emit the demangled names) -expand - Expand mode (show node structure of the demangling) -help - Display available options (-help-hidden for more) -no-sugar - No sugar mode (disable common language idioms such as ? and [] from the output) -tree-only - Tree-only mode (do not show the demangled string) -version - Display the version of this program
从IDA中复制一个函数名,如:
__TToFC9FuckSwift11AppDelegate26applicationDidBecomeActivefS0_FCSo13UIApplicationT_
我们运行例如以下命令:
xcrun swift-demangle "__TToFC9FuckSwift11AppDelegate26applicationDidBecomeActivefS0_FCSo13UIApplicationT_"
得到输出:
_TToFC9FuckSwift11AppDelegate26applicationDidBecomeActivefS0_FCSo13UIApplicationT_ ---> @objc FuckSwift.AppDelegate.applicationDidBecomeActive (FuckSwift.AppDelegate)(ObjectiveC.UIApplication) -> ()
能够看到函数被还原。
到这里我们停下,看看swift对越狱开发的影响:
1、眼下无法使用class-dump得到ObjC的头文件。
2、MobileSubstrate应该还能够正常工作。
3、能够使用demangle工具还原函数名,后期这部分工作IDA可能会自己主动支持。
总之,对越狱开发的流程会略微有影响,针相应用的越狱开发还能够存在。
以下我们看看命令行工具swift-ide-test的參数:
OVERVIEW: Swift IDE Test USAGE: swift-ide-test [options] [input files...] OPTIONS: -D=<string> - Build configurations -F=<string> - add a directory to the framework search path -I=<string> - add a directory to the import search path -annotate-print - Annotate AST printing -code-completion-diagnostics - Print compiler diagnostics while doing code completion -code-completion-token=<string> - Code completion token name -comments-xml-schema=<string> - Filename of the RelaxNG schema for documentation comments -enable-objc-factory-method-constructors - Implicitly import Objective-C factory methods as initializers -enable-objc-implicit-properties - Implicitly import Objective-C getter/setter pairs as properties -explode-pattern-binding-decls - Separate pattern binding decls into individual var decls -fatal-assembler-warnings - Consider warnings as error -fully-qualified-types - Print fully qualified types -fully-qualified-types-if-ambiguous - Print types fully-qualified if they would be ambiguous otherwise -function-definitions - Print function bodies -help - Display available options (-help-hidden for more) -implicit-objc-with - Make the "with" implicit in initializers -import-objc-header=<string> - header to implicitly import -module-cache-path=<string> - Clang module cache path -module-print-hidden - Print non-exported imported or submodules -module-print-skip-overlay - Skip Swift overlay modules -module-print-submodules - Recursively print submodules -module-to-print=<string> - Name of the module to print -objc-bridge-dictionary - Bridge Dictionary<K, V> to NSDictionary -prefer-type-repr - When printing types, prefer printing TypeReprs -print-after-all - Print IR after each pass -print-before-all - Print IR before each pass Mode: -code-completion - Perform code completion -repl-code-completion - Perform REPL-style code completion -syntax-coloring - Perform syntax coloring -structure - Perform document structure annotation -annotate - Perform semantic annotation -test-input-complete - Check if input source is complete -print-ast-not-typechecked - Print the non-typechecked AST -print-ast-typechecked - Print the typechecked AST -print-module - Print visible declarations in a module -print-types - Print types of all subexpressions and declarations in the AST -print-comments - Print documentation comments attached to decls -print-module-comments - Given a module, print documentation comments attached to decls -print-module-imports - Recursively print all imports visible from a particular module -print-usrs - Print USRs for all decls -parse-rest - Parse a ReST file -print-implicit-attrs - Print implicit attributes -print-regular-comments - Print regular comments from clang module headers -print-stats - Print statistics -sdk=<string> - path to the SDK to build against -skip-private-stdlib-decls - Don't print declarations that start with '_' -skip-unavailable - Don't print unavailable declarations -source-filename=<string> - Name of the source file -split-objc-selectors - Split Objective-C selectors -stats - Enable statistics output from program (available with Asserts) -synthesize-sugar-on-types - Always print Array and Optional with sugar -target=<string> - target triple -terminal - Use terminal color for source annotations -time-passes - Time each pass, printing elapsed time for each on exit -typecheck - Type check the AST -version - Display the version of this program
从參数上看。这非常可能是xcode的内部工具,用来做代码完毕与检查的。这里不详细分析。感兴趣的兄弟能够自己试试。
以下我们继续回到 swift 工具上,首先看看parse的输出。运行例如以下命令:
xcrun swift AppDelegate.swift -dump-parse
得到例如以下输出:
(source_file (import_decl UIKit') (class_decl "AppDelegate" type='<null type>' inherits: <null>, <null> (pattern_binding_decl (pattern_typed (pattern_named 'window') )) (var_decl "window" type='<null type>' storage_kind='stored') (func_decl "application(_:didFinishLaunchingWithOptions:)" type='<null type>' (body_params (pattern_typed implicit (pattern_named implicit 'self')) (pattern_tuple (pattern_typed (pattern_named 'application') (type_ident (component id='UIApplication' bind=none))) (pattern_typed (pattern_named 'launchOptions') ))) (result (type_ident (component id='Bool' bind=none))) (brace_stmt (sequence_expr type='<null>' (unresolved_dot_expr type='<null>' field 'window' (declref_expr type='<null>' decl=AppDelegate.(file).AppDelegate.func decl.self@AppDelegate.swift:17:10 specialized=yes)) (assign_expr (**NULL EXPRESSION**) (**NULL EXPRESSION**)) (call_expr type='<null>' (unresolved_decl_ref_expr type='<null>' name=UIWindow specialized=no) (tuple_expr type='<null>' names=frame (unresolved_dot_expr type='<null>' field 'bounds' (call_expr type='<null>' (unresolved_dot_expr type='<null>' field 'mainScreen' (unresolved_decl_ref_expr type='<null>' name=UIScreen specialized=no)) (tuple_expr type='<null>')))))) (sequence_expr type='<null>' (unresolved_dot_expr type='<null>' field 'backgroundColor' (force_value_expr type='<null>' (unresolved_dot_expr type='<null>' field 'window' (declref_expr type='<null>' decl=AppDelegate.(file).AppDelegate.func decl.self@AppDelegate.swift:17:10 specialized=yes)))) (assign_expr (**NULL EXPRESSION**) (**NULL EXPRESSION**)) (call_expr type='<null>' (unresolved_dot_expr type='<null>' field 'whiteColor' (unresolved_decl_ref_expr type='<null>' name=UIColor specialized=no)) (tuple_expr type='<null>'))) (call_expr type='<null>' (unresolved_dot_expr type='<null>' field 'makeKeyAndVisible' (force_value_expr type='<null>' (unresolved_dot_expr type='<null>' field 'window' (declref_expr type='<null>' decl=AppDelegate.(file).AppDelegate.func decl.self@AppDelegate.swift:17:10 specialized=yes)))) (tuple_expr type='<null>')) (return_stmt (unresolved_decl_ref_expr type='<null>' name=true specialized=no)))) (func_decl "applicationWillResignActive(_:)" type='<null type>' (body_params (pattern_typed implicit (pattern_named implicit 'self')) (pattern_tuple (pattern_typed (pattern_named 'application') (type_ident (component id='UIApplication' bind=none))))) (brace_stmt)) (func_decl "applicationDidEnterBackground(_:)" type='<null type>' (body_params (pattern_typed implicit (pattern_named implicit 'self')) (pattern_tuple (pattern_typed (pattern_named 'application') (type_ident (component id='UIApplication' bind=none))))) (brace_stmt)) (func_decl "applicationWillEnterForeground(_:)" type='<null type>' (body_params (pattern_typed implicit (pattern_named implicit 'self')) (pattern_tuple (pattern_typed (pattern_named 'application') (type_ident (component id='UIApplication' bind=none))))) (brace_stmt)) (func_decl "applicationDidBecomeActive(_:)" type='<null type>' (body_params (pattern_typed implicit (pattern_named implicit 'self')) (pattern_tuple (pattern_typed (pattern_named 'application') (type_ident (component id='UIApplication' bind=none))))) (brace_stmt)) (func_decl "applicationWillTerminate(_:)" type='<null type>' (body_params (pattern_typed implicit (pattern_named implicit 'self')) (pattern_tuple (pattern_typed (pattern_named 'application') (type_ident (component id='UIApplication' bind=none))))) (brace_stmt))))
因为不了解编译器相关的知识,无法解析上述输出,可是看起来非常像common lisp 的“点对”数据结构。
另外。我们会注意到还有一个比較重要的命令行參数:-repl。我们一起玩玩,看看这个工具能力怎么样。
在命令行运行例如以下命令:
xcrun swift -repl
能够得到一个脚本解析器的运行环境:
我们參考“The Swift Programming Language”写一个Hello World,看看效果:
能够使用:Ctrl + D退出解析器。
这里能够得到:
1、
swift既能够被编译运行,也能够被解析运行,是真正的动态语言。2、大家能够用这个工具来学习语言特性。
就分析到这里。希望对大家有帮助。