尝试在C#中创建基本编译器,获取访问冲突错误

时间:2017-08-03 05:31:26

标签: c# assembly dll compiler-construction access-violation

我试图了解编译器。我正在使用NASM编译我的目标文件,然后将它们变成dll。我使用依赖walker来验证我的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;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

好吧,我找到了解决方案。 alink难以将-fwin32格式链接到dll,因此我切换到了golink链接器。所以现在我正在使用 NASM汇编程序使用golink链接器并且能够使用与以前相同的设置使用它,代码在下面提供。

如果不将[位#]放在代码顶部,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;
        }
    }
}