A NUL byte in the output stream got accidentally not handled as IGN char
in xterm console mode. The internal mbtowc conversion doesn't handle
embedded NUL values gracefully, it always stops converting at NUL bytes.
This broke the output of strings with embedded NUL bytes.
Fix this by always skipping IGN chars in the "normal char output loop"
and make sure not to move the cursor one position to the right, as in
legacy console mode.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
NSIG is a deprecated symbol only visible under MISC visibility.
_NSIG is used widely instead, and on most systems NSIG is
defined in terms of _NSIG.
Follow suit: Change NSIG to _NSIG throughout and change visiblity
of NSIG to be defined only in __MISC_VISIBLE case.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
- If two cygwin programs are executed simultaneousley with pipes
in cmd.exe, xterm compatible mode is accidentally disabled by
the process which ends first. After that, escape sequences are
not handled correctly in the other app. This is the problem 2
reported in https://cygwin.com/ml/cygwin/2020-02/msg00116.html.
This patch fixes the issue. This patch also fixes the problem 3.
For these issues, the timing of setting and unsetting xterm
compatible mode is changed. For read, xterm compatible mode is
enabled only within read() or select() functions. For write, it
is enabled every time write() is called, and restored on close().
- In push_to_pcon_screenbuffer(), open() and ioctl() are called.
Since push_to_pcon_screenbuffer() is called in read() and write(),
errno which is set in read() and write() code may be overwritten
in open() or ioctl() call. This patch prevent this situation.
- PTY has a bug reported in:
https://cygwin.com/ml/cygwin/2020-02/msg00067.html.
This is the result of state mismatch between real pseudo console
attaching state and state variable. This patch fixes the issue.
- PTY has a problem that the key input, which is typed during
windows native app is running, disappear when it returns to shell.
(Problem 3 in https://cygwin.com/ml/cygwin/2020-02/msg00007.html)
This is beacuse pty has two input pipes, one is for cygwin apps
and the other one is for native windows apps. The key input during
windows native program is running is sent to the second input pipe
while cygwin shell reads input from the first input pipe.
This patch realize transfering input data between these two pipes.
- Debug codes used in the early stage of pseudo console support are
removed. (Regarding ALWAYS_USE_PCON and USE_API_HOOK) Along with
this, the codes related to this change are organized.
- PTY code has a problem that tcsh is terminated if the following
command is executed.
true; chcp &
This seems to be caused by invalid pointer access which occurs
when the process exits during the kill() code is execuetd. This
patch avoids the issue by not using kill().
- With this patch, foreground color and background color are allowed
to be set simultaneously by 24 bit color escape sequence such as
ESC[38;2;0;0;255;48;2;128;128;0m in legacy console mode.
When fhandler_base::fstat_helper is called, the handle h returned by
get_stat_handle() should be pc.handle() and should be safe to use for
getting the file information. Previously, the call to
get_file_attribute() for FIFOs set the first argument to NULL instead
of h, thereby forcing the file to be opened for fetching the security
descriptor in get_file_sd().
Make fhandler_socket_local::dup and fhandler_socket_local::fcntl (a
new method) call fhandler_base::dup and fhandler_base::fcntl if O_PATH
is set.
We're viewing the socket as a disk file here, but there's no need to
implement the actions of fhandler_disk_file::dup and
fhandler_disk_file::fcntl, which do nothing useful in this case beyond
what the fhandler_base methods do. (The extra actions are only useful
when I/O is going to be done on the file.)
If O_PATH is set, then the fhandler_socket_local object has a handle
that can be used for getting the statvfs information. Use it by
calling fhandler_base::fstatvfs_by_handle. Without this change,
fhandler_disk_file::fstatfvs would be called on a new fhandler_disk
object, which would then have to be opened.
If an AF_LOCAL socket is opened with O_PATH, all socket system calls
that take a file descriptor argument fail on the resulting descriptor.
Make sure that errno is set as on Linux for those calls that are
implemented on Linux. In almost all cases it is ENOTSOCK. There are
two exceptions:
- sockatatmark(3); errno is EBADF.
- bindresvport(3); errno is EAFNOSUPPORT if the second argument sin
(of type struct sockaddr_in *) is non-NULL and satisfies
sin->sin_family == AF_INET.
Finally, there are two BSD socket system calls implemented on Cygwin
but not Linux: getpeereid(3) and bindresvport_sa(3). Set errno to
ENOTSOCK for these for consistency with the majority of the other
calls.
If that flag is not set, or if an attempt is made to open a different
type of socket, the errno is now EOPNOTSUPP instead of ENXIO. This is
consistent with POSIX, starting with the 2016 edition. Earlier
editions were silent on this issue.
Opening is done in a (new) fhandler_socket_local::open method by
calling fhandler_base::open_fs.
Also add a corresponding fhandler_socket_local::close method.
This edits licenses held by Berkeley and NetBSD, both of which
have removed the advertising requirement from their licenses.
Signed-off-by: Keith Packard <keithp@keithp.com>
This option has been disabled long ago and nobody missed it.
Removing drops a bit of unneeded code
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
If O_PATH is set, then the fhandler_fifo object has a handle that can
be used for getting the statvfs information. Use it by calling
fhandler_base::fstatvfs_by_handle. Before this change,
fhandler_disk_file::fstatfvs was called on a new fhandler_disk_file
object, which would then have to be opened.
Define a new method fhandler_base::fstatvfs_by_handle, extracted from
fhandler_disk_file::fstatvfs, which gets the statvfs information when
a handle is available.
This will be used in future commits for special files that have been
opened with O_PATH.
Treat a special file opened with O_PATH the same as a regular file,
i.e., use its handle to get the stat information.
Before this change, fstat_fs opened the file a second time, with the
wrong flags and without closing the existing handle. A side effect
was to change the openflags of the file, possibly causing further
system calls to fail.
Currently this change only affects FIFOs, but it will affect
AF_LOCAL/AF_UNIX sockets too once they support O_PATH.
mknod32 actually creates a path_conv, just to call mknod_worker
with a win32 path. This doesn't only require to create path_conv
twice, it also breaks permissions on filesystems supporting ACLs.
Fix this by passing the path_conv created in the caller down to
symlink_worker. Also, while at it, simplify the handling of trailing
slashes and move it out of symlink_worker. Especially use the
new PC_SYM_NOFOLLOW_DIR flag to avoid fiddeling with creating
a new path copy without the trailing slash.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
Usually a trailing slash requires to follow an existing symlink,
even with PC_SYM_NOFOLLOW. The reason is that "foo/" is equivalent
to "foo/." so the symlink is in fact not the last path component,
"." is. This is default for almost all scenarios.
PC_SYM_NOFOLLOW_DIR now allows the caller to request not to
follow the symlink even if a trailing slash is given. This can
be used in callers to perform certain functions Linux-compatible.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
- After commit 6cc299f0e2, outputs of
cygwin programs which call both printf() and WriteConsole() are
frequently distorted. This patch fixes the issue.
- The cause of the problem reported in
https://www.cygwin.com/ml/cygwin/2020-01/msg00220.html is that the
chars input before dup() cannot be read from the new file descriptor.
This is because the readahead buffer (rabuf) in the console is newly
created by dup(), and does not inherit from the parent. This patch
fixes the issue.
If the O_PATH flag is set, fhandler_fifo::open now simply calls
fhandler_base::open_fs.
The previous attempt to handle O_PATH in commit aa55d22c, "Cygwin:
honor the O_PATH flag when opening a FIFO", fixed a hang but otherwise
didn't do anything useful.
If O_PATH is set in the flags argument of
fhandler_base::device_access_denied, return false. No
read/write/execute access should be required in this case.
Previously, the call to device_access_denied in open(2) would lead to
an attempt to open the file with read access even if the O_PATH flag
was set.
rdpru flag is cpuid xfn 80000008 ebx bit 4 added in linux 5.5;
see AMD64 Architecture Programmer's Manual Volume 3:
General-Purpose and System Instructions
https://www.amd.com/system/files/TechDocs/24594.pdf#page=329
and elsewhere in that document
- For programs which does not work properly with pseudo console,
disable_pcon in environment CYGWIN is introduced. If disable_pcon
is set, pseudo console support is disabled.
- For programs compiled with -mwindows option, reopening slave is
needed in push_to_pcon_screenbuffer(), however, it was not at
appropriate place. This causes the problem reported in
https://www.cygwin.com/ml/cygwin/2020-01/msg00161.html. This
patch fixes the issue.
- Though this rarely happens, sometimes the first printing of non-
cygwin process does not displayed correctly. To fix this issue,
the code for waiting for forwarding by master_fwd_thread is revised.
Following Linux, allow the pathname argument to be an empty string if
the AT_EMPTY_PATH flag is specified. In this case the dirfd argument
can refer to any type of file, not just a directory, and the call
operates on that file. In particular, dirfd can refer to a symlink
that was opened with O_PATH | O_NOFOLLOW.
Following Linux, allow the pathname argument to be an empty string,
provided the dirfd argument refers to a symlink opened with
O_PATH | O_NOFOLLOW. The readlinkat call then operates on that
symlink.
Commit 283cb372, "Cygwin: normalize_win32_path: improve error
checking", required a prefix '\\?\' or '\??\' in the source path to be
followed by 'UNC\' or 'X:\', where X is a drive letter. That was too
restrictive, since it disallowed the paths '\\?\X: and '\??\X:'. This
caused problems when a user tried to use the root of a drive as the
Cygwin installation root, as reported here:
https://cygwin.com/ml/cygwin/2020-01/msg00111.html
Modify the requirement so that '\??\X:' and '\\?\X:' are now allowed
as source paths, without a trailing backslash.
- In octave gui, sometimes state mismatch between real pty state
and state variable occurs. For example, this occurs when 'ls'
command is executed in octave gui. This patch fixes the issue.
- After commit e1a0775dc0, the problem
reported in https://www.cygwin.com/ml/cygwin/2020-01/msg00093.html
occurs. For Gnu scren and tmux, calling FreeConsole() on pty close
is necessary. However, if FreeConsole() is called, cygwin setup
with '-h' option does not work. Therefore, the commit
e1a0775dc0 delayed closing pty.
This is the cause of the problem above. Now, instead of delaying
pty close, FreeConsole() is not called if the process is non cygwin
processes such as cygwin setup.
- The console with 24bit color support has a problem that console
mode is changed if cygwin process is executed in cmd.exe which
started in cygwin shell. For example, cursor keys become not
working if bash -> cmd -> true are executed in this order.
This patch fixes the issue.
- In Win10 1809, the cursor position sometimes goes out of screen
by clear command in console. This seems to be caused by escape
sequence CSI3J (ESC[3J). This happens only for 1809. This patch
is a workaround for the issue.
- Special function keys such as arrow keys or function keys do not
work in ConEmu with cygwin-connector after commit
6a06c6bc8f. This patch fixes the
issue.
- PTY code which support pseudo console has a problem that causes
handle leaks. Four of these are bug in pty code, and the other
one seems to be a bug of Windows10. ClosePseudoConsole() fails
to close one internal handle. This patch fixes the issue.
- If two PTYs are opened in the same process and the first one
is closed, the helper process for the first PTY remains running.
This patch fixes the issue.
- The slowing down issue of X11 forwarding using ssh -Y, reported
in https://www.cygwin.com/ml/cygwin/2019-12/msg00295.html,
is due to the change of select() code for pty in the commit
915fcd0ae8. cygthread::detach()
takes at most about 10msec because Sleep() is used in the thread.
For this issue, this patch uses cygwait() instead of Sleep() and
introduces an event to abort the wait. For not only pty, but pipe
and fifo also have the same problem potentially, so this patch
applies same strategy to them as well.
Though our implementation of cpu sets doesn't need it, software from
Linux environments expects this definition to be present. It's
documented on the Linux CPU_SET(3) man page but was left out due to
oversight.
Addresses https://cygwin.com/ml/cygwin/2019-12/msg00248.html
Add that flag to the pipe type argument when creating the Windows
named pipe. And add a definition of that flag to ntdll.h (copied from
/usr/include/w32api/ddk/ntifs.h).
- Even with commit fe512b2b12, pty
still has a problem in ESC[?3h and ESC[?3l handling if invalid
sequence such as ESC[?$ is sent. This patch fixes the issue.
Both functions were introduce with Windows 7 only, so we need to
autoload them for the sake of Vista/2008.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
On certain error conditions there is a code snippet that checks
whether the last component of the path has a trailing dot or space or
a leading space. Skip this check if the last component is empty,
i.e., if the path ends with a backslash. This avoids an assertion
failure if the trailing backslash is the only backslash in the path,
as is the case for a DOS drive 'X:\'.
Addresses: https://cygwin.com/ml/cygwin/2019-12/msg00016.html
- Pseudo console clears console screen buffer if ESC[?3h or ESC[?3l
is sent. However, xterm/vt100 does not clear screen. This cause
mismatch between real screen and console screen buffer. Therefore,
this patch triggers redraw screen in that situation so that the
synchronization is done on the next execution of native app.
This solves the problem reported in:
https://www.cygwin.com/ml/cygwin-patches/2019-q4/msg00116.html
- Previously, pty cleared screen at startup for synchronization
between the real screen and console screen buffer for pseudo
console. With this patch, instead of clearing screen, the screen
is redrawn when the first native program is executed after pty
is created. In other words, synchronization is deferred until
the native app is executed. Moreover, this realizes excluding
$TERM dependent code.
fhandler_console::create_invisible_console_workaround() does not use the
lpApplicationName parameter and neglects to quote its command name on
lpCommandLine in the call to CreateProcessW.
Given CreateProcessW's brain-dead method to evaluate the application
path given on the command line, this opens up a security problem if
Cygwin is installed into a path with spaces in it.
Fix this by using the lpApplicationName parameter and quoting of the
application path in the lpCommandLine parameter (used as argv[0] in
the called console helper.
For extended paranoia, make the argument string array big enough to
fit full 64 bit pointer values into it. Handles usually only use
the lower 32 bit, but better safe than sorry.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
FH_CONS_MAX should refelect the fact that we allow 128 consoles, even if
it's unused.
Suggested-by: Achim Gratz <Stromeko@nexgo.de>
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
Commit 5a0f2c00aa "Cygwin: fork/exec: fix child process permissions"
removed the PROCESS_DUP_HANDLE handle permission of the parent process
handle in the child to avoid a security problem.
It turned out that this broke the following scenario: If a process forks
and then the parent execs, the child loses the ability to register the
parent's death. To wit, after the parent died the child process does
not set its own PPID to 1 anymore.
The current exec mechanism copies required handle values (handles to
keep contact to the child processes) into the child_info for the
about-to-be-exec'ed process. The exec'ed process is supposed to
duplicate these handles. This fails, given that we don't allow the
exec'ed process PROCESS_DUP_HANDLE access to the exec'ing process since
commit 5a0f2c00aa.
The fix is to avoid the DuplicateHandle calls in the exec'ed process.
This patch sets the affected handles to "inheritable" in the exec'ing
process at exec time. The exec'ed process just copies the handle values
and resets handle inheritance to "non-inheritable". The exec'ing
process doesn't have to reset handle inheritance, it exits after setting
up the exec'ed process anyway.
Testcase: $ ssh-agent /bin/sleep 3
ssh-agent forks and the parent exec's sleep. After sleep exits, `ps'
should show ssh-agent to have PPID 1, and eventually ssh-agent exits.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
Call find_exec with the FE_NNF flag to enforce a NULL return when the
executable isn't found in $PATH. Convert NULL to "". This aligns
spawnvp and spawnvpe with execvp and execvpe.
If the directory name has the form 'x:' followed by one or more
slashes or backslashes, and if there's at least one backslash, assume
that the user is referring to 'x:\', the root directory of drive x,
and don't strip the backslash.
Previously all trailing slashes and backslashes were stripped, and the
name was treated as a relative file name containing a literal colon.
Addresses https://cygwin.com/ml/cygwin/2019-08/msg00334.html.
Add feature test print macro that makes feature, bit, and flag text
comparison and checking easier. Handle as common former Intel only
feature flags also supported on AMD. Change order and some flag names
to agree with current Linux.
If the source path starts with the Win32 long path prefix '\\?\' or
the NT object directory prefix '\??\', require the prefix to be
followed by 'UNC\' or '<drive letter>:\'. Otherwise return EINVAL.
This fixes the assertion failure in symlink_info::check that was
reported here:
https://cygwin.com/ml/cygwin/2019-09/msg00228.html
That assertion failure was caused by normalize_win32_path returning a
path with no backslashes when the source path was '\\?\DRIVE'.
If the last component of the directory name is a symlink followed by a
slash, rmdir now fails, following Linux but not POSIX, even if the
symlink resolves to an existing empty directory.
mkdir was similarly changed in 2009 in commit
52dba6a5c4. Modify a comment to clarify
the purpose of that commit.
Addresses https://cygwin.com/ml/cygwin/2019-09/msg00221.html.
Prior to commit b0717aae, path_conv::check had the following code:
if (strncmp (path, "\\\\.\\", 4))
{
/* Windows ignores trailing dots and spaces in the last path
component, and ignores exactly one trailing dot in inner
path components. */
char *tail = NULL;
[...]
if (!tail || tail == path)
/* nothing */;
else if (tail[-1] != '\\')
{
*tail = '\0';
[...]
}
Commit b0717aae0 intended to disable this code, but it inadvertently
disabled only part of it. In particular, the declaration of the local
tail variable was in the disabled code, but the following remained:
if (!tail || tail == path)
/* nothing */;
else if (tail[-1] != '\\')
{
*tail = '\0';
[...]
}
[A later commit removed the disabled code.]
The tail variable here points into a string different from path,
causing that string to be truncated under some circumstances. See
https://cygwin.com/ml/cygwin/2019-09/msg00001.html
for more details.
This commit fixes the problem by removing the leftover code
that was intended to be removed in b0717aae.
- The autoload feature is used rather than GetModuleHandle(),
GetProcAddress() for CreatePseudoConsole(), ResizePseudoConsole()
and ClosePseudoConsole().
- Since calling system __loadlocale() caused execution error,
PTY used its own NLS function. The cause of the error has been
found, the corresponding code has been rewritten using system
function.
The CPU_SET macros defined in Cygwin's include/sys/cpuset.h must not
be visible in an application's namespace unless _GNU_SOURCE has been
#defined. Internally this means wrapping them in #if __GNU_VISIBLE.
- In non-canonical mode, cygwin console returned only one character
even if several keys are typed before read() called. This patch
fixes this behaviour.
- Previously, input and output pipes were switched together between
the traditional pty and the pseudo console. However, for example,
if stdin is redirected to another device, it is better to leave
input pipe traditional pty side even for non-cygwin program. This
patch realizes such behaviour.
- If screen alternated while pseudo console switching, it sometimes
failed. This might happen when the output of the non-cygwin program
is piped to less. This patch fixes this issue.
- When the I/O pipe is switched to the pseudo console side, the
behaviour of Ctrl-C was unstable. This rarely happens, however,
for example, shell sometimes crashes by Ctrl-C in that situation.
Furthermore, Ctrl-C was ignored if output of non-cygwin program
is redirected to pipe. This patch fixes these issues.
- Forcibly attach to pseudo console in advance so that the error
messages by system_printf() are displayed to screen reliably.
This is needed when stdout is redirected to another pty. In this
case, process has two ptys opened. However, process can attach
to only one console. So it is necessary to change console attached.
- PTY with pseudo console support sitll has problem which potentially
cause state mismatch between state variable and real console state.
This patch fixes this issue.
- select() did not work correctly when both read and except are
polled simultaneously for the same fd and the r/w pipe is switched
to pseudo console side. This patch fixes this isseu.
- Pseudo console support introduced by commit
169d65a577 shows garbage ^[[H^[[J in
some of emacs screens. These screens do not handle ANSI escape
sequences. Therefore, clear screen is disabled on these screens.
- Pseudo console support introduced by commit
169d65a577 sometimes cause random
crash or freeze by pressing ^C while cygwin and non-cygwin
processes are executed simultaneously in the same pty. This
patch is a workaround for this issue.
- API hook used for pseudo console support causes slow down.
This patch limits API hook to only program which is linked
with the corresponding APIs. Normal cygwin program is not
linked with such APIs (such as WriteFile, etc...) directly,
therefore, no slow down occurs. However, console access by
cygwin.dll itself cannot switch the r/w pipe to pseudo console
side. Therefore, the code to switch it forcely to pseudo
console side is added to smallprint.cc and strace.cc.
- Pseudo console support introduced by commit
169d65a577 has some bugs which
cause mismatch between state variables and real pseudo console
state regarding console attaching and r/w pipe switching. This
patch fixes this issue by redesigning the state management.
- PTY uses Win32 API hook for pseudo console suppot. The function
hook_api() is used for this purpose and defined in fhandler_tty.cc
previously. This patch moves it into hookapi.cc.
- Support pseudo console in PTY. Pseudo console is a new feature
in Windows 10 1809, which provides console APIs on virtual
terminal. With this patch, native console applications can work
in PTYs such as mintty, ssh, gnu screen or tmux.
Rather than waiting for signalfd_select_wait in a thread, which is racy,
create a global event "my_pendingsigs_evt" which is set and reset by
wait_sig depending only on the fact if blocked signals are pending or not.
This in turn allows to WFMO on this event in select as soon as signalfds
are present in the read descriptor set. Select's peek and verify
will then check if one of the present signalfds is affected.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
Borrow a trick from strace to lessen occurrences of "??? => ???" in ldd
output. Specifically, if the module name isn't found in the usual place
in the mapped image, use the file handle we have to look up the name.
On sigwaitinfo or reading from a signalfd, signal processing sets up
signal handling via sigdelayed even if the handler address is NULL.
This doesn't have any impact on sigwaitinfo scenarios (or at least, I
wasn't able to come up with a reproducer) but it breaks signalfd
scenarios, where eventually a call to call_signal_handler from
sigdelayed will try to call the NULL function.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
- If screen is alternated on console, cursor position is not restored
correctly in the case of xterm compatible mode is enabled. For example,
the shell prompt is shown at incorrect position after using vim.
This patch fixes this problem.
- The horizontal tab positions are broken after resizing console window.
This seems to be a bug of xterm compatible mode of windows console.
This workaround fixes this problem.
The default implementation of the fenv.h methods return
-EOPNOTSUP. Some of these have implementations appropriate
for soft-float.
The intention of the new fenv.h is that it be portable
and that architectures provide their own implementation
of sys/fenv.h.
This avoids collisions of shmat maps with Windows own datastructures
when allocating top-down.
This patch moves the mmap_allocator class definition into its
own files and just uses it from mmap and shmat.
Adding default winvar 'PATH=C:\cygwin64\binZ' to an environment that is
already allocated for 'SYSTEMROOT=ZWINDIR=Z', we need to count that
trailing (Z)ero as well. Otherwise we trigger this assertion failure:
$ /bin/env -i SYSTEMROOT= WINDIR= /bin/env
assertion "(s - envblock) <= tl" failed: file "/home/corinna/src/cygwin/cygwin-3.0.7/cygwin-3.0.7-1.x86_64/src/newlib-cygwin/winsup/cygwin/environ.cc", line 1302, function: char** build_env(const char* const*, WCHAR*&, int&, bool, HANDLE)
Aborted (core dumped)
When the exec family of functions is called for a script-like
file, the av::setup function handles the exec[vl]p case as
well. The execve case for files not starting with a she-bang
is handled first by returning ENOEXEC. Only after that, the
file's executability is checked.
This leads to the problem that ENOEXEC is returned for non-executable
files as well. A calling shell interprets this as a file it should try
to run as script. This is not desired for non-executable files.
Fix this problem by checking the file for executability first. Only
after that, follow the other potential code paths.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
This patch supplies an implementation of the CPU_SET(3) processor
affinity macros as documented on the relevant Linux man page.
There is a mostly superset implementation of cpusets under newlib's
libc/sys/RTEMS/include/sys that has Linux and FreeBSD compatibility
and is built on top of FreeBSD bitsets. This Cygwin implementation
and the RTEMS one could be combined if desired at some future point.
Do not attach to the child before it was successfully initialized, or we
would need more sophisticated cleanup on child initialization failure,
like suppressing SIGCHILD delivery with multiple threads ("waitproc")
involved.
Improves "Cygwin: fork: Remember child not before success.",
commit f03ea8e1c5, which leads to fork
problems if cygserver is running:
https://cygwin.com/ml/cygwin-patches/2019-q2/msg00155.html
During fork, the child process requires the process table to be
initialized for fixup_shms_after_fork, while still allowing subsequent
dlls.load_after_fork to fail silently (for when the "forkable" hardlinks
are not created yet).
pinfo::remember not performing reattach anymore requires explicit
pinfo::reattach now where appropriate.
Prepares to improve "Cygwin: fork: Remember child not before success."
commit f03ea8e1c5, which leads to fork
problems if cygserver is running:
https://cygwin.com/ml/cygwin-patches/2019-q2/msg00155.html
Introducing an independent Cygwin PID introduced a regression:
The expectation is that the myself pinfo pointer always points to a
specific address right in front of the loaded Cygwin DLL.
However, the independent Cygwin PID changes broke this. To create
myself at the right address requires to call init with h0 set to
INVALID_HANDLE_VALUE or an existing address:
void
pinfo::init (pid_t n, DWORD flag, HANDLE h0)
{
[...]
if (!h0 || myself.h)
[...]
else
{
shloc = SH_MYSELF;
if (h0 == INVALID_HANDLE_VALUE) <-- !!!
h0 = NULL;
}
The aforementioned commits changed that so h0 was always NULL, this way
creating myself at an arbitrary address.
This patch makes sure to set the handle to INVALID_HANDLE_VALUE again
when creating a new process, so init knows that myself has to be created
in the right spot. While at it, fix a potential uninitialized handle
value in child_info_spawn::handle_spawn.
Fixes: b5e1003722 ("Cygwin: processes: use dedicated Cygwin PID rather than Windows PID")
Fixes: 88605243a1 ("Cygwin: fix child getting another pid after spawnve")
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
_pinfo::set_ctty sets myself's pgid to the ctty pgid if the process has
been started from a non-Cygwin process. This isn't the right thing to
do when started from GDB. GDB starts the application via standard
Windows means, not via Cygwin fork/exec, so it's treated as being
a non-Cygwin parent.
But we want the app running in it's own process group. So skip this
step when running under a debugger
Signed-off-by: Corinna Vinschen <corinna-cygwin@cygwin.com>
Return -1 with EINVAL if pgid < 0.
Previously tcsetpgrp() would blindly go ahead and set the pgid of the
controlling terminal to a negative value, causing later calls to
various functions to fail.
For example, gdb has code like the following:
tcsetpgrp (0, getpgid (inf->pid));
If getpgid (inf->pid) fails (returns -1), then this code would set the
pgid of fd 0 to -1, so that some later calls to getpgid() would also
return -1. This caused the problem reported here:
https://cygwin.com/ml/cygwin/2019-07/msg00166.html.
So far negative values were denoting files, positive values
denoting directories. We should prefer a less error prone
method. Redefine virtual_ftype_t to contain only positive
values and replace checks for negativ or positive values with
inline functions virt_ftype_isfile() and virt_ftype_isdir().
Drop outdcated comments referring to numerical virtual_ftype_t
values.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
commit 2607639992 "Improve error handling in /proc/[pid]/
virtual files." changed the return value of the /proc/PID
formatting functions to return -1 instead of 0 in the error
case to allow a filesize of 0.
The patch neglected to change this behaviour for /proc/PID/fd
content. This patch fixes that.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
Change path_conv::is_lnk_special() so that it returns false on socket
files.
is_lnk_special() is called by rename2() in order to deal with special
files (FIFOs and symlinks, for example) whose Win32 names usually have
a ".lnk" suffix. Socket files do not fall into this category, and
this change prevents ".lnk" from being appended erroneously when such
files are renamed.
Remove a now redundant !pc.issocket() from fhandler_disk_file::link().
It is used only once, and the name is supposed to suggest "device that
is not based on the filesystem". This intended meaning is clearer if
we just replace is_auto_device() by its definition at the place where
it's used.
The sigpending mechanism failed to check if the pending signal was a
process-wide signal, or a signal for the curent thread. Fix that by
adding a matching conditional to wait_sig's __SIGPENDING code.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
So far sig_send's return type is int. The problem with this is
that sig_send returns a sigset_t on __SIGPENDING, and sigset_t
is defined as long type. So the function only returns the lower
32 bit of sigset_t, which is fine on 32 bit, but casts away the
pending RT signals on 64 bit.
Fix this by changing the return type of sig_send to sigset_t, so
as not to narrow down the sigset when returning from handling
__SIGPENDING. Make sure to cast correctly in all invocations
of sig_send.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
Have sched_getaffinity() interface like glibc's, and provide an
undocumented internal interface __sched_getaffinity_sys() like the Linux
kernel's sched_getaffinity() for benefit of taskset(1).
Add a function timerfd_tracker::enter_critical_section_cancelable,
which is like enter_critical_section but honors a cancel event. Call
this when a timer expires while the timerfd thread is in its inner
loop. This avoids a deadlock if timerfd_tracker::dtor has entered its
critical section and is trying to cancel the thread. See
https://cygwin.com/ml/cygwin/2019-06/msg00096.html.
This patch set implements the Linux syscalls sched_getaffinity,
sched_setaffinity, pthread_getaffinity_np, and pthread_setaffinity_np.
Linux has a straightforward view of the cpu sets used in affinity masks.
They are simply long (1024-bit) bit masks. This code emulates that view
while internally dealing with Windows' distribution of available CPUs among
processor groups.
Make it a manual reset event. It's only used once to allow a reader
to open, and there's no reason to ever reset it. Defensively set it
when a client connection is recorded, even though it should be set by
the writer that connected.
Call NtReadFile directly instead of calling fhandler_base::raw_read.
In addition to being simpler, this gives us access to the return value
from NtReadFile.
Add a method fifo_client_handler::pipe_state that queries Windows for
the state of a pipe instance. Use this to help terminate the
listen_client thread cleanly.
If the last client handler is useless, delete it instead of declaring
it invalid.
fhandler_fifo::close could be called from a signal handler or another
thread at a time when another function is holding the fifo_client
lock. This could prevent the listen_client thread from acting on the
thread termination event. Avoid a deadlock by calling
fifo_client_unlock at the beginning of fhandler_fifo::close.
libX11 provides <X11/Xlocale.h>. The build of libX11 itself adds
include/X11 to the compiler's include path. This results in a name
collision with /usr/include/xlocale.h on case-insensitive filesystems.
Commit 90e35b1eb3 renamed sys/_locale.h to xlocale.h in March 2017 under
the assumption that we should provide the locale_t type in the same file
as on Linux, FreeBSD, and Darwin.
A few weeks later (June 2017), glibc removed the xlocale.h file in favor
of bits/types/locale_t.h, which shouldn't be included directly anyway.
For reference and the reasoning, see
https://sourceware.org/git/?p=glibc.git;a=commit;h=f0be25b6336d
Given the above, revert 90e35b1eb3 and
fix additional usage of xlocale.h.
32 bit Cygwin performs a POSIX-compatible mapping after EOF which
is not supported in this form on Windows. The 64 bit Windows
kernel never supported the AT_ROUND_TO_PAGE mapping flag, so we
couldn't page-aligned map the space right after the file's EOF.
So mapping beyond EOF was disabled in 64 bit Windows and WOW64.
However, if mmap works, a matching munmap should work as well,
*and* it should not accidentally unmap unrelated memory.
Therefore we enable mapping beyond EOF on 64 bit as well. Since
that mapping is always 64K aligned, the are between the last file
page and the next 64K allocation boundary will be unallocated.
There's no way around that.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
When using NtCreateFile when creating a directory that already exists,
it will correctly return 'STATUS_OBJECT_NAME_COLLISION'.
However using this function to create a directory (and all its parents)
a normal use would be to start with mkdir(‘/cygdrive/c’) which translates
to ‘C:\’ for which it'll instead return ‘STATUS_ACCESS_DENIED’.
An increasing number of tools are being included in Windows which have the
same names as those included in Cygwin packages. Indicating which one is
first in PATH can be helpful in diagnosing behavioural discrepencies
between them.
Also, fix the alphabetization of ssh.
64 bit Windows started out with a 44 bit address space due to a
restriction of the AMD64 CPUs at the time. Starting with Windows
8.1, these CPUs are not supported anymore and Windows switched to
the full 48 bit address space supported by AMD64.
Cygwin didn't follow suit yet so mmaps are still restricted to
the lower 44 bit address space. Fix that by using a system-specific
upper address for mmap allocations, 44 bit up to Windows 8, 48 bit
starting with Windows 8.1.
While at it, move the heap by another 8 Gigs to leave some space
for a potential extension of DLL address space, and restrict the
mmap lower address so the heap can grow to 32 Gigs before colliding
with mmaps.
Do not remember the child before it was successfully initialized, or we
would need more sophisticated cleanup on child initialization failure,
like cleaning up the process table and suppressing SIGCHILD delivery
with multiple threads ("waitproc") involved. Compared to that, the
potential slowdown due to an extra yield () call should be negligible.
Pause the child process after performing fork fixups even if there were
no dynamically loaded dlls with extra data/bss transfers to wait for.
This allows the parent process to cancel the current fork call even if
the child process was successfully initialized already.
This is a preparation for when the parent does remember the child no
earlier than after successful child initialization.
Querying the ntlength and existence of the /var/run/cygfork directory in
the very first Cygwin process should not use nt_max_path_buf, as that
one is used by dll_list::alloc already.
NtQueryVirtualMemory for MemorySectionName may return some old path even
if the process was just started, for when some directory in between was
renamed - maybe because the NT file cache is hot for the old path still.
This was seen during gcc bootstrap, returning a MemorySectionName of
".../gcc/xgcc.exe" even if started as ".../prev-gcc/xgcc.exe", where the
directory rename from "gcc" to "prev-gcc" was done the moment before.
As we stat the module's real file right after loading now, there is no
point in using NtQueryVirtualMemory with MemorySectionName any more, and
we can use what GetModuleFileName returned instead.
-Add vendor identification
-Support in get_cpu_cache
Background:
Chengdu Haiguang IC Design Co., Ltd (Hygon) is a Joint Venture
between AMD and Haiguang Information Technology Co.,Ltd., aims at
providing high performance x86 processor for China server market.
Its first generation processor codename is Dhyana, which
originates from AMD technology and shares most of the
architecture with AMD's family 17h, but with different CPU Vendor
ID("HygonGenuine")/Family series number(Family 18h).
Related Hygon kernel patch can be found on:
http://lkml.kernel.org/r/5ce86123a7b9dad925ac583d88d2f921040e859b.1538583282.git.puwen@hygon.cn
Signed-off-by: Jinke Fan <fanjinke@hygon.cn>
There's no longer a need to consider the connect_evt after fork/exec.
After stopping the listen_client thread, all client handlers should be
in the fc_connected or fc_invalid states, so their connect_evt members
won't be used again.
Also remove code in fhandler_fifo::dup that just repeats things
already done in stop_listen_client.
Add a method fhandler_fifo::check_listen_client_thread that checks
whether the thread is running. Use it in raw_read instead of just
testing the handle listen_client_thr.
On exit from the listen_client thread, make sure there's no pending
FSCTL_PIPE_LISTEN request. Otherwise we might get a client connection
after restarting the thread, and we won't have a handle for
communicating with that client.
Remove the retry loop in the case of STATUS_PIPE_LISTENING; that case
shouldn't occur.
Remove the now-unused fc_connecting value from
fifo_client_connect_state.
It's now up to the caller to pass a handle to open_pipe and, if
desired, to call set_handle on return.
This will be useful for a future commit, in which we will open a
client connection without setting an io_handle.
When opening a duplexer, open a client connection to the first client
handler. Previously we gave the duplexer a bogus write handle, which
was just a duplicate of the first client handler's handle. This meant
that we had a pipe server with no clients connected, and all I/O
attempts failed with STATUS_PIPE_LISTENING.
Extend the last fcntl change to duplexers.
Remove a now unused fifo_client_handler constructor, as well as the
long unusued method fifo_client_handler::connect.
Don't create the pipe in duplex mode; the server handle will only be
used for reading.
NtQueryVirtualMemory for MemorySectionName does not reliable return the
changed dll file name when another process does move the file around,
and we may end up creating forkable hardlinks to wrong dll files.
So query the file id when loading the dll rather than before fork.
Make stat_real_file_once a method of struct dll, to be more flexible on
where to use. Also, debug print memory section name queried for a dll.
This is a preparation to query the file id when loading the dll.
The blocking mode of the Windows pipe underlying a writer is set to
match that of the writer itself when the latter is opened. Define
fhandler_fifo::fcntl to keep the pipe and the writer in sync if the
blocking mode is changed via fcntl.
* Change default fallback for failed winsock error -> POSIX error
mappings to EACCES, which is a valid errno for more socket-related
syscalls.
* Added a few previously missing entries to the wsock_errmap table
that have obvious POSIX errno.h analogues.
Add methods need_fixup_before, init_fixup_before, and
fixup_before_fork_exec to accomplish this. Stopping the thread makes
sure that the client handler lists of the parent and child remain in
sync while the forking/execing is in progress.
Don't use the same i/o handle for the first client handler as is used
for the fhandler itself; this can lead to a later attempt to close the
same handle twice. Instead use a duplicate.
* Pre-release version still reporting kernel version 6.4.
* Windows 10 1511 is out of support since 2017-10-10.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
Define fhandler:fifo::fixup_after_exec, which sets listen_client_thr
and lct_termination_evt to NULL. This forces the listen_client thread
to restart on the first attempt to read after an exec. Previously the
exec'd process could hang in fhandler_fifo::raw_read.
Remove fifo_client_handler::connect and move its code into
listen_client_thread. That way we can check the return status when a
client handler's connect_evt is signaled. Previously we incorrectly
assumed there was a successful connection.
Also simplify listen_client_thread in the following ways:
- Replace fhandler_fifo::disconnect_and_reconnect by a new
delete_client_handler method. Now we just delete invalid client
handlers rather than trying to re-use them.
- Try to maintain a client handler list that consists of connected
client handlers and exactly one that is listening for a connection.
This allows us to call WaitForMultipleObjects with only two wait
objects.
- Remove 'dummy_evt' from the fifo_client_handler struct; it is no
longer needed.
- On exit from listen_client_thread, delete the "extra" (listening)
client handler. Otherwise there could be a connection that doesn't
get recorded in the client handler list. This could happen when a
file descriptor is being duplicated.
Don't set the write end of the pipe to non-blocking mode if the FIFO
is opened in blocking mode.
In fhandler_fifo::raw_write in blocking mode, wait for the write to
complete rather than returning -1 with EAGAIN.
If the amount to write is large, write in smaller chunks (of size
determined by a new data member max_atomic_write), as in
fhandler_base_overlapped.
For convenience, add two new NTSTATUS codes, STATUS_THREAD_SIGNALED
and STATUS_THREAD_CANCELED, to ntdll.h.
After copyto is called, make the new fhandler's pipe_name point to the
new fhandler's pipe_name_buf, which is a *copy* of the old fhandler's
pipe_name_buf. Previously, get_pipe_name would return the wrong
result after a clone/dup, causing create_pipe_instance and open_pipe
to fail.
Also, stop the listen_client thread when cloning. Otherwise the
thread can keep accepting connections that the cloned fhandler won't
know about.
Do this via a new method fhandler_fifo::stop_listen_client, extracted
from fhandler_fifo::close.
Make read_ready a manual reset event. It should always be set shortly
after startup of the listen_client thread and remain set until the
thread terminates. (We don't want writers to connect without being
recorded in the client handler list.)
Remove the unnecessary code that checks for read_ready when a reader
is opening.
Add data members 'reader', 'writer', and 'duplexer' to the
fhandler_fifo class. Set them in fhandler_fifo::open. ('duplexer'
replaces the previous '_duplexer'.)
This will be useful in later commits.
The word "client" suggests something that holds a handle to the client
side of the pipe (in Windows terminology). But our
fifo_client_handlers hold a handle the server side of the pipe, and
they *connect* to clients.
Rather than newest last write time of all dlls loaded, use the forking
process' windows pid and windows thread id as directory name to create
the forkable hardlinks into. While this may create hardlinks more
often, it does avoid conflicts between dlls not having the newest last
write time.
* Changes error handling to allow /proc/[pid]/ virtual files to be
empty in some cases (in this case the file's formatter should return
-1 upon error, not 0).
* Better error handling of /proc/[pid]/stat for zombie processes:
previously trying to open this file on zombie processes resulted
in an EINVAL being returned by open(). Now the file can be read,
and fields that can no longer be read are just zeroed.
* Similarly for /proc/[pid]/statm for zombie processes.
* Similarly for /proc/[pid]/maps for zombie processes (in this case the
file can be read but is zero-length, which is consistent with observed
behavior on Linux.
- After 24 bit color support patch, arrow keys and function keys
do not work properly in native console applications if they
are started in cygwin console. This patch fixes this issue.
In case SA_SIGINFO flag is given, the signal handler may change
the context and the application is supposed to pick up from the
changed context. So far we don't do that, so the context given
to the signal handler is basically read-only, unless the signal
handler calls setcontext or swapcontext.
For a start, restore the thread's signal mask from the uc_sigmask
value of the context given to the signal handler.
If that's feasible for Cygwin, we restore the entire context from
the context changed by the signal handler in a followup patch.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
commit d1be0a59d4,
"Cygwin: winpids: Fix getting process multiple times"
fixed duplicate processes in ps -W output, but it fixed
the symptom, not the cause. It also didn't fix the problem
that the `ps' process itself may show up twice in its own
output.
This patch fixes it. The spawn worker only deleted the
"winpid.PID" symlink of the current process if the child is
a non-Cygwin process, under the assumption that the exec'ing
process exits anyway. However, the Window in which both
winpid.PID symlinks point to the same cygpid.PID area is just
too long. The spawn worker now also deletes its own winpid.PID
symlink if the exec'ed process is a Cygwin process.
Additionally the fix from d1be0a59d4
is now performed on the calling process, too.
Signed-off-by: Corinna Vinschen <corinna@vinschen.de>
- Add 24 bit color support using xterm compatibility mode in
Windows 10 1703 or later.
- Add fake 24 bit color support for legacy console, which uses
the nearest color from 16 system colors.
In dll_crt0_0, both threadinterface->Init and sigproc_init allocate
windows object handles using unpredictable memory regions, which may
collide with dynamically loaded dlls when they were relocated.
Make fhandler_base::clear_readahead virtual, and implement
fhandler_fifo::clear_readahead. This is called by
dtable::fixup_after_exec; it clears the readahead in each client.
Starting w/ the intro of S4U, seteuid32() calls lsaprivkeyauth(), then
s4uauth(). s4uauth calls LsaRegisterLogonProcess().
LsaRegisterLogonProcess fails w/ STATUS_PORT_CONNECTION_REFUSED, if the
proper privileges are not held.
Because of RtlNtStatusToDosError(), this status would be mapped to
ERROR_ACCESS_DENIED, which in turn would map to EACCES. Therefore it is
useless to add this status to errmap[] (errno.cc), as s4auauth() should
return EPERM as errno here (i.e. if process is not privileged).
Hence the kludge.
Before the intro of S4U, seteuid32() called lsaprivkeyauth(), then
lsaauth(), then create_token(). Before the intro of Vista, the latter
would have called NtCreateToken().
NtCreateToken() would have failed w/ STATUS_PRIVILEGE_NOT_HELD for a
process w/o the proper privileges. In that case, calling seteuid32()
would have returned EPERM (as required).
Since the intro of Vista, and if the process had been started from an
UNelevated shell, create_token() does NOT reach NtCreateToken()!
As create_token() failed to properly set errno in that case, calling
seteuid32() would return errno as set by lsaauth(), i.e. EACCES, not
in agreement w/ Posix (a bug which was present for years).
(lsaauth() called LsaRegisterLogonProcess() which would fail)
If a FIFO is opened with O_RDWR access, create the pipe with
read/write access, and make the first client have the handle of that
pipe as its I/O handle.
Adjust fhandler_fifo::raw_read to account for the result of trying to
read from that client if there's no data.
fhandler_fifo::clone called fhandler_base::clone on each client
fhandler. But those fhandlers are actually fhandler_fifo objects, so
when fhandler_base::clone calls copyto, it's actually
fhandler_fifo::copyto that gets called. This can lead to mysterious
crashes.
Fix this by simply calling clone (which translates to
fhandler_fifo::clone) on each client fhandler.
Add static functions peek_fifo, thread_fifo, start_thread_fifo, and
fifo_cleanup to select.cc. These are based on the corresponding pipe
functions, the main difference being that peek_fifo loops through the
connected clients to see if any of them have data available for
reading.
Add the fhandler_fifo methods select_read, select_write, and
select_except.
Add accessor methods get_nclients, get_handle, and is_connected that
are needed by peek_fifo.