C
C#2y ago
Ruttie

✅ VerificationException

A friend of mine has a method that uses the Reflection.Emit namespace to create a method with the following IL:
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
if (fi.FieldType.IsValueType && typeof(TField) == typeof(object))
gen.Emit(OpCodes.Unbox_Any, fi.FieldType);

gen.Emit(OpCodes.Stfld, fi);
gen.Emit(OpCodes.Ret);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
if (fi.FieldType.IsValueType && typeof(TField) == typeof(object))
gen.Emit(OpCodes.Unbox_Any, fi.FieldType);

gen.Emit(OpCodes.Stfld, fi);
gen.Emit(OpCodes.Ret);
What will happen if the field we try to access here is private/internal? According to my friend, the code runs fine, but according to ChatGPT the following will happen:
13 Replies
Ruttie
Ruttie2y ago
Now that I've got the time to check it: It appears I can access private fields I shouldn't have access to. However, on .NET 4.7.2, I get a System.Security.VerificationException. Does anyone know how I could get around this? It only happens on the method call.
canton7
canton72y ago
You can do the usual trick of using reflection? Compiled expressions also have no problem accessing private fields IIRC, although they're compiled to IL
Ruttie
Ruttie2y ago
well yeah, but this approach has it's benefits over reflection
Ruttie
Ruttie2y ago
'Compiled expressions'?
Anton
Anton2y ago
Expression.Compile Method (System.Linq.Expressions)
Compiles the lambda expression described by the expression tree into executable code and produces a delegate that represents the lambda expression.
Anton
Anton2y ago
it's one level of abstraction above il emission, it works with expression trees
Ruttie
Ruttie2y ago
How would you use such an expression in this case?
Anton
Anton2y ago
you would build up the syntax tree effectively, and then compile it using that method there are factory functions for making syntax nodes
Ruttie
Ruttie2y ago
damn that's slow to build
Ruttie
Ruttie2y ago
but it works for .net472 so it's the only option ig I'm still curious about this though
Anton
Anton2y ago
idk you can browse their sources and see how that compile method is implemented it shouldn't be intrinsic
Ruttie
Ruttie2y ago
The problem is, the compile method doesn't throw it, it only gets thrown when trying to execute the method
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.