SPInvocationGrabbing.m 4.15 KB
Newer Older
1 2 3
/*
 Copyright (c) 2011, Joachim Bengtsson
 All rights reserved.
4

5
 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
6

7
 * Neither the name of the organization nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
8

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "SPInvocationGrabbing.h"
#import <execinfo.h>

#pragma mark Invocation grabbing
@interface SPInvocationGrabber ()
@property (readwrite, retain, nonatomic) id object;
@property (readwrite, retain, nonatomic) NSInvocation *invocation;

@end

@implementation SPInvocationGrabber
- (id)initWithObject:(id)obj;
{
25
    return [self initWithObject:obj stacktraceSaving:YES];
26 27 28 29
}

-(id)initWithObject:(id)obj stacktraceSaving:(BOOL)saveStack;
{
30 31 32
    self.object = obj;
    if(saveStack)
        [self saveBacktrace];
33

34
    return self;
35
}
36

37 38
-(void)dealloc;
{
39 40 41 42 43
    free(frameStrings);
    self.object = nil;
    self.invocation = nil;

    [super dealloc];
44 45 46 47 48 49
}
@synthesize invocation = _invocation, object = _object;

@synthesize backgroundAfterForward, onMainAfterForward, waitUntilDone;
- (void)runInBackground;
{
50 51 52 53 54 55 56
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    @try {
        [self invoke];
    }
    @finally {
        [pool drain];
    }
57 58 59 60
}


- (void)forwardInvocation:(NSInvocation *)anInvocation {
61 62 63 64 65 66 67
    [anInvocation retainArguments];
    anInvocation.target = _object;
    self.invocation = anInvocation;

    if(backgroundAfterForward)
        [NSThread detachNewThreadSelector:@selector(runInBackground) toTarget:self withObject:nil];
    else if(onMainAfterForward)
68 69
        [self performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:waitUntilDone];
}
70

71
- (NSMethodSignature *)methodSignatureForSelector:(SEL)inSelector {
72 73 74 75 76
    NSMethodSignature *signature = [super methodSignatureForSelector:inSelector];
    if (signature == NULL)
        signature = [_object methodSignatureForSelector:inSelector];

    return signature;
77 78 79 80
}

- (void)invoke;
{
81 82 83 84 85 86 87 88 89 90 91 92 93
    @try {
        [_invocation invoke];
    }

    @catch (NSException * e) {
        NSLog(@"SPInvocationGrabber's target raised %@:\n\t%@\nInvocation was originally scheduled at:", e.name, e);
        [self printBacktrace];
        printf("\n");
        [e raise];
    }

    self.invocation = nil;
    self.object = nil;
94 95 96 97
}

-(void)saveBacktrace;
{
98 99 100
    void *backtraceFrames[128];
    frameCount = backtrace(&backtraceFrames[0], 128);
    frameStrings = backtrace_symbols(&backtraceFrames[0], frameCount);
101
}
102

103 104
-(void)printBacktrace;
{
105 106 107 108
    for(int x = 3; x < frameCount; x++) {
        if(frameStrings[x] == NULL) { break; }
        printf("%s\n", frameStrings[x]);
    }
109 110 111 112 113 114
}
@end

@implementation NSObject (SPInvocationGrabbing)
-(id)grab;
{
115
    return [[[SPInvocationGrabber alloc] initWithObject:self] autorelease];
116
}
117

118 119
-(id)invokeAfter:(NSTimeInterval)delta;
{
120 121 122
    id grabber = [self grab];
    [NSTimer scheduledTimerWithTimeInterval:delta target:grabber selector:@selector(invoke) userInfo:nil repeats:NO];
    return grabber;
123
}
124

125 126
- (id)nextRunloop;
{
127
    return [self invokeAfter:0];
128
}
129

130 131 132
-(id)inBackground;
{
    SPInvocationGrabber *grabber = [self grab];
133 134
    grabber.backgroundAfterForward = YES;
    return grabber;
135
}
136

137 138 139
-(id)onMainAsync:(BOOL)async;
{
    SPInvocationGrabber *grabber = [self grab];
140
    grabber.onMainAfterForward = YES;
141
    grabber.waitUntilDone = !async;
142
    return grabber;
143 144 145
}

@end