From time to time my users find this error:
myapp(7383,0x1a1471000) malloc: * mach_vm_map(size=67125248) failed
(error code=3)
error: can't allocate region
set a breakpoint in malloc_error_break to debug 2017-04-06 20:33:58.152 myapp[7383:3724816] Terminating app due to uncaught
exception 'NSMallocException', reason: ' NSAllocateObject():
attempt to allocate object of class 'IOSByteArray' failed'
* First throw call stack: (0x183386db0 0x1829ebf80 0x183386cf8 0x183c6b34c 0x10076e6e4 0x10097d3ec 0x10097e35c 0x100977dd4
0x100977bd8 0x100978ff8 0x10096c950 0x10099685c 0x100997360
0x100979ca4 0x100976dcc 0x1002ec30c 0x100332fe4 0x100332e18
0x1003740c4 0x1004070f8 0x1004064ac 0x1021089b0 0x10210806c
0x1021089b0 0x102107710 0x1004072d8 0x1021087ec 0x1004071b0
0x102126bbc 0x10207b2d8 0x10207b374 0x188613dc4 0x1886d17d4
0x18878f0c8 0x18879ca80 0x1884ce5a4 0x18333c728 0x18333a4cc
0x18333a8fc 0x183264c50 0x184b4c088 0x188546088 0x100382a60
0x182e028b8) libc++abi.dylib: terminating with uncaught exception of
type NSException
The problem is that I can not find the callstack of the error.
I'm using XZ java lib ported into objc lib using j2objc application.
So, I can use this lib but I can't catch this error.
Google Analytics helps me and shows this line:
"&exd" =
"NSMallocException\nTrace:\n\nNSAllocateObject\nIOSByteArray_NewArray\nOrgTukaaniXzLzLZDecoder_initWithInt_withByteArray_\nnew_OrgTukaaniXzLzLZDeco";
So, It seems there is an error occurs:
void OrgTukaaniXzLzLZDecoder_initWithInt_withByteArray_(OrgTukaaniXzLzLZDecoder *self, jint var1, IOSByteArray *var2) {
NSObject_init(self);
self->start_ = 0;
self->pos_ = 0;
self->full_ = 0;
self->limit_ = 0;
self->pendingLen_ = 0;
self->pendingDist_ = 0;
JreStrongAssignAndConsume(&self->buf_, [IOSByteArray newArrayWithLength:var1]);
if (var2 != nil) {
self->pos_ = JavaLangMath_minWithInt_withInt_(var2->size_, var1);
self->full_ = self->pos_;
self->start_ = self->pos_;
JavaLangSystem_arraycopyWithId_withInt_withId_withInt_withInt_(var2, var2->size_ - self->pos_, self->buf_, 0, self->pos_);
}
}
But I can't find this error using swift:
do {
// ............
let inxz:OrgTukaaniXzXZInputStream = try OrgTukaaniXzXZInputStream(javaIoInputStream:in_)
// ..........
} catch {
print(error)
}
Please, help me
Swift's try/catch is completely separate from ObjC exceptions like this one. Those can only be caught with ObjC using #try and #catch. It is not possible to do in Swift.
That said, ObjC is generally not exception-safe. You have to be very careful using them, and in almost all cases the correct behavior after an exception is to crash the program. In this case, wrapped around exactly one call to a bridged function, it may be possible to effectively catch and deal with, but doing it correctly is a fairly subtle skill and not recommended if you can avoid it.
Almost certainly the reason for this error is that you're trying to allocate something too large. Rather than trying to catch the exception, I would look into why the object is so large and address that. In particular, I'd look at how large var1 is and make sure it's in a reasonable range. Also make sure it's not negative. The fact that you're using jint suggests that you might be seeing a mismatch with your integer types which I would absolutely expect to cause this kind of crash.
Thanks to #Sultan . He gave me an idea to use XZ pure C lib instead of Java>ObjC lib. Now this crash does not exist. It seems j2obc is wonder framework but it has got rare uncatchable errors.
Related
I notices some code that made me think the Exception function call was optional? E.g., do these two lines perform the same function?
throw Exception('oops!');
throw 'oops!'
No.
The former, throw Exception('oops!');, creates a new Exception object using the Exception constructor, then throws that object.
It can be caught by try { ... } on Exception catch (e) { ... }.
The latter, throw 'oops!'; throws the string object.
It can be caught by try { ... } on String catch (e) { ... }.
Generally, you shouldn't be doing either.
If someone made an error, something that would have been nice to catch at compile-time and reject the program, but which happens to not be that easy to detect, throw an Error (preferably some suitable subclass of Error).
Errors are not intended to be caught, but to make the program fail visibly. Some frameworks do catch errors and log them instead. They're typically able to restart the code which failed and carry on, without needing to understand why.
If your code hit some exceptional situation which the caller should be made aware of (and which prevents just continuing), throw a specific subclass of Exception, one which contains the information the caller needs to programmatically handle that situation. Document that the code throws this particular exception. It's really a different kind of return value more than it's an error report. Exceptions are intended to be caught and handled. Not handling an exception is, itself, an error (which is why it's OK for an uncaught exception to also make the program fail visibly).
If you're debugging, by all means throw "WAT!"; all you want. Just remove it before you release the code.
Here's my Swift 2.1 code snippet. The error that's occurring is shown in the comments at the point where the error appears.
The error shows up in the debugging panel, and the app crashes. The app never prints the line in the catch, nor does it gracefully return as expected.
let audioFileURL = receivedAudio.filePathURL
guard let audioFile = try? AVAudioFile(forReading: audioFileURL) else {
print("file setup failed")
return
}
let audioFileFrameCount = AVAudioFrameCount(audioFile.length)
audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFile.fileFormat, frameCapacity: audioFileFrameCount)
do {
// ERROR: AVAudioFile.mm:263: -[AVAudioFile readIntoBuffer:frameCount:error:]: error -50
// Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'error -50'
// -50 = Core Audio: bad param
try audioFile.readIntoBuffer(audioFileBuffer)
}
catch {
print("unable to load sound file into buffer")
return
}
From everything I've seen, my do/try/catch format should be correct.
audioFile.readIntoBuffer returns void and has the keyword throws.
Yet, the catch is never executed.
What am I missing?
UPDATE: From Apple's documentation on AVAudioFile
For:
func readIntoBuffer(_ buffer: AVAudioPCMBuffer) throws
Under Discussion:
HANDLING ERRORS IN SWIFT:
In Swift, this API is imported as an initializer and is marked with the throws keyword to indicate that it throws an error in cases of failure.
You call this method in a try expression and handle any errors in the catch clauses of a do statement, as described in Error Handling in The Swift Programming Language (Swift 2.1) and Error Handling in Using Swift with Cocoa and Objective-C (Swift 2.1).
From The Swift Programming Language (Swift 2.1): Error Handline
NOTE
Error handling in Swift resembles exception handling in other languages, with the use of the try, catch and throw keywords. Unlike exception handling in many languages—including Objective-C—error handling in Swift does not involve unwinding the call stack, a process that can be computationally expensive. As such, the performance characteristics of a throw statement are comparable to those of a return statement.
And, finally, from the same document:
Handling Errors Using Do-Catch
You use a do-catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it is matched against the catch clauses to determine which one of them can handle the error.
I don't have to write and throw my own errors/exceptions for them to be caught. I should be able to catch Swift's exceptions as well.
The do - catch combination is fine. This issue is simply one that cannot be caught - and therefore never makes it to the catch block.
If the issue were catchable (defined and handled via Swift's throws functionality), the catch block would've been executed.
Some semantics: there is a long-standing argument about the differences between the terms error and exception.
Some developers consider the two terms to be distinct. In this case, the term error represents an issue that was designed to be handled. Swift's throws action would fit here. In this case, a do - catch combination would allow the issue to be caught.
An exception, for these developers, represents an unexpected, usually fatal, issue that cannot be caught and handled. (Generally, even if you could catch it, you would not be able to handle it.)
Others consider the two terms to be equivalent and interchangeable, regardless of whether the issue in question can be caught or not. (Apple's documentation seems to follow this philosophy.)
(Updated to focus on the answer rather than the semantics.)
catch will only catch the errors that are explicitly thrown. It will never catch exceptions.
What you seem to have here is an exception happening in the AVAudioFile SDK, not a Swift error, so it's not caught:
ERROR: AVAudioFile.mm:263: -[AVAudioFile readIntoBuffer:frameCount:error:]: error -50
Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'error -50'
-50 = Core Audio: bad param
In the context of Swift, "error" means an error thrown by a function, nothing else. The function being yours or not does not matter.
Exceptions in Swift are not caught ever. It's not the same as in Java at all, for example. In Swift, error != exception, they are two very different things.
I understand your opinion that "It should work for both" but it's simply not the case. You can see this as a semantic situation with using the keyword "catch" if you want, because it's the same keyword as other languages but behaves very differently; it resembles, but it's not the same.
As for your exception with AVAudioFile, I don't have a solution - maybe it's a bug in this SDK? Or it's not yet properly bind to Swift and the throwing system. In this case, and if nobody else has a solution, don't hesitate to report the bug to Apple.
see this example
struct E: ErrorType{}
func foo(i: Int) throws {
if i == 0 {
throw E()
}
print(10 / (i - 1))
}
do {
//try foo(1) // if you uncomment this line, the execution
// will crash, even though the function is declared
// as throwing and you use proper calling style (do / try / catch pattern)
try foo(0)
} catch {
print("error: ", error) // error: E()
}
I'm running into a situation in iOS (and OS X) where exceptions from NSKeyedUnarchiver cause binary-only third-party frameworks to crash my app (when deployed in the field) when they try to unarchive a corrupt archive, thus forcing users to delete and reinstall the app. This doesn't happen often, but I'd like that number to be zero.
I can't solve the problem by wrapping the NSKeyedUnarchiver calls, both because I don't have the source code and because those calls are not the direct result of anything that my code does; they run on arbitrary background threads at arbitrary times.
I'm currently swizzling the NSKeyedUnarchiver class so that reading a corrupt archive returns nil (as though the file were not there) rather than throwing an exception, but I can't be certain whether any of those third-party frameworks might do things correctly (with an #try/#catch block) and might break in interesting ways if I do so.
It would be helpful if I could somehow examine the Objective-C exception handling tree (or equivalent) to determine whether an exception handler would catch an exception if thrown, and if so, which handler. That way, my patched method could return nil if the exception would make it all the way up to Crashlytics (which would rethrow it, causing a crash), but could rethrow the exception if some other handler would catch it.
Is such a thing possible, and if so, how?
Why not wrap your exception-throwing callsite in a try/catch/finally?
#try {
//call to your third party unarchiver
}
#catch {
//remove your corrupted archive
}
#finally {
//party
}
Rolling your own global exception handler may also be of use here, ala: How do you implement global iPhone Exception Handling?
If you're not sure that wrapping third-party library code with #try/#catch is good enough you can hook NSKeyedUnarchiver methods to replace them with exact same wrapper thus making sure that exception is never gets thrown outside. Here is pseudo-code:
#try {
//call original NSKeyedUnarchiver implementation
}
#catch {
return nil;
}
Objc runtime has public APIs that can do such a thing
I have a very peculiar issue.
Recently I added 64bit support to my iOS project (arm64), ever since doing that I started receiving uncaught exceptions for segments of my code inside #try...#catch (I'm using Crashlytics for crash reporting). I managed to reproduce the problem with the following lines of code anywhere in my app (I wrote them inside init of one of my view controllers):
#try {
NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
NSString *s;
m[s] = #"poop";
} #catch (NSException *e) {
NSLog(#"POOP");
}
The exception gets caught by the UncaughtExceptionHandler instead of the #catch clause. I'm confused as to what can cause this. The output in the console:
2015-02-22 19:19:53.525 [391:30650] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: key cannot be nil'
*** First throw call stack:
(0x18823a59c 0x1989400e4 0x1881251f8 0x10011e2f4 0x10011e068 0x10010e480 0x10010db78 0x10010d944 0x1000a8050 0x100075d88 0x100075160 0x100142044 0x100141f6c 0x18c9ecaa0 0x18caa1fb4 0x18caa1eb0 0x18caa134c 0x18caa0ff8 0x18caa0d18 0x18caa0c98 0x18c9e9648 0x18c341994 0x18c33c564 0x18c33c408 0x18c33bc08 0x18c33b98c 0x18cc76dbc 0x18cc77c68 0x18cc75dec 0x1904b162c 0x1881f2a28 0x1881f1b30 0x1881efd30 0x18811d0a4 0x18ca573c8 0x18ca523c0 0x1000747d8 0x198faea08)
libc++abi.dylib: terminating with uncaught exception of type NSException
I tried removing the custom exception handler that I have and disabling Crashlytics, still no success.
As soon as I remove arm64 from ARCHS and VALID_ARCHS the code works and the exception is caught as expected.
Any information will be appreciated!
Small update - our XCTests also started not to catch exceptions, up until now the behaviour only happened on physical 64bit phones.
After a long session of git-bisecting the culprit was the following linker flag
-no_compact_unwind
I Used BlocksKit v2.2.0 which still had that flag even though it stopped using libffi (latest version of BlocksKit removed that unneeded flag). As soon as I removed that linker flag 64bit #try...#catch blocks started to work again.
I still don't have complete understanding of why this behaviour happens but I'm going to dig a bit more and update this thread if I find anything interesting.
phew
On iOS and Objective-C Exceptions are only to be used for un-recoverable programming errors, not for program execution control.
In particular they do not handle catches accross stack frames inthe APIs.
I'm writing Cocoa unit tests using XCTest and recently used XCTAssertThrows for the first time. That's pretty cool, but I want to make it even better with XCTAssertThrowsSpecific and requiring a certain exception.
Here is an example test:
-(void)testShortPassword {
XCTAssertThrows([user storePassword:#"abc"],#"Expect exception for short pw");
}
And on my user class I have the following code:
-(void)storePassword:(NSString*)password {
NSCAssert(password.length > 6, #"Password must be longer than 6 characters");
// go on to store the password on the keychain
}
Keeping in mind that Cocoa in general shies away from using exceptions (so it might be better to return an error, and show UI in the preceding example, etc.) How do I throw an exception in a manner that can be caught by XCTAssertThrowsSpecific? How do I specify that in XCTAssertThrowsSpecific(expression, specificException, format...)?
You should only use exceptions for exceptional cases, not for error handling and flow control
Having said that, here's how you use XCTAssertThrowsSpecific:
XCTAssertThrowsSpecific expects the specific class of the exception as the second parameter. NSCAssert throws an NSException. To test for that, use
XCTAssertThrowsSpecific([object methodThatShouldThrow], NSException, #"should throw an exception");
Now, that won't help much, because it's likely that every exception is an NSException or a subclass thereof.
NSExceptions have a name property that determines the type of the exception. In case of NSCAssert this is NSInternalInconsistencyException. To test for that, use XCTAssertThrowsSpecificNamed
XCTAssertThrowsSpecificNamed(
[object methodThatShouldThrow],
NSException,
NSInternalInconsistencyException,
#"should throw NSInternalInconsistencyException"
);