-
Notifications
You must be signed in to change notification settings - Fork 30
/
exec.c
2658 lines (2354 loc) · 79.3 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
/* Yash: yet another shell */
/* exec.c: command execution */
/* (C) 2007-2024 magicant */
/* 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 2 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 <http://www.gnu.org/licenses/>. */
#include "common.h"
#include "exec.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#if HAVE_GETTEXT
# include <libintl.h>
#endif
#include <limits.h>
#include <math.h>
#if HAVE_PATHS_H
# include <paths.h>
#endif
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/times.h>
#include <unistd.h>
#include <wchar.h>
#include "alias.h"
#include "builtin.h"
#include "expand.h"
#if YASH_ENABLE_HISTORY
# include "history.h"
#endif
#include "input.h"
#include "job.h"
#include "option.h"
#include "parser.h"
#include "path.h"
#include "plist.h"
#include "redir.h"
#include "sig.h"
#include "strbuf.h"
#include "util.h"
#include "variable.h"
#include "xfnmatch.h"
#include "yash.h"
#if YASH_ENABLE_DOUBLE_BRACKET
# include "builtins/test.h"
#endif
#if YASH_ENABLE_LINEEDIT
# include "lineedit/complete.h"
# include "lineedit/lineedit.h"
#endif
/* type of command execution */
typedef enum {
E_NORMAL, /* normal execution */
E_ASYNC, /* asynchronous execution */
E_SELF, /* execution in the shell's own process */
} exec_T;
/* info about file descriptors of pipes */
typedef struct pipeinfo_T {
int pi_fromprevfd; /* reading end of the pipe from the previous process */
int pi_tonextfds[2]; /* both ends of the pipe to the next process */
/* -1 is assigned to unused members. */
} pipeinfo_T;
#define PIPEINFO_INIT { -1, { -1, -1 }, }
/* values used to specify the behavior of command search. */
typedef enum srchcmdtype_T {
SCT_EXTERNAL = 1 << 0, /* search for an external command */
SCT_BUILTIN = 1 << 1, /* search for a built-in */
SCT_FUNCTION = 1 << 2, /* search for a function */
SCT_ALL = 1 << 3, /* search all */
SCT_STDPATH = 1 << 4, /* search the standard PATH */
SCT_CHECK = 1 << 5, /* check command existence */
} srchcmdtype_T;
typedef enum cmdtype_T {
CT_NONE,
CT_EXTERNALPROGRAM,
CT_SPECIALBUILTIN,
CT_MANDATORYBUILTIN,
CT_ELECTIVEBUILTIN,
CT_EXTENSIONBUILTIN,
CT_SUBSTITUTIVEBUILTIN,
CT_FUNCTION,
} cmdtype_T;
/* info about a simple command to execute */
typedef struct commandinfo_T {
cmdtype_T type; /* type of command */
union {
const char *path; /* command path (for external program) */
main_T *builtin; /* body of built-in */
command_T *function; /* body of function */
} value;
} commandinfo_T;
#define ci_path value.path
#define ci_builtin value.builtin
#define ci_function value.function
/* result of `fork_and_wait' */
typedef struct fork_and_wait_T {
pid_t cpid; /* child process ID */
wchar_t **namep; /* where to place the job name */
} fork_and_wait_T;
typedef enum exception_T {
E_NONE,
E_CONTINUE,
E_RETURN,
E_BREAK_ITERATION,
E_CONTINUE_ITERATION,
} exception_T;
/* state of currently executed loop */
typedef struct execstate_T {
unsigned loopnest; /* level of nested loops */
unsigned breakloopnest; /* target level of "break" */
bool noreturn; /* true when the "return" built-in is not allowed */
bool iterating; /* true when iterative execution is ongoing */
} execstate_T;
static void exec_pipelines(const pipeline_T *p, bool finally_exit);
static void exec_pipelines_async(const pipeline_T *p)
__attribute__((nonnull));
static void exec_commands(command_T *cs, exec_T type)
__attribute__((nonnull));
static inline size_t number_of_commands_in_pipeline(const command_T *c)
__attribute__((nonnull,pure,warn_unused_result));
static void apply_errexit_errreturn(const command_T *c);
static bool is_errexit_condition(void)
__attribute__((pure));
static bool is_errreturn_condition(void)
__attribute__((pure));
static bool is_err_condition_for(const command_T *c)
__attribute__((pure));
static inline void next_pipe(pipeinfo_T *pi, bool next)
__attribute__((nonnull));
static inline void connect_pipes(pipeinfo_T *pi)
__attribute__((nonnull));
static void exec_one_command(command_T *c, bool finally_exit)
__attribute__((nonnull));
static void exec_simple_command(const command_T *c, bool finally_exit)
__attribute__((nonnull));
static bool exec_simple_command_without_words(const command_T *c)
__attribute__((nonnull,warn_unused_result));
static bool exec_simple_command_with_words(
const command_T *c, int argc, void **argv, bool finally_exit)
__attribute__((nonnull,warn_unused_result));
static void print_xtrace(void *const *argv);
static void search_command(
const char *restrict name, const wchar_t *restrict wname,
commandinfo_T *restrict ci, enum srchcmdtype_T type)
__attribute__((nonnull));
static inline bool is_special_builtin(const char *cmdname)
__attribute__((nonnull,pure));
static bool command_not_found_handler(void *const *argv)
__attribute__((nonnull));
static wchar_t **invoke_simple_command(const commandinfo_T *ci,
int argc, char *argv0, void **argv, bool finally_exit)
__attribute__((nonnull,warn_unused_result));
static void exec_external_program(
const char *path, int argc, char *argv0, void **argv, char **envs)
__attribute__((nonnull));
static inline int xexecve(
const char *path, char *const *argv, char *const *envp)
__attribute__((nonnull(1)));
static void exec_fall_back_on_sh(
int argc, char *const *argv, char *const *env, const char *path)
__attribute__((nonnull(2,3,4)));
static void exec_function_body(
command_T *body, void *const *args, bool finally_exit, bool complete)
__attribute__((nonnull));
static void exec_nonsimple_command(command_T *c, bool finally_exit)
__attribute__((nonnull));
static void exec_if(const command_T *c, bool finally_exit)
__attribute__((nonnull));
static inline bool exec_condition(const and_or_T *c);
static void exec_for(const command_T *c, bool finally_exit)
__attribute__((nonnull));
static void exec_while(const command_T *c, bool finally_exit)
__attribute__((nonnull));
static void exec_case(const command_T *c, bool finally_exit)
__attribute__((nonnull));
static void exec_funcdef(const command_T *c, bool finally_exit)
__attribute__((nonnull));
static fork_and_wait_T fork_and_wait(sigtype_T sigtype)
__attribute__((warn_unused_result));
static void become_child(sigtype_T sigtype);
static int exec_iteration(void *const *commands, const char *codename)
__attribute__((nonnull));
/* exit status of the last command */
int laststatus = Exit_SUCCESS;
/* exit status of the command preceding the currently executed trap action */
int savelaststatus = -1; // -1 if not in a trap handler
/* exit status of the last command substitution */
static int lastcmdsubstatus;
/* exit status of the command that immediately preceded the EXIT trap. */
int exitstatus = -1; // -1 if not executing the EXIT trap
/* the process ID of the last asynchronous list */
pid_t lastasyncpid;
/* This flag is set to true while the shell is executing the condition of an if-
* statement, an and-or list, etc. to suppress the effect of the "errexit" and
* "errreturn" options. */
static bool suppresserrexit = false, suppresserrreturn = false;
/* state of currently executed loop */
static execstate_T execstate;
/* exceptional jump to be done (other than "break") */
static exception_T exception;
/* This flag is set when a special built-in is executed as such. */
bool special_builtin_executed;
/* This flag is set while the "exec" built-in is executed. */
static bool exec_builtin_executed = false;
/* True while executing auxiliary commands such as $PROMPT_COMMAND and
* $COMMAND_NOT_FOUND_HANDLER. */
bool is_executing_auxiliary = false;
/* the last assignment. */
static const assign_T *last_assign;
/* a buffer for xtrace.
* When assignments are performed while executing a simple command, the trace
* is appended to this buffer. Each trace of an assignment must be prefixed
* with a space to separate it with the previous one. The first space will be
* trimmed when the buffer is flushed to the standard error. */
static xwcsbuf_T xtrace_buffer = { .contents = NULL };
/* Resets `execstate' to the initial state. */
void reset_execstate(bool reset_iteration)
{
execstate.loopnest = 0;
execstate.breakloopnest = 0;
execstate.noreturn = false;
if (reset_iteration)
execstate.iterating = false;
}
/* Saves the current `execstate' and returns it.
* You typically call `reset_execstate' after calling this function. */
execstate_T *save_execstate(void)
{
execstate_T *save = xmalloc(sizeof execstate);
*save = execstate;
return save;
}
/* Restores `execstate' to `save' and frees `save'. */
void restore_execstate(execstate_T *save)
{
execstate = *save;
free(save);
}
/* Disables the "return" built-in in the current `execstate'. */
void disable_return(void)
{
execstate.noreturn = true;
}
/* If we're returning, clear the flag. */
void cancel_return(void)
{
if (exception == E_RETURN)
exception = E_NONE;
}
/* Returns true iff we're breaking/continuing/returning now. */
bool need_break(void)
{
return execstate.breakloopnest < execstate.loopnest
|| exception != E_NONE
|| is_interrupted();
}
/* Executes the and-or lists.
* If `finally_exit' is true, the shell exits after execution. */
void exec_and_or_lists(const and_or_T *a, bool finally_exit)
{
while (a != NULL && !need_break()) {
if (!a->ao_async)
exec_pipelines(a->ao_pipelines, finally_exit && !a->next);
else
exec_pipelines_async(a->ao_pipelines);
a = a->next;
}
if (finally_exit)
exit_shell();
}
/* Executes the pipelines. */
void exec_pipelines(const pipeline_T *p, bool finally_exit)
{
for (bool first = true; p != NULL; p = p->next, first = false) {
if (!first && p->pl_cond == (laststatus != Exit_SUCCESS))
continue;
bool savesee = suppresserrexit, saveser = suppresserrreturn;
bool suppress = p->pl_neg || p->next != NULL;
suppresserrexit |= suppress;
suppresserrreturn |= suppress;
bool self = finally_exit && !p->next && !p->pl_neg;
exec_commands(p->pl_commands, self ? E_SELF : E_NORMAL);
suppresserrexit = savesee, suppresserrreturn = saveser;
if (need_break())
break;
if (p->pl_neg) {
if (laststatus == Exit_SUCCESS)
laststatus = Exit_FAILURE;
else
laststatus = Exit_SUCCESS;
}
}
if (finally_exit)
exit_shell();
}
/* Executes the pipelines asynchronously. */
void exec_pipelines_async(const pipeline_T *p)
{
if (p->next == NULL && !p->pl_neg) {
exec_commands(p->pl_commands, E_ASYNC);
return;
}
pid_t cpid = fork_and_reset(0, false, t_quitint);
if (cpid > 0) {
/* parent process: add a new job */
job_T *job = xmalloc(add(sizeof *job, sizeof *job->j_procs));
process_T *ps = job->j_procs;
ps->pr_pid = cpid;
ps->pr_status = JS_RUNNING;
ps->pr_statuscode = 0;
ps->pr_name = pipelines_to_wcs(p);
job->j_pgid = doing_job_control_now ? cpid : 0;
job->j_status = JS_RUNNING;
job->j_statuschanged = true;
job->j_legacy = false;
job->j_nonotify = false;
job->j_pcount = 1;
set_active_job(job);
add_job(shopt_curasync);
laststatus = Exit_SUCCESS;
lastasyncpid = cpid;
} else if (cpid == 0) {
/* child process: execute the commands and then exit */
maybe_redirect_stdin_to_devnull();
exec_pipelines(p, true);
assert(false);
} else {
/* fork failure */
laststatus = Exit_NOEXEC;
}
}
/* Executes the commands in a pipeline. */
void exec_commands(command_T *const cs, exec_T type)
{
size_t count = number_of_commands_in_pipeline(cs);
assert(count > 0);
bool short_circuit =
type == E_SELF && !doing_job_control_now && !any_trap_set &&
(count == 1 || !shopt_pipefail);
if (count == 1 && type != E_ASYNC) {
exec_one_command(cs, /* finally_exit = */ short_circuit);
goto done;
}
/* fork a child process for each command in the pipeline */
pid_t pgid = 0;
pipeinfo_T pipe = PIPEINFO_INIT;
job_T *job = xmallocs(sizeof *job, count, sizeof *job->j_procs);
command_T *c;
process_T *p;
int forkstatus = Exit_SUCCESS;
for (c = cs, p = job->j_procs; c != NULL; c = c->next, p++) {
bool is_last = c->next == NULL;
next_pipe(&pipe, !is_last);
if (is_last && short_circuit)
goto exec_one_command; /* skip forking */
sigtype_T sigtype = (type == E_ASYNC) ? t_quitint : 0;
pid_t pid = fork_and_reset(pgid, type == E_NORMAL, sigtype);
if (pid == 0) {
exec_one_command: /* child process */
free(job);
connect_pipes(&pipe);
if (type == E_ASYNC && pipe.pi_fromprevfd < 0)
maybe_redirect_stdin_to_devnull();
exec_one_command(c, true);
assert(false);
} else if (pid >= 0) {
/* parent process: fork succeeded */
if (pgid == 0)
pgid = pid;
p->pr_pid = pid;
p->pr_status = JS_RUNNING;
// p->pr_statuscode = ?; // The process is still running.
p->pr_name = NULL; // The actual name is given later.
} else {
/* parent process: fork failed */
p->pr_pid = 0;
p->pr_status = JS_DONE;
p->pr_statuscode = forkstatus = Exit_NOEXEC;
p->pr_name = NULL;
}
}
assert(pipe.pi_tonextfds[PIPE_IN] < 0);
assert(pipe.pi_tonextfds[PIPE_OUT] < 0);
if (pipe.pi_fromprevfd >= 0)
xclose(pipe.pi_fromprevfd); /* close the leftover pipe */
/* establish the job and wait for it */
job->j_pgid = doing_job_control_now ? pgid : 0;
job->j_status = JS_RUNNING;
job->j_statuschanged = true;
job->j_legacy = false;
job->j_nonotify = false;
job->j_pcount = count;
set_active_job(job);
if (type != E_ASYNC) {
wait_for_job(ACTIVE_JOBNO, doing_job_control_now, false, false);
if (doing_job_control_now)
put_foreground(shell_pgid);
laststatus = calc_status_of_job(job);
} else {
laststatus = forkstatus;
lastasyncpid = job->j_procs[count - 1].pr_pid;
}
if (job->j_status == JS_DONE) {
notify_signaled_job(ACTIVE_JOBNO);
remove_job(ACTIVE_JOBNO);
} else {
/* name the job processes */
for (c = cs, p = job->j_procs; c != NULL; c = c->next, p++)
p->pr_name = command_to_wcs(c, false);
/* remember the suspended job */
add_job(type == E_NORMAL || shopt_curasync);
}
done:
handle_signals();
apply_errexit_errreturn(cs);
if (type == E_SELF)
exit_shell();
}
size_t number_of_commands_in_pipeline(const command_T *c)
{
size_t count = 1;
while ((c = c->next) != NULL)
count++;
return count;
}
/* Tests the current condition for "errexit" and "errreturn" and then performs
* exit or return if applicable. */
void apply_errexit_errreturn(const command_T *c)
{
if (is_errexit_condition() && is_err_condition_for(c))
exit_shell_with_status(laststatus);
if (is_errreturn_condition() && is_err_condition_for(c))
exception = E_RETURN;
}
/* Returns true if the shell should exit because of the `errexit' option. */
bool is_errexit_condition(void)
{
if (!shopt_errexit || suppresserrexit)
return false;
if (laststatus == Exit_SUCCESS)
return false;
#if YASH_ENABLE_LINEEDIT
if (le_state & LE_STATE_COMPLETING)
return false;
#endif
return true;
}
/* Returns true if the shell should return because of the `errreturn' option. */
bool is_errreturn_condition(void)
{
if (!shopt_errreturn || suppresserrreturn || execstate.noreturn)
return false;
return laststatus != Exit_SUCCESS;
}
/* Returns true if "errexit" and "errreturn" should be applied to the given
* command. */
bool is_err_condition_for(const command_T *c)
{
if (c == NULL)
return true;
/* If this is a multi-command pipeline, the commands are executed in
* subshells. Otherwise, we need to check the type of the command. */
if (c->next != NULL)
return true;
switch (c->c_type) {
case CT_SIMPLE:
case CT_SUBSHELL:
#if YASH_ENABLE_DOUBLE_BRACKET
case CT_BRACKET:
#endif
case CT_FUNCDEF:
return true;
case CT_GROUP:
case CT_IF:
case CT_FOR:
case CT_WHILE:
case CT_CASE:
return false;
}
assert(false);
}
/* Updates the contents of the `pipeinfo_T' to proceed to the next process
* execution. `pi->pi_fromprevfd' and `pi->pi_tonextfds[PIPE_OUT]' are closed,
* `pi->pi_tonextfds[PIPE_IN]' is moved to `pi->pi_fromprevfd', and,
* if `next' is true, a new pipe is opened in `pi->pi_tonextfds'; otherwise,
* `pi->pi_tonextfds' is assigned -1.
* Returns true iff successful. */
void next_pipe(pipeinfo_T *pi, bool next)
{
if (pi->pi_fromprevfd >= 0)
xclose(pi->pi_fromprevfd);
if (pi->pi_tonextfds[PIPE_OUT] >= 0)
xclose(pi->pi_tonextfds[PIPE_OUT]);
pi->pi_fromprevfd = pi->pi_tonextfds[PIPE_IN];
if (next) {
if (pipe(pi->pi_tonextfds) < 0)
goto fail;
/* The pipe's FDs must not be 0 or 1, or they may be overridden by each
* other when we move the pipe to the standard input/output later. So,
* if they are 0 or 1, we move them to bigger numbers. */
int origin = pi->pi_tonextfds[PIPE_IN];
int origout = pi->pi_tonextfds[PIPE_OUT];
if (origin < 2 || origout < 2) {
if (origin < 2)
pi->pi_tonextfds[PIPE_IN] = dup(origin);
if (origout < 2)
pi->pi_tonextfds[PIPE_OUT] = dup(origout);
if (origin < 2)
xclose(origin);
if (origout < 2)
xclose(origout);
if (pi->pi_tonextfds[PIPE_IN] < 0) {
xclose(pi->pi_tonextfds[PIPE_OUT]);
goto fail;
}
if (pi->pi_tonextfds[PIPE_OUT] < 0) {
xclose(pi->pi_tonextfds[PIPE_IN]);
goto fail;
}
}
} else {
pi->pi_tonextfds[PIPE_IN] = pi->pi_tonextfds[PIPE_OUT] = -1;
}
return;
fail:
pi->pi_tonextfds[PIPE_IN] = pi->pi_tonextfds[PIPE_OUT] = -1;
xerror(errno, Ngt("cannot open a pipe"));
}
/* Connects the pipe(s) and closes the pipes left. */
void connect_pipes(pipeinfo_T *pi)
{
if (pi->pi_fromprevfd >= 0) {
xdup2(pi->pi_fromprevfd, STDIN_FILENO);
xclose(pi->pi_fromprevfd);
}
if (pi->pi_tonextfds[PIPE_OUT] >= 0) {
xdup2(pi->pi_tonextfds[PIPE_OUT], STDOUT_FILENO);
xclose(pi->pi_tonextfds[PIPE_OUT]);
}
if (pi->pi_tonextfds[PIPE_IN] >= 0)
xclose(pi->pi_tonextfds[PIPE_IN]);
}
/* Executes the command. */
void exec_one_command(command_T *c, bool finally_exit)
{
/* prevent the command data from being freed in case the command is part of
* a function that is unset during execution. */
c = comsdup(c);
update_lineno(c->c_lineno);
if (c->c_type == CT_SIMPLE) {
exec_simple_command(c, finally_exit);
} else {
savefd_T *savefd;
if (open_redirections(c->c_redirs, &savefd)) {
exec_nonsimple_command(c, finally_exit && savefd == NULL);
undo_redirections(savefd);
} else {
undo_redirections(savefd);
laststatus = Exit_REDIRERR;
apply_errexit_errreturn(NULL);
}
}
comsfree(c);
if (finally_exit)
exit_shell();
}
/* Executes the simple command. */
void exec_simple_command(const command_T *c, bool finally_exit)
{
lastcmdsubstatus = Exit_SUCCESS;
/* expand the command words */
int argc;
void **argv;
if (!expand_line(c->c_words, &argc, &argv)) {
laststatus = Exit_EXPERROR;
goto done;
}
if (is_interrupted())
goto done1;
/* execute the remaining part */
if (argc == 0)
finally_exit |= exec_simple_command_without_words(c);
else
finally_exit |=
exec_simple_command_with_words(c, argc, argv, finally_exit);
/* cleanup */
done1:
plfree(argv, free);
done:
if (finally_exit)
/* If we're running the EXIT trap and the simple command failed with a
* shell error, we should exit with the current exit status indicating
* the error rather than the exit status saved just before entering the
* EXIT trap, so... */
exit_shell_with_status(laststatus); // rather than: exit_shell();
}
/* Executes the simple command that has no expanded words.
* Returns true if the shell should exit. */
bool exec_simple_command_without_words(const command_T *c)
{
/* perform assignments */
bool ok = do_assignments(c->c_assigns, false, false);
print_xtrace(NULL);
last_assign = c->c_assigns;
if (!ok) {
laststatus = Exit_ASSGNERR;
return !is_interactive_now;
}
/* done? */
if (c->c_redirs == NULL) {
laststatus = lastcmdsubstatus;
return false;
}
/* create a subshell to perform redirections in */
fork_and_wait_T faw = fork_and_wait(0);
if (faw.cpid != 0) {
/* parent process */
if (faw.namep != NULL)
*faw.namep = command_to_wcs(c, false);
return false;
}
/* open redirections in subshell */
savefd_T *savefd;
ok = open_redirections(c->c_redirs, &savefd);
undo_redirections(savefd);
exit_shell_with_status(ok ? lastcmdsubstatus : Exit_REDIRERR);
}
/* Executes the simple command that has one or more expanded words.
* `argv' must be a NULL-terminated array of pointers to wide strings that are
* the results of the word expansion on the simple command being executed.
* `argc' must be the number of words in `argv', which must be at least 1.
* If `finally_exit' is true, the shell process may be replaced by the command
* process. However, this function still may return in some cases.
* Returns true if the shell should exit. */
bool exec_simple_command_with_words(
const command_T *c, int argc, void **argv, bool finally_exit)
{
assert(argc > 0);
char *argv0 = malloc_wcstombs(argv[0]);
if (argv0 == NULL)
argv0 = xstrdup("");
/* open redirections */
savefd_T *savefd;
if (!open_redirections(c->c_redirs, &savefd)) {
/* On redirection error, the command is not executed. */
laststatus = Exit_REDIRERR;
if (posixly_correct && !is_interactive_now && is_special_builtin(argv0))
finally_exit = true;
goto done;
}
last_assign = c->c_assigns;
/* check if the command is a special built-in or function */
commandinfo_T cmdinfo;
search_command(argv0, argv[0], &cmdinfo, SCT_BUILTIN | SCT_FUNCTION);
special_builtin_executed = (cmdinfo.type == CT_SPECIALBUILTIN);
/* open a temporary variable environment */
bool temp = c->c_assigns != NULL && !special_builtin_executed;
if (temp)
open_new_environment(true);
/* perform the assignments */
if (!do_assignments(c->c_assigns, temp, true)) {
/* On assignment error, the command is not executed. */
print_xtrace(NULL);
laststatus = Exit_ASSGNERR;
if (!is_interactive_now)
finally_exit = true;
goto done1;
}
print_xtrace(argv);
/* find command path */
if (cmdinfo.type == CT_NONE) {
search_command(argv0, argv[0], &cmdinfo,
SCT_EXTERNAL | SCT_BUILTIN | SCT_CHECK);
if (cmdinfo.type == CT_NONE) {
if (!posixly_correct && command_not_found_handler(argv))
goto done1;
if (wcschr(argv[0], L'/') != NULL) {
cmdinfo.type = CT_EXTERNALPROGRAM;
cmdinfo.ci_path = argv0;
}
}
}
/* execute! */
wchar_t **namep = invoke_simple_command(&cmdinfo, argc, argv0, argv,
finally_exit && /* !temp && */ savefd == NULL);
if (namep != NULL)
*namep = command_to_wcs(c, false);
/* Redirections are not undone after a successful "exec" command:
* remove the saved data of file descriptors. */
if (exec_builtin_executed && laststatus == Exit_SUCCESS) {
clear_savefd(savefd);
savefd = NULL;
}
exec_builtin_executed = false;
/* cleanup */
done1:
if (temp)
close_current_environment();
done:
undo_redirections(savefd);
free(argv0);
return finally_exit;
}
/* Returns a pointer to the xtrace buffer.
* The buffer is initialized if not. */
xwcsbuf_T *get_xtrace_buffer(void)
{
if (xtrace_buffer.contents == NULL)
wb_init(&xtrace_buffer);
return &xtrace_buffer;
}
/* Prints a trace if the "xtrace" option is on. */
void print_xtrace(void *const *argv)
{
static bool expanding_ps4 = false;
bool tracevars = xtrace_buffer.contents != NULL
&& xtrace_buffer.length > 0;
if (shopt_xtrace && !expanding_ps4
&& (!is_executing_auxiliary || shopt_traceall)
&& (tracevars || argv != NULL)
#if YASH_ENABLE_LINEEDIT
&& !(le_state & LE_STATE_ACTIVE)
#endif
) {
bool first = true;
// Disallow recursion in case $PS4 contains a command substitution
// that may trigger another xtrace, which would be an infinite loop
expanding_ps4 = true;
struct promptset_T prompt = get_prompt(4);
expanding_ps4 = false;
print_prompt(prompt.main);
print_prompt(prompt.styler);
if (tracevars) {
fprintf(stderr, "%ls", xtrace_buffer.contents + 1);
first = false;
}
if (argv != NULL) {
for (void *const *a = argv; *a != NULL; a++) {
if (!first)
fputc(' ', stderr);
first = false;
wchar_t *quoted = quote_as_word(*a);
fprintf(stderr, "%ls", quoted);
free(quoted);
}
}
fputc('\n', stderr);
print_prompt(PROMPT_RESET);
free_prompt(prompt);
}
if (xtrace_buffer.contents != NULL) {
wb_destroy(&xtrace_buffer);
xtrace_buffer.contents = NULL;
}
}
/* Searches for a command.
* The result is assigned to `*ci'.
* `name' and `wname' must contain the same string value.
* If the SCT_ALL flag is not set:
* * a function whose name contains a slash cannot be found
* * a substitutive built-in cannot be found if the SCT_EXTERNAL flag is not
* set either.
* If the SCT_EXTERNAL flag is set, the SCT_CHECK flag is not set, and `name'
* contains a slash, the external command of the given `name' is always found.
*/
void search_command(
const char *restrict name, const wchar_t *restrict wname,
commandinfo_T *restrict ci, enum srchcmdtype_T type)
{
bool slash = wcschr(wname, L'/') != NULL;
const builtin_T *bi;
if (!slash && (type & SCT_BUILTIN))
bi = get_builtin(name);
else
bi = NULL;
if (bi != NULL && bi->type == BI_SPECIAL) {
ci->type = CT_SPECIALBUILTIN;
ci->ci_builtin = bi->body;
return;
}
if ((type & SCT_FUNCTION) && (!slash || (type & SCT_ALL))) {
command_T *funcbody = get_function(wname);
if (funcbody != NULL) {
ci->type = CT_FUNCTION;
ci->ci_function = funcbody;
return;
}
}
if (bi != NULL) {
switch (bi->type) {
case BI_MANDATORY:
ci->type = CT_MANDATORYBUILTIN;
ci->ci_builtin = bi->body;
return;
case BI_ELECTIVE:
ci->type = CT_ELECTIVEBUILTIN;
ci->ci_builtin = bi->body;
return;
case BI_EXTENSION:
if (posixly_correct) {
bi = NULL;
break;
} else {
ci->type = CT_EXTENSIONBUILTIN;
ci->ci_builtin = bi->body;
return;
}
case BI_SPECIAL:
assert(false);
case BI_SUBSTITUTIVE:
break;
}
}
if (slash) {
if (type & SCT_EXTERNAL) {
if (!(type & SCT_CHECK) || is_executable_regular(name)) {
ci->type = CT_EXTERNALPROGRAM;
ci->ci_path = name;
return;
}
}
} else {
if ((type & SCT_EXTERNAL) || (bi != NULL && (type & SCT_ALL))) {
const char *cmdpath;
if (type & SCT_STDPATH)
cmdpath = get_command_path_default(name);
else
cmdpath = get_command_path(name, false);
if (cmdpath != NULL) {
if (bi != NULL) {
assert(bi->type == BI_SUBSTITUTIVE);
ci->type = CT_SUBSTITUTIVEBUILTIN;
ci->ci_builtin = bi->body;
} else {
ci->type = CT_EXTERNALPROGRAM;
ci->ci_path = cmdpath;
}
return;
}
}
}
/* command not found... */
ci->type = CT_NONE;
ci->ci_path = NULL;
return;
}
/* Returns true iff the specified command is a special built-in. */
bool is_special_builtin(const char *cmdname)
{
const builtin_T *bi = get_builtin(cmdname);
return bi != NULL && bi->type == BI_SPECIAL;
}
/* Executes $COMMAND_NOT_FOUND_HANDLER if any.
* `argv' is set to the positional parameters of the environment in which the
* handler is executed.
* Returns true iff the hander was executed and $HANDLED was set non-empty. */
bool command_not_found_handler(void *const *argv)
{
static bool handling = false;
if (handling)
return false; /* don't allow reentrance */
handling = true;
bool handled;
int result;
open_new_environment(false);
set_positional_parameters(argv);
set_variable(L VAR_HANDLED, xwcsdup(L""), SCOPE_LOCAL, false);