Custom `catch_unwind`

Objective-C have exceptions similar to C++ exceptions (not very familiar with these, maybe some of this applies here as well), and catching them require using the objc_begin_catch and objc_end_catch helper functions, similar to Rust calling the internal __rust_panic_cleanup function as part of catch_unwind.

In the objc-crate's exception handling, we currently resort to letting an Objective-C compiler (like clang) generate a helper function that uses @try and @catch. This adds unnecessary overhead, and is bad for cross-compilation and all that.

core::intrinsics::try is the underlying intrinsic that makes catch_unwind work; with it, the overhead can be avoided by effectively re-implementing most of catch_unwind, see an example implementation here: Use nightly features by madsmtm · Pull Request #11 · SSheldon/rust-objc-exception · GitHub.

But obviously core::intrinsics::try is an intrinsic, and not intended to be stabilized, so I'd like to discuss a way we could stabilize it or parts of its functionality, to allow this use-case.

That code doesn't seem correct. It doesn't check that the exception is actually an Objective-C exception and not a Rust panic or C++ exception.

True, though that's not the point, it's meant to be used on the FFI boundary just before sending an Objective-C message (equivalent to calling an "C-unwind" function). So the (yup, unsafe) assumption is that any unwinding must be the result of a thrown Objective-C exception.

That said, if there is a way to check the "type" of the exception I'd love to know!

It seems like you are trying to use Rust panics as traditional, general error handling, like exceptions in other languages. Don't do that – panics are not meant to be used like that. If you want to perform regular error handling, use Result.

Hmm no, rather I'm trying to convert an Objective-C exception into the standard Rust Result

What do you need from the Rust compiler?

If I'm not mistaken you're assuming that Rust's try is going to be compatible with ObjC's @try. Is that even a promise that Rust can keep?

It might be worth getting involved with the FFI unwinding working group.

1 Like

Yeah, I was going to raise that. There's no guarantee that ObjectiveC and Rust's unwinding mechanisms are related in the slightest, and if you are on a platform where a de facto guarantee does exist, then you probably know how to catch exceptions from the former.

I would like similar abilities, but what is probably needed is a way to directly interact with the unwinding mechanism (SEH on windows, Sys-V/Itanium Unwinding, etc.), which would probably need to be platform-specific.


Coming back to this, I realize that you are right, what I'm trying to do here is fundamentally not possible since Rust's unwinding mechanism is explicitly unspecified, and I think that's the right decision.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.