Finalizers and the nasty stuff plug-ins can do if they want to...

One of the worst things I've ever found is a finalizer that does an endless loop.  This will seriously take your entire system down until you kill the process running the high priority GC thread.  I've found that you can get around the finalizer by calling GC.SuppressFinalize and passing in the object instance where you don't want your finalizer run.  Basically what I'm after now is:

Is this a true guarantee that the finalizer won't be run?
They require high security permissions to re-register.  If I lock them down to Execute permissions only can I be guaranteed they can't re-register?

Running arbitrary code is dangerous and I'd love to be able to lock things down to make it completely safe.  Given access to IL level hacks people can do some nasty stuff (the various types of stack overflows that render managed threads unable to be aborted for instance).

Anyway, to check out the GC finalizer issue, simply compile the code below.  If you comment out the SuppressFinalize call you'll see the impact on your system.  I was playing some MP3 files in Media Player and thought for a second they had been recorded with a skip because my system was being starved for CPU time due to the GC thread hanging.

using System;

public class ClassWithFinalizer {
    private string name;
   
    public ClassWithFinalizer(string name) {
        this.name = name;
    }

    ~ClassWithFinalizer() {
        Console.WriteLine(name);
       
        while(true) { }
    }
}

public class Runner {
    private static void Main(string[] args) {
        ClassWithFinalizer[] classes = new ClassWithFinalizer[10];
       
        for(int i = 0; i < classes.Length; i++) {
            classes[i] = new ClassWithFinalizer(i.ToString());
            GC.SuppressFinalize(classes[i]);
            classes[i] = null;
        }
       
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

Published Sunday, February 01, 2004 2:33 AM by Justin Rogers
Filed under:

Comments

Tuesday, February 03, 2004 9:18 PM by Brian Grunkemeyer

# re: Finalizers and the nasty stuff plug-ins can do if they want to...

There isn't much you can do to stop this. GC.ReRegisterForFinale does not have any security permissions on it, not even any host protection permission in our Whidbey builds.

One thing you could do is write your own "IL verifier", where you only load code that meets your programming model constraints. IE, disallow all static variables, or reject any classes that provide a finalizer (noting that Object of course has a finalizer - just test this rule on some conforming types).

Leave a Comment

(required) 
(required) 
(optional)
(required)