[英]Trying to create basic compiler in C#, getting Access Violation Errors
我正在嘗試學習一些有關編譯器的知識。 我正在使用NASM編譯我的目標文件,並鏈接將其轉換為dll。 我正在使用依賴關系遍歷程序來驗證我的dll的內容。 到目前為止,可以很好地在代碼中編譯我的dll,並且可以使用GetProcAddress檢索它。 但是,當我嘗試調用它時,出現以下錯誤:
未處理的異常:System.AccessViolationException:嘗試讀取或寫入受保護的內存。 這通常表明其他內存已損壞。
我所做的只是將eax設置為1,而不是100%為什么會收到錯誤消息。 我不確定哪個內存已損壞,我可以做些什么來正確調用此dll,將不勝感激。
編輯:我在Windows x64上使用32位程序集,在工作時,我回到家時嘗試使用x64程序集/匯編程序以查看其是否有效。
動態生成的程序集文件
global DllMain
export DllMain
global testfunc
export testfunc
section .code use32
DllMain: ; This code is required in .dll files
mov eax,1
ret 12
testfunc:
mov eax, 1
ret
C#代碼
namespace KCompiler
{
public static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
class Program
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int TestFuncDelegate();
static int Main(string[] args)
{
/*
AntlrFileStream stream = new AntlrFileStream("../../example.k");
CLexer lexer = new CLexer(stream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
CParser parser = new CParser(tokens);
ParseTreeWalker tree = new ParseTreeWalker();
CListener listener = new CListener();
tree.Walk(listener, parser.file());
*/
KAssembler assembler = new KAssembler();
//assembler.PushR("ebp");
//assembler.Mov32RR("ebp", "esp");
assembler.Mov32RI("eax", 1);
//assembler.PopR("ebp");
assembler.Return();
string RelativeDirectory = @"..\..";
string fullAssembly = File.ReadAllText(Path.Combine(RelativeDirectory,"k_template.asm")).Replace("{ASSEMBLY}", assembler.ToString());
Console.WriteLine(fullAssembly);
File.WriteAllText(Path.Combine(RelativeDirectory,"k.asm"), fullAssembly);
ProcessStartInfo nasmInfo = new ProcessStartInfo()
{
UseShellExecute = false,
FileName = Path.Combine(RelativeDirectory,"nasm.exe"),
RedirectStandardOutput = true,
Arguments = @"-fobj ..\..\k.asm",
};
using (Process nasm = Process.Start(nasmInfo))
{
nasm.WaitForExit();
Console.WriteLine($"NASM exited with code: {nasm.ExitCode}");
if (nasm.ExitCode != 0) return nasm.ExitCode;
}
ProcessStartInfo alinkInfo = new ProcessStartInfo()
{
UseShellExecute = false,
FileName = Path.Combine(RelativeDirectory,"alink.exe"),
RedirectStandardOutput = true,
Arguments = Path.Combine(RelativeDirectory,"k.obj") + " -oPE -dll",
};
using (Process alink = Process.Start(alinkInfo))
{
alink.WaitForExit();
Console.WriteLine($"alink exited with code: {alink.ExitCode}");
if (alink.ExitCode != 0) return alink.ExitCode;
}
IntPtr dll = new IntPtr(0);
try
{
dll = NativeMethods.LoadLibrary(Path.Combine(RelativeDirectory, "k.dll"));
Console.WriteLine(dll.ToInt32() == 0 ? "Unable to Load k.dll" : "Loaded k.dll");
if (dll.ToInt32() == 0) return 1;
IntPtr TestFunctionPtr = NativeMethods.GetProcAddress(dll, "testfunc");
Console.WriteLine(TestFunctionPtr.ToInt32() == 0 ? "Unable to Load 'testfunc'" : "Loaded 'testfunc'");
if (TestFunctionPtr.ToInt32() == 0) return 1;
TestFuncDelegate Test = Marshal.GetDelegateForFunctionPointer<TestFuncDelegate>(TestFunctionPtr);
int result = Test(); //Error right here
Console.WriteLine($"Test Function Returned: {result}");
}
finally
{
if(dll.ToInt32() != 0)
NativeMethods.FreeLibrary(dll);
}
return 0;
}
}
}
好吧,我找到了解決方案。 alink在將-fwin32格式鏈接到dll時遇到困難,因此我切換到golink鏈接器。 因此,現在我將NASM匯編器與golink鏈接器結合使用,並能夠使其與以前的安裝程序一起使用,下面提供了代碼。
另外,如果您不將[bits#]放在代碼的頂部,則NASM默認為16位模式,因此必須將其切換為32位。 如果在其中放置64,則必須編寫64位程序集才能使其正常工作。
ASM代碼
[bits 32]
global DllMain
global testfunc
export DllMain
export testfunc
section .text
DllMain: ; This code is required in .dll files
mov eax,1
ret 12
testfunc:
mov eax, 32
ret
C#代碼
using System;
using Antlr4;
using System.IO;
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
using System.Collections.Generic;
using KCompiler.KCore;
using KCompiler.Assembler;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace KCompiler
{
public static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
class Program
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate int TestFuncDelegate();
static int Main(string[] args)
{
/*
AntlrFileStream stream = new AntlrFileStream("../../example.k");
CLexer lexer = new CLexer(stream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
CParser parser = new CParser(tokens);
ParseTreeWalker tree = new ParseTreeWalker();
CListener listener = new CListener();
tree.Walk(listener, parser.file());
*/
KAssembler assembler = new KAssembler();
assembler.Mov32RI("eax", 32);
string RelativeDirectory = @"..\..";
string fullAssembly = File.ReadAllText(Path.Combine(RelativeDirectory,"k_template.asm")).Replace("{ASSEMBLY}", assembler.ToString());
Console.WriteLine(fullAssembly);
File.WriteAllText(Path.Combine(RelativeDirectory,"k.asm"), fullAssembly);
ProcessStartInfo nasmInfo = new ProcessStartInfo()
{
UseShellExecute = false,
FileName = Path.Combine(RelativeDirectory,"nasm.exe"),
RedirectStandardOutput = true,
Arguments = @"-fwin32 "+ Path.Combine(RelativeDirectory,"k.asm")
};
using (Process nasm = Process.Start(nasmInfo))
{
nasm.WaitForExit();
Console.WriteLine($"NASM exited with code: {nasm.ExitCode}");
if (nasm.ExitCode != 0) return nasm.ExitCode;
}
ProcessStartInfo golinkInfo = new ProcessStartInfo()
{
UseShellExecute = false,
FileName = Path.Combine(RelativeDirectory,"GoLink.exe"),
RedirectStandardOutput = true,
//Arguments = Path.Combine(RelativeDirectory,"k.obj") + " -c -oPE -dll -subsys windows",
Arguments = Path.Combine(RelativeDirectory, "k.obj") + " /dll",
};
using (Process golink = Process.Start(golinkInfo))
{
golink.WaitForExit();
Console.WriteLine($"alink exited with code: {golink.ExitCode}");
if (golink.ExitCode != 0) return golink.ExitCode;
}
IntPtr dll = new IntPtr(0);
try
{
dll = NativeMethods.LoadLibrary(Path.Combine(RelativeDirectory, "k.dll"));
Console.WriteLine(dll.ToInt32() == 0 ? "Unable to Load k.dll" : "Loaded k.dll");
if (dll.ToInt32() == 0) return 1;
IntPtr TestFunctionPtr = NativeMethods.GetProcAddress(dll, "testfunc");
Console.WriteLine(TestFunctionPtr.ToInt32() == 0 ? "Unable to Load 'testfunc'" : "Loaded 'testfunc'");
if (TestFunctionPtr.ToInt32() == 0) return 1;
TestFuncDelegate Test = Marshal.GetDelegateForFunctionPointer<TestFuncDelegate>(TestFunctionPtr);
int result = Test();
Console.WriteLine($"Test Function Returned: {result}");
}
finally
{
if(dll.ToInt32() != 0)
NativeMethods.FreeLibrary(dll);
}
return 0;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.