tags:

views:

235

answers:

4

As part of segmenting my app into separate appdomains in order to catch and recover from an intermittent crash when calling a native dll, I need a way to reliably trigger this type of crash in order to determine if I am catching the appdomain going down correctly.

I'm looking for some simple native code (C++ ?) I can compile into a dll, and call from my dotnet code with the expectation it'll take the dotnet code down with it.

Any suggestions?

A: 

Just make a native C++ function that does anything bad, such as divide by zero, ie:

void BeABadMethod()
{
    int i = 5;
    int j = 0;
    printf("%d", i/j);
}
Reed Copsey
A: 
void CrashAndBurn (void)
{
    *((int *)0) = 1337;
}
Nick Bedford
+1  A: 

Rather than writing your own DLL, you can import from one of the standard ones and do something you know will cause an exception. For instance, calling GetProcAddress with hModule = 0 should result in an exception. It might check for 0 since 0 can be NULL, but I really doubt it will check for other small numbers like 1 or 2 :)

How to import GetProcAddress according to pinvoke.net:

[DllImport("kernel32.dll", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
public static extern UIntPtr GetProcAddress(IntPtr hModule, string procName);

This program:

using System.Runtime.InteropServices;
using System;
public class x
{
    [DllImport("kernel32.dll", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
    public static extern UIntPtr GetProcAddress(IntPtr hModule, string procName);

    static void Main()
    {
        Console.WriteLine(GetProcAddress((IntPtr)5, "asdf"));
    }
}

results in the following error in Mono, becuase I don't have kernel32:

Unhandled Exception: System.EntryPointNotFoundException: GetProcAddress
  at (wrapper managed-to-native) x:GetProcAddress (intptr,string)
  at x.Main () [0x00000] 

so I'm not sure what it will do in .NET on Windows -- hopefully that will cause a crash!

Mark Rushakoff
A: 

You can create a native DLL that makes a callback to a managed code delegate instance that has gone out of scope before the DLL attempts to call it. I don't know what effect this has in the full .Net framework, but in the .Net Compact Framework it makes your application vanish instantly, in a completely untrappable way.

This may not be exactly what you're looking for, but on the other hand it may be exactly what you're looking for, since this is a fairly common source of intermittent errors when calling native DLLs from managed code (more generally, these kinds of errors can happen when you pass in structures that aren't scoped properly or haven't been "pinned", and thus can get disposed or moved by the GC while the native DLL is still working with them).

MusiGenesis