1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
/* execle() function: Execute a program, replacing the current process.
Copyright (C) 2020-2021 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <bruno@clisp.org>, 2020. */
/* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
may optimize away the arg0 == NULL test below. */
#define _GL_ARG_NONNULL(params)
#include <config.h>
/* Specification. */
#include <unistd.h>
#include <errno.h>
#include <stdarg.h>
#include "malloca.h"
int
execle (const char *program, const char *arg0, ...)
{
va_list args;
/* The callee is not expecting a NULL argv[0]. */
if (arg0 == NULL)
{
errno = EINVAL;
return -1;
}
/* Count the number of arguments (including arg0 and the trailing NULL). */
size_t count = 1;
va_start (args, arg0);
for (;;)
{
count++;
if (va_arg (args, const char *) == NULL)
break;
}
va_end (args);
/* Allocate the argument vector. */
const char **argv = (const char **) malloca (count * sizeof (const char *));
if (argv == NULL)
{
errno = ENOMEM;
return -1;
}
/* Copy the arguments into the argument vector. */
{
size_t i = 0;
argv[i++] = arg0;
va_start (args, arg0);
for (; i < count;)
argv[i++] = va_arg (args, const char *);
}
char * const *env = va_arg (args, char * const *);
va_end (args);
/* Invoke execve. */
execve (program, argv, env);
/* If execve returned, it must have failed. */
int saved_errno = errno;
freea (argv);
errno = saved_errno;
return -1;
}
|