gpt4 book ai didi

c# - 是否有可能完全用托管 .NET 语言编写 JIT 编译器(针对 native 代码)

转载 作者:IT王子 更新时间:2023-10-29 03:38:29 25 4
gpt4 key购买 nike

我正在考虑编写 JIT 编译器的想法,我只是想知道在理论上是否有可能在托管代码中编写整个内容。特别是,一旦您将汇编程序生成为字节数组,您如何跳入其中开始执行?

最佳答案

对于概念的完整证明,这里是将 Rasmus 的 JIT 方法完全翻译成 F#

open System
open System.Runtime.InteropServices

type AllocationType =
| COMMIT=0x1000u

type MemoryProtection =
| EXECUTE_READWRITE=0x40u

type FreeType =
| DECOMMIT = 0x4000u

[<DllImport("kernel32.dll", SetLastError=true)>]
extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, AllocationType flAllocationType, MemoryProtection flProtect);

[<DllImport("kernel32.dll", SetLastError=true)>]
extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize, FreeType freeType);

let JITcode: byte[] = [|0x55uy;0x8Buy;0xECuy;0x8Buy;0x45uy;0x08uy;0xD1uy;0xC8uy;0x5Duy;0xC3uy|]

[<UnmanagedFunctionPointer(CallingConvention.Cdecl)>]
type Ret1ArgDelegate = delegate of (uint32) -> uint32

[<EntryPointAttribute>]
let main (args: string[]) =
let executableMemory = VirtualAlloc(IntPtr.Zero, UIntPtr(uint32(JITcode.Length)), AllocationType.COMMIT, MemoryProtection.EXECUTE_READWRITE)
Marshal.Copy(JITcode, 0, executableMemory, JITcode.Length)
let jitedFun = Marshal.GetDelegateForFunctionPointer(executableMemory, typeof<Ret1ArgDelegate>) :?> Ret1ArgDelegate
let mutable test = 0xFFFFFFFCu
printfn "Value before: %X" test
test <- jitedFun.Invoke test
printfn "Value after: %X" test
VirtualFree(executableMemory, UIntPtr.Zero, FreeType.DECOMMIT) |> ignore
0

愉快地执行屈服

Value before: FFFFFFFC
Value after: 7FFFFFFE

关于c# - 是否有可能完全用托管 .NET 语言编写 JIT 编译器(针对 native 代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9557293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com