obfuz/Editor/ObfusPasses/MemEncrypt/MemoryEncryptionPass.cs

100 lines
3.0 KiB
C#
Raw Normal View History

2025-04-30 21:47:21 +08:00
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using Obfuz;
2025-05-04 19:55:10 +08:00
using Obfuz.ObfusPasses.MemEncrypt;
2025-04-30 21:47:21 +08:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
2025-05-04 19:55:10 +08:00
namespace Obfuz.ObfusPasses.MemEncrypt
2025-04-30 21:47:21 +08:00
{
2025-05-04 19:55:10 +08:00
public class MemoryEncryptionPass : InstructionObfuscationPassBase
2025-04-30 21:47:21 +08:00
{
private readonly IEncryptionPolicy _encryptionPolicy = new ConfigEncryptionPolicy();
2025-04-30 22:40:16 +08:00
private readonly IMemoryEncryptor _memoryEncryptor = new DefaultMemoryEncryptor();
2025-04-30 21:47:21 +08:00
2025-05-04 19:24:14 +08:00
public override void Start(ObfuscationPassContext ctx)
2025-04-30 21:47:21 +08:00
{
}
2025-05-04 19:24:14 +08:00
public override void Stop(ObfuscationPassContext ctx)
2025-04-30 21:47:21 +08:00
{
}
protected override bool NeedObfuscateMethod(MethodDef method)
{
return true;
}
private FieldDef TryResolveFieldDef(IField field)
{
if (field is FieldDef fieldDef)
{
return fieldDef;
}
if (field is MemberRef memberRef)
{
return memberRef.ResolveFieldDef();
}
throw new System.Exception($"Cannot resolve field: {field}");
}
protected override bool TryObfuscateInstruction(MethodDef callingMethod, Instruction inst, IList<Instruction> instructions, int instructionIndex, List<Instruction> outputInstructions, List<Instruction> totalFinalInstructions)
{
Code code = inst.OpCode.Code;
if (!(inst.Operand is IField field))
{
return false;
}
FieldDef fieldDef = TryResolveFieldDef(field);
if (fieldDef == null)
{
return false;
}
if (!_encryptionPolicy.NeedEncrypt(fieldDef))
{
return false;
}
2025-04-30 22:40:16 +08:00
var ctx = new MemoryEncryptionContext
{
module = callingMethod.Module,
currentInstruction = inst,
};
2025-04-30 21:47:21 +08:00
switch (code)
{
case Code.Ldfld:
{
2025-04-30 22:40:16 +08:00
_memoryEncryptor.Decrypt(fieldDef, outputInstructions, ctx);
2025-04-30 21:47:21 +08:00
break;
}
case Code.Stfld:
{
2025-04-30 22:40:16 +08:00
_memoryEncryptor.Encrypt(fieldDef, outputInstructions, ctx);
2025-04-30 21:47:21 +08:00
break;
}
case Code.Ldsfld:
{
2025-04-30 22:40:16 +08:00
_memoryEncryptor.Decrypt(fieldDef, outputInstructions, ctx);
2025-04-30 21:47:21 +08:00
break;
}
case Code.Stsfld:
{
2025-04-30 22:40:16 +08:00
_memoryEncryptor.Encrypt(fieldDef, outputInstructions, ctx);
2025-04-30 21:47:21 +08:00
break;
}
case Code.Ldflda:
case Code.Ldsflda:
{
throw new System.Exception($"You shouldn't get reference to memory encryption field: {field}");
}
default: return false;
}
2025-05-03 20:42:08 +08:00
//Debug.Log($"memory encrypt field: {field}");
2025-04-30 21:47:21 +08:00
return true;
}
}
}