Code Injection With CCI - Part 2.5

You might be able to tell that I'm writing this series "on-the-fly" a little bit. That is, I'm finding out things as I go along from the Cecil-to-CCI migration. One thing I found out is that you can override the OpenBinaryDocument() methods and use UnmanagedBinaryMemoryBlock to prevent MetadataReaderHost from locking the assembly you load:

public override IBinaryDocumentMemoryBlock OpenBinaryDocument(
    IBinaryDocument parentSourceDocument, string childDocumentName)
{
    return UnmanagedBinaryMemoryBlock.CreateUnmanagedBinaryMemoryBlock(
        childDocumentName, parentSourceDocument);
}

public override IBinaryDocumentMemoryBlock OpenBinaryDocument(
    IBinaryDocument sourceDocument)
{
    return UnmanagedBinaryMemoryBlock.CreateUnmanagedBinaryMemoryBlock(
        sourceDocument.Location, sourceDocument);
}

Now I can save my changed assembly right back to the file:

PeWriter.WritePeToStream(module, host,
    File.Create(module.Location));

Sweet!

I'll continue on in Part 3 with method modification - specifically, adding label support to correct branch offset values.

* Posted at 04.29.2009 07:59:16 AM CST | Link *

Blog History