newlib-cygwin/winsup/cygwin/fhandler_pipe.cc

1241 lines
33 KiB
C++
Raw Normal View History

/* fhandler_pipe.cc: pipes for Cygwin.
2000-02-18 03:38:33 +08:00
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
/* FIXME: Should this really be fhandler_pipe.cc? */
#include "winsup.h"
#include <stdlib.h>
#include <sys/socket.h>
#include "cygerrno.h"
#include "security.h"
Add "path.h" include throughout, where needed. Use new path_conv methods and operators to simplify testing for directory and attributes, throughout. * path.h (path_conv::exists): New method. (path_conv::has_attribute): Ditto. (path_conv::isdir): Ditto. (path_conv::DWORD &): New operator. (path_conv::int &): Ditto. * dir.cc (rmdir): Eliminate a goto. * dtable.cc (dtable::build_fhandler): Accept opt and suffix info for path_conv.check. Return fh == NULL on path_conv error. Pass unit to set_name as appropriate. (dtable::reset_unix_path_name): New method. * dtable.h (dtable): Declare new method. Reflect arg changes to build_fhandler. * fhandler.cc (fhandler_disk_dummy_name): Eliminate. (fhandler_base::set_name): Expect paths to be NULL. Build unix_path_name from win32_path_name when it is a device. (fhandler_base::reset_unix_path_name): New method. (fhandler_base::raw_read): Report EISDIR when ERROR_INVALID_FUNCTION or ERROR_INVALID_PARAMETER and reading a directory. (fhandler_disk_file::fstat): Don't call stat_dev since we should now never be calling fhandler_disk_file methods with devices. (fhandler_base::fhandler_base): Clear {unix,win32}_path_name. (fhandler_base::~fhandler_base): Always free {unix,win32}_path_name. (fhandler_disk_file::fhandler_disk_file): Remove set_no_free_names kludge. (fhandler_disk_file::open): Ditto. * fhandler.h (fhandler_base::no_free_names): Eliminate. (fhandler_base::set_no_free_names): Ditto. * fhandler_tty.cc (fhandler_tty_slave::fhandler_tty_slave): Don't set unix_path_name here. * path.cc (fchdir): Lock fd table throughout. Use new dtable::reset_unix_path_name method to reset path. * syscalls.cc (stat_worker): Reorganize to always call fstat method. Pass path_conv method to fhandler_*::open. (chroot): Elminate a goto.
2001-10-01 12:10:07 +08:00
#include "path.h"
* devices.cc: New file. * devices.gperf: New file. * devices.shilka: New file. * cygwin-gperf: New file. * cygwin-shilka: New file. * fhandler_fifo.cc: New file. * fhandler_nodevice.cc : New file. Reorganize headers so that path.h precedes fhandler.h throughout. Remove device argument and unit arguments from fhandler constructors throughout. Remove pc arguments to fhandler functions and use internal pc element instead, throughout. Use dev element in pc throughout. Use major/minor elements rather than units and device numbers previously in fhandler class. Use correct methods for fhandler file names rather than directly accessing file name variables, throughout. * Makefile.in (DLL_OFILES): Add devices.o, fhandler_fifo.o * dcrt0.cc (dll_crt0_1): Call device::init. * devices.h: Renumber devices based on more Linux-like major/minor numbers. Add more devices. Declare standard device storage. (device): Declare struct. * dir.cc (opendir): Use new 'build_fh_name' to construct a fhandler_* type. * dtable.cc (dtable::get_debugger_info): Ditto. (cygwin_attach_handle_to_fd): Ditto. (dtable::release): Remove special FH_SOCKET case in favor of generic "need_fixup_before" test. (dtable::init_std_file_from_handle): Use either build_fh_dev or build_fh_name to build standard fhandler. (dtable::build_fh_name): Renamed from dtable::build_fhandler_from_name. Move out of dtable class. Don't accept a path_conv argument. Just build it here and pass it to: (build_fh_pc): Renamed from dtable::build_fhandler. Move out of dtable class. Use intrinsic device type in path_conv to create new fhandler. (build_fh_dev): Renamed from dtable::build_fhandler. Move out of dtable class. Simplify arguments to just take new 'device' type and a name. Just return pointer to fhandler rather than trying to insert into dtable. (dtable::dup_worker): Accommodate above build_fh name changes. (dtable::find_fifo): New (currently broken) function. (handle_to_fn): Use strechr for efficiency. * dtable.h: Reflect above build_fh name changes and argument differences. (fhandler_base *&operator []): Return self rather than copy of self. * fhandler.cc (fhandler_base::operator =): Use pc element to set normalized path. (fhandler_base::set_name): Ditto. (fhandler_base::raw_read): Use method to access name. (fhandler_base::write): Correctly use get_output_handle rather than get_handle. (handler_base::device_access_denied): New function. (fhandler_base::open): Eliminate pc argument and use pc element of fhandler_base throughout. (fhandler_base::fstat): Detect if device is based in filesystem and use fstat_fs to calculate stat, if so. (fhandler_base::fhandler_base): Eliminate handling of file names and, instead, just free appropriate component from pc. (fhandler_base::opendir): Remove path_conv parameter. * fhandler.h: Remove all device flags. (fhandler_base::pc): New element. (fhandler_base::set_name): Change argument to path_conv. (fhandler_base::error): New function. (fhandler_base::exists): New function. (fhandler_base::pc_binmode): New function. (fhandler_base::dev): New function. (fhandler_base::open_fs): New function. (fhandler_base::fstat_fs): New function. (fhandler_base::fstat_by_name): New function. (fhandler_base::fstat_by_handle): New function. (fhandler_base::isfifo): New function. (fhandler_base::is_slow): New function. (fhandler_base::is_auto_device): New function. (fhandler_base::is_fs_special): New function. (fhandler_base::device_access_denied): New function. (fhandler_base::operator DWORD&): New operator. (fhandler_base::get_name): Return normalized path from pc. (fhandler_base::get_win32_name): Return windows path from pc. (fhandler_base::isdevice): Renamed from is_device. (fhandler_base::get_native_name): Return device format. (fhandler_fifo): New class. (fhandler_nodevice): New class. (select_stuff::device_specific): Remove array. (select_stuff::device_specific_pipe): New class element. (select_stuff::device_specific_socket): New class element. (select_stuff::device_specific_serial): New class element. (select_stuff::select_stuff): Initialize new elements. * fhandler_disk_file.cc (fhandler_base::fstat_by_handle): Move to base class from fhandler_disk_file. (fhandler_base::fstat_by_name): Ditto. (fhandler_base::fstat_by_name): Ditto. (fhandler_disk_file::open): Move most functionality into fhandler_base::open_fs. (fhandler_base::open_fs): New function. (fhandler_disk_file::close): Move most functionality into fhandler_base::close_fs. (fhandler_base::close_fs): New function. * fhandler_mem.cc (fhandler_dev_mem::open): Use device name in debugging output. * fhandler_socket.cc (fhandler_socket::set_connect_secret): Copy standard urandom device into appropriate place. (fhandler_socket::accept): Reflect change in fdsock return value. * fhandler_tty.cc: See "throughouts" above. * net.cc: Accommodate fdsock change throughout. (fdsock): Return success or failure, accept fd argument and device argument. * path.cc (symlink_info::major): New element. (symlink_info::minor): New element. (symlink_info::parse_device): Declare new function. (fs_info::update): Accommodate changes in path_conv class. (path_conv::fillin): Ditto. (path_conv::return_and_clear_normalized_path): Eliminate. (path_conv::set_normalized_path): New function. (path_conv::path_conv): Set info in dev element. Use path_conv methods Check for FH_FS rather than FH_BAD to indicate when to fill in filesystem stuff. where appropriate rather than direct access. Use set_normalized_path to set normalized path. (windows_device_names): Eliminate. (get_dev): Ditto. (get_raw_device_number): Ditto. (get_device_number): Ditto. (win32_device_name): Call new device name parser to do most of the heavy lifting. (mount_info::conv_to_win32_path): Fill in dev field as appropriate. (symlink_worker): Handle new device files. (symlink_info::check): Ditto. (symlink_info::parse_device): Define new function. * path.h (executable_states): Move here from fhandler.h. (fs_info): Rename variables to *_storage and create methods for accessing same. (path_conv): Add dev element, remove devn and unit and adjust inline methods to accommodate. (set_normalized_path): Declare new function. * pinfo.cc (_pinfo::commune_recv): Add broken support for handling fifos. (_pinfo::commune_send): Ditto. * pipe.cc (fhandler_pipe::close): check for existence of handle before closing it. (handler_pipe::create): Rename from make_pipe. Change arguments to accept fhandler_pipe array. Accommodate fifos. (pipe): Rework to deal with fhandler_pipe::create changes. (_pipe): Ditto. * select.cc: Use individual device_specific types throughout rather than indexing with obsolete device number. (set_bits): Use is_socket call rather than checking device number. * shared_info.h (CURR_MOUNT_MAGIC): Update. (conv_to_win32_path): Reflect addition of device argument. * syscalls.cc (mknod_worker): New function. (open): Use build_fh_name to build fhandler. (chown_worker): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. (chmod_device): New function. (chmod): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. Use chmod_device to set mode of in-filesystem devices. (stat_worker): Eliminate path_conv argument. Call build_fh_name to construct fhandler. Use fh->error() rather than pc->error to detect errors in fhandler construction. (access_worker): New function pulled from access. Accommodate in-filesystem devices. (access): Use access_worker. (fpathconf): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. (mknod_worker): New function. (mknod32): New function. (chroot): Free normalized path -- assuming it was actually cmalloced. * tty.cc (create_tty_master): Tweak for new device class. (tty::common_init): Ditto. * winsup.h (stat_worker): Remove. (symlink_worker): Declare. * exceptions.cc (set_process_mask): Just call sig_dispatch_pending and don't worry about pending_signals since sig_dispatch_pending should always do the right thing now. (sig_handle): Reorganize SIGCONT handling to more closely conform to SUSv3. * pinfo.h: Move __SIG enum to sigproc.h. (PICOM_FIFO): New enum element. (_pinfo): Remove 'thread2signal' stuff throughout class. (_pinfo::commune_send): Make varargs. (_pinfo::sigtodo): Eliminate. (_pinfo::thread2signal): Ditto. * signal.cc (kill_worker): Eliminate call to setthread2signal. * sigproc.cc (local_sigtodo): Eliminate. (getlocal_sigtodo): Ditto. (sigelem): New class. (pending_signals): New class. (sigqueue): New variable, start of sigqueue linked list. (sigcatch_nonmain): Eliminate. (sigcatch_main): Eliminate. (sigcatch_nosync): Eliminate. (sigcomplete_nonmain): Eliminate. (pending_signals): Eliminate. (sig_clear): Call signal thread to clear pending signals, unless already in signal thread. (sigpending): Call signal thread to get pending signals. (sig_dispatch_pending): Eliminate use of pending_signals and just check sigqueue. (sigproc_terminate): Eliminate all of the obsolete semaphore stuff. Close signal pipe handle. (sig_send): Eliminate all of the obsolete semaphore stuff and use pipe to send signals. (getevent): Eliminate. (pending_signals::add): New function. (pending_signals::del): New function. (pending_signals::next): New function. (wait_sig): Eliminate all of the obsolete semaphore stuff. Use pipe to communicate and maintain a linked list of signals. * sigproc.h: Move __SIG defines here. Add __SIGPENDING. (sig_dispatch_pending): Remove "C" specifier. (sig_handle): Accept a mask argument. * thread.cc: Remove signal handling considerations throughout.
2003-09-25 08:37:18 +08:00
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
#include "pinfo.h"
* cygprops.h: New file. * dtable.cc (handle_to_fn): Add check for correct installation_key string in object name for pipes and ttys. * external.cc (cygwin_internal): Add CW_GET_INSTKEY to allow fetching the installation_key from cygserver. * fhandler_fifo.cc (fhandler_fifo::fifo_name): Add installation_key to fifo name. * globals.cc: Include cygprops.h. (_RDATA): Move slightly and add comment. (cygwin_props): Define. * mount.cc (mount_info::init): Accommodate the fact that installation_root is now a global variable in DLL common shared memory, rather than a member of cygwin_shared. * pipe.cc (fhandler_pipe::create_selectable): Add installation_key to pipe name. * shared.cc (installation_root): Define here for storage in DLL common shared memory. (installation_key): Ditto. (installation_key_buf): Ditto. (init_installation_root): Convert from shared_info method to ordinary function. Add initializing installation_key. Invalidate installation_key depending of value of disable_key property. Add comment to explain. (get_shared_parent_dir): Add installation_key to directory name. (get_session_parent_dir): Ditto. (shared_info::initialize): Move call to init_installation_root from here... (memory_init): ...to here. Add debug output to print installation root and installation key. Add comment to explain why. * shared_info.h (SHARED_INFO_CB): Recalculate. (CURR_SHARED_MAGIC): Ditto. (class shared_info): Remove definition of installation_root and declaration of init_installation_root. (init_installation_root): Declare. (installation_root): Declare. (installation_key): Declare. * uinfo.cc (pwdgrp::load): Accommodate the fact that installation_root is now a global variable in DLL common shared memory. * include/cygwin/version.h: Bump API minor number. (CYGWIN_INFO_INSTALLATIONS_NAME): Add. * include/sys/cygwin.h (cygwin_getinfo_types): Add CW_GET_INSTKEY.
2009-10-31 21:24:06 +08:00
#include "shared_info.h"
#include "tls_pbuf.h"
/* This is only to be used for writing. When reading,
STATUS_PIPE_EMPTY simply means there's no data to be read. */
#define STATUS_PIPE_IS_CLOSED(status) \
({ NTSTATUS _s = (status); \
_s == STATUS_PIPE_CLOSING \
|| _s == STATUS_PIPE_BROKEN \
|| _s == STATUS_PIPE_EMPTY; })
fhandler_pipe_fifo::fhandler_pipe_fifo ()
: fhandler_base (), pipe_buf_size (DEFAULT_PIPEBUFSIZE)
{
}
* devices.cc: New file. * devices.gperf: New file. * devices.shilka: New file. * cygwin-gperf: New file. * cygwin-shilka: New file. * fhandler_fifo.cc: New file. * fhandler_nodevice.cc : New file. Reorganize headers so that path.h precedes fhandler.h throughout. Remove device argument and unit arguments from fhandler constructors throughout. Remove pc arguments to fhandler functions and use internal pc element instead, throughout. Use dev element in pc throughout. Use major/minor elements rather than units and device numbers previously in fhandler class. Use correct methods for fhandler file names rather than directly accessing file name variables, throughout. * Makefile.in (DLL_OFILES): Add devices.o, fhandler_fifo.o * dcrt0.cc (dll_crt0_1): Call device::init. * devices.h: Renumber devices based on more Linux-like major/minor numbers. Add more devices. Declare standard device storage. (device): Declare struct. * dir.cc (opendir): Use new 'build_fh_name' to construct a fhandler_* type. * dtable.cc (dtable::get_debugger_info): Ditto. (cygwin_attach_handle_to_fd): Ditto. (dtable::release): Remove special FH_SOCKET case in favor of generic "need_fixup_before" test. (dtable::init_std_file_from_handle): Use either build_fh_dev or build_fh_name to build standard fhandler. (dtable::build_fh_name): Renamed from dtable::build_fhandler_from_name. Move out of dtable class. Don't accept a path_conv argument. Just build it here and pass it to: (build_fh_pc): Renamed from dtable::build_fhandler. Move out of dtable class. Use intrinsic device type in path_conv to create new fhandler. (build_fh_dev): Renamed from dtable::build_fhandler. Move out of dtable class. Simplify arguments to just take new 'device' type and a name. Just return pointer to fhandler rather than trying to insert into dtable. (dtable::dup_worker): Accommodate above build_fh name changes. (dtable::find_fifo): New (currently broken) function. (handle_to_fn): Use strechr for efficiency. * dtable.h: Reflect above build_fh name changes and argument differences. (fhandler_base *&operator []): Return self rather than copy of self. * fhandler.cc (fhandler_base::operator =): Use pc element to set normalized path. (fhandler_base::set_name): Ditto. (fhandler_base::raw_read): Use method to access name. (fhandler_base::write): Correctly use get_output_handle rather than get_handle. (handler_base::device_access_denied): New function. (fhandler_base::open): Eliminate pc argument and use pc element of fhandler_base throughout. (fhandler_base::fstat): Detect if device is based in filesystem and use fstat_fs to calculate stat, if so. (fhandler_base::fhandler_base): Eliminate handling of file names and, instead, just free appropriate component from pc. (fhandler_base::opendir): Remove path_conv parameter. * fhandler.h: Remove all device flags. (fhandler_base::pc): New element. (fhandler_base::set_name): Change argument to path_conv. (fhandler_base::error): New function. (fhandler_base::exists): New function. (fhandler_base::pc_binmode): New function. (fhandler_base::dev): New function. (fhandler_base::open_fs): New function. (fhandler_base::fstat_fs): New function. (fhandler_base::fstat_by_name): New function. (fhandler_base::fstat_by_handle): New function. (fhandler_base::isfifo): New function. (fhandler_base::is_slow): New function. (fhandler_base::is_auto_device): New function. (fhandler_base::is_fs_special): New function. (fhandler_base::device_access_denied): New function. (fhandler_base::operator DWORD&): New operator. (fhandler_base::get_name): Return normalized path from pc. (fhandler_base::get_win32_name): Return windows path from pc. (fhandler_base::isdevice): Renamed from is_device. (fhandler_base::get_native_name): Return device format. (fhandler_fifo): New class. (fhandler_nodevice): New class. (select_stuff::device_specific): Remove array. (select_stuff::device_specific_pipe): New class element. (select_stuff::device_specific_socket): New class element. (select_stuff::device_specific_serial): New class element. (select_stuff::select_stuff): Initialize new elements. * fhandler_disk_file.cc (fhandler_base::fstat_by_handle): Move to base class from fhandler_disk_file. (fhandler_base::fstat_by_name): Ditto. (fhandler_base::fstat_by_name): Ditto. (fhandler_disk_file::open): Move most functionality into fhandler_base::open_fs. (fhandler_base::open_fs): New function. (fhandler_disk_file::close): Move most functionality into fhandler_base::close_fs. (fhandler_base::close_fs): New function. * fhandler_mem.cc (fhandler_dev_mem::open): Use device name in debugging output. * fhandler_socket.cc (fhandler_socket::set_connect_secret): Copy standard urandom device into appropriate place. (fhandler_socket::accept): Reflect change in fdsock return value. * fhandler_tty.cc: See "throughouts" above. * net.cc: Accommodate fdsock change throughout. (fdsock): Return success or failure, accept fd argument and device argument. * path.cc (symlink_info::major): New element. (symlink_info::minor): New element. (symlink_info::parse_device): Declare new function. (fs_info::update): Accommodate changes in path_conv class. (path_conv::fillin): Ditto. (path_conv::return_and_clear_normalized_path): Eliminate. (path_conv::set_normalized_path): New function. (path_conv::path_conv): Set info in dev element. Use path_conv methods Check for FH_FS rather than FH_BAD to indicate when to fill in filesystem stuff. where appropriate rather than direct access. Use set_normalized_path to set normalized path. (windows_device_names): Eliminate. (get_dev): Ditto. (get_raw_device_number): Ditto. (get_device_number): Ditto. (win32_device_name): Call new device name parser to do most of the heavy lifting. (mount_info::conv_to_win32_path): Fill in dev field as appropriate. (symlink_worker): Handle new device files. (symlink_info::check): Ditto. (symlink_info::parse_device): Define new function. * path.h (executable_states): Move here from fhandler.h. (fs_info): Rename variables to *_storage and create methods for accessing same. (path_conv): Add dev element, remove devn and unit and adjust inline methods to accommodate. (set_normalized_path): Declare new function. * pinfo.cc (_pinfo::commune_recv): Add broken support for handling fifos. (_pinfo::commune_send): Ditto. * pipe.cc (fhandler_pipe::close): check for existence of handle before closing it. (handler_pipe::create): Rename from make_pipe. Change arguments to accept fhandler_pipe array. Accommodate fifos. (pipe): Rework to deal with fhandler_pipe::create changes. (_pipe): Ditto. * select.cc: Use individual device_specific types throughout rather than indexing with obsolete device number. (set_bits): Use is_socket call rather than checking device number. * shared_info.h (CURR_MOUNT_MAGIC): Update. (conv_to_win32_path): Reflect addition of device argument. * syscalls.cc (mknod_worker): New function. (open): Use build_fh_name to build fhandler. (chown_worker): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. (chmod_device): New function. (chmod): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. Use chmod_device to set mode of in-filesystem devices. (stat_worker): Eliminate path_conv argument. Call build_fh_name to construct fhandler. Use fh->error() rather than pc->error to detect errors in fhandler construction. (access_worker): New function pulled from access. Accommodate in-filesystem devices. (access): Use access_worker. (fpathconf): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. (mknod_worker): New function. (mknod32): New function. (chroot): Free normalized path -- assuming it was actually cmalloced. * tty.cc (create_tty_master): Tweak for new device class. (tty::common_init): Ditto. * winsup.h (stat_worker): Remove. (symlink_worker): Declare. * exceptions.cc (set_process_mask): Just call sig_dispatch_pending and don't worry about pending_signals since sig_dispatch_pending should always do the right thing now. (sig_handle): Reorganize SIGCONT handling to more closely conform to SUSv3. * pinfo.h: Move __SIG enum to sigproc.h. (PICOM_FIFO): New enum element. (_pinfo): Remove 'thread2signal' stuff throughout class. (_pinfo::commune_send): Make varargs. (_pinfo::sigtodo): Eliminate. (_pinfo::thread2signal): Ditto. * signal.cc (kill_worker): Eliminate call to setthread2signal. * sigproc.cc (local_sigtodo): Eliminate. (getlocal_sigtodo): Ditto. (sigelem): New class. (pending_signals): New class. (sigqueue): New variable, start of sigqueue linked list. (sigcatch_nonmain): Eliminate. (sigcatch_main): Eliminate. (sigcatch_nosync): Eliminate. (sigcomplete_nonmain): Eliminate. (pending_signals): Eliminate. (sig_clear): Call signal thread to clear pending signals, unless already in signal thread. (sigpending): Call signal thread to get pending signals. (sig_dispatch_pending): Eliminate use of pending_signals and just check sigqueue. (sigproc_terminate): Eliminate all of the obsolete semaphore stuff. Close signal pipe handle. (sig_send): Eliminate all of the obsolete semaphore stuff and use pipe to send signals. (getevent): Eliminate. (pending_signals::add): New function. (pending_signals::del): New function. (pending_signals::next): New function. (wait_sig): Eliminate all of the obsolete semaphore stuff. Use pipe to communicate and maintain a linked list of signals. * sigproc.h: Move __SIG defines here. Add __SIGPENDING. (sig_dispatch_pending): Remove "C" specifier. (sig_handle): Accept a mask argument. * thread.cc: Remove signal handling considerations throughout.
2003-09-25 08:37:18 +08:00
fhandler_pipe::fhandler_pipe ()
: fhandler_pipe_fifo (), popen_pid (0)
{
need_fork_fixup (true);
}
/* The following function is intended for fhandler_pipe objects
created by the second version of fhandler_pipe::create below. See
the comment preceding the latter.
In addition to setting the blocking mode of the pipe handle, it
also sets the pipe's read mode to byte_stream unconditionally. */
void
fhandler_pipe::set_pipe_non_blocking (bool nonblocking)
{
NTSTATUS status;
IO_STATUS_BLOCK io;
FILE_PIPE_INFORMATION fpi;
fpi.ReadMode = FILE_PIPE_BYTE_STREAM_MODE;
fpi.CompletionMode = nonblocking ? FILE_PIPE_COMPLETE_OPERATION
: FILE_PIPE_QUEUE_OPERATION;
status = NtSetInformationFile (get_handle (), &io, &fpi, sizeof fpi,
FilePipeInformation);
if (!NT_SUCCESS (status))
debug_printf ("NtSetInformationFile(FilePipeInformation): %y", status);
}
int
2016-01-11 19:35:41 +08:00
fhandler_pipe::init (HANDLE f, DWORD a, mode_t mode, int64_t uniq_id)
{
/* FIXME: Have to clean this up someday
FIXME: Do we have to check for both !get_win32_name() and
!*get_win32_name()? */
if ((!get_win32_name () || !*get_win32_name ()) && get_name ())
{
char *d;
const char *s;
char *hold_normalized_name = (char *) alloca (strlen (get_name ()) + 1);
for (s = get_name (), d = hold_normalized_name; *s; s++, d++)
if (*s == '/')
*d = '\\';
else
*d = *s;
*d = '\0';
set_name (hold_normalized_name);
}
bool opened_properly = a & FILE_CREATE_PIPE_INSTANCE;
a &= ~FILE_CREATE_PIPE_INSTANCE;
fhandler_base::init (f, a, mode);
* cygwin.din (dup3): Export. (pipe2): Export. * dtable.cc (dtable::dup_worker): Take additional flags parameter. Handle O_CLOEXEC flag. (dtable::dup3): Rename from dup2. Take additional flags parameter. Check for valid flags. Drop check for newfd == oldfd. * dtable.h (dtable::dup_worker): Add flags parameter. (dtable::dup3): Rename from dup2. * fcntl.cc (fcntl64): Add F_DUPFD_CLOEXEC case. * fhandler.h (fhandler_mailslot::get_object_attr): Add flags parameter. * fhandler.cc (fhandler_base::open): Use security attribute with inheritance according to setting of O_CLOEXEC flag. * fhandler_console.cc (fhandler_console::open): Ditto. * fhandler_fifo.cc (sec_user_cloexec): New inline function to create security attribute with inheritance according to setting of O_CLOEXEC flag. (fhandler_fifo::open): Call sec_user_cloexec to fetch security attribute. (fhandler_fifo::wait): Ditto. * fhandler_mem.cc (fhandler_dev_mem::open): Ditto. * fhandler_mailslot.cc (fhandler_mailslot::get_object_attr): Take additional flags parameter. Use security attribute with inheritance according to setting of O_CLOEXEC flag. (fhandler_mailslot::open): Call get_object_attr with flags parameter. * fhandler_registry.cc (fhandler_registry::open): Call set_close_on_exec on real handles to accommodate O_CLOEXEC flag. * fhandler_tty.cc (fhandler_tty_slave::open): Ditto. * fhandler_tape.cc: Create mutex with inheritance according to setting of O_CLOEXEC flag. * pipe.cc: Replace usage of O_NOINHERIT with O_CLOEXEC. (fhandler_pipe::init): Simplify setting close_on_exec flag. (fhandler_pipe::open): Remove setting close_on_exec flag. (fhandler_pipe::create): Use security attribute with inheritance according to setting of O_CLOEXEC flag. (pipe2): New exported function. * posix_ipc.cc: Throughout, open backing files with O_CLOEXEC flag to follow POSIX semantics. * security.h (sec_none_cloexec): New define. * syscalls.cc (dup): Add missing extern "C" qualifier. Accommodate renaming of dtable::dup2 to dtable::dup3. (dup2): Ditto. Check newfd == oldfd here. (dup3): New function. Check newfd == oldfd here. (open): Set close_on_exec flag according to O_CLOEXEC flag before calling fhandler->open. * include/cygwin/version.h (CYGWIN_VERSION_API_MINOR): Bump.
2010-01-15 02:46:02 +08:00
close_on_exec (mode & O_CLOEXEC);
2016-01-11 19:35:41 +08:00
set_ino (uniq_id);
set_unique_id (uniq_id | !!(mode & GENERIC_WRITE));
if (opened_properly)
set_pipe_non_blocking (is_nonblocking ());
return 1;
}
extern "C" int sscanf (const char *, const char *, ...);
int
fhandler_pipe::open (int flags, mode_t mode)
{
2016-01-11 19:35:41 +08:00
HANDLE proc, nio_hdl = NULL;
int64_t uniq_id;
fhandler_pipe *fh = NULL, *fhr = NULL, *fhw = NULL;
size_t size;
int pid, rwflags = (flags & O_ACCMODE);
bool inh;
2016-01-11 19:35:41 +08:00
bool got_one = false;
if (sscanf (get_name (), "/proc/%d/fd/pipe:[%llu]",
&pid, (long long *) &uniq_id) < 2)
{
set_errno (ENOENT);
return 0;
}
if (pid == myself->pid)
{
cygheap_fdenum cfd (true);
while (cfd.next () >= 0)
{
2016-01-11 19:35:41 +08:00
/* Windows doesn't allow to copy a pipe HANDLE with another access
mode. So we check for read and write side of pipe and try to
find the one matching the requested access mode. */
if (cfd->get_unique_id () == uniq_id)
got_one = true;
else if (cfd->get_unique_id () == uniq_id + 1)
got_one = true;
else
continue;
if ((rwflags == O_RDONLY && !(cfd->get_access () & GENERIC_READ))
|| (rwflags == O_WRONLY && !(cfd->get_access () & GENERIC_WRITE)))
2016-01-11 19:35:41 +08:00
continue;
copy_from (cfd);
set_handle (NULL);
pc.close_conv_handle ();
* cygerrno.h (__set_errno): Modify debugging output to make searching strace logs easier. Throughout, change /dev/tty* to /dev/pty*. Throughout, add flags argument to fhandler_*::dup methods. * devices.in: Rename (temporarily?) /dev/ttyN to /dev/ptyN. Add /dev/ptymN devices for pty masters. * devices.cc: Regenerate. * devices.h (MAX_CONSOLES): Set to max number supported by devices.in. (fh_devices::FH_PTMX): Rename from FH_PTYM. (device::operator int): Return by reference. * dtable.cc (fh_alloc): Take pc as an argument rather than just the device. This makes debugging easier since more information is available. Actually implement handling for already-allocated pty master devices. Make different decisions when generating fhandler for not-opened devices. Add kludge to deal with opening /dev/tty. (cnew_no_ctor): New macro. (build_fh_pc): Make debugging output more verbose. Use new clone() fhandler interface to duplicate archetypes. Reset last term opened. (dtable::dup_worker): Use Use new clone() fhandler interface to duplicate archetypes. Pass flags to child dup handler. (dtable::dup3): Set O_NOCTTY flag if newfd is not stdin/stdout/stderr. * fhandler.cc (fhandler_base::reset): Rename from operator =() and reduce functionality and sense of copy direction. (fhandler_base::open_with_arch): Use published interface to query io_handle(). Use new copyto() fhandler method to copy from/to found archetype. * fhandler.h: Throughout, delete size(), add copyout, clone, and fhandler_* (void *) methods. (fhandler_base::reset): Rename from operator =(). (fhandler_termios::is_dev_tty): Delete. (fhandler_termios): change "protected" region to "private". (fhandler_termios::is_dev_tty): Delete. (fhandler_termios): Rearrange protected/public. (fhandler_termios::fhandler_termios): Remember last fhandler_termios "opened". (fhandler_termios::~fhandler_termios): Forget last fhandler_termios opened. (ioctl): Rename from ioctl_termios. Take a void * argument. Reflect argument change in pinfo::set_ctty. (fhandler_console::dup): Declare new function. Set ctty here if appropriate. (fhandler_pty_master::from_master): Privatize. (fhandler_pty_master::to_master): Ditto. (fhandler_pty_master::dwProcessId): Ditto. (fhandler_pty_master::fhandler_pty_master): Add an `int' argument. (fhandler_pty_master::open_setup): Declare new function. (fhandler_pty_master::~fhandler_pty_master): Declare new method. (fhandler_nodevice): Remove commented out function declaration. * fhandler_console.cc: Use get_ttyp() instead of tc() throughout. (fhandler_console::dup): Define new function to set controlling ctty on dup, as appropriate. (fhandler_console::ioctl): Reflect ioctl_termios name change. (fhandler_console::setup): Rename from get_tty_stuff. (fhandler_console::open_setup): Reflect argument change in pinfo::set_ctty. (fhandler_console::fhandler_console): Set _tc here. * fhandler_termios.cc (handler_termios::ioctl): Rename. Take a void * arg like other ioctl functions. * fhandler_tty.cc (fhandler_pty_slave::dup): Call myself->set_ctty to potentially reset the controlling terminal. (fhandler_pty_slave::ioctl): Reflect name/arg change for ioctl_termios. (fhandler_pty_slave::fhandler_pty_slave): Take a "unit" argument. Call setup() here so that we will know the unit number of this fhandler as soon as possible. Set the unit as appropriate. (handler_pty_master::open): Move most stuff to constructor and open_setup. (handler_pty_slave::open_setup): Reflect argument change in pinfo::set_ctty. (handler_pty_master::open_setup): Define new function. (fhandler_pty_master::cleanup): Clear handles as a flag that the destructor does not have to do "close" operations. (fhandler_pty_master::close): Ditto. (fhandler_pty_master::~fhandler_pty_master): Define new method. (fhandler_pty_master::ioctl): Reflect name/arg change for ioctl_termios. (fhandler_pty_master::setup): Allocate tty here. Rely on handles being returned from allocated test rather than opening them here. Avoid setting _need_nl here since it is already zeroed in the constructor. Set up device information with DEV_TTYM_MAJOR. * path.h (path_conv &operator =): Take a const argument. (path_conv::dup): Ditto. (pathconv_arg::PC_OPEN): New enum. (pathconv_arg::PC_CTTY): Ditto. (path_types::PATH_CTTY): Ditto. (path_types::PATH_OPEN): Ditto. (path_conv::isopen): New method. (path_conv::isctty_capable): Ditto. * path.cc (path_conv::check): Set PATH_OPEN and PATH_CTTY as appropriate. * pipe.cc (fhandler_pipe::open): Use copyto to copy pipe handle. * syscall.cc (open): Reinstate fd > 2 check to disallow resetting ctty on non-std* handles. * tty.cc (tty_list::allocate): Pass out handles for allocated tty. use `not_allocated' to find unallocated ttys. Avoid keeping the lock since the allocation of the tty should be sufficient to prevent multiple access. (tty::not_allocated): Clarify comment. Rename. Return handles when an unused tty is found. Simply test for existing tty. (tty::exists): Rewrite to use `not_allocated'. * tty.h (NTTYS): Reset down to actual number supported by devices.in. (tty::not_allocated): Declare new function. (tty_list::allocate): Pass out read/write tty handles. Zero them when not found. * fhandler_proc.cc: Reflect name change from FH_PTYM -> FH_PTMX. * pinfo.h (pinfo::set_ctty): Reduce/reorder arguments passed in. * pinfo.cc (pinfo::set_ctty): Ditto. Just use tc() built into the passed-in fhandler_termios pointer. Return true if ctty is assigned. * syscalls.cc (open): Call build_fh_pc with PC_OPEN flag. Set PC_CTTY if appropriate. (stat_worker): Remove is_dev_tty () stuff.
2011-10-16 06:37:30 +08:00
if (!cfd->dup (this, flags))
return 1;
return 0;
}
2016-01-11 19:35:41 +08:00
/* Found the pipe but access mode didn't match? EACCES.
Otherwise ENOENT */
set_errno (got_one ? EACCES : ENOENT);
return 0;
}
pinfo p (pid);
if (!p)
{
set_errno (ESRCH);
return 0;
}
if (!(proc = OpenProcess (PROCESS_DUP_HANDLE, false, p->dwProcessId)))
{
__seterrno ();
return 0;
}
2016-01-11 19:35:41 +08:00
fhr = p->pipe_fhandler (uniq_id, size);
if (fhr && rwflags == O_RDONLY)
fh = fhr;
else
{
2016-01-11 19:35:41 +08:00
fhw = p->pipe_fhandler (uniq_id + 1, size);
if (fhw && rwflags == O_WRONLY)
fh = fhw;
}
2016-01-11 19:35:41 +08:00
if (!fh)
{
2016-01-11 19:35:41 +08:00
/* Too bad, but Windows only allows the same access mode when dup'ing
the pipe. */
set_errno (fhr || fhw ? EACCES : ENOENT);
goto out;
}
* cygwin.din (dup3): Export. (pipe2): Export. * dtable.cc (dtable::dup_worker): Take additional flags parameter. Handle O_CLOEXEC flag. (dtable::dup3): Rename from dup2. Take additional flags parameter. Check for valid flags. Drop check for newfd == oldfd. * dtable.h (dtable::dup_worker): Add flags parameter. (dtable::dup3): Rename from dup2. * fcntl.cc (fcntl64): Add F_DUPFD_CLOEXEC case. * fhandler.h (fhandler_mailslot::get_object_attr): Add flags parameter. * fhandler.cc (fhandler_base::open): Use security attribute with inheritance according to setting of O_CLOEXEC flag. * fhandler_console.cc (fhandler_console::open): Ditto. * fhandler_fifo.cc (sec_user_cloexec): New inline function to create security attribute with inheritance according to setting of O_CLOEXEC flag. (fhandler_fifo::open): Call sec_user_cloexec to fetch security attribute. (fhandler_fifo::wait): Ditto. * fhandler_mem.cc (fhandler_dev_mem::open): Ditto. * fhandler_mailslot.cc (fhandler_mailslot::get_object_attr): Take additional flags parameter. Use security attribute with inheritance according to setting of O_CLOEXEC flag. (fhandler_mailslot::open): Call get_object_attr with flags parameter. * fhandler_registry.cc (fhandler_registry::open): Call set_close_on_exec on real handles to accommodate O_CLOEXEC flag. * fhandler_tty.cc (fhandler_tty_slave::open): Ditto. * fhandler_tape.cc: Create mutex with inheritance according to setting of O_CLOEXEC flag. * pipe.cc: Replace usage of O_NOINHERIT with O_CLOEXEC. (fhandler_pipe::init): Simplify setting close_on_exec flag. (fhandler_pipe::open): Remove setting close_on_exec flag. (fhandler_pipe::create): Use security attribute with inheritance according to setting of O_CLOEXEC flag. (pipe2): New exported function. * posix_ipc.cc: Throughout, open backing files with O_CLOEXEC flag to follow POSIX semantics. * security.h (sec_none_cloexec): New define. * syscalls.cc (dup): Add missing extern "C" qualifier. Accommodate renaming of dtable::dup2 to dtable::dup3. (dup2): Ditto. Check newfd == oldfd here. (dup3): New function. Check newfd == oldfd here. (open): Set close_on_exec flag according to O_CLOEXEC flag before calling fhandler->open. * include/cygwin/version.h (CYGWIN_VERSION_API_MINOR): Bump.
2010-01-15 02:46:02 +08:00
inh = !(flags & O_CLOEXEC);
2016-01-11 19:35:41 +08:00
if (!DuplicateHandle (proc, fh->get_handle (), GetCurrentProcess (),
&nio_hdl, 0, inh, DUPLICATE_SAME_ACCESS))
{
__seterrno ();
goto out;
}
init (nio_hdl, fh->get_access (), mode & O_TEXT ?: O_BINARY,
fh->get_plain_ino ());
cfree (fh);
CloseHandle (proc);
return 1;
out:
if (nio_hdl)
CloseHandle (nio_hdl);
if (fh)
free (fh);
if (proc)
CloseHandle (proc);
return 0;
}
bool
fhandler_pipe::open_setup (int flags)
{
bool read_mtx_created = false;
if (!fhandler_base::open_setup (flags))
goto err;
if (get_dev () == FH_PIPER && !read_mtx)
{
SECURITY_ATTRIBUTES *sa = sec_none_cloexec (flags);
read_mtx = CreateMutex (sa, FALSE, NULL);
if (read_mtx)
read_mtx_created = true;
else
{
debug_printf ("CreateMutex read_mtx failed: %E");
goto err;
}
}
if (!hdl_cnt_mtx)
{
SECURITY_ATTRIBUTES *sa = sec_none_cloexec (flags);
hdl_cnt_mtx = CreateMutex (sa, FALSE, NULL);
if (!hdl_cnt_mtx)
{
debug_printf ("CreateMutex hdl_cnt_mtx failed: %E");
goto err_close_read_mtx;
}
}
return true;
err_close_read_mtx:
if (read_mtx_created)
CloseHandle (read_mtx);
err:
return false;
}
2013-04-23 17:44:36 +08:00
off_t
fhandler_pipe::lseek (off_t offset, int whence)
{
2013-04-23 17:44:36 +08:00
debug_printf ("(%D, %d)", offset, whence);
set_errno (ESPIPE);
return -1;
}
int
2013-04-23 17:44:36 +08:00
fhandler_pipe::fadvise (off_t offset, off_t length, int advice)
{
return ESPIPE;
}
int
2013-04-23 17:44:36 +08:00
fhandler_pipe::ftruncate (off_t length, bool allow_truncate)
{
return allow_truncate ? EINVAL : ESPIPE;
}
char *
fhandler_pipe::get_proc_fd_name (char *buf)
* cygheap.h (class cygheap_fdenum): New class to enumerate used fhandlers. * dtable.h (class dtable): Add cygheap_fdenum as friend class. * fhandler.h (fhandler_base::get_proc_fd_name): New virtual method to return a name for /proc/<pid>/fd. (fhandler_socket::get_proc_fd_name): Ditto. (fhandler_pipe::get_proc_fd_name): Ditto. (fhandler_virtual::opendir): Make virtual method. (fhandler_process::opendir): New method. * fhandler.cc (fhandler_base::get_proc_fd_name): New method. * fhandler_process.cc: Include ctype.h. (PROCESS_FD): Define. (process_listing): Add "fd". (fhandler_process::exists): Fix comment. Return 1 in case of "fd" directory. Handle files below "fd". (fhandler_process::fstat): Drop "self" handling. Set correct link count for directories. (fhandler_process::opendir): New method to handle "fd" directory. (fhandler_process::readdir): Add "fd" handling. (fhandler_process::open): Drop "self" handling. (fhandler_process::fill_filebuf): Ditto. Add "fd" handling. Fix "maps" output string. * fhandler_registry.cc (fhandler_registry::fstat): Set correct link count for directories. * fhandler_socket.cc (fhandler_socket::get_proc_fd_name): New method. * path.cc (symlink_info::set): Fix thinko. * pinfo.cc (_pinfo::commune_recv): Rename pathbuf to path throughout. Drop local path variable in PICOM_FIFO case. Fix debug output. Close handles as early as possible. Add PICOM_FDS and PICOM_FD handling. (_pinfo::commune_send): Add PICOM_FDS and PICOM_FD handling. (_pinfo::fd): New method. (_pinfo::fds): New method. * pinfo.h (enum picom): Add PICOM_FDS and PICOM_FD. (_pinfo::fd): Declare. (_pinfo::fds): Declare. * pipe.cc (fhandler_pipe::get_proc_fd_name): New method.
2005-01-31 18:28:55 +08:00
{
__small_sprintf (buf, "pipe:[%U]", get_plain_ino ());
* cygheap.h (class cygheap_fdenum): New class to enumerate used fhandlers. * dtable.h (class dtable): Add cygheap_fdenum as friend class. * fhandler.h (fhandler_base::get_proc_fd_name): New virtual method to return a name for /proc/<pid>/fd. (fhandler_socket::get_proc_fd_name): Ditto. (fhandler_pipe::get_proc_fd_name): Ditto. (fhandler_virtual::opendir): Make virtual method. (fhandler_process::opendir): New method. * fhandler.cc (fhandler_base::get_proc_fd_name): New method. * fhandler_process.cc: Include ctype.h. (PROCESS_FD): Define. (process_listing): Add "fd". (fhandler_process::exists): Fix comment. Return 1 in case of "fd" directory. Handle files below "fd". (fhandler_process::fstat): Drop "self" handling. Set correct link count for directories. (fhandler_process::opendir): New method to handle "fd" directory. (fhandler_process::readdir): Add "fd" handling. (fhandler_process::open): Drop "self" handling. (fhandler_process::fill_filebuf): Ditto. Add "fd" handling. Fix "maps" output string. * fhandler_registry.cc (fhandler_registry::fstat): Set correct link count for directories. * fhandler_socket.cc (fhandler_socket::get_proc_fd_name): New method. * path.cc (symlink_info::set): Fix thinko. * pinfo.cc (_pinfo::commune_recv): Rename pathbuf to path throughout. Drop local path variable in PICOM_FIFO case. Fix debug output. Close handles as early as possible. Add PICOM_FDS and PICOM_FD handling. (_pinfo::commune_send): Add PICOM_FDS and PICOM_FD handling. (_pinfo::fd): New method. (_pinfo::fds): New method. * pinfo.h (enum picom): Add PICOM_FDS and PICOM_FD. (_pinfo::fd): Declare. (_pinfo::fds): Declare. * pipe.cc (fhandler_pipe::get_proc_fd_name): New method.
2005-01-31 18:28:55 +08:00
return buf;
}
void
fhandler_pipe::release_select_sem (const char *from)
{
LONG n_release;
if (get_dev () == FH_PIPER) /* Number of select() and writer */
n_release = get_obj_handle_count (select_sem)
- get_obj_handle_count (read_mtx);
else /* Number of select() call */
n_release = get_obj_handle_count (select_sem)
- get_obj_handle_count (hdl_cnt_mtx);
debug_printf("%s(%s) release %d", from,
get_dev () == FH_PIPER ? "PIPER" : "PIPEW", n_release);
if (n_release)
ReleaseSemaphore (select_sem, n_release, NULL);
}
void __reg3
fhandler_pipe::raw_read (void *ptr, size_t& len)
{
size_t nbytes = 0;
NTSTATUS status = STATUS_SUCCESS;
IO_STATUS_BLOCK io;
HANDLE evt = NULL;
if (!len)
return;
/* Create a wait event if we're in blocking mode. */
if (!is_nonblocking () && !(evt = CreateEvent (NULL, false, false, NULL)))
{
__seterrno ();
len = (size_t) -1;
return;
}
DWORD timeout = is_nonblocking () ? 0 : INFINITE;
DWORD waitret = cygwait (read_mtx, timeout);
switch (waitret)
{
case WAIT_OBJECT_0:
break;
case WAIT_TIMEOUT:
set_errno (EAGAIN);
len = (size_t) -1;
return;
default:
set_errno (EINTR);
len = (size_t) -1;
return;
}
while (nbytes < len)
{
ULONG_PTR nbytes_now = 0;
ULONG len1 = (ULONG) (len - nbytes);
waitret = WAIT_OBJECT_0;
if (evt)
ResetEvent (evt);
FILE_PIPE_LOCAL_INFORMATION fpli;
status = NtQueryInformationFile (get_handle (), &io,
&fpli, sizeof (fpli),
FilePipeLocalInformation);
if (NT_SUCCESS (status))
{
if (fpli.ReadDataAvailable == 0 && nbytes != 0)
break;
}
else if (nbytes != 0)
break;
status = NtReadFile (get_handle (), evt, NULL, NULL, &io, ptr,
len1, NULL, NULL);
if (evt && status == STATUS_PENDING)
{
waitret = cygwait (evt, INFINITE, cw_cancel | cw_sig);
/* If io.Status is STATUS_CANCELLED after CancelIo, IO has actually
been cancelled and io.Information contains the number of bytes
processed so far.
Otherwise IO has been finished regulary and io.Status contains
valid success or error information. */
CancelIo (get_handle ());
if (waitret == WAIT_SIGNALED && io.Status != STATUS_CANCELLED)
waitret = WAIT_OBJECT_0;
if (waitret == WAIT_CANCELED)
status = STATUS_THREAD_CANCELED;
else if (waitret == WAIT_SIGNALED)
status = STATUS_THREAD_SIGNALED;
else
status = io.Status;
}
if (isclosed ()) /* A signal handler might have closed the fd. */
{
if (waitret == WAIT_OBJECT_0)
set_errno (EBADF);
else
__seterrno ();
nbytes = (size_t) -1;
}
else if (NT_SUCCESS (status)
|| status == STATUS_BUFFER_OVERFLOW
|| status == STATUS_THREAD_CANCELED
|| status == STATUS_THREAD_SIGNALED)
{
nbytes_now = io.Information;
ptr = ((char *) ptr) + nbytes_now;
nbytes += nbytes_now;
if (select_sem && nbytes_now > 0)
release_select_sem ("raw_read");
}
else
{
/* Some errors are not really errors. Detect such cases here. */
switch (status)
{
case STATUS_END_OF_FILE:
case STATUS_PIPE_BROKEN:
/* This is really EOF. */
break;
case STATUS_PIPE_LISTENING:
case STATUS_PIPE_EMPTY:
if (nbytes != 0)
break;
if (is_nonblocking ())
{
set_errno (EAGAIN);
nbytes = (size_t) -1;
break;
}
fallthrough;
default:
__seterrno_from_nt_status (status);
nbytes = (size_t) -1;
break;
}
}
if (nbytes_now == 0 || status == STATUS_BUFFER_OVERFLOW)
break;
}
ReleaseMutex (read_mtx);
if (evt)
CloseHandle (evt);
if (status == STATUS_THREAD_SIGNALED && nbytes == 0)
{
set_errno (EINTR);
nbytes = (size_t) -1;
}
else if (status == STATUS_THREAD_CANCELED)
pthread::static_cancel_self ();
len = nbytes;
}
bool
fhandler_pipe::reader_closed ()
{
if (!query_hdl)
return false;
WaitForSingleObject (hdl_cnt_mtx, INFINITE);
int n_reader = get_obj_handle_count (query_hdl);
int n_writer = get_obj_handle_count (get_handle ());
ReleaseMutex (hdl_cnt_mtx);
return n_reader == n_writer;
}
ssize_t __reg3
fhandler_pipe_fifo::raw_write (const void *ptr, size_t len)
{
size_t nbytes = 0;
ULONG chunk;
NTSTATUS status = STATUS_SUCCESS;
IO_STATUS_BLOCK io;
HANDLE evt = NULL;
if (!len)
return 0;
if (reader_closed ())
{
set_errno (EPIPE);
raise (SIGPIPE);
return -1;
}
if (len <= pipe_buf_size)
chunk = len;
else if (is_nonblocking ())
chunk = len = pipe_buf_size;
else
chunk = pipe_buf_size;
/* Create a wait event if the pipe or fifo is in blocking mode. */
if (!is_nonblocking () && !(evt = CreateEvent (NULL, false, false, NULL)))
{
__seterrno ();
return -1;
}
/* Write in chunks, accumulating a total. If there's an error, just
return the accumulated total unless the first write fails, in
which case return -1. */
while (nbytes < len)
{
ULONG_PTR nbytes_now = 0;
size_t left = len - nbytes;
ULONG len1;
DWORD waitret = WAIT_OBJECT_0;
if (left > chunk)
len1 = chunk;
else
len1 = (ULONG) left;
/* NtWriteFile returns success with # of bytes written == 0 if writing
on a non-blocking pipe fails because the pipe buffer doesn't have
sufficient space.
POSIX requires
- A write request for {PIPE_BUF} or fewer bytes shall have the
following effect: if there is sufficient space available in the
pipe, write() shall transfer all the data and return the number
of bytes requested. Otherwise, write() shall transfer no data and
return -1 with errno set to [EAGAIN].
- A write request for more than {PIPE_BUF} bytes shall cause one
of the following:
- When at least one byte can be written, transfer what it can and
return the number of bytes written. When all data previously
written to the pipe is read, it shall transfer at least {PIPE_BUF}
bytes.
- When no data can be written, transfer no data, and return -1 with
errno set to [EAGAIN]. */
while (len1 > 0)
{
status = NtWriteFile (get_handle (), evt, NULL, NULL, &io,
(PVOID) ptr, len1, NULL, NULL);
if (evt || !NT_SUCCESS (status) || io.Information > 0
|| len <= PIPE_BUF)
break;
len1 >>= 1;
}
if (evt && status == STATUS_PENDING)
{
while (WAIT_TIMEOUT ==
(waitret = cygwait (evt, (DWORD) 0, cw_cancel | cw_sig)))
{
if (reader_closed ())
{
CancelIo (get_handle ());
set_errno (EPIPE);
raise (SIGPIPE);
goto out;
}
else
cygwait (select_sem, 10);
}
/* If io.Status is STATUS_CANCELLED after CancelIo, IO has actually
been cancelled and io.Information contains the number of bytes
processed so far.
Otherwise IO has been finished regulary and io.Status contains
valid success or error information. */
CancelIo (get_handle ());
if (waitret == WAIT_SIGNALED && io.Status != STATUS_CANCELLED)
waitret = WAIT_OBJECT_0;
if (waitret == WAIT_CANCELED)
status = STATUS_THREAD_CANCELED;
else if (waitret == WAIT_SIGNALED)
status = STATUS_THREAD_SIGNALED;
else
status = io.Status;
}
if (isclosed ()) /* A signal handler might have closed the fd. */
{
if (waitret == WAIT_OBJECT_0)
set_errno (EBADF);
else
__seterrno ();
}
else if (NT_SUCCESS (status)
|| status == STATUS_THREAD_CANCELED
|| status == STATUS_THREAD_SIGNALED)
{
nbytes_now = io.Information;
ptr = ((char *) ptr) + nbytes_now;
nbytes += nbytes_now;
if (select_sem && nbytes_now > 0)
release_select_sem ("raw_write");
/* 0 bytes returned? EAGAIN. See above. */
if (NT_SUCCESS (status) && nbytes == 0)
set_errno (EAGAIN);
}
else if (STATUS_PIPE_IS_CLOSED (status))
{
set_errno (EPIPE);
raise (SIGPIPE);
}
else
__seterrno_from_nt_status (status);
if (nbytes_now == 0)
break;
}
out:
if (evt)
CloseHandle (evt);
if (status == STATUS_THREAD_SIGNALED && nbytes == 0)
set_errno (EINTR);
else if (status == STATUS_THREAD_CANCELED)
pthread::static_cancel_self ();
return nbytes ?: -1;
}
void
fhandler_pipe::set_close_on_exec (bool val)
{
fhandler_base::set_close_on_exec (val);
if (read_mtx)
set_no_inheritance (read_mtx, val);
if (select_sem)
set_no_inheritance (select_sem, val);
if (query_hdl)
set_no_inheritance (query_hdl, val);
set_no_inheritance (hdl_cnt_mtx, val);
}
void
fhandler_pipe::fixup_after_fork (HANDLE parent)
{
fork_fixup (parent, hdl_cnt_mtx, "hdl_cnt_mtx");
WaitForSingleObject (hdl_cnt_mtx, INFINITE);
if (read_mtx)
fork_fixup (parent, read_mtx, "read_mtx");
if (select_sem)
fork_fixup (parent, select_sem, "select_sem");
if (query_hdl)
fork_fixup (parent, query_hdl, "query_hdl");
fhandler_base::fixup_after_fork (parent);
ReleaseMutex (hdl_cnt_mtx);
}
int
* cygerrno.h (__set_errno): Modify debugging output to make searching strace logs easier. Throughout, change /dev/tty* to /dev/pty*. Throughout, add flags argument to fhandler_*::dup methods. * devices.in: Rename (temporarily?) /dev/ttyN to /dev/ptyN. Add /dev/ptymN devices for pty masters. * devices.cc: Regenerate. * devices.h (MAX_CONSOLES): Set to max number supported by devices.in. (fh_devices::FH_PTMX): Rename from FH_PTYM. (device::operator int): Return by reference. * dtable.cc (fh_alloc): Take pc as an argument rather than just the device. This makes debugging easier since more information is available. Actually implement handling for already-allocated pty master devices. Make different decisions when generating fhandler for not-opened devices. Add kludge to deal with opening /dev/tty. (cnew_no_ctor): New macro. (build_fh_pc): Make debugging output more verbose. Use new clone() fhandler interface to duplicate archetypes. Reset last term opened. (dtable::dup_worker): Use Use new clone() fhandler interface to duplicate archetypes. Pass flags to child dup handler. (dtable::dup3): Set O_NOCTTY flag if newfd is not stdin/stdout/stderr. * fhandler.cc (fhandler_base::reset): Rename from operator =() and reduce functionality and sense of copy direction. (fhandler_base::open_with_arch): Use published interface to query io_handle(). Use new copyto() fhandler method to copy from/to found archetype. * fhandler.h: Throughout, delete size(), add copyout, clone, and fhandler_* (void *) methods. (fhandler_base::reset): Rename from operator =(). (fhandler_termios::is_dev_tty): Delete. (fhandler_termios): change "protected" region to "private". (fhandler_termios::is_dev_tty): Delete. (fhandler_termios): Rearrange protected/public. (fhandler_termios::fhandler_termios): Remember last fhandler_termios "opened". (fhandler_termios::~fhandler_termios): Forget last fhandler_termios opened. (ioctl): Rename from ioctl_termios. Take a void * argument. Reflect argument change in pinfo::set_ctty. (fhandler_console::dup): Declare new function. Set ctty here if appropriate. (fhandler_pty_master::from_master): Privatize. (fhandler_pty_master::to_master): Ditto. (fhandler_pty_master::dwProcessId): Ditto. (fhandler_pty_master::fhandler_pty_master): Add an `int' argument. (fhandler_pty_master::open_setup): Declare new function. (fhandler_pty_master::~fhandler_pty_master): Declare new method. (fhandler_nodevice): Remove commented out function declaration. * fhandler_console.cc: Use get_ttyp() instead of tc() throughout. (fhandler_console::dup): Define new function to set controlling ctty on dup, as appropriate. (fhandler_console::ioctl): Reflect ioctl_termios name change. (fhandler_console::setup): Rename from get_tty_stuff. (fhandler_console::open_setup): Reflect argument change in pinfo::set_ctty. (fhandler_console::fhandler_console): Set _tc here. * fhandler_termios.cc (handler_termios::ioctl): Rename. Take a void * arg like other ioctl functions. * fhandler_tty.cc (fhandler_pty_slave::dup): Call myself->set_ctty to potentially reset the controlling terminal. (fhandler_pty_slave::ioctl): Reflect name/arg change for ioctl_termios. (fhandler_pty_slave::fhandler_pty_slave): Take a "unit" argument. Call setup() here so that we will know the unit number of this fhandler as soon as possible. Set the unit as appropriate. (handler_pty_master::open): Move most stuff to constructor and open_setup. (handler_pty_slave::open_setup): Reflect argument change in pinfo::set_ctty. (handler_pty_master::open_setup): Define new function. (fhandler_pty_master::cleanup): Clear handles as a flag that the destructor does not have to do "close" operations. (fhandler_pty_master::close): Ditto. (fhandler_pty_master::~fhandler_pty_master): Define new method. (fhandler_pty_master::ioctl): Reflect name/arg change for ioctl_termios. (fhandler_pty_master::setup): Allocate tty here. Rely on handles being returned from allocated test rather than opening them here. Avoid setting _need_nl here since it is already zeroed in the constructor. Set up device information with DEV_TTYM_MAJOR. * path.h (path_conv &operator =): Take a const argument. (path_conv::dup): Ditto. (pathconv_arg::PC_OPEN): New enum. (pathconv_arg::PC_CTTY): Ditto. (path_types::PATH_CTTY): Ditto. (path_types::PATH_OPEN): Ditto. (path_conv::isopen): New method. (path_conv::isctty_capable): Ditto. * path.cc (path_conv::check): Set PATH_OPEN and PATH_CTTY as appropriate. * pipe.cc (fhandler_pipe::open): Use copyto to copy pipe handle. * syscall.cc (open): Reinstate fd > 2 check to disallow resetting ctty on non-std* handles. * tty.cc (tty_list::allocate): Pass out handles for allocated tty. use `not_allocated' to find unallocated ttys. Avoid keeping the lock since the allocation of the tty should be sufficient to prevent multiple access. (tty::not_allocated): Clarify comment. Rename. Return handles when an unused tty is found. Simply test for existing tty. (tty::exists): Rewrite to use `not_allocated'. * tty.h (NTTYS): Reset down to actual number supported by devices.in. (tty::not_allocated): Declare new function. (tty_list::allocate): Pass out read/write tty handles. Zero them when not found. * fhandler_proc.cc: Reflect name change from FH_PTYM -> FH_PTMX. * pinfo.h (pinfo::set_ctty): Reduce/reorder arguments passed in. * pinfo.cc (pinfo::set_ctty): Ditto. Just use tc() built into the passed-in fhandler_termios pointer. Return true if ctty is assigned. * syscalls.cc (open): Call build_fh_pc with PC_OPEN flag. Set PC_CTTY if appropriate. (stat_worker): Remove is_dev_tty () stuff.
2011-10-16 06:37:30 +08:00
fhandler_pipe::dup (fhandler_base *child, int flags)
{
fhandler_pipe *ftp = (fhandler_pipe *) child;
* child_info.h (child_info_spawn::__stdin): New element. (child_info_spawn::__stdin): Ditto. (CURR_CHILD_INFO_MAGIC): Regenerate. * dcrt0.cc (check_sanity_and_sync): Minor cleanup. (child_info_spawn::handle_spawn): Handle new __std* elements by calling move_fd. * dtable.cc (dtable::move_fd): Define new function. * dtable.h (dtable::move_fd): Declare new function. * fhandler.h (fhandler_pipe::popen_pid): Declare new element. * fhandler.h (fhandler_pipe::get_popen_pid): Define new function. * fhandler.h (fhandler_pipe::set_popen_pid): Ditto. * pipe.cc (fhandler_pipe::fhandler_pipe): Zero popen_pid. (fhandler_pipe::dup): Ditto. * spawn.cc (handle): Change second argument to bool. (spawn_guts): Accept __stdin/__stdout arguments and set them appropriately in child_info structure and in STARTUPINFO structure. * syscalls.cc (popen): New cygwin-specific implementation using spawn. (pclose): Ditto. * winsup.h (spawn_guts): Accommodate new arguments for spawn_guts. * fhandler.cc (fhandler_base::set_no_inheritance): Make second arg a bool. * fhandler.h (fhandler_base::set_no_inheritance): Ditto for declaration. * child_info.h (child_info::msv_count): Rename from the now-inappropriate "zero". (child_info_spawn::filler): Add filler to work around Vista bug. (child_info_fork::filler): Ditto. * dcrt0.cc (get_cygwin_startup_info): Remove "zero" check since it is now always filled out. * fork.cc (frok::parent): Move ch.zero manipulation to constructor. * spawn.cc (spawn_guts): Ditto. Remove _ch wrapper. * sigproc.cc (child_info::child_info): Initialize starter[]. * shared.cc (shared_info::heap_slop_size): Remove noisy system_printfs. * shared_info.h (CURR_SHARED_MAGIC): Regenerate.
2006-12-12 02:55:29 +08:00
ftp->set_popen_pid (0);
int res = 0;
WaitForSingleObject (hdl_cnt_mtx, INFINITE);
if (fhandler_base::dup (child, flags))
Preliminary change to make fifos/pipes interruptible and fifos reliable. * dtable.cc (dtable::find_fifo): Eliminate definition. * dtable.h (dtable::find_fifo): Ditto for declaration. * fhandler.cc (fhandler_base::raw_read): Remove pipe-specific stuff. (fhandler_base::fhandler_base): Ditto. (fhandler_base::close): Handle overlapped I/O structure if appropriate. (fhandler_base::dup): Ditto. (fhandler_base::fork_fixup): Ditto. (fhandler_base::setup_overlapped): Define new function. (fhandler_base::destroy_overlapped): Ditto. (fhandler_base::wait_overlapped): Ditto. (fhandler_base::read_overlapped): Ditto. (fhandler_base::write_overlapped): Ditto. * fhandler.h (fhandler_base::get_overlapped): Declare new function. (fhandler_base::setup_overlapped): Ditto. (fhandler_base::destroy_overlapped): Ditto. (fhandler_base::wait_overlapped): Ditto. (fhandler_base::read_overlapped): Ditto. (fhandler_base::write_overlapped): Ditto. (fhandler_base::get_guard): Eliminate. (fhandler_pipe::*): Rework to eliminate most Win9x related cruft, removing many variables and defining a new overlapped capability. (fhandler_fifo::*): Ditto. (fifo_state): Declare new enum. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove old Win9x stuff. Initialize overlapped handle to NULL. (fhandler_fifo::set_use): Eliminate. (fhandler_fifo::open_nonserver): Define. (fhandler_fifo::open): Rework to use named pipes and overlapped I/O. (fhandler_fifo::wait): Define new function to wait for named pipe connection. (fhandler_fifo::read): Rework to use wait() and new overlapped I/O functionality. (fhandler_fifo::write): Ditto. (fhandler_fifo::dup): Eliminate. * pinfo.cc (commune_process): Remove fifo handling. (_pinfo::commune_request): Ditto. * pinfo.h (picom): Ditto. * pipe.cc (fhandler_pipe::fhandler_pipe): Remove Win9x stuff. Initialize overlapped handle to NULL. (fhandler_pipe::open): Eliminate Win9x stuff. (fhandler_pipe::set_close_on_exec): Eliminate. (read_pipe): Eliminate. (fhandler_pipe::close): Ditto. (fhandler_pipe::fixup_after_exec): Ditto. (fhandler_pipe::fixup_in_child): Ditto. (fhandler_pipe::read): Rework to use overlapped I/O. (fhandler_pipe::write): New function using overlapped I/O. (fhandler_pipe::dup): Rework to eliminate Win9x stuff. (fhandler_pipe::create_selectable): Rework to eliminate Win9x and use overlapped I/O. * select.cc (peek_pipe): Rework to eliminate Win9x stuff and use overlapped I/O. (fhandler_base::ready_for_read): Ditto.
2007-07-08 01:00:33 +08:00
res = -1;
else if (read_mtx &&
!DuplicateHandle (GetCurrentProcess (), read_mtx,
GetCurrentProcess (), &ftp->read_mtx,
0, !(flags & O_CLOEXEC), DUPLICATE_SAME_ACCESS))
{
__seterrno ();
ftp->close ();
res = -1;
}
else if (select_sem &&
!DuplicateHandle (GetCurrentProcess (), select_sem,
GetCurrentProcess (), &ftp->select_sem,
0, !(flags & O_CLOEXEC), DUPLICATE_SAME_ACCESS))
{
__seterrno ();
ftp->close ();
res = -1;
}
else if (query_hdl &&
!DuplicateHandle (GetCurrentProcess (), query_hdl,
GetCurrentProcess (), &ftp->query_hdl,
0, !(flags & O_CLOEXEC), DUPLICATE_SAME_ACCESS))
{
__seterrno ();
ftp->close ();
res = -1;
}
else if (!DuplicateHandle (GetCurrentProcess (), hdl_cnt_mtx,
GetCurrentProcess (), &ftp->hdl_cnt_mtx,
0, !(flags & O_CLOEXEC), DUPLICATE_SAME_ACCESS))
{
__seterrno ();
ftp->close ();
res = -1;
}
ReleaseMutex (hdl_cnt_mtx);
debug_printf ("res %d", res);
return res;
}
int
fhandler_pipe::close ()
{
if (select_sem)
{
release_select_sem ("close");
CloseHandle (select_sem);
}
if (read_mtx)
CloseHandle (read_mtx);
WaitForSingleObject (hdl_cnt_mtx, INFINITE);
if (query_hdl)
CloseHandle (query_hdl);
int ret = fhandler_base::close ();
ReleaseMutex (hdl_cnt_mtx);
CloseHandle (hdl_cnt_mtx);
if (query_hdl_proc)
CloseHandle (query_hdl_proc);
return ret;
}
#define PIPE_INTRO "\\\\.\\pipe\\cygwin-"
/* Create a pipe, and return handles to the read and write ends,
just like CreatePipe, but ensure that the write end permits
FILE_READ_ATTRIBUTES access, on later versions of win32 where
this is supported. This access is needed by NtQueryInformationFile,
which is used to implement select and nonblocking writes.
Note that the return value is either 0 or GetLastError,
unlike CreatePipe, which returns a bool for success or failure. */
DWORD
fhandler_pipe::create (LPSECURITY_ATTRIBUTES sa_ptr, PHANDLE r, PHANDLE w,
2016-01-11 19:35:41 +08:00
DWORD psize, const char *name, DWORD open_mode,
int64_t *unique_id)
{
/* Default to error. */
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
if (r)
*r = NULL;
if (w)
*w = NULL;
/* Ensure that there is enough pipe buffer space for atomic writes. */
if (!psize)
* errno.cc (errmap): Change mapping of NO_SYSTEM_RESOURCES to EFBIG. * fhandler.cc (MAX_OVERLAPPED_WRITE_LEN): New constant. (MIN_OVERLAPPED_WRITE_LEN): Ditto. (fhandler_base_overlapped::close): Accommodate change in arguments to wait_overlapped. (fhandler_base_overlapped::setup_overlapped): Add __stdcall and regparm modifiers. (fhandler_base_overlapped::destroy_overlapped): Ditto. (fhandler_base_overlapped::has_ongoing_io): Ditto. (fhandler_base_overlapped::wait_overlapped): Modify to return an enum returning various states. Accept nonblocking parameter. (fhandler_base_overlapped::read_overlapped): Add __stdcall and regparm modifiers. Rework to attempt to be smarter about reacting to states returned by wait_overlapped. (fhandler_base_overlapped::write_overlapped): Ditto. Add fallback option for when wait_overlapped detects that smaller chunks must be written. (fhandler_base_overlapped::write_overlapped_fallback): Ditto. * fhandler.h (DEFAULT_PIPEBUFSIZE): Move definition here from pipe.cc. (fhandler_base::has_ongoing_io): Define with __stdcall and regparm modifiers. (fhandler_base_overlapped::wait_return): New enum. (fhandler_base_overlapped::max_atomic_write): New variable. (fhandler_base_overlapped:: wait_overlapped): Accommodate changes mentioned above to arguments and modifiers. (fhandler_base_overlapped::setup_overlapped): Ditto for modifiers. (fhandler_base_overlapped::read_overlapped): Ditto. (fhandler_base_overlapped::write_overlapped): Ditto. (fhandler_base_overlapped::destroy_overlapped): Ditto. (fhandler_base_overlapped::has_ongoing_io): Ditto. (fhandler_base_overlapped::fhandler_base_overlapped): Zero max_atomic_write. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Set max_atomic_write to the size of the DEFAULT_PIPEBUFSIZE. (fhandler_fifo::wait): Accommodate change in arguments to wait_overlapped. * pipe.cc (fhandler_pipe::fhandler_pipe): Set max_atomic_write to the size of the DEFAULT_PIPEBUFSIZE. (fhandler_pipe::create_selectable): Allow minimum size of DEFAULT_PIPEBUFSIZE. (DEFAULT_PIPEBUFSIZE): Delete here, move to fhandler.h.
2011-03-10 00:47:44 +08:00
psize = DEFAULT_PIPEBUFSIZE;
* cygprops.h: New file. * dtable.cc (handle_to_fn): Add check for correct installation_key string in object name for pipes and ttys. * external.cc (cygwin_internal): Add CW_GET_INSTKEY to allow fetching the installation_key from cygserver. * fhandler_fifo.cc (fhandler_fifo::fifo_name): Add installation_key to fifo name. * globals.cc: Include cygprops.h. (_RDATA): Move slightly and add comment. (cygwin_props): Define. * mount.cc (mount_info::init): Accommodate the fact that installation_root is now a global variable in DLL common shared memory, rather than a member of cygwin_shared. * pipe.cc (fhandler_pipe::create_selectable): Add installation_key to pipe name. * shared.cc (installation_root): Define here for storage in DLL common shared memory. (installation_key): Ditto. (installation_key_buf): Ditto. (init_installation_root): Convert from shared_info method to ordinary function. Add initializing installation_key. Invalidate installation_key depending of value of disable_key property. Add comment to explain. (get_shared_parent_dir): Add installation_key to directory name. (get_session_parent_dir): Ditto. (shared_info::initialize): Move call to init_installation_root from here... (memory_init): ...to here. Add debug output to print installation root and installation key. Add comment to explain why. * shared_info.h (SHARED_INFO_CB): Recalculate. (CURR_SHARED_MAGIC): Ditto. (class shared_info): Remove definition of installation_root and declaration of init_installation_root. (init_installation_root): Declare. (installation_root): Declare. (installation_key): Declare. * uinfo.cc (pwdgrp::load): Accommodate the fact that installation_root is now a global variable in DLL common shared memory. * include/cygwin/version.h: Bump API minor number. (CYGWIN_INFO_INSTALLATIONS_NAME): Add. * include/sys/cygwin.h (cygwin_getinfo_types): Add CW_GET_INSTKEY.
2009-10-31 21:24:06 +08:00
char pipename[MAX_PATH];
size_t len = __small_sprintf (pipename, PIPE_INTRO "%S-",
&cygheap->installation_key);
DWORD pipe_mode = PIPE_READMODE_BYTE | PIPE_REJECT_REMOTE_CLIENTS;
if (!name)
pipe_mode |= pipe_byte ? PIPE_TYPE_BYTE : PIPE_TYPE_MESSAGE;
else
pipe_mode |= PIPE_TYPE_MESSAGE;
* cygprops.h: New file. * dtable.cc (handle_to_fn): Add check for correct installation_key string in object name for pipes and ttys. * external.cc (cygwin_internal): Add CW_GET_INSTKEY to allow fetching the installation_key from cygserver. * fhandler_fifo.cc (fhandler_fifo::fifo_name): Add installation_key to fifo name. * globals.cc: Include cygprops.h. (_RDATA): Move slightly and add comment. (cygwin_props): Define. * mount.cc (mount_info::init): Accommodate the fact that installation_root is now a global variable in DLL common shared memory, rather than a member of cygwin_shared. * pipe.cc (fhandler_pipe::create_selectable): Add installation_key to pipe name. * shared.cc (installation_root): Define here for storage in DLL common shared memory. (installation_key): Ditto. (installation_key_buf): Ditto. (init_installation_root): Convert from shared_info method to ordinary function. Add initializing installation_key. Invalidate installation_key depending of value of disable_key property. Add comment to explain. (get_shared_parent_dir): Add installation_key to directory name. (get_session_parent_dir): Ditto. (shared_info::initialize): Move call to init_installation_root from here... (memory_init): ...to here. Add debug output to print installation root and installation key. Add comment to explain why. * shared_info.h (SHARED_INFO_CB): Recalculate. (CURR_SHARED_MAGIC): Ditto. (class shared_info): Remove definition of installation_root and declaration of init_installation_root. (init_installation_root): Declare. (installation_root): Declare. (installation_key): Declare. * uinfo.cc (pwdgrp::load): Accommodate the fact that installation_root is now a global variable in DLL common shared memory. * include/cygwin/version.h: Bump API minor number. (CYGWIN_INFO_INSTALLATIONS_NAME): Add. * include/sys/cygwin.h (cygwin_getinfo_types): Add CW_GET_INSTKEY.
2009-10-31 21:24:06 +08:00
if (!name || (open_mode & PIPE_ADD_PID))
{
len += __small_sprintf (pipename + len, "%u-", GetCurrentProcessId ());
open_mode &= ~PIPE_ADD_PID;
}
if (name)
len += __small_sprintf (pipename + len, "%s", name);
open_mode |= PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE;
/* Retry CreateNamedPipe as long as the pipe name is in use.
Retrying will probably never be necessary, but we want
to be as robust as possible. */
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
DWORD err = 0;
while (r && !*r)
{
static volatile ULONG pipe_unique_id;
if (!name)
2016-01-11 19:35:41 +08:00
{
LONG id = InterlockedIncrement ((LONG *) &pipe_unique_id);
__small_sprintf (pipename + len, "pipe-%p", id);
if (unique_id)
*unique_id = ((int64_t) id << 32 | GetCurrentProcessId ());
}
2013-04-23 17:44:36 +08:00
debug_printf ("name %s, size %u, mode %s", pipename, psize,
(pipe_mode & PIPE_TYPE_MESSAGE)
? "PIPE_TYPE_MESSAGE" : "PIPE_TYPE_BYTE");
/* Use CreateNamedPipe instead of CreatePipe, because the latter
returns a write handle that does not permit FILE_READ_ATTRIBUTES
access, on versions of win32 earlier than WinXP SP2.
CreatePipe also stupidly creates a full duplex pipe, which is
a waste, since only a single direction is actually used.
It's important to only allow a single instance, to ensure that
the pipe was not created earlier by some other process, even if
2013-04-23 17:44:36 +08:00
the pid has been reused.
Note that the write side of the pipe is opened as PIPE_TYPE_MESSAGE.
This *seems* to more closely mimic Linux pipe behavior and is
definitely required for pty handling since fhandler_pty_master
writes to the pipe in chunks, terminated by newline when CANON mode
is specified. */
*r = CreateNamedPipe (pipename, open_mode, pipe_mode, 1, psize,
psize, NMPWAIT_USE_DEFAULT_WAIT, sa_ptr);
if (*r != INVALID_HANDLE_VALUE)
{
debug_printf ("pipe read handle %p", *r);
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
err = 0;
break;
}
err = GetLastError ();
switch (err)
{
case ERROR_PIPE_BUSY:
/* The pipe is already open with compatible parameters.
Pick a new name and retry. */
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
debug_printf ("pipe busy", !name ? ", retrying" : "");
if (!name)
*r = NULL;
break;
case ERROR_ACCESS_DENIED:
/* The pipe is already open with incompatible parameters.
Pick a new name and retry. */
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
debug_printf ("pipe access denied%s", !name ? ", retrying" : "");
if (!name)
*r = NULL;
break;
default:
Preliminary change to make fifos/pipes interruptible and fifos reliable. * dtable.cc (dtable::find_fifo): Eliminate definition. * dtable.h (dtable::find_fifo): Ditto for declaration. * fhandler.cc (fhandler_base::raw_read): Remove pipe-specific stuff. (fhandler_base::fhandler_base): Ditto. (fhandler_base::close): Handle overlapped I/O structure if appropriate. (fhandler_base::dup): Ditto. (fhandler_base::fork_fixup): Ditto. (fhandler_base::setup_overlapped): Define new function. (fhandler_base::destroy_overlapped): Ditto. (fhandler_base::wait_overlapped): Ditto. (fhandler_base::read_overlapped): Ditto. (fhandler_base::write_overlapped): Ditto. * fhandler.h (fhandler_base::get_overlapped): Declare new function. (fhandler_base::setup_overlapped): Ditto. (fhandler_base::destroy_overlapped): Ditto. (fhandler_base::wait_overlapped): Ditto. (fhandler_base::read_overlapped): Ditto. (fhandler_base::write_overlapped): Ditto. (fhandler_base::get_guard): Eliminate. (fhandler_pipe::*): Rework to eliminate most Win9x related cruft, removing many variables and defining a new overlapped capability. (fhandler_fifo::*): Ditto. (fifo_state): Declare new enum. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove old Win9x stuff. Initialize overlapped handle to NULL. (fhandler_fifo::set_use): Eliminate. (fhandler_fifo::open_nonserver): Define. (fhandler_fifo::open): Rework to use named pipes and overlapped I/O. (fhandler_fifo::wait): Define new function to wait for named pipe connection. (fhandler_fifo::read): Rework to use wait() and new overlapped I/O functionality. (fhandler_fifo::write): Ditto. (fhandler_fifo::dup): Eliminate. * pinfo.cc (commune_process): Remove fifo handling. (_pinfo::commune_request): Ditto. * pinfo.h (picom): Ditto. * pipe.cc (fhandler_pipe::fhandler_pipe): Remove Win9x stuff. Initialize overlapped handle to NULL. (fhandler_pipe::open): Eliminate Win9x stuff. (fhandler_pipe::set_close_on_exec): Eliminate. (read_pipe): Eliminate. (fhandler_pipe::close): Ditto. (fhandler_pipe::fixup_after_exec): Ditto. (fhandler_pipe::fixup_in_child): Ditto. (fhandler_pipe::read): Rework to use overlapped I/O. (fhandler_pipe::write): New function using overlapped I/O. (fhandler_pipe::dup): Rework to eliminate Win9x stuff. (fhandler_pipe::create_selectable): Rework to eliminate Win9x and use overlapped I/O. * select.cc (peek_pipe): Rework to eliminate Win9x stuff and use overlapped I/O. (fhandler_base::ready_for_read): Ditto.
2007-07-08 01:00:33 +08:00
{
err = GetLastError ();
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
debug_printf ("failed, %E");
Preliminary change to make fifos/pipes interruptible and fifos reliable. * dtable.cc (dtable::find_fifo): Eliminate definition. * dtable.h (dtable::find_fifo): Ditto for declaration. * fhandler.cc (fhandler_base::raw_read): Remove pipe-specific stuff. (fhandler_base::fhandler_base): Ditto. (fhandler_base::close): Handle overlapped I/O structure if appropriate. (fhandler_base::dup): Ditto. (fhandler_base::fork_fixup): Ditto. (fhandler_base::setup_overlapped): Define new function. (fhandler_base::destroy_overlapped): Ditto. (fhandler_base::wait_overlapped): Ditto. (fhandler_base::read_overlapped): Ditto. (fhandler_base::write_overlapped): Ditto. * fhandler.h (fhandler_base::get_overlapped): Declare new function. (fhandler_base::setup_overlapped): Ditto. (fhandler_base::destroy_overlapped): Ditto. (fhandler_base::wait_overlapped): Ditto. (fhandler_base::read_overlapped): Ditto. (fhandler_base::write_overlapped): Ditto. (fhandler_base::get_guard): Eliminate. (fhandler_pipe::*): Rework to eliminate most Win9x related cruft, removing many variables and defining a new overlapped capability. (fhandler_fifo::*): Ditto. (fifo_state): Declare new enum. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove old Win9x stuff. Initialize overlapped handle to NULL. (fhandler_fifo::set_use): Eliminate. (fhandler_fifo::open_nonserver): Define. (fhandler_fifo::open): Rework to use named pipes and overlapped I/O. (fhandler_fifo::wait): Define new function to wait for named pipe connection. (fhandler_fifo::read): Rework to use wait() and new overlapped I/O functionality. (fhandler_fifo::write): Ditto. (fhandler_fifo::dup): Eliminate. * pinfo.cc (commune_process): Remove fifo handling. (_pinfo::commune_request): Ditto. * pinfo.h (picom): Ditto. * pipe.cc (fhandler_pipe::fhandler_pipe): Remove Win9x stuff. Initialize overlapped handle to NULL. (fhandler_pipe::open): Eliminate Win9x stuff. (fhandler_pipe::set_close_on_exec): Eliminate. (read_pipe): Eliminate. (fhandler_pipe::close): Ditto. (fhandler_pipe::fixup_after_exec): Ditto. (fhandler_pipe::fixup_in_child): Ditto. (fhandler_pipe::read): Rework to use overlapped I/O. (fhandler_pipe::write): New function using overlapped I/O. (fhandler_pipe::dup): Rework to eliminate Win9x stuff. (fhandler_pipe::create_selectable): Rework to eliminate Win9x and use overlapped I/O. * select.cc (peek_pipe): Rework to eliminate Win9x stuff and use overlapped I/O. (fhandler_base::ready_for_read): Ditto.
2007-07-08 01:00:33 +08:00
}
}
}
if (err)
{
*r = NULL;
return err;
}
if (!w)
debug_printf ("pipe write handle NULL");
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
else
{
debug_printf ("CreateFile: name %s", pipename);
/* Open the named pipe for writing.
Be sure to permit FILE_READ_ATTRIBUTES access. */
DWORD access = GENERIC_WRITE | FILE_READ_ATTRIBUTES;
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
if ((open_mode & PIPE_ACCESS_DUPLEX) == PIPE_ACCESS_DUPLEX)
access |= GENERIC_READ | FILE_WRITE_ATTRIBUTES;
*w = CreateFile (pipename, access, 0, sa_ptr, OPEN_EXISTING,
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
open_mode & FILE_FLAG_OVERLAPPED, 0);
if (!*w || *w == INVALID_HANDLE_VALUE)
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
{
/* Failure. */
DWORD err = GetLastError ();
debug_printf ("CreateFile failed, r %p, %E", r);
if (r)
CloseHandle (*r);
*w = NULL;
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
return err;
}
debug_printf ("pipe write handle %p", *w);
* fhandler.h (fhandler_pipe::create_selectable): Remove optional argument, take an options argument for CreateNamedPipe/CreateFile. Change handle arguments to expect pointers. (fhandler_fifo::fifo_state): Delete. (fhandler_fifo::dummy_client): Ditto. (fhandler_fifo::open_nonserver): Ditto. (fhandler_fifo::wait_state): Ditto. (fhandler_fifo::raw_write): Ditto. (fhandler_fifo::read_ready): New field. (fhandler_fifo::write_ready): Ditto. (fhandler_fifo::wait): Modify argument. (fhandler_fifo::fifo_name): Add a new argument. (fhandler_fifo::fixup_after_fork): New function. * fhandler_fifo.cc (fhandler_fifo::fhandler_fifo): Remove initialization of expunged elements. Initialize new handles to NULL. (fhandler_fifo::open_nonserver): Delete. (fnevent): New macro for creating a named event. (fnpipe): New macro for creating a unique named pipe name. (create_pipe): New macro for simplification of named pipe creation. (fhandler_fifo::fifo_name): Use new argument when creating a shared name. (fhandler_fifo::open): Rewrite. Use events to synchronize. (pure_debug_printf): New macro, active only when DEBUGGING. (fhandler_fifo::wait): Rewrite to wait for new fifo events which are supplied as a parameter. (fhandler_fifo::raw_read): Rewrite to use handle mechanism to detect client-side disconnect. (fhandler_fifo::raw_write): Delete. (fhandler_fifo::close): Remove accommodations for expunged fields. Close event handles. (fhandler_fifo::dup): Remove accommodations for expunged fields. Duplicate event handles. (fhandler_fifo::fixup_after_fork): New function. Perform fixups on event handles. (fhandler_fifo::set_close_on_exec): Remove accommodations for expunged fields. Set inheritance for new handle fields. * miscfuncs.cc (CreatePipeOverlapped): Accommodate changes in fhandler_pipe::create_selectable. * tty.cc (tty::not_allocated): Ditto. * pipe.cc (fhandler_pipe::create): Ditto. (fhandler_pipe::create_selectable): Accept an extra open_mode argument. Pass arguments by reference and allow opening one end of the pipe at a time. * sys/strace.h (debug_only_printf): Define new macro which calls debug_printf only when DEBUGGING is defined.
2011-10-30 12:50:36 +08:00
}
/* Success. */
return 0;
}
inline static bool
is_running_as_service (void)
{
return check_token_membership (well_known_service_sid)
|| cygheap->user.saved_sid () == well_known_system_sid;
}
/* The next version of fhandler_pipe::create used to call the previous
version. But the read handle created by the latter doesn't have
FILE_WRITE_ATTRIBUTES access unless the pipe is created with
PIPE_ACCESS_DUPLEX, and it doesn't seem possible to add that access
right. This causes set_pipe_non_blocking to fail.
To fix this we will define a helper function 'nt_create' that is
similar to the above fhandler_pipe::create but uses
NtCreateNamedPipeFile instead of CreateNamedPipe; this gives more
flexibility in setting the access rights. We will use this helper
function in the version of fhandler_pipe::create below, which
suffices for all of our uses of set_pipe_non_blocking. For
simplicity, nt_create will omit the 'open_mode' and 'name'
parameters, which aren't needed for our purposes. */
static int nt_create (LPSECURITY_ATTRIBUTES, HANDLE &, HANDLE &, DWORD,
int64_t *);
int
fhandler_pipe::create (fhandler_pipe *fhs[2], unsigned psize, int mode)
2000-02-18 03:38:33 +08:00
{
HANDLE r, w;
* cygwin.din (dup3): Export. (pipe2): Export. * dtable.cc (dtable::dup_worker): Take additional flags parameter. Handle O_CLOEXEC flag. (dtable::dup3): Rename from dup2. Take additional flags parameter. Check for valid flags. Drop check for newfd == oldfd. * dtable.h (dtable::dup_worker): Add flags parameter. (dtable::dup3): Rename from dup2. * fcntl.cc (fcntl64): Add F_DUPFD_CLOEXEC case. * fhandler.h (fhandler_mailslot::get_object_attr): Add flags parameter. * fhandler.cc (fhandler_base::open): Use security attribute with inheritance according to setting of O_CLOEXEC flag. * fhandler_console.cc (fhandler_console::open): Ditto. * fhandler_fifo.cc (sec_user_cloexec): New inline function to create security attribute with inheritance according to setting of O_CLOEXEC flag. (fhandler_fifo::open): Call sec_user_cloexec to fetch security attribute. (fhandler_fifo::wait): Ditto. * fhandler_mem.cc (fhandler_dev_mem::open): Ditto. * fhandler_mailslot.cc (fhandler_mailslot::get_object_attr): Take additional flags parameter. Use security attribute with inheritance according to setting of O_CLOEXEC flag. (fhandler_mailslot::open): Call get_object_attr with flags parameter. * fhandler_registry.cc (fhandler_registry::open): Call set_close_on_exec on real handles to accommodate O_CLOEXEC flag. * fhandler_tty.cc (fhandler_tty_slave::open): Ditto. * fhandler_tape.cc: Create mutex with inheritance according to setting of O_CLOEXEC flag. * pipe.cc: Replace usage of O_NOINHERIT with O_CLOEXEC. (fhandler_pipe::init): Simplify setting close_on_exec flag. (fhandler_pipe::open): Remove setting close_on_exec flag. (fhandler_pipe::create): Use security attribute with inheritance according to setting of O_CLOEXEC flag. (pipe2): New exported function. * posix_ipc.cc: Throughout, open backing files with O_CLOEXEC flag to follow POSIX semantics. * security.h (sec_none_cloexec): New define. * syscalls.cc (dup): Add missing extern "C" qualifier. Accommodate renaming of dtable::dup2 to dtable::dup3. (dup2): Ditto. Check newfd == oldfd here. (dup3): New function. Check newfd == oldfd here. (open): Set close_on_exec flag according to O_CLOEXEC flag before calling fhandler->open. * include/cygwin/version.h (CYGWIN_VERSION_API_MINOR): Bump.
2010-01-15 02:46:02 +08:00
SECURITY_ATTRIBUTES *sa = sec_none_cloexec (mode);
int res = -1;
2016-01-11 19:35:41 +08:00
int64_t unique_id;
2000-02-18 03:38:33 +08:00
int ret = nt_create (sa, r, w, psize, &unique_id);
if (ret)
{
__seterrno_from_win_error (ret);
goto out;
2000-02-18 03:38:33 +08:00
}
if ((fhs[0] = (fhandler_pipe *) build_fh_dev (*piper_dev)) == NULL)
goto err_close_rw_handle;
if ((fhs[1] = (fhandler_pipe *) build_fh_dev (*pipew_dev)) == NULL)
goto err_delete_fhs0;
mode |= mode & O_TEXT ?: O_BINARY;
fhs[0]->init (r, FILE_CREATE_PIPE_INSTANCE | GENERIC_READ, mode, unique_id);
fhs[1]->init (w, FILE_CREATE_PIPE_INSTANCE | GENERIC_WRITE, mode, unique_id);
/* For the read side of the pipe, add a mutex. See raw_read for the
usage. */
fhs[0]->read_mtx = CreateMutexW (sa, FALSE, NULL);
if (!fhs[0]->read_mtx)
goto err_delete_fhs1;
fhs[0]->select_sem = CreateSemaphore (sa, 0, INT32_MAX, NULL);
if (!fhs[0]->select_sem)
goto err_close_read_mtx;
if (!DuplicateHandle (GetCurrentProcess (), fhs[0]->select_sem,
GetCurrentProcess (), &fhs[1]->select_sem,
0, sa->bInheritHandle, DUPLICATE_SAME_ACCESS))
goto err_close_select_sem0;
if (is_running_as_service () &&
!DuplicateHandle (GetCurrentProcess (), r,
GetCurrentProcess (), &fhs[1]->query_hdl,
FILE_READ_DATA, sa->bInheritHandle, 0))
goto err_close_select_sem1;
fhs[0]->hdl_cnt_mtx = CreateMutexW (sa, FALSE, NULL);
if (!fhs[0]->hdl_cnt_mtx)
goto err_close_query_hdl;
if (!DuplicateHandle (GetCurrentProcess (), fhs[0]->hdl_cnt_mtx,
GetCurrentProcess (), &fhs[1]->hdl_cnt_mtx,
0, sa->bInheritHandle, DUPLICATE_SAME_ACCESS))
goto err_close_hdl_cnt_mtx0;
res = 0;
goto out;
err_close_hdl_cnt_mtx0:
CloseHandle (fhs[0]->hdl_cnt_mtx);
err_close_query_hdl:
if (fhs[1]->query_hdl)
CloseHandle (fhs[1]->query_hdl);
err_close_select_sem1:
CloseHandle (fhs[1]->select_sem);
err_close_select_sem0:
CloseHandle (fhs[0]->select_sem);
err_close_read_mtx:
CloseHandle (fhs[0]->read_mtx);
err_delete_fhs1:
delete fhs[1];
err_delete_fhs0:
delete fhs[0];
err_close_rw_handle:
NtClose (r);
NtClose (w);
out:
debug_printf ("%R = pipe([%p, %p], %d, %y)",
res, fhs[0], fhs[1], psize, mode);
return res;
2000-02-18 03:38:33 +08:00
}
static int
nt_create (LPSECURITY_ATTRIBUTES sa_ptr, HANDLE &r, HANDLE &w,
DWORD psize, int64_t *unique_id)
{
NTSTATUS status;
HANDLE npfsh;
ACCESS_MASK access;
OBJECT_ATTRIBUTES attr;
IO_STATUS_BLOCK io;
LARGE_INTEGER timeout;
/* Default to error. */
r = NULL;
w = NULL;
status = fhandler_base::npfs_handle (npfsh);
if (!NT_SUCCESS (status))
{
__seterrno_from_nt_status (status);
return GetLastError ();
}
/* Ensure that there is enough pipe buffer space for atomic writes. */
if (!psize)
psize = DEFAULT_PIPEBUFSIZE;
UNICODE_STRING pipename;
WCHAR pipename_buf[MAX_PATH];
size_t len = __small_swprintf (pipename_buf, L"%S-%u-",
&cygheap->installation_key,
GetCurrentProcessId ());
access = GENERIC_READ | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE;
access |= FILE_WRITE_EA; /* Add this right as a marker of cygwin read pipe */
ULONG pipe_type = pipe_byte ? FILE_PIPE_BYTE_STREAM_TYPE
: FILE_PIPE_MESSAGE_TYPE;
/* Retry NtCreateNamedPipeFile as long as the pipe name is in use.
Retrying will probably never be necessary, but we want
to be as robust as possible. */
DWORD err = 0;
while (!r)
{
static volatile ULONG pipe_unique_id;
LONG id = InterlockedIncrement ((LONG *) &pipe_unique_id);
__small_swprintf (pipename_buf + len, L"pipe-nt-%p", id);
if (unique_id)
*unique_id = ((int64_t) id << 32 | GetCurrentProcessId ());
debug_printf ("name %W, size %u, mode %s", pipename_buf, psize,
(pipe_type & FILE_PIPE_MESSAGE_TYPE)
? "PIPE_TYPE_MESSAGE" : "PIPE_TYPE_BYTE");
RtlInitUnicodeString (&pipename, pipename_buf);
InitializeObjectAttributes (&attr, &pipename,
sa_ptr->bInheritHandle ? OBJ_INHERIT : 0,
npfsh, sa_ptr->lpSecurityDescriptor);
timeout.QuadPart = -500000;
status = NtCreateNamedPipeFile (&r, access, &attr, &io,
FILE_SHARE_READ | FILE_SHARE_WRITE,
FILE_CREATE, 0, pipe_type,
FILE_PIPE_BYTE_STREAM_MODE,
0, 1, psize, psize, &timeout);
if (NT_SUCCESS (status))
{
debug_printf ("pipe read handle %p", r);
err = 0;
break;
}
switch (status)
{
case STATUS_PIPE_BUSY:
case STATUS_INSTANCE_NOT_AVAILABLE:
case STATUS_PIPE_NOT_AVAILABLE:
/* The pipe is already open with compatible parameters.
Pick a new name and retry. */
debug_printf ("pipe busy, retrying");
r = NULL;
break;
case STATUS_ACCESS_DENIED:
/* The pipe is already open with incompatible parameters.
Pick a new name and retry. */
debug_printf ("pipe access denied, retrying");
r = NULL;
break;
default:
{
__seterrno_from_nt_status (status);
err = GetLastError ();
debug_printf ("failed, %E");
r = NULL;
}
}
}
if (err)
{
r = NULL;
return err;
}
debug_printf ("NtOpenFile: name %S", &pipename);
access = GENERIC_WRITE | FILE_READ_ATTRIBUTES | SYNCHRONIZE;
status = NtOpenFile (&w, access, &attr, &io, 0, 0);
if (!NT_SUCCESS (status))
{
DWORD err = GetLastError ();
debug_printf ("NtOpenFile failed, r %p, %E", r);
if (r)
NtClose (r);
w = NULL;
return err;
}
/* Success. */
return 0;
}
/* Called by dtable::init_std_file_from_handle for stdio handles
inherited from non-Cygwin processes. */
void
fhandler_pipe::set_pipe_buf_size ()
{
NTSTATUS status;
IO_STATUS_BLOCK io;
FILE_PIPE_LOCAL_INFORMATION fpli;
status = NtQueryInformationFile (get_handle (), &io, &fpli, sizeof fpli,
FilePipeLocalInformation);
if (NT_SUCCESS (status))
pipe_buf_size = fpli.InboundQuota;
}
int
fhandler_pipe::ioctl (unsigned int cmd, void *p)
{
int n;
switch (cmd)
{
case FIONREAD:
if (get_device () == FH_PIPEW)
{
set_errno (EINVAL);
return -1;
}
if (!PeekNamedPipe (get_handle (), NULL, 0, NULL, (DWORD *) &n, NULL))
{
__seterrno ();
return -1;
}
break;
default:
return fhandler_base::ioctl (cmd, p);
break;
}
*(int *) p = n;
return 0;
}
int
fhandler_pipe::fcntl (int cmd, intptr_t arg)
{
if (cmd != F_SETFL)
return fhandler_base::fcntl (cmd, arg);
const bool was_nonblocking = is_nonblocking ();
int res = fhandler_base::fcntl (cmd, arg);
const bool now_nonblocking = is_nonblocking ();
if (now_nonblocking != was_nonblocking)
set_pipe_non_blocking (now_nonblocking);
return res;
}
2016-01-11 19:35:41 +08:00
int __reg2
fhandler_pipe::fstat (struct stat *buf)
{
int ret = fhandler_base::fstat (buf);
if (!ret)
{
buf->st_dev = FH_PIPE;
if (!(buf->st_ino = get_plain_ino ()))
sscanf (get_name (), "/proc/%*d/fd/pipe:[%llu]",
2016-01-11 19:35:41 +08:00
(long long *) &buf->st_ino);
}
return ret;
}
int __reg2
fhandler_pipe::fstatvfs (struct statvfs *sfs)
{
set_errno (EBADF);
return -1;
}
HANDLE
fhandler_pipe::temporary_query_hdl ()
{
if (get_dev () != FH_PIPEW)
return NULL;
ULONG len;
NTSTATUS status;
tmp_pathbuf tp;
OBJECT_NAME_INFORMATION *ntfn = (OBJECT_NAME_INFORMATION *) tp.w_get ();
/* Try process handle opened and pipe handle value cached first
in order to reduce overhead. */
if (query_hdl_proc && query_hdl_value)
{
HANDLE h;
if (!DuplicateHandle (query_hdl_proc, query_hdl_value,
GetCurrentProcess (), &h, FILE_READ_DATA, 0, 0))
goto cache_err;
/* Check name */
status = NtQueryObject (h, ObjectNameInformation, ntfn, 65536, &len);
if (!NT_SUCCESS (status) || !ntfn->Name.Buffer)
goto hdl_err;
ntfn->Name.Buffer[ntfn->Name.Length / sizeof (WCHAR)] = L'\0';
uint64_t key;
DWORD pid;
LONG id;
if (swscanf (ntfn->Name.Buffer,
L"\\Device\\NamedPipe\\%llx-%u-pipe-nt-0x%x",
&key, &pid, &id) == 3 &&
key == pipename_key && pid == pipename_pid && id == pipename_id)
return h;
hdl_err:
CloseHandle (h);
cache_err:
CloseHandle (query_hdl_proc);
query_hdl_proc = NULL;
query_hdl_value = NULL;
}
status = NtQueryObject (get_handle (), ObjectNameInformation, ntfn,
65536, &len);
if (!NT_SUCCESS (status) || !ntfn->Name.Buffer)
return NULL; /* Non cygwin pipe? */
WCHAR name[MAX_PATH];
int namelen = min (ntfn->Name.Length / sizeof (WCHAR), MAX_PATH-1);
memcpy (name, ntfn->Name.Buffer, namelen * sizeof (WCHAR));
name[namelen] = L'\0';
if (swscanf (name, L"\\Device\\NamedPipe\\%llx-%u-pipe-nt-0x%x",
&pipename_key, &pipename_pid, &pipename_id) != 3)
return NULL; /* Non cygwin pipe? */
SIZE_T n_handle = 65536;
PSYSTEM_HANDLE_INFORMATION shi;
do
{
SIZE_T nbytes =
sizeof (ULONG) + n_handle * sizeof (SYSTEM_HANDLE_TABLE_ENTRY_INFO);
shi = (PSYSTEM_HANDLE_INFORMATION) HeapAlloc (GetProcessHeap (),
0, nbytes);
if (!shi)
return NULL;
status = NtQuerySystemInformation (SystemHandleInformation,
shi, nbytes, NULL);
if (NT_SUCCESS (status))
break;
HeapFree (GetProcessHeap (), 0, shi);
n_handle *= 2;
}
while (n_handle < (1L<<20));
if (!NT_SUCCESS (status))
return NULL;
HANDLE qh = NULL;
for (LONG i = (LONG) shi->NumberOfHandles - 1; i >= 0; i--)
{
/* Check for the peculiarity of cygwin read pipe */
DWORD access = FILE_READ_DATA | FILE_READ_EA | FILE_WRITE_EA /* marker */
| FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES
| READ_CONTROL | SYNCHRONIZE;
if (shi->Handles[i].GrantedAccess != access)
continue;
/* Retrieve handle */
HANDLE proc = OpenProcess (PROCESS_DUP_HANDLE, 0,
shi->Handles[i].UniqueProcessId);
if (!proc)
continue;
HANDLE h = (HANDLE)(intptr_t) shi->Handles[i].HandleValue;
BOOL res = DuplicateHandle (proc, h, GetCurrentProcess (), &h,
FILE_READ_DATA, 0, 0);
if (!res)
goto close_proc;
/* Check object name */
status = NtQueryObject (h, ObjectNameInformation, ntfn, 65536, &len);
if (!NT_SUCCESS (status) || !ntfn->Name.Buffer)
goto close_handle;
ntfn->Name.Buffer[ntfn->Name.Length / sizeof (WCHAR)] = L'\0';
if (wcscmp (name, ntfn->Name.Buffer) == 0)
{
query_hdl_proc = proc;
query_hdl_value = (HANDLE)(intptr_t) shi->Handles[i].HandleValue;
qh = h;
break;
}
close_handle:
CloseHandle (h);
close_proc:
CloseHandle (proc);
}
HeapFree (GetProcessHeap (), 0, shi);
return qh;
}