在运行时将代码注入可执行文件 [英] Injecting code into executable at runtime

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

问题描述

我正在开发应用程序(用 C++ 编写),它在运行时生成一些机器代码(现在是 Linux,x86-64,但我计划在 ARM 上迁移).接下来它将生成的代码存储在内存中并通过跳转到内存位置来执行它.很长一段时间我都遇到了分配可执行内存的问题,但我终于解决了:

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,而不是匿名映射,但除此之外它基本上是相同的.

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.

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

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