Search code examples
.netaop

Is there an aspect weaver that can amend method implementation with no clear pointcut?


Is there any practical way to patch a fragment of business logic buried deep within a method that doesn't have a unique signature of types/members touched?

If the base implementation (in a binary-only component) is structured like this:

class PastaPlate
{
    int mode;
    double increment;
    bool fullTiltBoogieMode;

    void Loop()
    {
        while(true)
        {
            // 1000 lines of spaghetti, which may or may not mutate mode
            if (mode == 7) increment = 42.0;
            if (mode == 13) increment = -0.666;
            if (mode == 8) increment = 64.0;
            if (mode == 666) increment = -0.666;
            // 1000 more lines of spaghetti which depend on mode and increment
        }
    }
}

Suppose I wanted to introduce another if statement over mode after if (mode == 8), or modify the consequent for if (mode == 13) to change the value of increment without modifying if (mode == 666). Is there an aspect weaver or other IL-modification tool that can support this sort of painful use case?


Solution

  • I've taken the approach of writing these sorts of amenders (I hesitate to call them aspects, since some are so narrowly applicable as to be the moral equivalent of monkey-patches) as straightforward Cecil-based console applications: read in the target assembly, navigate through the metadata and IL, amend as desired, then write the modified assembly back out.

    Fody essentially provides an MSBuild extension point for running a pipeline of Cecil amenders, which is useful in the context of a project build but less so for patching third-party binaries.