ioncodes / dnpatch

.NET Patcher library using dnlib
MIT License
313 stars 48 forks source link

Patched target is about 40KB smaller than original file after saving to disk #58

Closed JesYo closed 3 years ago

JesYo commented 3 years ago

I wrote a simple program that loads a .NET compiled DLL, replaces a single instruction for a method, and then saves the resultant patch to a new file. When I inspect the new file, it's about 40KB smaller than the original, so it's obviously missing quite a bit from the original assembly. When I inspect the newly patched file, it looks like there are entire PE sections missing that were in the original. Do I need to use dnlib functions to manually read in all the PE sections and then re-write them to my newly patched file? Or am I forgetting to do something else to preserve all the original pieces of the file? Here's my code to give context:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using dnpatch;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
             /*
             * Replaces the instructions at the given index
             */
            Patcher p = new Patcher("MyOriginalFile.dll");
            Instruction opCodesManipulateOffset = Instruction.Create(OpCodes.Ldc_I4, 112);

            Target target = new Target()
                {
                    Namespace = "MyTargetNamespace",
                    Class = "MyTargetClass",
                    Method = "MyTargetMethod",
                    Instruction = opCodesManipulateOffset,
                    Index = 75,
                    Parameters = new[] { "Int32", "String", "String" }
                };
                p.Patch(target);
                p.Save("MyTargetPatchedFile.dll");

        }
    }
}
JesYo commented 3 years ago

I may have resolved this on my own. Turns out the assembly I was looking to patch was a mixed assembly -- so only the managed part was being written. I forklifted the pieces of dnpatch I needed to find the right method->instructions, but then used dnlib's NativeWrite in order to save the resultant assembly.