Create C++ module for interop with llvm

This commit is contained in:
Colton1skees
2023-03-04 14:44:58 -06:00
parent 6111bb20c5
commit f8bd72bcdd
15 changed files with 1730 additions and 29 deletions
+3
View File
@@ -34,6 +34,9 @@ x64/
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# Pre-built LLVM binaries.
llvm-15.0.3-win64/
*_i.c
*_p.c
*.ilk
+20 -12
View File
@@ -26,14 +26,14 @@ using Dna.Decompilation;
using Dna.Structuring.Stackify;
// Load the 64 bit PE file.
// Note: This file is automatically copied to the build directory.
var path = @"ProtectedExecutable.bin";
var binary = new WindowsBinary(64, File.ReadAllBytes(path), 0x140000000);
var path = @"C:\Users\Public\Documents\VMProtect\Code Markers\MSVC\x64\Release\Project1.vmp.exe";
var binary = new WindowsBinary(64, File.ReadAllBytes(path));
// Instantiate dna.
var dna = new Dna.Dna(binary);
// Parse a (virtualized) control flow graph from the binary.
ulong funcAddr = 0x1400F2947;
ulong funcAddr = 0x14000177E;
var cfg = dna.RecursiveDescent.ReconstructCfg(funcAddr);
// The VM entry spans across multiple routines. To avoid disassembling multiple
@@ -92,31 +92,39 @@ prompt();
var dotGraph = GraphVisualizer.GetDotGraph(liftedCfg);
File.WriteAllText("graph.dot", dotGraph.Compile(false, false));
bool emulate = true;
bool emulate = false;
if(emulate)
{
// Load the binary into unicorn engine.
var emulator = new UnicornEmulator(architecture);
PEMapper.MapBinary(emulator, binary);
//PEMapper.MapBinary(emulator, binary);
ulong tebBase = 0x7fded000;
ulong tebSize = 0x10000;
emulator.MapMemory(tebBase, (int)tebSize);
emulator.MapMemory(0, (int)tebSize);
//emulator.MapMemory(0, (int)tebSize);
var igt = new GdtHelper(emulator.Emulator, 0x0, 0x1000);
igt.Setup(tebBase);
//var igt = new GdtHelper(emulator.Emulator, 0x0, 0x1000);
//igt.Setup(tebBase);
// Setup the stack.
ulong rsp = 0x100000000;
emulator.MapMemory(rsp, 0x1000 * 1200);
rsp += 0x20000;
ulong pebAddr = 0x9A67F99120;
emulator.MapMemory(pebAddr - 0x120, 0x1000);
UInt16 val = 0x4A63;
emulator.WriteMemory(pebAddr, BitConverter.GetBytes(val));
//emulator.MapMemory(0, 0x1000 * 10);
int theSize = 0x1000 * 10;
emulator.MapMemory(0, theSize);
for(int i = 0; i < theSize; i++)
{
// emulator.WriteMemory((ulong)i, new byte[] { 0xFF });
}
//ulong gs = 0x1000;
//emulator.MapMemory(0, 0x1000 * 1000);
//emulator.SetRegister(register_e.ID_REG_X86_GS, 0);
@@ -124,14 +132,14 @@ if(emulate)
emulator.SetRegister(register_e.ID_REG_X86_RSP, rsp);
emulator.SetRegister(register_e.ID_REG_X86_RBP, rsp);
emulator.SetRegister(register_e.ID_REG_X86_RIP, 0x14000177E);
//emulator.SetRegister(register_e.ID_REG_X86_RIP, 0x14000177E);
// Execute the function.
emulator.Start(0x14000177E);
}
Thread.Sleep(100000);
Console.WriteLine("Started");
// Lift the control flow graph to LLVM IR.
+172
View File
@@ -0,0 +1,172 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{e6a58095-9b8b-4830-bfea-2947c4f2681a}</ProjectGuid>
<RootNamespace>DnaLLVMInterop</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>ClangCL</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>ClangCL</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>C:\Users\colton\source\repos\Dna\llvm-15.0.3-win64\include;$(IncludePath)</IncludePath>
<LibraryPath>C:\Users\colton\source\repos\Dna\llvm-15.0.3-win64\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<IncludePath>C:\Users\colton\source\repos\Dna\llvm-15.0.3-win64\include;$(IncludePath)</IncludePath>
<LibraryPath>C:\Users\colton\source\repos\Dna\llvm-15.0.3-win64\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;DNALLVMINTEROP_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;DNALLVMINTEROP_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;DNALLVMINTEROP_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<LanguageStandard>stdcpplatest</LanguageStandard>
<LanguageStandard_C>stdc17</LanguageStandard_C>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>DebugFastLink</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>LLVM-C.lib;LLVMAggressiveInstCombine.lib;LLVMAnalysis.lib;LLVMAsmParser.lib;LLVMAsmPrinter.lib;LLVMBinaryFormat.lib;LLVMBitReader.lib;LLVMBitstreamReader.lib;LLVMBitWriter.lib;LLVMCFGuard.lib;LLVMCFIVerify.lib;LLVMCodeGen.lib;LLVMCore.lib;LLVMCoroutines.lib;LLVMCoverage.lib;LLVMDebugInfoCodeView.lib;LLVMDebuginfod.lib;LLVMDebugInfoDWARF.lib;LLVMDebugInfoGSYM.lib;LLVMDebugInfoMSF.lib;LLVMDebugInfoPDB.lib;LLVMDemangle.lib;LLVMDiff.lib;LLVMDlltoolDriver.lib;LLVMDWARFLinker.lib;LLVMDWP.lib;LLVMExecutionEngine.lib;LLVMExegesis.lib;LLVMExegesisAArch64.lib;LLVMExegesisMips.lib;LLVMExegesisPowerPC.lib;LLVMExegesisX86.lib;LLVMExtensions.lib;LLVMFileCheck.lib;LLVMFrontendOpenACC.lib;LLVMFrontendOpenMP.lib;LLVMFuzzerCLI.lib;LLVMFuzzMutate.lib;LLVMGlobalISel.lib;LLVMInstCombine.lib;LLVMInstrumentation.lib;LLVMInterfaceStub.lib;LLVMInterpreter.lib;LLVMipo.lib;LLVMIRReader.lib;LLVMJITLink.lib;LLVMLibDriver.lib;LLVMLineEditor.lib;LLVMLinker.lib;LLVMLTO.lib;LLVMMC.lib;LLVMMCA.lib;LLVMMCDisassembler.lib;LLVMMCJIT.lib;LLVMMCParser.lib;LLVMMIRParser.lib;LLVMNVPTXCodeGen.lib;LLVMNVPTXDesc.lib;LLVMNVPTXInfo.lib;LLVMObjCARCOpts.lib;LLVMObjCopy.lib;LLVMObject.lib;LLVMObjectYAML.lib;LLVMOption.lib;LLVMOrcJIT.lib;LLVMOrcShared.lib;LLVMOrcTargetProcess.lib;LLVMPasses.lib;LLVMProfileData.lib;LLVMRemarks.lib;LLVMRuntimeDyld.lib;LLVMScalarOpts.lib;LLVMSelectionDAG.lib;LLVMSupport.lib;LLVMSymbolize.lib;LLVMSystemZAsmParser.lib;LLVMSystemZCodeGen.lib;LLVMSystemZDesc.lib;LLVMSystemZDisassembler.lib;LLVMSystemZInfo.lib;LLVMTableGen.lib;LLVMTableGenGlobalISel.lib;LLVMTarget.lib;LLVMTextAPI.lib;LLVMTransformUtils.lib;LLVMVEAsmParser.lib;LLVMVECodeGen.lib;LLVMVectorize.lib;LLVMVEDesc.lib;LLVMVEDisassembler.lib;LLVMVEInfo.lib;LLVMWindowsDriver.lib;LLVMWindowsManifest.lib;LLVMX86AsmParser.lib;LLVMX86CodeGen.lib;LLVMX86Desc.lib;LLVMX86Disassembler.lib;LLVMX86Info.lib;LLVMX86TargetMCA.lib;LLVMXCoreCodeGen.lib;LLVMXCoreDesc.lib;LLVMXCoreDisassembler.lib;LLVMXCoreInfo.lib;LLVMXRay.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;DNALLVMINTEROP_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<LanguageStandard>stdcpplatest</LanguageStandard>
<LanguageStandard_C>stdc17</LanguageStandard_C>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>DebugFastLink</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
<AdditionalDependencies>LLVM-C.lib;LLVMAggressiveInstCombine.lib;LLVMAnalysis.lib;LLVMAsmParser.lib;LLVMAsmPrinter.lib;LLVMBinaryFormat.lib;LLVMBitReader.lib;LLVMBitstreamReader.lib;LLVMBitWriter.lib;LLVMCFGuard.lib;LLVMCFIVerify.lib;LLVMCodeGen.lib;LLVMCore.lib;LLVMCoroutines.lib;LLVMCoverage.lib;LLVMDebugInfoCodeView.lib;LLVMDebuginfod.lib;LLVMDebugInfoDWARF.lib;LLVMDebugInfoGSYM.lib;LLVMDebugInfoMSF.lib;LLVMDebugInfoPDB.lib;LLVMDemangle.lib;LLVMDiff.lib;LLVMDlltoolDriver.lib;LLVMDWARFLinker.lib;LLVMDWP.lib;LLVMExecutionEngine.lib;LLVMExegesis.lib;LLVMExegesisAArch64.lib;LLVMExegesisMips.lib;LLVMExegesisPowerPC.lib;LLVMExegesisX86.lib;LLVMExtensions.lib;LLVMFileCheck.lib;LLVMFrontendOpenACC.lib;LLVMFrontendOpenMP.lib;LLVMFuzzerCLI.lib;LLVMFuzzMutate.lib;LLVMGlobalISel.lib;LLVMInstCombine.lib;LLVMInstrumentation.lib;LLVMInterfaceStub.lib;LLVMInterpreter.lib;LLVMipo.lib;LLVMIRReader.lib;LLVMJITLink.lib;LLVMLibDriver.lib;LLVMLineEditor.lib;LLVMLinker.lib;LLVMLTO.lib;LLVMMC.lib;LLVMMCA.lib;LLVMMCDisassembler.lib;LLVMMCJIT.lib;LLVMMCParser.lib;LLVMMIRParser.lib;LLVMNVPTXCodeGen.lib;LLVMNVPTXDesc.lib;LLVMNVPTXInfo.lib;LLVMObjCARCOpts.lib;LLVMObjCopy.lib;LLVMObject.lib;LLVMObjectYAML.lib;LLVMOption.lib;LLVMOrcJIT.lib;LLVMOrcShared.lib;LLVMOrcTargetProcess.lib;LLVMPasses.lib;LLVMProfileData.lib;LLVMRemarks.lib;LLVMRuntimeDyld.lib;LLVMScalarOpts.lib;LLVMSelectionDAG.lib;LLVMSupport.lib;LLVMSymbolize.lib;LLVMSystemZAsmParser.lib;LLVMSystemZCodeGen.lib;LLVMSystemZDesc.lib;LLVMSystemZDisassembler.lib;LLVMSystemZInfo.lib;LLVMTableGen.lib;LLVMTableGenGlobalISel.lib;LLVMTarget.lib;LLVMTextAPI.lib;LLVMTransformUtils.lib;LLVMVEAsmParser.lib;LLVMVECodeGen.lib;LLVMVectorize.lib;LLVMVEDesc.lib;LLVMVEDisassembler.lib;LLVMVEInfo.lib;LLVMWindowsDriver.lib;LLVMWindowsManifest.lib;LLVMX86AsmParser.lib;LLVMX86CodeGen.lib;LLVMX86Desc.lib;LLVMX86Disassembler.lib;LLVMX86Info.lib;LLVMX86TargetMCA.lib;LLVMXCoreCodeGen.lib;LLVMXCoreDesc.lib;LLVMXCoreDisassembler.lib;LLVMXCoreInfo.lib;LLVMXRay.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="Passes\ControlledNodeSplittingPass.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp" />
<ClCompile Include="Passes\ControlledNodeSplittingPass.cpp" />
</ItemGroup>
<ItemGroup>
<None Include="..\llvm-15.0.3-win64\bin\LLVM-C.dll">
<DeploymentContent>true</DeploymentContent>
</None>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClInclude Include="Passes\ControlledNodeSplittingPass.h">
<Filter>Passes</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp" />
<ClCompile Include="Passes\ControlledNodeSplittingPass.cpp">
<Filter>Passes</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Filter Include="Passes">
<UniqueIdentifier>{2aee77a2-525d-4f67-b255-9daecc2522a0}</UniqueIdentifier>
</Filter>
<Filter Include="API">
<UniqueIdentifier>{ce61e1b2-6444-4d20-b2ac-8d89cdc72726}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="..\llvm-15.0.3-win64\bin\LLVM-C.dll" />
</ItemGroup>
</Project>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,61 @@
/******************************************************************************
* Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#pragma once
#include <llvm/Pass.h>
namespace llvm {
namespace sl {
/// This pass computes a reducible AST above the control flow.
/// Irreducible control flow is removed using "Controlled Node Splitting".
class ControlledNodeSplittingPass : public FunctionPass
{
public:
static char ID;
public:
/// Constructor.
ControlledNodeSplittingPass();
/// Run this pass on the given function.
///
/// \param function the LLVM function
bool runOnFunction(Function& function) final;
/// Get the name of the pass.
StringRef getPassName() const final {
return "Controlled Node Splitting";
}
};
/// Create the "Controlled Node Splitting" pass.
Pass* createControlledNodeSplittingPass();
} // sl
} // llvm
+9
View File
@@ -0,0 +1,9 @@
// dllmain.cpp : Defines the entry point for the DLL application.
#include <llvm/Support/JSON.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/Pass.h>
#include <llvm/Transforms/Scalar.h>
#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
#include "llvm/Transforms/Utils/LowerSwitch.h"
#include <Windows.h>
+26
View File
@@ -26,6 +26,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
.editorconfig = .editorconfig
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Dna.LLVMInterop", "Dna.LLVMInterop\Dna.LLVMInterop.vcxproj", "{E6A58095-9B8B-4830-BFEA-2947C4F2681A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -258,6 +260,30 @@ Global
{47D397E7-098D-4058-9B19-DC01124ED897}.RelWithDebInfo|x64.Build.0 = Release|Any CPU
{47D397E7-098D-4058-9B19-DC01124ED897}.RelWithDebInfo|x86.ActiveCfg = Release|Any CPU
{47D397E7-098D-4058-9B19-DC01124ED897}.RelWithDebInfo|x86.Build.0 = Release|Any CPU
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Debug|Any CPU.ActiveCfg = Debug|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Debug|Any CPU.Build.0 = Debug|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Debug|x64.ActiveCfg = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Debug|x64.Build.0 = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Debug|x86.ActiveCfg = Debug|Win32
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Debug|x86.Build.0 = Debug|Win32
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.MinSizeRel|Any CPU.ActiveCfg = Debug|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.MinSizeRel|Any CPU.Build.0 = Debug|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.MinSizeRel|x64.ActiveCfg = Debug|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.MinSizeRel|x64.Build.0 = Debug|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.MinSizeRel|x86.ActiveCfg = Debug|Win32
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.MinSizeRel|x86.Build.0 = Debug|Win32
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Release|Any CPU.ActiveCfg = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Release|Any CPU.Build.0 = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Release|x64.ActiveCfg = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Release|x64.Build.0 = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Release|x86.ActiveCfg = Release|Win32
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.Release|x86.Build.0 = Release|Win32
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.RelWithDebInfo|Any CPU.ActiveCfg = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.RelWithDebInfo|Any CPU.Build.0 = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.RelWithDebInfo|x64.ActiveCfg = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.RelWithDebInfo|x64.Build.0 = Release|x64
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.RelWithDebInfo|x86.ActiveCfg = Release|Win32
{E6A58095-9B8B-4830-BFEA-2947C4F2681A}.RelWithDebInfo|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+68
View File
@@ -0,0 +1,68 @@
using AsmResolver.PE.File;
using ELFSharp.ELF;
using ELFSharp.ELF.Sections;
using ELFSharp.ELF.Segments;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dna.Binary.Windows
{
public class LinuxBinary : IBinary
{
public int Bitness { get; }
public byte[] Bytes { get; set; }
public ulong BaseAddress { get; }
public IELF ELFFile { get; }
/// <summary>
/// Initializes a new instance of the <see cref="WindowsBinary"/> class.
/// </summary>
/// <param name="bitness">The bitness of the binary(i.e 32 or 64).</param>
/// <param name="binaryBytes">The raw bytes of the PE file.</param>
/// <param name="baseAddress">
/// The optional base address of the binary.
/// If no address is provided, then base address specified in the optional header is used.
/// </param>
public LinuxBinary(int bitness, byte[] binaryBytes, ulong baseAddress)
{
Bitness = bitness;
Bytes = binaryBytes;
ELFFile = ELFReader.Load(new MemoryStream(binaryBytes), true);
BaseAddress = baseAddress;
}
/// <inheritdoc cref="IBinary.ReadBytes(ulong, int)"/>
public byte[] ReadBytes(ulong address, int count = 15)
{
// Compute a zero based offset for the address.
var offset = address - BaseAddress;
// Compute the segment containing the address.
// TODO: Properly handle data split across multiple segments.
var section = ELFFile.Sections
.Where(x => x is Section<ulong>)
.Cast<Section<ulong>>()
.Single(x => x.Offset <= offset && (x.Offset + x.Size) >= (offset + (ulong)count));
// Allocate a buffer to store the results in.
byte[] buffer = new byte[count];
// Read the raw data from the binary.
var segmentOffset = offset - section.Offset;
Array.Copy(section.GetContents(), (int)segmentOffset, buffer, 0, count);
return buffer;
}
/// <inheritdoc cref="IBinary.WriteBytes(ulong, byte[])"/>
public void WriteBytes(ulong address, byte[] bytes)
{
throw new NotImplementedException();
}
}
}
+18 -4
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
@@ -17,21 +17,24 @@
</PropertyGroup>
<ItemGroup>
<Compile Remove="Binary\Linux\**" />
<Compile Remove="Lifting\X86\**" />
<EmbeddedResource Remove="Binary\Linux\**" />
<EmbeddedResource Remove="Lifting\X86\**" />
<None Remove="Binary\Linux\**" />
<None Remove="Lifting\X86\**" />
</ItemGroup>
<ItemGroup>
<Folder Include="Binary\Linux\" />
<None Include="..\llvm-15.0.3-win64\bin\LLVM-C.dll" />
<None Include="..\x64\Release\Dna.LLVMInterop.dll" Link="Dna.LLVMInterop.dll" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AsmResolver" Version="4.9.0" />
<PackageReference Include="AsmResolver.PE.File" Version="4.9.0" />
<PackageReference Include="ELFSharp" Version="2.15.0" />
<PackageReference Include="ELFSharp" Version="2.16.1" />
<PackageReference Include="Iced" Version="1.17.0" />
<PackageReference Include="libLLVM.runtime.win-x64" Version="15.0.0" />
<PackageReference Include="LLVMSharp" Version="15.0.0-beta1" />
<PackageReference Include="Microsoft.Z3" Version="4.11.2" />
<PackageReference Include="Rivers" Version="0.1.0" />
@@ -41,8 +44,19 @@
<ItemGroup>
<ProjectReference Include="..\Dna.ControlFlow\Dna.ControlFlow.csproj" />
<ProjectReference Include="..\Dna.DataStructures\Dna.DataStructures.csproj" />
<ProjectReference Include="..\Dna.LLVMInterop\Dna.LLVMInterop.vcxproj">
<IncludeAssets>..\llvm-15.0.3-win64\bin\LLVM-C.dll</IncludeAssets>
<Private>True</Private>
<CopyLocalSatelliteAssemblies>True</CopyLocalSatelliteAssemblies>
</ProjectReference>
<ProjectReference Include="..\TritonTranslator\TritonTranslator\TritonTranslator.csproj" />
<ProjectReference Include="..\unicorn-net\src\Unicorn.Net\Unicorn.Net.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="..\llvm-15.0.3-win64\bin\LLVM-C.dll" Link="LLVM-C.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
@@ -1,5 +1,6 @@
using Dna.Binary;
using Dna.Binary.Windows;
using ELFSharp.ELF.Sections;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -9,11 +10,29 @@ using System.Threading.Tasks;
namespace Dna.Emulation
{
/// <summary>
/// Class for mapping windows binaries into an emulator's memory space.
/// Class for mapping binaries into an emulator's memory space.
/// </summary>
public static class PEMapper
public static class BinaryMapper
{
public static void MapBinary(ICpuEmulator state, WindowsBinary binary)
public static void MapELFFile(ICpuEmulator state, LinuxBinary binary)
{
// TODO: Actually map the correct amount of memory.
state.MapMemory(binary.BaseAddress, 0x1000 * 1000);
// Get all mappable sections.
var elfFile = binary.ELFFile;
var sections = elfFile.Sections
.Where(x => x is Section<ulong>)
.Cast<Section<ulong>>();
foreach(var section in sections)
{
// Compute the address to map the section at.
var address = section.Offset + binary.BaseAddress;
}
}
public static void MapPEFile(ICpuEmulator state, WindowsBinary binary)
{
state.MapMemory(binary.BaseAddress, 0x1000 * 1000);
var peFile = binary.PEFile;
+3 -4
View File
@@ -106,13 +106,12 @@ namespace Dna.Emulation.Unicorn
gdts.Add(CreateGdtEntry(0, 0, 0, 0));
}
gdts[15] = CreateGdtEntry()
var ds = CreateSegmentSelector(17, 0x0, 0xfffff, A_PRESENT | A_PRIV_0 | A_DATA | A_DATA_WRITABLE | A_DIRECTION_UP);
var es = CreateSegmentSelector(28, 0x0, 0xfffff, A_PRESENT | A_PRIV_0 | A_DATA | A_DATA_WRITABLE | A_DIRECTION_UP);
var fs = CreateSegmentSelector(32, teb, 1, A_PRESENT | A_PRIV_0 | A_DATA | A_DATA_WRITABLE); // FIXME: Correct the limit
var gs = CreateSegmentSelector(33, 0x0, 0xfffff, A_PRESENT | A_PRIV_0 | A_DATA | A_DATA_WRITABLE | A_DIRECTION_UP);
var cs = CreateSegmentSelector(11, 0x0, 0xfffff, A_PRESENT | A_PRIV_0 | A_CODE | A_CODE_READABLE | A_CONFORMING);
// var fs = CreateSegmentSelector(32, teb, 1, A_PRESENT | A_PRIV_0 | A_DATA | A_DATA_WRITABLE); // FIXME: Correct the limit
//var gs = CreateSegmentSelector(33, 0x0, 0xfffff, A_PRESENT | A_PRIV_0 | A_DATA | A_DATA_WRITABLE | A_DIRECTION_UP);
//var cs = CreateSegmentSelector(11, 0x0, 0xfffff, A_PRESENT | A_PRIV_0 | A_CODE | A_CODE_READABLE | A_CONFORMING);
}
}
}
+31 -5
View File
@@ -28,7 +28,7 @@ namespace Dna.Emulation.Unicorn
this.architecture = architecture;
// Insert a hook to throw an exception when unmapped memory usages occur.
//Emulator.Hooks.Code.Add(CodeHook, null);
Emulator.Hooks.Code.Add(CodeHook, null);
Emulator.Hooks.Memory.Add(MemoryEventHookType.UnmappedFetch | MemoryEventHookType.UnmappedRead | MemoryEventHookType.UnmappedWrite, UnmappedMemoryHook, null);
Emulator.Hooks.Memory.Add(MemoryHookType.Read, OnMemoryRead, null);
Emulator.Hooks.Memory.Add(MemoryHookType.Write, OnMemoryWrite, null);
@@ -104,9 +104,11 @@ namespace Dna.Emulation.Unicorn
/// </summary>
private bool UnmappedMemoryHook(Emulator emulator, MemoryType type, ulong address, int size, ulong value, object userData)
{
//Console.WriteLine("rax: 0x{0}", rax);
Console.WriteLine("rip: 0x{0}", GetRegister(register_e.ID_REG_X86_RIP).ToString("X"));
Console.WriteLine("rdx: 0x{0}", GetRegister(register_e.ID_REG_X86_RDX).ToString("X"));
Console.WriteLine("r8: 0x{0}", GetRegister(register_e.ID_REG_X86_R8).ToString("X"));
throw new InvalidOperationException($"Emulator accessed unmapped memory. (type: {type}), (address: {address})");
}
@@ -127,10 +129,34 @@ namespace Dna.Emulation.Unicorn
{
Debugger.Break();
}
/*
Console.WriteLine("Code hook");
Console.WriteLine("executing {0}:", ((ulong)Emulator.Registers.RIP).ToString("X"));
if(rax == 0x1400F17E1)
{
SetRegister(register_e.ID_REG_X86_RDI, 0x9A67F99000);
}
if(rax == 0x1400F17DD)
{
//SetRegister(register_e.ID_REG_X86_RDI, 0x0000009A67F99000);
}
// Cpuid
if(rax == 0x1400F27F1)
{
SetRegister(register_e.ID_REG_X86_RAX, 0x00000000000A0655);
SetRegister(register_e.ID_REG_X86_RBX, 0x000000000A200800);
SetRegister(register_e.ID_REG_X86_RCX, 0x00000000FEDAF387);
SetRegister(register_e.ID_REG_X86_RDX, 0x00000000BFEBFBFF);
}
if(rax == 0x140001799)
{
Debugger.Break();
}
// Console.WriteLine("Code hook");
// Console.WriteLine("executing {0}:", ((ulong)Emulator.Registers.RIP).ToString("X"));
/*
if (Emulator.Registers.RIP == 0x140001753)
{
Console.WriteLine("RAX: 0x{0}", Emulator.Registers.RAX.ToString("X"));
+6
View File
@@ -23,3 +23,9 @@ You can find an example usage [here](https://github.com/Colton1skees/Dna/blob/ma
* [X] Decompilation to pseudo C
* [ ] Jump table recovery
* [ ] Compiler back to x86/x64
# Setup
The .NET component of Dna is supported on Windows, Linux, and Mac OSX. The C++ component(LLVM.Interop) has been used exclusively on windows.
To get the C++ component building, extract [this precompiled version of llvm](https://github.com/LLVMParty/REVIDE/releases/download/libraries/llvm-15.0.3-win64.7z) to the root directory of Dna.