2 Copyright © 2008-2013, The AROS Development Team. All rights reserved.
5 Support functions for POSIX exec*() functions.
7 #include <exec/types.h>
11 #include <aros/libcall.h>
23 #include "__posixc_intbase.h"
30 #include <aros/debug.h>
32 static BOOL
containswhite(const char *str
);
33 static char *escape(const char *str
);
34 static char *appendarg(char *argptr
, int *argptrsize
, const char *arg
, APTR pool
);
35 static char *appendargs(char *argptr
, int *argptrsize
, char *const args
[], APTR pool
);
36 static void __exec_cleanup(struct PosixCIntBase
*PosixCBase
);
38 static void __exec_do_regular(struct PosixCIntBase
*PosixCBase
);
39 static void __exec_do_pretend_child(struct PosixCIntBase
*PosixCBase
);
41 /* Public functions */
42 /********************/
44 void __exec_do(APTR id
)
46 struct PosixCIntBase
*PosixCBase
=
47 (struct PosixCIntBase
*)__aros_getbase_PosixCBase();
49 D(bug("[__exec_do] Entering, id(%x)\n", id
));
54 if (PosixCBase
->flags
& PRETEND_CHILD
)
56 /* forking parent executing child code prior to child taking over */
57 __exec_do_pretend_child(PosixCBase
);
61 /* exec* without fork or forked child executing exec */
62 __exec_do_regular(PosixCBase
);
66 APTR
__exec_prepare(const char *filename
, int searchpath
, char *const argv
[], char *const envp
[])
68 struct PosixCIntBase
*PosixCBase
=
69 (struct PosixCIntBase
*)__aros_getbase_PosixCBase();
70 char *filename2
= NULL
;
71 const char *filename2_dos
= NULL
;
74 char ***environptr
= __posixc_get_environptr();
75 char **environ
= (environptr
!= NULL
) ? *environptr
: NULL
;
77 D(bug("Entering __exec_prepare(\"%s\", %d, %x, %x)\n",
78 filename
, searchpath
, argv
, envp
81 if (filename
== NULL
|| filename
[0] == '\0' || argv
== NULL
)
87 /* Use own memory to allocate so that no stdc.library functions need to be called
88 exec_pool can also be allocated in __exec_valist2array
90 if (!PosixCBase
->exec_pool
)
91 PosixCBase
->exec_pool
= CreatePool(MEMF_PUBLIC
, 1024, 512);
92 if (!PosixCBase
->exec_pool
)
98 /* Remember current stdcbase, child may overwrite it and mess up exiting */
99 PosixCBase
->exec_oldstdcbase
= PosixCBase
->PosixCBase
.StdCBase
;
101 /* Search path if asked and no directory separator is present in the file */
102 if (searchpath
&& index(filename
, '/') == NULL
&& index(filename
, ':') == NULL
)
105 char *path
= NULL
, *path_ptr
, *path_item
;
110 for (i
=0; environ
[i
]; i
++)
112 if (strncmp(environ
[i
], "PATH=", 5) == 0)
114 path
= &environ
[i
][5];
121 path
= getenv("PATH");
124 path
= ":/bin:/usr/bin";
126 D(bug("__exec_prepare: PATH('%s')\n", path
));
128 path_ptr
= AllocPooled(PosixCBase
->exec_pool
, strlen(path
) + 1);
129 strcpy(path_ptr
, path
);
132 D(bug("__exec_prepare: PATH('%s')\n", path
));
135 filename2
= AllocPooled(PosixCBase
->exec_pool
, size
);
142 for(path_ptr
= path
, lock
= (BPTR
)NULL
, path_item
= strsep(&path_ptr
, ",:");
143 lock
== (BPTR
)NULL
&& path_item
!= NULL
;
144 path_item
= strsep(&path_ptr
, ",:")
147 if(path_item
[0] == '\0')
150 len
= strlen(path_item
) + strlen(filename
) + 2;
154 FreePooled(PosixCBase
->exec_pool
, filename2
, size
);
156 filename2
= AllocPooled(PosixCBase
->exec_pool
, size
);
164 strcpy(filename2
, path_item
);
165 strcat(filename2
, "/");
166 strcat(filename2
, filename
);
167 filename2_dos
= __path_u2a(filename2
);
168 lock
= Lock(filename2_dos
, SHARED_LOCK
);
169 D(bug("__exec_prepare: Lock(\"%s\") == %x\n", filename2
, (APTR
)lock
));
172 if(lock
!= (BPTR
)NULL
)
182 filename2
= (char *)filename
;
183 filename2_dos
= __path_u2a(filename2
);
186 if (PosixCBase
->flags
& PRETEND_CHILD
)
188 struct vfork_data
*udata
= PosixCBase
->vfork_data
;
190 udata
->exec_filename
= filename2
;
191 udata
->exec_argv
= argv
;
192 udata
->exec_envp
= envp
;
194 /* Set this so the child knows that __exec_prepare was called */
195 udata
->child_executed
= 1;
197 D(bug("__exec_prepare: Calling child\n"));
198 /* Now call child process, so it will call __exec_prepare */
199 Signal(udata
->child
, 1 << udata
->child_signal
);
201 D(bug("__exec_prepare: Waiting for child to finish __exec_prepare\n"));
202 /* __exec_prepare should be finished now on child */
203 Wait(1 << udata
->parent_signal
);
207 D(bug("__exec_prepare: Continue child immediately on error\n"));
208 Signal(udata
->child
, 1 << udata
->child_signal
);
213 D(bug("__exec_prepare: Exiting from forked __exec_prepare id=%x, errno=%d\n",
214 udata
->exec_id
, udata
->child_errno
217 return (APTR
)PosixCBase
;
220 D(bug("__exec_prepare: Not running as PRETEND_CHILD\n"));
221 PosixCBase
->exec_args
= AllocPooled(PosixCBase
->exec_pool
, argssize
);
222 PosixCBase
->exec_args
[0] = '\0';
224 /* Let's check if it's a script */
225 BPTR fh
= Open((CONST_STRPTR
)filename2_dos
, MODE_OLDFILE
);
228 if(FGetC(fh
) == '#' && FGetC(fh
) == '!')
230 char firstline
[128], *linebuf
, *inter
, *interargs
= NULL
;
232 /* It is a script, let's read the first line */
233 if(FGets(fh
, (STRPTR
)firstline
, sizeof(firstline
) - 1))
235 /* delete end of line if present */
236 if(firstline
[0] && firstline
[strlen(firstline
)-1] == '\n')
237 firstline
[strlen(firstline
)-1] = '\0';
239 while(isblank(*linebuf
)) linebuf
++;
242 /* Interpreter name is here */
244 while(*linebuf
!= '\0' && !isblank(*linebuf
)) linebuf
++;
248 while(isblank(*linebuf
)) linebuf
++;
250 /* Interpreter arguments are here */
254 /* Add interpeter args and the script name to command line args */
255 char *args
[] = {NULL
, NULL
, NULL
};
265 PosixCBase
->exec_args
= appendargs(
266 PosixCBase
->exec_args
, &argssize
, args
, PosixCBase
->exec_pool
268 if (!PosixCBase
->exec_args
)
274 /* Set file to execute as the script interpreter */
275 filename2
= AllocPooled(PosixCBase
->exec_pool
, strlen(inter
) + 1);
276 strcpy(filename2
, inter
);
277 filename2_dos
= __path_u2a(filename2
);
285 /* Simply assume it doesn't exist */
286 errno
= __stdc_ioerr2errno(IoErr());
290 /* Add arguments to command line args */
291 PosixCBase
->exec_args
= appendargs(PosixCBase
->exec_args
, &argssize
, argv
+ 1, PosixCBase
->exec_pool
);
292 if (!PosixCBase
->exec_args
)
298 /* End command line args with '\n' */
299 if(strlen(PosixCBase
->exec_args
) > 0)
300 PosixCBase
->exec_args
[strlen(PosixCBase
->exec_args
) - 1] = '\n';
302 strcat(PosixCBase
->exec_args
, "\n");
304 /* let's make some sanity tests */
306 if(stat(filename2
, &st
) == 0)
308 if(!(st
.st_mode
& S_IXUSR
) && !(st
.st_mode
& S_IXGRP
) && !(st
.st_mode
& S_IXOTH
))
310 /* file is not executable */
314 if(st
.st_mode
& S_IFDIR
)
316 /* it's a directory */
323 /* couldn't stat file */
328 PosixCBase
->exec_taskname
= AllocPooled(PosixCBase
->exec_pool
, strlen(filename2_dos
) + 1);
329 if (!PosixCBase
->exec_taskname
)
334 strcpy(PosixCBase
->exec_taskname
, filename2_dos
);
336 /* Load file to execute */
337 PosixCBase
->exec_seglist
= LoadSeg((CONST_STRPTR
)filename2_dos
);
338 if (!PosixCBase
->exec_seglist
)
344 me
= (struct Process
*)FindTask(NULL
);
346 if (envp
&& envp
!= environ
)
348 struct MinList tempenv
;
349 struct LocalVar
*lv
, *lv2
;
353 /* Remember previous environment variables so they can be put back
354 * if something goes wrong
357 ForeachNodeSafe(&me
->pr_LocalVars
, lv
, lv2
)
359 Remove((struct Node
*)lv
);
360 AddTail((struct List
*)&tempenv
, (struct Node
*)lv
);
363 NEWLIST(&me
->pr_LocalVars
);
366 for (envit
= envp
; *envit
&& env_ok
; envit
++)
367 env_ok
= putenv(*envit
) == 0;
370 /* Old vars may be freed */
371 ForeachNodeSafe(&tempenv
, lv
, lv2
)
373 Remove((struct Node
*)lv
);
374 FreeMem(lv
->lv_Value
, lv
->lv_Len
);
380 ForeachNodeSafe(&me
->pr_LocalVars
, lv
, lv2
)
382 Remove((struct Node
*)lv
);
383 FreeMem(lv
->lv_Value
, lv
->lv_Len
);
387 /* Put old ones back */
388 ForeachNodeSafe(&tempenv
, lv
, lv2
)
390 Remove((struct Node
*)lv
);
391 AddTail((struct List
*)&me
->pr_LocalVars
, (struct Node
*)lv
);
399 D(bug("__exec_prepare: Done, returning %p\n", PosixCBase
));
402 return (APTR
)PosixCBase
;
405 __exec_cleanup(PosixCBase
);
410 static void __exec_do_pretend_child(struct PosixCIntBase
*PosixCBase
)
412 /* When exec is called under vfork condition, the PRETEND_CHILD flag is set
413 and we need to signal child that exec is called.
416 struct vfork_data
*udata
= PosixCBase
->vfork_data
;
418 D(bug("[__exec_do_pretend_child] PRETEND_CHILD\n"));
420 __close_on_exec_fdescs();
422 D(bug("[__exec_do_pretend_child] Notify child to call __exec_do\n"));
424 /* Signal child that __exec_do is called */
425 Signal(udata
->child
, 1 << udata
->child_signal
);
427 /* Clean up in parent */
428 D(bug("[__exec_do_pretend_child] Cleaning up parent\n"));
429 __exec_cleanup(PosixCBase
);
431 /* Continue as parent process */
432 D(bug("[__exec_do_pretend_child] Stop running as PRETEND_CHILD\n"));
435 assert(0); /* Should not be reached */
438 static void __exec_do_regular(struct PosixCIntBase
*PosixCBase
)
441 struct CommandLineInterface
*cli
= Cli();
442 struct Task
*self
= FindTask(NULL
);
445 PosixCBase
->flags
|= EXEC_PARENT
;
447 oldtaskname
= self
->tc_Node
.ln_Name
;
448 self
->tc_Node
.ln_Name
= PosixCBase
->exec_taskname
;
449 SetProgramName((STRPTR
)PosixCBase
->exec_taskname
);
452 /* Set standard files to the standard files from arosc */
453 fdesc
*in
= __getfdesc(STDIN_FILENO
), *out
= __getfdesc(STDOUT_FILENO
),
454 *err
= __getfdesc(STDERR_FILENO
);
455 BPTR oldin
= BNULL
, oldout
= BNULL
, olderr
= BNULL
;
456 char inchanged
= 0, outchanged
= 0, errchanged
= 0;
457 struct Process
*me
= (struct Process
*)FindTask(NULL
);
459 if(in
&& in
->fcb
->handle
!= Input())
461 oldin
= SelectInput(in
->fcb
->handle
);
464 if(out
&& in
->fcb
->handle
!= Output())
466 oldout
= SelectOutput(out
->fcb
->handle
);
473 if (me
->pr_CES
!= err
->fcb
->handle
)
476 else /* me->pr_CES */
478 /* Only replace if stdout != stderr */
479 if (out
&& out
->fcb
->handle
!= err
->fcb
->handle
)
485 me
->pr_CES
= err
->fcb
->handle
;
489 D(bug("[__exec_do_regular] Running program, PosixCBase=%x\n", PosixCBase
));
490 returncode
= RunCommand(
491 PosixCBase
->exec_seglist
,
492 cli
->cli_DefaultStack
* CLI_DEFAULTSTACK_UNIT
,
493 (STRPTR
)PosixCBase
->exec_args
,
494 strlen(PosixCBase
->exec_args
)
497 /* RunCommand() does not Close() standard output so may not flush either.
498 So to be sure flush them here */
506 SelectOutput(oldout
);
510 D(bug("[__exec_do_regular] Program ran, PosixCBase=%x, __aros_getbase_PosixCBase()=%x\n",
511 PosixCBase
, __aros_getbase_PosixCBase()
515 self
->tc_Node
.ln_Name
= oldtaskname
;
516 SetProgramName((STRPTR
)oldtaskname
);
518 __exec_cleanup(PosixCBase
);
520 D(bug("[__exec_do_regular] exiting from __exec()\n"));
525 char *const *__exec_valist2array(const char *arg1
, va_list list
)
527 struct PosixCIntBase
*PosixCBase
=
528 (struct PosixCIntBase
*)__aros_getbase_PosixCBase();
530 static char *no_arg
[] = {NULL
};
534 assert(PosixCBase
->exec_tmparray
== NULL
);
536 va_copy(list2
, list
);
541 for (argit
= va_arg(list
, char *), argc
= 1;
543 argit
= va_arg(list
, char *)
547 if (!(PosixCBase
->exec_tmparray
= malloc((argc
+1)*(sizeof(char *)))))
549 D(bug("__exec_valist2array: Memory allocation failed\n"));
554 PosixCBase
->exec_tmparray
[0] = (char *)arg1
;
555 for (argit
= va_arg(list2
, char *), i
= 1;
556 i
<= argc
; /* i == argc will copy the NULL pointer */
557 argit
= va_arg(list2
, char *), i
++
560 D(bug("arg %d: %x\n", i
, argit
));
561 PosixCBase
->exec_tmparray
[i
] = argit
;
566 return PosixCBase
->exec_tmparray
;
570 void __exec_cleanup_array()
572 struct PosixCIntBase
*PosixCBase
=
573 (struct PosixCIntBase
*)__aros_getbase_PosixCBase();
575 if (PosixCBase
->exec_tmparray
)
577 free((void *)PosixCBase
->exec_tmparray
);
578 PosixCBase
->exec_tmparray
= NULL
;
583 /* Support functions */
584 /*********************/
586 /* Return TRUE if there are any white spaces in the string */
587 static BOOL
containswhite(const char *str
)
590 if(isspace(*str
++)) return TRUE
;
594 /* Escape the string and quote it */
595 static char *escape(const char *str
)
597 const char *strptr
= str
;
598 char *escaped
, *escptr
;
599 /* Additional two characters for '"', and one for '\0' */
600 int bufsize
= strlen(str
) + 3;
601 /* Take into account characters to ecape */
602 while(*strptr
!= '\0')
612 escptr
= escaped
= (char*) malloc(bufsize
);
616 for(strptr
= str
; *strptr
!= '\0'; strptr
++)
624 *escptr
++ = (*strptr
== '\n' ? 'N' : *strptr
);
636 /* Append arg string to argptr increasing argptr if needed */
637 static char *appendarg(char *argptr
, int *argptrsize
, const char *arg
, APTR pool
)
639 while(strlen(argptr
) + strlen(arg
) + 2 > *argptrsize
)
642 int argptrsize2
= 2*(*argptrsize
);
644 argptr2
= AllocPooled(pool
, argptrsize2
);
647 FreePooled(pool
, argptr
, *argptrsize
);
650 strcpy(argptr2
, argptr
);
651 FreePooled(pool
, argptr
, *argptrsize
);
653 *argptrsize
= argptrsize2
;
661 static char *appendargs(char *argptr
, int *argssizeptr
, char *const args
[], APTR pool
)
665 for (argsit
= args
; *argsit
&& argptr
; argsit
++)
667 if(containswhite(*argsit
))
669 char *escaped
= escape(*argsit
);
672 FreePooled(pool
, argptr
, *argssizeptr
);
675 argptr
= appendarg(argptr
, argssizeptr
, escaped
, pool
);
679 argptr
= appendarg(argptr
, argssizeptr
, *argsit
, pool
);
685 static void __exec_cleanup(struct PosixCIntBase
*PosixCBase
)
687 D(bug("__exec_cleanup: me(%x)\n", FindTask(NULL
)));
689 if (PosixCBase
->exec_pool
)
691 DeletePool(PosixCBase
->exec_pool
);
692 PosixCBase
->exec_pool
= NULL
;
694 if (PosixCBase
->exec_seglist
)
696 UnLoadSeg(PosixCBase
->exec_seglist
);
697 PosixCBase
->exec_seglist
= (BPTR
)NULL
;
700 if (PosixCBase
->exec_oldstdcbase
)
702 PosixCBase
->PosixCBase
.StdCBase
= PosixCBase
->exec_oldstdcbase
;
703 PosixCBase
->exec_oldstdcbase
= NULL
;