philiplaureano/LinFu

Method Interception : "Common Language Runtime detected an invalid program."

Closed this issue · 3 comments

The exception occurs while executing the example Interception (MethodReplacement) program

public class SampleInterceptor : IInterceptor
{
public object Intercept(IInvocationInfo info)
{
var methodName = info.TargetMethod.Name;
Console.WriteLine("method '{0}' called", methodName);
object retValue = info.TargetMethod.Invoke(info.Target, info.Arguments); //Throws Exception : "Common Language Runtime detected an invalid program"
return retValue; //retValue is always null
}
}

I just updated the samples now with the latest LinFu binaries. Try it out and let me know if it works for you.

Well, now the following exception is being shown.

"JIT Compiler encountered an internal limitation."

Please note that this exception is being thrown from within the following method (class BankAccount):

public void Deposit(int amount)
{
_balance += amount;

        Console.WriteLine("Deposited: {0}", amount);
        Console.WriteLine("New Balance: {0}", Balance);

}

So, if I comment the above method call (Deposit()) within the Pay() method, the program works:

public void Pay(int wage)
{
var currentAmount = wage;
//_checkingAccount.Deposit(currentAmount);

        Console.WriteLine("Paid {0} units", wage);

}

However, my intention is to intercept all the methods and get return value correctly from within the target methods. For example:

Let's change the Pay() method to return an int

public int Pay(int wage)
{
var currentAmount = wage;
//_checkingAccount.Deposit(currentAmount);

        Console.WriteLine("Paid {0} units", wage);
        return wage;

}

And, Intercept the method call and also get the return value correctly from within the intercepted method as follows:

public object Intercept(IInvocationInfo info)
{
var methodName = info.TargetMethod.Name;
Console.WriteLine("method '{0}' called", methodName);

        // Replace the input parameter with 42
        var result = info.TargetMethod.Invoke(info.Target, new object[]{42});
        //Get the return value correctly from the target method. 
        return result;

}

Right now, the program throws the mentioned exception and hence not able to return correct value.

Thanks in advance for your effort.

Using a reflector, I took a look at the Weaven Pay() method, after modifying the Pay() as returning an int. There I found the following codes, alsong with the injected codes
...
int amount = wage;
this._checkingAccount.Deposit(amount);
Console.WriteLine("Paid {0} units", wage);
int num2 = wage;
....

return (int) obj2;

//Please note that, the obj2 is never assigned with a value and hence, the postweaven methods always return null. This may give you some clue.

Thanks