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.
Related
I am using Jacoco for unit test code coverage. Jacoco's generated report shows that few branches are missed in my Kotlin code. I noticed that the coroutine code and the code after it, is not properly covered according to Jacoco. I am not sure if it is because of coroutine or something else.
While running my unit test with the IntelliJ Code Coverage my Kotlin class shows 100% coverage.
I don't know why Jacoco is showing lesser coverage. I have written my Unit Tests using Spock (Groovy).
Please refer the below images:
Missed Branches:
Original Code:
Similarly to "Why is JaCoCo not covering my String switch statements?" :
JaCoCo performs analysis of bytecode, not source code. Compilation of Example.kt with kotlinc 1.3.10
package example
fun main(args: Array<String>) {
kotlinx.coroutines.runBlocking { // line 4
}
}
results in two files ExampleKt.class and ExampleKt$main$1.class, bytecode of last one (javap -v -p ExampleKt$main$1.class) contains method invokeSuspend(Object)
public final java.lang.Object invokeSuspend(java.lang.Object);
descriptor: (Ljava/lang/Object;)Ljava/lang/Object;
flags: ACC_PUBLIC, ACC_FINAL
Code:
stack=3, locals=4, args_size=2
0: invokestatic #29 // Method kotlin/coroutines/intrinsics/IntrinsicsKt.getCOROUTINE_SUSPENDED:()Ljava/lang/Object;
3: astore_3
4: aload_0
5: getfield #33 // Field label:I
8: tableswitch { // 0 to 0
0: 28
default: 53
}
28: aload_1
29: dup
30: instanceof #35 // class kotlin/Result$Failure
33: ifeq 43
36: checkcast #35 // class kotlin/Result$Failure
39: getfield #39 // Field kotlin/Result$Failure.exception:Ljava/lang/Throwable;
42: athrow
43: pop
44: aload_0
45: getfield #41 // Field p$:Lkotlinx/coroutines/CoroutineScope;
48: astore_2
49: getstatic #47 // Field kotlin/Unit.INSTANCE:Lkotlin/Unit;
52: areturn
53: new #49 // class java/lang/IllegalStateException
56: dup
57: ldc #51 // String call to 'resume' before 'invoke' with coroutine
59: invokespecial #55 // Method java/lang/IllegalStateException."<init>":(Ljava/lang/String;)V
62: athrow
LineNumberTable:
line 4: 3
line 5: 49
which is associated with line 4 of source file and contains branches (ifeq, tableswitch).
While latest as of today JaCoCo version (0.8.2) has filters for various compiler-generated artifacts such as String in switch statement, bytecode that Kotlin compiler generates for coroutines is not filtered. Changelog can be seen at https://www.jacoco.org/jacoco/trunk/doc/changes.html And among others at https://www.jacoco.org/research/index.html there is also presentation about bytecode pattern matching that shows/explains many compiler-generated artifacts.
What you see in IntelliJ IDEA as 100% - is only line coverage, so you are trying to compare two completely different things. As a proof - here is screenshot of IntelliJ IDEA which shows 100% line coverage, but only one branch of if was executed (where args.size >= 0 evaluates to true)
And here is corresponding screenshots of JaCoCo report for execution of the same source file
Going up to the package level you can see 100% line coverage, but 50% branch coverage
And then going down to the class level via the first link ExampleKt.main.new Function2() {...} you can again see that method invokeSuspend(Object) contributes missed branches
Update (29/01/2019)
JaCoCo version 0.8.3 has filter for branches added by the Kotlin compiler for suspending lambdas and functions:
Jacoco version 0.8.3 fixes it, it has been released yesterday January 24th.
Full change-log can be found here: https://github.com/jacoco/jacoco/releases
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
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];
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.
(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?