Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if method is unsafe via reflection

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!

like image 766
Igal Tabachnik Avatar asked Jun 15 '10 11:06

Igal Tabachnik


1 Answers

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.

like image 53
Adam Ruth Avatar answered Oct 05 '22 06:10

Adam Ruth