AppDomain.CreateDomain causes Access Violation - c#

I'm making a plugin loader for Unity game (Subnautica). The loading mechanism itself works fine but I want to load the assemblies into a separate app domain so I can unload them at runtime too.
However, calling AppDomain.CreateDomain(string) crashes Unity, leaving an error log with
Unknown caused an Access Violation (0xc0000005)
in module Unknown at 0033:049f7717.
...
Read from location 00000000 caused an access violation.
and the log the game produces with
0x0000000005048C6D ((<unknown>))
ERROR: SymGetSymFromAddr64, GetLastError: 'The specified module could not be found.'
ERROR: SymGetModuleInfo64, GetLastError: 'A dynamic link library (DLL) initialization routine failed.'
I have tried injecting the code that calls AppDomain.CreateDomain into the game's code directly and I tried injecting code that loads the dll that calls AppDomain.CreateDomain using Assembly.Load, both methods crash with the same message.
Unity version is 5.4.4f1, I'm on Windows 10 and the assembly that calls AppDomain.CreateDomain uses .net 3.5. This is the error.log created by Unity and the stack trace from output_log.txt created by Subnautica.
Does anyone have any idea what could be causing Unity to crash?
PS, I know with certainty that AppDomain.CreateDomain is causing the problem.

Related

How to debug failed calls to ConvertAssemblyToTypeLib()?

The function ConvertAssemblyToTypeLib from assembly System.Runtime.InteropServices is a black box that is giving me a lot of head aches.
In most cases, this call
ITypeLibConverter tlbConv = new TypeLibConverter();
ITypeLib tlb = (ITypeLib)tlbConv.ConvertAssemblyToTypeLib(asm, tlbname, 0, this);
succeeds, but sometimes it throws this exception:
System.Runtime.InteropServices.COMException
HResult=0x80131163
Type library exporter encountered an error while processing 'MyType1.SendSetAsync(#0), MyType1'.
Error: Referenced type is defined in managed component, which is imported from a type library that could
not be loaded (type: 'MyType2.Interop.IComTask'; component:
'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\MyType2.Interop\v4.0_3.4.30000.0__nnnnnnnnnnnnnnnnn\MyType2.Interop.dll').
It's obvious that at least one of my dependent components is not installed/registered correctly.
But after removing everything from the GAC, scrubbing every related entry from the registry, and rebuilding everything from scratch, the above mentioned call succeeds again.
I'm sick and tired of driving the bull dozer through my living room just because a single nail is missing in the wall.
I tried running Assembly Binding Log Viewer while issuing the call to ConvertAssemblyToTypeLib but that did not record anything.
The assembly C:\Windows\Microsoft.Net\assembly\GAC_MSIL\MyType2.Interop\v4.0_3.4.30000.0__nnnnnnnnnnnnnnnnn\MyType2.Interop.dll does exists, I can open it in the object browser of Visual Studio and it looks just fine. Most notably it has the IComTask interface mentioned in the error message.
Any clues how I can pin point the component that causes the error?

Dynamics CRM 2011 SyncWorkflowExecutionPlugin unable to find assembly

A strange error suddenly cropped up on our Dynamics CRM 2011 server - a specific plugin assembly can not be found when the plugin execution is triggered through a workflow process, with the error:
[Microsoft.Crm.ObjectModel: Microsoft.Crm.ObjectModel.SyncWorkflowExecutionPlugin]
[324f29aa-6082-ea11-80ee-005056837add: ]
Starting sync workflow 'workflow name', Id: 2d4f29aa-6082-ea11-80ee-005056837add
Sync workflow 'workflow name' terminated with error 'The type initializer for '<Module>' threw an exception.'
And exception stack trace ultimately leads to:
Inner Exception: <CrtImplementationDetails>.ModuleLoadException: The C++ module failed to load while attempting to initialize the default appdomain.
at <CrtImplementationDetails>.ThrowModuleLoadException(String errorMessage, Exception innerException)
at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
at .cctor()
Inner Exception: System.Runtime.Serialization.SerializationException: Unable to find assembly 'AssemblyName, Version=8.75.0.267, Culture=neutral, PublicKeyToken=4e4051c21cef725b'.
The assembly is present on the server, version, culture, and public key token all match. Oddly enough the plugin steps work fine when the execution is triggered directly through a create/update/etc request - it's only when the execution is triggered through a workflow that the error occurs. And by triggered through a workflow I don't mean running code activity from that assembly, I mean a situation like:
Entity is created
OnCreate plugin from Assembly1 runs without issues
Workflow runs that updates a related entity, triggering OnUpdate plugin from Assembly1 - ERROR
This issue cropped up initially after a server restart. Another restart fixed it temporarily, until two days later it started happening again. We've tried everything we can think of - updating the assembly, unregistering/re-registering it, restarting all services, restarting the server again. Does anyone have any idea what might be the cause of this and how to fix it?
We discovered the issue was caused by a Windows update that had been applied before the initial restart, which had installed .NET framework v4.8 on the server. Although the application was still using an older version, apparently just having v4.8 installed was enough to cause errors. Reverting back to an earlier .NET version fixed the problem.
I am not certain what is the exact technical reason for this - seems to be something related to App Domains (https://learn.microsoft.com/en-us/dotnet/api/system.appdomain?view=netframework-4.8). But if you encounter a similar issue, check your .NET framework version.

Catch UnhandledException in com assemblies

I search a way to locate UnhandledException in a native c++ desktop application. The error occurs in a .net assembly that is called by in process com interop. Problems are I do not know witch assembly causes the UnhandledException and I can not reproduce on my developer machine, so I can not simply use the debugger.
I try with AppDomain.CurrentDomain.UnhandledException but I think each com call get it's own AppDomain. Whatever it does not work, app is still crashing and event is not triggered.
Also I try to use stackify prefix, but may app is not an webservice and not an windows service, so this does not work.
Event logs are written but do not point to the error.
Any idea how I could identify the assembly causing the problem?
-- Edit --
Not all assemblies used via com interop are my own, so it is not that easy to add code to all of them.
Erros in event log is:
Source: .Net Framework
ID: 1026
Message: The process was terminated on a unhandeled exception.
Errorcode c0000005

RavenDB within ASP.NET MVC with Unity causes ResolutionFailedException

I have the following:
ASP.NET MVC 5
RavenDB.Client version="3.0.3690"
Unity version="3.5.1404.0"
Unity.Mvc latest
Periodically, especially after the ASP.NET application has been idle for some time, upon loading the page I get the following exception:
Exception information:
Exception type: ResolutionFailedException
Exception message: Resolution of the dependency failed, type = "MyCompany.Web.Controllers.MainController", name = "(none)".
Exception occurred while: Calling constructor XXXXXXXX.
Exception is: FileNotFoundException - Could not load file or assembly 'ICSharpCode.NRefactory.CSharp, Version=5.0.0.0, Culture=neutral, PublicKeyToken=d4bfe873e7598c49' or one of its dependencies. The system cannot find the file specified.
Note that ICSharpCode.NRefactory.CSharp appears to be an embedded assembly inside RavenDB. I don't reference it anywhere in my code, and it's not in the bin folder.
I never get this error in a console or WPF application, so it must be something with unloading AppDomains and/or recycling ASP.NET AppPools.
Perhaps the code in Unity.Mvc doesn't handle the unloading of embedded assemblies properly. Or perhaps something is missing from the section of my web.config.
Once I get the error, I hit the F5 (Refresh) button in the browser, and viola, the error goes away and the page loads as expected.
Any idea?
Thanks,
-Alec.

Why can't MonoDroid find my assemblies?

I made a simple Android HelloWorld app using Xamarin Studio 4.2.3 that doesn't do anything except it prints out some message if a random number is greater than 0.5. It works just great on a Nexus 4 and a Nexus 5.
The next thing I'm doing is to extract the .dll with the code from the app's apk (from the assemblies folder) using 7Zip. Using .Net Reflector and Reflexil I'm modifying a single instruction, usually the brfalse.s that gets generated by the IF statement in "if(rand.nextDouble()>0.5){doStuff()}" such that it branches to the instruction right in front of the call to doStuff(), thereby effectively making the IF statement useless and ensuring the method always gets called.
Next I'm saving the patched .dll, replacing the original one in the .apk with the patched one, sign and zipalign the .apk and finally I'm installing it using adb.
When I'm launching the app on my phones it crashes directly and LogCat shows the following:
03-20 10:12:08.709: I/ActivityManager(764): Start proc HelloMonoLVL.HelloMonoLVL for activity HelloMonoLVL.HelloMonoLVL/hellomonolvl.hellomonolvl.TrialSplashScreen: pid=23099 uid=10128 gids={50128}
03-20 10:12:08.729: D/dalvikvm(23099): Trying to load lib /data/app-lib/HelloMonoLVL.HelloMonoLVL-1/libmonodroid.so 0x427154a0
03-20 10:12:08.729: D/dalvikvm(23099): Added shared lib /data/app-lib/HelloMonoLVL.HelloMonoLVL-1/libmonodroid.so 0x427154a0
03-20 10:12:08.739: W/libc(23099): WARNING: generic atexit() called from legacy shared library
03-20 10:12:08.759: W/monodroid-gc(23099): GREF GC Threshold: 46800
03-20 10:12:08.769: A/monodroid-assembly(23099): Coult not load assembly 'HelloMonoLVL' during startup registration.
03-20 10:12:08.769: A/monodroid-assembly(23099): This might be due to an invalid debug instalation.
03-20 10:12:08.769: A/monodroid-assembly(23099): A common cause is to 'adb install' the app directly instead of doing from the IDE.
03-20 10:12:08.789: I/ActivityManager(764): Process HelloMonoLVL.HelloMonoLVL (pid 23099) has died.
03-20 10:12:08.789: W/ActivityManager(764): Force removing ActivityRecord{42752a50 u0 HelloMonoLVL.HelloMonoLVL/hellomonolvl.hellomonolvl.TrialSplashScreen t238}: app died, no saved state
Since this didn't work I used the C# port of the LVL. Built the LVL sample app, deployed and it works on the phones. I again extracted the .dll with the license verification code, using Reflexil I changed the code of a method, injected the patched .dll in the apk, signed and zipaligned the apk. Again it doesn't work but crashes on launch and I now get:
03-20 10:21:19.049: D/dalvikvm(23507): Trying to load lib /data/app-lib/de.marius.lvl-1/libmonodroid.so 0x42711448
03-20 10:21:19.049: D/dalvikvm(23507): Added shared lib /data/app-lib/de.marius.lvl-1/libmonodroid.so 0x42711448
03-20 10:21:19.069: A/MonoDroid(23507): No assemblies found in '/data/data/de.marius.lvl/files/.__override__' or '/storage/emulated/0/Android/data/de.marius.lvl/files/.__override__'. Assuming this is part of Fast Deployment. Exiting...
03-20 10:21:19.079: I/ActivityManager(764): Process de.marius.lvl (pid 23507) has died.
03-20 10:21:19.079: W/ActivityManager(764): Force removing ActivityRecord{42bc3c60 u0 de.marius.lvl/.TrialSplashScreen t239}: app died, no saved state
It doesn't seem to make any difference if I'm using the apk that Xamarin generates in Release mode or Debug mode. I tried both using the apk versions from the bin folder of the project and the ones I pulled from the phone with adb pull.
I'm new to Xamarin so maybe my approach is naive. Is there something like a hash check that my patched .dlls don't pass? I saw that Reflexil has an option to remove StrongNames, I tried that but it didn't seem to make any difference (but I must admit I don't really know how those work).
Is it even possible what I'm trying to do?
Any help is much appreciate.
Uninstall all the packages installed in your project including android support libraries like Android.Support.v4 support libraries and clean the solution.
Then again reinstall all the required packages and support libraries and rebuild your solution. It may help you sort out your query.

Categories