Skip to content

Castle allows to rewrite read-only parameters (in modifier) #369

Closed

Description

@zvirja

Consider the following code sample:

[Fact]
public void TestProxy()
{
    var proxy = new ProxyGenerator().CreateInterfaceProxyWithoutTarget<IInterfaceWithIn>(new RewritingInterceptor());
    
    var val = new MutableStruct { Value = 24 };
    proxy.DoNotMutate(val);

    Assert.Equal(24, val.Value);
}

public struct MutableStruct
{
    public int Value { get; set; }
}

public interface IInterfaceWithIn
{
    void DoNotMutate(in MutableStruct value);
}

public class RewritingInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        if (invocation.Method.Name == "DoNotMutate")
        {
            invocation.SetArgumentValue(0, new MutableStruct {Value = 42});
        }
    }
}

The issue happens because value is passed by ref, so technically it's possible to rewrite the value. However, like Roslyn, Castle should not allow to rewrite the value via API.

Likely, the fix should be placed somewhere here.

/cc: @stakx @blairconrad JFYI as our mock libraries contain tooling for this feature invocation.

Activity

  1. stakx commented on Jun 11, 2018

    @stakx
    Member

    Yes, this appears to be a problem. I believe we should add a check for in-ness of parameters here:

    if (!parameters[i].ParameterType.GetTypeInfo().IsByRef)

    We could additionally probe whether (parameters[i].Attributes & (ParameterAttributes.In | ParameterAttributes.Out)) == ParameterAtteibutes.In, and if so, not write back the argument value.

    (AFAIK, in parameters are marked in various ways, depending on the situation, but the IL [in] attribute should always be set. IIRC it is not set for regular by-value parameters unless maybe in COM interfaces.)

  2. stakx commented on Jun 11, 2018

    @stakx
    Member

    @zvirja - I've had a free afternoon and thought I'd tackle this. You were spot on with where the fix needs to go. 👍

  3. added this to the vNext milestone on Jun 12, 2018
  4. zvirja commented on Jun 13, 2018

    @zvirja
    Author

    @jonorossi Could you please release this bug fix on NuGet? At the NSubstitute side I would like to do the following:

    • Consume this version as a required to guarantee safety.
    • Write unit tests that our generated delegates propagate the in modifier correctly. To do that I would like to confirm that value is indeed read-only, but current I cannot write such a test.

    I believe it should be fine for Castle.Core to publish a bugfix release with increased revision.

    Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions