views:

114

answers:

3

I'm looking for a way to filter out methods which have the unsafe modifier via reflection. It doesn't seem to be a method attribute.

Is there a way?

EDIT: it seems that this info is not in the metadata, at least I can't see it in the IL. However reflector shows the unsafe modifier in C# view. Any ideas on how it's done?

EDIT 2: For my needs I ended up with a check, that assumes that if one of the method's parameters is a pointer, or a return type is a pointer, then the method is unsafe.

    public static bool IsUnsafe(this MethodInfo methodInfo)
    {
        if (HasUnsafeParameters(methodInfo))
        {
            return true;
        }

        return methodInfo.ReturnType.IsPointer;
    }

    private static bool HasUnsafeParameters(MethodBase methodBase)
    {
        var parameters = methodBase.GetParameters();
        bool hasUnsafe = parameters.Any(p => p.ParameterType.IsPointer);

        return hasUnsafe;
    }

This doesn't handle, of course, a situation where an unsafe block is executed within a method, but again, all I am interested in is the method signature.

Thanks!

A: 

Don't think there is a way out of the box. If the code you're reflecting is yours, you can create your own UnsafeAttribute and tag those methods with the attribute and filter on that...

Koen
Thanks, but I'm actually trying to filter our `mscorlib` types...
hmemcpy
+1  A: 

Unfortunately the unsafe keyword simply wraps the body of the method in an unsafe block and doesn't emit anything that reflection would see. The only way to be certain is to disassemble the method and see if there are any unsafe operations inside.

Adam Ruth
I'd also think that if you could see it with reflection, they would have a property for us on MethodInfo...
Koen
It'd be nice, but unfortunately the unsafe keyword is a C# thing, not an IL thing. IL has unsafe operations but no concept of the unsafe keyword.
Adam Ruth
Thank you, Adam. I am accepting this answer because this is the conclusion I reached myself.
hmemcpy
+2  A: 

That's the job of an IL verifier. PEVerify.exe in the Windows SDK's bin directory. It verifies the IL in the method bodies and flags unsafe IL. Pointers, mostly. You'll get a fairly big list if you let it loose on the system.dll assembly.

Note that it refuses to verify mscorlib.dll, you're pretty stuck if that's the one you care about. Copying and renaming it doesn't help.

Hans Passant