What does __forwarding__ in the stack trace mean? - objective-c

(gdb) bt
#0 0x302ac924 in ___TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION___ ()
#1 0x92077e3b in objc_exception_throw ()
#2 0x302d6ffb in -[NSObject doesNotRecognizeSelector:] ()
#3 0x3026e056 in ___forwarding___ ()
#4 0x3024a0a2 in __forwarding_prep_0___ ()
#5 0x00004ae9 in -[GameObject doesTouch:] (self=0xe893a0, _cmd=0x643ee, obj=0xe82e20) at /Users/aaa/Desktop/CPT/Game/Classes/GameObject.m:220
#6 0x00006e05 in -[StaticGrid checkTouchNearest:] (self=0xe82f20, _cmd=0x64ec3, obj=0xe893a0) at /Users/aaa/Desktop/CPT/Game/Classes/StaticGrid.m:62
#7 0x0000a393 in -[EAGLView touchesBegan:withEvent:] (self=0xe8dad0, _cmd=0x3199fa3c, touches=0x632c0b0, event=0xe14590) at /Users/aaa/Desktop/CPT/Game/Classes/EAGLView.m:459
#8 0x30910f33 in -[UIWindow _sendTouchesForEvent:] ()
#9 0x308faecb in -[UIApplication sendEvent:] ()
#10 0x309013e1 in _UIApplicationHandleEvent ()
#11 0x32046375 in PurpleEventCallback ()
#12 0x30245560 in CFRunLoopRunSpecific ()
#13 0x30244628 in CFRunLoopRunInMode ()
#14 0x32044c31 in GSEventRunModal ()
#15 0x32044cf6 in GSEventRun ()
#16 0x309021ee in UIApplicationMain ()
...
Currently I have a rare occuring error that I do not know the cause yet. I am not sure where to look at, so what I want to ask is what do the first five lines (#0 to #4) mean? I know that it claims that there are some errors, but what are those things like "___forwarding___"?
If you have some knowledge in this, please help. Thank you very much.

The forwarding stuff is used for uhm… forwarding messages. Each object can easily forward the messages it receives to some other objects, see the excellent tutorial by Scott Stevenson. When your GameObject receives a message it does not understand, it tries to forward it. If there is no forwarding implemented, the doesNotRecognizeSelector method is called and you get the exception.
Detailed description can be found in the Apple documentation for the NSObject class:
When an object is sent a message for
which it has no corresponding method,
the runtime system gives the receiver
an opportunity to delegate the message
to another receiver. It delegates the
message by creating an NSInvocation
object representing the message and
sending the receiver a
forwardInvocation: message containing
this NSInvocation object as the
argument. The receiver’s
forwardInvocation: method can then
choose to forward the message to
another object.
(…)
NSObject’s implementation of
forwardInvocation: simply invokes the
doesNotRecognizeSelector: method; it
doesn’t forward any messages. Thus, if
you choose not to implement
forwardInvocation:, sending
unrecognized messages to objects will
raise exceptions.
As for your error, it seems that the GameObject gets sent some message it does not understand. This can be a simple typo or something more subtle like memory management error, you’d have to give us more information.

First thing I would check is whether GameObject has a -doesTouch: or +doesTouch: method. I am not sure what __forwarding... is. What error message do you see in the console log?

Related

NSXMLParser I implemented with Swift works on iOS 8 but not on 7.1

Long story short, I was pulling some data from a RSS feed and everything was working good. Well, untill I decided to test it on the iOS 7.1 simulator. It crashed right away.
Here is the XML Parser I created in the ViewDidLoad:
var parser = NSXMLParser()
var url: NSURL = NSURL.URLWithString("http://exampleURLforthisPost.com/?feed=rss2")
parser = NSXMLParser (contentsOfURL: url)
parser.delegate = self
parser.shouldProcessNamespaces = false
parser.shouldReportNamespacePrefixes = false
parser.shouldResolveExternalEntities = false
parser.parse()
It works fine with iOS 8 but when I run it with iOS 7.1, "EXC_BAD_ACCESS" error designated on the "parser = NSXMLParser (contentsOfURL: url)" line. Is there something different I should designate when running iOS 7.1?
Thanks for any assistance!
I'm getting the same problem, under ios8. However, I have a stack trace;
#0 0x000000010930b87c in CFStringCreateCopy ()
#1 0x000000010ae753d4 in Foundation._convertNSStringToString (ObjectiveC.NSString) -> Swift.String ()
#2 0x0000000108a3fffb in #objc Fuel_Locator.FuelWatchReader.parser (Fuel_Locator.FuelWatchReader)(ObjectiveC.NSXMLParser, didEndElement : Swift.String, namespaceURI : Swift.String, qualifiedName : Swift.String) -> () ()
#3 0x0000000108d2c6ad in _endElementNs ()
#4 0x0000000108b1dd96 in xmlParseEndTag2 ()
#5 0x0000000108b20424 in xmlParseTryOrFinish ()
#6 0x0000000108b1f4b0 in xmlParseChunk ()
#7 0x0000000108d299be in -[NSXMLParser parseData:] ()
#8 0x0000000108d29c1f in -[NSXMLParser parseData:] ()
#9 0x0000000108d29d7a in -[NSXMLParser parseFromStream] ()
This result is not good, as it indicates that the problem is occurring when the parser attempts to make a swift copy of a NSString that it has read from the XML. BTW, this only happens when the didEndElement method is about to be called in the delegate. If the method is not present, then error don't happen… but that is hardly useful.
try
var parser : NSXMLParser! = NSXMLParser(contentsOfURL: url)
It looks like NSXMLParser(contentsOfURL: url) may return nil in error case (e.g. invalid URL), so you need to assign it to an optional value to avoid unwrap nil value.

NSProxy pretending to be Class doesn't handle respondsToSelector in 64-bit runtime

In OCMockito, test doubles are implemented with NSProxy. A double standing in for an instance implements -respondsToSelector: as follows:
- (BOOL)respondsToSelector:(SEL)aSelector {
return [_mockedClass instancesRespondToSelector:aSelector];
}
But a double standing in for a class implements -respondsToSelector: like this:
- (BOOL)respondsToSelector:(SEL)aSelector {
return [_mockedClass respondsToSelector:aSelector];
}
This all works in the 32-bit runtime. For example, if _mockedClass is [NSString class], the proxy correctly answers that it responds to the selector +pathWithComponents:
But in the 64-bit runtime, it crashes:
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: EXC_I386_GPFLT
Application Specific Information:
objc[1868]: GC: forcing GC OFF because OBJC_DISABLE_GC is set
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 libobjc.A.dylib 0x00007fff95cbffc6 cache_getImp + 6
1 libobjc.A.dylib 0x00007fff95ccd1dc lookUpImpOrForward + 50
2 libobjc.A.dylib 0x00007fff95ccd198 lookUpImpOrNil + 20
3 libobjc.A.dylib 0x00007fff95cc218a class_respondsToSelector + 37
4 com.apple.CoreFoundation 0x00007fff91c131ad ___forwarding___ + 429
5 com.apple.CoreFoundation 0x00007fff91c12f78 _CF_forwarding_prep_0 + 120
6 org.mockito.OCMockitoTests 0x000000010451a55b -[StubClassTest testStubbedMethod_ShouldReturnGivenObject] + 107 (StubClassTest.m:48)
Note that it's calling class_respondsToSelector(…). I suspect that I'm being bitten by an optimization made to the runtime. What can I do to fix this?
it's a bit long answer, so bear with me. I ran a simple code just to verify the behavior:
Class mock = mockClass([NSProcessInfo class]);
[mock processInfo];
[verify(mock) processInfo];
Indeed It does crash with bad pointer exception. Replacing first line with
id mock = mockClass([NSProcessInfo class]);
works as expected. I figured that it might be worth to look at the code after ARC. Those snippets are a bit to long, so here are the gists: Class-based test, id-based test
As you can see, when you declare variable of type Class there is an extra release. My guess is that since classes are registered for the entire runtime duration (unless removed using runtime api) it's ok to have Class variable as __unsafe_unretained.
To summarize, you have two possible solutions:
#implementation StubClassTest
{
__strong Class mockClass;
}
or
#implementation StubClassTest
{
id mockClass;
}
seem to fix the issue for me.
Update
As a special case, if the object’s base type is Class (possibly protocol-qualified), the type is adjusted to have __unsafe_unretained qualification instead.
From http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects

-[CFRunLoopTimer release]: message sent to deallocated instance 0x62398f80

I have googled for several hours and read quite lots of message sent to deallocated instance posts, and tried methods suggested in those posts, but I still can't spot the bug that causes the crash.
I have tried enabling NSZombieEnabled, MallocStackLogging, MallocStackLoggingNoCompact and got this line:
*** -[CFRunLoopTimer release]: message sent to deallocated instance 0x62398f80
But in my code, I didn't use a CFRunLoopTimer or NSTimer.
and with info malloc, I got the following output:
[Switching to process 97238 thread 0x11903]
sharedlibrary apply-load-rules all
mygame(97238,0xb01cd000) malloc: recording malloc stacks to disk using standard recorder
(gdb) info malloc 0x62398f80
Alloc: Block address: 0x62398f80 length: 128
Stack - pthread: 0xac0422c0 number of frames: 41
0: 0xe9d22 in GMmalloc_zone_malloc_internal
1: 0xe9ebb in GMmalloc_zone_malloc
2: 0x142ba88 in __CFAllocatorSystemAllocate
3: 0x142ba63 in CFAllocatorAllocate
4: 0x142b8de in _CFRuntimeCreateInstance
5: 0x147c1c5 in CFRunLoopTimerCreate
6: 0x32bb831 in _ZN7WebCore22setSharedTimerFireTimeEd
7: 0x338dd4b in _ZN7WebCore21MainThreadSharedTimer11setFireTimeEd
8: 0x338daf3 in _ZN7WebCore12ThreadTimers17updateSharedTimerEv
9: 0x3397781 in _ZN7WebCore9TimerBase15setNextFireTimeEd
10: 0x339786a in _ZN7WebCore9TimerBase5startEdd
11: 0x2be78be in _ZN7WebCore5Frame9keepAliveEv
12: 0x2e86312 in _ZN7WebCore15JSDOMWindowBase10globalExecEv
13: 0x2ea699a in _ZN7WebCore15JSEventListener11handleEventEPNS_22ScriptExecutionContextEPNS_5EventE
14: 0x2bc4e02 in _ZN7WebCore11EventTarget18fireEventListenersEPNS_5EventEPNS_15EventTargetDataERN3WTF6VectorINS_23RegisteredEventListenerELm1EEE
15: 0x2bc4f1c in _ZN7WebCore11EventTarget18fireEventListenersEPNS_5EventE
16: 0x2bc46ee in _ZN7WebCore11EventTarget13dispatchEventEN3WTF10PassRefPtrINS_5EventEEE
17: 0x33eb040 in _ZN7WebCore9WebSocket10didConnectEv
18: 0x33eafa4 in _ZThn20_N7WebCore9WebSocket10didConnectEv
19: 0x33ed470 in _ZN7WebCore16WebSocketChannel13processBufferEv
20: 0x33edd18 in _ZN7WebCore16WebSocketChannel14didReceiveDataEPNS_18SocketStreamHandleEPKci
21: 0x32c681b in _ZN7WebCore18SocketStreamHandle18readStreamCallbackEm
22: 0x32c68f8 in _ZN7WebCore18SocketStreamHandle18readStreamCallbackEP14__CFReadStreammPv
23: 0x14c803d in _signalEventSync
24: 0x14c879a in _cfstream_solo_signalEventSync
25: 0x14c7e41 in _CFStreamSignalEvent
26: 0x14c86f7 in CFReadStreamSignalEvent
27: 0x1ca371 in _ZN12SocketStream40dispatchSignalFromSocketCallbackUnlockedEP24SocketStreamSignalHolder
28: 0x126011 in _ZN12SocketStream14socketCallbackEP10__CFSocketmPK8__CFDataPKv
29: 0x125f21 in _ZN12SocketStream22_SocketCallBack_streamEP10__CFSocketmPK8__CFDataPKvPv
30: 0x1495e14 in __CFSocketPerformV0
31: 0x14fb94f in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
32: 0x145eb43 in __CFRunLoopDoSources0
33: 0x145e424 in __CFRunLoopRun
34: 0x145dd84 in CFRunLoopRunSpecific
35: 0x145dc9b in CFRunLoopRunInMode
36: 0x1d5c7d8 in GSEventRunModal
37: 0x1d5c88a in GSEventRun
38: 0x39c626 in UIApplicationMain
39: 0x3095 in main at /Users/neevek/workspace/xcode_projects/mygame/mygame/main.m:16
40: 0x2925 in start
EDIT
I am almost desperate, I have spent 2 days on this problem. the only thing I can spot is the CFRunLoopTimer zombie object. I use CocoaHttpServer and NSURLConnection in my code. From somewhere I learnt that NSURLConnection depends on NSRunLoop, so I wonder if it is the NSRunLoop that causes the crash. in my app, both CocoaHTTPServer and NSURLConnection depend on NSRunLoop, of cause they run on different threads.
Please help!
I use Instruments to find the zombie object, and took 2 screenshots of the crash report:
And the [HttpServer bonjourThread] method:
I've fixed this, just call a dummy stringByEvaluatingJavaScriptFromString on the UIWebView before invoking a method on the context. I believe the reason this works is the call into javascript is done on the Web Thread and it uses a timer to receive the reply back to the main thread, when calling invoke this timer wasn't created so when the reply comes back from the Web Thread it crashes trying to release a timer that was never created in the first place. By using the proper API stringByEvaluatingJavaScriptFromString in insures the timer is created and then the invokeMethod can make use of the same timer.
JSContext* context = [webView valueForKeyPath:#"documentView.webView.mainFrame.javaScriptContext"];
JSValue* value = context[#"Colors"];
// timer CFRelease crash fix
[webView stringByEvaluatingJavaScriptFromString:nil];
[value invokeMethod:#"update" withArguments:#[objectID,modifier]];
The only solution according to me is to search your code for NSTimer- Any 3rd part libraries can use it.Once the NSTimer is found just add a retain statement at the end of the NSTimer initialization,
Like this:
idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime
target:self
selector:#selector(idleTimerExceeded)
userInfo:nil
repeats:NO]retain];

Objective-C: How to pass a tree of objects to a remote distributed object?

I have a class called Node which contains a set of parameters and an NSMutableArray called subNodes. One process creates one Node object as a root of the tree and uses the subNodes arrays to create a large tree of Nodes. This entire tree should be passed to another process, so I set up an NSConnection:
Node *tree;
// ...create Node-Tree...
NSConnection *otherProcess = [NSConnection connectionWithRegisteredName:#"MyApp"
host:nil];
MyObj *remoteObj = (MyObj*) [[otherProcess rootProxy] retain];
[remoteObj setNodeTree:tree];
The communication itself works, the remote method 'setNodeTree', which expects the root-Node will be called. However, the transfer of the tree doesn't work. I had to implement a copyWithZone method for the Node class:
-(id)copyWithZone:(NSZone*)zone
{
Node *nodeCopy = [[[self class] allocWithZone:zone] init];
[nodeCopy setSize:[self size]];
[nodeCopy setSubnodes:[[self subnodes] copyWithZone:zone]];
return nodeCopy;
}
But the client terminates with the following exception:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: '[NOTE: this exception originated in the server.]
Cannot create BOOL from object <Node: 0x10018f640> of class NSDistantObject'
*** Call stack at first throw:
(
0 CoreFoundation 0x00007fff81f687b4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x00007fff823a80f3 objc_exception_throw + 45
2 Foundation 0x00007fff8831e0c3 -[NSConnection sendInvocation:internal:] + 4304
3 CoreFoundation 0x00007fff81f3a98c ___forwarding___ + 860
4 CoreFoundation 0x00007fff81f36a68 _CF_forwarding_prep_0 + 232
5 MyProgram 0x00000001000015d5 main + 260
6 MyProgram 0x0000000100000fa8 start + 52
7 ??? 0x0000000000000002 0x0 + 2
)
terminate called after throwing an instance of 'NSException'
Any ideas what went wrong here? Apparently a BOOL variable is expected somewhere, but the Node doesn't contain any and there is no method used which expects or returns a BOOL.
Two alternatives are possible:
serialization and deserialization of whole tree,
shared memory between processes.
For performance and code readability, my preference goes to shared memory. A reference start is shmget(2) manual page.

appendBezierPathWithGlyph fails in [NSBezierPath currentPoint]

Has anybody an idea in which case this can happen?
GDB output:
0 .. 8: kill, abort, objc_exception_throw etc.
9: 0x00007fff87ea21f4 in +[NSException raise:format:] ()
10: 0x00007fff8694e9e2 in -[NSBezierPath currentPoint] ()
11: 0x00007fff869e3b3b in __NSAppendBezierPathWithGlyphs ()
12: 0x00007fff869e5baf in -[NSBezierPath appendBezierPathWithGlyphs:count:inFont:]()
13: 0x00007fff869e2e2d in -[NSBezierPath appendBezierPathWithGlyph:inFont:] ()
objc_exception_throw is the function to throw an exception. There are two things to look at in this circumstance: The Console log, which will identify the exception itself, and the call stack leading to objc_exception_throw.
In this case, I can guess what the exception was from the call stack alone: currentPoint will throw if the path has no current point. This is backed up by the documentation for the appendBezierPathWithGlyphs:count:inFont: method (as well as for the method you're directly calling):
You must set the path's current point (using the moveToPoint: method or through the creation of a preceding line or curve segment) before you invoke this method.