-
-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathNewArm64Utils.cs
More file actions
82 lines (67 loc) · 2.74 KB
/
NewArm64Utils.cs
File metadata and controls
82 lines (67 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Linq;
using Disarm;
using LibCpp2IL;
namespace Cpp2IL.Core.Utils;
public static class NewArm64Utils
{
public static List<Arm64Instruction> GetArm64MethodBodyAtVirtualAddress(ulong virtAddress, bool managed = true, int count = -1)
{
if (managed)
{
var startOfNext = MiscUtils.GetAddressOfNextFunctionStart(virtAddress);
//We have to fall through to default behavior for the last method because we cannot accurately pinpoint its end
if (startOfNext > 0)
{
var rawStartOfNextMethod = LibCpp2IlMain.Binary!.MapVirtualAddressToRaw(startOfNext);
var rawStart = LibCpp2IlMain.Binary.MapVirtualAddressToRaw(virtAddress);
if (rawStartOfNextMethod < rawStart)
rawStartOfNextMethod = LibCpp2IlMain.Binary.RawLength;
var bytes = LibCpp2IlMain.Binary.GetRawBinaryContent().Slice((int)rawStart, (int)(rawStartOfNextMethod - rawStart));
return Disassemble(bytes.Span, virtAddress);
}
}
//Unmanaged function, look for first b
var pos = (int)LibCpp2IlMain.Binary!.MapVirtualAddressToRaw(virtAddress);
var allBytes = LibCpp2IlMain.Binary.GetRawBinaryContent();
var span = allBytes.Slice(pos, 4).Span;
List<Arm64Instruction> ret = [];
while ((count == -1 || ret.Count < count) && !ret.Any(i => i.Mnemonic is Arm64Mnemonic.B || i.Mnemonic is Arm64Mnemonic.INVALID))
{
ret = Disassemble(span, virtAddress);
//All arm64 instructions are 4 bytes
span = allBytes.Slice(pos, span.Length + 4).Span;
}
return ret;
}
private static List<Arm64Instruction> Disassemble(ReadOnlySpan<byte> bytes, ulong virtAddress)
{
try
{
return Disassembler.Disassemble(bytes, virtAddress, new Disassembler.Options(true, true, false)).ToList();
}
catch (Exception e)
{
throw new($"Failed to disassemble method body: {string.Join(", ", bytes.ToArray().Select(b => "0x" + b.ToString("X2")))}", e);
}
}
public static List<Arm64Instruction> ToList(this Disassembler.SpanEnumerator enumerator)
{
var ret = new List<Arm64Instruction>();
while (enumerator.MoveNext())
{
ret.Add(enumerator.Current);
}
return ret;
}
public static Arm64Instruction LastValid(this List<Arm64Instruction> list)
{
for (var i = list.Count - 1; i >= 0; i--)
{
if (list[i].Mnemonic is not (Arm64Mnemonic.INVALID or Arm64Mnemonic.UNIMPLEMENTED))
return list[i];
}
return list[^1];
}
}