forked from fish-shell/fish-shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.cpp
1612 lines (1358 loc) · 54.1 KB
/
exec.cpp
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
/** \file exec.c
Functions for executing a program.
Some of the code in this file is based on code from the Glibc
manual, though the changes performed have been massive.
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <wchar.h>
#include <string.h>
#include <limits.h>
#include <signal.h>
#include <sys/wait.h>
#include <assert.h>
#include <dirent.h>
#include <time.h>
#include <vector>
#include <algorithm>
#include <memory>
#ifdef HAVE_SIGINFO_H
#include <siginfo.h>
#endif
#include "fallback.h"
#include "util.h"
#include "iothread.h"
#include "postfork.h"
#include "common.h"
#include "wutil.h"
#include "proc.h"
#include "exec.h"
#include "parser.h"
#include "builtin.h"
#include "function.h"
#include "env.h"
#include "wildcard.h"
#include "sanity.h"
#include "expand.h"
#include "signal.h"
#include "parse_util.h"
/**
file descriptor redirection error message
*/
#define FD_ERROR _( L"An error occurred while redirecting file descriptor %d" )
/**
file descriptor redirection error message
*/
#define WRITE_ERROR _( L"An error occurred while writing output" )
/**
file redirection error message
*/
#define FILE_ERROR _( L"An error occurred while redirecting file '%s'" )
/**
Base open mode to pass to calls to open
*/
#define OPEN_MASK 0666
/**
List of all pipes used by internal pipes. These must be closed in
many situations in order to make sure that stray fds aren't lying
around.
Note this is used after fork, so we must not do anything that may allocate memory. Hopefully methods like open_fds.at() don't.
*/
static std::vector<bool> open_fds;
// Called in a forked child
static void exec_write_and_exit(int fd, const char *buff, size_t count, int status)
{
if (write_loop(fd, buff, count) == -1)
{
debug(0, WRITE_ERROR);
wperror(L"write");
exit_without_destructors(status);
}
exit_without_destructors(status);
}
void exec_close(int fd)
{
ASSERT_IS_MAIN_THREAD();
/* This may be called in a child of fork(), so don't allocate memory */
if (fd < 0)
{
debug(0, L"Called close on invalid file descriptor ");
return;
}
while (close(fd) == -1)
{
if (errno != EINTR)
{
debug(1, FD_ERROR, fd);
wperror(L"close");
break;
}
}
/* Maybe remove this from our set of open fds */
if ((size_t)fd < open_fds.size())
{
open_fds[fd] = false;
}
}
int exec_pipe(int fd[2])
{
ASSERT_IS_MAIN_THREAD();
int res;
while ((res=pipe(fd)))
{
if (errno != EINTR)
{
// caller will call wperror
return res;
}
}
debug(4, L"Created pipe using fds %d and %d", fd[0], fd[1]);
int max_fd = std::max(fd[0], fd[1]);
if (max_fd >= 0 && open_fds.size() <= (size_t)max_fd)
{
open_fds.resize(max_fd + 1, false);
}
open_fds.at(fd[0]) = true;
open_fds.at(fd[1]) = true;
return res;
}
/* Returns true if the redirection is a file redirection to a file other than /dev/null */
static bool redirection_is_to_real_file(const io_data_t *io)
{
bool result = false;
if (io != NULL && io->io_mode == IO_FILE)
{
/* It's a file redirection. Compare the path to /dev/null */
CAST_INIT(const io_file_t *, io_file, io);
const char *path = io_file->filename_cstr;
if (strcmp(path, "/dev/null") != 0)
{
/* It's not /dev/null */
result = true;
}
}
return result;
}
static bool chain_contains_redirection_to_real_file(const io_chain_t &io_chain)
{
bool result = false;
for (size_t idx=0; idx < io_chain.size(); idx++)
{
const shared_ptr<const io_data_t> &io = io_chain.at(idx);
if (redirection_is_to_real_file(io.get()))
{
result = true;
break;
}
}
return result;
}
void print_open_fds(void)
{
for (size_t i=0; i < open_fds.size(); ++i)
{
if (open_fds.at(i))
{
fprintf(stderr, "fd %lu\n", i);
}
}
}
/**
Check if the specified fd is used as a part of a pipeline in the
specidied set of IO redirections.
This is called after fork().
\param fd the fd to search for
\param io_chain the set of io redirections to search in
*/
static bool use_fd_in_pipe(int fd, const io_chain_t &io_chain)
{
for (size_t idx = 0; idx < io_chain.size(); idx++)
{
const shared_ptr<const io_data_t> &io = io_chain.at(idx);
if ((io->io_mode == IO_BUFFER) ||
(io->io_mode == IO_PIPE))
{
CAST_INIT(const io_pipe_t *, io_pipe, io.get());
if (io_pipe->pipe_fd[0] == fd || io_pipe->pipe_fd[1] == fd)
return true;
}
}
return false;
}
/**
Close all fds in open_fds, except for those that are mentioned in
the redirection list io. This should make sure that there are no
stray opened file descriptors in the child.
\param io the list of io redirections for this job. Pipes mentioned
here should not be closed.
*/
void close_unused_internal_pipes(const io_chain_t &io)
{
/* A call to exec_close will modify open_fds, so be careful how we walk */
for (size_t i=0; i < open_fds.size(); i++)
{
if (open_fds[i])
{
int fd = (int)i;
if (!use_fd_in_pipe(fd, io))
{
debug(4, L"Close fd %d, used in other context", fd);
exec_close(fd);
i--;
}
}
}
}
void get_unused_internal_pipes(std::vector<int> &fds, const io_chain_t &io)
{
for (size_t i=0; i < open_fds.size(); i++)
{
if (open_fds[i])
{
int fd = (int)i;
if (!use_fd_in_pipe(fd, io))
{
fds.push_back(fd);
}
}
}
}
/**
Returns the interpreter for the specified script. Returns NULL if file
is not a script with a shebang.
*/
char *get_interpreter(const char *command, char *interpreter, size_t buff_size)
{
// OK to not use CLO_EXEC here because this is only called after fork
int fd = open(command, O_RDONLY);
if (fd >= 0)
{
size_t idx = 0;
while (idx + 1 < buff_size)
{
char ch;
ssize_t amt = read(fd, &ch, sizeof ch);
if (amt <= 0)
break;
if (ch == '\n')
break;
interpreter[idx++] = ch;
}
interpreter[idx++] = '\0';
close(fd);
}
if (strncmp(interpreter, "#! /", 4) == 0)
{
return interpreter + 3;
}
else if (strncmp(interpreter, "#!/", 3) == 0)
{
return interpreter + 2;
}
else
{
return NULL;
}
}
/**
This function is executed by the child process created by a call to
fork(). It should be called after \c setup_child_process. It calls
execve to replace the fish process image with the command specified
in \c p. It never returns.
*/
/* Called in a forked child! Do not allocate memory, etc. */
static void safe_launch_process(process_t *p, const char *actual_cmd, const char *const* cargv, const char *const *cenvv)
{
int err;
// debug( 1, L"exec '%ls'", p->argv[0] );
// This function never returns, so we take certain liberties with constness
char * const * envv = const_cast<char* const *>(cenvv);
char * const * argv = const_cast<char* const *>(cargv);
execve(actual_cmd, argv, envv);
err = errno;
/*
Something went wrong with execve, check for a ":", and run
/bin/sh if encountered. This is a weird predecessor to the shebang
that is still sometimes used since it is supported on Windows.
*/
/* OK to not use CLO_EXEC here because this is called after fork and the file is immediately closed */
int fd = open(actual_cmd, O_RDONLY);
if (fd >= 0)
{
char begin[1] = {0};
ssize_t amt_read = read(fd, begin, 1);
close(fd);
if ((amt_read==1) && (begin[0] == ':'))
{
// Relaunch it with /bin/sh. Don't allocate memory, so if you have more args than this, update your silly script! Maybe this should be changed to be based on ARG_MAX somehow.
char sh_command[] = "/bin/sh";
char *argv2[128];
argv2[0] = sh_command;
for (size_t i=1; i < sizeof argv2 / sizeof *argv2; i++)
{
argv2[i] = argv[i-1];
if (argv2[i] == NULL)
break;
}
execve(sh_command, argv2, envv);
}
}
errno = err;
safe_report_exec_error(errno, actual_cmd, argv, envv);
exit_without_destructors(STATUS_EXEC_FAIL);
}
/**
This function is similar to launch_process, except it is not called after a fork (i.e. it only calls exec) and therefore it can allocate memory.
*/
static void launch_process_nofork(process_t *p)
{
ASSERT_IS_MAIN_THREAD();
ASSERT_IS_NOT_FORKED_CHILD();
char **argv = wcsv2strv(p->get_argv());
const char *const *envv = env_export_arr(false);
char *actual_cmd = wcs2str(p->actual_cmd.c_str());
/* Bounce to launch_process. This never returns. */
safe_launch_process(p, actual_cmd, argv, envv);
}
/**
Check if the IO redirection chains contains redirections for the
specified file descriptor
*/
static int has_fd(const io_chain_t &d, int fd)
{
return io_chain_get(d, fd).get() != NULL;
}
/**
Close a list of fds.
*/
static void io_cleanup_fds(const std::vector<int> &opened_fds)
{
std::for_each(opened_fds.begin(), opened_fds.end(), close);
}
/**
Make a copy of the specified io redirection chain, but change file
redirection into fd redirection. This makes the redirection chain
suitable for use as block-level io, since the file won't be
repeatedly reopened for every command in the block, which would
reset the cursor position.
\return the transmogrified chain on sucess, or 0 on failiure
*/
static bool io_transmogrify(const io_chain_t &in_chain, io_chain_t &out_chain, std::vector<int> &out_opened_fds)
{
ASSERT_IS_MAIN_THREAD();
assert(out_chain.empty());
/* Just to be clear what we do for an empty chain */
if (in_chain.empty())
{
return true;
}
bool success = true;
/* Make our chain of redirections */
io_chain_t result_chain;
/* In the event we can't finish transmorgrifying, we'll have to close all the files we opened. */
std::vector<int> opened_fds;
for (size_t idx = 0; idx < in_chain.size(); idx++)
{
const shared_ptr<io_data_t> &in = in_chain.at(idx);
shared_ptr<io_data_t> out; //gets allocated via new
switch (in->io_mode)
{
default:
/* Unknown type, should never happen */
fprintf(stderr, "Unknown io_mode %ld\n", (long)in->io_mode);
abort();
break;
/*
These redirections don't need transmogrification. They can be passed through.
*/
case IO_PIPE:
case IO_FD:
case IO_BUFFER:
case IO_CLOSE:
{
out = in;
break;
}
/*
Transmogrify file redirections
*/
case IO_FILE:
{
int fd;
CAST_INIT(io_file_t *, in_file, in.get());
if ((fd=open(in_file->filename_cstr, in_file->flags, OPEN_MASK))==-1)
{
debug(1,
FILE_ERROR,
in_file->filename_cstr);
wperror(L"open");
success = false;
break;
}
opened_fds.push_back(fd);
out.reset(new io_fd_t(in->fd, fd, true));
break;
}
}
if (out.get() != NULL)
result_chain.push_back(out);
/* Don't go any further if we failed */
if (! success)
{
break;
}
}
/* Now either return success, or clean up */
if (success)
{
/* Yay */
out_chain.swap(result_chain);
out_opened_fds.swap(opened_fds);
}
else
{
/* No dice - clean up */
result_chain.clear();
io_cleanup_fds(opened_fds);
}
return success;
}
/**
Morph an io redirection chain into redirections suitable for
passing to eval, call eval, and clean up morphed redirections.
\param def the code to evaluate
\param block_type the type of block to push on evaluation
\param io the io redirections to be performed on this block
*/
static void internal_exec_helper(parser_t &parser,
const wchar_t *def,
enum block_type_t block_type,
const io_chain_t &ios)
{
io_chain_t morphed_chain;
std::vector<int> opened_fds;
bool transmorgrified = io_transmogrify(ios, morphed_chain, opened_fds);
int is_block_old=is_block;
is_block=1;
/*
Did the transmogrification fail - if so, set error status and return
*/
if (! transmorgrified)
{
proc_set_last_status(STATUS_EXEC_FAIL);
return;
}
signal_unblock();
parser.eval(def, morphed_chain, block_type);
signal_block();
morphed_chain.clear();
io_cleanup_fds(opened_fds);
job_reap(0);
is_block=is_block_old;
}
/* Returns whether we can use posix spawn for a given process in a given job.
Per https://github.com/fish-shell/fish-shell/issues/364 , error handling for file redirections is too difficult with posix_spawn,
so in that case we use fork/exec.
Furthermore, to avoid the race between the caller calling tcsetpgrp() and the client checking the foreground process group, we don't use posix_spawn if we're going to foreground the process. (If we use fork(), we can call tcsetpgrp after the fork, before the exec, and avoid the race).
*/
static bool can_use_posix_spawn_for_job(const job_t *job, const process_t *process)
{
if (job_get_flag(job, JOB_CONTROL))
{
/* We are going to use job control; therefore when we launch this job it will get its own process group ID. But will it be foregrounded? */
if (job_get_flag(job, JOB_TERMINAL) && job_get_flag(job, JOB_FOREGROUND))
{
/* It will be foregrounded, so we will call tcsetpgrp(), therefore do not use posix_spawn */
return false;
}
}
/* Now see if we have a redirection involving a file. The only one we allow is /dev/null, which we assume will not fail. */
bool result = true;
if (chain_contains_redirection_to_real_file(job->block_io_chain()) || chain_contains_redirection_to_real_file(process->io_chain()))
{
result = false;
}
return result;
}
/* What exec does if no_exec is set. This only has to handle block pushing and popping. See #624. */
static void exec_no_exec(parser_t &parser, const job_t *job)
{
/* Hack hack hack. If this is an 'end' job, then trigger a pop. If this is a job that would create a block, trigger a push. See #624 */
const process_t *p = job->first_process;
if (p && p->type == INTERNAL_BUILTIN)
{
const wchar_t *builtin_name_cstr = p->argv0();
if (builtin_name_cstr != NULL)
{
const wcstring builtin_name = builtin_name_cstr;
if (contains(builtin_name, L"for", L"function", L"begin", L"switch"))
{
// The above builtins are the ones that produce an unbalanced block from within their function implementation
// This list should be maintained somewhere else
parser.push_block(new fake_block_t());
}
else if (builtin_name == L"end")
{
if (parser.current_block == NULL || parser.current_block->type() == TOP)
{
fprintf(stderr, "Warning: not popping the root block\n");
}
else
{
parser.pop_block();
}
}
}
}
}
void exec_job(parser_t &parser, job_t *j)
{
pid_t pid = 0;
sigset_t chldset;
/*
Set to true if something goes wrong while exec:ing the job, in
which case the cleanup code will kick in.
*/
bool exec_error = false;
bool needs_keepalive = false;
process_t keepalive;
CHECK(j,);
CHECK_BLOCK();
if (no_exec)
{
exec_no_exec(parser, j);
return;
}
sigemptyset(&chldset);
sigaddset(&chldset, SIGCHLD);
debug(4, L"Exec job '%ls' with id %d", j->command_wcstr(), j->job_id);
/* PCA Here we detect the special case of an input buffer redirection, i.e. we want a process to receive data that we hold in a buffer (it is an INPUT for the process, but an output for fish). This is extremely rare: I believe only run_pager creates these and it would be nice to dump it. So we can only have at most one.
It would be great to wean fish_pager off of input redirections so that we can dump input redirections and the INTERNAL_BUFFER process type altogether.
*/
const io_buffer_t *single_magic_input_redirect = NULL;
const io_chain_t all_ios = j->all_io_redirections();
for (size_t idx = 0; idx < all_ios.size(); idx++)
{
const shared_ptr<io_data_t> &io = all_ios.at(idx);
if ((io->io_mode == IO_BUFFER))
{
CAST_INIT(io_buffer_t *, io_buffer, io.get());
if (io_buffer->is_input)
{
/* We expect to have at most one of these, per the comment above. Note that this assertion is the only reason we don't break out of the loop below */
assert(single_magic_input_redirect == NULL && "Should have at most one input IO_BUFFER");
/*
Input redirection - create a new gobetween process to take
care of buffering, save the redirection in input_redirect
*/
process_t *fake = new process_t();
fake->type = INTERNAL_BUFFER;
fake->pipe_write_fd = STDOUT_FILENO;
j->first_process->pipe_read_fd = io->fd;
fake->next = j->first_process;
j->first_process = fake;
single_magic_input_redirect = io_buffer;
}
}
}
if (j->first_process->type==INTERNAL_EXEC)
{
/*
Do a regular launch - but without forking first...
*/
signal_block();
/*
setup_child_process makes sure signals are properly set
up. It will also call signal_unblock
*/
/* PCA This is for handling exec. Passing all_ios here matches what fish 2.0.0 and 1.x did. It's known to be wrong - for example, it means that redirections bound for subsequent commands in the pipeline will apply to exec. However, using exec in a pipeline doesn't really make sense, so I'm not trying to fix it here. */
if (!setup_child_process(j, 0, all_ios))
{
/*
launch_process _never_ returns
*/
launch_process_nofork(j->first_process);
}
else
{
job_set_flag(j, JOB_CONSTRUCTED, 1);
j->first_process->completed=1;
return;
}
}
signal_block();
/*
See if we need to create a group keepalive process. This is
a process that we create to make sure that the process group
doesn't die accidentally, and is often needed when a
builtin/block/function is inside a pipeline, since that
usually means we have to wait for one program to exit before
continuing in the pipeline, causing the group leader to
exit.
*/
if (job_get_flag(j, JOB_CONTROL))
{
for (const process_t *p = j->first_process; p; p = p->next)
{
if (p->type != EXTERNAL)
{
if (p->next)
{
needs_keepalive = true;
break;
}
if (p != j->first_process)
{
needs_keepalive = true;
break;
}
}
}
}
if (needs_keepalive)
{
/* Call fork. No need to wait for threads since our use is confined and simple. */
if (g_log_forks)
{
printf("fork #%d: Executing keepalive fork for '%ls'\n", g_fork_count, j->command_wcstr());
}
keepalive.pid = execute_fork(false);
if (keepalive.pid == 0)
{
/* Child */
keepalive.pid = getpid();
set_child_group(j, &keepalive, 1);
pause();
exit_without_destructors(0);
}
else
{
/* Parent */
set_child_group(j, &keepalive, 0);
}
}
/*
This loop loops over every process_t in the job, starting it as
appropriate. This turns out to be rather complex, since a
process_t can be one of many rather different things.
The loop also has to handle pipelining between the jobs.
*/
/* We can have up to three pipes "in flight" at a time:
1. The pipe the current process should read from (courtesy of the previous process)
2. The pipe that the current process should write to
3. The pipe that the next process should read from (courtesy of us)
We are careful to set these to -1 when closed, so if we exit the loop abruptly, we can still close them.
*/
int pipe_current_read = -1, pipe_current_write = -1, pipe_next_read = -1;
for (process_t *p=j->first_process; p; p = p->next)
{
/* The IO chain for this process. It starts with the block IO, then pipes, and then gets any from the process */
io_chain_t process_net_io_chain = j->block_io_chain();
/* "Consume" any pipe_next_read by making it current */
assert(pipe_current_read == -1);
pipe_current_read = pipe_next_read;
pipe_next_read = -1;
/* See if we need a pipe */
const bool pipes_to_next_command = (p->next != NULL);
/* The pipes the current process write to and read from.
Unfortunately these can't be just allocated on the stack, since
j->io wants shared_ptr.
The write pipe (destined for stdout) needs to occur before redirections. For example, with a redirection like this:
`foo 2>&1 | bar`, what we want to happen is this:
dup2(pipe, stdout)
dup2(stdout, stderr)
so that stdout and stderr both wind up referencing the pipe.
The read pipe (destined for stdin) is more ambiguous. Imagine a pipeline like this:
echo alpha | cat < beta.txt
Should cat output alpha or beta? bash and ksh output 'beta', tcsh gets it right and complains about ambiguity, and zsh outputs both (!). No shells appear to output 'alpha', so we match bash here. That would mean putting the pipe first, so that it gets trumped by the file redirection.
However, eval does this:
echo "begin; $argv "\n" ;end eval2_inner <&3 3<&-" | source 3<&0
which depends on the redirection being evaluated before the pipe. So the write end of the pipe comes first, the read pipe of the pipe comes last. See issue #966.
*/
shared_ptr<io_pipe_t> pipe_write;
shared_ptr<io_pipe_t> pipe_read;
/* Write pipe goes first */
if (p->next)
{
pipe_write.reset(new io_pipe_t(p->pipe_write_fd, false));
process_net_io_chain.push_back(pipe_write);
}
/* The explicit IO redirections associated with the process */
process_net_io_chain.append(p->io_chain());
/* Read pipe goes last */
if (p != j->first_process)
{
pipe_read.reset(new io_pipe_t(p->pipe_read_fd, true));
/* Record the current read in pipe_read */
pipe_read->pipe_fd[0] = pipe_current_read;
process_net_io_chain.push_back(pipe_read);
}
/*
This call is used so the global environment variable array
is regenerated, if needed, before the fork. That way, we
avoid a lot of duplicate work where EVERY child would need
to generate it, since that result would not get written
back to the parent. This call could be safely removed, but
it would result in slightly lower performance - at least on
uniprocessor systems.
*/
if (p->type == EXTERNAL)
env_export_arr(true);
/*
Set up fd:s that will be used in the pipe
*/
if (pipes_to_next_command)
{
// debug( 1, L"%ls|%ls" , p->argv[0], p->next->argv[0]);
int local_pipe[2] = {-1, -1};
if (exec_pipe(local_pipe) == -1)
{
debug(1, PIPE_ERROR);
wperror(L"pipe");
exec_error = true;
job_mark_process_as_failed(j, p);
break;
}
// This tells the redirection about the fds, but the redirection does not close them
memcpy(pipe_write->pipe_fd, local_pipe, sizeof(int)*2);
// Record our pipes
// The fds should be negative to indicate that we aren't overwriting an fd we failed to close
assert(pipe_current_write == -1);
pipe_current_write = local_pipe[1];
assert(pipe_next_read == -1);
pipe_next_read = local_pipe[0];
}
//fprintf(stderr, "before IO: ");
//io_print(j->io);
// This is the IO buffer we use for storing the output of a block or function when it is in a pipeline
shared_ptr<io_buffer_t> block_output_io_buffer;
switch (p->type)
{
case INTERNAL_FUNCTION:
{
/*
Calls to function_get_definition might need to
source a file as a part of autoloading, hence there
must be no blocks.
*/
signal_unblock();
wcstring def;
bool function_exists = function_get_definition(p->argv0(), &def);
wcstring_list_t named_arguments = function_get_named_arguments(p->argv0());
bool shadows = function_get_shadows(p->argv0());
signal_block();
if (! function_exists)
{
debug(0, _(L"Unknown function '%ls'"), p->argv0());
break;
}
function_block_t *newv = new function_block_t(p, p->argv0(), shadows);
parser.push_block(newv);
/*
set_argv might trigger an event
handler, hence we need to unblock
signals.
*/
signal_unblock();
parse_util_set_argv(p->get_argv()+1, named_arguments);
signal_block();
parser.forbid_function(p->argv0());
if (p->next)
{
// Be careful to handle failure, e.g. too many open fds
block_output_io_buffer.reset(io_buffer_t::create(false /* = not input */, STDOUT_FILENO));
if (block_output_io_buffer.get() == NULL)
{
exec_error = true;
job_mark_process_as_failed(j, p);
}
else
{
/* This looks sketchy, because we're adding this io buffer locally - they aren't in the process or job redirection list. Therefore select_try won't be able to read them. However we call block_output_io_buffer->read() below, which reads until EOF. So there's no need to select on this. */
process_net_io_chain.push_back(block_output_io_buffer);
}
}
if (! exec_error)
{
internal_exec_helper(parser, def.c_str(), TOP, process_net_io_chain);
}
parser.allow_function();
parser.pop_block();
break;
}
case INTERNAL_BLOCK:
{
if (p->next)
{
block_output_io_buffer.reset(io_buffer_t::create(0));
if (block_output_io_buffer.get() == NULL)
{
exec_error = true;
job_mark_process_as_failed(j, p);
}
else
{
/* See the comment above about it's OK to add an IO redirection to this local buffer, even though it won't be handled in select_try */
process_net_io_chain.push_back(block_output_io_buffer);
}
}
if (! exec_error)
{
internal_exec_helper(parser, p->argv0(), TOP, process_net_io_chain);
}
break;
}
case INTERNAL_BUILTIN:
{
int builtin_stdin=0;
bool close_stdin = false;
/*
If this is the first process, check the io
redirections and see where we should be reading
from.
*/
if (p == j->first_process)
{
const shared_ptr<const io_data_t> in = process_net_io_chain.get_io_for_fd(STDIN_FILENO);
if (in)
{
switch (in->io_mode)
{
case IO_FD:
{
CAST_INIT(const io_fd_t *, in_fd, in.get());
builtin_stdin = in_fd->old_fd;
break;
}
case IO_PIPE:
{
CAST_INIT(const io_pipe_t *, in_pipe, in.get());
builtin_stdin = in_pipe->pipe_fd[0];
break;
}
case IO_FILE:
{
/* Do not set CLO_EXEC because child needs access */
CAST_INIT(const io_file_t *, in_file, in.get());
builtin_stdin=open(in_file->filename_cstr,
in_file->flags, OPEN_MASK);
if (builtin_stdin == -1)