-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathprocess.py
1500 lines (1203 loc) · 45 KB
/
process.py
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
# Copyright 2016 Andy Chu. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
"""
process.py - Launch processes and manipulate file descriptors.
"""
from __future__ import print_function
from errno import EACCES, EBADF, ECHILD, EINTR, ENOENT, ENOEXEC
import fcntl as fcntl_
import signal as signal_
from sys import exit # mycpp translation directly calls exit(int status)!
from _devbuild.gen.id_kind_asdl import Id
from _devbuild.gen.runtime_asdl import (
job_state_e, job_state_t, job_state_str,
wait_status, wait_status_t,
redirect, redirect_arg_e, redirect_arg__Path, redirect_arg__CopyFd,
redirect_arg__MoveFd, redirect_arg__HereDoc,
value, value_e, lvalue, value__Str, trace, trace_t
)
from _devbuild.gen.syntax_asdl import (
redir_loc, redir_loc_e, redir_loc_t, redir_loc__VarName, redir_loc__Fd,
)
from core import dev
from core import pyutil
from core.pyutil import stderr_line
from core import pyos
from core import state
from core import ui
from core import util
from core.pyerror import log
from frontend import match
from osh import cmd_eval
from qsn_ import qsn
from mycpp import mylib
from mycpp.mylib import tagswitch, iteritems, NewStr
import posix_ as posix
from posix_ import (
# translated by mycpp and directly called! No wrapper!
WUNTRACED,
WIFSIGNALED, WIFEXITED, WIFSTOPPED,
WEXITSTATUS, WTERMSIG,
O_APPEND, O_CREAT, O_RDONLY, O_RDWR, O_WRONLY, O_TRUNC,
)
from typing import List, Tuple, Dict, Optional, cast, TYPE_CHECKING
if TYPE_CHECKING:
from _devbuild.gen.runtime_asdl import cmd_value__Argv
from _devbuild.gen.syntax_asdl import command_t
from core import optview
from core.state import Mem
from core.ui import ErrorFormatter
from core.util import _DebugFile
from osh.cmd_eval import CommandEvaluator
NO_FD = -1
# Minimum file descriptor that the shell can use. Other descriptors can be
# directly used by user programs, e.g. exec 9>&1
#
# Oil uses 100 because users are allowed TWO digits in frontend/lexer_def.py.
# This is a compromise between bash (unlimited, but requires crazy
# bookkeeping), and dash/zsh (10) and mksh (24)
_SHELL_MIN_FD = 100
def SaveFd(fd):
# type: (int) -> int
saved = fcntl_.fcntl(fd, fcntl_.F_DUPFD, _SHELL_MIN_FD) # type: int
return saved
class _RedirFrame(object):
def __init__(self, saved_fd, orig_fd, forget):
# type: (int, int, bool) -> None
self.saved_fd = saved_fd
self.orig_fd = orig_fd
self.forget = forget
class _FdFrame(object):
def __init__(self):
# type: () -> None
self.saved = [] # type: List[_RedirFrame]
self.need_wait = [] # type: List[Process]
def Forget(self):
# type: () -> None
"""For exec 1>&2."""
for rf in reversed(self.saved):
if rf.saved_fd != NO_FD and rf.forget:
posix.close(rf.saved_fd)
del self.saved[:] # like list.clear() in Python 3.3
del self.need_wait[:]
def __repr__(self):
# type: () -> str
return '<_FdFrame %s>' % self.saved
class FdState(object):
"""File descriptor state for the current process.
For example, you can do 'myfunc > out.txt' without forking. Child processes
inherit our state.
"""
def __init__(self, errfmt, job_state, mem, tracer, waiter):
# type: (ErrorFormatter, JobState, Mem, Optional[dev.Tracer], Optional[Waiter]) -> None
"""
Args:
errfmt: for errors
job_state: For keeping track of _HereDocWriterThunk
"""
self.errfmt = errfmt
self.job_state = job_state
self.cur_frame = _FdFrame() # for the top level
self.stack = [self.cur_frame]
self.mem = mem
self.tracer = tracer
self.waiter = waiter
def Open(self, path):
# type: (str) -> mylib.LineReader
"""Opens a path for read, but moves it out of the reserved 3-9 fd range.
Returns:
A Python file object. The caller is responsible for Close().
Raises:
IOError or OSError if the path can't be found. (This is Python-induced wart)
"""
fd_mode = O_RDONLY
return self._Open(path, 'r', fd_mode)
if mylib.PYTHON:
# used for util.DebugFile
def OpenForWrite(self, path):
# type: (str) -> mylib.Writer
fd_mode = O_CREAT | O_RDWR
f = self._Open(path, 'w', fd_mode)
# Hack to change mylib.LineReader into mylib.Writer. In reality the file
# object supports both interfaces.
return cast('mylib.Writer', f)
def _Open(self, path, c_mode, fd_mode):
# type: (str, str, int) -> mylib.LineReader
fd = posix.open(path, fd_mode, 0o666) # may raise OSError
# Immediately move it to a new location
new_fd = SaveFd(fd)
posix.close(fd)
# Return a Python file handle
f = posix.fdopen(new_fd, c_mode) # may raise IOError.
return f
def _WriteFdToMem(self, fd_name, fd):
# type: (str, int) -> None
if self.mem:
# setvar, not setref
state.OshLanguageSetValue(self.mem, lvalue.Named(fd_name), value.Str(str(fd)))
def _ReadFdFromMem(self, fd_name):
# type: (str) -> int
val = self.mem.GetValue(fd_name)
if val.tag_() == value_e.Str:
try:
return int(cast(value__Str, val).s)
except ValueError:
return NO_FD
return NO_FD
def _PushSave(self, fd):
# type: (int) -> bool
"""Save fd to a new location and remember to restore it later."""
#log('---- _PushSave %s', fd)
need_restore = True
try:
new_fd = SaveFd(fd)
except IOError as e:
# Example program that causes this error: exec 4>&1. Descriptor 4 isn't
# open.
# This seems to be ignored in dash too in savefd()?
if e.errno == EBADF:
#log('ERROR fd %d: %s', fd, e)
need_restore = False
else:
raise
else:
posix.close(fd)
fcntl_.fcntl(new_fd, fcntl_.F_SETFD, fcntl_.FD_CLOEXEC)
#pyutil.ShowFdState()
if need_restore:
self.cur_frame.saved.append(_RedirFrame(new_fd, fd, True))
else:
# if we got EBADF, we still need to close the original on Pop()
self._PushClose(fd)
#pass
return need_restore
def _PushDup(self, fd1, loc):
# type: (int, redir_loc_t) -> int
"""Save fd2 in a higher range, and dup fd1 onto fd2.
Returns whether F_DUPFD/dup2 succeeded, and the new descriptor.
"""
UP_loc = loc
if loc.tag_() == redir_loc_e.VarName:
fd2_name = cast(redir_loc__VarName, UP_loc).name
try:
# F_DUPFD: GREATER than range
new_fd = fcntl_.fcntl(fd1, fcntl_.F_DUPFD, _SHELL_MIN_FD) # type: int
except IOError as e:
if e.errno == EBADF:
self.errfmt.Print_('%d: %s' % (fd1, pyutil.strerror(e)))
return NO_FD
else:
raise # this redirect failed
self._WriteFdToMem(fd2_name, new_fd)
elif loc.tag_() == redir_loc_e.Fd:
fd2 = cast(redir_loc__Fd, UP_loc).fd
if fd1 == fd2:
# The user could have asked for it to be open on descrptor 3, but open()
# already returned 3, e.g. echo 3>out.txt
return NO_FD
# Check the validity of fd1 before _PushSave(fd2)
try:
fcntl_.fcntl(fd1, fcntl_.F_GETFD)
except IOError as e:
self.errfmt.Print_('%d: %s' % (fd1, pyutil.strerror(e)))
raise
need_restore = self._PushSave(fd2)
#log('==== dup2 %s %s\n' % (fd1, fd2))
try:
posix.dup2(fd1, fd2)
except OSError as e:
# bash/dash give this error too, e.g. for 'echo hi 1>&3'
self.errfmt.Print_('%d: %s' % (fd1, pyutil.strerror(e)))
# Restore and return error
if need_restore:
rf = self.cur_frame.saved.pop()
posix.dup2(rf.saved_fd, rf.orig_fd)
posix.close(rf.saved_fd)
raise # this redirect failed
new_fd = fd2
else:
raise AssertionError()
return new_fd
def _PushCloseFd(self, loc):
# type: (redir_loc_t) -> bool
"""For 2>&-"""
# exec {fd}>&- means close the named descriptor
UP_loc = loc
if loc.tag_() == redir_loc_e.VarName:
fd_name = cast(redir_loc__VarName, UP_loc).name
fd = self._ReadFdFromMem(fd_name)
if fd == NO_FD:
return False
elif loc.tag_() == redir_loc_e.Fd:
fd = cast(redir_loc__Fd, UP_loc).fd
else:
raise AssertionError()
self._PushSave(fd)
return True
def _PushClose(self, fd):
# type: (int) -> None
self.cur_frame.saved.append(_RedirFrame(NO_FD, fd, False))
def _PushWait(self, proc):
# type: (Process) -> None
self.cur_frame.need_wait.append(proc)
def _ApplyRedirect(self, r):
# type: (redirect) -> None
arg = r.arg
UP_arg = arg
with tagswitch(arg) as case:
if case(redirect_arg_e.Path):
arg = cast(redirect_arg__Path, UP_arg)
if r.op_id in (Id.Redir_Great, Id.Redir_AndGreat): # > &>
# NOTE: This is different than >| because it respects noclobber, but
# that option is almost never used. See test/wild.sh.
mode = O_CREAT | O_WRONLY | O_TRUNC
elif r.op_id == Id.Redir_Clobber: # >|
mode = O_CREAT | O_WRONLY | O_TRUNC
elif r.op_id in (Id.Redir_DGreat, Id.Redir_AndDGreat): # >> &>>
mode = O_CREAT | O_WRONLY | O_APPEND
elif r.op_id == Id.Redir_Less: # <
mode = O_RDONLY
elif r.op_id == Id.Redir_LessGreat: # <>
mode = O_CREAT | O_RDWR
else:
raise NotImplementedError(r.op_id)
# NOTE: 0666 is affected by umask, all shells use it.
try:
open_fd = posix.open(arg.filename, mode, 0o666)
except OSError as e:
self.errfmt.Print_(
"Can't open %r: %s" % (arg.filename, pyutil.strerror(e)),
span_id=r.op_spid)
raise # redirect failed
new_fd = self._PushDup(open_fd, r.loc)
if new_fd != NO_FD:
posix.close(open_fd)
# Now handle &> and &>> and their variants. These pairs are the same:
#
# stdout_stderr.py &> out-err.txt
# stdout_stderr.py > out-err.txt 2>&1
#
# stdout_stderr.py 3&> out-err.txt
# stdout_stderr.py 3> out-err.txt 2>&3
#
# Ditto for {fd}> and {fd}&>
if r.op_id in (Id.Redir_AndGreat, Id.Redir_AndDGreat):
self._PushDup(new_fd, redir_loc.Fd(2))
elif case(redirect_arg_e.CopyFd): # e.g. echo hi 1>&2
arg = cast(redirect_arg__CopyFd, UP_arg)
if r.op_id == Id.Redir_GreatAnd: # 1>&2
self._PushDup(arg.target_fd, r.loc)
elif r.op_id == Id.Redir_LessAnd: # 0<&5
# The only difference between >& and <& is the default file
# descriptor argument.
self._PushDup(arg.target_fd, r.loc)
else:
raise NotImplementedError()
elif case(redirect_arg_e.MoveFd): # e.g. echo hi 5>&6-
arg = cast(redirect_arg__MoveFd, UP_arg)
new_fd = self._PushDup(arg.target_fd, r.loc)
if new_fd != NO_FD:
posix.close(arg.target_fd)
UP_loc = r.loc
if r.loc.tag_() == redir_loc_e.Fd:
fd = cast(redir_loc__Fd, UP_loc).fd
else:
fd = NO_FD
self.cur_frame.saved.append(_RedirFrame(new_fd, fd, False))
elif case(redirect_arg_e.CloseFd): # e.g. echo hi 5>&-
self._PushCloseFd(r.loc)
elif case(redirect_arg_e.HereDoc):
arg = cast(redirect_arg__HereDoc, UP_arg)
# NOTE: Do these descriptors have to be moved out of the range 0-9?
read_fd, write_fd = posix.pipe()
self._PushDup(read_fd, r.loc) # stdin is now the pipe
# We can't close like we do in the filename case above? The writer can
# get a "broken pipe".
self._PushClose(read_fd)
thunk = _HereDocWriterThunk(write_fd, arg.body)
# TODO: Use PIPE_SIZE to save a process in the case of small here docs,
# which are the common case. (dash does this.)
start_process = True
#start_process = False
if start_process:
here_proc = Process(thunk, self.job_state, self.tracer)
# NOTE: we could close the read pipe here, but it doesn't really
# matter because we control the code.
_ = here_proc.Start(trace.HereDoc())
#log('Started %s as %d', here_proc, pid)
self._PushWait(here_proc)
# Now that we've started the child, close it in the parent.
posix.close(write_fd)
else:
posix.write(write_fd, arg.body)
posix.close(write_fd)
def Push(self, redirects):
# type: (List[redirect]) -> bool
"""Apply a group of redirects and remember to undo them."""
#log('> fd_state.Push %s', redirects)
new_frame = _FdFrame()
self.stack.append(new_frame)
self.cur_frame = new_frame
for r in redirects:
#log('apply %s', r)
self.errfmt.PushLocation(r.op_spid)
try:
self._ApplyRedirect(r)
except (IOError, OSError) as e:
self.Pop()
return False # for bad descriptor, etc.
finally:
self.errfmt.PopLocation()
#log('done applying %d redirects', len(redirects))
return True
def PushStdinFromPipe(self, r):
# type: (int) -> bool
"""Save the current stdin and make it come from descriptor 'r'.
'r' is typically the read-end of a pipe. For 'lastpipe'/ZSH semantics of
echo foo | read line; echo $line
"""
new_frame = _FdFrame()
self.stack.append(new_frame)
self.cur_frame = new_frame
self._PushDup(r, redir_loc.Fd(0))
return True
def Pop(self):
# type: () -> None
frame = self.stack.pop()
#log('< Pop %s', frame)
for rf in reversed(frame.saved):
if rf.saved_fd == NO_FD:
#log('Close %d', orig)
try:
posix.close(rf.orig_fd)
except OSError as e:
log('Error closing descriptor %d: %s', rf.orig_fd, pyutil.strerror(e))
raise
else:
try:
posix.dup2(rf.saved_fd, rf.orig_fd)
except OSError as e:
log('dup2(%d, %d) error: %s', rf.saved_fd, rf.orig_fd, pyutil.strerror(e))
#log('fd state:')
#posix.system('ls -l /proc/%s/fd' % posix.getpid())
raise
posix.close(rf.saved_fd)
#log('dup2 %s %s', saved, orig)
# Wait for here doc processes to finish.
for proc in frame.need_wait:
unused_status = proc.Wait(self.waiter)
def MakePermanent(self):
# type: () -> None
self.cur_frame.Forget()
class ChildStateChange(object):
def __init__(self):
# type: () -> None
"""Empty constructor for mycpp."""
pass
def Apply(self):
# type: () -> None
raise NotImplementedError()
class StdinFromPipe(ChildStateChange):
def __init__(self, pipe_read_fd, w):
# type: (int, int) -> None
self.r = pipe_read_fd
self.w = w
def __repr__(self):
# type: () -> str
return '<StdinFromPipe %d %d>' % (self.r, self.w)
def Apply(self):
# type: () -> None
posix.dup2(self.r, 0)
posix.close(self.r) # close after dup
posix.close(self.w) # we're reading from the pipe, not writing
#log('child CLOSE w %d pid=%d', self.w, posix.getpid())
class StdoutToPipe(ChildStateChange):
def __init__(self, r, pipe_write_fd):
# type: (int, int) -> None
self.r = r
self.w = pipe_write_fd
def __repr__(self):
# type: () -> str
return '<StdoutToPipe %d %d>' % (self.r, self.w)
def Apply(self):
# type: () -> None
posix.dup2(self.w, 1)
posix.close(self.w) # close after dup
posix.close(self.r) # we're writing to the pipe, not reading
#log('child CLOSE r %d pid=%d', self.r, posix.getpid())
class ExternalProgram(object):
"""The capability to execute an external program like 'ls'. """
def __init__(self,
hijack_shebang, # type: str
fd_state, # type: FdState
errfmt, # type: ErrorFormatter
debug_f, # type: _DebugFile
):
# type: (...) -> None
"""
Args:
hijack_shebang: The path of an interpreter to run instead of the one
specified in the shebang line. May be empty.
"""
self.hijack_shebang = hijack_shebang
self.fd_state = fd_state
self.errfmt = errfmt
self.debug_f = debug_f
def Exec(self, argv0_path, cmd_val, environ):
# type: (str, cmd_value__Argv, Dict[str, str]) -> None
"""Execute a program and exit this process.
Called by:
ls /
exec ls /
( ls / )
"""
self._Exec(argv0_path, cmd_val.argv, cmd_val.arg_spids[0], environ, True)
assert False, "This line should never execute" # NO RETURN
def _Exec(self, argv0_path, argv, argv0_spid, environ, should_retry):
# type: (str, List[str], int, Dict[str, str], bool) -> None
if len(self.hijack_shebang):
try:
f = self.fd_state.Open(argv0_path)
except (IOError, OSError) as e:
pass
else:
try:
# Test if the shebang looks like a shell. The file might be binary
# with no newlines, so read 80 bytes instead of readline().
line = f.read(80) # type: ignore # TODO: fix this
if match.ShouldHijack(line):
argv = [self.hijack_shebang, argv0_path] + argv[1:]
argv0_path = self.hijack_shebang
self.debug_f.log('Hijacked: %s', argv)
else:
#self.debug_f.log('Not hijacking %s (%r)', argv, line)
pass
finally:
f.close()
try:
posix.execve(argv0_path, argv, environ)
except OSError as e:
# Run with /bin/sh when ENOEXEC error (no shebang). All shells do this.
if e.errno == ENOEXEC and should_retry:
new_argv = ['/bin/sh', argv0_path]
new_argv.extend(argv[1:])
self._Exec('/bin/sh', new_argv, argv0_spid, environ, False)
# NO RETURN
# Would be nice: when the path is relative and ENOENT: print PWD and do
# spelling correction?
self.errfmt.Print_(
"Can't execute %r: %s" % (argv0_path, pyutil.strerror(e)),
span_id=argv0_spid)
# POSIX mentions 126 and 127 for two specific errors. The rest are
# unspecified.
#
# http://pubs.opengroup.org/onlinepubs/9699919799.2016edition/utilities/V3_chap02.html#tag_18_08_02
if e.errno == EACCES:
status = 126
elif e.errno == ENOENT:
# TODO: most shells print 'command not found', rather than strerror()
# == "No such file or directory". That's better because it's at the
# end of the path search, and we're never searching for a directory.
status = 127
else:
# dash uses 2, but we use that for parse errors. This seems to be
# consistent with mksh and zsh.
status = 127
exit(status) # raises SystemExit
# NO RETURN
class Thunk(object):
"""Abstract base class for things runnable in another process."""
def __init__(self):
# type: () -> None
"""Empty constructor for mycpp."""
pass
def Run(self):
# type: () -> None
"""Returns a status code."""
raise NotImplementedError()
def UserString(self):
# type: () -> str
"""Display for the 'jobs' list."""
raise NotImplementedError()
def __repr__(self):
# type: () -> str
return self.UserString()
class ExternalThunk(Thunk):
"""An external executable."""
def __init__(self, ext_prog, argv0_path, cmd_val, environ):
# type: (ExternalProgram, str, cmd_value__Argv, Dict[str, str]) -> None
self.ext_prog = ext_prog
self.argv0_path = argv0_path
self.cmd_val = cmd_val
self.environ = environ
def UserString(self):
# type: () -> str
# NOTE: This is the format the Tracer uses.
# bash displays sleep $n & (code)
# but OSH displays sleep 1 & (argv array)
# We could switch the former but I'm not sure it's necessary.
tmp = [qsn.maybe_shell_encode(a) for a in self.cmd_val.argv]
return '[process] %s' % ' '.join(tmp)
def Run(self):
# type: () -> None
"""
An ExternalThunk is run in parent for the exec builtin.
"""
self.ext_prog.Exec(self.argv0_path, self.cmd_val, self.environ)
class SubProgramThunk(Thunk):
"""A subprogram that can be executed in another process."""
def __init__(self, cmd_ev, node, inherit_errexit=True):
# type: (CommandEvaluator, command_t, bool) -> None
self.cmd_ev = cmd_ev
self.node = node
self.inherit_errexit = inherit_errexit # for bash errexit compatibility
def UserString(self):
# type: () -> str
# NOTE: These can be pieces of a pipeline, so they're arbitrary nodes.
# TODO: Extract SPIDS from node to display source? Note that
# CompoundStatus also has locations of each pipeline component; see
# Executor.RunPipeline()
thunk_str = ui.CommandType(self.node)
return '[subprog] %s' % thunk_str
def Run(self):
# type: () -> None
#self.errfmt.OneLineErrExit() # don't quote code in child processes
# NOTE: may NOT return due to exec().
if not self.inherit_errexit:
self.cmd_ev.mutable_opts.DisableErrExit()
try:
# optimize to eliminate redundant subshells like ( echo hi ) | wc -l etc.
self.cmd_ev.ExecuteAndCatch(self.node, cmd_flags=cmd_eval.Optimize)
status = self.cmd_ev.LastStatus()
# NOTE: We ignore the is_fatal return value. The user should set -o
# errexit so failures in subprocesses cause failures in the parent.
except util.UserExit as e:
status = e.status
# Handle errors in a subshell. These two cases are repeated from main()
# and the core/completion.py hook.
except KeyboardInterrupt:
print('')
status = 130 # 128 + 2
except (IOError, OSError) as e:
stderr_line('osh I/O error: %s', pyutil.strerror(e))
status = 2
# We do NOT want to raise SystemExit here. Otherwise dev.Tracer::Pop()
# gets called in BOTH processes.
# The crash dump seems to be unaffected.
posix._exit(status)
class _HereDocWriterThunk(Thunk):
"""Write a here doc to one end of a pipe.
May be be executed in either a child process or the main shell process.
"""
def __init__(self, w, body_str):
# type: (int, str) -> None
self.w = w
self.body_str = body_str
def UserString(self):
# type: () -> str
# You can hit Ctrl-Z and the here doc writer will be suspended! Other
# shells don't have this problem because they use temp files! That's a bit
# unfortunate.
return '[here doc writer]'
def Run(self):
# type: () -> None
"""
do_exit: For small pipelines
"""
#log('Writing %r', self.body_str)
posix.write(self.w, self.body_str)
#log('Wrote %r', self.body_str)
posix.close(self.w)
#log('Closed %d', self.w)
exit(0) # Could this fail?
class Job(object):
"""Interface for both Process and Pipeline.
They both can be put in the background and waited on.
Confusing thing about pipelines in the background: They have TOO MANY NAMES.
sleep 1 | sleep 2 &
- The LAST PID is what's printed at the prompt. This is $!, a PROCESS ID and
not a JOB ID.
# https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#Special-Parameters
- The process group leader (setpgid) is the FIRST PID.
- It's also %1 or %+. The last job started.
"""
def __init__(self):
# type: () -> None
# Initial state with & or Ctrl-Z is Running.
self.state = job_state_e.Running
def DisplayJob(self, job_id, f):
# type: (int, mylib.Writer) -> None
raise NotImplementedError()
def State(self):
# type: () -> job_state_t
return self.state
def JobWait(self, waiter):
# type: (Waiter) -> wait_status_t
"""Wait for this process/pipeline to be stopped or finished."""
raise NotImplementedError()
class Process(Job):
"""A process to run.
TODO: Should we make it clear that this is a FOREGROUND process? A
background process is wrapped in a "job". It is unevaluated.
It provides an API to manipulate file descriptor state in parent and child.
"""
def __init__(self, thunk, job_state, tracer):
# type: (Thunk, JobState, dev.Tracer) -> None
"""
Args:
thunk: Thunk instance
job_state: for process bookkeeping
"""
Job.__init__(self)
assert isinstance(thunk, Thunk), thunk
self.thunk = thunk
self.job_state = job_state
self.tracer = tracer
# For pipelines
self.parent_pipeline = None # type: Pipeline
self.state_changes = [] # type: List[ChildStateChange]
self.close_r = -1
self.close_w = -1
self.pid = -1
self.status = -1
def Init_ParentPipeline(self, pi):
# type: (Pipeline) -> None
"""For updating PIPESTATUS."""
self.parent_pipeline = pi
def __repr__(self):
# type: () -> str
# note: be wary of infinite mutual recursion
#s = ' %s' % self.parent_pipeline if self.parent_pipeline else ''
#return '<Process %s%s>' % (self.thunk, s)
return '<Process %s %s>' % (_JobStateStr(self.state), self.thunk)
def DisplayJob(self, job_id, f):
# type: (int, mylib.Writer) -> None
if job_id == -1:
job_id_str = ' '
else:
job_id_str = '%%%d' % job_id
f.write('%s %d %7s ' % (job_id_str, self.pid, _JobStateStr(self.state)))
f.write(self.thunk.UserString())
f.write('\n')
def AddStateChange(self, s):
# type: (ChildStateChange) -> None
self.state_changes.append(s)
def AddPipeToClose(self, r, w):
# type: (int, int) -> None
self.close_r = r
self.close_w = w
def MaybeClosePipe(self):
# type: () -> None
if self.close_r != -1:
posix.close(self.close_r)
posix.close(self.close_w)
def Start(self, why):
# type: (trace_t) -> int
"""Start this process with fork(), handling redirects."""
# TODO: If OSH were a job control shell, we might need to call some of
# these here. They control the distribution of signals, some of which
# originate from a terminal. All the processes in a pipeline should be in
# a single process group.
#
# - posix.setpgid()
# - posix.setpgrp()
# - posix.tcsetpgrp()
#
# NOTE: posix.setsid() isn't called by the shell; it's should be called by the
# login program that starts the shell.
#
# The whole job control mechanism is complicated and hacky.
pid = posix.fork()
if pid < 0:
# When does this happen?
raise RuntimeError('Fatal error in posix.fork()')
elif pid == 0: # child
pyos.SignalState_AfterForkingChild()
for st in self.state_changes:
st.Apply()
self.tracer.SetProcess(posix.getpid())
self.thunk.Run()
# Never returns
#log('STARTED process %s, pid = %d', self, pid)
self.tracer.OnProcessStart(pid, why)
# Class invariant: after the process is started, it stores its PID.
self.pid = pid
# Program invariant: We keep track of every child process!
self.job_state.AddChildProcess(pid, self)
return pid
def Wait(self, waiter):
# type: (Waiter) -> int
"""Wait for this process to finish."""
while self.state == job_state_e.Running:
# signals are ignored
if waiter.WaitForOne() == W1_ECHILD:
break
return self.status
def JobWait(self, waiter):
# type: (Waiter) -> wait_status_t
# wait builtin can be interrupted
while self.state == job_state_e.Running:
result = waiter.WaitForOne()
if result >= 0: # signal
return wait_status.Cancelled(result)
if result == W1_ECHILD:
break
return wait_status.Proc(self.status)
def WhenStopped(self):
# type: () -> None
self.state = job_state_e.Stopped
def WhenDone(self, pid, status):
# type: (int, int) -> None
"""Called by the Waiter when this Process finishes."""
#log('WhenDone %d %d', pid, status)
assert pid == self.pid, 'Expected %d, got %d' % (self.pid, pid)
self.status = status
self.state = job_state_e.Done
if self.parent_pipeline:
self.parent_pipeline.WhenDone(pid, status)
def RunWait(self, waiter, why):
# type: (Waiter, trace_t) -> int
"""Run this process synchronously."""
self.Start(why)
return self.Wait(waiter)
class Pipeline(Job):
"""A pipeline of processes to run.
Cases we handle:
foo | bar
$(foo | bar)
foo | bar | read v
"""
def __init__(self, sigpipe_status_ok):
# type: (bool) -> None
Job.__init__(self)
self.procs = [] # type: List[Process]
self.pids = [] # type: List[int] # pids in order
self.pipe_status = [] # type: List[int] # status in order
self.status = -1 # for 'wait' jobs
# Optional for foreground
self.last_thunk = None # type: Tuple[CommandEvaluator, command_t]
self.last_pipe = None # type: Tuple[int, int]
self.sigpipe_status_ok = sigpipe_status_ok
def DisplayJob(self, job_id, f):
# type: (int, mylib.Writer) -> None
for i, proc in enumerate(self.procs):
if i == 0: # show job ID for first element in pipeline
job_id_str = '%%%d' % job_id
else:
job_id_str = ' ' # 2 spaces
f.write('%s %d %7s ' % (job_id_str, proc.pid, _JobStateStr(proc.state)))
f.write(proc.thunk.UserString())
f.write('\n')
def DebugPrint(self):
# type: () -> None
print('Pipeline in state %s' % _JobStateStr(self.state))
if mylib.PYTHON: # %s for Process not allowed in C++
for proc in self.procs:
print(' proc %s' % proc)
_, last_node = self.last_thunk
print(' last %s' % last_node)
print(' pipe_status %s' % self.pipe_status)
def Add(self, p):
# type: (Process) -> None
"""Append a process to the pipeline."""
if len(self.procs) == 0:
self.procs.append(p)