EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) - objective-c

I really can't figure out why I have this bug.
First of all the debugger stop at machine code
The thread also shows nothing. The program stop at no code actually
So it has something to do with _dispatch_worker_thread
What is that?
Any way how I can debug this? Should I just rollback?

This kind of crash will happen when you are running a (vector)extension which is not supported on your CPU.
For example, in xcode 5 under "project-settings / build-settings / Code Generation, set the
"Enable Additional Vector extensions" to "AVX2". Build your executable.
Now run it on an:
Intel Core i5: it's going to crash (wherever the compiler decided to use avx2) with 'exc_i386_invop subcode=0x0'.
Intel Core i7: it will work.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP) is the by-product of a __builtin_trap() - which is a GCC and clang intrinsic function. On x86 it we get
0x4dfa2: movl %esi, (%esp)
0x4dfa5: movl %edx, 4(%esp)
0x4dfa9: movl %eax, 8(%esp)
0x4dfad: calll 0x110ffa ; symbol stub for: objc_msgSend
0x4dfb2: cmpb $0, %al
0x4dfb4: je 38
-> 0x4dfba: ud2
0x4dfbc: movl -32(%ebp), %eax
The instruction ud2 is the culprit here, and is not handled specially by Xcode.
On ARM we this compiles into trap and results in a trace break-point in XCode. Is this a bug in clang we have here?
Ultimately in the context of the original question, I suspect that the library function that is failing has hit a assertion.

In my case I was adding an observer for contentSize to a UITextView in viewDidLoad and was never removing it. Fixed it by adding it in viewDidAppear and then removing it in viewWillDisappear.
It was so annoying to find out :(
Add observer in viewDidAppear
[self.textViewMessage addObserver:self
forKeyPath:NSStringFromSelector(#selector(contentSize))
options:NSKeyValueObservingOptionNew
context:nil];
Remove observer in viewWillDisappear
[self.textViewMessage removeObserver:self forKeyPath:NSStringFromSelector(#selector(contentSize))];

Related

Crash in [NSWindow orderFrontRegardless] after updating to macOS Mojave

Getting this weird crash after updating to Mojave.
Not doing anything special, just creating an NSWindow and calling orderFrontRegardless
Always worked fine before.
1 libsystem_platform.dylib 0x00007fff6610ab5d _sigtramp + 29
2 ??? 0x0000000000000000 0x0 + 0
3 CoreFoundation 0x00007fff39b00bb6 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
4 CoreFoundation 0x00007fff39b00b30 ___CFXRegistrationPost_block_invoke + 63
5 CoreFoundation 0x00007fff39b00a9a _CFXRegistrationPost + 404
6 CoreFoundation 0x00007fff39b08f48 ___CFXNotificationPost_block_invoke + 87
7 CoreFoundation 0x00007fff39a71994 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1642
8 CoreFoundation 0x00007fff39a70d47 _CFXNotificationPost + 732
9 Foundation 0x00007fff3bdab217 -[NSNotificationCenter postNotificationName:object:userInfo:] + 66
10 AppKit 0x00007fff3720538b -[NSWindow _setFrameCommon:display:stashSize:] + 3090
11 AppKit 0x00007fff37204766 -[NSWindow _setFrame:display:allowImplicitAnimation:stashSize:] + 192
12 AppKit 0x00007fff3720469f -[NSWindow setFrame:display:] + 51
13 AppKit 0x00007fff3727aca9 -[NSWindow _reallyDoOrderWindowAboveOrBelow:relativeTo:findKey:forCounter:force:isModal:] + 1336
14 AppKit 0x00007fff372792a0 -[NSWindow _doOrderWindow:relativeTo:findKey:forCounter:force:isModal:] + 283
15 AppKit 0x00007fff37a0dce9 -[NSWindow orderFrontRegardless] + 40
Code (it's a console app):
NSWindow *window = [[NSWindow alloc] initWithContentRect:windowRect
styleMask:windowStyle
backing:NSBackingStoreBuffered
defer:NO];
// Since Snow Leopard, programs without application bundles and Info.plist
// files don't get a menubar and can't be brought to the front unless the
// presentation option is changed
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
[NSApp activateIgnoringOtherApps:YES];
[window makeKeyAndOrderFront:nil];
How do you initialize the app? Do you have NSApplication initialized before using AppKit?
Something like these steps should be necessary in main.m:
#autoreleasepool {
NSApplication* application = NSApplication.sharedApplication;
AppDelegate* delegate = [[AppDelegate alloc] init];
application.delegate = delegate;
[application run];
}
Also your delegate might be getting deallocated, since NSApp holds a weak reference to it.
You indicated that you were dereferencing an uninitialized pointer. But, I don't have enough information from the report you posted to know if this was (perhaps by luck) null, or just garbage memory. I'll assume that at some point you crashed with an EXC_BAD_ACCESS (signal equivalent is SIGBUS or SIGSEGV, depending).
The critical bit of information here was that you had a signal handler installed.
Signal handlers generally (but not always) run on the crashing thread using the same stack. The kernel injects the handler using that _sigtramp function. Upon signal delivery, current stack state contained the information you needed to track down the bad memory access. But, your signal handler was invoked instead. So it ran, mutating the stack as it did.
Then, your signal handler completed somehow. It is possible to configure a signal handler using sigaction such that the process state is restored to the moment just before the crashing event. I'm not sure how your signal handler was configured. But, ultimately, I'm going to assume that the process was allowed to exit.
At this point, Apple's ReportCrash would have been triggered, and would capture backtraces for all threads in whatever state your signal handler left them. This is critical, because that's not necessarily the crashing state.
Adding complexity, backtrace_symbols_fd is not at all safe to use from a signal handler. Async safety is challenging, and running code from a signal handler is highly difficult to get right. There are very few things you can do safely. I'm pretty sure, additionally, that backtrace_symbols_fd allocates memory. So, if your crash was in the memory allocator somewhere, and it sounds like it was, you were definitely at risk for a deadlock. Judging by the backtrace, it seems like that's exactly what might have happened. Check out man sigaction for some details.
Worse, unwinding the stack over a signal handler frame is particularly challenging because of the magic the kernel does to run your handler. That's why that ??? frame is in there.
A summary:
Without a signal handler installed, Apple's ReportCrash would have produced a correct (and likely helpful) backtrace for the crashing thread.
The stack trace you've included isn't great, but it's hard to know exactly why.
It appears that backtrace_symbols_fd didn't do a good job of unwinding, possibly due to it being inappropriate to use from a signal handler, possibly because it isn't backed by a good-enough stack unwinding mechanism for this situation. But, without more information, it's difficult for me to know. I am surprised the the top frame was _sigtramp, though. That doesn't make a lot of sense. It makes me think something might have been going wrong in the signal handler itself. It is possible to crash a second time in your handler.
Apple's backtraces (generated by ReportCrash, backtrace_symbols_fd, or NSThread's callStackReturnAddresses, for example) can definitely be trusted, provided you're careful to use them in safe contexts.
Turns out I had a serious memory bug in a completely different place not even mentioned in the backtrace.
I was dereferencing an uninitialised pointer.
This is the second time it happens.
Do no trust Apple's backtraces when debugging memory errors.
Even with libgmalloc.

NSThread setStackSize not setting the size of thread

I am using an NSThread and setting the stack size for it as follows:
thread=[[NSThread alloc]initWithTarget:self selector:#selector(fibnocciForLoop) object:nil];
[thread setStackSize:12];
[thread start];
As written Apple docs for for -[NSThread setStackSize:]:
Discussion
You must call this method before starting your thread. Setting the stack size after the thread has started changes the attribute size (which is reflected by the stackSize method), but it does not affect the actual number of pages set aside for the thread.
But when I check the stack size later in the debugger I don't get the value I set:
print (int)[thread stackSize]
$1 = 524288
My question is why does the setStackSize: method exist if it does nothing?
Please let me know where I am wrong, or whether the API for setStackSize: is not of any use?
EDIT:
Refer to Answer by #Josh Caswell for this question, i missed the K in 4K , and hence the above code will work fine as under:
thread=[[NSThread alloc]initWithTarget:self
selector:#selector(fibnocciForLoop) object:nil];
[thread setStackSize:12*4096];//4K=4096
[thread start];
EXTENSION OF THIS QUESTION:
Can someone kindly explain as to why Apple gave this method setStackSize, and how and when to use this particular method, because it requires a lot of calculations for the user to calculate as to how many bytes are/will be used.
I want to know its exact purpose in NSThread?
Thanks!
The setStackSize: documentation also says:
The stack size for the receiver. This value must be in bytes and a multiple of 4KB.
12 is not a multiple of 4K, so your NSThread ignores your setting and probably uses its default, which appears to be 128 pages (a page on iOS (and OS X) being 4KB), or 4 MB.
It's not clear what you want 12 to mean, but you'll need to change it to indicate at least 4096 bytes if you want NSThread to use your setting.
Just by reading the documentation you linked, have you tried calling [setStackSize:12] after [start]?
thread=[[NSThread alloc]initWithTarget:self selector:#selector(fibnocciForLoop) object:nil];
[thread start];
[thread setStackSize:4096]; // multiple of 4KB
Edit: Ok, nevermind. I totally read the documentation wrong. Do not do this.

EXC_BAD_ACCESS (code=1, address=0x0) when runModalForWindow

I have a window and a window controller which opens when the user clicks a button.
Sometimes I get EXC_BAD_ACCESS(code=1, address=0x0).
0x7fff6f2a59e0: movq (%rax), %rdi
Here is the code:
ChooseProceduresWindowController *chooseProceduresWindowController = [[ChooseProceduresWindowController alloc] initWithWindowNibName:#"ChooseProceduresWindow"];
[NSApp runModalForWindow:[chooseProceduresWindowController window]];
The error appears then runModalForWindow: is called.
I don't get this error every time, but I couldn't find a pattern.
Thanks
the best way to debug EXC_BAD_ACCESS errors is to use NSZombies.
Check out this video for an explanation :
http://youtu.be/LQtPr8bkB3g
NSZombie keeps all your objects in memory when you are trying to release an object that has already been released, so you get closer to finding your bug. As #Mark H said, it is a memory management issue.
Also you could put an NSLog in your dealloc method to have a better idea of what is getting deallocated when at runtime.
That error will be thrown when the object doesn't exist in memory. I'd start looking for memory management issues. The first would be to make sure you are releasing the ChooseProceduresWindowController after using it.

EXC_BAD_ACCESS on CCLabelBMFont dealloc?

On CCLabelBMFont, I get a EXC_BAD_ACCESS on its dealloc method. Specifically, line [configuration_ release];
I do not understand that at all. What could possibly cause that? My CCLabelBMFont was created alright, displayed alright, and when it is dealloced (when the scene is replaced), bang, the error comes.
Ideas?
Set NSZombieEnabled, MallocStackLogging, and guard malloc in the debugger. Then, when your App crashes, type this in the gdb console:
(gdb) info malloc-history 0x543216
Replace 0x543216 with the address of the object that caused the crash, and you will get a much more useful stack trace and it should help you pinpoint the exact line in your code that is causing the problem.
See this article for more detailed instructions.

Various Assembly Questions

I'm looking at some assembly stuff. So, pushl bar is the same as subl $4, %esp movl bar, ($esp).
Few questions:
1) What is special about the %esp register?
2) What does the parenthesis around the register mean?
3) pushl bar would meaning having bar on top of the stack, right? So what is happening when I do subl $4? Does that mean I am creating am empty space on top of the stack for me to move bar into?
ESP is the stack pointer - it always points to the "top" of the stack
The brackets mean "the memory pointed at by" ESP rather than the ESP register itself
You are moving the stack pointer down by four bytes (the stack grows downwards in most implementations - pushing something onto the "top" of the stack means storing it at a lower memory address)