Start optimizing binary rearrangement – operation chapter


1. Page missing interrupt time before optimization (first installation)

If yes, please delete it first-fsanitize-coverage=func,trace-pc-guardto configure.

Delete the app and clear the Xcode cache;

Xcode menu bar > Product > profile (shortcut key command + I), wait for running to complete;

appear InstrumentsInterface, selectSystem Trace ;

Start the project, stop after the first interface appears, and wait for analysis,

Start optimizing binary rearrangement - operation chapter

searchMain Thread, selectVirtu Memory, view missing page interruptFile Backed Page inFrequency and time;

2. Get all function symbols loaded at startup

Delete the app in XcodeBuild Settings > Apple Clang - Custom Compiler Flags > Other C Flags in

add to-fsanitize-coverage=func,trace-pc-guard ,

It will appear after startupFirst interfaceAdd the following code:

#import <dlfcn.h>
#import <libkern/OSAtomic.h>

//Atomic queue
static OSQueueHead symboList = OS_ATOMIC_QUEUE_INIT;
//Define symbol structure
typedef struct {
    void * pc;
    void * next;
} SymbolNode;

void __sanitizer_cov_trace_pc_guard_init(uint32_t *start, uint32_t *stop) {
    static uint64_t N;  // Counter for the guards.
    if (start == stop || *start) return;  // Initialize only once.
    printf("[clang] INIT: %p %p\n", start, stop);
    for (uint32_t *x = start; x < stop; x++)
        *x = ++N;  // Guards should start from 1.

void __sanitizer_cov_trace_pc_guard(uint32_t *guard) {
    //if (!*guard) return;  // Duplicate the guard check.
    void *PC = __builtin_return_address(0);
    SymbolNode * node = malloc(sizeof(SymbolNode));
    *node = (SymbolNode){PC,NULL};
    //Join the team
    //Offsetof is used here to add the next node in the queue and find the position of the next pointer of the previous node
    OSAtomicEnqueue(&symboList, node, offsetof(SymbolNode, next));

void tmpOrderFile() {
    NSMutableArray<NSString *> * symbolNames = [NSMutableArray array];
    while (true) {
        //Offsetof is to find the offset of an attribute relative to a structure
        SymbolNode * node = OSAtomicDequeue(&symboList, offsetof(SymbolNode, next));
        if (node == NULL) break;
        Dl_info info;
        dladdr(node->pc, &info);
        NSString * name = @(info.dli_sname);
        BOOL isObjc = [name hasPrefix:@"+["] || [name hasPrefix:@"-["];
        NSString * symbolName = isObjc ? name : [@"_" stringByAppendingString:name];
        //Weight removal
        if (![symbolNames containsObject:symbolName]) {
            [symbolNames addObject:symbolName];
    //Kill yourself
    NSString * thisFunc = [NSString stringWithFormat:@"_%s",__FUNCTION__];
    if ([symbolNames containsObject:thisFunc]) {
        [symbolNames removeObject:thisFunc];

    NSMutableArray * symbolAry = [NSMutableArray arrayWithArray:[[symbolNames reverseObjectEnumerator] allObjects]];
    NSLog(@"[clang] %@",symbolAry);
    //Write results to file
    NSString * funcString = [symbolAry componentsJoinedByString:@"\n"];
    NSString * filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"lb.order"];
    NSData * fileContents = [funcString dataUsingEncoding:NSUTF8StringEncoding];
    BOOL result = [[NSFileManager defaultManager] createFileAtPath:filePath contents:fileContents attributes:nil];
    if (result) {
        NSLog(@"[clang] %@",filePath);
        Nslog (@ "[clang] file write error");

Then inviewDidAppearCall intmpOrderFile(), (or it can be called in other event methods)

After the first interface appears (or other event methods are triggered and completed), download the file

Start optimizing binary rearrangement - operation chapter

Right click the “display package content” of the downloaded file and find the lb.order file under the TMP file, which contains all the bullets loaded at startup

3. Rearrange start symbols

Copy the ld.order file to the project directory;

Search in build settingorder file, write ld.order file path:

Start optimizing binary rearrangement - operation chapter

Repeat step 1 to see the optimized effect

View symbol rearrangement order

Search link map in build setting and modify itWrite Link Map FileYes, after running toProductsPeer directoryIntermediates.noindexNext find..._ios.buildDirectory under a TXT file, search# Symbols:, which is the symbol order of project compilation. It can be compared with LD. Order. If it is the same, it shows that it is effective

Start optimizing binary rearrangement - operation chapter

4. Time consuming for page missing and interruption after optimization

Start optimizing binary rearrangement - operation chapter

The project is well planned, so there is not much room for optimization

Page missing interrupt speed increased by 32.44%; The overall speed increased by 46.34ms and 29.32%.