Common clang commands

  • Clang-rewrite-objc main.m rewrites obj files to C, C ++ files

  • Clang-xclang-ast -dump -fsyntax-only main.m Generate file generate tree

  • Clang-xclang-dump-tokens main.m — Tokens main.m — tokens main.m — tokens main.m

  • A simple example to see how this is compiled

    #import <Foundation/Foundation.h>
    #define DEFINEEight 8
    
    int main(){
        @autoreleasepool {
            int eight = DEFINEEight;
            int six = 6;
            NSString* site = [[NSString alloc] initWithUTF8String:"starming"];
            int rank = eight + six;
            NSLog(@"%@ rank %d", site, rank);
        }
        return 0;
    }
    Copy the code

The compilation process

  • Compile at the command line

    xcrun -sdk iphoneos clang -arch armv7 -F Foundation -fobjc-arc -c main.m -o main.o
    xcrun -sdk iphoneos clang main.o -arch armv7 -fobjc-arc -framework Foundation -o main
    
    #While you can't see the entire clang process, you can use -e to see what clang does in the preprocessing step.
    clang -E main.m
    
    #After execution, you can see the file
    
    # 1 "/System/Library/Frameworks/Foundation.framework/Headers/FoundationLegacySwiftCompatibility.h" 1 3
    # 185 "/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h"2, 3,
    # 2 "main.m" 2
    
    int main(){
        @autoreleasepool {
            int eight = 8;
            int six = 6;
            NSString* site = [[NSString alloc] initWithUTF8String:"starming"];
            int rank = eight + six;
            NSLog(@"%@ rank %d", site, rank);
        }
        return 0;
    }
    
    #The handling of this process includes macro replacement, header file import, and the like#if processing. After the preprocessing is complete, a lexical analysis is performed, where the code is sliced into tokens such as brackets, equals signs, and strings.
    clang -fmodules -fsyntax-only -Xclang -dump-tokens main.m
    
    #Then it is parsed to verify that the syntax is correct, and all the nodes are formed into an abstract syntax tree AST.
    clang -fmodules -fsyntax-only -Xclang -ast-dump main.m
    
    #After completing these steps, IR intermediate code generation can begin. CodeGen is responsible for translating the syntax tree from top to bottom into LLVM IR, which is the output at the front end of the compilation process and the input at the back end.
    clang -S -fobjc-arc -emit-llvm main.m -o main.ll
    
    #Here LLVM will do some optimization work, in Xcode compilation Settings can also set optimization levels -01, -03, -0s, you can also write your own Pass.
    #Pass is a node that optimizes LLVM, and each node does something that adds up to a complete optimization and transformation of LLVM.
    #If bitcode is enabled, Apple will make further optimization. If there is a new backend architecture, it can still be generated with this optimized Bitcode.
    clang -emit-llvm -c main.m -o main.bc
    
    #To generate the assembly
    clang -S -fobjc-arc main.m -o main.s
    
    #Generate object file
    clang -fmodules -c main.m -o main.o
    
    #Generate an executable so that you can execute and see the output
    clang main.o -o main
    
    #perform
    ./main
    
    #The output
    starming rank 14
    Copy the code
  • Here are the complete steps

    • Compile information is written to auxiliary files to create file architecture.app files
    • Process file packaging information
    • Execute the CocoaPod pre-compile script, checkPods manifest.lock
    • Compile. M files using CompileC and clang
    • Link the required Framework
    • Compile xib
    • Copy xiB, resource file
    • Compile ImageAssets
    • To deal with the info. Plist
    • Run the CocoaPod script
    • Copy standard library
    • Create.app files and signatures
  • See how clang compiles.m files in Xcode

    • After Xcode is compiled, you can view the clang build information for each.m file in the build corresponding to the target in the Show The Report Navigator. Just search for “Show the Report Navigator” in help and it will appear

    • Using MASCompositeConstraint. M for compiling the navigation framework as an example, the task will be described first

      CompileC /Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.bui ld/Debug-iphonesimulator/Masonry.build/Objects-normal/x86_64/MASCompositeConstraint.o Masonry/Masonry/MASCompositeConstraint.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compilerCopy the code
    • Update the working PATH and set the PATH

      cd /Users/lanya/Desktop/Neuer_iOS/Pods export LANG=en_US.US-ASCII export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcod e.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"Copy the code
    • Next comes the actual compile command

      • It’s easier to understand the clang command arguments by looking at the compile commands at 👇

        Clang -x compiler language such as objective-c-arch compiler architecture such as arm7 -f starts with -f. -w starts with -w, you can use these custom build warnings. -D starts with -d, which means precompiled macros, -iphonesimulator11.1. SDK The iOS SDK version used for compilation -i writes the compilation information to the specified auxiliary file -f Required Framework -C identifier indicating the need to run a preprocessor, parse, type check, LLVM generation optimization and assembly code generation. O file -O compilation resultsCopy the code
  • Specific compilation process

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c -arch x86_64  -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu11 -fobjc-arc -fmodules -gmodules -fmodules-cache-path=/Users/lanya/Library/Developer/Xcode/DerivedData/ModuleCache -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fbuild-session-file=/Users/lanya/Library/Developer/Xcode/DerivedData/ModuleCache/Session.modulevalidation -fmodules-validate-once-per-build-session -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -fmodule-name=Masonry -fapplication-extension -Wno-trigraphs -fpascal-strings -O0 -fno-common -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wdocumentation -Wunreachable-code -Wno-implicit-atomic-properties -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-arc-repeated-use-of-weak -Wduplicate-method-match -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wno-float-conversion -Wnon-literal-null-conversion -Wobjc-literal-conversion -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector  -Wno-strict-selector-match -Wundeclared-selector -Wno-deprecated-implementations -DPOD_CONFIGURATION_DEBUG=1 -DDEBUG=1 -DCOCOAPODS=1 -DOBJC_OLD_DISPATCH_PROTOTYPES=0 -isysroot / Applications/Xcode. App/Contents/Developer/Platforms/iPhoneSimulator platform/Developer/SDKs/iPhoneSimulator11.2. The SDK -fasm-blocks -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -mios-simulator-version-min= 8.0-g -Wno-sign-conversion -Winfinite-recursion -Wcomma -Wblock-capture-autoreleasing -Wstrict-prototypes -Wunguarded-availability -fobjc-abi-version=2 -fobjc-legacy-dispatch -index-store-path /Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Index/DataStore -iquote /Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.bui ld/Debug-iphonesimulator/Masonry.build/Masonry-generated-files.hmap -I/Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.b uild/Debug-iphonesimulator/Masonry.build/Masonry-own-target-headers.hmap -I/Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.b uild/Debug-iphonesimulator/Masonry.build/Masonry-all-non-framework-target-headers.hmap -ivfsoverlay /Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.bui ld/all-product-headers.yaml -iquote /Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.bui ld/Debug-iphonesimulator/Masonry.build/Masonry-project-headers.hmap -I/Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Products/Debug-iphonesimulat or/Masonry/include -I/Users/lanya/Desktop/Neuer_iOS/Pods/Headers/Private -I/Users/lanya/Desktop/Neuer_iOS/Pods/Headers/Public -I/Users/lanya/Desktop/Neuer_iOS/Pods/Headers/Public/PgyUpdate -I/Users/lanya/Desktop/Neuer_iOS/Pods/Headers/Public/Pgyer -I/Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.b uild/Debug-iphonesimulator/Masonry.build/DerivedSources/x86_64 -I/Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.b uild/Debug-iphonesimulator/Masonry.build/DerivedSources -F/Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Products/Debug-iphonesimulat or/Masonry -include /Users/lanya/Desktop/Neuer_iOS/Pods/Target\ Support\ Files/Masonry/Masonry-prefix.pch -MMD -MT dependencies -MF /Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.bui ld/Debug-iphonesimulator/Masonry.build/Objects-normal/x86_64/MASCompositeConstraint.d --serialize-diagnostics /Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.bui ld/Debug-iphonesimulator/Masonry.build/Objects-normal/x86_64/MASCompositeConstraint.dia -c /Users/lanya/Desktop/Neuer_iOS/Pods/Masonry/Masonry/MASCompositeConstraint.m -o /Users/lanya/Library/Developer/Xcode/DerivedData/NEUer-bjvoyplxzoxgkpgkiodfvurkgzwn/Build/Intermediates.noindex/Pods.bui ld/Debug-iphonesimulator/Masonry.build/Objects-normal/x86_64/MASCompositeConstraint.oCopy the code

​

  • After compiling the third-party library, we will build the target of our program

    Create product structure Process product packaging Run custom shell script 'Check Pods Manifest.lock' Compile ... .m files in each project Link /Users/... Copy path... Compile asset catalogs Compile Storyboard file... Process info.plist Link Storyboards Run custom shell script 'Embed Pods Frameworks' Run custom shell script 'Copy Pods Resources' ... Touch NEUer.app Sign NEUer.appCopy the code

  • Target controls the Build process

    • Build Settings, Build Phases, and Build Rules in Xcode’s Project Editor control the compilation process.
  • Build Phases

    • Rules for building executables. Specify dependencies for target. Build dependencies are required before Target builds. Specify all files that must be compiled in the Compile Source. These files are processed according to the Build Setting and Build Rules.
    • The Link Binary With Libraries list all the static and dynamic Libraries that will be linked to the compiled object file.
    • Build Phase also copies static resources into the bundle.
    • You can do this by adding custom scripts to build Phases, as CocoaPods does.
  • Bulid Rules

    • Specifies how different file types are compiled. Each build rule specifies how the type is handled and where the output is. A new rule can be added to add handling methods for specific file types.
  • Bulid Settings

    • Set the options at each stage of the build process.
  • Pbxproj engineering file

* These Settings for build process control are saved in the project file. Pbxproj. In this file you can look for rootObject's ID * and use that ID to find the definition of the main project. ```objective-c /* Begin PBXProject section */ 2EC5E1AA1E7814B200BAB0EF /* Project object */ = { isa = PBXProject; . Targets targets = (2EC5E1B11E7814B200BAB0EF /*) /* End PBXProject section */ * targets will point to the definition of each taget EWork */, ); BuildConfigurationList specifies the available configuration items, and buildConfigurationList specifies the available configuration items. Contains Debug and Release. BuildPhases, buildRules, and Dependencies can be defined in more detail in this index. */ /* Begin PBXNativeTarget section */ 2EC5E1B11E7814B200BAB0EF /* EWork */ = { isa = PBXNativeTarget; buildConfigurationList = 2EC5E1CC1E7814B200BAB0EF /* Build configuration list for PBXNativeTarget "EWork" */; buildPhases = ( 73F5AAE2AEC5EE766978C0E2 /* [CP] Check Pods Manifest.lock */, 2EC5E1AE1E7814B200BAB0EF /* Sources */, 2EC5E1AF1E7814B200BAB0EF /* Frameworks */, 2EC5E1B01E7814B200BAB0EF /* Resources */, B42D03564A9A71BAD7183E61 /* [CP] Embed Pods Frameworks */, 4672989246AFA7B2776DFA56 /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( ); name = EWork; productName = EWork; productReference = 2EC5E1B21E7814B200BAB0EF /* EWork.app */; productType = "com.apple.product-type.application"; }; /* Begin XCConfigurationList section */ 2EC5E1AD1E7814B200BAB0EF /* Build configuration list for PBXProject "EWork" */ = { isa = XCConfigurationList; buildConfigurations = ( 2EC5E1CA1E7814B200BAB0EF /* Debug */, 2EC5E1CB1E7814B200BAB0EF /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 2EC5E1CC1E7814B200BAB0EF /* Build configuration list for PBXNativeTarget "EWork" */ = { isa = XCConfigurationList; buildConfigurations = ( 2EC5E1CD1E7814B200BAB0EF /* Debug */, 2EC5E1CE1E7814B200BAB0EF /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ ```Copy the code
  • Link Map File of binary content generated after compilation

    • Application sandbox path acquisition

    • LinkMapFile

      • What is LinkMap

        • In the field of iOS development, LinkMap output is a pure text format file, containing important compile information and error information, this is Apple is used to analyze your application to the main way, in this way can find applications in whether or not to use the private library such as the content of the submitted does not comply with the Apple application specification, but for our developer, LinkMap is an effective way to analyze source code and view Crash
      • Why use LinkMap

        • When a large iOS project in the process of continuous iterative update, a growing amount of code, need to reconstruct and review code more and more, but once the code to achieve a certain degree becomes less controllable, in order to make the project can be sustainable and integrated the steady development, narrowing the iOS installation package size is must do, You usually start by compressing images and audio files, using development tools to find redundant resource files, and then refactoring the code to make the executable leaner. In the process of continuous iteration of a project I was engaged in, the installation package of App was getting bigger and bigger. Through shell script analysis, it was up to hundreds of thousands of lines, which was very necessary to slim down, including.h.M.m.CP.RSS format files. Watch program introduced in Pods file and related third party libraries, as many as hundreds of libraries, then such a large App will involve the issue of application of thin body, how to solve the problem of the code is not controllable, how to improve the project the stability and robustness of the underlying infrastructure, believe LinkMap can give us some answers.

        • The composition of LinkMap

          • App compile Path (#Path)
            • # Path: /Users/lanya/Library/Developer/Xcode/DerivedData/littleTest-fcueraakmygtmodagachcreqjbjw/Build/Products/Debug/littleTest
          • App architecture (#Arch)
            • # Arch: x86_64
          • Complete list of Object files for App (#Object Files)
          • App Section table (#Section)
          • Position and size of specific object files in the corresponding section of App (#Symbols)
        • Enable mode and file directory of the LinkMap service

          • Setting Write Link Map File to Yes in Build Settings will generate such a File in the specified directory each compilation.Xcode->Project->Build Settings-> Search Map -> Set the Write Link Map Files option to YESXcodeproj = xxx-xxxxx. Xcodeproj = xxx-xxxxx. Xcodeproj = xxx-xxxxx
          • The file is located in the specified path, default is in~/Library/Developer/Xcode/DerivedData/xxx-xxx-fwtuexpkzxsfkjaootcqwizogrhf/Build/Intermediates/xx-xxx.build/Debug-iphone simulator/xxx-xxx.build/xxx-xxx-LinkMap-normal-x86_64.txt
          • For example: One of my projects LitteleTest:/Users/lanya/Library/Developer/Xcode/DerivedData/littleTest-fcueraakmygtmodagachcreqjbjw/Build/Intermediates.noindex/lit tleTest.build/Debug/littleTest.build/littleTest-LinkMap-normal-x86_64.txt
        • Now let’s talk about what the LinkMap parts do

          • #Object Files: the contents of this section are.o compiled from.m files and.a files that need link. The file number is followed by the file path.

             # Object files:[ 0] linker synthesized [ 1] /Users/lanya/Library/Developer/Xcode/DerivedData/littleTest-fcueraakmygtmodagachcreqjbjw/Build/Intermediates.noindex/lit tleTest.build/Debug/littleTest.build/Objects-normal/x86_64/main.o [ 2] /Users/lanya/Library/Developer/Xcode/DerivedData/littleTest-fcueraakmygtmodagachcreqjbjw/Build/Intermediates.noindex/lit tleTest.build/Debug/littleTest.build/Objects-normal/x86_64/Test.o [ 3] / Applications/Xcode. App/Contents/Developer/Platforms/MacOSX platform/Developer/SDKs/MacOSX10.13 SDK/System/Library/Frame works//Foundation.framework/Foundation.tbd [ 4] / Applications/Xcode. App/Contents/Developer/Platforms/MacOSX platform/Developer/SDKs/MacOSX10.13 SDK/usr/lib/libobjc. TBDCopy the code
          • App Section table (#Section) : This describes the position and size of each Section in the executable. The Segment type of each Section is __TEXT code Segment and __DATA data Segment.

              # Sections:
                # Address	Size    	Segment	Section
                0x100000B10	0x000002D9	__TEXT	__text
                0x100000DEA	0x00000054	__TEXT	__stubs
                0x100000E40	0x0000009C	__TEXT	__stub_helper
                0x100000EDC	0x0000006E	__TEXT	__objc_methname
                0x100000F4A	0x0000003B	__TEXT	__cstring
                0x100000F85	0x00000007	__TEXT	__objc_classname
                0x100000F8C	0x0000001D	__TEXT	__objc_methtype
                0x100000FAC	0x00000048	__TEXT	__unwind_info
                0x100001000	0x00000010	__DATA	__nl_symbol_ptr
                0x100001010	0x00000070	__DATA	__la_symbol_ptr
                0x100001080	0x00000060	__DATA	__cfstring
                0x1000010E0	0x00000008	__DATA	__objc_classlist
                0x1000010E8	0x00000008	__DATA	__objc_imageinfo
                0x1000010F0	0x00000170	__DATA	__objc_const
                0x100001260	0x00000020	__DATA	__objc_selrefs
                0x100001280	0x00000008	__DATA	__objc_classrefs
                0x100001288	0x00000008	__DATA	__objc_superrefs
                0x100001290	0x00000010	__DATA	__objc_ivar
                0x1000012A0	0x00000050	__DATA	__objc_data
            Copy the code
          • Position and size of the specific object file in the corresponding section of App (#Symbols) : Symbols subdivides Sections. All methods, IVar, and strings are described here, along with their corresponding addresses, sizes, and file numbers.

            # Symbols:# Address Size File Name 0x100000B10 0x00000106 [ 1] _main 0x100000C20 0x000000A0 [ 2] -[Test init] 0x100000CC0 0x00000060 [ 2] -[Test setObject:] 0x100000D20 0x00000040 [ 2] -[Test obj] 0x100000D60 0x00000040 [ 2] -[Test setObj:] 0x100000DA0 0x00000049 [ 2] -[Test .cxx_destruct] 0x100000DEA 0x00000006 [ 3] _NSHomeDirectory 0x100000DF0 0x00000006 [ 3] _NSLog 0x100000DF6 0x00000006 [ 4] _objc_autoreleasePoolPop 0x100000DFC 0x00000006 [ 4] _objc_autoreleasePoolPush 0x100000E02 0x00000006 [ 4] _objc_autoreleaseReturnValue 0x100000E08 0x00000006 [ 4] _objc_destroyWeak 0x100000E0E 0x00000006 [ 4] _objc_loadWeakRetained 0x100000E14 0x00000006 [ 4] _objc_msgSend 0x100000E1A 0x00000006 [ 4] _objc_msgSendSuper2 0x100000E20 0x00000006 [ 4] _objc_release 0x100000E26 0x00000006 [ 4] _objc_retain 0x100000E2C 0x00000006 [ 4] _objc_retainAutoreleasedReturnValue 0x100000E32 0x00000006 [ 4] _objc_storeStrong 0x100000E38 0x00000006  [ 4] _objc_storeWeak 0x100000E40 0x00000010 [ 0] helper helper 0x100000E50 0x0000000A [ 3] _NSHomeDirectory 0x100000E5A  0x0000000A [ 3] _NSLog 0x100000E64 0x0000000A [ 4] _objc_autoreleasePoolPop 0x100000E6E 0x0000000A [ 4] _objc_autoreleasePoolPush 0x100000E78 0x0000000A [ 4] _objc_autoreleaseReturnValue 0x100000E82 0x0000000A [ 4] _objc_destroyWeak 0x100000E8C 0x0000000A [ 4] _objc_loadWeakRetained 0x100000E96 0x0000000A [ 4] _objc_msgSend 0x100000EA0 0x0000000A [ 4] _objc_msgSendSuper2 0x100000EAA 0x0000000A [ 4] _objc_release 0x100000EB4 0x0000000A [ 4] _objc_retain 0x100000EBE 0x0000000A [ 4] _objc_retainAutoreleasedReturnValue 0x100000EC8 0x0000000A [ 4] _objc_storeStrong 0x100000ED2 0x0000000A [ 4] _objc_storeWeak 0x100000EDC 0x00000006 [ 1] literal string: alloc 0x100000EE2 0x00000014 [ 1] literal string: initWithUTF8String: 0x100000EF6 0x00000020 [ 1] literal string: stringByAppendingPathComponent: 0x100000F16 0x00000005 [ 2] literal string: init 0x100000F1B 0x0000000B [ 2] literal string: setObject: 0x100000F26 0x0000000E [ 2] literal string: .cxx_destruct 0x100000F34 0x00000004 [ 2] literal string: obj 0x100000F38 0x00000008 [ 2] literal string: setObj: 0x100000F40 0x00000005 [ 2] literal string: obj_ 0x100000F45 0x00000005 [ 2] literal string: _obj 0x100000F4A 0x00000009 [ 1] literal string: starming 0x100000F53 0x0000000B [ 1] literal string: %@ rank %d 0x100000F5E 0x00000013 [ 1] literal string: Documents/neuer.db 0x100000F71 0x00000003 [ 1] literal string: %@ 0x100000F74 0x00000004 [ 2] literal string: obj 0x100000F78 0x0000000D [ 2] literal string: T@,W,N,V_obj 0x100000F85 0x00000005 [ 2] literal string: Test 0x100000F8A 0x00000002 [ 2] literal string: 0x100000F8C 0x00000008 [ 2] literal string: @16@0:8 0x100000F94 0x0000000B [ 2] literal string: v24@0:8@16 0x100000F9F 0x00000008 [ 2] literal string: v16@0:8 0x100000FA7 0x00000002 [ 2] literal string: @ 0x100000FAC 0x00000048 [ 0] compact unwind info 0x100001000 0x00000008 [ 0] non-lazy-pointer-to-local: dyld_stub_binder 0x100001008 0x00000008 [ 0] non-lazy-pointer 0x100001010 0x00000008 [ 3] _NSHomeDirectory 0x100001018 0x00000008 [ 3] _NSLog 0x100001020 0x00000008 [ 4] _objc_autoreleasePoolPop 0x100001028 0x00000008 [ 4] _objc_autoreleasePoolPush 0x100001030 0x00000008 [ 4] _objc_autoreleaseReturnValue 0x100001038 0x00000008 [ 4] _objc_destroyWeak 0x100001040 0x00000008 [ 4] _objc_loadWeakRetained 0x100001048 0x00000008 [ 4] _objc_msgSend 0x100001050 0x00000008 [ 4] _objc_msgSendSuper2 0x100001058 0x00000008 [ 4] _objc_release 0x100001060 0x00000008 [ 4] _objc_retain 0x100001068 0x00000008 [ 4] _objc_retainAutoreleasedReturnValue 0x100001070 0x00000008 [ 4] _objc_storeStrong 0x100001078 0x00000008 [ 4] _objc_storeWeak 0x100001080 0x00000020 [ 1] CFString 0x1000010A0 0x00000020 [ 1] CFString 0x1000010C0 0x00000020 [ 1] CFString 0x1000010E0 0x00000008 [ 2] anon 0x1000010E8 0x00000008 [ 0] objc image info 0x1000010F0 0x00000048 [ 2] l_OBJC_METACLASS_RO_$_Test 0x100001138 0x00000080 [ 2] l_OBJC_$_INSTANCE_METHODS_Test 0x1000011B8 0x00000048 [ 2] l_OBJC_$_INSTANCE_VARIABLES_Test 0x100001200 0x00000018 [ 2] l_OBJC_$_PROP_LIST_Test 0x100001218 0x00000048 [ 2] l_OBJC_CLASS_RO_$_Test 0x100001260 0x00000008 [ 1] pointer-to-literal-cstring 0x100001268 0x00000008 [ 1] pointer-to-literal-cstring 0x100001270 0x00000008 [ 1] pointer-to-literal-cstring 0x100001278 0x00000008 [ 2] pointer-to-literal-cstring 0x100001280 0x00000008 [ 1] objc-class-ref 0x100001288 0x00000008 [ 2] anon 0x100001290 0x00000008 [ 2] _OBJC_IVAR_$_Test.obj_ 0x100001298 0x00000008 [ 2] _OBJC_IVAR_$_Test._obj 0x1000012A0 0x00000028 [ 2] _OBJC_CLASS_$_Test 0x1000012C8 0x00000028 [ 2] _OBJC_METACLASS_$_TestCopy the code
  • dSYM

    • Definition: after each compilation, a dSYM file is generated. During execution, the program calls the method function by address, and the dSYM file stores the function address map, so that the address in the call stack can obtain the location of the specific function through the dSYM mapping table. It is generally used to process the call stack acquired during crash. The crash file symbolizes it.
    • Function: When the release version crashes, there’s a log file that contains the memory address of the error, Using the Symbolicatecrash tool, you can convert logs and dSYM files into readable log information, that is, the memory address, into a function or variable in the program and the file name to which it belongs. Product -> scheme -> EditScheme)
    • How to find:/ Users/username/Library/Developer/Xcode/DerivedData/littleTest fcueraakmygtmodagachcreqjbjw/Build/Products/Release
    • DSYM crash log error location: You need to use Symbolicatecrash, a tool that comes with Xcode, for error conversion. Find symbolicatecrash:find /Applications/Xcode.app -name symbolicatecrash -type f
      • Find the location as:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/PrivateFrameworks/DVTFou ndation.framework/symbolicatecrash
    • Then place the Symbolicatecrash, Crash, and dSYM files in the same directory
    • Specific operation please see this: summary is very good
  • The Mach – O files

    • First let’s look at what fat binaries mean: That’s what Wikipedia says, but basically, fat binaries are binaries that have more content than normal binaries because they contain compatibility information for iOS devices that need to support different CPU architectures.

  • Mach-o, short for Mach Object file format, is an executable file, object code, shared libraries, dynamically loaded code, and core DUMP. Is an alternative to the A. out format. Mach-O provides more extensibility and faster access to symbol table information. Mach-o is used on Mach core-based systems, and is currently used in NeXTSTEP, Darwin, and Mac OS X (iPhone).

  • Document compiled executables, object code, shared libraries, dynamically loaded code, and memory dump file formats. Unlike a file like XML, it is just a binary byte stream with different blocks of data that contain meta information, such as byte order, CPU type, block size, etc. The file content cannot be modified because there is a _CodeSignature directory in the.app directory, which contains the signature of the program code. The signature is used to ensure that the files in the.app, including resource files and Mach-O files, cannot be changed after the signature.

  • Mach-O

    • Mach-o Header: contains byte order, magic, CPU type, number of loading instructions, etc
    • Load Commands: A table that contains many contents, including region locations, symbol tables, dynamic symbol tables, etc. Each load instruction contains a meta-information such as the instruction type, name, location in the binary, and so on.
    • Raw segment data: Can have multiple segments, each of which can have zero or more sections. Each segment has a virtual address mapped to the process’s address space.
  • Take a look at the structure that describes this file

    struct mach_header {
      uint32_t      magic;
      cpu_type_t    cputype;
      cpu_subtype_t cpusubtype;
      uint32_t      filetype;
      uint32_t      ncmds;
      uint32_t      sizeofcmds;
      uint32_t      flags;
    };
    
    struct segment_command {
      uint32_t  cmd;
      uint32_t  cmdsize;
      char      segname[16];
      uint32_t  vmaddr;
      uint32_t  vmsize;
      uint32_t  fileoff;
      uint32_t  filesize;
      vm_prot_t maxprot;
      vm_prot_t initprot;
      uint32_t  nsects;
      uint32_t  flags;
    };
    Copy the code
    • With this structure, you need to fetch magic first, and then other information based on the offset. Traversing NCMDS yields all segments. Cputype includes CPU_TYPE_I386, CPU_TYPE_X86_64, CPU_TYPE_ARM, and CPU_TYPE_ARM64 CPU types.
  • Mach-O file reference article

    • Mach-O is defined in detail
    • Interesting discussion on the Mach-O loading process
  • Dyld dynamic linking

    • After the executable is generated, dynamic linking is done at startup, binding symbols and addresses. First load the dependent dylibs, correct the address offset, because iOS uses ASLR to do address offset to avoid attacks, determine the non-lazy Pointer address for symbolic address binding, load all classes, Finally, the load method and the constructor constructor function of the Clang Attribute are executed.
  • See article: An in-depth look at iOS compilation