├── test
└── example
│ ├── .gitignore
│ ├── example.csproj
│ └── Program.cs
├── .gitignore
├── include
├── logger.hpp
├── native.hpp
├── method.hpp
├── dll.hpp
├── types.hpp
├── tables.hpp
├── context.hpp
├── file_headers.hpp
└── opcode.hpp
├── CMakeLists.txt
├── source
├── logger.cpp
├── native.cpp
├── main.cpp
├── dll.cpp
└── method.cpp
└── LICENSE
/test/example/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | bin/
3 | obj/
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | .idea/
3 |
4 | cmake-build-debug/
5 |
--------------------------------------------------------------------------------
/include/logger.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | namespace ili {
4 |
5 | class Logger {
6 | public:
7 | static constexpr bool DebugLogging = true;
8 |
9 | static void error(const char *format, ...);
10 | static void info(const char *format, ...);
11 | static void debug(const char *format, ...);
12 | };
13 |
14 | }
--------------------------------------------------------------------------------
/test/example/example.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | true
7 | true
8 | win-x64
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/test/example/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace example {
4 |
5 | static class Program
6 | {
7 | private static string test(string value) {
8 | Console.WriteLine(value);
9 |
10 | return "Hello";
11 | }
12 |
13 | static void Main()
14 | {
15 | Console.WriteLine(test("Test"));
16 | }
17 | }
18 |
19 | }
--------------------------------------------------------------------------------
/include/native.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | namespace ili {
7 |
8 | class Context;
9 |
10 | class NativeMethods {
11 | public:
12 | static void loadMSCORLIBLibrary(Context &ctx);
13 | static void loadNXLibrary(Context &ctx);
14 |
15 | static void registerMethod(Context &ctx, std::string methodName, std::function method);
16 | static void callMethod(Context &ctx, std::string methodName);
17 | };
18 |
19 | }
20 |
21 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.15)
2 | project(CSharpInterpreter)
3 |
4 | include_directories(CSharpInterpreter include)
5 |
6 | set(CMAKE_CXX_STANDARD 20)
7 |
8 | set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0")
9 | set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wall")
10 | set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O0")
11 | set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wall")
12 |
13 | add_executable(CSharpInterpreter source/main.cpp source/dll.cpp source/method.cpp source/logger.cpp source/native.cpp)
--------------------------------------------------------------------------------
/include/method.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "types.hpp"
4 | #include "context.hpp"
5 | #include "tables.hpp"
6 |
7 | namespace ili {
8 |
9 |
10 | class Method {
11 | public:
12 | Method(Context &ctx, u32 methodToken);
13 | ~Method();
14 | void run();
15 |
16 | private:
17 | Context &m_ctx;
18 | table_method_def_t *m_methodDef;
19 |
20 | u8 *m_programCounter;
21 |
22 | VariableBase *m_localVariable[0xFF] = { nullptr };
23 |
24 |
25 | // General Operations
26 |
27 | template
28 | T getNext();
29 |
30 | DLL* getDLL();
31 |
32 | // Instruction Implementations
33 |
34 | void stloc(u8 id);
35 | void ldloc(u8 id);
36 | void ldloca(u8 id);
37 | template
38 | void ldc(Type type, T num);
39 |
40 | void call(u32 methodToken);
41 | };
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/source/logger.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "logger.hpp"
4 |
5 | namespace ili {
6 |
7 | void Logger::error(const char *format, ...) {
8 | va_list ap;
9 | va_start(ap, format);
10 | printf("\033%s[%s]\033[0m ", "[0;31m", "ERROR");
11 | vprintf(format, ap);
12 | printf("\n");
13 | va_end(ap);
14 | }
15 |
16 | void Logger::info(const char *format, ...) {
17 | va_list ap;
18 | va_start(ap, format);
19 | printf("\033%s[%s]\033[0m ", "[0;34m", "INFO");
20 | vprintf(format, ap);
21 | printf("\n");
22 | va_end(ap);
23 | }
24 |
25 | void Logger::debug(const char *format, ...) {
26 | if (!Logger::DebugLogging)
27 | return;
28 |
29 | va_list ap;
30 | va_start(ap, format);
31 | printf("\033%s[%s]\033[0m ", "[0;32m", "DEBUG");
32 | vprintf(format, ap);
33 | printf("\n");
34 | va_end(ap);
35 | }
36 |
37 | }
--------------------------------------------------------------------------------
/source/native.cpp:
--------------------------------------------------------------------------------
1 | #include "native.hpp"
2 |
3 | #include "context.hpp"
4 | #include "dll.hpp"
5 |
6 |
7 |
8 | namespace ili {
9 |
10 | void NativeMethods::registerMethod(Context &ctx, std::string methodName, std::function method) {
11 | ctx.nativeFunctions.insert({ methodName, method });
12 | }
13 |
14 | void NativeMethods::callMethod(Context &ctx, std::string methodName) {
15 | ctx.nativeFunctions[methodName]();
16 | }
17 |
18 |
19 | void NativeMethods::loadMSCORLIBLibrary(Context &ctx) {
20 | registerMethod(ctx, "[mscorlib]System.Object::.ctor", []{ /* ... */ } );
21 | registerMethod(ctx, "[System.Console]System.Console::WriteLine", [&ctx]{ callMethod(ctx, "[NX]NX.Console::WriteLine"); } );
22 | }
23 |
24 | void NativeMethods::loadNXLibrary(Context &ctx) {
25 | registerMethod(ctx, "[NX]NX.Console::WriteLine", [&ctx] {
26 | printf("%s\n", ctx.dll->decodeUserString(ctx.pop()).c_str());
27 | });
28 | }
29 |
30 | }
--------------------------------------------------------------------------------
/source/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "dll.hpp"
3 | #include "native.hpp"
4 | #include "method.hpp"
5 |
6 | #include
7 |
8 | static void loadExecutable(std::string path) {
9 | static ili::Context context;
10 |
11 | context.dll = new ili::DLL(path);
12 | context.dll->validate();
13 |
14 | context.heap = new u8[0x0010'0000];
15 |
16 | context.stack = new u8[context.dll->getStackSize()];
17 | context.typeStack = new Type[context.dll->getStackSize()];
18 |
19 | context.stackPointer = context.stack;
20 | context.framePointer = nullptr;
21 | context.typeStackPointer = context.typeStack;
22 | context.typeFramePointer = nullptr;
23 |
24 | ili::NativeMethods::loadMSCORLIBLibrary(context);
25 | ili::NativeMethods::loadNXLibrary(context);
26 |
27 | // Execute Main
28 | {
29 | auto entryPoint = std::make_unique(context, context.dll->getEntryMethodToken());
30 | entryPoint->run();
31 |
32 | if (context.getUsedStackSize() == 0)
33 | ili::Logger::info("Program finished");
34 | else
35 | ili::Logger::info("Program finished with exit code %d", context.pop());
36 |
37 | }
38 |
39 | delete[] context.typeStack;
40 | delete[] context.stack;
41 | delete[] context.heap;
42 | delete context.dll;
43 | }
44 |
45 | int main() {
46 | auto hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE);
47 | ::SetConsoleMode(hConsole, ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT);
48 | loadExecutable("test/example/bin/Debug/net8.0/win-x64/example.dll");
49 |
50 | return 0;
51 | }
52 |
--------------------------------------------------------------------------------
/include/dll.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "types.hpp"
4 | #include "file_headers.hpp"
5 | #include "tables.hpp"
6 |
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 |
13 | namespace ili {
14 |
15 | #define OFFSET(base, offset) (reinterpret_cast(base) + offset)
16 | #define VRA_TO_OFFSET(section, rva) section->rawDataPointer + (rva - section->virtualAddress)
17 | #define ALIGN(value, alignment) (((value) + alignment) & (~(alignment - 1)))
18 |
19 | class DLL {
20 | public:
21 | DLL(std::string filePath);
22 | ~DLL();
23 |
24 | void validate();
25 |
26 | table_method_def_t* getMethodDefByMetadataToken(u32 methodToken);
27 | table_member_ref_t* getMemberRefByMetadataToken(u32 memberToken);
28 | table_method_def_t* getMethodDefByIndex(u32 index);
29 | table_type_def_t* getTypeDefByIndex(u32 index);
30 | table_type_ref_t* getTypeRefByIndex(u32 index);
31 | table_assembly_ref_t* getAssemblyRefByIndex(u32 index);
32 | table_field_t* getFieldByIndex(u32 index);
33 |
34 | u32 getEntryMethodToken();
35 |
36 | const char* getString(u32 index);
37 | std::span getUserString(u32 index);
38 | u8 *getBlob(u32 index);
39 |
40 | u8* getData();
41 |
42 | u32 getStackSize();
43 |
44 | section_table_entry_t* getVirtualSection(u64 rva);
45 |
46 | std::string getFullMethodName(u32 methodToken);
47 | std::string decodeUserString(u32 token);
48 |
49 | u16 findTypeDefWithMethod(u32 methodToken);
50 | table_class_layout_t* getClassLayoutOfType(table_type_def_t *typeDef);
51 |
52 | u32 getBlobSize(u32 index);
53 | u8 getBlobHeaderSize(u32 index);
54 |
55 | u32 getNumTableRows(u8 index);
56 |
57 | private:
58 | u8 *m_dllData;
59 | size_t m_fileSize;
60 |
61 | dos_header_t *m_dosHeader;
62 | dos_stub_t *m_dosStub;
63 | nt_header_t *m_ntHeader;
64 | optional_header_t *m_optionalHeader;
65 | std::vector m_sectionTable;
66 | crl_runtime_header_t *m_crlRuntimeHeader;
67 | metadata_t m_metadata = { 0 };
68 | std::vector m_streamHeaders;
69 | u32 m_numRows[64] = { 0 };
70 |
71 | std::vector> m_tildeTableData;
72 | u8 *m_stringsHeap;
73 | u8 *m_userStringsHeap;
74 | u8 *m_blobHeap;
75 | };
76 |
77 | }
--------------------------------------------------------------------------------
/include/types.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 |
7 | using u8 = uint8_t;
8 | using u16 = uint16_t;
9 | using u32 = uint32_t;
10 | using u64 = uint64_t;
11 |
12 | using s8 = int8_t;
13 | using s16 = int16_t;
14 | using s32 = int32_t;
15 | using s64 = int64_t;
16 |
17 | using namespace std::string_literals;
18 |
19 | enum class Type : u8 {
20 | Invalid = 0,
21 | Int32 = 1,
22 | Int64 = 2,
23 | Native_int = 4,
24 | Native_unsigned_int = 8,
25 | F = 16,
26 | O = 32,
27 | Pointer = 64
28 | };
29 |
30 | enum class SignatureElementType : u8 {
31 | End,
32 | Void,
33 | Boolean,
34 | Char,
35 | I1,
36 | U1,
37 | I2,
38 | U2,
39 | I4,
40 | U4,
41 | I8,
42 | U8,
43 | R4,
44 | R8,
45 | String,
46 | Ptr,
47 | ByRef,
48 | ValueType,
49 | Class,
50 | Var,
51 | Array,
52 | GenericInst,
53 | TypedByRef,
54 | I,
55 | U,
56 | FuncPtr,
57 | Object,
58 | SzArray,
59 | MVar,
60 | CmodReqd,
61 | CmodOpt,
62 | Internal,
63 | Modifier,
64 | Sentinel,
65 | Pinned
66 | };
67 |
68 | static u8 getSignatureElementTypeSize(SignatureElementType type) {
69 | switch (type) {
70 | case SignatureElementType::Boolean: return 1;
71 | case SignatureElementType::Char: return 2;
72 | case SignatureElementType::I1: return 1;
73 | case SignatureElementType::U1: return 1;
74 | case SignatureElementType::I2: return 2;
75 | case SignatureElementType::U2: return 2;
76 | case SignatureElementType::I4: return 4;
77 | case SignatureElementType::U4: return 4;
78 | case SignatureElementType::I8: return 8;
79 | case SignatureElementType::U8: return 8;
80 | case SignatureElementType::R4: return 4;
81 | case SignatureElementType::R8: return 8;
82 | case SignatureElementType::String: return 8;
83 | case SignatureElementType::Ptr: return 8;
84 | default: return 0;
85 | }
86 | }
87 |
88 | static u8 getTypeSize(Type type) {
89 | switch (type) {
90 | case Type::Int32: return 4;
91 | case Type::Int64: return 8;
92 | case Type::Native_int: return 8;
93 | case Type::Native_unsigned_int: return 8;
94 | case Type::F: return 8;
95 | case Type::O: return 8;
96 | case Type::Pointer: return 8;
97 | default: return 0;
98 | }
99 | }
100 |
101 | #define PACKED __attribute__((packed))
--------------------------------------------------------------------------------
/include/tables.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | namespace ili {
4 |
5 | #define TABLE_ID(token) (token >> 24)
6 | #define TABLE_INDEX(token) (token & 0x00FFFFFF)
7 |
8 | #define TABLE_ID_METHODDEF 0x06
9 | #define TABLE_ID_ASSEMBLYREF 0x23
10 | #define TABLE_ID_TYPEREF 0x01
11 | #define TABLE_ID_TYPEDEF 0x02
12 | #define TABLE_ID_MEMBERREF 0x0A
13 | #define TABLE_ID_CLASS_LAYOUT 0x0F
14 | #define TABLE_ID_MODULE 0x00
15 | #define TABLE_ID_FIELD 0x04
16 |
17 | typedef struct PACKED { // 0x06
18 | u32 rva;
19 | u16 implFlags;
20 | u16 flags;
21 | u16 nameIndex;
22 | u16 signatureIndex;
23 | u16 paramListIndex;
24 | } table_method_def_t;
25 |
26 | typedef struct PACKED { // 0x23
27 | u16 versionMajor;
28 | u16 versionMinor;
29 | u16 buildNumber;
30 | u16 revisionNumber;
31 | u32 flags;
32 | u16 publicKeyOrTokenIndex;
33 | u16 nameIndex;
34 | u16 cultureIndex;
35 | u16 hashValueIndex;
36 | } table_assembly_ref_t;
37 |
38 | typedef struct PACKED { // 0x01
39 | u16 resolutionScopeIndex;
40 | u16 typeNameIndex;
41 | u16 typeNamespaceIndex;
42 | } table_type_ref_t;
43 |
44 | typedef struct PACKED { // 0x02
45 | u32 flags;
46 | u16 typeNameIndex;
47 | u16 typeNamespaceIndex;
48 | u16 extendsIndex;
49 | u16 fieldListIndex;
50 | u16 methodListIndex;
51 | } table_type_def_t;
52 |
53 | typedef struct PACKED { // 0x0A
54 | u16 classIndex;
55 | u16 nameIndex;
56 | u16 signatureIndex;
57 | } table_member_ref_t;
58 |
59 | typedef struct PACKED { // 0x00
60 | u16 generation;
61 | u16 nameIndex;
62 | u16 mvId;
63 | u16 encId;
64 | u16 encBaseId;
65 | } table_module_t;
66 |
67 | typedef struct PACKED { // 0x0F
68 | u16 packingSize;
69 | u32 classSize;
70 | u16 parentIndex;
71 | } table_class_layout_t;
72 |
73 | typedef struct PACKED { // 0x04
74 | u16 flags;
75 | u16 nameIndex;
76 | u16 signatureIndex;
77 | } table_field_t;
78 |
79 | #define TYPE_DEF_OR_REF 2
80 | #define HAS_CONSTANT 2
81 | #define HAS_CUSTOM_ATTRIBUTE 5
82 | #define HAS_FIELD_MARSHALL 1
83 | #define HAS_DECL_SECURITY 2
84 | #define MEMBER_REF_PARENT 3
85 | #define HAS_SEMANTICS 1
86 | #define METHOD_DEF_OR_REF 1
87 | #define MEMBER_FORWARDED 1
88 | #define IMPLEMENTATION 2
89 | #define CUSTOM_ATTRIBUTE_TYPE 3
90 | #define RESOLUTION_SCOPE 2
91 | #define TYPE_OR_METHOD_DEF 1
92 |
93 | #define INDEX_TAG(index, tag_type) index & (0xFFFFFFFF << tag_type)
94 | #define INDEX_INDEX(index, tag_type) (index >> tag_type)
95 |
96 | }
--------------------------------------------------------------------------------
/include/context.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "types.hpp"
4 |
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include "logger.hpp"
12 |
13 | namespace ili {
14 |
15 | struct VariableBase {
16 | Type type;
17 | };
18 |
19 | template
20 | struct Variable : public VariableBase {
21 | T value;
22 | };
23 |
24 | struct HeapReference {
25 | u8 *heapPointer;
26 | size_t size;
27 | };
28 |
29 | class Method;
30 | class DLL;
31 |
32 |
33 | struct Context {
34 | DLL *dll = nullptr;
35 |
36 | u8 *heap = nullptr;
37 | std::list heapReferences;
38 |
39 | u8 *stackPointer = nullptr;
40 | u8 *framePointer = nullptr;
41 | u8 *stack;
42 |
43 | Type *typeStackPointer = nullptr;
44 | Type *typeFramePointer = nullptr;
45 | Type *typeStack;
46 |
47 | std::unordered_map> nativeFunctions;
48 |
49 |
50 |
51 | Type getTypeOnStack(u16 pos = 0) {
52 | return *(typeStackPointer - 1 - pos);
53 | }
54 |
55 | template
56 | T pop() {
57 | T ret = {};
58 |
59 | if (stackPointer <= stack) {
60 | Logger::error("Popped %d bytes from the stack but the stack is empty!", sizeof(T));
61 | exit(1);
62 | }
63 |
64 | size_t sizeToPop = getTypeSize(getTypeOnStack());
65 |
66 | if (sizeToPop > sizeof(T)) {
67 | Logger::error("Popped %d bytes into %d byte return value!", sizeToPop, sizeof(T));
68 | exit(1);
69 | }
70 |
71 | typeStackPointer--;
72 | stackPointer -= sizeof(T);
73 |
74 | if (stackPointer < stack) {
75 | Logger::error("Popped %d which was more than the stack held!", sizeof(T));
76 | exit(1);
77 | }
78 |
79 | std::memset(&ret, 0x00, sizeof(T));
80 | std::memcpy(&ret, stackPointer, sizeToPop);
81 |
82 | Logger::debug("Popped %d bytes from stack: %016llx", sizeof(T), ret);
83 |
84 | return ret;
85 | }
86 |
87 | template
88 | void push(Type type, T val) {
89 |
90 | std::memcpy(stackPointer, &val, getTypeSize(type));
91 | *typeStackPointer = type;
92 |
93 | typeStackPointer++;
94 | stackPointer += sizeof(T);
95 |
96 | Logger::debug("Pushed %d bytes onto stack: %016llx", sizeof(T), val);
97 | }
98 |
99 | u32 getUsedStackSize() {
100 | return this->stackPointer - this->stack;
101 | }
102 | };
103 |
104 | }
--------------------------------------------------------------------------------
/include/file_headers.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | namespace ili {
6 |
7 | typedef struct PACKED {
8 | char magic[2]; // MZ
9 | u8 unused[0x3C];
10 | u16 peHeaderPointer; // Offset 0x3C
11 | } dos_header_t;
12 | static_assert(sizeof(dos_header_t) == 0x40, "dos_header_t size invalid!");
13 |
14 | typedef struct PACKED {
15 | u8 data[0x40];
16 | } dos_stub_t;
17 | static_assert(sizeof(dos_stub_t) == 0x40, "dos_stub_t size invalid!");
18 |
19 | typedef struct PACKED {
20 | char magic[4]; // PE\0\0 (0x00004550)
21 | u16 machine;
22 | u16 numSections;
23 | u32 timeDateStamp;
24 | u32 symbolTablePointer;
25 | u32 numSymbolTables;
26 | u16 optionalHeaderSize;
27 | u16 characteristics;
28 | } nt_header_t;
29 | static_assert(sizeof(nt_header_t) == 0x18, "nt_header_t size invalid!");
30 |
31 | typedef struct PACKED {
32 | u32 rva;
33 | u32 size;
34 | } table_t;
35 | static_assert(sizeof(table_t) == 0x08, "table_t size invalid!");
36 |
37 | typedef struct PACKED {
38 | char magic[2];
39 | u8 linkerVersionMajor;
40 | u8 linkerVersionMinor;
41 | u32 codeSize;
42 | u32 dataSize;
43 | u32 bssSize;
44 | u32 entryPointRVA;
45 | u32 codeBaseRVA;
46 |
47 | u64 imageBase;
48 | u32 sectionAlignment;
49 | u32 fileAlignment;
50 | u16 osVersionMajor;
51 | u16 osVersionMinor;
52 | u16 imageVersionMajor;
53 | u16 imageVersionMinor;
54 | u16 subsystemVersionMajor;
55 | u16 subsystemVersionMinor;
56 | u32 win32VersionValue;
57 | u32 imageSize;
58 | u32 headersSize;
59 | u32 checksum;
60 | u16 subsystem;
61 | u16 dllCharacteristics;
62 | u64 stackReserveSize;
63 | u64 stackCommitSize;
64 | u64 heapReserveSize;
65 | u64 heapCommitSize;
66 | u32 loaderFlags;
67 | u32 numRvaAndSizes;
68 |
69 | table_t exportTable;
70 | table_t importTable;
71 | table_t resourceTable;
72 | table_t exceptionTable;
73 | table_t certificateTable;
74 | table_t baseRelocationTable;
75 | table_t debug;
76 | table_t architectureData;
77 | table_t globalPointer;
78 | table_t tslTable;
79 | table_t loadConfigTable;
80 | table_t boundImport;
81 | table_t importAddressTable;
82 | table_t delayImportAddressTable;
83 | table_t crlRuntimeHeader;
84 | u64 unused;
85 | } optional_header_t;
86 |
87 | typedef struct PACKED {
88 | char name[8];
89 | u32 virtualSize;
90 | u32 virtualAddress;
91 | u32 rawDataSize;
92 | u32 rawDataPointer;
93 | u32 relocationsPointer;
94 | u32 lineNumbersPointer;
95 | u16 numRelocations;
96 | u16 numLineNumbers;
97 | u32 characteristics;
98 | } section_table_entry_t;
99 | static_assert(sizeof(section_table_entry_t) == 0x28, "section_table_entry_t size invalid!");
100 |
101 | typedef struct PACKED {
102 | u32 headerSize;
103 | u16 runtimeVersionMajor;
104 | u16 runtimeVersionMinor;
105 | table_t metaData;
106 | u32 flags;
107 | u32 entryPointToken;
108 | u64 resources;
109 | u64 strongNameSignature;
110 | u64 codeManagerTable;
111 | u64 vTableFixups;
112 | u64 exportAddressTableJumps;
113 | u64 managedNativeHeader;
114 | } crl_runtime_header_t;
115 | static_assert(sizeof(crl_runtime_header_t) == 0x48, "crl_runtime_header_t size invalid!");
116 |
117 | typedef struct PACKED {
118 | u32 offset;
119 | u32 size;
120 | char name[32];
121 | } stream_header_t;
122 |
123 | typedef struct PACKED {
124 | char magic[4];
125 | u16 versionMajor;
126 | u16 versionMinor;
127 | u32 reserved;
128 | u32 length;
129 | char version[0xFF];
130 | u16 flags;
131 | u16 streams;
132 | } metadata_t;
133 |
134 | typedef struct PACKED {
135 | u32 reserved_x00;
136 | u8 versionMajor;
137 | u8 versionMinor;
138 | u8 heapSize;
139 | u8 reserved_x07;
140 | u64 valid;
141 | u64 sorted;
142 | } tilde_stream_t;
143 |
144 | typedef struct PACKED {
145 | u8 *base;
146 | size_t size;
147 | } unspecified_table_t;
148 |
149 |
150 | static constexpr u8 getMetadataTableSize(u8 index) {
151 | // TODO: Some of these values depend on if a table/heap has more than 2^16 entries
152 | // TODO: For now, assume we don't reach that limit
153 | constexpr u8 table[64] = {
154 | 10, 6, 14, 0, 6, 0, 14, 0,
155 | 6, 0, 6, 0, 6, 0, 0, 0,
156 | 0, 2, 0, 0, 0, 0, 0, 0,
157 | 0, 0, 0, 0, 0, 0, 0, 0,
158 | 22, 0, 0, 20
159 | };
160 |
161 | if (index >= sizeof(table))
162 | return 0;
163 |
164 | return table[index];
165 | }
166 |
167 | }
--------------------------------------------------------------------------------
/include/opcode.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "types.hpp"
4 |
5 | namespace ili {
6 |
7 | enum class OpcodePrefix : u16 {
8 | Nop = 0x00,
9 | Brk = 0x01,
10 | Ldarg_0 = 0x02,
11 | Ldarg_1 = 0x03,
12 | Ldarg_2 = 0x04,
13 | Ldarg_3 = 0x05,
14 | Ldloc_0 = 0x06,
15 | Ldloc_1 = 0x07,
16 | Ldloc_2 = 0x08,
17 | Ldloc_3 = 0x09,
18 | Stloc_0 = 0x0A,
19 | Stloc_1 = 0x0B,
20 | Stloc_2 = 0x0C,
21 | Stloc_3 = 0x0D,
22 | Ldarg_s = 0x0E,
23 | Ldarga_s = 0x0F,
24 | Starg_s = 0x10,
25 | Ldloc_s = 0x11,
26 | Ldloca_s = 0x12,
27 | Stloc_s = 0x13,
28 | Ldnull = 0x14,
29 | Ldc_i4_m1 = 0x15,
30 | Ldc_i4_0 = 0x16,
31 | Ldc_i4_1 = 0x17,
32 | Ldc_i4_2 = 0x18,
33 | Ldc_i4_3 = 0x19,
34 | Ldc_i4_4 = 0x1A,
35 | Ldc_i4_5 = 0x1B,
36 | Ldc_i4_6 = 0x1C,
37 | Ldc_i4_7 = 0x1D,
38 | Ldc_i4_8 = 0x1E,
39 | Ldc_i4_s = 0x1F,
40 | Ldc_i4 = 0x20,
41 | Ldc_i8 = 0x21,
42 | Ldc_r4 = 0x22,
43 | Ldc_r8 = 0x23,
44 | Dup = 0x25,
45 | Pop = 0x26,
46 | Jmp = 0x27,
47 | Call = 0x28,
48 | Calli = 0x29,
49 | Ret = 0x2A,
50 | Br_s = 0x2B,
51 | Brfalse_s,
52 | Brtrue_s,
53 | Beq_s,
54 | Bge_s,
55 | Bgt_s,
56 | Ble_s,
57 | Blt_s,
58 | Bne_un_s,
59 | Bge_un_s,
60 | Bgt_un_s,
61 | Ble_un_s,
62 | Blt_un_s,
63 | Br = 0x38,
64 | Brfalse,
65 | Brtrue,
66 | Beq,
67 | Bge,
68 | Bgt,
69 | Ble,
70 | Blt,
71 | Bne_un,
72 | Bge_un,
73 | Bgt_un,
74 | Ble_un,
75 | Blt_un,
76 | Swtch,
77 | Ldind_i1,
78 | Ldind_u1,
79 | Ldind_i2,
80 | Ldind_u2,
81 | Ldind_i4,
82 | Ldind_u4,
83 | Ldind_i8,
84 | Ldind_i,
85 | Ldind_r4,
86 | Ldind_r8,
87 | Ldind_ref,
88 | Stind_ref,
89 | Stind_i1,
90 | Stind_i2,
91 | Stind_i4,
92 | Stind_i8,
93 | Stind_r4,
94 | Stind_r8,
95 | Add,
96 | Sub,
97 | Mul,
98 | Div,
99 | Div_un,
100 | Rem,
101 | Rem_un,
102 | Logical_and,
103 | Logical_or,
104 | Logical_xor,
105 | Shl,
106 | Shr,
107 | Shr_un,
108 | Neg,
109 | Logical_not,
110 | Conv_i1,
111 | Conv_i2,
112 | Conv_i4,
113 | Conv_i8,
114 | Conv_r4,
115 | Conv_r8,
116 | Conv_u4,
117 | Conv_u8,
118 | Callvirt,
119 | Cpobj,
120 | Ldobj,
121 | Ldstr = 0x72,
122 | Newobj,
123 | Castclass,
124 | Isinst,
125 | Conv_r_un = 0x76,
126 | Unbox = 0x79,
127 | Thrw,
128 | Ldfld,
129 | Ldflda,
130 | Stfld,
131 | Ldsfld,
132 | Ldsflda,
133 | Stsfld,
134 | Stobj,
135 | Conv_ovf_i1_un,
136 | Conv_ovf_i2_un,
137 | Conv_ovf_i4_un,
138 | Conv_ovf_i8_un,
139 | Conv_ovf_u1_un,
140 | Conv_ovf_u2_un,
141 | Conv_ovf_u4_un,
142 | Conv_ovf_u8_un,
143 | Conv_ovf_i_un,
144 | Conv_ovf_u_un,
145 | Box,
146 | Newarr,
147 | Ldlen,
148 | Ldelema,
149 | Ldelem_i1,
150 | Ldelem_u1,
151 | Ldelem_i2,
152 | Ldelem_u2,
153 | Ldelem_i4,
154 | Ldelem_u4,
155 | Ldelem_i8,
156 | Ldelem_i,
157 | Ldelem_r4,
158 | Ldelem_r8,
159 | Ldelem_ref,
160 | Stelem_i,
161 | Stelem_i1,
162 | Stelem_i2,
163 | Stelem_i4,
164 | Stelem_i8,
165 | Stelem_r4,
166 | Stelem_r8,
167 | Stelem_ref,
168 | Ldelem,
169 | Stelem,
170 | Unbox_any = 0xA5,
171 | Conv_ovf_i1 = 0xB3,
172 | Conv_ovf_u1,
173 | Conv_ovf_i2,
174 | Conv_ovf_u2,
175 | Conv_ovf_i4,
176 | Conv_ovf_u4,
177 | Conv_ovf_i8,
178 | Conv_ovf_u8 = 0xBA,
179 | Refanyval = 0xC2,
180 | Ckfinite = 0xC3,
181 | Mkrefany = 0xC6,
182 | Ldtoken = 0xD0,
183 | Conv_u2,
184 | Conv_u1,
185 | Conv_i,
186 | Conv_ovf_i,
187 | Conv_ovf_u,
188 | Add_ovf,
189 | Add_ovf_un,
190 | Mul_ovf,
191 | Mul_ovf_un,
192 | Sub_ovf,
193 | Sub_ovf_un,
194 | Endfinally,
195 | Leave,
196 | Leave_s,
197 | Stind_i,
198 | Conv_u,
199 |
200 | Arglist = 0xFE00,
201 | Ceq,
202 | Cgt,
203 | Cgt_un,
204 | Clt,
205 | Clt_un,
206 | Ldftn,
207 | Ldvirtftn = 0xFE07,
208 | Ldarg = 0xFE0A,
209 | Ldarga,
210 | Starg,
211 | Ldloc,
212 | Ldloca,
213 | Stloc,
214 | Localloc = 0xFE0F,
215 | Endfilter = 0xFE11,
216 | Unaligned,
217 | Volatle,
218 | Tail,
219 | Initobj,
220 | Constrained,
221 | Cpblk,
222 | Initblk,
223 | No,
224 | Rethrow = 0xFE1A,
225 | Size_of = 0xFE1C,
226 | Refanytype,
227 | Readonly
228 | };
229 | }
--------------------------------------------------------------------------------
/source/dll.cpp:
--------------------------------------------------------------------------------
1 | #include "dll.hpp"
2 |
3 | #include "types.hpp"
4 | #include "file_headers.hpp"
5 | #include "tables.hpp"
6 | #include "logger.hpp"
7 |
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 |
16 | using namespace std::literals::string_view_literals;
17 |
18 | namespace ili {
19 |
20 | DLL::DLL(std::string filePath) {
21 | FILE *dllFile = fopen(filePath.c_str(), "rb");
22 |
23 | if (dllFile == nullptr) {
24 | Logger::error("Cannot open file %s!", filePath.c_str());
25 | exit(1);
26 | }
27 |
28 | fseek(dllFile, 0, SEEK_END);
29 |
30 | this->m_fileSize = ftell(dllFile);
31 | this->m_dllData = new u8[this->m_fileSize];
32 | rewind(dllFile);
33 | fread(this->m_dllData, 1, this->m_fileSize, dllFile);
34 | fclose(dllFile);
35 |
36 | this->m_dosHeader = reinterpret_cast(this->m_dllData);
37 | this->m_dosStub = reinterpret_cast(OFFSET(this->m_dosHeader, sizeof(dos_header_t)));
38 | this->m_ntHeader = reinterpret_cast(OFFSET(this->m_dosStub, sizeof(dos_stub_t)));
39 | this->m_optionalHeader = reinterpret_cast(OFFSET(this->m_ntHeader, sizeof(nt_header_t)));
40 |
41 |
42 | for (u8 section = 0; section < this->m_ntHeader->numSections; section++)
43 | this->m_sectionTable.push_back(reinterpret_cast(OFFSET(this->m_optionalHeader, sizeof(optional_header_t) + section * sizeof(section_table_entry_t))));
44 |
45 | section_table_entry_t *crlSection = this->getVirtualSection(this->m_optionalHeader->crlRuntimeHeader.rva);
46 | this->m_crlRuntimeHeader = reinterpret_cast(OFFSET(this->m_dllData, VRA_TO_OFFSET(crlSection, this->m_optionalHeader->crlRuntimeHeader.rva)));
47 |
48 | section_table_entry_t *metadataSection = this->getVirtualSection(this->m_crlRuntimeHeader->metaData.rva);
49 | u8 *metadataBase = OFFSET(this->m_dllData, VRA_TO_OFFSET(metadataSection, this->m_crlRuntimeHeader->metaData.rva));
50 | u8 *currentDataPtr = metadataBase;
51 |
52 | // Parse Metadata
53 | {
54 |
55 | std::memcpy(&this->m_metadata, currentDataPtr, offsetof(metadata_t, version));
56 | currentDataPtr += offsetof(metadata_t, version);
57 | std::memcpy(&this->m_metadata.version, currentDataPtr, this->m_metadata.length);
58 | currentDataPtr += this->m_metadata.length;
59 | std::memcpy(&this->m_metadata.flags, currentDataPtr, 2 * sizeof(u16));
60 | currentDataPtr += 2 * sizeof(u16);
61 |
62 | }
63 |
64 | // Parse Stream Headers
65 | {
66 | stream_header_t *currHeader = reinterpret_cast(currentDataPtr);
67 | for (u8 stream = 0; stream < this->m_metadata.streams; stream++) {
68 | this->m_streamHeaders.push_back(currHeader);
69 | currentDataPtr += (2 * sizeof(u32)) + ALIGN(strlen(currHeader->name), 4);
70 | currHeader = reinterpret_cast(currentDataPtr);
71 | }
72 |
73 | }
74 |
75 | // Parse #~ Stream rows and tables
76 | {
77 | for (u8 stream = 0; stream < this->m_metadata.streams; stream++) {
78 | if (std::string(this->m_streamHeaders[stream]->name) == "#~") {
79 | tilde_stream_t *tildeStream = reinterpret_cast(OFFSET(metadataBase, this->m_streamHeaders[stream]->offset));
80 |
81 | currentDataPtr += 24; // Skip to rows array
82 |
83 | for (u8 i = 0; i < 64; i++) {
84 | if ((tildeStream->valid & (1ULL << i)) == (1ULL << i)) {
85 | this->m_numRows[i] = *reinterpret_cast(currentDataPtr);
86 | currentDataPtr += sizeof(u32);
87 | }
88 | }
89 |
90 | for (u8 i = 0; i < 64; i++) {
91 | u32 count = this->m_numRows[i];
92 |
93 | this->m_tildeTableData.push_back({});
94 | if (count != 0) {
95 | u8 tableSize = getMetadataTableSize(i);
96 | for (u16 j = 0; j < count; j++) {
97 | this->m_tildeTableData[i].push_back({ currentDataPtr, tableSize });
98 | currentDataPtr += tableSize;
99 | }
100 | }
101 | }
102 | } else if (std::string(this->m_streamHeaders[stream]->name) == "#Strings") {
103 | this->m_stringsHeap = OFFSET(metadataBase, this->m_streamHeaders[stream]->offset);
104 | } else if (std::string(this->m_streamHeaders[stream]->name) == "#US") {
105 | this->m_userStringsHeap = OFFSET(metadataBase, this->m_streamHeaders[stream]->offset);
106 | } else if (std::string(this->m_streamHeaders[stream]->name) == "#Blob") {
107 | this->m_blobHeap = OFFSET(metadataBase, this->m_streamHeaders[stream]->offset);
108 | }
109 | }
110 | }
111 | }
112 |
113 | DLL::~DLL() {
114 | delete[] this->m_dllData;
115 | }
116 |
117 | void DLL::validate() {
118 | if (std::memcmp(this->m_dosHeader->magic, "MZ", 2) != 0) {
119 | Logger::error("Invalid DOS Header!");
120 | exit(1);
121 | } else Logger::info("Valid DOS Header!");
122 |
123 | if (std::memcmp(this->m_ntHeader->magic, "PE\x00\x00", 4) != 0) {
124 | Logger::error("Invalid NT Header!");
125 | exit(1);
126 | } else Logger::info("Valid NT Header!");
127 |
128 | Logger::info("Stack size: %lx", this->getStackSize());
129 |
130 | if (this->m_crlRuntimeHeader->headerSize != sizeof(crl_runtime_header_t)) {
131 | Logger::error("Invalid CLR Header!");
132 | exit(1);
133 | } else Logger::info("Valid CLR Header!");
134 |
135 | Logger::info("Runtime version: %d.%d", this->m_crlRuntimeHeader->runtimeVersionMajor, this->m_crlRuntimeHeader->runtimeVersionMinor);
136 | Logger::info("Entrypoint Token: %x", this->m_crlRuntimeHeader->entryPointToken);
137 |
138 | if (std::memcmp(this->m_metadata.magic, "BSJB", 4) != 0) {
139 | Logger::error("Invalid Metadata Header!");
140 | exit(1);
141 | } else Logger::info("Valid Metadata Header!");
142 |
143 | Logger::info(".NET Framework version: %s", this->m_metadata.version);
144 |
145 | for (u8 stream = 0; stream < this->m_metadata.streams; stream++) {
146 | Logger::info("Found Stream: %s", this->m_streamHeaders[stream]->name);
147 |
148 | if (std::string(this->m_streamHeaders[stream]->name) == "#~") {
149 | for (u8 i = 0; i < 64; i++)
150 | if (this->m_numRows[i] != 0)
151 | Logger::info(" Table 0x%X: %u entries", i, this->m_numRows[i]);
152 | }
153 | }
154 | }
155 |
156 | table_method_def_t* DLL::getMethodDefByMetadataToken(u32 token) {
157 | if (TABLE_ID(token) == TABLE_ID_METHODDEF)
158 | return reinterpret_cast(this->m_tildeTableData[TABLE_ID(token)][TABLE_INDEX(token) - 1].base);
159 | else return nullptr;
160 | }
161 |
162 | table_member_ref_t* DLL::getMemberRefByMetadataToken(u32 token) {
163 | if (TABLE_ID(token) == TABLE_ID_MEMBERREF)
164 | return reinterpret_cast(this->m_tildeTableData[TABLE_ID(token)][TABLE_INDEX(token) - 1].base);
165 | else return nullptr;
166 | }
167 |
168 | table_method_def_t * DLL::getMethodDefByIndex(u32 index) {
169 | return reinterpret_cast(this->m_tildeTableData[TABLE_ID_METHODDEF][index - 1].base);
170 | }
171 |
172 | table_type_ref_t* DLL::getTypeRefByIndex(u32 index) {
173 | return reinterpret_cast(this->m_tildeTableData[TABLE_ID_TYPEREF][index - 1].base);
174 | }
175 |
176 | table_type_def_t* DLL::getTypeDefByIndex(u32 index) {
177 | return reinterpret_cast(this->m_tildeTableData[TABLE_ID_TYPEDEF][index - 1].base);
178 | }
179 |
180 | table_assembly_ref_t* DLL::getAssemblyRefByIndex(u32 index) {
181 | return reinterpret_cast(this->m_tildeTableData[TABLE_ID_ASSEMBLYREF][index - 1].base);
182 | }
183 |
184 | table_field_t* DLL::getFieldByIndex(u32 index) {
185 | return reinterpret_cast(this->m_tildeTableData[TABLE_ID_FIELD][index - 1].base);
186 | }
187 |
188 | u32 DLL::getEntryMethodToken() {
189 | return this->m_crlRuntimeHeader->entryPointToken;
190 | }
191 |
192 | const char* DLL::getString(u32 index) {
193 | return reinterpret_cast(&this->m_stringsHeap[index]);
194 | }
195 |
196 | u32 DLL::getBlobSize(u32 index) {
197 | switch (getBlobHeaderSize(index)) {
198 | case 1: return this->m_blobHeap[index];
199 | case 2: return ((this->m_blobHeap[index] & 0x3F) << 8) + this->m_blobHeap[index + 1];
200 | case 4: return ((this->m_blobHeap[index] & 0x1F) << 24)
201 | + (this->m_blobHeap[index + 1] << 16)
202 | + (this->m_blobHeap[index + 2] << 8)
203 | + this->m_blobHeap[index + 3];
204 | default: return 0;
205 | }
206 | }
207 |
208 | u8 DLL::getBlobHeaderSize(u32 index) {
209 | if ((this->m_userStringsHeap[index] & 0x80) == 0x00)
210 | return 1;
211 | if ((this->m_userStringsHeap[index] & 0xC0) == 0x80)
212 | return 2;
213 | if ((this->m_userStringsHeap[index] & 0xE0) == 0xC0)
214 | return 4;
215 |
216 | return 0;
217 | }
218 |
219 | std::span DLL::getUserString(u32 index) {
220 | if ((index >> 24) == 0x70) {
221 | index = index & 0x00FFFFFF;
222 |
223 | auto blobHeaderSize = getBlobHeaderSize(index);
224 | auto string = &this->m_userStringsHeap[index] + blobHeaderSize;
225 | u32 size = 0;
226 | std::memcpy(&size, &this->m_userStringsHeap[index], blobHeaderSize);
227 |
228 | return { string, size };
229 | }
230 |
231 | return {};
232 | }
233 |
234 | u8* DLL::getBlob(u32 index) {
235 | return &this->m_blobHeap[index + getBlobHeaderSize(index)];
236 | }
237 |
238 | u8* DLL::getData() {
239 | return this->m_dllData;
240 | }
241 |
242 | u32 DLL::getStackSize() {
243 | return this->m_optionalHeader->stackReserveSize;
244 | }
245 |
246 | std::string DLL::getFullMethodName(u32 methodToken) {
247 | auto memberRef = this->getMemberRefByMetadataToken(methodToken);
248 | auto typeRef = this->getTypeRefByIndex(INDEX_INDEX(memberRef->classIndex, MEMBER_REF_PARENT));
249 | auto assemblyRef = this->getAssemblyRefByIndex(INDEX_INDEX(typeRef->resolutionScopeIndex, RESOLUTION_SCOPE));
250 |
251 | auto assembly = this->getString(assemblyRef->nameIndex);
252 | auto nameSpace = this->getString(typeRef->typeNamespaceIndex);
253 | auto type = this->getString(typeRef->typeNameIndex);
254 | auto method = this->getString(memberRef->nameIndex);
255 |
256 | return "["s + assembly + "]"s + nameSpace + "."s + type + "::"s + method;
257 | }
258 |
259 | std::string DLL::decodeUserString(u32 token) {
260 | auto utf16String = this->getUserString(token);
261 | std::wstring_convert,char16_t> conversion;
262 | return conversion.to_bytes(reinterpret_cast(utf16String.data()), reinterpret_cast(utf16String.data() + utf16String.size_bytes() - 1));
263 | }
264 |
265 | section_table_entry_t* DLL::getVirtualSection(u64 rva) {
266 | for (u8 section = 0; section < this->m_ntHeader->numSections; section++) {
267 | if (rva >= this->m_sectionTable[section]->virtualAddress
268 | && rva < this->m_sectionTable[section]->virtualAddress + this->m_sectionTable[section]->virtualSize)
269 | return this->m_sectionTable[section];
270 | }
271 |
272 | return nullptr;
273 | }
274 |
275 | u16 DLL::findTypeDefWithMethod(u32 methodToken) {
276 | table_method_def_t *methodToFind = this->getMethodDefByMetadataToken(methodToken);
277 |
278 | if (methodToFind == nullptr)
279 | return 0;
280 |
281 | // Check all rows in the typedef table except the last one for if it contains the method
282 | for (u32 i = 0; i < this->m_numRows[TABLE_ID_METHODDEF] - 1; i++) {
283 | table_type_def_t* currTypeDef = reinterpret_cast(this->m_tildeTableData[TABLE_ID_TYPEDEF][i].base);
284 | table_type_def_t* nextTypeDef = reinterpret_cast(this->m_tildeTableData[TABLE_ID_TYPEDEF][i + 1].base);
285 |
286 | table_method_def_t* currMethodDef = this->getMethodDefByIndex(currTypeDef->methodListIndex);
287 | table_method_def_t* nextMethodDef = this->getMethodDefByIndex(nextTypeDef->methodListIndex);
288 |
289 | if (methodToFind >= currMethodDef && methodToFind < nextMethodDef)
290 | return i + 1;
291 | }
292 |
293 | // When the method hasn't been found in the previous rows, it has to be in the last one
294 | // since if it wouldn't exist at all, methodToFind would have been nullptr
295 | return this->m_numRows[TABLE_ID_METHODDEF];
296 | }
297 |
298 | table_class_layout_t* DLL::getClassLayoutOfType(table_type_def_t *typeDef) {
299 | for (u32 i = 0; i < this->m_numRows[TABLE_ID_CLASS_LAYOUT]; i++) {
300 | table_class_layout_t *currClassLayout = reinterpret_cast(this->m_tildeTableData[TABLE_ID_CLASS_LAYOUT][i].base);
301 |
302 | if (reinterpret_cast(this->m_tildeTableData[TABLE_ID_TYPEDEF][currClassLayout->parentIndex].base) == typeDef)
303 | return currClassLayout;
304 | }
305 |
306 | return nullptr;
307 | }
308 |
309 | u32 DLL::getNumTableRows(u8 index) {
310 | if (index >= sizeof(this->m_numRows))
311 | return 0;
312 |
313 | return this->m_numRows[index];
314 | }
315 |
316 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/source/method.cpp:
--------------------------------------------------------------------------------
1 | #include "method.hpp"
2 |
3 | #include
4 |
5 | #include "types.hpp"
6 | #include "tables.hpp"
7 | #include "dll.hpp"
8 | #include "opcode.hpp"
9 | #include "context.hpp"
10 | #include "logger.hpp"
11 |
12 | namespace ili {
13 |
14 | Method::Method(Context &ctx, u32 methodToken) : m_ctx(ctx) {
15 | this->m_methodDef = getDLL()->getMethodDefByMetadataToken(methodToken);
16 | Logger::debug("Executing method '%s'", getDLL()->getString(this->m_methodDef->nameIndex));
17 | }
18 |
19 | Method::~Method() {
20 | for (u16 i = 0; i < 0xFF; i++) {
21 | if (this->m_localVariable[i] == nullptr)
22 | continue;
23 |
24 | delete this->m_localVariable[i];
25 | this->m_localVariable[i] = nullptr;
26 | }
27 | }
28 |
29 | void Method::run() {
30 | section_table_entry_t *ilHeaderSection = getDLL()->getVirtualSection(this->m_methodDef->rva);
31 | u8 *methodHeader = OFFSET(getDLL()->getData(), VRA_TO_OFFSET(ilHeaderSection, this->m_methodDef->rva));
32 |
33 | if ((*methodHeader & 0x03) == 0x02) // Tiny Header
34 | this->m_programCounter = methodHeader + 1;
35 | else if ((*methodHeader & 0x03) == 0x03) // Fat Header
36 | this->m_programCounter = methodHeader + 12;
37 |
38 | for (u16 i = 0; i < 0xFF; i++)
39 | this->m_localVariable[i] = nullptr;
40 |
41 | u8 *methodStart = this->m_programCounter;
42 |
43 | while (true) {
44 | u8 currOpcode = *this->m_programCounter;
45 |
46 | this->m_programCounter++;
47 |
48 | if (currOpcode != 0xFE) { // Handle normal opcodes
49 | switch (static_cast(currOpcode)) {
50 | case OpcodePrefix::Nop:
51 | Logger::debug("Instruction NOP");
52 | break;
53 | case OpcodePrefix::Brk:
54 | Logger::debug("Instruction BREAK");
55 | raise(SIGILL);
56 | break;
57 | case OpcodePrefix::Call: {
58 | Logger::debug("Instruction CALL");
59 | u32 token = this->getNext();
60 | call(token); // TODO: Handle return value
61 |
62 | break;
63 | }
64 | case OpcodePrefix::Stloc_0:
65 | Logger::debug("Instruction STLOC.0");
66 | stloc(0);
67 |
68 | break;
69 | case OpcodePrefix::Stloc_1:
70 | Logger::debug("Instruction STLOC.1");
71 | stloc(1);
72 |
73 | break;
74 | case OpcodePrefix::Stloc_2:
75 | Logger::debug("Instruction STLOC.2");
76 | stloc(2);
77 | break;
78 | case OpcodePrefix::Stloc_3:
79 | Logger::debug("Instruction STLOC.3");
80 | stloc(3);
81 | break;
82 | case OpcodePrefix::Stloc_s:
83 | Logger::debug("Instruction STLOC.s");
84 | stloc(getNext());
85 | break;
86 | case OpcodePrefix::Ldc_i4_0:
87 | Logger::debug("Instruction LDC.I4.0");
88 | ldc(Type::Int32, 0);
89 | break;
90 | case OpcodePrefix::Ldc_i4_1:
91 | Logger::debug("Instruction LDC.I4.1");
92 | ldc(Type::Int32, 1);
93 | break;
94 | case OpcodePrefix::Ldc_i4_2:
95 | Logger::debug("Instruction LDC.I4.2");
96 | ldc(Type::Int32, 2);
97 | break;
98 | case OpcodePrefix::Ldc_i4_3:
99 | Logger::debug("Instruction LDC.I4.3");
100 | ldc(Type::Int32, 3);
101 | break;
102 | case OpcodePrefix::Ldc_i4_4:
103 | Logger::debug("Instruction LDC.I4.4");
104 | ldc(Type::Int32, 4);
105 | break;
106 | case OpcodePrefix::Ldc_i4_5:
107 | Logger::debug("Instruction LDC.I4.5");
108 | ldc(Type::Int32, 5);
109 | break;
110 | case OpcodePrefix::Ldc_i4_6:
111 | Logger::debug("Instruction LDC.I4.6");
112 | ldc(Type::Int32, 6);
113 | break;
114 | case OpcodePrefix::Ldc_i4_7:
115 | Logger::debug("Instruction LDC.I4.7");
116 | ldc(Type::Int32, 7);
117 | break;
118 | case OpcodePrefix::Ldc_i4_8:
119 | Logger::debug("Instruction LDC.I4.8");
120 | ldc(Type::Int32, 8);
121 | break;
122 | case OpcodePrefix::Ldc_i4_m1:
123 | Logger::debug("Instruction LDC.I4.M1");
124 | ldc(Type::Int32, -1);
125 | break;
126 | case OpcodePrefix::Ldc_i4:
127 | Logger::debug("Instruction LDC.I4");
128 | ldc(Type::Int32, getNext());
129 | break;
130 | case OpcodePrefix::Ldc_i8:
131 | Logger::debug("Instruction LDC.I8");
132 | ldc(Type::Int64, getNext());
133 | break;
134 | case OpcodePrefix::Ldc_r4:
135 | Logger::debug("Instruction LDC.R4");
136 | ldc(Type::F, getNext());
137 | break;
138 | case OpcodePrefix::Ldc_r8:
139 | Logger::debug("Instruction LDC.R8");
140 | ldc(Type::F, getNext());
141 | break;
142 | case OpcodePrefix::Ldc_i4_s:
143 | Logger::debug("Instruction LDC.I4.s");
144 | ldc(Type::Int32, getNext());
145 | break;
146 | case OpcodePrefix::Ldloc_0:
147 | Logger::debug("Instruction LDLOC.0");
148 | ldloc(0);
149 | break;
150 | case OpcodePrefix::Ldloc_1:
151 | Logger::debug("Instruction LDLOC.1");
152 | ldloc(1);
153 | break;
154 | case OpcodePrefix::Ldloc_2:
155 | Logger::debug("Instruction LDLOC.2");
156 | ldloc(2);
157 | break;
158 | case OpcodePrefix::Ldloc_3:
159 | Logger::debug("Instruction LDLOC.3");
160 | ldloc(3);
161 | break;
162 | case OpcodePrefix::Ldloc_s:
163 | Logger::debug("Instruction LDLOC.s");
164 | ldloc(getNext());
165 | break;
166 | case OpcodePrefix::Ldloca_s:
167 | Logger::debug("Instruction LDLOCA.s");
168 | ldloca(getNext());
169 | break;
170 | case OpcodePrefix::Ldstr:
171 | Logger::debug("Instruction LDSTR");
172 | this->m_ctx.push(Type::O, getNext());
173 | break;
174 | case OpcodePrefix ::Ldarg_0:
175 | Logger::debug("Instruction LDARG.0");
176 | break;
177 | case OpcodePrefix::Br:
178 | Logger::debug("Instruction BR");
179 | this->m_programCounter = methodStart + getNext();
180 | break;
181 | case OpcodePrefix::Br_s:
182 | Logger::debug("Instruction BR.S");
183 | this->m_programCounter += getNext();
184 | break;
185 | case OpcodePrefix::Add: {
186 | Logger::debug("Instruction ADD");
187 | Type opAType = this->m_ctx.getTypeOnStack(2);
188 | Type opBType = this->m_ctx.getTypeOnStack(1);
189 | Type resType = Type::Invalid;
190 |
191 | // Type validating
192 | if (opAType == opBType)
193 | resType = opAType;
194 |
195 | if ((opAType == Type::Int32 && opBType == Type::Native_int) ||
196 | (opAType == Type::Native_int && opBType == Type::Int32))
197 | resType = Type::Native_int;
198 |
199 | if ((opAType == Type::Pointer && (opBType == Type::Int32 || opBType == Type::Native_int)) ||
200 | (opAType == Type::Pointer && (opBType == Type::Int32 || opBType == Type::Native_int)))
201 | resType = Type::Pointer;
202 |
203 | if (opAType == Type::O || opBType == Type::O || (opAType == Type::Pointer && opBType == Type::Pointer))
204 | resType = Type::Invalid;
205 |
206 | if (resType == Type::Invalid) {
207 | Logger::error("Add operation performed on invalid types!");
208 | exit(1);
209 | }
210 |
211 | //Addition
212 | if ((opAType == Type::Int32 && opBType == Type::Int32) || (opAType == Type::Int32 && opBType == Type::Native_int) || (opAType == Type::Native_int && opBType == Type::Int32))
213 | this->m_ctx.push(resType, this->m_ctx.pop() + this->m_ctx.pop());
214 | else if (opAType == Type::Int64 && opBType == Type::Int64)
215 | this->m_ctx.push(resType, this->m_ctx.pop() + this->m_ctx.pop());
216 | else if (opAType == Type::Native_int && opBType == Type::Native_int)
217 | this->m_ctx.push(resType, this->m_ctx.pop() + this->m_ctx.pop());
218 | else if (opAType == Type::F && opBType == Type::F)
219 | this->m_ctx.push(resType, this->m_ctx.pop() + this->m_ctx.pop());
220 | else if (opAType == Type::Pointer && opBType == Type::Pointer)
221 | this->m_ctx.push(resType, this->m_ctx.pop() + this->m_ctx.pop());
222 | else if (opAType == Type::Pointer && opBType == Type::Int32)
223 | this->m_ctx.push(resType, this->m_ctx.pop() + this->m_ctx.pop());
224 | else if (opAType == Type::Pointer && opBType == Type::Native_int)
225 | this->m_ctx.push(resType, this->m_ctx.pop() + this->m_ctx.pop());
226 | else if (opAType == Type::Int32 && opBType == Type::Pointer)
227 | this->m_ctx.push(resType, this->m_ctx.pop() + this->m_ctx.pop());
228 | else if (opAType == Type::Native_int && opBType == Type::Pointer)
229 | this->m_ctx.push(resType, this->m_ctx.pop() + this->m_ctx.pop());
230 |
231 | break;
232 | }
233 | case OpcodePrefix::Newobj: {
234 | Logger::debug("Instruction NEWOBJ");
235 | u32 token = this->getNext();
236 | if (TABLE_ID(token) == TABLE_ID_METHODDEF) {
237 | u16 typeIndex = getDLL()->findTypeDefWithMethod(token);
238 |
239 | table_type_def_t *type = getDLL()->getTypeDefByIndex(typeIndex);
240 | table_type_def_t *typeNext = getDLL()->getTypeDefByIndex(typeIndex + 1);
241 |
242 | Logger::debug("Creating instance of Type %s::%s", getDLL()->getString(type->typeNamespaceIndex), getDLL()->getString(type->typeNameIndex));
243 |
244 | size_t objSize = 0;
245 | for (u16 i = type->fieldListIndex; i < typeNext->fieldListIndex && i <= getDLL()->getNumTableRows(TABLE_ID_FIELD); i++) {
246 | auto field = getDLL()->getFieldByIndex(i);
247 | auto sig = getDLL()->getBlob(field->signatureIndex);
248 | auto sigSize = getDLL()->getBlobSize(field->signatureIndex);
249 |
250 | size_t fieldSize = getSignatureElementTypeSize(static_cast(*(sig + sigSize - 1)));
251 |
252 | objSize += fieldSize;
253 |
254 | Logger::debug(" Field %s [0x%02x]", getDLL()->getString(field->nameIndex), fieldSize);
255 | }
256 |
257 | Logger::debug("Allocating %d bytes on the heap", objSize);
258 |
259 | u8 *newMemory = nullptr;
260 | if (this->m_ctx.heapReferences.empty()) {
261 | newMemory = this->m_ctx.heap;
262 | } else {
263 | auto lastElement = this->m_ctx.heapReferences.back();
264 | newMemory = lastElement.heapPointer + lastElement.size;
265 | }
266 |
267 | std::memset(newMemory, 0x00, objSize);
268 | this->m_ctx.heapReferences.push_back({ newMemory, objSize });
269 |
270 | this->m_ctx.push(Type::O, reinterpret_cast(newMemory));
271 |
272 | call(token);
273 | }
274 | break;
275 | }
276 | case OpcodePrefix::Ret: {
277 | Logger::debug("Instruction RET");
278 |
279 | return;
280 | }
281 | default:
282 | Logger::error("Unknown opcode (0x%02x)!", currOpcode);
283 | exit(1);
284 | break;
285 | }
286 | }
287 | else { // Handle extended opcodes
288 | currOpcode = *this->m_programCounter;
289 | this->m_programCounter++;
290 |
291 | switch (currOpcode) {
292 |
293 | }
294 | }
295 | }
296 | }
297 |
298 | // General Operations
299 |
300 | template
301 | T Method::getNext() {
302 | T value = *reinterpret_cast(this->m_programCounter);
303 | this->m_programCounter += sizeof(T);
304 |
305 | return value;
306 | }
307 |
308 | DLL* Method::getDLL() {
309 | return this->m_ctx.dll;
310 | }
311 |
312 | // Instruction Implementations
313 |
314 | void Method::stloc(u8 id) {
315 | if (this->m_localVariable[id] != nullptr)
316 | delete this->m_localVariable[id];
317 | this->m_localVariable[id] = nullptr;
318 |
319 | Type type = this->m_ctx.getTypeOnStack();
320 |
321 | switch (type) {
322 | case Type::Int32:
323 | this->m_localVariable[id] = new Variable{type, this->m_ctx.pop()};
324 | break;
325 | case Type::Int64:
326 | this->m_localVariable[id] = new Variable{type, this->m_ctx.pop()};
327 | break;
328 | case Type::Native_int:
329 | this->m_localVariable[id] = new Variable{type, this->m_ctx.pop()};
330 | break;
331 | case Type::F:
332 | this->m_localVariable[id] = new Variable{type, this->m_ctx.pop()};
333 | break;
334 | case Type::O:
335 | this->m_localVariable[id] = new Variable{type, this->m_ctx.pop()};
336 | break;
337 | case Type::Pointer:
338 | this->m_localVariable[id] = new Variable{type, this->m_ctx.pop()};
339 | break;
340 | }
341 | }
342 |
343 | void Method::ldloc(u8 id) {
344 | auto varType = this->m_localVariable[id]->type;
345 |
346 | switch (varType) {
347 | case Type::Int32:
348 | this->m_ctx.push(varType, static_cast*>(this->m_localVariable[id])->value);
349 | break;
350 | case Type::Int64:
351 | this->m_ctx.push(varType, static_cast*>(this->m_localVariable[id])->value);
352 | break;
353 | case Type::Native_int:
354 | this->m_ctx.push(varType, static_cast*>(this->m_localVariable[id])->value);
355 | break;
356 | case Type::F:
357 | this->m_ctx.push(varType, static_cast*>(this->m_localVariable[id])->value);
358 | break;
359 | case Type::O:
360 | this->m_ctx.push(varType, static_cast*>(this->m_localVariable[id])->value);
361 | break;
362 | case Type::Pointer:
363 | this->m_ctx.push(varType, static_cast*>(this->m_localVariable[id])->value);
364 | break;
365 | }
366 | if (this->m_localVariable[id] != nullptr)
367 | delete this->m_localVariable[id];
368 |
369 | this->m_localVariable[id] = nullptr;
370 | }
371 |
372 | void Method::ldloca(u8 id) {
373 | this->m_ctx.push(Type::Pointer, reinterpret_cast(this->m_localVariable[id]));
374 | }
375 |
376 | template
377 | void Method::ldc(Type type, T num) {
378 | this->m_ctx.push(type, num);
379 | }
380 |
381 | void Method::call(u32 methodToken) {
382 | switch (TABLE_ID(methodToken)) {
383 | case TABLE_ID_METHODDEF:
384 | {
385 | auto method = getDLL()->getMethodDefByMetadataToken(methodToken);
386 | auto sig = getDLL()->getBlob(method->signatureIndex);
387 |
388 | auto calledMethod = new Method(this->m_ctx, methodToken);
389 | calledMethod->run();
390 |
391 | delete calledMethod;
392 | break;
393 | }
394 | case TABLE_ID_MEMBERREF:
395 | {
396 | auto fullMethodName = getDLL()->getFullMethodName(methodToken);
397 | Logger::debug("Executing native method %s", fullMethodName.c_str());
398 |
399 | this->m_ctx.nativeFunctions[fullMethodName]();
400 |
401 | break;
402 | }
403 | }
404 | }
405 |
406 | }
407 |
408 |
--------------------------------------------------------------------------------