Tuesday, September 25, 2007

Be careful with reflection and delegates

For instance, you have pluggable application which runs set of assemblies (plugins), each in separate "sandbox" domain. Next code block included within "malicious" plugin causes application to crash:


class Program
{
static void Main(string[] args)
{
AppDomain newDomain = AppDomain.CreateDomain("NewDomain");
ObjectHandle oh = newDomain.CreateInstance(Assembly.GetExecutingAssembly().FullName, "CLRCrashApp.SomeClass");
((SomeClass)oh.Unwrap()).DoSomething();
}
}

public class SomeClass : MarshalByRefObject
{
private delegate void DoSomethingDelegate();
public SomeClass() : base()
{
}
public void DoSomething()
{
Console.WriteLine("AppDomain is: {0}", AppDomain.CurrentDomain.FriendlyName);
try
{
Activator.CreateInstance(typeof(DoSomethingDelegate), new object[] { null, null });
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.ToString());
}
}
finally
{
Console.WriteLine("Finally is executing...");
}
}
}

So, be careful when playing with reflection and delegates. Small mistake can cause crash of your entire application. Event separate AppDomain won't help you handle this.

In order to prevent such "malicious" plug-ins it is necessary to use CLR hosting API and host CLR by your own.

No comments:

 
Counter