如何从内存中 运行 任意脚本或可执行文件?
How to run an arbitrary script or executable from memory?
我知道我可以使用像 execl("/bin/sh", "-c", some_string, 0)
这样的系统调用来解释使用特定 shell/interpreter 的 shell 代码的 "snippet"。但在我的例子中,我在内存中有一个任意字符串,它代表一些需要 运行 的完整脚本。也就是说,此 string/memory 缓冲区的内容可能是:
#! /bin/bash
echo "Hello"
或者他们可能是:
#! /usr/bin/env python
print "Hello from Python"
我想理论上 string/buffer 甚至可以包含一个有效的二进制可执行文件,尽管这不是特别优先的。
我的问题是:有没有办法让系统直接从我给它的内存缓冲区启动子进程,而不是将其写入临时文件?或者至少,一种将字符串提供给 shell 并将其路由到正确的解释器的方法?
我发现的所有系统调用似乎都期望现有可执行文件的 路径,而不是采用可执行文件本身的低级别。我不想自己解析shebang或任何东西。
您没有指定操作系统,但由于 #!
特定于 Unix,我认为这就是您所说的。
据我所知,没有系统调用可以从内存块而不是文件中加载程序。加载程序的最低级系统调用是 execve()
函数,它需要要加载的文件的路径名。
My question is: is there any way to have the system launch a
subprocess directly from a buffer of memory I give it, without writing
it to a temporary file? Or at least, a way to give the string to a
shell and have it route it to the proper interpreter?
It seems that all the system calls I've found expect a path to an
existing executable, rather than something low level which takes an
executable itself. I do not want to parse the shebang or anything
myself.
简单回答:没有。
详细答案:
execl
和 shebang 约定是 POSIX 主义,所以这个答案将集中在 POSIX 系统上。无论您要执行的程序是使用 shebang 约定的脚本还是二进制可执行文件,the exec
-family functions 都是 用户空间程序使不同程序 [=31] 的方式=]. system()
和 popen()
等其他接口是在这些接口之上实现的。
exec 系列函数都希望从文件 加载过程映像。此外,一旦成功,它们就会用新图像替换调用它们的进程的内容,包括分配给它的所有内存。
更一般地说,几乎所有现代操作系统都强制执行进程隔离,而进程隔离的核心支柱之一是任何进程都不能访问另一个进程的内存。
我知道我可以使用像 execl("/bin/sh", "-c", some_string, 0)
这样的系统调用来解释使用特定 shell/interpreter 的 shell 代码的 "snippet"。但在我的例子中,我在内存中有一个任意字符串,它代表一些需要 运行 的完整脚本。也就是说,此 string/memory 缓冲区的内容可能是:
#! /bin/bash
echo "Hello"
或者他们可能是:
#! /usr/bin/env python
print "Hello from Python"
我想理论上 string/buffer 甚至可以包含一个有效的二进制可执行文件,尽管这不是特别优先的。
我的问题是:有没有办法让系统直接从我给它的内存缓冲区启动子进程,而不是将其写入临时文件?或者至少,一种将字符串提供给 shell 并将其路由到正确的解释器的方法?
我发现的所有系统调用似乎都期望现有可执行文件的 路径,而不是采用可执行文件本身的低级别。我不想自己解析shebang或任何东西。
您没有指定操作系统,但由于 #!
特定于 Unix,我认为这就是您所说的。
据我所知,没有系统调用可以从内存块而不是文件中加载程序。加载程序的最低级系统调用是 execve()
函数,它需要要加载的文件的路径名。
My question is: is there any way to have the system launch a subprocess directly from a buffer of memory I give it, without writing it to a temporary file? Or at least, a way to give the string to a shell and have it route it to the proper interpreter?
It seems that all the system calls I've found expect a path to an existing executable, rather than something low level which takes an executable itself. I do not want to parse the shebang or anything myself.
简单回答:没有。
详细答案:
execl
和 shebang 约定是 POSIX 主义,所以这个答案将集中在 POSIX 系统上。无论您要执行的程序是使用 shebang 约定的脚本还是二进制可执行文件,the exec
-family functions 都是 用户空间程序使不同程序 [=31] 的方式=]. system()
和 popen()
等其他接口是在这些接口之上实现的。
exec 系列函数都希望从文件 加载过程映像。此外,一旦成功,它们就会用新图像替换调用它们的进程的内容,包括分配给它的所有内存。
更一般地说,几乎所有现代操作系统都强制执行进程隔离,而进程隔离的核心支柱之一是任何进程都不能访问另一个进程的内存。