3

I have a C# dll with a member similar to the following:

public void DoStuff(int i) {
    try {
        something.InnerDoStuff(i);
    }
    catch (Exception ex) {
        throw ex;
    }
}

I figured out how to get the throw opcode:

Add-Type -Path 'c:\Program Files\ILSpy2\Mono.Cecil.dll'
Add-Type -Path 'c:\Program Files\ILSpy2\Mono.Cecil.pdb.dll'

$dll = 'c:\Program Files\ZippySoft\Something\foo.dll'
$assemblyDefinition = [Mono.Cecil.AssemblyDefinition]::ReadAssembly($dll);

$doThingsIlAsm = (
    (
        $assemblyDefinition.MainModule.Types `
            | where { $_.Name -eq 'DoerOfThings' } `
            | select -first 1 *
    ).Methods | where { $_.Name -eq 'DoStuff' }
).Body.Instructions 

$throwOp = ($doThingsIlAsm | where {
    $_.OpCode.Name -eq 'throw'
})

My question is how do I replace throw opcode with a rethrow opcode?

Justin Dearing
  • 14,270
  • 22
  • 88
  • 161
  • Your headline asks how to "replace" the opcode, but you have asked merely how to "get" it. Which are you interested in? – latkin Aug 23 '12 at 18:06

1 Answers1

3

I believe you can get an ILProcessor for your method, Create a rethrow opcode, and then use the processor's Replace method to swap the throw for a rethrow.

Instead of immediately getting your method body's instructions, get a reference to the method body and use it to get myMethod.Body.GetIlProcessor as well as myMethod.Body.Instructions. Then you can find the throw instruction as you already are, and use the Replace method to swap them out.

This is very untested, but I think the gist of it is:

$throw = # your existing stuff
$il = myMethod.Body.GetIlProcessor()
$rethrow = $il.Create(OpCodes.Rethrow) # not sure about the powershell syntax for enums
$il.Replace($throw, $rethrow)
goric
  • 11,491
  • 7
  • 53
  • 69