注射code到运行时可执行 [英] Injecting code into executable at runtime

查看:217
本文介绍了注射code到运行时可执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作的应用程序(用C ++编写),它在运行时生成一些机器code(Linux操作系统,X86-64了,但我计划迁移的ARM)。接下来,它产生的店code在内存中,并通过跳转到内存位置执行它。在很长一段时间,我曾与分配可执行内存有问题,但我终于解决它使用:

I'm working on application (written in C++), which generate some machine code at runtime (Linux, x86-64 now, but I plan to migrate on ARM). Next it store generated code in memory and execute it by jumping to memory location. For a long time I had a problem with allocating executable memory, but I finally solved it using:

uint8_t *memory = mmap (NULL, length, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

到目前为止,它的工作原理,但我不知道这是否是优雅的方式做这样的事情。我不知道可执行装载机如何做到这一点?

So far it works, but I'm not sure if it's elegant way to do such things. I wonder how executable loader do this?

推荐答案

这是本质上如何执行装载机做的事情;在他们的情况下,他们执行 MMAP A文件,而不是一个匿名映射,但,除了它的基本上是相同的。

This is essentially how executable loaders do things; in their case they perform a mmap of a file, not an anonymous mapping, but apart from that it's essentially the same.

请注意,这是一个好主意,不要有写和在同一时间执行访问,因为它使某些类型的安全漏洞更容易。您可以使用则mprotect 初始映射后调整的保护标志。

Note that it's a good idea not to have both write and execute access at the same time, as it makes certain types of security exploits easier. You can use mprotect to adjust the protection flags after the initial mapping.

这篇关于注射code到运行时可执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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