Determine if a method is unsafe with reflection

I am looking for a way to filter out methods that have an unsafe modifier through reflection. This is not like a method attribute.

Is there any way?

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

EDIT 2:. For my needs, I received a check that suggests that if one of the method parameters is a pointer or the 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 does not handle, of course, the situation when an unsafe block is executed in a method, but again, all that interests me is the signature of the method.

Thanks!

+7
reflection c # unsafe
source share
3 answers

Unfortunately, the unsafe keyword simply wraps the method body in an insecure block and does not emit anything that could be reflected. The only way to be sure is to parse the method and see if there are any unsafe operations inside.

+4
source share

This is the job of the IL verifier. PEVerify.exe in the Windows SDK bin directory. It checks IL in bodies of methods and flags of unsafe IL. Pointers, basically. You will get a pretty large list if you free it on the system.dll assembly.

Please note that he refuses to check mscorlib.dll, you are pretty stuck if he is interested in you. Copying and renaming does not help.

+2
source share

Do not think that there is a way out of the box. If the code you reflect is yours, you can create your own UnsafeAttribute and mark these methods with an attribute and a filter on this ...

0
source share

All Articles