将空程序参数向量传递给execve()是否合法? [英] Is it legal to pass a null program argument vector to execve()?

查看:249
本文介绍了将空程序参数向量传递给execve()是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下C代码(x86_64)

  #include< unistd.h> 
int main()
{
execve(/ bin / ls,0,0);
}

我编译为 gcc ac SIGABRT 错误


 通过exec系统调用传递NULL argv [0]。 
中止


接下来在gdb上运行,也得到了一个 SIGABRT ,但是我做了第二次运行并且工作!


<$ p $
启动程序:/ bin / ls
[使用libthread_db启用线程调试]
使用主机libthread_db库/lib/x86_64-linux-gnu/libthread_db.so.1 。


为什么?




我测试了 / bin / sh ,发现它始终与* argv [] = NULL一起工作...

再次,我编写了一些可执行文件(不需要任何参数)来测试并发现它们全部工作。所以我猜想只有 / bin / sh 或其他shell可以与* argv []设置为NULL一起使用,其他文件(如 / bin / ls )出现故障或表现异常。 解决方案

p> execve()系统调用的手册页说明


argv envp 数组必须每个在数组末尾包含一个空指针。 / p>

如果您的程序不符合这些要求,那么从这一点开始事情会变得不确定。如果它对某些程序起作用,那只是运气不好。






手册页还说


按照惯例,这些字符串中的第一个(即 argv [0] )应该包含文件名与执行的文件相关联。

该约定相当强大(由POSIX强制执行),因此无法执行的程序可能会考虑越野车。如果您要依赖 argv [0] main()来说,测试它是否被正确调用可能是一个好主意c $ c>,所以你可能会失败并带有一个很好的错误消息,而不是一个错误,但并不是所有的程序都可以。


Consider following C code (x86_64)

#include <unistd.h>
int main()
{
    execve("/bin/ls", 0, 0);
}

I compiled as gcc a.c and executed; I got a SIGABRT with error

A NULL argv[0] was passed through an exec system call.  
Aborted

Next running on gdb, at first I also got a SIGABRT, however I did second run and it worked!

Starting program: /bin/ls 
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Why?


I tested for /bin/sh and found it always worked with *argv[] = NULL ...
Again I wrote some executable file (without any parameter needed) to test and found all them work.

So I guess only /bin/sh or other shells would work with *argv[] set to NULL, other files (like /bin/ls) fail or behave unexpectedly.

解决方案

The man page for the execve() system call says

The argv and envp arrays must each include a null pointer at the end of the array.

If your program doesn't conform to those requirements, there's no certainty of how well things will go from that point on. If it "works" for some programs, that's just bad luck.


The man page also says

By convention, the first of these strings (i.e., argv[0]) should contain the filename associated with the file being executed.

That convention is rather strong (mandated by POSIX), so programs that fail to do so can be considered buggy. It's probably a good idea for your main() to test it's been called correctly if you're going to rely on argv[0] so you can fail with a nice error message rather than a fault, but not all programs do.

这篇关于将空程序参数向量传递给execve()是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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