I have code to detect when an exception is created inside of a method like so:
foreach (var instr in body.Instructions)
{
if (instr.OpCode.Code == Code.Newobj)
{
var methRef = (Mono.Cecil.MethodReference)instr.Operand;
var type = Type.GetType(methRef.DeclaringType.FullName);
if (typeof(System.Exception).IsAssignableFrom(type))
// do stuff
}
}
full code here.
So far this is working well for straight forward code, but in the case where I'm dealing with a closure it obviously won't work because the exception is inside of a method on the object generated for the closure, not in the method that I am currently testing. The exception in:
private static int DataAccessMethod(int value)
{
int r = 0;
System.Threading.ManualResetEvent evt = new System.Threading.ManualResetEvent(false);
var workItem = System.Threading.ThreadPool.QueueUserWorkItem((_) =>
{
if (r == 0)
{
throw new System.InvalidOperationException("I canr spell.");
}
r = value * value;
evt.Set();
});
evt.WaitOne();
return r;
}
for instance will go undetected. My question is:
Is there anyway to detect that the operand to newobj is referring to a closure type?
As #usr noted in comments closures are just normal classes, they doesn't exist distinctly in IL. Only difference is you've not created it; compiler did it for you.
I believe you should be looking at unique compiler generated names to find them. EricLippert describes naming conventions followed by compiler here, Do note that it is subject to change in future versions of compiler.
Also after coming to the conclusion that the Type is a closure you can verify that using CompilerGenerated attribute.
Related
Recently I tried applying Maybe monad pattern in my C# code using this library.
What I found difficult to grasp was converting such a function into Maybe paradigm:
public Maybe<object> DoSomething(IReader reader)
{
while (true)
{
var result = reader.Read();
if (result == null) return Maybe<object>.Nothing;
if (result.HasValue) return new Maybe<object>(null);
}
}
I would like to have it written using from x in X form. The functionality that stands behind this function is to read IReader until it returns a value (Maybe has a value) or an error occurs (null gets returned).
the answer to your comment/question is: you don't - yeah you could try it using recursive calls but this might fail horrible in C# and you are way better of with the while
from x in X is just the monadic - bind (it get's translated into the SelectMany functions) and there is just no direct way in the LINQ syntax for this.
But you can write your own function like this:
public tValue DoUntilSome<tValue>(Func<Maybe<tValue>> f)
{
while (true)
{
var x = f();
if (x.HasValue) return x.Value;
}
}
and call like (see below)
var result = DoUntilSome(() => TryRead(reader));
remarks
first the Maybe<object> (object) part is a smell - because you most certainly want a concrete type in there instead of the generic object
Then new Maybe<object>(null) is very strange too
I would have suggested something like:
public Maybe<tValue> TryRead<tValue>(IReader reader)
{
var result = reader.Read();
if (result == null || !result.HasValue)
return Maybe<tValue>.Nothing;
return new Maybe<tValue>((tValue)reader.Value);
}
then of course this part is there to get some Maybe value - the thing you are trying to do with from x in X is the monadic-bind - which you can only use once you have a Maybe to start with:
from value in TryRead<tValue>(reader)
from other in TrySomethingDifferent(value) // here is the bind
select ....
disclaimer
I did not compile any of this (because I was to lazy to download the github project and stuff) - put you should be able to easily solve any syntax errors that might hide there - sorry for that
In case you have major troubles just leave a comment
I am writing a component that involves Actions and came upon a requirement to find a way to identify using reflection cases when the Action.Target object is a closure that the compiler have generated. I am doing an experiment to try and find a way, the purpose of this little experiment is to develop a predicate that takes an Action and returns a bool that tells if the action target is an instance of such closure class.
In my test case, I have the following methods that create 4 different types of actions:
private void _createClosure(int i)
{
ClosureAction = new Action(() =>
{
var j = i;
var k = somenum;
});
}
private void _createLambda()
{
LambdaAction = new Action(() =>
{
this._instanceAction();
});
}
private void _createInstance()
{
InstanceAction = new Action(_instanceAction);
}
private void _createStatic()
{
StaticAction = new Action(_staticAction);
}
private int somenum;
private void _instanceAction()
{
somenum++;
}
private static void _staticAction()
{
}
The following table shows the properties of each action:
As you see, LambaAction and ClosureAction are quite similar in terms of defnition, they both use lambda, but the closure one has a local function variable that is being used inside the lambda, and therefore the compiler is forced into generating a closure class. Its clear that the second row, the one that presents ClosureAction, is the only one that has a target that is a closure type. The static one does not have a target at all, and the other two use the calling class (Called ActionReferences) as target. The next table presents a comparison of the target reflection type properties:
So we can see that what's unique about the closure case is that the target type is not a type info but rather a nested type. It's also the only one that is private nested, sealed and has a name that contains the string +<>c__DisplayClass. Now while I think that these characteristics are conclusive for any normal usage case, I would prefer to define a predicate that I can rely on. I don't like to base this mechanism on compilers naming conventions or properties that are not unique because technically, the user may create a private nested sealed class with the same naming convention... it's not likely, but it's not 100% clean solution.
So finally - the question is this: Is there a clean cut way to write a predicate the identifies actions that are actually compiler generated closures?
Thanks
This isn't 100% accurate, but it generally works:
bool isClosure = action.Target != null && Attribute.IsDefined(
action.Target.GetType(), typeof(CompilerGeneratedAttribute));
Console.WriteLine(isClosure);
You can of course force false positives just by manually adding [CompilerGenerated] to any type you choose.
You could also use action.Method.DeclaringType, but since all captures involve a target instance, it is useful to retain the Target check:
bool isClosure = action.Target != null && Attribute.IsDefined(
action.Method.DeclaringType, typeof(CompilerGeneratedAttribute));
Using Roslyn, my aim is to check if a method parameter is checked for not being null before the parameter is dereferenced. This check can be in a submethod of course.
My approach is to get the first dereferencing of the parameter and search the syntax tree between that and the method start for null checks. How can I do some kind of control flow analysis to determine if the first dereferencing of the parameter can be reached with the parameter being null?
This is way too broad question, with a little explanation what is your final goal. Are you trying to detect null-pointer exceptions before they even happen, 100%? (Pretty much impossible)
I have written static analysis myself few months ago, I didn't use roslyn, but this doesn't matter.
Check this out to get you possibly started - it's reporting warnings when there are unused variables:
internal class UnUsedVariableWarningDefinition : ICodeIssue
{
public IEnumerable<IssueReport> Analyze()
{
var usageMap = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase);
var variableMap = new Dictionary<string, IdentifierNode>(StringComparer.InvariantCultureIgnoreCase);
foreach (var node in NodeAnalyzerHelper.FindNodesDfs(Root))
{
var assignmentNode = node as AssignmentNode;
if (assignmentNode != null)
{
var variableNode = assignmentNode.Identifier;
int usages;
if (!usageMap.TryGetValue(variableNode.Identifier, out usages))
{
usageMap[variableNode.Identifier] = 0;
variableMap[variableNode.Identifier] = variableNode;
}
}
else
{
// not really an assignmentNode,
// let's see if we have detected the usage of IdentifierNode somewhere.
var variableNode = node as IdentifierNode;
if (variableNode != null)
{
if (usageMap.ContainsKey(variableNode.Identifier))
usageMap[variableNode.Identifier]++;
}
}
}
foreach (var node in usageMap.Where(x => x.Value == 0).Select(x => variableMap[x.Key]))
{
yield return node.ConstructWarning("No usages of this variable found. Are you sure this is needed?");
}
}
}
Notice that FindNodesDfs() is basically a syntax tree walker, which walks syntax nodes depth-first style. What it does is just scans AssigfnmentNodes and puts them to Dictionary, as soon as it identifies IdentifierNode, it checks the dictionary if it has previously encountered assignment, or not. It's a bit similiar what you're trying to do, I guess.
What is the proper way to create a variable that will house a list of anonymous objects that are generated through a LINQ query while keeping the variable declaration outside of a try/catch and the assignment being handled inside of a try/catch?
At the moment I'm declaring the variable as IEnumberable<object>, but this causes some issues down the road when I'm trying to use it later...
i.e.
var variableDeclaration;
try{
...
assignment
...
}catch...
EDIT:
If it's relevant (don't think it is) the list of objects is being returned as a Json result from an MVC3 action. I'm trying to reduce the time that some using statements are open with the DB as I'm having some performance issues that I'm trying to clear up a bit. In doing some of my testing I came across this issue and can't seem to find info on it.
EDIT 2:
If I could request the avoidance of focusing on LINQ. While LINQ is used the question is more specific to the scoping issues associated with Anonymous objects. Not the fact that LINQ is used (in this case) to generate them.
Also, a couple of answers have mentioned the use of dynamic while this will compile it doesn't allow for the usages that I'm needing later on the method. If what I'm wanting to do isn't possible then at the moment the answer appears to be to create a new class with the definition that I'm needing and to use that.
It's possible to get around this by creating a generic Cast method as outlined by Jon Skeet here. It will work and give you the intellisense you want. But, at this point, what's wrong with creating a custom type for your linq method?
public class MyClass
{
public int MyInt { get; set; }
}
IEnumerable<MyClass> myClass =
//Some Linq query that returns a collection of MyClass
Well, if you're using LINQ, the query is not evaluated unless materialized...
So, you might be able to:
var myQuery = //blah
try
{
myQuery = myQuery.ToList(); //or other materializing call
}
catch
{
}
Could you perhaps get away with using dynamic ??
dynamic variableDeclaration;
try
{
variableDeclaration = SomeList.Where(This => This == That);
}
catch { }
Not sure what this will affect further in your code block, but just a thought :)
If you are declaring the variable ahead of using it like a try/catch you can't use [var] as it is intendend. Instead you have to type the the variable.
var x = 0;
try{
x = SomethingReturningAnInt();
}
or
int x;
try{
x = SomethingReturningAnInt();
}
However in your case you don't really "know" what the method returns
var x = ...;
try{
x = Something();
}
catch{}
won't work
Option you have when you don't know the type in advance is use of dynamic:
dynamic x;
try{
x = Something();
}
catch{}
(But that feels like going back to VB4)
Another cheat: you can define variable locally (similarly to Jon's hack in Dave Zych answer) and than use it inside try/catch. As long as you can create the same anonymous item type before try-catch you are OK (as anonymous types wit the same field names and types are considered the same):
var myAnonymouslyType = Enumerable.Repeat(
new {Field1 = (int)1, Field2 = (string)"fake"}, 0);
try
{
myAnonymouslyType = ...(item =>
new {Field1 = item.Id, Field2=item.Text})...
}
...
This is safer option than covered in Jon's casting of anonymous types between functions because compiler will immediately find errors if types don't match.
Note: I'd vote for non-anonymous type if you have to go this way...
Note 2: depending on your actual need consider simply returning data from inside try/catch and having second return of default information outside.
This has vexed me for a while. In the end I've build some Generic helper methods where I can pass in the code that generates the anonymous objects, and the catch code as lamdas as follows
public static class TryCatch
{
public static T Expression<T>(Func<T> lamda, Action<Exception> onException)
{
try
{
return lamda();
}
catch(Exception e)
{
onException(e);
return default(T);
}
}
}
//and example
Exception throwexception = null;
var results = TryCatch.Expression(
//TRY
() =>
{
//simulate exception happening sometimes.
if (new Random().Next(3) == 2)
{
throw new Exception("test this");
}
//return an anonymous object
return new { a = 1, b = 2 };
} ,
//CATCH
(e) => { throwexception = e;
//retrow if you wish
//throw e;
}
);
https://gist.github.com/klumsy/6287279
One can enumerate the called method parameter types/information like this:
private void SomeMethod(int thisValue, string thatValue)
{
StackTrace stackTrace = new StackTrace();
foreach (ParameterInfo pInfo in stackTrace.GetFrame(0).GetMethod().GetParameters())
{
string name = pInfo.Name;
string type = pInfo.GetType().ToString();
}
}
But is there any way to get the actual object of each parameter?
EDIT:
My goal is to enumerate all parameters and get their values.
Using LinQ Expressions, one can get the parameter value like so:
private void SomeMethod(int thisValue, string thatValue)
{
object valueOfThis = GetParameterValue(() => thisValue);
object valueOfThat = GetParameterValue(() => thatValue);
}
private object GetParameterValue<T>(Expression<Func<T>> expr)
{
var body = ((MemberExpression)expr.Body);
return ((FieldInfo)body.Member).GetValue(((ConstantExpression)body.Expression).Value);
}
But what I would like to do is something like:
foreach (fooObject o in thisMethod.GetParameterObjects())
{
object someValue = GetParameterValue(() => fooObject);
}
And thereby have a generic method for collection all parameters and their values.
UPDATE:
Looks like I "overcomplicated" the initial answer by trying to explain everything. Here is the short version of the answer.
private static void SomeMethod(int thisValue, string thatValue)
{
IEnumerable<object> parameters = GetParameters(() => SomeMethod(thisValue, thatValue));
foreach (var p in parameters)
Console.WriteLine(p);
}
private static IEnumerable<object> GetParameters(Expression<Action> expr)
{
var body = (MethodCallExpression)expr.Body;
foreach (MemberExpression a in body.Arguments)
{
var test = ((FieldInfo)a.Member).GetValue(((ConstantExpression)a.Expression).Value);
yield return test;
}
}
And here is the long version with some explanations.
In fact, if you use expression trees, you don't need to be inside a method to enumerate its parameters.
static void Main(string[] args)
{
// First approach.
IEnumerable<object> parameters = GetParametersFromConstants(() => SomeMethod(0, "zero"));
foreach (var p in parameters)
Console.WriteLine(p);
// Second approach.
int thisValue = 0;
string thatValue = "zero";
IEnumerable<object> parameters2 = GetParametersFromVariables(() => SomeMethod(thisValue, thatValue));
foreach (var p in parameters2)
Console.WriteLine(p);
Console.ReadLine();
}
private static void SomeMethod(int thisValue, string thatValue)
{
Console.WriteLine(thisValue + " " + thatValue);
}
private static IEnumerable<object> GetParametersFromVariables(Expression<Action> expr)
{
var body = (MethodCallExpression)expr.Body;
foreach (MemberExpression a in body.Arguments)
{
var test = ((FieldInfo)a.Member).GetValue(((ConstantExpression)a.Expression).Value);
yield return test;
}
}
private static IEnumerable<object> GetParametersFromConstants(Expression<Action> expr)
{
var body = (MethodCallExpression)expr.Body;
foreach (ConstantExpression a in body.Arguments)
{
var test = a.Value;
yield return test;
}
}
}
Note, that if you use expression trees, your code depends a lot on an expression passed to the method. I have shown one using constants and one using variables. But of course there can be more scenarios. You can refactor this code to use a single method for both cases, but I decided that is illustrates the problem better this way.
Okay, so here's the deal.
You can not do that, not from a managed language. I don't see how anyone would allow you to take control of the stack frame. And in a way that's what you want. Because you need the information to get the values.
Now the run-time knows this, it has all the information, but you can not make assumptions on how it will go about creating a stack frame, because you are not meant to do this.
Ergo, there's only one way to go about this. The profiling API.
I end up here. Within the functions of the profiling API. I bet there's a way to do this that let's you dig into the parameter values by invoking a unmanaged class from managed code.
Now, I wouldn't do this because there's great profiling tools out there already, JetBrains dotTrace to name one and with IntelliTrace in VS2010 all these headaches will simply go away... IntelliTrace will let you do time traveling debugging.
The other and obvious way to do this is totally foobar, but might end up fun to experiment with, it can always be done this way, but I would never in my life put this code in a production environment.
// compile with unsafe
unsafe
{
var p = stackalloc int[1];
var baseAddr = p - sizeof(int);
}
Now, you can not write to baseAddr but you should be allowed to read it. The tricky part is to make sense of the stack frames and that has to with the calling convention and that you must know for certain a head of time. Here's a run down of that stuff and it's fastcall.
With this information and the ParameterInfo objects you should be able to walk your way through the arguments.
Since you'll be working with raw pointers you'll need to make those into managed objects, and there's a class for that.
There you go, go nuts!
A big warning though, what you'll find as you walk up the stack, won't be what you expect. Because arguments can be placed in registers and registers can not be accessed from within managed code.
You can use MethodInfo.GetCurrentMethod().GetParameters() to get a list of method parameters. But it's impossible to get their values by reflection.