在 NX 位关闭的情况下在 linux 中分配数据页 [英] Allocating a data page in linux with NX bit turned off

查看:11
本文介绍了在 NX 位关闭的情况下在 linux 中分配数据页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的程序中生成一些机器代码然后运行它.一种方法是写出一个 .so 文件,然后将其加载到程序中,但这似乎太昂贵了.

I would like to generate some machine code in my program and then run it. One way to do it would be to write out a .so file and then load it in the program but that seems too expensive.

在 linux 中有没有办法让我在我的数据页中写出代码,然后在那里设置我的函数指针并调用它?我在 Windows 上看到过类似的情况,您可以在为该页面关​​闭 NX 保护的情况下分配一个页面,但我找不到类似的 linux 操作系统调用.

IS there a way in linux for me to write out the code in my data pages and then set my function ointer there and just call it? I've seen something similar on windows where you can allocate a page with the NX protection turned off for that page, but I can't find a similar OS call for linux.

推荐答案

mmap(2)(带有 munmap(2))和 mprotect(2) 系统调用是执行此操作的基本操作.回想一下,系统调用从应用程序的角度来看是基本操作.你想要 PROT_EXEC

The mmap(2) (with munmap(2)) and mprotect(2) syscalls are the elementary operations to do that. Recall that syscalls are elementary operations from the point of view of an application. You want PROT_EXEC

您可以只 strace 任何动态链接的可执行文件来获得有关如何调用它们的线索,因为动态链接器 ld.so 正在使用它们.

You could just strace any dynamically linked executable to get a clue about how you might call them, since the dynamic linker ld.so is using them.

生成共享对象可能比您想象的要便宜.实际上,生成 C 代码,运行编译器,然后 dlopen-ing 生成的共享对象是有一定意义的,即使您以交互方式工作也是如此.我的 MELT 领域特定语言(以扩展 GCC)正在这样做.回想一下,您可以毫无问题地执行大量 dlopen-s.

Generating a shared object might be less expensive than you imagine. Actually, generating C code, running the compiler, then dlopen-ing the resulting shared object has some sense, even when you work interactively. My MELT domain specific language (to extend GCC) is doing this. Recall that you can do a big lot of dlopen-s without issues.

如果你想在内存中生成机器码,你可以使用 GNU 闪电(快速生成慢机器码),dotgnu 中的 libjit(生成更少错误的机器代码),LuaJitasmjit (x86 or amd64 specific), LLVM (慢慢生成优化机器码).顺便说一句,SBCL Common Lisp 实现是动态编译到内存并在运行时生成好的机器代码(还有所有JIT for JVMs 这样做).

If you want to generate machine code in memory, you could use GNU lightning (quick generation of slow machine code), libjit from dotgnu (generate less bad machine code), LuaJit, asmjit (x86 or amd64 specific), LLVM (slowly generate optimized machine code). BTW, the SBCL Common Lisp implementation is dynamically compiling to memory and produces good machine code at runtime (and there is also all the JIT for JVMs doing that).

这篇关于在 NX 位关闭的情况下在 linux 中分配数据页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆