How to Hook messages in IOS

Source: Internet
Author: User

How to Hook messages in IOS

  

After the end of the year, it's time to get started.

We all know that a lot of messages can be easily hooked through APIs in windows. There seems to be no existing APIs in IOS (maybe I haven't found them yet ), some time ago, I happened to see some things during the Objective-C runtime, so I wondered if I could try to implement the hook function.

Why is it necessary to hook a message? Sometimes we may not be able to inherit a class directly, but we want to intercept some messages for processing first, and then proceed to the normal processing process. Some APIs used in the runtime today implement the Basic hook function.

The source code is directly listed below:

1 // 2 // TestHookObject. m 3 // TestHookMessage 4 // 5 // Created by mapleCao on 13-2-28. 6 // Copyright (c) 2013 mapleCao. all rights reserved. 7 // 8 9 # import "TestHookObject. h "10 # import <objc/objc. h> 11 # import <objc/runtime. h> 12 13 @ implementation TestHookObject14 15 // this method will just excute once16 + (void) initialize17 {18 // obtain the method19 Method sendEvent = class_ge in the UIWindow TInstanceMethod ([UIWindow class], @ selector (sendEvent :)); 20 Method sendEventMySelf = class_getInstanceMethod ([self class], @ selector (sendEventHooked :)); 21 22 // bind the original implementation of the target function to the kernel method 23 IMP sendevenibd = method_getImplementation (sendEvent); 24 class_addMethod ([UIWindow class], @ selector (sendEventOriginal :), sendevenibd, method_getTypeEncoding (sendEvent); 25 26 // use Implement. replace 27 IMP sendEventMySelfImp = method_getImplementation (sendEventMySelf); 28 evaluate ([UIWindow class], @ selector (sendEvent :), evaluate, method_getTypeEncoding (sendEvent )); 29} 30 31/* 32 * intercepted sendEvent33 of window * after processing, we can continue calling the normal processing process 34 */35-(void) sendEventHooked :( UIEvent *) event36 {37 // do something what ever you want38 NSLog (@ "haha, this is my self sendEventMet Hod !!!!!!! "); 39 40 // invoke original implemention41 [self implements mselector: @ selector (sendEventOriginal :) withObject: event]; 42} 43 44 @ end

Next we will analyze the above code line by line:

First, let's look at 19 rows. This line mainly aims to get the native sendEvent Method of UIWindow (a struct used to describe the Method ), the second line is to get the sendEvent Method in the class we define (the signatures of these two methods must be the same; otherwise, an error is reported during running ). In row 23rd, we obtained the corresponding IMP (a function pointer) through the native sendEvent Method of UIWindow. In row 24th, we added a sendEventOriginal Method to the UIWindow class using the Runtime API Class_addMethod, this method uses the native sendEvent Implementation of UIWindow and has the same method signature (must be the same; otherwise, an error is returned during running ). Row 27 is the IMP for retrieving sendEventMySelf in our custom class, and row 28 is the key line. The main purpose of this line is to specify a new implementation for the native sendEvent of UIWindow, we can see that we have specified this implementation to our own defined sendEventMySelf. Here, we have done a big success by switching the bar.

After executing the above rows, we will successfully redirect the sendEvent of UIWindow to our own sendEventMySelf implementation, then, redirect the original implementation to the sendEventOriginal method we added to it. In sendEventMySelf, We can first process the message we want, and then call the sendEventOriginal method in line 41 to go to the normal execution process.

You may be confused about this section: "We do not have the sendEventOriginal method in the Custom class ?"

Why is it not reported to be executed normally? Because sendEventMySelf is redirected from the sendEvent of the UIWindow, the self in this method represents the instance of the UIWindow at runtime, instead of the instance of TestHookObject. Adding sendEventOriginal is the instance method we add to UIWindow during runtime, so it can be called normally. Of course, it is also possible to directly call this method through the following method, but the compiler will prompt a warning (the compiler is not so intelligent), so we adopt the performSelector call method.

[self sendEventOriginal:event];

The above is the implementation of the Hook. We only need to let the TestHookObject class execute an initial operation. After the execution, we can. The sendEvent message of UIWindow will be hooked to our sendEventMySelf.

The following is the call code:

 

Install Hook

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];    // Override point for customization after application launch.    self.viewController = [[[TestHookViewController alloc] initWithNibName:@"TestHookViewController" bundle:nil] autorelease];    self.window.rootViewController = self.viewController;    [self.window makeKeyAndVisible];            //hook UIWindow‘s SendEvent method    TestHookObject *hookSendEvent = [[TestHookObject alloc] init];    [hookSendEvent release];        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];    btn.center = CGPointMake(160, 240);    btn.backgroundColor = [UIColor redColor];    [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventAllEvents];    [self.window addSubview:btn];    [btn release];        return YES;}

 

In the code, we also add a button to verify whether the message is transmitted normally after the hook is complete. It is verified that the Message flow is completely normal.

I wrote my first blog in 2013. I hope you will like it !!!

 

Note: you are welcome to reprint it. Please indicate the source for reprinting!

 

Reference: Objective-C Runtime source code

Objective-C Runtime Reference

One piece-Maple Leaf

February 28, 2013

  

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.