英文:
How can i execute an executable from memory?
问题
假设我在编译程序时将一个二进制文件包含进去,我将它保存在一个变量中,类似这样:
var myExec =[]byte{'s','o','m','e',' ','b','y','t','e','s'}
所以我的问题是,是否有一种方法可以在程序中执行这个二进制文件,而不必将它写回磁盘并调用exec或fork来执行?
我正在使用Golang编写我的应用程序,所以我希望使用Go或C(使用CGO)来实现这个方法。
基本上,我正在寻找一种类似将bash脚本通过管道传递给bash的方法,只是我不知道在哪里可以将原生可执行文件的字节传递给它以运行,而将其写回磁盘,然后让操作系统再次读取它似乎需要做很多额外的工作。
英文:
Let's say I have included a binary into my program during compilation so, I keep it in a variable something like
var myExec =[]byte{'s','o','m','e',' ','b','y','t','e','s'}
So my question is whether there is a way to execute this binary within my program without writing it back to the disc and calling exec or fork on it?
I am writing my app in Golang so the method I am seeking for is to do it using Go or C (using CGO).
Basically, I am seeking something like piping the bash script into bash just I don't know where can I pipe the bytes of a native executable to run it and writing it back to disk and then letting os to read it again seems a lot of extra work to be done
答案1
得分: 5
在C语言中,假设在Linux环境下,你可以通过使用mprotect()
系统调用来改变内存区域的保护属性,使其可以被执行(即将一个数据区域转换为代码区域)。之后,你可以通过跳转到该内存区域来执行其中的代码。
英文:
In C and assuming Linux, you can change the protection of a memory region by means of the mprotect()
system call, so that it can be executed (i.e.: turn a data region into a code region). After that, you could execute that region of memory by jumping into it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论