Trace Objective-C method calls by class or instance

Related tags

Tools Xtrace
Overview

Icon Xtrace

Note: This project has been superseeded by the more rigourous SwiftTrace.

Trace Objective-C method calls by class or instance

Xtrace is a header Xtrace.h and a C++ implementation file Xtrace.mm that allows you to intercept all method calls to instances of a class or a particular instance giving you output such as this:

   [<UILabel 0x8d4f170> setCenter:{240, 160}] v16@0:4{CGPoint=ff}8
	[<UILabel 0x8d4f170> actionForLayer:<CALayer 0x8d69410> forKey:<__NSCFString 0x8a535e0>] @16@0:4@8@12
	 [<UILabel 0x8d4f170> _shouldAnimatePropertyWithKey:<__NSCFString 0x8a535e0>] c12@0:4@8
	 -> 1 (_shouldAnimatePropertyWithKey:)
	-> <NSNull 0x194d068> (actionForLayer:forKey:)
  [<UILabel 0x8d4f170> window] @8@0:4
  -> <UIWindow 0x8a69920> (window)
  [<UILabel 0x8d4f170> _isAncestorOfFirstResponder] c8@0:4
  -> 0 (_isAncestorOfFirstResponder)
 [<UILabel 0x8d4f170> layoutSublayersOfLayer:<CALayer 0x8d69410>] v12@0:4@8
  [<UILabel 0x8d4f170> _viewControllerToNotifyOnLayoutSubviews] @8@0:4
   [<UILabel 0x8d4f170> _viewDelegate] @8@0:4
   -> <nil 0x0> (_viewDelegate)

To use, add Xtrace.{h,mm} to your project and add an import of Xtrace.h to your project's ".pch" file so you can access its methods from anywhere in your project. There is a simple category based shortcut interface to start tracing:

	[MyClass xtrace]; // to trace all calls to instances of a class
	// this will intercept all methods of any superclasses as well
    // but only for instances of the class that has been traced (v2.1)
	
	[instance xtrace]; // to trace all calls to a particular instance.
	// multiple instances can by traced, use "notrace" to stop tracing
    // instance tracing takes precedence over class based filtering.

    [Xtrace traceBundleContainingClass:myClass];
    // trace your entire app's classes or those of an embedded framework
    
    [Xtrace traceClassPattern:@"^UI" excluding:nil]; // trace all of UIkit

If you have the XcodeColors plugin installed you can now color traces by selector, class or group of classes:

Icon

As an alternative to building Xtrace into your project, Xtrace is now included in the "code injection" plugin from injectionforxcode.com. Once you have injected, all xtrace methods are available for you to use in lldb.

(lldb) p [UITableView xtrace]

// dump pseudo-header for class
(lldb) p [UITableView xdump]
@interface UITableView : UIScrollView {
    id<UITableViewDataSource> _dataSource; // @"<UITableViewDataSource>"
    UITableViewRowData * _rowData; // @"UITableViewRowData"
    float _rowHeight; // f
    float _sectionHeaderHeight; // f
    float _sectionFooterHeight; // f
    float _estimatedRowHeight; // f
    float _estimatedSectionHeaderHeight; // f
    float _estimatedSectionFooterHeight; // f
    CGRect _visibleBounds; // {CGRect="origin"{CGPoint="x"f"y"f}"size"{CGSize="width"f"height"f}}
...

The example project, originally called "Xray" will show you how to use the Xtrace module to get up and running. Your milage will vary though the source should build and work for 32 bit configurations on an iOS device or 64 bit OS X applications or the simulator. The starting point is the XRAppDelegate.m class. The XRDetailViewController.m then switches to instance viewing of a specific UILabel when the detail view loads.

Display of method arguments is now on by default, but if you have problems:

[Xtrace showArguments:NO];

You can display the calling function on entry by setting:

[Xtrace showCaller:YES];

You should also be able to switch to log the "description" of all values using:

[Xtrace describeValues:YES];

Other features are a method name filtering regular expression. These filters are applied as the class is "swizzled" when you request tracing.

[Xtrace includeMethods:@"a|regular|expression"];
[Xtrace excludeMethods:@"WithObjects:$"]; // varargs methods don't work
[Xtrace excludeTypes:@"CGRect|CGSize"]; // stack frame problems on 64 bits
[Xtrace excludeTypes:nil]; // reset filter after class is set up.

Classes can also be excluded (again before other classes are traced) by calling:

[UIView notrace]; // or alternatively..
[Xtrace dontTrace:[UIView class]];

A rudimentary profiling interface is also available:

[Xtrace dumpProfile:100 dp:6]; // top 100 elapsed time to 6 decimal places

1.318244/2    [UIApplication sendAction:to:from:forEvent:]
0.725028/2    [UIWindow sendEvent:]
0.706975/2    [UIWindow _sendTouchesForEvent:]
0.701802/1    [UIControl touchesEnded:withEvent:]
0.699627/2    [UIControl _sendActionsForEvents:withEvent:]
0.659325/1    [UIControl sendAction:to:forEvent:]
0.659292/1    [UIApplication sendAction:toTarget:fromSender:forEvent:]
0.659204/1    [UIBarButtonItem _sendAction:withEvent:]
0.659082/1    [UIViewController _toggleEditing:]
0.659071/1    [UITableViewController setEditing:animated:]
0.593577/53   [CALayer layoutSublayers]
0.592025/53   [UIView layoutSublayersOfLayer:]
...

Aspect oriented features

Finally, callbacks can also be registered on a delegate to be called before or after any method is called:

[Xtrace setDelegate:delegate]; // delegate must not be traced itself
[Xtrace forClass:[UILabel class] after:@selector(setText:) callback:@selector(label:setText:)];

// void method signature for UILabel
- (void)setText:(NSString *)text;

// "before" and "after" callback implementation in delegate
- (void)label:(id)receiver setText:(NSString *)text {
    ...
}

Callbacks for specific methods can be used independently of full Class or instance tracing. "after" callbacks for methods that return a value can replace the value returned to the caller something like a variation on "aspect oriented programming".

// non-void method signature in class "AClass"
- (NSString *)appendString:(NSString *)string;

// code to inject "after" method callback
[Xtrace forClass:[AClass class] after:@selector(appendString:) callback:@selector(out:object:appendString:)];

// "after" callback implementation in delegate
- (NSString *)out:(NSString *)originalReturnValue object:(id)receiver appendString:(NSString *)string {
    ...
    return newReturnValue; // could be originalReturnValue
}

The callback selector names are arbitrary. It's the order and type of arguments that is critical. Expect some trouble passing structs on 64 bit builds. The signature for intercepting a "getter" is a little contrived:

// setup callback
[Xtrace forClass:[UILabel class] after:@selector(text) callback:@selector(out:labelText:)];

// implementation of callback
- (NSString *)out:(NSString *)text labelText:(UILabel *)label {
    ...
    return text;
}

There is also a block based api for callbacks which can be called at any time:

[Xtrace forClass:[UIView class] before:@selector(sizeToFit) callbackBlock:^( UILabel *label ) {
    NSLog( @"%@ sizeToFit before: %@", label, NSStringFromCGRect(label.frame) );
}];
[Xtrace forClass:[UIView class] after:@selector(sizeToFit) callbackBlock:^( UILabel *label ) {
    NSLog( @"%@ sizeToFit after: %@", label, NSStringFromCGRect(label.frame) );
}];

What works:

Icon

Reliability is now quite good for 32 bit builds considering.. I've had to introduce a method exclusion blacklist of a few methods causing problems. On 64 bit OS X you can expect some stack frame complications for methods with "struct" argument or return types - in particular for arguments to callbacks to the delegate. Xtrace does not currently work on the ARM64 abi - rebuild for 32 bits.

The ordering of calls to the api is: 1) Any class exclusions, 2) any method selector filter then 3) Class tracing or instance tracing and 4) any callbacks. That's about it. If you encounter problems drop me a line on xtrace (at) johnholdsworth.com. The developer of Xtrace and the "Injection Plugin" is available for Cocoa/iOS development work in the London area.

Announcements of major commits to the repo will be made on twitter @Injection4Xcode.

As ever:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • get self object

    get self object

    Hello,

    Thanks for the XTrace projet, it is awesome !!!

    Simply I would like to know how could I get the self object from which the method is intercepted. Here is an example : I would like to intercept the before of any UIViewController subclass, so I added this code : [Xtrace forClass:[self class] before:@selector(viewWillAppear:) callback:@selector(beforeViewWillAppear:sender:)];

    When I go to my interception method and I would like to display sender, It says that this object is always (null) : +(void)beforeViewWillAppear:(BOOL)animated sender:(id)sender { NSLog(@"%@",sender); }

    How could I pass the sender object to my interceptions methods in my delegate ?

    Thanks in advance.

    opened by iamredeye 6
  • Add Podspec (address #9)

    Add Podspec (address #9)

    This adds valid podspec.

    Couple of notes:

    • Podspec must have LICENSE. It is not possible to have Podspec without LICENSE. I created LICENSE file and copied there license text from Xtrace.h. It is BSD 2-Clause, correct?
    • Podspec must point to some specific tag. Tag must contain the same version number as s.version. So please set a tag on the latest commit like v4.2 and modify Xtrace.podspec so that its s.source points to this new tagged commit.
    • Now Xtrace.podspec points to April's v4.1 which has Xtrace files within Xray directory. When you create new tagged commit be sure to remove Xray for the s.source_files = ... so it would be:
    s.source_files = 'Xtrace.h', 'Xtrace.mm'
    

    After you have new tagged commit it is time to push your podspec to trunk. It is very easy to accomplish, just follow these simple tutorials - it becomes very easy once you get it for the first time:

    http://useyourloaf.com/blog/2014/08/13/creating-a-cocoapod.html http://guides.cocoapods.org/making/getting-setup-with-trunk.html

    I am ready to help. Let me know if it worked for you.

    opened by stanislaw 4
  • Feature request: add tracing of outer context (callers within call stack)

    Feature request: add tracing of outer context (callers within call stack)

    Hello, @johnno1962!

    First of all thanks for Xtrace - it is really great to call -xtrace on arbitrary objects and see what's going on!

    For last two days I've been investigating some bugs related either to RestKit or to CoreData. I tried to use xtrace on classes of my interest and found that xtrace has a lack of support of caller tracing.

    What I mean is that for example when I call -xtrace on some object I also want to see the outer context: who calls this method, who calls caller and so on... I hope this will be easy thing to add since [NSThread callStackSymbols] can provide this information.

    What would also be great is to have an option to configure stack depth of what Xtrace should trace. For example if this option is set to 1 then I see only the last caller of my object's method. If I set more I will see more callers within call stack.

    I hope my request is clear. Please let me know what you think.


    P.S. You realized one of the projects I dreamed about writing a such myself :) now it's great to just have such intelligent implementation that you did.

    Thanks again for Xtrace!

    opened by stanislaw 4
  • Intercept BlockHandler

    Intercept BlockHandler

    Hi,

    I can't figure out how to intercept a CompletionHandler Example For This Method :

    • (void)sendAsynchronousRequest:(NSURLRequest_) request queue:(NSOperationQueue_) queue completionHandler:(void (^)(NSURLResponse_, NSData_, NSError*))handler

    I would like to intercept the CompletionHandler and get NSURLResponse, NSData and NSError values after its execution.

    I have tried to do the traditional way in Xtrace but I have got Bad_Access exception

    Thanks

    opened by iamredeye 4
  • Adding Xtrace.mm to Xcode plugin stops plugin loading

    Adding Xtrace.mm to Xcode plugin stops plugin loading

    Not really sure if this is an issue, but thought I'd bounce it off you to see if you have seen it before.

    I have a working Xcode plugin but when I drag Xtrace.mm and Xtrace.h into the plugin project, for some reason, after an Xcode restart the plugin doesn't get loaded.

    Note that the problem occurs even if I don't actually have any calls to Xtrace code in my plugin code. If, however, I uncheck the Target Membership for Xtrace.mm (ie. stop it being compiled) the plugin will load successfully again.

    There is zero errors emitted in /var/log/system.log, so I'm a bit stumped. Just curious if you have seen anything like this before?

    opened by edwardaux 4
  • How to profile only the required functions?

    How to profile only the required functions?

    I know the dumpProfile function which lists the top 100 (depends on the count you give) functions that took most elapsed time.

    Can I specify the exact functions to which the profiling has to run?

    opened by winster 2
  • Xtracing Google Chrome / Chromium

    Xtracing Google Chrome / Chromium

    Xtracing Google Chrome / Chromium doesn't seem to work. I'm attaching to main process using LLDB, loading Xtrace.framework, and trying to xtrace on something, and it immediately fails with an exception.

    (lldb) p (BOOL)[[NSBundle bundleWithPath:@"/Library/Frameworks/Xtrace.framework"] load]
    (BOOL) $0 = YES
    (lldb) p (id)[[NSObject alloc] init]
    (id) $1 = 0x000062000001df30
    (lldb) p (void)[$1 xtrace]
    error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x2aa983abec0).
    The process has been returned to the state before expression evaluation.
    

    Tried doing the same in a custom Chromium build, and it reports this error:

    [6197:1815:0225/220057:FATAL:chrome_browser_application_mac.mm(148)] Someone is trying to raise an exception!  NSInvalidArgumentException reason NSGetSizeAndAlignment(): unsupported type encoding spec 'b' at 'b1b31}}8' in '{?=ddd{?=b1b31}}8'
    

    What's the best way to troubleshoot this?

    opened by mblsha 2
  • Arm64 support

    Arm64 support

    Hello,

    I tried to compile the xtrace library classes for an app with arm64 architecture but no success. I had seen in the code this condition :

    ifdef arm64

    // make this into #warning to switch between the simulator and a device more easily //#error Xtrace will not work on an ARM64 build. Rebuild for $(ARCHS_STANDARD_32_BIT).

    I commented it but have faced SIGABT exceptions with arm64 devices.

    Is there a solution for this issue please ?

    Thanks

    opened by iamredeye 2
  • Double Pointer arguments

    Double Pointer arguments

    Hello Johno1962, Bug thanks for your help last time.

    I have tried to intercept class method to get pointers to the response and error objets : NSURLResponse * response = nil; NSError * error = nil; NSLog(@"before sendSynchronousRequest"); NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

    As you see reponse and error are passed as reference variables to the method. I would like to get a pointer on them in the method "static void returning" so I can explore the values on these objects. I have tried to call "formatValue" method and explore the formatting that you have done to convert arguments but I can't really convert the argument object to NSURLResponse** object or NSError** object.

    Thanks a lot, sorry for bothering.

    opened by iamredeye 1
  • Marked int as unsigned to prevent compiler warning.

    Marked int as unsigned to prevent compiler warning.

    It should be ok to use an unsigned int here cause it's a loop index based on an NSArray. Personally I would use NSUInteger, this will help when compiling for ARM64. But to stay in line with the rest of the XTrace code I opted not to do so.

    opened by jeroenleenarts 0
  • awesome tool | made a few changes to get it to work for me

    awesome tool | made a few changes to get it to work for me

    1. change

    Extended array of methods best not to touch. Without that, xtrace causes an exception after a while: 'expection' being: _os_unfair_lock_recursive_abort

    I added retainWeakReference, _tryRetain, autorelease, isEqual:, hash and I added back the dealloc related methods


    see:

                else if ( name[0] == '.' ||
                         [nameStr isEqualToString:@"description"] || [nameStr hasPrefix:@"_description"] ||
                         [nameStr isEqualToString:@"isEqual:"] || [nameStr hasPrefix:@"hash"] ||
                         [nameStr isEqualToString:@"retainWeakReference"] || [nameStr isEqualToString:@"_tryRetain"] || [nameStr isEqualToString:@"retain"] || [nameStr isEqualToString:@"release"] || [nameStr isEqualToString:@"autorelease"] ||
                         [nameStr isEqualToString:@"_isDeallocating"] || [nameStr isEqualToString:@"dealloc"] || [nameStr hasPrefix:@"_dealloc"] )
                    ; // best avoided
    

    2. change

    Made formatValue function not call isKindOfClass on proxy objects to avoid a crash when proxies implement isKindOfClass

    other

    • added #pragma clang diagnostic ignored "-Wignored-attributes" so the NS_RETAINS macro on the templated c function works in all cases
    • had to remove the last pop pragma to make it compile
    opened by Daij-Djan 2
Owner
John Holdsworth
Add a bio
John Holdsworth
An Xcode Plugin to convert Objective-C to Swift

XCSwiftr Convert Objective-C code into Swift from within Xcode. This plugin uses the Java applet of objc2swift to do the conversion. Noticed that the

Ignacio Romero Zurbuchen 338 Nov 29, 2022
Trace Swift and Objective-C method invocations

SwiftTrace Trace Swift and Objective-C method invocations of non-final classes in an app bundle or framework. Think Xtrace but for Swift and Objective

John Holdsworth 605 Dec 27, 2022
JSPatch bridge Objective-C and Javascript using the Objective-C runtime. You can call any Objective-C class and method in JavaScript by just including a small engine. JSPatch is generally used to hotfix iOS App.

JSPatch 中文介绍 | 文档 | JSPatch平台 请大家不要自行接入 JSPatch,统一接入 JSPatch 平台,让热修复在一个安全和可控的环境下使用。原因详见 这里 JSPatch bridges Objective-C and JavaScript using the Object

bang 11.4k Jan 1, 2023
🎨 View instance initializing sugar for Swift & UIKit

?? View instance initializing sugar for Swift & UIKit

Yongjun Lee 11 Dec 1, 2022
A fast, convenient and nonintrusive conversion framework between JSON and model. Your model class doesn't need to extend any base class. You don't need to modify any model file.

MJExtension A fast, convenient and nonintrusive conversion framework between JSON and model. 转换速度快、使用简单方便的字典转模型框架 ?? ✍??Release Notes: more details Co

M了个J 8.5k Jan 3, 2023
A simple class that wraps the process of saving or loading a struct or class into a single file

EZFile This is a simple class that wraps the process of saving or loading a stru

null 7 May 16, 2022
Xcode Plugin helps you find missing methods in your class header, protocols, and super class, also makes fast inserting.

FastStub-Xcode Life is short, why waste it on meaningless typing? What is it? A code generating feature borrowed from Android Studio. FastStub automat

mrpeak 509 Jun 29, 2022
Pretty GCD calls and easier code execution.

Threader Pretty GCD calls and easier code execution. Overview Threader makes GCD calls easy to read & write. It also provides a simple way to execute

Mitch Treece 35 Sep 9, 2022
Sample app to open parking lot gates by phone calls

DouzePointCinq - Test app Sample iOS app to open parking lot gates by phone calls. Screenshots (dark & light modes) How to use Clone the project git c

Anthony You 1 Oct 29, 2021
An iOS Safari extension that redirects MetaMask calls to Rainbow.

Rainbow Bridge (iOS App) An iOS Safari extension that redirects MetaMask calls to Rainbow. Since I can't figure out how to get the Rainbow source runn

Miguel Piedrafita 10 Aug 20, 2022
Make API Calls using SwiftUI

SwiftUIApICall Make API Calls using SwiftUI This is a simple app for maing API C

Abdulaziz M. Ghaleb 0 Dec 18, 2021
Project shows how to unit test asynchronous API calls in Swift using Mocking without using any 3rd party software

UnitTestingNetworkCalls-Swift Project shows how to unit test asynchronous API ca

Gary M 0 May 6, 2022
Lightweight lib around NSURLSession to ease HTTP calls

AeroGear iOS HTTP Thin layer to take care of your http requests working with NSURLSession. Project Info License: Apache License, Version 2.0 Build: Co

AeroGear 44 Sep 27, 2022
iOS Tweak to redirect Discord API calls to a Fosscord server.

FosscordTweak iOS Tweak to redirect Discord API calls to a Fosscord server. Installation Manual Download .deb file from release and install on jailbro

null 8 May 16, 2022
A command line tool that calls your Xcode Test Plan and creates screenshots of your app automatically.

ShotPlan (WIP) A command line tool that calls your Xcode Test Plan and creates screenshots of your app automatically. ShotPlan will also take care of

Devran Cosmo Uenal 6 Jul 21, 2022
Poi - You can use tinder UI like tableview method

Poi You can use tinder UI like tableview method Installation Manual Installation Use this command git clone [email protected]:HideakiTouhara/Poi.git Imp

null 65 Nov 7, 2022
Elegant Apply Style by Swift Method Chain.🌙

ApplyStyleKit ApplyStyleKit is a library that applies styles to UIKit using Swifty Method Chain. Normally, when applying styles to UIView etc.,it is n

shindyu 203 Nov 22, 2022
IMBeeHive is a kind of modular programming method

概述 IMBeeHive是用于iOS的App模块化编程的框架实现方案,本项目主要借鉴了阿里巴巴BeeHive,在此基础上通过逆向了一些大厂的APP使得功能更加强大完善。同时现在也在寻找一起开发这个框架的开发者,如果您对此感兴趣,请联系我的微信:alvinkk01. 背景 随着公司业务的不断发展,项目

null 6 Dec 14, 2021
A handy collection of Swift method and Tools to build project faster and more efficient.

SwifterKnife is a collection of Swift extension method and some tools that often use in develop project, with them you might build project faster and

李阳 4 Dec 29, 2022