Handling exception obtained by calling native-to-managed thunk - mono

The scenario is pretty straighforward, I've embedded mono runtime 2.10.8 in my app, and I'm calling the managed methods via pointers obtained by: mono_method_get_unmanaged_thunk:
// obtain pointer
bool (__stdcall*foo) (MonoException**);
foo = mono_method_get_unmanaged_thunk(somemethod);
// call it
MonoException* exc;
foo(&exc);
if(exc)
// handle exception
// nothing else...
What puzzles me, that I'm doing nothing else with the MonoException pointer (documentation I've read doesn't say anything about this). Is it removal handled by the managed runtime? If so, how it can be sure that my native side is not holding a pointer to it?
Edit
I've read through the sources and found out that exceptions are just pointers to objects created with mono_object_new, so they are subject of the garbage collection.
Now, I've also read that if I want to keep some pointer on native side and prevent it from being garbaged I need to obtain GC handle for it. So the (modified) question now is:
If the point of returned pointer to exception object is only to serve as error reporting facility, and such error reporting is made right after the managed call, is it safe to assume it won't get garbaged before I handle it (without using gc handle)?

To quote the page you linked:
Note that this registration is not necessary for LOCAL variables, as they are stored on the stack. It is only necessary for global variables, as they are not a part of the GC's root set.
So that means in your scenario you don't have to allocate a handle.

Related

ERROR objc_retainedObject() unavailable

when i'm trying to build my project I have a new error where objc_retainedObject() is used.
I have the error message objc_retianedObject is unavailable: use CFBridgingRelease() or a (__bridge_transfer id) cast instead.
I replaced the usages of objc_retainedObject() by CFBridgingRelease and there are no longer errors and I can run the app, but when the app is going to display my QRCode-scanning view, it crashed without messages.
It is the same when I put #define objc_retainedObject(o) ((__bridge_transfer id)(objc_objectptr_t)(o)) which was supposed to be a solution.
I believe that it is an XCode configuration or a missing library problem. Any ideas?
Do not recreate objc_retainedObject. It was removed on purpose. CFBridgingRelease and CFBridgingRetain are the correct tools for moving CF objects into ARC. (__bridge is the tool for dealing with CF objects that you don't need to transfer to ARC because you aren't storing them.)
If your program is crashing, you're probably managing memory incorrectly. It is likely that objc_retainedObject was incorrect (even if you happened to get away with it). See when should you use __bridge vs. CFBridgingRelease/CFBridgingRetain? for correct memory management when transferring CF objects to ARC.
Without knowing more about the code, I can't guess exactly where you've made a mistake, but you probably are calling CFBridgingRelease on an object that you didn't acquire via the Create Rule. You don't just throw CFBridgingRelease on every CF object you encounter. You need to make sure you're balancing an existing retain.

VB.NET Track COM RCW error

I have a really big project that I can not easily strip down.
When the application is being closed, I get the error
"InvalidComObjectException: A COM object that has been disconnected from the RCW can not be used."
Details:
System.Runtime.InteropServices.InvalidComObjectException has occured.
HResult=-2146233049
Message=A COM object that has been disconnected from its RCW can not be used.
Source=mscorlib
StackTrace:
at System.StubHelpers.StubHelpers.StubRegisterRCW(Object pThis)
InnerException:
Unfortunately I can not see what COM object this is about.
Does anybody know how I can find that out? Unfortunately I can't read ASM to analyze the disassembly.
There are some steps you could try and since you haven't posted any code I will try to enumerate some of the most common key factors...
First, there is no order when disposing objects. If a close/dispose/finalize action is invoked, object C might be disposed before object A and if some object is still alive it might try to access an already disposed object.
Second, beware of events. It's very common to get errors about accessing a disposed object originated from an event call.
Third, do not dispose objects inside an event scope nor destructors. Create your own method to free your object(s).
Since you don't know which COM object is the culprit, I suggest you look for the ones that you do close, dispose, disconnect, etc...
You might want to read this blog in order to better understand how RCW's work and also to help you with your problem.
Edit:
After reading your comment, I felt I should add two possible causes:
If after removing Microsoft.VisualBasic runtime methods you've solved your problem, then I suspect that inside one, or more, of those methods you have incremented the count of a reference to one, or more, of your COM(s) and did not release properly.
Be sure to ReleaseComObject checking the reference count until it's 0 and then set it to nothing(VB) or null(C#) and let the Garbage Collector do the rest.
The other option is that one of those methods tried to access an already disposed reference to a COM object, resulting in a RCW error, since is no longer callable.
As a final comment, after releasing the COM object always set it to nothing or null, this will release the reference to the variable and you can always check it's availability anywhere in the code.

iOS6 and ACAccount: Twitter type disappears?

I try to authenticate my app with Twitter with following code: pastebin
However, if I remove the (useless?) loop line 23ff
for (ACAccount *acc in arrayOfAccounts) {
[acc accountType].identifier;
//Otherwise the identifier get lost - god knows why -__-
}
the acc.type becomes (null) when it gets executed further in
AccountHandler checkAccountOf:acc. If I leave the loop in, the type is correctly set.
I am pretty sure it has to do with the fact that I am in a block and then move on to the main queue, but I am wondering if I am doing something wrong? This loop does not look like sth I am supposed to have to do.
Something kinda similar happened here.
ACAccounts are not thread safe. You should use them only on the thread that they originate. And for this purpose you can read 'thread' as 'queue'.
While I've not seen formal documentation of that, if you NSLog an account you'll see that it's a Core Data object and the lack of thread safety on Core Data objects is well documented.
The specific behaviour is that a Core Data object can be a fault. That means that what you're holding is a reference to the object but not the actual object. When you try to access a property the object will be loaded into memory.
What Core Data is doing underneath is caching things in memory and returning faults until it knows that an object is really needed. The efficient coordination of that cache is what limits individual instances of the Core Data object that coordinates objects to a single thread.
If you do the action that should bring the object into memory on the wrong thread — which is what happens when you access identifier here — then the behaviour is undefined. You could just get a nil result or you could crash your application.
(aside: the reason that Core Data works like this is that it stores an object graph, so possibly 1000s of interconnected objects, and you can traverse it just like any other group of objects. However you don't normally want to pay the costs associated with loading every single one of them into memory just to access whatever usually tiny subset of information you're going to use, so it needs a way of providing a normal Objective-C interface while lazily loading)
The code you've linked to skirts around that issue by ensuring that the objects are in the cache, and hence in memory, before queue hopping. So the 'fetch from store' step occurs on the correct queue. However the code is nevertheless entirely unsafe because objects may transition from being in memory back to being faults according to whatever logic Core Data cares to apply.
The author obviously thinks they've found some bug on Apple's part. They haven't, they've merely decided to assume something is thread safe when it isn't and have then found a way of relying on undefined behaviour that happened to work in their tests.
Moral of the story: keep the accounts themselves on a single thread. If you want to do some processing with the properties of an account then collect the relevant properties themselves as fundamental Foundation objects and post those off.

Strange COM behaviour called from .net

i am working on an application which calls the COM component of a partner's application. Ours is .Net, theirs isn't. I don't know much about COM; I know that the component we're calling is late-bound i.e.
obj As Object = CreateObject("THIRDPARTY.ThirdPartyObject")
We then call a method on this COM object (Option Strict Off in the head of the VB file):
obj.AMethod(ByVal Arg1 As Integer, ByVal Arg2 As Integer, ByVal Arg3 as Boolean)
I am a bit nonplussed that even though this call works, this overload doesn't exist in the COM interop .dll that is created if I instead add a reference to the COM server using Add Reference. The only available call to this method that it says is available is AMethod().
However, this in itself is not what bothers me. What bothers me is that this call works for a while, THEN throws a TargetParameterCountException after a few dozen calls have executed successfully.
I ask thee thus, StackOverflow:
What. The. Hell.
The only thing I can guess at is that the documentation for the COM component states that this method is executed synchronously - so therefore maybe whatever's responsible for throwing that exception is being blocked until some indeterminate point in time? Other than that, I'm completely stumped at this bizarre, and more importantly inconsistent behaviour.
edit #1:
More significant information that I've just remembered - from time to time the call throws an ExecutionEngineException instead. It only took one glance at the documentation to realise that this is VERY BAD. Doing a little bit of digging suggests to me that the late-binding call is causing stack corruption, crashing the entire CLR. Presumably this means that the runtime is shooting down bad calls (with TargetParameterCountException) some of the time and missing them (ExecutionEngineException) others.
edit #2:
Answering David Lively's questions:
The call with zero arguments that's currently in the code has been there for a long time. I haven't been able to get hold of a manual for the third party's COM implementation past two major revisions ago, so it's possible that they've withdrawn that signature from service
There is only one location that this method is called from
This is one desktop app calling another, on the same machine. Nothing fancy
The object is persisted throughout the scope of the user's interaction with the application, so there's never a new one created.
Unfortunately, it seems likely that there is indeed a bug in the implementation, as you suggest. The trouble with this vendor is that, when we report a bug, their response tends to follow the general form: i) deny there's a problem; ii) deny it's their problem; iii) refuse to fix it. These three steps tend to span a frustratingly long period of time.
No, it can't cause stack corruption. IDispatch::Invoke() is used to call the method, the arguments are packaged in an array. The stock implementation of IDispatch certainly would detect the argument mismatch, it uses the type library info to check. But it is conceivable that the COM server author implemented it himself. Imperfectly. It is something a C++ hacker might do, the stock implementation is dreadfully slow. The GC heap getting corrupted is the kind of thing that happens when imperfect code executes.
I haven't played with calling COM objects from VB in quite a while, but I'll take a wild guess:
I would expect an exception to be thrown if you're calling the object with too few or too many arguments, but it appears that's not the case. What is the real signature of the method you're calling?
In some languages and some situations, when you call a method, arguments are placed on the stack. If you place too many arguments, it's possible for the extraneous ones to remain on the stack after the method completes. This should cause lots of other problems, though.
Some possibilities/considerations:
The object is throwing this exception internally. This should be taken up with the author.
You're calling with too many parameters. If, as you said, the overload you're trying to call isn't published in the object's type library, you may actually be calling a different published method with a different signature. I'd REALLY expect a compiler error if this is the case.
Are your later calls taking place in the same part of your code, or is there a different execution branch that might be doing things a bit differently, and causing the error?
Are you running this from a desktop app/script, or a website? If a website, are you receiving a valid, expected response, or does the request hang as if an internal long-running process doesn't complete?
The object may be allocating and not releasing resources, which could cause undefined behavior when those resources are exhausted.
Are you releasing the object between calls, or is it recreated every time?
Also, re: your comments about late binding: the .CreateObject() method of instantiating a COM object is the normal, accepted way to do this. That shouldn't have anything to do with the issue. Based on the exceptions you listed, I'm strongly inclined to believe that there is an internal issue with the object.
Good luck.
OK, basically - false alarm. I've done it wrong - I've copied some code over from somewhere improperly and the thing I'm calling was never supposed to support that overload. What I find interesting is that the component didn't reject that late-bound call out of hand, but did everything it was supposed to do, at least initially.

checking for failed new

why does this ATL/COM code check for successful alloc? I would have expected a custom allocation to be visible through CoGetALloc or some such api. A standards-conforming C++ runtime should be throwing std::bad_alloc, but then again maybe the allocator has indeed been traded out for a non-throwing impl.
DDClientData* pNewData = new DDClientData();
if (pNewData==NULL)
return E_OUTOFMEMORY;
COM methods are not allowed to let exceptions out - the implementation can throw exceptions, but it must handle them before they escape the method and translate to an appropriate HRESULT.
The code above will not have desired effect - once new fails std::bad_alloc is thrown and the check for a null pointer is not executed. The implementation has to either wrap the new call into try-catch or wrap the whole method implementation into try-catch. ATL usually uses _ATLTRY-like macros around the new call.
COM doesn't use exceptions: any COM object is supposed to return a valid HRESULT on failure. Plus there are guarantees about setting return values on exit, which any conforming COM object has to comply with. For these reasons, exceptions play badly with COM/ATL, and aren't used at all internally at Microsoft[1], not even for allocations. The code sample shown above simply reflects that convention.
[1] Sez me, an MS FTE. COM components at MS are compiled with C++ exceptions disabled.