1EXECVE(2)                  Linux Programmer's Manual                 EXECVE(2)
2
3
4

NAME

6       execve - execute program
7

SYNOPSIS

9       #include <unistd.h>
10
11       int execve(const char *pathname, char *const argv[],
12                  char *const envp[]);
13

DESCRIPTION

15       execve() executes the program referred to by pathname.  This causes the
16       program that is currently being run by the calling process  to  be  re‐
17       placed  with  a  new  program,  with newly initialized stack, heap, and
18       (initialized and uninitialized) data segments.
19
20       pathname must be either a binary executable, or a script starting  with
21       a line of the form:
22
23           #!interpreter [optional-arg]
24
25       For details of the latter case, see "Interpreter scripts" below.
26
27       argv  is  an  array of pointers to strings passed to the new program as
28       its command-line arguments.  By convention, the first of these  strings
29       (i.e.,  argv[0])  should  contain the filename associated with the file
30       being executed.  The argv array must be terminated by a  NULL  pointer.
31       (Thus, in the new program, argv[argc] will be NULL.)
32
33       envp  is  an  array  of pointers to strings, conventionally of the form
34       key=value, which are passed as the environment of the new program.  The
35       envp array must be terminated by a NULL pointer.
36
37       The  argument  vector  and  environment can be accessed by the new pro‐
38       gram's main function, when it is defined as:
39
40           int main(int argc, char *argv[], char *envp[])
41
42       Note, however, that the use of a third argument to the main function is
43       not  specified in POSIX.1; according to POSIX.1, the environment should
44       be accessed via the external variable environ(7).
45
46       execve() does not return on success, and the  text,  initialized  data,
47       uninitialized  data  (bss),  and stack of the calling process are over‐
48       written according to the contents of the newly loaded program.
49
50       If the current program is being ptraced, a SIGTRAP signal is sent to it
51       after a successful execve().
52
53       If  the set-user-ID bit is set on the program file referred to by path‐
54       name, then the effective user ID of the calling process is  changed  to
55       that  of the owner of the program file.  Similarly, if the set-group-ID
56       bit is set on the program file, then the  effective  group  ID  of  the
57       calling process is set to the group of the program file.
58
59       The  aforementioned  transformations  of the effective IDs are not per‐
60       formed (i.e., the set-user-ID and set-group-ID bits are ignored) if any
61       of the following is true:
62
63       *  the  no_new_privs  attribute  is  set  for  the  calling thread (see
64          prctl(2));
65
66       *  the underlying filesystem is mounted nosuid (the MS_NOSUID flag  for
67          mount(2)); or
68
69       *  the calling process is being ptraced.
70
71       The capabilities of the program file (see capabilities(7)) are also ig‐
72       nored if any of the above are true.
73
74       The effective user ID of the process is copied to the  saved  set-user-
75       ID; similarly, the effective group ID is copied to the saved set-group-
76       ID.  This copying takes place after any effective ID changes that occur
77       because of the set-user-ID and set-group-ID mode bits.
78
79       The process's real UID and real GID, as well as its supplementary group
80       IDs, are unchanged by a call to execve().
81
82       If the executable is an a.out dynamically linked binary executable con‐
83       taining  shared-library  stubs,  the  Linux  dynamic linker ld.so(8) is
84       called at the start of execution to bring needed  shared  objects  into
85       memory and link the executable with them.
86
87       If  the  executable  is a dynamically linked ELF executable, the inter‐
88       preter named in the PT_INTERP segment is used to load the needed shared
89       objects.  This interpreter is typically /lib/ld-linux.so.2 for binaries
90       linked with glibc (see ld-linux.so(8)).
91
92   Effect on process attributes
93       All process attributes are preserved during  an  execve(),  except  the
94       following:
95
96       *  The  dispositions  of any signals that are being caught are reset to
97          the default (signal(7)).
98
99       *  Any alternate signal stack is not preserved (sigaltstack(2)).
100
101       *  Memory mappings are not preserved (mmap(2)).
102
103       *  Attached System V shared memory segments are detached (shmat(2)).
104
105       *  POSIX shared memory regions are unmapped (shm_open(3)).
106
107       *  Open POSIX message queue descriptors are closed (mq_overview(7)).
108
109       *  Any open POSIX named semaphores are closed (sem_overview(7)).
110
111       *  POSIX timers are not preserved (timer_create(2)).
112
113       *  Any open directory streams are closed (opendir(3)).
114
115       *  Memory locks are not preserved (mlock(2), mlockall(2)).
116
117       *  Exit handlers are not preserved (atexit(3), on_exit(3)).
118
119       *  The  floating-point  environment  is  reset  to  the  default   (see
120          fenv(3)).
121
122       The  process  attributes  in  the  preceding  list are all specified in
123       POSIX.1.  The following Linux-specific process attributes are also  not
124       preserved during an execve():
125
126       *  The  process's  "dumpable" attribute is set to the value 1, unless a
127          set-user-ID program, a set-group-ID program, or a program with capa‐
128          bilities  is being executed, in which case the dumpable flag may in‐
129          stead be reset to the value in  /proc/sys/fs/suid_dumpable,  in  the
130          circumstances  described  under  PR_SET_DUMPABLE  in prctl(2).  Note
131          that changes to the "dumpable"  attribute  may  cause  ownership  of
132          files in the process's /proc/[pid] directory to change to root:root,
133          as described in proc(5).
134
135       *  The prctl(2) PR_SET_KEEPCAPS flag is cleared.
136
137       *  (Since Linux 2.4.36 / 2.6.23) If a set-user-ID or set-group-ID  pro‐
138          gram is being executed, then the parent death signal set by prctl(2)
139          PR_SET_PDEATHSIG flag is cleared.
140
141       *  The process name, as set by prctl(2) PR_SET_NAME (and  displayed  by
142          ps -o comm), is reset to the name of the new executable file.
143
144       *  The  SECBIT_KEEP_CAPS  securebits  flag  is  cleared.  See capabili‐
145          ties(7).
146
147       *  The termination signal is reset to SIGCHLD (see clone(2)).
148
149       *  The file descriptor table is unshared, undoing  the  effect  of  the
150          CLONE_FILES flag of clone(2).
151
152       Note the following further points:
153
154       *  All  threads  other  than the calling thread are destroyed during an
155          execve().  Mutexes, condition variables, and other pthreads  objects
156          are not preserved.
157
158       *  The  equivalent  of  setlocale(LC_ALL,  "C")  is executed at program
159          start-up.
160
161       *  POSIX.1 specifies that the dispositions of any signals that are  ig‐
162          nored  or  set to the default are left unchanged.  POSIX.1 specifies
163          one exception: if SIGCHLD is being ignored, then  an  implementation
164          may  leave  the  disposition  unchanged  or reset it to the default;
165          Linux does the former.
166
167       *  Any   outstanding   asynchronous   I/O   operations   are   canceled
168          (aio_read(3), aio_write(3)).
169
170       *  For  the  handling  of  capabilities  during execve(), see capabili‐
171          ties(7).
172
173       *  By default, file descriptors remain open across an  execve().   File
174          descriptors  that  are  marked close-on-exec are closed; see the de‐
175          scription of FD_CLOEXEC in  fcntl(2).   (If  a  file  descriptor  is
176          closed,  this will cause the release of all record locks obtained on
177          the underlying file by this process.   See  fcntl(2)  for  details.)
178          POSIX.1 says that if file descriptors 0, 1, and 2 would otherwise be
179          closed after a successful execve(), and the process would gain priv‐
180          ilege  because  the  set-user-ID or set-group-ID mode bit was set on
181          the executed file, then the system may open an unspecified file  for
182          each of these file descriptors.  As a general principle, no portable
183          program, whether privileged or not, can assume that these three file
184          descriptors will remain closed across an execve().
185
186   Interpreter scripts
187       An  interpreter  script  is a text file that has execute permission en‐
188       abled and whose first line is of the form:
189
190           #!interpreter [optional-arg]
191
192       The interpreter must be a valid pathname for an executable file.
193
194       If the pathname argument of execve() specifies an  interpreter  script,
195       then interpreter will be invoked with the following arguments:
196
197           interpreter [optional-arg] pathname arg...
198
199       where pathname is the pathname of the file specified as the first argu‐
200       ment of execve(), and arg...  is the series of words pointed to by  the
201       argv  argument of execve(), starting at argv[1].  Note that there is no
202       way to get the argv[0] that was passed to the execve() call.
203
204       For portable use, optional-arg should either be absent, or be specified
205       as  a  single word (i.e., it should not contain white space); see NOTES
206       below.
207
208       Since Linux 2.6.28, the kernel permits the interpreter of a  script  to
209       itself  be  a  script.   This permission is recursive, up to a limit of
210       four recursions, so that the interpreter may be a script which  is  in‐
211       terpreted by a script, and so on.
212
213   Limits on size of arguments and environment
214       Most  UNIX  implementations  impose some limit on the total size of the
215       command-line argument (argv) and environment (envp) strings that may be
216       passed to a new program.  POSIX.1 allows an implementation to advertise
217       this limit using the ARG_MAX constant (either defined in <limits.h>  or
218       available at run time using the call sysconf(_SC_ARG_MAX)).
219
220       On  Linux prior to kernel 2.6.23, the memory used to store the environ‐
221       ment and argument strings was limited to 32 pages (defined by the  ker‐
222       nel  constant  MAX_ARG_PAGES).  On architectures with a 4-kB page size,
223       this yields a maximum size of 128 kB.
224
225       On kernel 2.6.23 and later, most architectures support a size limit de‐
226       rived from the soft RLIMIT_STACK resource limit (see getrlimit(2)) that
227       is in force at the time of the execve() call.  (Architectures  with  no
228       memory  management  unit are excepted: they maintain the limit that was
229       in effect before kernel 2.6.23.)  This change allows programs to have a
230       much larger argument and/or environment list.  For these architectures,
231       the total size is limited to 1/4 of the allowed stack size.   (Imposing
232       the  1/4-limit  ensures  that  the  new  program  always has some stack
233       space.)  Additionally, the total size is limited to 3/4 of the value of
234       the  kernel  constant _STK_LIM (8 MiB).  Since Linux 2.6.25, the kernel
235       also places a floor of 32 pages on this size limit, so that, even  when
236       RLIMIT_STACK  is  set  very low, applications are guaranteed to have at
237       least as much argument and environment space as was provided  by  Linux
238       2.6.22  and  earlier.  (This guarantee was not provided in Linux 2.6.23
239       and 2.6.24.)  Additionally, the limit per string is 32 pages (the  ker‐
240       nel  constant  MAX_ARG_STRLEN),  and  the  maximum number of strings is
241       0x7FFFFFFF.
242

RETURN VALUE

244       On success, execve() does not return, on error -1 is returned, and  er‐
245       rno is set to indicate the error.
246

ERRORS

248       E2BIG  The total number of bytes in the environment (envp) and argument
249              list (argv) is too large.
250
251       EACCES Search permission is denied on a component of the path prefix of
252              pathname  or  the  name  of  a  script  interpreter.   (See also
253              path_resolution(7).)
254
255       EACCES The file or a script interpreter is not a regular file.
256
257       EACCES Execute permission is denied for the file or a script or ELF in‐
258              terpreter.
259
260       EACCES The filesystem is mounted noexec.
261
262       EAGAIN (since Linux 3.1)
263              Having  changed  its  real UID using one of the set*uid() calls,
264              the caller was—and is now still—above its RLIMIT_NPROC  resource
265              limit  (see  setrlimit(2)).   For a more detailed explanation of
266              this error, see NOTES.
267
268       EFAULT pathname or one of the pointers in  the  vectors  argv  or  envp
269              points outside your accessible address space.
270
271       EINVAL An  ELF  executable  had  more than one PT_INTERP segment (i.e.,
272              tried to name more than one interpreter).
273
274       EIO    An I/O error occurred.
275
276       EISDIR An ELF interpreter was a directory.
277
278       ELIBBAD
279              An ELF interpreter was not in a recognized format.
280
281       ELOOP  Too many symbolic links were encountered in  resolving  pathname
282              or the name of a script or ELF interpreter.
283
284       ELOOP  The  maximum recursion limit was reached during recursive script
285              interpretation (see "Interpreter scripts", above).  Before Linux
286              3.8, the error produced for this case was ENOEXEC.
287
288       EMFILE The per-process limit on the number of open file descriptors has
289              been reached.
290
291       ENAMETOOLONG
292              pathname is too long.
293
294       ENFILE The system-wide limit on the total number of open files has been
295              reached.
296
297       ENOENT The file pathname or a script or ELF interpreter does not exist.
298
299       ENOEXEC
300              An  executable  is  not in a recognized format, is for the wrong
301              architecture, or has some other format error that means it  can‐
302              not be executed.
303
304       ENOMEM Insufficient kernel memory was available.
305
306       ENOTDIR
307              A  component  of  the path prefix of pathname or a script or ELF
308              interpreter is not a directory.
309
310       EPERM  The filesystem is mounted nosuid, the user is not the superuser,
311              and the file has the set-user-ID or set-group-ID bit set.
312
313       EPERM  The  process  is being traced, the user is not the superuser and
314              the file has the set-user-ID or set-group-ID bit set.
315
316       EPERM  A "capability-dumb" applications would not obtain the  full  set
317              of  permitted  capabilities granted by the executable file.  See
318              capabilities(7).
319
320       ETXTBSY
321              The specified executable was open for writing  by  one  or  more
322              processes.
323

CONFORMING TO

325       POSIX.1-2001,  POSIX.1-2008, SVr4, 4.3BSD.  POSIX does not document the
326       #! behavior, but it exists (with some variations) on  other  UNIX  sys‐
327       tems.
328

NOTES

330       One  sometimes  sees  execve()  (and the related functions described in
331       exec(3)) described as "executing a new process" (or similar).  This  is
332       a  highly  misleading  description:  there  is no new process; many at‐
333       tributes of the calling process remain unchanged  (in  particular,  its
334       PID).   All  that execve() does is arrange for an existing process (the
335       calling process) to execute a new program.
336
337       Set-user-ID and set-group-ID processes can not be ptrace(2)d.
338
339       The result of mounting a filesystem nosuid varies across  Linux  kernel
340       versions:  some  will  refuse execution of set-user-ID and set-group-ID
341       executables when this would give the user powers they did not have  al‐
342       ready  (and  return  EPERM),  some will just ignore the set-user-ID and
343       set-group-ID bits and exec() successfully.
344
345       On Linux, argv and envp can be specified as NULL.  In both cases,  this
346       has  the  same effect as specifying the argument as a pointer to a list
347       containing a single null pointer.  Do not take advantage of  this  non‐
348       standard and nonportable misfeature!  On many other UNIX systems, spec‐
349       ifying argv as NULL will result in an error (EFAULT).  Some other  UNIX
350       systems treat the envp==NULL case the same as Linux.
351
352       POSIX.1  says  that  values  returned by sysconf(3) should be invariant
353       over the lifetime of a process.  However, since Linux  2.6.23,  if  the
354       RLIMIT_STACK  resource  limit  changes,  then  the  value  reported  by
355       _SC_ARG_MAX will also change, to reflect the fact  that  the  limit  on
356       space  for holding command-line arguments and environment variables has
357       changed.
358
359       In most cases where execve() fails, control returns to the original ex‐
360       ecutable  image,  and the caller of execve() can then handle the error.
361       However, in (rare) cases (typically  caused  by  resource  exhaustion),
362       failure  may occur past the point of no return: the original executable
363       image has been torn down, but the new image  could  not  be  completely
364       built.   In  such  cases,  the  kernel kills the process with a SIGSEGV
365       (SIGKILL until Linux 3.17) signal.
366
367   Interpreter scripts
368       The kernel imposes a maximum length on the text that follows  the  "#!"
369       characters  at  the  start of a script; characters beyond the limit are
370       ignored.  Before Linux 5.1, the limit is 127 characters.   Since  Linux
371       5.1, the limit is 255 characters.
372
373       The  semantics  of  the  optional-arg argument of an interpreter script
374       vary across implementations.  On Linux, the entire string following the
375       interpreter name is passed as a single argument to the interpreter, and
376       this string can include white space.  However, behavior differs on some
377       other systems.  Some systems use the first white space to terminate op‐
378       tional-arg.  On some systems, an interpreter script can  have  multiple
379       arguments, and white spaces in optional-arg are used to delimit the ar‐
380       guments.
381
382       Linux (like most other modern UNIX systems) ignores the set-user-ID and
383       set-group-ID bits on scripts.
384
385   execve() and EAGAIN
386       A  more  detailed explanation of the EAGAIN error that can occur (since
387       Linux 3.1) when calling execve() is as follows.
388
389       The EAGAIN error can occur when a  preceding  call  to  setuid(2),  se‐
390       treuid(2),  or  setresuid(2)  caused the real user ID of the process to
391       change, and that change caused the process to exceed  its  RLIMIT_NPROC
392       resource limit (i.e., the number of processes belonging to the new real
393       UID exceeds the resource limit).  From Linux 2.6.0 to 3.0, this  caused
394       the  set*uid() call to fail.  (Prior to 2.6, the resource limit was not
395       imposed on processes that changed their user IDs.)
396
397       Since Linux 3.1, the scenario  just  described  no  longer  causes  the
398       set*uid()  call  to  fail,  because  it too often led to security holes
399       where buggy applications didn't check the  return  status  and  assumed
400       that—if  the  caller had root privileges—the call would always succeed.
401       Instead, the set*uid() calls now successfully change the real UID,  but
402       the kernel sets an internal flag, named PF_NPROC_EXCEEDED, to note that
403       the RLIMIT_NPROC resource limit has been exceeded.  If the PF_NPROC_EX‐
404       CEEDED flag is set and the resource limit is still exceeded at the time
405       of a subsequent execve() call, that call fails with the  error  EAGAIN.
406       This kernel logic ensures that the RLIMIT_NPROC resource limit is still
407       enforced for the common privileged daemon  workflow—namely,  fork(2)  +
408       set*uid() + execve().
409
410       If  the  resource  limit  was not still exceeded at the time of the ex‐
411       ecve() call (because other processes belonging to this real UID  termi‐
412       nated  between  the set*uid() call and the execve() call), then the ex‐
413       ecve() call  succeeds  and  the  kernel  clears  the  PF_NPROC_EXCEEDED
414       process flag.  The flag is also cleared if a subsequent call to fork(2)
415       by this process succeeds.
416
417   Historical
418       With UNIX V6, the argument list of an exec() call was ended by 0, while
419       the  argument  list  of main was ended by -1.  Thus, this argument list
420       was not directly usable in a further exec() call.  Since UNIX V7,  both
421       are NULL.
422

EXAMPLES

424       The  following  program  is designed to be execed by the second program
425       below.  It just echoes its command-line arguments, one per line.
426
427           /* myecho.c */
428
429           #include <stdio.h>
430           #include <stdlib.h>
431
432           int
433           main(int argc, char *argv[])
434           {
435               for (int j = 0; j < argc; j++)
436                   printf("argv[%d]: %s\n", j, argv[j]);
437
438               exit(EXIT_SUCCESS);
439           }
440
441       This program can be used to exec the program named in its  command-line
442       argument:
443
444           /* execve.c */
445
446           #include <stdio.h>
447           #include <stdlib.h>
448           #include <unistd.h>
449
450           int
451           main(int argc, char *argv[])
452           {
453               char *newargv[] = { NULL, "hello", "world", NULL };
454               char *newenviron[] = { NULL };
455
456               if (argc != 2) {
457                   fprintf(stderr, "Usage: %s <file-to-exec>\n", argv[0]);
458                   exit(EXIT_FAILURE);
459               }
460
461               newargv[0] = argv[1];
462
463               execve(argv[1], newargv, newenviron);
464               perror("execve");   /* execve() returns only on error */
465               exit(EXIT_FAILURE);
466           }
467
468       We can use the second program to exec the first as follows:
469
470           $ cc myecho.c -o myecho
471           $ cc execve.c -o execve
472           $ ./execve ./myecho
473           argv[0]: ./myecho
474           argv[1]: hello
475           argv[2]: world
476
477       We  can  also use these programs to demonstrate the use of a script in‐
478       terpreter.  To do this we create a script whose  "interpreter"  is  our
479       myecho program:
480
481           $ cat > script
482           #!./myecho script-arg
483           ^D
484           $ chmod +x script
485
486       We can then use our program to exec the script:
487
488           $ ./execve ./script
489           argv[0]: ./myecho
490           argv[1]: script-arg
491           argv[2]: ./script
492           argv[3]: hello
493           argv[4]: world
494

SEE ALSO

496       chmod(2), execveat(2), fork(2), get_robust_list(2), ptrace(2), exec(3),
497       fexecve(3), getauxval(3), getopt(3), system(3),  capabilities(7),  cre‐
498       dentials(7), environ(7), path_resolution(7), ld.so(8)
499

COLOPHON

501       This  page  is  part of release 5.13 of the Linux man-pages project.  A
502       description of the project, information about reporting bugs,  and  the
503       latest     version     of     this    page,    can    be    found    at
504       https://www.kernel.org/doc/man-pages/.
505
506
507
508Linux                             2021-08-27                         EXECVE(2)
Impressum