mirrored from git://git.code.sf.net/p/zsh/code
-
Notifications
You must be signed in to change notification settings - Fork 449
/
Copy pathexec.c
6343 lines (5797 loc) · 163 KB
/
exec.c
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* exec.c - command execution
*
* This file is part of zsh, the Z shell.
*
* Copyright (c) 1992-1997 Paul Falstad
* All rights reserved.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and to distribute modified versions of this software for any
* purpose, provided that the above copyright notice and the following
* two paragraphs appear in all copies of this software.
*
* In no event shall Paul Falstad or the Zsh Development Group be liable
* to any party for direct, indirect, special, incidental, or consequential
* damages arising out of the use of this software and its documentation,
* even if Paul Falstad and the Zsh Development Group have been advised of
* the possibility of such damage.
*
* Paul Falstad and the Zsh Development Group specifically disclaim any
* warranties, including, but not limited to, the implied warranties of
* merchantability and fitness for a particular purpose. The software
* provided hereunder is on an "as is" basis, and Paul Falstad and the
* Zsh Development Group have no obligation to provide maintenance,
* support, updates, enhancements, or modifications.
*
*/
#include "zsh.mdh"
#include "exec.pro"
/* Flags for last argument of addvars */
enum {
/* Export the variable for "VAR=val cmd ..." */
ADDVAR_EXPORT = 1 << 0,
/* Apply restrictions for variable */
ADDVAR_RESTRICT = 1 << 1,
/* Variable list is being restored later */
ADDVAR_RESTORE = 1 << 2
};
/* Structure in which to save values around shell function call */
struct funcsave {
char opts[OPT_SIZE];
char *argv0;
int zoptind, lastval, optcind, numpipestats;
int *pipestats;
char *scriptname;
int breaks, contflag, loops, emulation, noerrexit, oflags, restore_sticky;
Emulation_options sticky;
struct funcstack fstack;
};
typedef struct funcsave *Funcsave;
/*
* used to suppress ERREXIT and trapping of SIGZERR, SIGEXIT.
* Bits from noerrexit_bits.
*/
/**/
int noerrexit;
/* used to suppress ERREXIT or ERRRETURN for one occurrence: 0 or 1 */
/**/
int this_noerrexit;
/*
* noerrs = 1: suppress error messages
* noerrs = 2: don't set errflag on parse error, either
*/
/**/
mod_export int noerrs;
/* do not save history on exec and exit */
/**/
int nohistsave;
/* error flag: bits from enum errflag_bits */
/**/
mod_export int errflag;
/*
* State of trap return value. Value is from enum trap_state.
*/
/**/
int trap_state;
/*
* Value associated with return from a trap.
* This is only active if we are inside a trap, else its value
* is irrelevant. It is initialised to -1 for a function trap and
* -2 for a non-function trap and if negative is decremented as
* we go deeper into functions and incremented as we come back up.
* The value is used to decide if an explicit "return" should cause
* a return from the caller of the trap; it does this by setting
* trap_return to a status (i.e. a non-negative value).
*
* In summary, trap_return is
* - zero unless we are in a trap
* - negative in a trap unless it has triggered. Code uses this
* to detect an active trap.
* - non-negative in a trap once it was triggered. It should remain
* non-negative until restored after execution of the trap.
*/
/**/
int trap_return;
/* != 0 if this is a subshell */
/**/
int subsh;
/* != 0 if we have a return pending */
/**/
mod_export int retflag;
/**/
long lastval2;
/* The table of file descriptors. A table element is zero if the *
* corresponding fd is not used by the shell. It is greater than *
* 1 if the fd is used by a <(...) or >(...) substitution and 1 if *
* it is an internal file descriptor which must be closed before *
* executing an external command. The first ten elements of the *
* table is not used. A table element is set by movefd and cleard *
* by zclose. */
/**/
mod_export unsigned char *fdtable;
/* The allocated size of fdtable */
/**/
int fdtable_size;
/* The highest fd that marked with nonzero in fdtable */
/**/
mod_export int max_zsh_fd;
/* input fd from the coprocess */
/**/
mod_export int coprocin;
/* output fd from the coprocess */
/**/
mod_export int coprocout;
/* count of file locks recorded in fdtable */
/**/
int fdtable_flocks;
/* != 0 if the line editor is active */
/**/
mod_export int zleactive;
/* pid of process undergoing 'process substitution' */
/**/
pid_t cmdoutpid;
/* pid of last process started by <(...), >(...) */
/**/
mod_export pid_t procsubstpid;
/* exit status of process undergoing 'process substitution' */
/**/
int cmdoutval;
/*
* This is set by an exiting $(...) substitution to indicate we need
* to retain the status. We initialize it to zero if we think we need
* to reset the status for a command.
*/
/**/
int use_cmdoutval;
/* The context in which a shell function is called, see SFC_* in zsh.h. */
/**/
mod_export int sfcontext;
/* Stack to save some variables before executing a signal handler function */
/**/
struct execstack *exstack;
/* Stack with names of function calls, 'source' calls, and 'eval' calls
* currently active. */
/**/
mod_export Funcstack funcstack;
#define execerr() \
do { \
if (!forked) { \
redir_err = lastval = 1; \
goto done; \
} else { \
_exit(1); \
} \
} while (0)
static int doneps4;
static char *STTYval;
static char *blank_env[] = { NULL };
/* Execution functions. */
static int (*execfuncs[WC_COUNT-WC_CURSH]) _((Estate, int)) = {
execcursh, exectime, NULL /* execfuncdef handled specially */,
execfor, execselect,
execwhile, execrepeat, execcase, execif, execcond,
execarith, execautofn, exectry
};
/* structure for command builtin for when it is used with -v or -V */
static struct builtin commandbn =
BUILTIN("command", 0, bin_whence, 0, -1, BIN_COMMAND, "pvV", NULL);
/* parse string into a list */
/**/
mod_export Eprog
parse_string(char *s, int reset_lineno)
{
Eprog p;
zlong oldlineno;
zcontext_save();
inpush(s, INP_LINENO, NULL);
strinbeg(0);
oldlineno = lineno;
if (reset_lineno)
lineno = 1;
p = parse_list();
lineno = oldlineno;
if (tok == LEXERR && !lastval)
lastval = 1;
strinend();
inpop();
zcontext_restore();
return p;
}
/**/
#ifdef HAVE_GETRLIMIT
/* the resource limits for the shell and its children */
/**/
mod_export struct rlimit current_limits[RLIM_NLIMITS], limits[RLIM_NLIMITS];
/**/
mod_export int
zsetlimit(int limnum, char *nam)
{
if (limits[limnum].rlim_max != current_limits[limnum].rlim_max ||
limits[limnum].rlim_cur != current_limits[limnum].rlim_cur) {
if (setrlimit(limnum, limits + limnum)) {
if (nam)
zwarnnam(nam, "setrlimit failed: %e", errno);
limits[limnum] = current_limits[limnum];
return -1;
}
current_limits[limnum] = limits[limnum];
}
return 0;
}
/**/
mod_export int
setlimits(char *nam)
{
int limnum;
int ret = 0;
for (limnum = 0; limnum < RLIM_NLIMITS; limnum++)
if (zsetlimit(limnum, nam))
ret++;
return ret;
}
/**/
#endif /* HAVE_GETRLIMIT */
/* fork and set limits */
/**/
static pid_t
zfork(struct timeval *tv)
{
pid_t pid;
struct timezone dummy_tz;
/*
* Is anybody willing to explain this test?
*/
if (thisjob != -1 && thisjob >= jobtabsize - 1 && !expandjobtab()) {
zerr("job table full");
return -1;
}
if (tv)
gettimeofday(tv, &dummy_tz);
/*
* Queueing signals is necessary on Linux because fork()
* manipulates mutexes, leading to deadlock in memory
* allocation. We don't expect fork() to be particularly
* zippy anyway.
*/
queue_signals();
pid = fork();
unqueue_signals();
if (pid == -1) {
zerr("fork failed: %e", errno);
return -1;
}
#ifdef HAVE_GETRLIMIT
if (!pid)
/* set resource limits for the child process */
setlimits(NULL);
#endif
return pid;
}
/*
* Allen Edeln gebiet ich Andacht,
* Hohen und Niedern von Heimdalls Geschlecht;
* Ich will list_pipe's Wirken kuenden
* Die aeltesten Sagen, der ich mich entsinne...
*
* In most shells, if you do something like:
*
* cat foo | while read a; do grep $a bar; done
*
* the shell forks and executes the loop in the sub-shell thus created.
* In zsh this traditionally executes the loop in the current shell, which
* is nice to have if the loop does something to change the shell, like
* setting parameters or calling builtins.
* Putting the loop in a sub-shell makes life easy, because the shell only
* has to put it into the job-structure and then treats it as a normal
* process. Suspending and interrupting is no problem then.
* Some years ago, zsh either couldn't suspend such things at all, or
* it got really messed up when users tried to do it. As a solution, we
* implemented the list_pipe-stuff, which has since then become a reason
* for many nightmares.
* Pipelines like the one above are executed by the functions in this file
* which call each other (and sometimes recursively). The one above, for
* example would lead to a function call stack roughly like:
*
* execlist->execpline->execcmd->execwhile->execlist->execpline
*
* (when waiting for the grep, ignoring execpline2 for now). At this time,
* zsh has built two job-table entries for it: one for the cat and one for
* the grep. If the user hits ^Z at this point (and jobbing is used), the
* shell is notified that the grep was suspended. The list_pipe flag is
* used to tell the execpline where it was waiting that it was in a pipeline
* with a shell construct at the end (which may also be a shell function or
* several other things). When zsh sees the suspended grep, it forks to let
* the sub-shell execute the rest of the while loop. The parent shell walks
* up in the function call stack to the first execpline. There it has to find
* out that it has just forked and then has to add information about the sub-
* shell (its pid and the text for it) in the job entry of the cat. The pid
* is passed down in the list_pipe_pid variable.
* But there is a problem: the suspended grep is a child of the parent shell
* and can't be adopted by the sub-shell. So the parent shell also has to
* keep the information about this process (more precisely: this pipeline)
* by keeping the job table entry it created for it. The fact that there
* are two jobs which have to be treated together is remembered by setting
* the STAT_SUPERJOB flag in the entry for the cat-job (which now also
* contains a process-entry for the whole loop -- the sub-shell) and by
* setting STAT_SUBJOB in the job of the grep-job. With that we can keep
* sub-jobs from being displayed and we can handle an fg/bg on the super-
* job correctly. When the super-job is continued, the shell also wakes up
* the sub-job. But then, the grep will exit sometime. Now the parent shell
* has to remember not to try to wake it up again (in case of another ^Z).
* It also has to wake up the sub-shell (which suspended itself immediately
* after creation), so that the rest of the loop is executed by it.
* But there is more: when the sub-shell is created, the cat may already
* have exited, so we can't put the sub-shell in the process group of it.
* In this case, we put the sub-shell in the process group of the parent
* shell and in any case, the sub-shell has to put all commands executed
* by it into its own process group, because only this way the parent
* shell can control them since it only knows the process group of the sub-
* shell. Of course, this information is also important when putting a job
* in the foreground, where we have to attach its process group to the
* controlling tty.
* All this is made more difficult because we have to handle return values
* correctly. If the grep is signaled, its exit status has to be propagated
* back to the parent shell which needs it to set the exit status of the
* super-job. And of course, when the grep is signaled (including ^C), the
* loop has to be stopped, etc.
* The code for all this is distributed over three files (exec.c, jobs.c,
* and signals.c) and none of them is a simple one. So, all in all, there
* may still be bugs, but considering the complexity (with race conditions,
* signal handling, and all that), this should probably be expected.
*/
/**/
int list_pipe = 0, simple_pline = 0;
static pid_t list_pipe_pid;
static struct timeval list_pipe_start;
static int nowait, pline_level = 0;
static int list_pipe_child = 0, list_pipe_job;
static char list_pipe_text[JOBTEXTSIZE];
/* execute a current shell command */
/**/
static int
execcursh(Estate state, int do_exec)
{
Wordcode end = state->pc + WC_CURSH_SKIP(state->pc[-1]);
/* Skip word only used for try/always */
state->pc++;
/*
* The test thisjob != -1 was added because sometimes thisjob
* can be invalid at this point. The case in question was
* in a precmd function after operations involving background
* jobs.
*
* This is because sometimes we bypass job control to execute
* very simple functions via execssimple().
*/
if (!list_pipe && thisjob != -1 && thisjob != list_pipe_job &&
!hasprocs(thisjob))
deletejob(jobtab + thisjob, 0);
cmdpush(CS_CURSH);
execlist(state, 1, do_exec);
cmdpop();
state->pc = end;
this_noerrexit = 1;
return lastval;
}
/* execve after handling $_ and #! */
#define POUNDBANGLIMIT 128
/**/
static int
zexecve(char *pth, char **argv, char **newenvp)
{
int eno;
static char buf[PATH_MAX * 2+1];
char **eep;
unmetafy(pth, NULL);
for (eep = argv; *eep; eep++)
if (*eep != pth)
unmetafy(*eep, NULL);
buf[0] = '_';
buf[1] = '=';
if (*pth == '/')
strcpy(buf + 2, pth);
else
sprintf(buf + 2, "%s/%s", pwd, pth);
zputenv(buf);
#ifndef FD_CLOEXEC
closedumps();
#endif
if (newenvp == NULL)
newenvp = environ;
winch_unblock();
execve(pth, argv, newenvp);
/* If the execve returns (which in general shouldn't happen), *
* then check for an errno equal to ENOEXEC. This errno is set *
* if the process file has the appropriate access permission, *
* but has an invalid magic number in its header. */
if ((eno = errno) == ENOEXEC || eno == ENOENT) {
char execvebuf[POUNDBANGLIMIT + 1], *ptr, *ptr2, *argv0;
int fd, ct, t0;
if ((fd = open(pth, O_RDONLY|O_NOCTTY)) >= 0) {
argv0 = *argv;
*argv = pth;
memset(execvebuf, '\0', POUNDBANGLIMIT + 1);
ct = read(fd, execvebuf, POUNDBANGLIMIT);
close(fd);
if (ct >= 0) {
if (ct >= 2 && execvebuf[0] == '#' && execvebuf[1] == '!') {
for (t0 = 0; t0 != ct; t0++)
if (execvebuf[t0] == '\n')
break;
if (t0 == ct)
zerr("%s: bad interpreter: %s: %e", pth,
execvebuf + 2, eno);
else {
while (inblank(execvebuf[t0]))
execvebuf[t0--] = '\0';
for (ptr = execvebuf + 2; *ptr && *ptr == ' '; ptr++);
for (ptr2 = ptr; *ptr && *ptr != ' '; ptr++);
if (eno == ENOENT) {
char *pprog;
if (*ptr)
*ptr = '\0';
if (*ptr2 != '/' &&
(pprog = pathprog(ptr2, NULL))) {
if (ptr == execvebuf + t0 + 1) {
argv[-1] = ptr2;
winch_unblock();
execve(pprog, argv - 1, newenvp);
} else {
argv[-2] = ptr2;
argv[-1] = ptr + 1;
winch_unblock();
execve(pprog, argv - 2, newenvp);
}
}
zerr("%s: bad interpreter: %s: %e", pth, ptr2,
eno);
} else if (*ptr) {
*ptr = '\0';
argv[-2] = ptr2;
argv[-1] = ptr + 1;
winch_unblock();
execve(ptr2, argv - 2, newenvp);
} else {
argv[-1] = ptr2;
winch_unblock();
execve(ptr2, argv - 1, newenvp);
}
}
} else if (eno == ENOEXEC) {
for (t0 = 0; t0 != ct; t0++)
if (!execvebuf[t0])
break;
if (t0 == ct) {
argv[-1] = "sh";
winch_unblock();
execve("/bin/sh", argv - 1, newenvp);
}
}
} else
eno = errno;
*argv = argv0;
} else
eno = errno;
}
/* restore the original arguments and path but do not bother with *
* null characters as these cannot be passed to external commands *
* anyway. So the result is truncated at the first null char. */
pth = metafy(pth, -1, META_NOALLOC);
for (eep = argv; *eep; eep++)
if (*eep != pth)
(void) metafy(*eep, -1, META_NOALLOC);
return eno;
}
#define MAXCMDLEN (PATH_MAX*4)
/* test whether we really want to believe the error number */
/**/
static int
isgooderr(int e, char *dir)
{
/*
* Maybe the directory was unreadable, or maybe it wasn't
* even a directory.
*/
return ((e != EACCES || !access(dir, X_OK)) &&
e != ENOENT && e != ENOTDIR);
}
/*
* Attempt to handle command not found.
* Return 0 if the condition was handled, non-zero otherwise.
*/
/**/
static int
commandnotfound(char *arg0, LinkList args)
{
Shfunc shf = (Shfunc)
shfunctab->getnode(shfunctab, "command_not_found_handler");
if (!shf) {
lastval = 127;
return 1;
}
pushnode(args, arg0);
lastval = doshfunc(shf, args, 1);
return 0;
}
/*
* Search the default path for cmd.
* pbuf of length plen is the buffer to use.
* Return NULL if not found.
*/
static char *
search_defpath(char *cmd, char *pbuf, int plen)
{
char *ps = DEFAULT_PATH, *pe = NULL, *s;
for (ps = DEFAULT_PATH; ps; ps = pe ? pe+1 : NULL) {
pe = strchr(ps, ':');
if (*ps == '/') {
s = pbuf;
if (pe) {
if (pe - ps >= plen)
continue;
struncpy(&s, ps, pe-ps);
} else {
if (strlen(ps) >= plen)
continue;
strucpy(&s, ps);
}
*s++ = '/';
if ((s - pbuf) + strlen(cmd) >= plen)
continue;
strucpy(&s, cmd);
if (iscom(pbuf))
return pbuf;
}
}
return NULL;
}
/* execute an external command */
/**/
static void
execute(LinkList args, int flags, int defpath)
{
Cmdnam cn;
char buf[MAXCMDLEN+1], buf2[MAXCMDLEN+1];
char *s, *z, *arg0;
char **argv, **pp, **newenvp = NULL;
int eno = 0, ee;
arg0 = (char *) peekfirst(args);
if (isset(RESTRICTED) && (strchr(arg0, '/') || defpath)) {
zerr("%s: restricted", arg0);
_exit(1);
}
/* If the parameter STTY is set in the command's environment, *
* we first run the stty command with the value of this *
* parameter as it arguments. */
if ((s = STTYval) && isatty(0) && (GETPGRP() == getpid())) {
char *t = tricat("stty", " ", s);
STTYval = 0; /* this prevents infinite recursion */
zsfree(s);
execstring(t, 1, 0, "stty");
zsfree(t);
} else if (s) {
STTYval = 0;
zsfree(s);
}
/* If ARGV0 is in the commands environment, we use *
* that as argv[0] for this external command */
if (unset(RESTRICTED) && (z = zgetenv("ARGV0"))) {
setdata(firstnode(args), (void *) ztrdup(z));
/*
* Note we don't do anything with the parameter structure
* for ARGV0: that's OK since we're about to exec or exit
* on failure.
*/
#ifdef USE_SET_UNSET_ENV
unsetenv("ARGV0");
#else
delenvvalue(z - 6);
#endif
} else if (flags & BINF_DASH) {
/* Else if the pre-command `-' was given, we add `-' *
* to the front of argv[0] for this command. */
sprintf(buf2, "-%s", arg0);
setdata(firstnode(args), (void *) ztrdup(buf2));
}
argv = makecline(args);
if (flags & BINF_CLEARENV)
newenvp = blank_env;
/*
* Note that we don't close fd's attached to process substitution
* here, which should be visible to external processes.
*/
closem(FDT_XTRACE, 0);
#ifndef FD_CLOEXEC
if (SHTTY != -1) {
close(SHTTY);
SHTTY = -1;
}
#endif
child_unblock();
if ((int) strlen(arg0) >= PATH_MAX) {
zerr("command too long: %s", arg0);
_exit(1);
}
for (s = arg0; *s; s++)
if (*s == '/') {
int lerrno = zexecve(arg0, argv, newenvp);
if (arg0 == s || unset(PATHDIRS) ||
(arg0[0] == '.' && (arg0 + 1 == s ||
(arg0[1] == '.' && arg0 + 2 == s)))) {
zerr("%e: %s", lerrno, arg0);
_exit((lerrno == EACCES || lerrno == ENOEXEC) ? 126 : 127);
}
break;
}
/* for command -p, search the default path */
if (defpath) {
char pbuf[PATH_MAX+1];
char *dptr;
if (!search_defpath(arg0, pbuf, PATH_MAX)) {
if (commandnotfound(arg0, args) == 0)
_realexit();
zerr("command not found: %s", arg0);
_exit(127);
}
ee = zexecve(pbuf, argv, newenvp);
if ((dptr = strrchr(pbuf, '/')))
*dptr = '\0';
if (isgooderr(ee, *pbuf ? pbuf : "/"))
eno = ee;
} else {
if ((cn = (Cmdnam) cmdnamtab->getnode(cmdnamtab, arg0))) {
char nn[PATH_MAX+1], *dptr;
if (cn->node.flags & HASHED)
strcpy(nn, cn->u.cmd);
else {
for (pp = path; pp < cn->u.name; pp++)
if (!**pp || (**pp == '.' && (*pp)[1] == '\0')) {
ee = zexecve(arg0, argv, newenvp);
if (isgooderr(ee, *pp))
eno = ee;
} else if (**pp != '/') {
z = buf;
strucpy(&z, *pp);
*z++ = '/';
strcpy(z, arg0);
ee = zexecve(buf, argv, newenvp);
if (isgooderr(ee, *pp))
eno = ee;
}
strcpy(nn, cn->u.name ? *(cn->u.name) : "");
strcat(nn, "/");
strcat(nn, cn->node.nam);
}
ee = zexecve(nn, argv, newenvp);
if ((dptr = strrchr(nn, '/')))
*dptr = '\0';
if (isgooderr(ee, *nn ? nn : "/"))
eno = ee;
}
for (pp = path; *pp; pp++)
if (!(*pp)[0] || ((*pp)[0] == '.' && !(*pp)[1])) {
ee = zexecve(arg0, argv, newenvp);
if (isgooderr(ee, *pp))
eno = ee;
} else {
z = buf;
strucpy(&z, *pp);
*z++ = '/';
strcpy(z, arg0);
ee = zexecve(buf, argv, newenvp);
if (isgooderr(ee, *pp))
eno = ee;
}
}
if (eno)
zerr("%e: %s", eno, arg0);
else if (commandnotfound(arg0, args) == 0)
_realexit();
else
zerr("command not found: %s", arg0);
_exit((eno == EACCES || eno == ENOEXEC) ? 126 : 127);
}
#define RET_IF_COM(X) { if (iscom(X)) return docopy ? dupstring(X) : arg0; }
/*
* Get the full pathname of an external command.
* If the second argument is zero, return the first argument if found;
* if non-zero, return the path using heap memory. (RET_IF_COM(X),
* above).
* If the third argument is non-zero, use the system default path
* instead of the current path.
*/
/**/
mod_export char *
findcmd(char *arg0, int docopy, int default_path)
{
char **pp;
char *z, *s, buf[MAXCMDLEN];
Cmdnam cn;
if (default_path)
{
if (search_defpath(arg0, buf, MAXCMDLEN))
return docopy ? dupstring(buf) : arg0;
return NULL;
}
cn = (Cmdnam) cmdnamtab->getnode(cmdnamtab, arg0);
if (!cn && isset(HASHCMDS) && !isrelative(arg0))
cn = hashcmd(arg0, path);
if ((int) strlen(arg0) > PATH_MAX)
return NULL;
if ((s = strchr(arg0, '/'))) {
RET_IF_COM(arg0);
if (arg0 == s || unset(PATHDIRS) || !strncmp(arg0, "./", 2) ||
!strncmp(arg0, "../", 3)) {
return NULL;
}
}
if (cn) {
char nn[PATH_MAX+1];
if (cn->node.flags & HASHED)
strcpy(nn, cn->u.cmd);
else {
for (pp = path; pp < cn->u.name; pp++)
if (**pp != '/') {
z = buf;
if (**pp) {
strucpy(&z, *pp);
*z++ = '/';
}
strcpy(z, arg0);
RET_IF_COM(buf);
}
strcpy(nn, cn->u.name ? *(cn->u.name) : "");
strcat(nn, "/");
strcat(nn, cn->node.nam);
}
RET_IF_COM(nn);
}
for (pp = path; *pp; pp++) {
z = buf;
if (**pp) {
strucpy(&z, *pp);
*z++ = '/';
}
strcpy(z, arg0);
RET_IF_COM(buf);
}
return NULL;
}
/*
* Return TRUE if the given path denotes an executable regular file, or a
* symlink to one.
*/
/**/
int
iscom(char *s)
{
struct stat statbuf;
char *us = unmeta(s);
return (access(us, X_OK) == 0 && stat(us, &statbuf) >= 0 &&
S_ISREG(statbuf.st_mode));
}
/**/
int
isreallycom(Cmdnam cn)
{
char fullnam[MAXCMDLEN];
if (cn->node.flags & HASHED)
strcpy(fullnam, cn->u.cmd);
else if (!cn->u.name)
return 0;
else {
strcpy(fullnam, *(cn->u.name));
strcat(fullnam, "/");
strcat(fullnam, cn->node.nam);
}
return iscom(fullnam);
}
/*
* Return TRUE if the given path contains a dot or dot-dot component
* and does not start with a slash.
*/
/**/
int
isrelative(char *s)
{
if (*s != '/')
return 1;
for (; *s; s++)
if (*s == '.' && s[-1] == '/' &&
(s[1] == '/' || s[1] == '\0' ||
(s[1] == '.' && (s[2] == '/' || s[2] == '\0'))))
return 1;
return 0;
}
/**/
mod_export Cmdnam
hashcmd(char *arg0, char **pp)
{
Cmdnam cn;
char *s, buf[PATH_MAX+1];
char **pq;
if (*arg0 == '/')
return NULL;
for (; *pp; pp++)
if (**pp == '/') {
s = buf;
struncpy(&s, *pp, PATH_MAX);
*s++ = '/';
if ((s - buf) + strlen(arg0) >= PATH_MAX)
continue;
strcpy(s, arg0);
if (iscom(buf))
break;
}
if (!*pp)
return NULL;
cn = (Cmdnam) zshcalloc(sizeof *cn);
cn->node.flags = 0;
cn->u.name = pp;
cmdnamtab->addnode(cmdnamtab, ztrdup(arg0), cn);
if (isset(HASHDIRS)) {
for (pq = pathchecked; pq <= pp; pq++)
hashdir(pq);
pathchecked = pp + 1;
}
return cn;
}
/* The value that 'locallevel' had when we forked. When we get back to this
* level, the current process (which is a subshell) will terminate.
*/
/**/
int
forklevel;
/* Arguments to entersubsh() */
enum {
/* Subshell is to be run asynchronously (else synchronously) */
ESUB_ASYNC = 0x01,
/*
* Perform process group and tty handling and clear the
* (real) job table, since it won't be any longer valid
*/
ESUB_PGRP = 0x02,
/* Don't unset traps */
ESUB_KEEPTRAP = 0x04,
/* This is only a fake entry to a subshell */
ESUB_FAKE = 0x08,
/* Release the process group if pid is the shell's process group */
ESUB_REVERTPGRP = 0x10,
/* Don't handle the MONITOR option even if previously set */
ESUB_NOMONITOR = 0x20,
/* This is a subshell where job control is allowed */
ESUB_JOB_CONTROL = 0x40