obfuz/Editor/Emit/RandomDataNodeCreator.cs

78 lines
2.6 KiB
C#
Raw Normal View History

2025-04-22 08:13:58 +08:00

using Obfuz.Utils;
using Obfuz.Emit.DataNodes;
using Obfuz.Emit.Functions;
2025-04-22 08:13:58 +08:00
using System.Collections.Generic;
namespace Obfuz.Emit
2025-04-22 08:13:58 +08:00
{
public class RandomDataNodeCreator : DataNodeCreatorBase
{
private readonly Dictionary<DataNodeType, List<IFunction>> _functions = new Dictionary<DataNodeType, List<IFunction>>();
2025-04-22 19:34:46 +08:00
private readonly IRandom _random;
2025-04-22 08:13:58 +08:00
2025-04-22 19:34:46 +08:00
public RandomDataNodeCreator(IRandom random)
2025-04-22 08:13:58 +08:00
{
2025-04-22 19:34:46 +08:00
_random = random;
var intFuncs = new List<IFunction>()
2025-04-22 08:13:58 +08:00
{
2025-04-23 10:49:18 +08:00
new IntAdd(),
new IntXor(),
2025-04-23 10:28:27 +08:00
new IntRotateShift(),
//new ConstFromFieldRvaDataCreator(),
//new ConstDataCreator(),
2025-04-22 08:13:58 +08:00
};
_functions.Add(DataNodeType.Int32, intFuncs);
_functions.Add(DataNodeType.Int64, intFuncs);
var floatFuncs = new List<IFunction>()
{
new MemoryCastIntAsFloat(),
};
_functions.Add(DataNodeType.Float32, floatFuncs);
_functions.Add(DataNodeType.Float64, floatFuncs);
var stringFuncs = new List<IFunction>()
{
new ConstFieldDataCreator(),
};
_functions.Add(DataNodeType.String, stringFuncs);
2025-04-23 13:46:50 +08:00
var bytesFuncs = new List<IFunction>()
{
new BytesInitializeFromFieldRvaDataCreator(),
};
_functions.Add(DataNodeType.Bytes, bytesFuncs);
2025-04-22 08:13:58 +08:00
}
public override IDataNode CreateRandom(DataNodeType type, object value, CreateExpressionOptions options)
{
if (!_functions.TryGetValue(type, out var funcs))
{
throw new System.Exception($"No functions available for type {type}");
}
2025-04-23 10:49:18 +08:00
if (options.depth >= 4)
2025-04-22 08:13:58 +08:00
{
2025-04-22 19:34:46 +08:00
//return new ConstDataNode() { Type = type, Value = value };
2025-04-23 10:28:27 +08:00
return _random.NextInt(100) < 50 ?
//return true ?
new ConstFromFieldRvaDataNode() { Type = type, Value = value } :
new ConstDataNode() { Type = type, Value = value };
2025-04-22 08:13:58 +08:00
}
var func = funcs[options.random.NextInt(funcs.Count)];
2025-04-22 10:42:58 +08:00
return func.CreateExpr(type, value, options);
2025-04-22 08:13:58 +08:00
}
public IDataNode CreateRandom(DataNodeType type, object value)
{
var options = new CreateExpressionOptions
{
depth = 0,
random = _random,
expressionCreator = this,
};
return CreateRandom(type, value, options);
}
}
}