Skip to content

Commit

Permalink
Fix issue with branching to swapped stfld -> callvirt
Browse files Browse the repository at this point in the history
Given the (abridged) psuedo-IL
```asm
ldfld PlayerData ...

ldfld bool   ...
brtrue.s     :opt

ldfld string ..
br.s         :set

opt:
ldfld string ...

set: stfld PlayerData::someField
```

We were patching it to the following:
```asm
ldfld PlayerData ...

ldfld bool   ...
brtrue.s     :opt

ldfld string ...
br.s         :set

opt:
ldfld string ...

ldstr "someField"
set: callvirt instance void PlayerData::SetStringSwappedArgs(string, string)
```

and the way we did this patching is by swapping an `stfld` to a `callvirt`
and then inserting the `ldstr` for the field name (which is the second arg
for our SetStringSwappedArgs) before this `callvirt` we inserted.
However, given this situation, we skip over the ldstr of the field name
when coming from the `false` branch path as it branches directly to
`set` as it had previously branched directly to an `stfld` and branching
is instruction location based.

The fix for this is relatively simple, just swap the `stfld` with the
`ldstr` instead, and then insert our `callvirt` afterwards, which gives
the following:

```asm
ldfld PlayerData ...

ldfld bool   ...
brtrue.s     :opt

ldfld string ...
br.s         :set

opt:
ldfld string ...

set: ldstr "someField"
callvirt instance void PlayerData::SetStringSwappedArgs(string, string)
```
  • Loading branch information
fifty-six committed May 21, 2022
1 parent 1472b8f commit c50b65e
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions PrePatcher/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,11 @@ ILProcessor il
generic.GenericArguments.Add(field.FieldType);
callSet = Instruction.Create(OpCodes.Callvirt, generic);
}

il.InsertAfter(instr, callSet);

instr.OpCode = callSet.OpCode;
instr.Operand = callSet.Operand;

il.InsertBefore(instr, ldstr);
instr.OpCode = ldstr.OpCode;
instr.Operand = ldstr.Operand;
}

private static void SwapLdFld
Expand Down Expand Up @@ -259,11 +259,11 @@ ILProcessor il
generic.GenericArguments.Add(field.FieldType);
callGet = Instruction.Create(OpCodes.Callvirt, generic);
}

il.InsertAfter(instr, callGet);

instr.OpCode = callGet.OpCode;
instr.Operand = callGet.Operand;

il.InsertBefore(instr, ldstr);
instr.OpCode = ldstr.OpCode;
instr.Operand = ldstr.Operand;
}

private static MethodDefinition GenerateSwappedMethod(TypeDefinition methodParent, MethodReference oldMethod)
Expand Down

0 comments on commit c50b65e

Please sign in to comment.