Repository navigation
Conversation
I'm not sure if this happens on all platforms, but under WSL with the existing codebase, processes in the job chain that pipe their stdout/stderr to the next process in the job could terminate before the next job started (on fast enough machines for quick enough jobs). This caused issues like fish-shell#4235 and possibly fish-shell#3952, at least for external commands. What was happening is that the first process was finishing before the second process was fully set up. fish would then try to assign (in both the child and the parent) the process group id belonging to the process group leader to the new process; and if the first process had already terminated, it would have ended its process group with it as well before that happened. I'm not sure if there was already a mechanism in place for ensuring that a process remains running at least as long as it takes for the next process in the chain to join its group, etc., but if that code was there, it wasn't working in my test setup (WSL). This patch definitely needs some review; I'm not sure how I should handle non-external commands (and external commands executed via posix_spawn). I don't know if they are affected by the race condition in the first place, but when I tried to add the same "wait for next command in chain to run before unblocking" that would cause black screens requiring ctrl+c to bypass. The "unblock previous command" code was originally run by the next child to be forked, but was then moved to the shell code instead, making it more-centrally located and less error-prone. Note that additional headers may be required for the mmap system call on other platforms.
This code should be more portable, and certainly cleaner. We are currently always sending SIGCONT to the last process (if it was part of a job chain) regardless of whether it called SIGSTOP on itself or not, which should be fine. Need to explore whether or not the other forks in src/exec.cpp need to be SIGSTOP'd on run or only the one that we included in this patch.
I hadn't realized that the for loop is called multiple times for a given "single input" (anything that doesn't include semicolons, etc) to fish, and so processes were being blocked but blocked_pid was lost by the time that the next job (which was reading from the last process in the previous job) came around. Now using a static variable to store the last blocked PID. AFAICT, this main job control loop is always executed from the same process and thread, so this shouldn't need to be wrapped in atomics/mutexes, etc.
We were having child processes SIGSTOP themselves immediately after setting their process group and before launching their intended targets, but they were not necessarily stopped by the time the next command was being executed (so the opposite of the original race condition where they might have finished executing by the time the next command came around), and as a result when we sent them SIGCONT, that could never reach. Now using waitpid to synchronize the SIGSTOP/SIGCONT between the two. If we had a good, unnamed inter-process event/semaphore, we could use that to have a child process conditionally stop itself if the next command in the job chain hadn't yet been started / setup, but this is probably a lot more straightforward and less-confusing, which isn't a bad thing. Additionally, there was a bug caused by the fact that the main exec_job loop actually blocks to read from previous commands in the job if the current command is a built-in that doesn't need to fork. With this waitpid code, I was able to finally add the SIGSTOP code to all the fork'd processes in the main exec_job loop without introducing deadlocks; it turns out that they should be treated just like the main EXTERNAL fork, but they tend to execute faster causing the same deadlock described above to occur more readily. The only thing I'm not sure about is whether we should execute unblock_pid undconditionally for all !EXTERNAL commands. It makes more sense to *only* do that if a blocking read were about to be done in the main loop, otherwise the original race condition could still appear (though it is probably mitigated by whatever duration the SIGSTOP lasted for, even if it is SIGCONT'd before the next command tries to join the process group).
Setting the process group in a fork/exec scenario is a well-documented race condition in pretty much any job control mechanism [0] [1]. The Wikipedia article contradicts the glibc article and suggests that the best approach is for the parent to wait for the child to become the process group leader, while the glibc article suggests that both should make it so (which is what fish did previously). However, I'm running into cases where tcsetpgrp is causing an EPERM error, which it isn't documented to do except if the session id for the calling process differs from that of the target process group (which is never the case in fish since they are all part of the same session), which should cause a _different_ error (SIGTTOU to be sent to all members of the calling process' group). In all cases, this is easily remedied by checking if the process group in question is already in control of the terimnal. There's still the off-chance that in the time between we check that and the time that the command completes that situation may have changed, but the parent process is supposed to ignore the result of this call if it errors out. [0]: https://en.wikipedia.org/wiki/Process_group [1]: https://www.gnu.org/software/libc/manual/html_node/Launching-Jobs.html
…tions In the last commit, we introduced an indiscriminate if !EXTERNAL check that unblocks a previously SIGSTOP'd command (if any) to allow the main loop in exec_job to read from it without deadlocking (since builtins and functions read directly from input as an optimization, sometimes). Now only unblocking where a fork will not happen to ensure that if a builtin ends up forking, that fork'd process is guaranteed to be able to join the previous process' process group and access its output pipes.
There is no more race condition between parent and child with regards to setting the process groups. Each child sets it for themselves and then blocks indefinitely until the parent does what it needs to for them (having waited for them to set their process groups). They are not SIGCONT'd until the next process in the chain (if any) starts so that that process can join their process group and open the pipes.
The process_t pointer sent to setup_child_process can actually be 0 without it being failure, as that is what fish sends when `exec` is run (in the case of INTERNAL_EXEC). This was causing exec to fail.
setup_child_process blocks in the case of IO_FILE, meaning it can't be called before child processes SIGSTOP.
If tcgetpgrp for STDIN was already a match, the `cont` branch was skipped. This wais making the history.expect test fail.
The return value on OS X is more along the lines of the documented waitpid behavior; EINVAL is returned if the group no longer exists.
No longer using a lambda for pgroupTerminated, using a boolean flag instead. The new code structure should be much more self-documenting.
Do you still want us to review that PR? Does it need to be merged before this PR is merged? Note that I haven't yet looked at PR#4246 or this one because I'm dealing with the fix for issue #3822 which is proving to be more difficult than I expected. Much like you are finding with your changes to the job control code. I love your observations like this one:
That is a good example of why I haven't tried to fix these problems. My thinking has been that refactoring the code to eliminate such issues should be done first. Since doing so may, as a side-effect, fix some problems in this class of issues. But I'm thrilled that you are brave enough to jump in and try to make sense of, and improve, the existing code prior to such refactoring. |
If you don't have a copy you should buy "Advanced Programming in the UNIX Environment" (aka "APUE") by W. Richard Stevens and Stephen A. Rago ASAP. It's a must have book for these types of issues. Now that I've got my command substitution change done and out for review I can start reviewing this PR. The first handful of commits I've reviewed look good. You might want to take a quick look at my PR #3691 and issue #2007. That's where I eliminated a bunch of expensive |
Much appreciated. It's the sort of thing we demand at $dayjob since changes that are too large, cover too much ground, or are not self contained make doing reviews much more painful than they need to be. I like what I've seen so far in this series of changes. |
|
@krader1961 I just ordered a copy of APUE. Thanks for the suggestion! |
|
I did a superficial review of this series of changes. The main problems I saw ranged from trivial to mildly worrisome:
Applying this PR to the current |
|
@krader1961 thanks for reviewing. I agree about the lambda issue, I wanted to actually move the posix_spawn and the execute_fork out into a separate function that decides on its own which to use, which would simplify things further. The If you have any specific concerns or worries about a potential deadlock or bad synchronization with the signalling code, please let me know, as it is my intention for this fork/PR to fully address the underlying race conditions and to be fully correct both in theory and certainly in practice (not just a bandaid). |
No specific concerns. Just a vague uneasiness due to 30+ years of debugging problems due to signal handling. |
|
Also, now that I've had a good nights rest I see the conflicts are trivial to fix. They're a consequence of my signal management cleanup commit fb08fe5 which removed all the unnecessary signal_block()/signal_unblock() calls and removing the |
|
I had to revert my signal_block cleanup change to cleanly apply this PR. Trying to fix the conflicts one at a time by hand was proving too difficult. But I finally got this and my signal_block cleanup reapplied and everything seems to work. Thanks for all the hard work, @mqudsi. |
|
Can we take this for 2.7.0? I understand the desire to take "low risk" changes only but merging to master will get these patches to a much wider audience much sooner. |
|
I'd prefer we didn't, @zanchey. While @mqudsi and I think it is correct and doesn't contain any obvious bugs it is clearly a significant change to the implementation. With the final 2.x release less than a month away I think it's better to stick with the bugs we know than potentially introduce new bugs. Too, after that release we'll want to merge major back into master which will get this change quite a lot more exposure. |
|
fwiw, I'd be uncomfortable having this added to the last 2.x release. It sucks that 2.x is broken for WSL users (apart from being broken in theory), but I'd still rather not. |
While PR #4246 fixes the initial issue I had with #4235, I ran into a number of issues with the code while working on this and I don't feel that the PR would be anything more than a bandaid. I have been working on a new branch that fixes the overall parent-child and child-child synchronization in
exec_job; it's pushed here: https://github.com/mqudsi/fish-shell/tree/fork_exec_changesI'm still working on it but I finally have it passing all the tests. I'm using it as my daily shell on OS X, WSL, and FreeBSD; so I'm patching things as I uncover them but I'm confident enough to at least share the current branch here for feedback.
Unfortunately I ran into a lot of problems trying to switch the code over to something more elegant because there are a number of (unclear) cases where the main
exec_jobloop can block as it tries to read from a preceding pipe or file (as an optimization, using the builtins instead of forking a new process). The previous code seems to duplicate a lot of functionality between child and parent in hopes that one or the other executes first (pretty much like all other job control code out there), but the problem is that it's not able to tell when something is an error and when it's OK to fail, leading to problems like the WSL issue and a few others I've seen in my searches.The new code defines an explicit order for the system calls used to set up a new child process, and strictly enforces it. No kernel code for setting up process groups is duplicated between child and parent, each has a specific responsibility to set up something to arrive at the final state. I've also eliminated all the race conditions I could find in the code; there were a lot of cases where a preceding process could have terminated before the next process in the job chain started up and tried to join the existing process group and read from the previous process' pipes. It was all scenarios that almost never happened, but there was nothing as far as I could tell to actually make sure it didn't/handle it if it did.
I think I've finally tracked down all that blocking code and have the flow working ok now, but I'm going to keep stress-testing it to see if anything comes up.
Changing the
exec_jobcode involved a lot of research (both reading and testing) on different operating systems to get the actual behavior oftcsetpgrpandwaitpidironed out in all the different cases; I've done my best to clarify everything with copious amounts of comments so that it's all clear for future maintenance or if anything along the lines of "why is this being done here" comes up. I tried to make my changes both as localized and as clear as possible in hopes of making potentially merging this in at some point easier.I still want to break up
exec_jobfurther, I don't like the two giant switch cases and there's a ton of overlapping behavior between them; some of it differs only slightly in ways that make it unclear whether or not the deviations are on purpose or simply a matter of omission (for example,exec_erroris only set if fork fails for external processes, but isn't for builtins - from what I can tell, it should be for both).Since we're requiring C++11, I've implemented a few things as lambdas and call them where needed to eliminated code duplication without convoluting the code further; hopefully that is OK. I want to do that for most of the code in
exec_jobso that the different cases can all be handled in one spot where possible; but I refrained from doing it until the overhaul of the actual synchronization was complete and working so that I have a good control to compare behavior against.I've also commented any occurrences of blocking code in the main
exec_jobloop to hopefully save anyone from pulling their hair out in the future while trying to pin down a hang in job control. It's not at all clear from the code itself which operations and function calls might block the main loop while they attempt IO from a file or another process.Anyway, like I said, this is still a work in progress but I wanted to get feedback and work on this in public rather than come in with a massive patch a month from now.
Thanks.