summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCorinna Vinschen <vinschen@redhat.com>2006-07-18 10:33:54 +0000
committerCorinna Vinschen <vinschen@redhat.com>2006-07-18 10:33:54 +0000
commit8e2b869a12b603977f055eb78db48774451090b2 (patch)
treef5d425abaf76db563d989b08bc6c4c4c75cab270
parentfe0b5cedadb292f368f222143bb47f4e6e2b6da2 (diff)
downloadgdb-8e2b869a12b603977f055eb78db48774451090b2.tar.gz
* Merge HEAD into cv-branch.
-rw-r--r--winsup/cygwin/ChangeLog38
-rw-r--r--winsup/cygwin/cygheap.h436
-rw-r--r--winsup/cygwin/cygwin.sc143
-rwxr-xr-xwinsup/cygwin/dllfixdbg75
-rw-r--r--winsup/cygwin/exceptions.cc3
-rw-r--r--winsup/cygwin/fhandler.h6
-rw-r--r--winsup/cygwin/fhandler_fifo.cc243
-rw-r--r--winsup/cygwin/fhandler_floppy.cc520
-rw-r--r--winsup/cygwin/fhandler_tty.cc1493
-rw-r--r--winsup/cygwin/fork.cc6
-rw-r--r--winsup/cygwin/include/cygwin/types.h252
-rw-r--r--winsup/cygwin/mmap.cc5
-rw-r--r--winsup/cygwin/pipe.cc544
-rw-r--r--winsup/cygwin/sec_helper.cc561
-rw-r--r--winsup/cygwin/spawn.cc1025
-rw-r--r--winsup/cygwin/sync.h73
-rw-r--r--winsup/cygwin/wininfo.h25
17 files changed, 5441 insertions, 7 deletions
diff --git a/winsup/cygwin/ChangeLog b/winsup/cygwin/ChangeLog
index 86400b64948..368f7a1d54a 100644
--- a/winsup/cygwin/ChangeLog
+++ b/winsup/cygwin/ChangeLog
@@ -1,3 +1,41 @@
+2006-07-17 Christopher Faylor <cgf@timesys.com>
+
+ GCC 4.1 fixes.
+ * cygheap.h (cygheap_user): Remove unneeded class names from function
+ declaration.
+ * fhandler.h (fhandler_base): Ditto.
+ (fhandler_dev_floppy): Ditto.
+ (fhandler_console): Ditto.
+ * wininfo.h (wininfo): Ditto.
+ * exceptions.cc (sigpacket::process): Avoid compiler errors about gotos
+ and initialization.
+ * fhandler_fifo.cc (fhandler_fifo::open): Ditto.
+ * fhandler_floppy.cc (fhandler_dev_floppy::ioctl): Ditto.
+ * fhandler_tty.cc (fhandler_tty_slave::ioctl): Ditto.
+ * mmap.cc (mmap64): Ditto.
+ * pipe.cc (fhandler_pipe::open): Ditto.
+ * spawn.cc (spawn_guts): Ditto.
+
+ * sec_helper.cc: Fix some comments.
+ (get_null_sd): Move file-scope static to only function where it is
+ used.
+
+2006-07-14 Christopher Faylor <cgf@timesys.com>
+
+ * fork.cc (fork): Lock the process before forking to prevent things
+ like new fds from being opened, etc.
+ * sync.h (lock_process::dont_bother): New function.
+
+2006-07-14 Christopher Faylor <cgf@timesys.com>
+
+ * include/cygwin/types.h: Update copyright.
+
+2006-07-14 Christopher Faylor <cgf@timesys.com>
+
+ * cygwin.sc: Make sure there's something in the cygheap.
+ * dllfixdbg: Accommodate newer binutils which put the gnu_debuglink at
+ the end rather than at the beginning.
+
2006-07-14 Corinna Vinschen <corinna@vinschen.de>
* security.cc (get_token_group_sidlist): Always add the interactive
diff --git a/winsup/cygwin/cygheap.h b/winsup/cygwin/cygheap.h
new file mode 100644
index 00000000000..0afe1620d71
--- /dev/null
+++ b/winsup/cygwin/cygheap.h
@@ -0,0 +1,436 @@
+/* cygheap.h: Cygwin heap manager.
+
+ Copyright 2000, 2001, 2002, 2003, 2004, 2005 Red Hat, Inc.
+
+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. */
+
+#include "hires.h"
+
+#undef cfree
+
+enum cygheap_types
+{
+ HEAP_FHANDLER,
+ HEAP_STR,
+ HEAP_ARGV,
+ HEAP_BUF,
+ HEAP_MOUNT,
+ HEAP_SIGS,
+ HEAP_ARCHETYPES,
+ HEAP_TLS,
+ HEAP_COMMUNE,
+ HEAP_1_START,
+ HEAP_1_HOOK,
+ HEAP_1_STR,
+ HEAP_1_ARGV,
+ HEAP_1_BUF,
+ HEAP_1_EXEC,
+ HEAP_1_MAX = 100,
+ HEAP_2_STR,
+ HEAP_MMAP = 200
+};
+
+#define incygheap(s) (cygheap && ((char *) (s) >= (char *) cygheap) && ((char *) (s) <= ((char *) cygheap_max)))
+
+struct _cmalloc_entry
+{
+ union
+ {
+ DWORD b;
+ char *ptr;
+ };
+ struct _cmalloc_entry *prev;
+ char data[0];
+};
+
+struct cygheap_root_mount_info
+{
+ char posix_path[CYG_MAX_PATH];
+ unsigned posix_pathlen;
+ char native_path[CYG_MAX_PATH];
+ unsigned native_pathlen;
+};
+
+/* CGF: FIXME This doesn't belong here */
+
+class cygheap_root
+{
+ /* Root directory information.
+ This is used after a chroot is called. */
+ struct cygheap_root_mount_info *m;
+
+public:
+ bool posix_ok (const char *path)
+ {
+ if (!m)
+ return 1;
+ return path_prefix_p (m->posix_path, path, m->posix_pathlen);
+ }
+ bool ischroot_native (const char *path)
+ {
+ if (!m)
+ return 1;
+ return strncasematch (m->native_path, path, m->native_pathlen)
+ && (path[m->native_pathlen] == '\\' || !path[m->native_pathlen]);
+ }
+ const char *unchroot (const char *path)
+ {
+ if (!m)
+ return path;
+ const char *p = path + m->posix_pathlen;
+ if (!*p)
+ p = "/";
+ return p;
+ }
+ bool exists () {return !!m;}
+ void set (const char *, const char *);
+ size_t posix_length () const { return m->posix_pathlen; }
+ const char *posix_path () const { return m->posix_path; }
+ size_t native_length () const { return m->native_pathlen; }
+ const char *native_path () const { return m->native_path; }
+};
+
+enum homebodies
+{
+ CH_HOMEDRIVE,
+ CH_HOMEPATH,
+ CH_HOME
+};
+
+class cygheap_user
+{
+ /* Extendend user information.
+ The information is derived from the internal_getlogin call
+ when on a NT system. */
+ char *pname; /* user's name */
+ char *plogsrv; /* Logon server, may be FQDN */
+ char *pdomain; /* Logon domain of the user */
+ char *homedrive; /* User's home drive */
+ char *homepath; /* User's home path */
+ char *psystemroot; /* Value of SYSTEMROOT */
+ char *pwinname; /* User's name as far as Windows knows it */
+ char *puserprof; /* User profile */
+ cygsid effec_cygsid; /* buffer for user's SID */
+ cygsid saved_cygsid; /* Remains intact even after impersonation */
+public:
+ __uid32_t saved_uid; /* Remains intact even after impersonation */
+ __gid32_t saved_gid; /* Ditto */
+ __uid32_t real_uid; /* Remains intact on seteuid, replaced by setuid */
+ __gid32_t real_gid; /* Ditto */
+ user_groups groups; /* Primary and supp SIDs */
+
+ /* token is needed if set(e)uid should be called. It can be set by a call
+ to `set_impersonation_token()'. */
+ HANDLE external_token;
+ HANDLE internal_token;
+ HANDLE curr_primary_token;
+ HANDLE current_token;
+
+ /* CGF 2002-06-27. I removed the initializaton from this constructor
+ since this class is always allocated statically. That means that everything
+ is zero anyway so there is no need to initialize it to zero. Since the
+ token initialization is always handled during process startup as well,
+ I've removed the constructor entirely. Please reinstate this if this
+ situation ever changes.
+ cygheap_user () : pname (NULL), plogsrv (NULL), pdomain (NULL),
+ homedrive (NULL), homepath (NULL),
+ token (INVALID_HANDLE_VALUE) {}
+ */
+
+ ~cygheap_user ();
+
+ void init ();
+ void set_name (const char *new_name);
+ const char *name () const { return pname; }
+
+ const char *env_logsrv (const char *, size_t);
+ const char *env_homepath (const char *, size_t);
+ const char *env_homedrive (const char *, size_t);
+ const char *env_userprofile (const char *, size_t);
+ const char *env_domain (const char *, size_t);
+ const char *env_name (const char *, size_t);
+ const char *env_systemroot (const char *, size_t);
+
+ const char *logsrv ()
+ {
+ const char *p = env_logsrv ("LOGONSERVER=", sizeof ("LOGONSERVER=") - 1);
+ return (p == almost_null) ? NULL : p;
+ }
+ const char *winname ()
+ {
+ const char *p = env_name ("USERNAME=", sizeof ("USERNAME=") - 1);
+ return (p == almost_null) ? NULL : p;
+ }
+ const char *domain ()
+ {
+ const char *p = env_domain ("USERDOMAIN=", sizeof ("USERDOMAIN=") - 1);
+ return (p == almost_null) ? NULL : p;
+ }
+ BOOL set_sid (PSID new_sid) {return (BOOL) (effec_cygsid = new_sid);}
+ BOOL set_saved_sid () { return (BOOL) (saved_cygsid = effec_cygsid); }
+ PSID sid () { return effec_cygsid; }
+ PSID saved_sid () { return saved_cygsid; }
+ const char *ontherange (homebodies what, struct passwd * = NULL);
+#define NO_IMPERSONATION NULL
+ bool issetuid () const { return current_token != NO_IMPERSONATION; }
+ HANDLE primary_token () { return curr_primary_token; }
+ HANDLE token () { return current_token; }
+ void deimpersonate ()
+ {
+ if (issetuid ())
+ {
+ RevertToSelf ();
+ ImpersonateLoggedOnUser (hProcImpToken);
+ }
+ }
+ bool reimpersonate ()
+ {
+ return ImpersonateLoggedOnUser (issetuid () ? token () : hProcImpToken);
+ }
+ bool has_impersonation_tokens ()
+ { return external_token != NO_IMPERSONATION
+ || internal_token != NO_IMPERSONATION
+ || curr_primary_token != NO_IMPERSONATION; }
+ void close_impersonation_tokens ()
+ {
+ if (current_token != NO_IMPERSONATION)
+ CloseHandle (current_token);
+ if (curr_primary_token != NO_IMPERSONATION
+ && curr_primary_token != external_token
+ && curr_primary_token != internal_token)
+ CloseHandle (curr_primary_token);
+ if (external_token != NO_IMPERSONATION)
+ CloseHandle (external_token);
+ if (internal_token != NO_IMPERSONATION)
+ CloseHandle (internal_token);
+ }
+ char * get_windows_id (char * buf)
+ {
+ if (wincap.is_winnt ())
+ return effec_cygsid.string (buf);
+ else
+ return strcpy (buf, name ());
+ }
+
+ const char *test_uid (char *&, const char *, size_t)
+ __attribute__ ((regparm (3)));
+};
+
+/* cwd cache stuff. */
+
+class muto;
+
+struct cwdstuff
+{
+ char *posix;
+ char *win32;
+ DWORD hash;
+ DWORD drive_length;
+ static muto cwd_lock;
+ char *get (char *, int = 1, int = 0, unsigned = CYG_MAX_PATH);
+ DWORD get_hash ();
+ DWORD get_drive (char * dst)
+ {
+ get_initial ();
+ memcpy (dst, win32, drive_length);
+ cwd_lock.release ();
+ return drive_length;
+ }
+ void init ();
+ void fixup_after_exec (char *, char *, DWORD);
+ bool get_initial ();
+ int set (const char *, const char *, bool);
+};
+
+#ifdef DEBUGGING
+struct cygheap_debug
+{
+ handle_list starth;
+ handle_list *endh;
+ handle_list freeh[500];
+};
+#endif
+
+struct user_heap_info
+{
+ void *base;
+ void *ptr;
+ void *top;
+ void *max;
+ unsigned chunk;
+};
+
+struct hook_chain
+{
+ void **loc;
+ const void *func;
+ struct hook_chain *next;
+};
+
+struct init_cygheap
+{
+ _cmalloc_entry *chain;
+ char *buckets[32];
+ cygheap_root root;
+ cygheap_user user;
+ user_heap_info user_heap;
+ mode_t umask;
+ HANDLE shared_h;
+ HANDLE console_h;
+ HANDLE mt_h;
+ cwdstuff cwd;
+ dtable fdtab;
+ LUID luid[SE_NUM_PRIVS];
+ const char *shared_prefix;
+#ifdef DEBUGGING
+ cygheap_debug debug;
+#endif
+ struct sigaction *sigs;
+
+ fhandler_tty_slave *ctty; /* Current tty */
+#ifdef NEWVFORK
+ fhandler_tty_slave *ctty_on_hold;
+#endif
+ struct _cygtls **threadlist;
+ size_t sthreads;
+ pid_t pid; /* my pid */
+ HANDLE pid_handle; /* handle for my pid */
+ hook_chain hooks;
+ void close_ctty ();
+ int manage_console_count (const char *, int, bool = false) __attribute__ ((regparm (3)));
+private:
+ int console_count;
+};
+
+
+#define _CYGHEAPSIZE_SLOP (128 * 1024)
+#define CYGHEAPSIZE (sizeof (init_cygheap) + (20000 * sizeof (fhandler_union)) + _CYGHEAPSIZE_SLOP)
+#define CYGHEAPSIZE_MIN (sizeof (init_cygheap) + (10000 * sizeof (fhandler_union)))
+
+extern init_cygheap *cygheap;
+extern void *cygheap_max;
+
+class cygheap_fdmanip
+{
+ protected:
+ int fd;
+ fhandler_base **fh;
+ bool locked;
+ public:
+ cygheap_fdmanip (): fh (NULL) {}
+ virtual ~cygheap_fdmanip ()
+ {
+ if (locked)
+ cygheap->fdtab.unlock ();
+ }
+ void release ()
+ {
+ cygheap->fdtab.release (fd);
+ }
+ operator int &() {return fd;}
+ operator fhandler_base* &() {return *fh;}
+ operator fhandler_socket* () const {return reinterpret_cast<fhandler_socket *> (*fh);}
+ operator fhandler_pipe* () const {return reinterpret_cast<fhandler_pipe *> (*fh);}
+ void operator = (fhandler_base *fh) {*this->fh = fh;}
+ fhandler_base *operator -> () const {return *fh;}
+ bool isopen () const
+ {
+ if (*fh)
+ return true;
+ set_errno (EBADF);
+ return false;
+ }
+};
+
+class cygheap_fdnew : public cygheap_fdmanip
+{
+ public:
+ cygheap_fdnew (int seed_fd = -1, bool lockit = true)
+ {
+ if (lockit)
+ cygheap->fdtab.lock ();
+ if (seed_fd < 0)
+ fd = cygheap->fdtab.find_unused_handle ();
+ else
+ fd = cygheap->fdtab.find_unused_handle (seed_fd + 1);
+ if (fd >= 0)
+ {
+ locked = lockit;
+ fh = cygheap->fdtab + fd;
+ }
+ else
+ {
+ set_errno (EMFILE);
+ if (lockit)
+ cygheap->fdtab.unlock ();
+ locked = false;
+ }
+ }
+ void operator = (fhandler_base *fh) {*this->fh = fh;}
+};
+
+class cygheap_fdget : public cygheap_fdmanip
+{
+ public:
+ cygheap_fdget (int fd, bool lockit = false, bool do_set_errno = true)
+ {
+ if (lockit)
+ cygheap->fdtab.lock ();
+ if (fd >= 0 && fd < (int) cygheap->fdtab.size
+ && *(fh = cygheap->fdtab + fd) != NULL)
+ {
+ this->fd = fd;
+ locked = lockit;
+ }
+ else
+ {
+ this->fd = -1;
+ if (do_set_errno)
+ set_errno (EBADF);
+ if (lockit)
+ cygheap->fdtab.unlock ();
+ locked = false;
+ }
+ }
+};
+
+class cygheap_fdenum : public cygheap_fdmanip
+{
+ public:
+ cygheap_fdenum (bool lockit = false)
+ {
+ locked = lockit;
+ if (lockit)
+ cygheap->fdtab.lock ();
+ fd = -1;
+ }
+ int next ()
+ {
+ while (++fd < (int) cygheap->fdtab.size)
+ if (*(fh = cygheap->fdtab + fd) != NULL)
+ return fd;
+ return -1;
+ }
+ void rewind ()
+ {
+ fd = -1;
+ }
+};
+
+class child_info;
+void __stdcall cygheap_fixup_in_child (bool);
+extern "C" {
+void __stdcall cfree (void *) __attribute__ ((regparm(1)));
+void *__stdcall cmalloc (cygheap_types, DWORD) __attribute__ ((regparm(2)));
+void *__stdcall crealloc (void *, DWORD) __attribute__ ((regparm(2)));
+void *__stdcall ccalloc (cygheap_types, DWORD, DWORD) __attribute__ ((regparm(3)));
+char *__stdcall cstrdup (const char *) __attribute__ ((regparm(1)));
+char *__stdcall cstrdup1 (const char *) __attribute__ ((regparm(1)));
+void __stdcall cfree_and_set (char *&, char * = NULL) __attribute__ ((regparm(2)));
+void __stdcall cygheap_init ();
+extern char _cygheap_start[] __attribute__((section(".idata")));
+}
diff --git a/winsup/cygwin/cygwin.sc b/winsup/cygwin/cygwin.sc
new file mode 100644
index 00000000000..58ee37664e0
--- /dev/null
+++ b/winsup/cygwin/cygwin.sc
@@ -0,0 +1,143 @@
+OUTPUT_FORMAT(pei-i386)
+SECTIONS
+{
+ .text __image_base__ + __section_alignment__ :
+ {
+ *(.init)
+ *(.text)
+ *(SORT(.text$*))
+ *(.glue_7t)
+ *(.glue_7)
+ ___CTOR_LIST__ = .; __CTOR_LIST__ = .;
+ LONG (-1); *(SORT(.ctors.*)); *(.ctors); *(.ctor); LONG (0);
+ ___DTOR_LIST__ = .; __DTOR_LIST__ = .;
+ LONG (-1); *(SORT(.dtors.*)); *(.dtors); *(.dtor); LONG (0);
+ *(.fini)
+ /* ??? Why is .gcc_exc here? */
+ *(.gcc_exc)
+ etext = .;
+ *(.gcc_except_table)
+ }
+ .autoload_text ALIGN(__section_alignment__) :
+ {
+ *(.*_autoload_text);
+ }
+ /* The Cygwin DLL uses a section to avoid copying certain data
+ on fork. This used to be named ".data". The linker used
+ to include this between __data_start__ and __data_end__, but that
+ breaks building the cygwin32 dll. Instead, we name the section
+ ".data_cygwin_nocopy" and explictly include it after __data_end__. */
+ .data ALIGN(__section_alignment__) :
+ {
+ __data_start__ = .;
+ *(.data)
+ *(.data2)
+ *(SORT(.data$*))
+ __data_end__ = .;
+ *(.data_cygwin_nocopy)
+ }
+ .rdata ALIGN(__section_alignment__) :
+ {
+ *(.rdata)
+ *(SORT(.rdata$*))
+ *(.eh_frame)
+ }
+ .pdata ALIGN(__section_alignment__) :
+ {
+ *(.pdata)
+ }
+ .bss ALIGN(__section_alignment__) :
+ {
+ __bss_start__ = .;
+ *(.bss)
+ *(COMMON)
+ __bss_end__ = .;
+ }
+ .edata ALIGN(__section_alignment__) :
+ {
+ *(.edata)
+ }
+ .rsrc BLOCK(__section_alignment__) :
+ {
+ *(.rsrc)
+ *(SORT(.rsrc$*))
+ }
+ .reloc BLOCK(__section_alignment__) :
+ {
+ *(.reloc)
+ }
+ .cygwin_dll_common ALIGN(__section_alignment__):
+ {
+ *(.cygwin_dll_common)
+ }
+ .gnu_debuglink_overlay ALIGN(__section_alignment__) (NOLOAD):
+ {
+ BYTE(0) /* c */
+ BYTE(0) /* y */
+ BYTE(0) /* g */
+ BYTE(0) /* w */
+ BYTE(0) /* i */
+ BYTE(0) /* n */
+ BYTE(0) /* 1 */
+ BYTE(0) /* . */
+ BYTE(0) /* d */
+ BYTE(0) /* b */
+ BYTE(0) /* g */
+ BYTE(0) /* \0 */
+ LONG(0) /* checksum */
+ }
+ .idata ALIGN(__section_alignment__) :
+ {
+ /* This cannot currently be handled with grouped sections.
+ See pe.em:sort_sections. */
+ SORT(*)(.idata$2)
+ SORT(*)(.idata$3)
+ /* These zeroes mark the end of the import list. */
+ LONG (0); LONG (0); LONG (0); LONG (0); LONG (0);
+ SORT(*)(.idata$4)
+ SORT(*)(.idata$5)
+ SORT(*)(.idata$6)
+ SORT(*)(.idata$7)
+ . = ALIGN(16);
+ __cygheap_start = ABSOLUTE(.);
+ . = ALIGN(0x10000);
+ }
+ .cygheap ALIGN(__section_alignment__) :
+ {
+ __cygheap_mid = .;
+ *(.cygheap)
+ . = . + 1;
+ . = ALIGN(512 * 1024);
+ }
+ __cygheap_end = ABSOLUTE(.);
+ __cygheap_end1 = __cygheap_mid + SIZEOF(.cygheap);
+ __cygwin_debug_size = SIZEOF(.gnu_debuglink);
+ /DISCARD/ :
+ {
+ *(.debug$S)
+ *(.debug$T)
+ *(.debug$F)
+ *(.drectve)
+ }
+ .stab ALIGN(__section_alignment__) (NOLOAD) :
+ {
+ *(.stab)
+ }
+ .stabstr ALIGN(__section_alignment__) (NOLOAD) :
+ {
+ *(.stabstr)
+ }
+ /* DWARF 1.1 and DWARF 2 */
+ .debug_aranges ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_aranges) }
+ .debug_pubnames ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_pubnames) }
+ /* DWARF 2 */
+ .debug_info ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_info) }
+ .debug_abbrev ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_abbrev) }
+ .debug_line ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_line) }
+ .debug_frame ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_frame) }
+ .debug_str ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_str) }
+ .debug_loc ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_loc) }
+ .debug_macinfo ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_macinfo) }
+ .debug_macinfo ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_macinfo) }
+ .debug_ranges ALIGN(__section_alignment__) (NOLOAD) : { *(.debug_ranges) }
+}
diff --git a/winsup/cygwin/dllfixdbg b/winsup/cygwin/dllfixdbg
new file mode 100755
index 00000000000..4ffc4e6ce30
--- /dev/null
+++ b/winsup/cygwin/dllfixdbg
@@ -0,0 +1,75 @@
+#!/usr/bin/perl
+# Copyright 2006 Red Hat, Inc.
+#
+# 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.
+#
+use integer;
+use strict;
+sub xit($@);
+my $strip = $ARGV[0] eq '-s';
+shift if $strip;
+my $objdump = shift;
+my @objcopy = ((shift));
+my $dll = shift;
+my $dbg = shift;
+xit 0, @objcopy, '-j', '.stab', '-j', '.stabstr', $dll, $dbg;
+xit 0, @objcopy, '-g', '--add-gnu-debuglink=' . $dbg, $dll;
+open(OBJDUMP, '-|', "$objdump --headers $dll");
+my %section;
+while (<OBJDUMP>) {
+ my ($idx, $name, $size, $vma, $lma, $fileoff, $algn) = /^\s*(\d+)\s+(\.\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*$/;
+ if ($name eq '.gnu_debuglink') {
+ push(@objcopy, '--set-section-flag', '.gnu_debuglink=contents,readonly,debug,noload');
+ $idx = $section{'.gnu_debuglink'}{-idx} if defined($section{'.gnu_debuglink'}{-idx});
+ } elsif ($name eq '.gnu_debuglink_overlay') {
+ push (@objcopy, '-R', '.gnu_debuglink_overlay');
+ $section{'.gnu_debuglink'}{-idx} = $idx;
+ next;
+ }
+ defined($idx) and
+ $section{$name} = {-idx=>int($idx), -size=>hex($size), -vma=>hex($vma), -lma=>hex($lma), -fileoff=>hex($fileoff),
+ -algn=>0x00001000};
+}
+close OBJDUMP;
+my $vma;
+for my $k (sort {$section{$a}{-idx} <=> $section{$b}{-idx}} keys %section) {
+ if ($strip && $k =~ /\.(?:stab|debug)/o) {
+ push(@objcopy, '-R', $k);
+ next;
+ }
+ if (!defined($vma)) {
+ $vma = $section{$k}{-vma};
+ }
+ if ($vma != $section{$k}{-vma}) {
+ my $newvma = align($vma, $section{$k}{-algn});
+ if ($newvma != $vma) {
+ printf STDERR "$0: ERROR $k VMA 0x%08x != 0x%08x\n", $vma, $newvma;
+ exit 1;
+ }
+ push(@objcopy, '--change-section-address', sprintf "$k=0x%08x", $vma);
+ }
+ $vma = align($vma + $section{$k}{-size}, $section{$k}{-algn});
+}
+
+warn "$0: ERROR final VMA (" . sprintf("0x%08x", $vma) . ") not on 64K boundary\n" if $vma != align($vma, 64 * 1024);
+push(@objcopy, $dll, @ARGV);
+xit 1, @objcopy;
+sub align {
+ my $n = $_[0];
+ my $align = $_[1] - 1;
+ return ($n + $align) & ~$align;
+}
+
+sub xit($@) {
+ my $execit = shift;
+ print "+ @_\n";
+ if ($execit) {
+ exec @_ or die "$0: couldn't exec $_[0] - $!\n";
+ } else {
+ system @_ and die "$0: couldn't exec $_[0] - $!\n";
+ }
+}
diff --git a/winsup/cygwin/exceptions.cc b/winsup/cygwin/exceptions.cc
index 12c6e0687b5..e5345f13ec2 100644
--- a/winsup/cygwin/exceptions.cc
+++ b/winsup/cygwin/exceptions.cc
@@ -1118,6 +1118,8 @@ int __stdcall
sigpacket::process ()
{
DWORD continue_now;
+ struct sigaction dummy = global_sigs[SIGSTOP];
+
if (si.si_signo != SIGCONT)
continue_now = false;
else
@@ -1235,7 +1237,6 @@ stop:
if (ISSTATE (myself, PID_STOPPED))
goto done;
handler = (void *) sig_handle_tty_stop;
- struct sigaction dummy = global_sigs[SIGSTOP];
thissig = dummy;
dosig:
diff --git a/winsup/cygwin/fhandler.h b/winsup/cygwin/fhandler.h
index 887b929663c..06ae26e01a2 100644
--- a/winsup/cygwin/fhandler.h
+++ b/winsup/cygwin/fhandler.h
@@ -275,7 +275,7 @@ class fhandler_base
__attribute__ ((regparm (3)));
int __stdcall fstat_by_handle (struct __stat64 *buf) __attribute__ ((regparm (2)));
int __stdcall fstat_by_name (struct __stat64 *buf) __attribute__ ((regparm (2)));
- int fhandler_base::utimes_fs (const struct timeval *) __attribute__ ((regparm (2)));
+ int utimes_fs (const struct timeval *) __attribute__ ((regparm (2)));
virtual int __stdcall fchmod (mode_t mode) __attribute__ ((regparm (1)));
virtual int __stdcall fchown (__uid32_t uid, __gid32_t gid) __attribute__ ((regparm (2)));
virtual int __stdcall facl (int, int, __acl32 *) __attribute__ ((regparm (3)));
@@ -614,7 +614,7 @@ class fhandler_dev_floppy: public fhandler_dev_raw
IMPLEMENT_STATUS_FLAG (bool, eom_detected)
inline _off64_t get_current_position ();
- int fhandler_dev_floppy::get_drive_info (struct hd_geometry *geo);
+ int get_drive_info (struct hd_geometry *geo);
BOOL write_file (const void *buf, DWORD to_write, DWORD *written, int *err);
BOOL read_file (void *buf, DWORD to_read, DWORD *read, int *err);
@@ -941,7 +941,7 @@ class fhandler_console: public fhandler_termios
static tty_min *get_tty_stuff (int);
bool is_slow () {return 1;}
static bool need_invisible ();
- static bool fhandler_console::has_a () {return !invisible_console;}
+ static bool has_a () {return !invisible_console;}
};
class fhandler_tty_common: public fhandler_termios
diff --git a/winsup/cygwin/fhandler_fifo.cc b/winsup/cygwin/fhandler_fifo.cc
new file mode 100644
index 00000000000..aa631528ae1
--- /dev/null
+++ b/winsup/cygwin/fhandler_fifo.cc
@@ -0,0 +1,243 @@
+/* fhandler_fifo.cc - See fhandler.h for a description of the fhandler classes.
+
+ Copyright 2002, 2003, 2004, 2005, 2006 Red Hat, Inc.
+
+ 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. */
+
+#include "winsup.h"
+#include <errno.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+#include "cygerrno.h"
+#include "perprocess.h"
+#include "security.h"
+#include "path.h"
+#include "fhandler.h"
+#include "dtable.h"
+#include "cygheap.h"
+#include "pinfo.h"
+
+fhandler_fifo::fhandler_fifo ()
+ : fhandler_pipe (), output_handle (NULL),
+ read_use (0), write_use (0)
+{
+}
+
+void
+fhandler_fifo::set_use (int incr)
+{
+ long oread_use = read_use;
+
+ if (get_flags () & (O_WRONLY | O_APPEND))
+ write_use += incr;
+ else if (get_flags () & O_RDWR)
+ {
+ write_use += incr;
+ read_use += incr;
+ }
+ else
+ read_use += incr;
+
+ if (incr >= 0)
+ return;
+ if (read_use <= 0 && oread_use != read_use)
+ {
+ HANDLE h = get_handle ();
+ if (h)
+ {
+ set_io_handle (NULL);
+ CloseHandle (h);
+ }
+ }
+}
+
+int
+fhandler_fifo::close ()
+{
+ fhandler_pipe::close ();
+ if (get_output_handle ())
+ CloseHandle (get_output_handle ());
+ if (!hExeced)
+ set_use (-1);
+ return 0;
+}
+
+#define DUMMY_O_RDONLY 4
+
+void
+fhandler_fifo::close_one_end ()
+{
+ int testflags = (get_flags () & (O_RDWR | O_WRONLY | O_APPEND)) ?: DUMMY_O_RDONLY;
+ static int flagtypes[] = {DUMMY_O_RDONLY | O_RDWR, O_WRONLY | O_APPEND | O_RDWR};
+ HANDLE *handles[2] = {&(get_handle ()), &(get_output_handle ())};
+ for (int i = 0; i < 2; i++)
+ if (!(testflags & flagtypes[i]))
+ {
+ CloseHandle (*handles[i]);
+ *handles[i] = NULL;
+ }
+ else if (i == 0 && !read_state)
+ {
+ create_read_state (2);
+ need_fork_fixup (true);
+ }
+}
+int
+fhandler_fifo::open_not_mine (int flags)
+{
+ winpids pids ((DWORD) 0);
+ int res = 0;
+
+ for (unsigned i = 0; i < pids.npids; i++)
+ {
+ _pinfo *p = pids[i];
+ commune_result r;
+ if (p->pid != myself->pid)
+ {
+ r = p->commune_request (PICOM_FIFO, get_win32_name ());
+ if (r.handles[0] == NULL)
+ continue; // process doesn't own fifo
+ debug_printf ("pid %d, handles[0] %p, handles[1] %p", p->pid,
+ r.handles[0], r.handles[1]);
+ }
+ else
+ {
+ /* FIXME: racy? */
+ fhandler_fifo *fh = cygheap->fdtab.find_fifo (get_win32_name ());
+ if (!fh)
+ continue;
+ if (!DuplicateHandle (hMainProc, fh->get_handle (), hMainProc,
+ &r.handles[0], 0, false, DUPLICATE_SAME_ACCESS))
+ {
+ __seterrno ();
+ goto out;
+ }
+ if (!DuplicateHandle (hMainProc, fh->get_output_handle (), hMainProc,
+ &r.handles[1], 0, false, DUPLICATE_SAME_ACCESS))
+ {
+ CloseHandle (r.handles[0]);
+ __seterrno ();
+ goto out;
+ }
+ }
+
+ set_io_handle (r.handles[0]);
+ set_output_handle (r.handles[1]);
+ set_flags (flags);
+ close_one_end ();
+ res = 1;
+ goto out;
+ }
+
+ set_errno (EAGAIN);
+
+out:
+ debug_printf ("res %d", res);
+ return res;
+}
+
+#define FIFO_PREFIX "_cygfifo_"
+
+int
+fhandler_fifo::open (int flags, mode_t)
+{
+ int res = 1;
+ char mutex[CYG_MAX_PATH];
+ char *emutex = mutex + CYG_MAX_PATH;
+ char *p, *p1;
+ DWORD resw;
+
+ /* Generate a semi-unique name to associate with this fifo but try to ensure
+ that it is no larger than CYG_MAX_PATH */
+ for (p = mutex, p1 = strchr (get_name (), '\0');
+ --p1 >= get_name () && p < emutex ; p++)
+ *p = (*p1 == '/') ? '_' : *p1;
+ strncpy (p, FIFO_PREFIX, emutex - p);
+ mutex[CYG_MAX_PATH - 1] = '\0';
+
+ /* Create a mutex lock access to this fifo to prevent a race by two processes
+ trying to figure out if they own the fifo or if they should create it. */
+ HANDLE h = CreateMutex (&sec_none_nih, false, mutex);
+ if (!h)
+ {
+ __seterrno ();
+ system_printf ("couldn't open fifo mutex '%s', %E", mutex);
+ res = 0;
+ goto out;
+ }
+
+ lock_process::locker.release (); /* Since we may be a while, release the
+ process lock that is held when we
+ open an fd. */
+ /* FIXME? Need to wait for signal here?
+ This shouldn't block for long, but... */
+ resw = WaitForSingleObject (h, INFINITE);
+ lock_process::locker.acquire (); /* Restore the lock */
+ if (resw != WAIT_OBJECT_0 && resw != WAIT_ABANDONED_0)
+ {
+ __seterrno ();
+ system_printf ("Wait for fifo mutex '%s' failed, %E", mutex);
+ goto out;
+ }
+
+ set_io_handle (NULL);
+ set_output_handle (NULL);
+ if (open_not_mine (flags))
+ goto out;
+
+ fhandler_pipe *fhs[2];
+ if (create (fhs, 1, flags, true))
+ {
+ __seterrno ();
+ res = 0;
+ }
+ else
+ {
+ set_flags (flags);
+ set_io_handle (fhs[0]->get_handle ());
+ set_output_handle (fhs[1]->get_handle ());
+ guard = fhs[0]->guard;
+ read_state = fhs[0]->read_state;
+ writepipe_exists = fhs[1]->writepipe_exists;
+ orig_pid = fhs[0]->orig_pid;
+ id = fhs[0]->id;
+ delete (fhs[0]);
+ delete (fhs[1]);
+ set_use (1);
+ need_fork_fixup (true);
+ }
+
+out:
+ if (h)
+ {
+ ReleaseMutex (h);
+ CloseHandle (h);
+ }
+ debug_printf ("returning %d, errno %d", res, get_errno ());
+ return res;
+}
+
+int
+fhandler_fifo::dup (fhandler_base *child)
+{
+ int res = fhandler_pipe::dup (child);
+ if (!res)
+ {
+ fhandler_fifo *ff = (fhandler_fifo *) child;
+ if (get_output_handle ()
+ && !DuplicateHandle (hMainProc, get_output_handle (), hMainProc,
+ &ff->get_output_handle (), false, true,
+ DUPLICATE_SAME_ACCESS))
+ {
+ __seterrno ();
+ child->close ();
+ res = -1;
+ }
+ }
+ return res;
+}
diff --git a/winsup/cygwin/fhandler_floppy.cc b/winsup/cygwin/fhandler_floppy.cc
new file mode 100644
index 00000000000..4595e73a32e
--- /dev/null
+++ b/winsup/cygwin/fhandler_floppy.cc
@@ -0,0 +1,520 @@
+/* fhandler_floppy.cc. See fhandler.h for a description of the
+ fhandler classes.
+
+ Copyright 1999, 2000, 2001, 2002, 2003, 2004 Red Hat, Inc.
+
+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. */
+
+#include "winsup.h"
+#include <sys/termios.h>
+#include <unistd.h>
+#include <winioctl.h>
+#include <asm/socket.h>
+#include <cygwin/rdevio.h>
+#include <cygwin/hdreg.h>
+#include <cygwin/fs.h>
+#include "cygerrno.h"
+#include "security.h"
+#include "path.h"
+#include "fhandler.h"
+#include <ntdef.h>
+#include "ntdll.h"
+
+#define IS_EOM(err) ((err) == ERROR_INVALID_PARAMETER \
+ || (err) == ERROR_SEEK \
+ || (err) == ERROR_SECTOR_NOT_FOUND)
+
+/**********************************************************************/
+/* fhandler_dev_floppy */
+
+fhandler_dev_floppy::fhandler_dev_floppy ()
+ : fhandler_dev_raw (), status ()
+{
+}
+
+int
+fhandler_dev_floppy::get_drive_info (struct hd_geometry *geo)
+{
+ char dbuf[256];
+ char pbuf[256];
+
+ DISK_GEOMETRY *di = NULL;
+ PARTITION_INFORMATION_EX *pix = NULL;
+ PARTITION_INFORMATION *pi = NULL;
+ DWORD bytes_read = 0;
+
+ /* Always try using the new EX ioctls first (>= XP). If not available,
+ fall back to trying the old non-EX ioctls.
+ Unfortunately the EX ioctls are not implemented in the floppy driver. */
+ if (wincap.has_disk_ex_ioctls () && get_major () != DEV_FLOPPY_MAJOR)
+ {
+ if (!DeviceIoControl (get_handle (),
+ IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0,
+ dbuf, 256, &bytes_read, NULL))
+ __seterrno ();
+ else
+ {
+ di = &((DISK_GEOMETRY_EX *) dbuf)->Geometry;
+ if (!DeviceIoControl (get_handle (),
+ IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0,
+ pbuf, 256, &bytes_read, NULL))
+ __seterrno ();
+ else
+ pix = (PARTITION_INFORMATION_EX *) pbuf;
+ }
+ }
+ if (!di)
+ {
+ if (!DeviceIoControl (get_handle (),
+ IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
+ dbuf, 256, &bytes_read, NULL))
+ __seterrno ();
+ else
+ {
+ di = (DISK_GEOMETRY *) dbuf;
+ if (!DeviceIoControl (get_handle (),
+ IOCTL_DISK_GET_PARTITION_INFO, NULL, 0,
+ pbuf, 256, &bytes_read, NULL))
+ __seterrno ();
+ else
+ pi = (PARTITION_INFORMATION *) pbuf;
+ }
+ }
+ if (!di)
+ {
+ /* Up to Win2K, even IOCTL_DISK_GET_DRIVE_GEOMETRY fails when trying
+ it on CD or DVD drives. In that case fall back to requesting
+ simple file system information. */
+ NTSTATUS status;
+ IO_STATUS_BLOCK io;
+ FILE_FS_SIZE_INFORMATION ffsi;
+
+ status = NtQueryVolumeInformationFile (get_handle (), &io, &ffsi,
+ sizeof ffsi,
+ FileFsSizeInformation);
+ if (!NT_SUCCESS (status))
+ {
+ __seterrno_from_nt_status (status);
+ return -1;
+ }
+ debug_printf ("fsys geometry: (%D units)*(%u sec)*(%u bps)",
+ ffsi.TotalAllocationUnits.QuadPart,
+ ffsi.SectorsPerAllocationUnit,
+ ffsi.BytesPerSector);
+ bytes_per_sector = ffsi.BytesPerSector;
+ drive_size = ffsi.TotalAllocationUnits.QuadPart
+ * ffsi.SectorsPerAllocationUnit
+ * ffsi.BytesPerSector;
+ if (geo)
+ {
+ geo->heads = 1;
+ geo->sectors = ffsi.SectorsPerAllocationUnit;
+ geo->cylinders = ffsi.TotalAllocationUnits.LowPart;
+ geo->start = 0;
+ }
+ }
+ else
+ {
+ debug_printf ("disk geometry: (%D cyl)*(%u trk)*(%u sec)*(%u bps)",
+ di->Cylinders.QuadPart,
+ di->TracksPerCylinder,
+ di->SectorsPerTrack,
+ di->BytesPerSector);
+ bytes_per_sector = di->BytesPerSector;
+ if (pix)
+ {
+ debug_printf ("partition info: offset %D length %D",
+ pix->StartingOffset.QuadPart,
+ pix->PartitionLength.QuadPart);
+ drive_size = pix->PartitionLength.QuadPart;
+ }
+ else if (pi)
+ {
+ debug_printf ("partition info: offset %D length %D",
+ pi->StartingOffset.QuadPart,
+ pi->PartitionLength.QuadPart);
+ drive_size = pi->PartitionLength.QuadPart;
+ }
+ else
+ {
+ /* Getting the partition size by using the drive geometry information
+ looks wrong, but this is a historical necessity. NT4 didn't
+ maintain partition information for the whole drive (aka
+ "partition 0"), but returned ERROR_INVALID_HANDLE instead. That
+ got fixed in W2K. */
+ drive_size = di->Cylinders.QuadPart * di->TracksPerCylinder
+ * di->SectorsPerTrack * di->BytesPerSector;
+ }
+ if (geo)
+ {
+ geo->heads = di->TracksPerCylinder;
+ geo->sectors = di->SectorsPerTrack;
+ geo->cylinders = di->Cylinders.LowPart;
+ if (pix)
+ geo->start = pix->StartingOffset.QuadPart >> 9ULL;
+ else if (pi)
+ geo->start = pi->StartingOffset.QuadPart >> 9ULL;
+ else
+ geo->start = 0;
+ }
+ }
+ debug_printf ("drive size: %D", drive_size);
+
+ return 0;
+}
+
+/* Wrapper functions for ReadFile and WriteFile to simplify error handling. */
+BOOL
+fhandler_dev_floppy::read_file (void *buf, DWORD to_read, DWORD *read, int *err)
+{
+ BOOL ret;
+
+ *err = 0;
+ if (!(ret = ReadFile (get_handle (), buf, to_read, read, 0)))
+ *err = GetLastError ();
+ syscall_printf ("%d (err %d) = ReadFile (%d, %d, to_read %d, read %d, 0)",
+ ret, *err, get_handle (), buf, to_read, *read);
+ return ret;
+}
+
+BOOL
+fhandler_dev_floppy::write_file (const void *buf, DWORD to_write,
+ DWORD *written, int *err)
+{
+ BOOL ret;
+
+ *err = 0;
+ if (!(ret = WriteFile (get_handle (), buf, to_write, written, 0)))
+ *err = GetLastError ();
+ syscall_printf ("%d (err %d) = WriteFile (%d, %d, write %d, written %d, 0)",
+ ret, *err, get_handle (), buf, to_write, *written);
+ return ret;
+}
+
+int
+fhandler_dev_floppy::open (int flags, mode_t)
+{
+ /* The correct size of the buffer would be 512 bytes, which is the atomic
+ size, supported by WinNT. Unfortunately, the performance is worse than
+ access to file system on same device! Setting buffer size to a
+ relatively big value increases performance by means. The new ioctl call
+ with 'rdevio.h' header file supports changing this value.
+
+ As default buffer size, we're using some value which is a multiple of
+ the typical tar and cpio buffer sizes, Except O_DIRECT is set, in which
+ case we're not buffering at all. */
+ devbufsiz = (flags & O_DIRECT) ? 0L : 61440L;
+ int ret = fhandler_dev_raw::open (flags);
+
+ if (ret && get_drive_info (NULL))
+ {
+ close ();
+ return 0;
+ }
+
+ return ret;
+}
+
+int
+fhandler_dev_floppy::dup (fhandler_base *child)
+{
+ int ret = fhandler_dev_raw::dup (child);
+
+ if (!ret)
+ {
+ fhandler_dev_floppy *fhc = (fhandler_dev_floppy *) child;
+
+ fhc->drive_size = drive_size;
+ fhc->bytes_per_sector = bytes_per_sector;
+ fhc->eom_detected (eom_detected ());
+ }
+ return ret;
+}
+
+inline _off64_t
+fhandler_dev_floppy::get_current_position ()
+{
+ LARGE_INTEGER off = { QuadPart: 0LL };
+ off.LowPart = SetFilePointer (get_handle (), 0, &off.HighPart, FILE_CURRENT);
+ return off.QuadPart;
+}
+
+void
+fhandler_dev_floppy::raw_read (void *ptr, size_t& ulen)
+{
+ DWORD bytes_read = 0;
+ DWORD read2;
+ DWORD bytes_to_read;
+ int ret;
+ size_t len = ulen;
+ char *tgt;
+ char *p = (char *) ptr;
+
+ /* Checking a previous end of media */
+ if (eom_detected () && !lastblk_to_read ())
+ {
+ set_errno (ENOSPC);
+ goto err;
+ }
+
+ if (devbuf)
+ {
+ while (len > 0)
+ {
+ if (devbufstart < devbufend)
+ {
+ bytes_to_read = min (len, devbufend - devbufstart);
+ debug_printf ("read %d bytes from buffer (rest %d)",
+ bytes_to_read,
+ devbufend - devbufstart - bytes_to_read);
+ memcpy (p, devbuf + devbufstart, bytes_to_read);
+ len -= bytes_to_read;
+ p += bytes_to_read;
+ bytes_read += bytes_to_read;
+ devbufstart += bytes_to_read;
+
+ if (lastblk_to_read ())
+ {
+ lastblk_to_read (false);
+ break;
+ }
+ }
+ if (len > 0)
+ {
+ if (len >= devbufsiz)
+ {
+ bytes_to_read = (len / bytes_per_sector) * bytes_per_sector;
+ tgt = p;
+ }
+ else
+ {
+ tgt = devbuf;
+ bytes_to_read = devbufsiz;
+ }
+ _off64_t current_position = get_current_position ();
+ if (current_position + bytes_to_read >= drive_size)
+ bytes_to_read = drive_size - current_position;
+ if (!bytes_to_read)
+ {
+ eom_detected (true);
+ break;
+ }
+
+ debug_printf ("read %d bytes %s", bytes_to_read,
+ len < devbufsiz ? "into buffer" : "directly");
+ if (!read_file (tgt, bytes_to_read, &read2, &ret))
+ {
+ if (!IS_EOM (ret))
+ {
+ __seterrno ();
+ goto err;
+ }
+
+ eom_detected (true);
+
+ if (!read2)
+ {
+ if (!bytes_read)
+ {
+ debug_printf ("return -1, set errno to ENOSPC");
+ set_errno (ENOSPC);
+ goto err;
+ }
+ break;
+ }
+ lastblk_to_read (true);
+ }
+ if (!read2)
+ break;
+ if (tgt == devbuf)
+ {
+ devbufstart = 0;
+ devbufend = read2;
+ }
+ else
+ {
+ len -= read2;
+ p += read2;
+ bytes_read += read2;
+ }
+ }
+ }
+ }
+ else if (!read_file (p, len, &bytes_read, &ret))
+ {
+ if (!IS_EOM (ret))
+ {
+ __seterrno ();
+ goto err;
+ }
+ if (bytes_read)
+ eom_detected (true);
+ else
+ {
+ debug_printf ("return -1, set errno to ENOSPC");
+ set_errno (ENOSPC);
+ goto err;
+ }
+ }
+
+ ulen = (size_t) bytes_read;
+ return;
+
+err:
+ ulen = (size_t) -1;
+}
+
+int
+fhandler_dev_floppy::raw_write (const void *ptr, size_t len)
+{
+ DWORD bytes_written = 0;
+ char *p = (char *) ptr;
+ int ret;
+
+ /* Checking a previous end of media on tape */
+ if (eom_detected ())
+ {
+ set_errno (ENOSPC);
+ return -1;
+ }
+
+ /* Invalidate buffer. */
+ devbufstart = devbufend = 0;
+
+ if (len > 0)
+ {
+ if (!write_file (p, len, &bytes_written, &ret))
+ {
+ if (!IS_EOM (ret))
+ {
+ __seterrno ();
+ return -1;
+ }
+ eom_detected (true);
+ if (!bytes_written)
+ {
+ set_errno (ENOSPC);
+ return -1;
+ }
+ }
+ }
+ return bytes_written;
+}
+
+_off64_t
+fhandler_dev_floppy::lseek (_off64_t offset, int whence)
+{
+ char buf[512];
+ _off64_t lloffset = offset;
+ LARGE_INTEGER sector_aligned_offset;
+ _off64_t bytes_left;
+
+ if (whence == SEEK_END)
+ {
+ lloffset += drive_size;
+ whence = SEEK_SET;
+ }
+ else if (whence == SEEK_CUR)
+ {
+ lloffset += get_current_position () - (devbufend - devbufstart);
+ whence = SEEK_SET;
+ }
+
+ if (whence != SEEK_SET || lloffset < 0 || lloffset > drive_size)
+ {
+ set_errno (EINVAL);
+ return -1;
+ }
+
+ sector_aligned_offset.QuadPart = (lloffset / bytes_per_sector)
+ * bytes_per_sector;
+ bytes_left = lloffset - sector_aligned_offset.QuadPart;
+
+ /* Invalidate buffer. */
+ devbufstart = devbufend = 0;
+
+ sector_aligned_offset.LowPart =
+ SetFilePointer (get_handle (),
+ sector_aligned_offset.LowPart,
+ &sector_aligned_offset.HighPart,
+ FILE_BEGIN);
+ if (sector_aligned_offset.LowPart == INVALID_SET_FILE_POINTER
+ && GetLastError ())
+ {
+ __seterrno ();
+ return -1;
+ }
+
+ eom_detected (false);
+
+ if (bytes_left)
+ {
+ size_t len = bytes_left;
+ raw_read (buf, len);
+ }
+ return sector_aligned_offset.QuadPart + bytes_left;
+}
+
+int
+fhandler_dev_floppy::ioctl (unsigned int cmd, void *buf)
+{
+ DISK_GEOMETRY di;
+ DWORD bytes_read;
+ switch (cmd)
+ {
+ case HDIO_GETGEO:
+ {
+ debug_printf ("HDIO_GETGEO");
+ return get_drive_info ((struct hd_geometry *) buf);
+ }
+ case BLKGETSIZE:
+ case BLKGETSIZE64:
+ {
+ debug_printf ("BLKGETSIZE");
+ if (cmd == BLKGETSIZE)
+ *(long *)buf = drive_size >> 9UL;
+ else
+ *(_off64_t *)buf = drive_size;
+ return 0;
+ }
+ case BLKRRPART:
+ {
+ debug_printf ("BLKRRPART");
+ if (!DeviceIoControl (get_handle (),
+ IOCTL_DISK_UPDATE_DRIVE_SIZE,
+ NULL, 0,
+ &di, sizeof (di),
+ &bytes_read, NULL))
+ {
+ __seterrno ();
+ return -1;
+ }
+ get_drive_info (NULL);
+ return 0;
+ }
+ case BLKSSZGET:
+ {
+ debug_printf ("BLKSSZGET");
+ *(int *)buf = bytes_per_sector;
+ return 0;
+ }
+ case RDSETBLK:
+ /* Just check the restriction that blocksize must be a multiple
+ of the sector size of the underlying volume sector size,
+ then fall through to fhandler_dev_raw::ioctl. */
+ if (((struct rdop *) buf)->rd_parm % bytes_per_sector)
+ {
+ SetLastError (ERROR_INVALID_PARAMETER);
+ __seterrno ();
+ return -1;
+ }
+ /*FALLTHRUGH*/
+ default:
+ return fhandler_dev_raw::ioctl (cmd, buf);
+ }
+}
+
diff --git a/winsup/cygwin/fhandler_tty.cc b/winsup/cygwin/fhandler_tty.cc
new file mode 100644
index 00000000000..0121d62b417
--- /dev/null
+++ b/winsup/cygwin/fhandler_tty.cc
@@ -0,0 +1,1493 @@
+/* fhandler_tty.cc
+
+ Copyright 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
+ 2006 Red Hat, Inc.
+
+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. */
+
+#include "winsup.h"
+#include <wingdi.h>
+#include <winuser.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <limits.h>
+#include <cygwin/kd.h>
+#include "cygerrno.h"
+#include "security.h"
+#include "path.h"
+#include "fhandler.h"
+#include "dtable.h"
+#include "sigproc.h"
+#include "pinfo.h"
+#include "cygheap.h"
+#include "shared_info.h"
+#include "cygserver.h"
+#include "cygthread.h"
+#include "child_info.h"
+
+/* tty master stuff */
+
+fhandler_tty_master NO_COPY *tty_master;
+
+static DWORD WINAPI process_input (void *); // Input queue thread
+static DWORD WINAPI process_output (void *); // Output queue thread
+static DWORD WINAPI process_ioctl (void *); // Ioctl requests thread
+
+fhandler_tty_master::fhandler_tty_master ()
+ : fhandler_pty_master (), console (NULL)
+{
+}
+
+int
+fhandler_tty_slave::get_unit ()
+{
+ return dev () == FH_TTY ? myself->ctty : dev ().minor;
+}
+
+void
+fhandler_tty_master::set_winsize (bool sendSIGWINCH)
+{
+ winsize w;
+ console->ioctl (TIOCGWINSZ, &w);
+ get_ttyp ()->winsize = w;
+ if (sendSIGWINCH)
+ tc->kill_pgrp (SIGWINCH);
+}
+
+int
+fhandler_tty_master::init ()
+{
+ termios_printf ("Creating master for tty%d", get_unit ());
+
+ if (init_console ())
+ {
+ termios_printf ("can't create fhandler");
+ return -1;
+ }
+
+ termios ti;
+ memset (&ti, 0, sizeof (ti));
+ console->tcsetattr (0, &ti);
+
+ if (!setup (false))
+ return 1;
+
+ set_winsize (false);
+
+ set_close_on_exec (true);
+
+ cygthread *h;
+ h = new cygthread (process_input, 0, cygself, "ttyin");
+ h->SetThreadPriority (THREAD_PRIORITY_HIGHEST);
+ h->zap_h ();
+
+ h = new cygthread (process_ioctl, 0, cygself, "ttyioctl");
+ h->SetThreadPriority (THREAD_PRIORITY_HIGHEST);
+ h->zap_h ();
+
+ h = new cygthread (process_output, 0, cygself, "ttyout");
+ h->SetThreadPriority (THREAD_PRIORITY_HIGHEST);
+ h->zap_h ();
+
+ return 0;
+}
+
+#ifdef DEBUGGING
+static class mutex_stack
+{
+public:
+ const char *fn;
+ int ln;
+ const char *tname;
+} ostack[100];
+
+static int osi;
+#endif /*DEBUGGING*/
+
+DWORD
+fhandler_tty_common::__acquire_output_mutex (const char *fn, int ln,
+ DWORD ms)
+{
+ if (strace.active ())
+ strace.prntf (_STRACE_TERMIOS, fn, "(%d): tty output_mutex: waiting %d ms", ln, ms);
+ DWORD res = WaitForSingleObject (output_mutex, ms);
+ if (res == WAIT_OBJECT_0)
+ {
+#ifndef DEBUGGING
+ if (strace.active ())
+ strace.prntf (_STRACE_TERMIOS, fn, "(%d): tty output_mutex: acquired", ln, res);
+#else
+ ostack[osi].fn = fn;
+ ostack[osi].ln = ln;
+ ostack[osi].tname = cygthread::name ();
+ termios_printf ("acquired for %s:%d, osi %d", fn, ln, osi);
+ osi++;
+#endif
+ }
+ return res;
+}
+
+void
+fhandler_tty_common::__release_output_mutex (const char *fn, int ln)
+{
+ if (ReleaseMutex (output_mutex))
+ {
+#ifndef DEBUGGING
+ if (strace.active ())
+ strace.prntf (_STRACE_TERMIOS, fn, "(%d): tty output_mutex released", ln);
+#else
+ if (osi > 0)
+ osi--;
+ termios_printf ("released at %s:%d, osi %d", fn, ln, osi);
+ termios_printf (" for %s:%d (%s)", ostack[osi].fn, ostack[osi].ln, ostack[osi].tname);
+ ostack[osi].ln = -ln;
+#endif
+ }
+#ifdef DEBUGGING
+ else if (osi > 0)
+ {
+ system_printf ("couldn't release output mutex but we seem to own it, %E");
+ try_to_debug ();
+ }
+#endif
+}
+
+/* Process tty input. */
+
+void
+fhandler_pty_master::doecho (const void *str, DWORD len)
+{
+ acquire_output_mutex (INFINITE);
+ if (!WriteFile (to_master, str, len, &len, NULL))
+ termios_printf ("Write to %p failed, %E", to_master);
+// WaitForSingleObject (output_done_event, INFINITE);
+ release_output_mutex ();
+}
+
+int
+fhandler_pty_master::accept_input ()
+{
+ DWORD bytes_left;
+ int ret = 1;
+
+ WaitForSingleObject (input_mutex, INFINITE);
+
+ bytes_left = eat_readahead (-1);
+
+ if (!bytes_left)
+ {
+ termios_printf ("sending EOF to slave");
+ get_ttyp ()->read_retval = 0;
+ }
+ else
+ {
+ char *p = rabuf;
+ DWORD rc;
+ DWORD written = 0;
+
+ termios_printf ("about to write %d chars to slave", bytes_left);
+ rc = WriteFile (get_output_handle (), p, bytes_left, &written, NULL);
+ if (!rc)
+ {
+ debug_printf ("error writing to pipe %E");
+ get_ttyp ()->read_retval = -1;
+ ret = -1;
+ }
+ else
+ {
+ get_ttyp ()->read_retval = 1;
+ p += written;
+ bytes_left -= written;
+ if (bytes_left > 0)
+ {
+ debug_printf ("to_slave pipe is full");
+ puts_readahead (p, bytes_left);
+ ret = 0;
+ }
+ }
+ }
+
+ SetEvent (input_available_event);
+ ReleaseMutex (input_mutex);
+ return ret;
+}
+
+static DWORD WINAPI
+process_input (void *)
+{
+ char rawbuf[INP_BUFFER_SIZE];
+
+ while (1)
+ {
+ size_t nraw = INP_BUFFER_SIZE;
+ tty_master->console->read ((void *) rawbuf, nraw);
+ if (tty_master->line_edit (rawbuf, nraw, tty_master->get_ttyp ()->ti)
+ == line_edit_signalled)
+ tty_master->console->eat_readahead (-1);
+ }
+}
+
+bool
+fhandler_pty_master::hit_eof ()
+{
+ if (get_ttyp ()->was_opened && !get_ttyp ()->slave_alive ())
+ {
+ /* We have the only remaining open handle to this pty, and
+ the slave pty has been opened at least once. We treat
+ this as EOF. */
+ termios_printf ("all other handles closed");
+ return 1;
+ }
+ return 0;
+}
+
+/* Process tty output requests */
+
+int
+fhandler_pty_master::process_slave_output (char *buf, size_t len, int pktmode_on)
+{
+ size_t rlen;
+ char outbuf[OUT_BUFFER_SIZE + 1];
+ DWORD n;
+ int column = 0;
+ int rc = 0;
+
+ if (len == 0)
+ goto out;
+
+ if (need_nl)
+ {
+ /* We need to return a left over \n character, resulting from
+ \r\n conversion. Note that we already checked for FLUSHO and
+ output_stopped at the time that we read the character, so we
+ don't check again here. */
+ if (buf)
+ buf[0] = '\n';
+ need_nl = 0;
+ rc = 1;
+ goto out;
+ }
+
+
+ for (;;)
+ {
+ /* Set RLEN to the number of bytes to read from the pipe. */
+ rlen = len;
+ if (get_ttyp ()->ti.c_oflag & OPOST && get_ttyp ()->ti.c_oflag & ONLCR)
+ {
+ /* We are going to expand \n to \r\n, so don't read more than
+ half of the number of bytes requested. */
+ rlen /= 2;
+ if (rlen == 0)
+ rlen = 1;
+ }
+ if (rlen > sizeof outbuf)
+ rlen = sizeof outbuf;
+
+ HANDLE handle = get_io_handle ();
+
+ n = 0; // get_readahead_into_buffer (outbuf, len);
+ if (!n)
+ {
+ /* Doing a busy wait like this is quite inefficient, but nothing
+ else seems to work completely. Windows should provide some sort
+ of overlapped I/O for pipes, or something, but it doesn't. */
+ while (1)
+ {
+ if (!PeekNamedPipe (handle, NULL, 0, NULL, &n, NULL))
+ goto err;
+ if (n > 0)
+ break;
+ if (hit_eof ())
+ goto out;
+ /* DISCARD (FLUSHO) and tcflush can finish here. */
+ if (n == 0 && (get_ttyp ()->ti.c_lflag & FLUSHO || !buf))
+ goto out;
+ if (n == 0 && is_nonblocking ())
+ {
+ set_errno (EAGAIN);
+ rc = -1;
+ break;
+ }
+
+ Sleep (10);
+ }
+
+ if (ReadFile (handle, outbuf, rlen, &n, NULL) == FALSE)
+ goto err;
+ }
+
+ termios_printf ("bytes read %u", n);
+ get_ttyp ()->write_error = 0;
+ if (output_done_event != NULL)
+ SetEvent (output_done_event);
+
+ if (get_ttyp ()->ti.c_lflag & FLUSHO || !buf)
+ continue;
+
+ char *optr;
+ optr = buf;
+ if (pktmode_on)
+ *optr++ = TIOCPKT_DATA;
+
+ if (!(get_ttyp ()->ti.c_oflag & OPOST)) // post-process output
+ {
+ memcpy (optr, outbuf, n);
+ optr += n;
+ }
+ else // raw output mode
+ {
+ char *iptr = outbuf;
+
+ while (n--)
+ {
+ switch (*iptr)
+ {
+ case '\r':
+ if ((get_ttyp ()->ti.c_oflag & ONOCR) && column == 0)
+ {
+ iptr++;
+ continue;
+ }
+ if (get_ttyp ()->ti.c_oflag & OCRNL)
+ *iptr = '\n';
+ else
+ column = 0;
+ break;
+ case '\n':
+ if (get_ttyp ()->ti.c_oflag & ONLCR)
+ {
+ *optr++ = '\r';
+ column = 0;
+ }
+ if (get_ttyp ()->ti.c_oflag & ONLRET)
+ column = 0;
+ break;
+ default:
+ column++;
+ break;
+ }
+
+ /* Don't store data past the end of the user's buffer. This
+ can happen if the user requests a read of 1 byte when
+ doing \r\n expansion. */
+ if (optr - buf >= (int) len)
+ {
+ if (*iptr != '\n' || n != 0)
+ system_printf ("internal error: %d unexpected characters", n);
+ need_nl = 1;
+ break;
+ }
+
+ *optr++ = *iptr++;
+ }
+ }
+ rc = optr - buf;
+ break;
+
+ err:
+ if (GetLastError () == ERROR_BROKEN_PIPE)
+ rc = 0;
+ else
+ {
+ __seterrno ();
+ rc = -1;
+ }
+ break;
+ }
+
+out:
+ termios_printf ("returning %d", rc);
+ return rc;
+}
+
+static DWORD WINAPI
+process_output (void *)
+{
+ char buf[OUT_BUFFER_SIZE * 2];
+
+ for (;;)
+ {
+ int n = tty_master->process_slave_output (buf, OUT_BUFFER_SIZE, 0);
+ if (n <= 0)
+ {
+ if (n < 0)
+ termios_printf ("ReadFile %E");
+ ExitThread (0);
+ }
+ n = tty_master->console->write ((void *) buf, (size_t) n);
+ tty_master->get_ttyp ()->write_error = n == -1 ? get_errno () : 0;
+ }
+}
+
+
+/* Process tty ioctl requests */
+
+static DWORD WINAPI
+process_ioctl (void *)
+{
+ while (1)
+ {
+ WaitForSingleObject (tty_master->ioctl_request_event, INFINITE);
+ termios_printf ("ioctl() request");
+ tty *ttyp = tty_master->get_ttyp ();
+ ttyp->ioctl_retval =
+ tty_master->console->ioctl (ttyp->cmd,
+ (ttyp->cmd == KDSKBMETA)
+ ? (void *) ttyp->arg.value
+ : (void *) &ttyp->arg);
+ SetEvent (tty_master->ioctl_done_event);
+ }
+}
+
+/**********************************************************************/
+/* Tty slave stuff */
+
+fhandler_tty_slave::fhandler_tty_slave ()
+ : fhandler_tty_common (), inuse (NULL)
+{
+ uninterruptible_io (true);
+}
+
+/* FIXME: This function needs to close handles when it has
+ a failing condition. */
+int
+fhandler_tty_slave::open (int flags, mode_t)
+{
+ if (get_device () == FH_TTY)
+ dev().tty_to_real_device ();
+ fhandler_tty_slave *arch = (fhandler_tty_slave *) cygheap->fdtab.find_archetype (pc.dev);
+ if (arch)
+ {
+ *this = *(fhandler_tty_slave *) arch;
+ termios_printf ("copied fhandler_tty_slave archetype");
+ set_flags ((flags & ~O_TEXT) | O_BINARY);
+ cygheap->manage_console_count ("fhandler_tty_slave::open<arch>", 1);
+ goto out;
+ }
+
+ tcinit (cygwin_shared->tty[get_unit ()]);
+
+ cygwin_shared->tty.attach (get_unit ());
+
+ set_flags ((flags & ~O_TEXT) | O_BINARY);
+ /* Create synchronisation events */
+ char buf[CYG_MAX_PATH];
+
+ /* output_done_event may or may not exist. It will exist if the tty
+ was opened by fhandler_tty_master::init, normally called at
+ startup if use_tty is non-zero. It will not exist if this is a
+ pty opened by fhandler_pty_master::open. In the former case, tty
+ output is handled by a separate thread which controls output. */
+ shared_name (buf, OUTPUT_DONE_EVENT, get_unit ());
+ output_done_event = OpenEvent (EVENT_ALL_ACCESS, TRUE, buf);
+
+ if (!(output_mutex = get_ttyp ()->open_output_mutex ()))
+ {
+ termios_printf ("open output mutex failed, %E");
+ __seterrno ();
+ return 0;
+ }
+ if (!(input_mutex = get_ttyp ()->open_input_mutex ()))
+ {
+ termios_printf ("open input mutex failed, %E");
+ __seterrno ();
+ return 0;
+ }
+ shared_name (buf, INPUT_AVAILABLE_EVENT, get_unit ());
+ if (!(input_available_event = OpenEvent (EVENT_ALL_ACCESS, TRUE, buf)))
+ {
+ termios_printf ("open input event failed, %E");
+ __seterrno ();
+ return 0;
+ }
+
+ /* The ioctl events may or may not exist. See output_done_event,
+ above. */
+ shared_name (buf, IOCTL_REQUEST_EVENT, get_unit ());
+ ioctl_request_event = OpenEvent (EVENT_ALL_ACCESS, TRUE, buf);
+ shared_name (buf, IOCTL_DONE_EVENT, get_unit ());
+ ioctl_done_event = OpenEvent (EVENT_ALL_ACCESS, TRUE, buf);
+
+ /* FIXME: Needs a method to eliminate tty races */
+ {
+ acquire_output_mutex (500);
+ inuse = get_ttyp ()->create_inuse (TTY_SLAVE_ALIVE);
+ get_ttyp ()->was_opened = true;
+ release_output_mutex ();
+ }
+
+ if (!get_ttyp ()->from_master || !get_ttyp ()->to_master)
+ {
+ termios_printf ("tty handles have been closed");
+ set_errno (EACCES);
+ return 0;
+ }
+
+ HANDLE from_master_local;
+ HANDLE to_master_local;
+ from_master_local = to_master_local = NULL;
+
+#ifdef USE_SERVER
+ if (!wincap.has_security ()
+ || cygserver_running == CYGSERVER_UNAVAIL
+ || !cygserver_attach_tty (&from_master_local, &to_master_local))
+#endif
+ {
+ if (get_ttyp ()->master_pid < 0)
+ {
+ set_errno (EAGAIN);
+ termios_printf ("*** master is closed");
+ return 0;
+ }
+ pinfo p (get_ttyp ()->master_pid);
+ if (!p)
+ {
+ set_errno (EAGAIN);
+ termios_printf ("*** couldn't find tty master");
+ return 0;
+ }
+#ifdef USE_SERVER
+ termios_printf ("cannot dup handles via server. using old method.");
+#endif
+ HANDLE tty_owner = OpenProcess (PROCESS_DUP_HANDLE, FALSE,
+ p->dwProcessId);
+ if (tty_owner == NULL)
+ {
+ termios_printf ("can't open tty (%d) handle process %d",
+ get_unit (), get_ttyp ()->master_pid);
+ __seterrno ();
+ return 0;
+ }
+
+ if (!DuplicateHandle (tty_owner, get_ttyp ()->from_master,
+ hMainProc, &from_master_local, 0, TRUE,
+ DUPLICATE_SAME_ACCESS))
+ {
+ termios_printf ("can't duplicate input, %E");
+ __seterrno ();
+ return 0;
+ }
+
+ VerifyHandle (from_master_local);
+ if (!DuplicateHandle (tty_owner, get_ttyp ()->to_master,
+ hMainProc, &to_master_local, 0, TRUE,
+ DUPLICATE_SAME_ACCESS))
+ {
+ termios_printf ("can't duplicate output, %E");
+ __seterrno ();
+ return 0;
+ }
+ VerifyHandle (to_master_local);
+ CloseHandle (tty_owner);
+ }
+
+ termios_printf ("duplicated from_master %p->%p from tty_owner",
+ get_ttyp ()->from_master, from_master_local);
+ termios_printf ("duplicated to_master %p->%p from tty_owner",
+ get_ttyp ()->to_master, to_master_local);
+
+ set_io_handle (from_master_local);
+ set_output_handle (to_master_local);
+
+ set_open_status ();
+ if (cygheap->manage_console_count ("fhandler_tty_slave::open", 1) == 1
+ && !output_done_event)
+ fhandler_console::need_invisible ();
+
+ // FIXME: Do this better someday
+ arch = (fhandler_tty_slave *) cmalloc (HEAP_ARCHETYPES, sizeof (*this));
+ *((fhandler_tty_slave **) cygheap->fdtab.add_archetype ()) = arch;
+ archetype = arch;
+ *arch = *this;
+
+out:
+ usecount = 0;
+ arch->usecount++;
+ report_tty_counts (this, "opened", "");
+ myself->set_ctty (get_ttyp (), flags, arch);
+
+ return 1;
+}
+
+int
+fhandler_tty_slave::close ()
+{
+ /* This used to always call fhandler_tty_common::close when hExeced but that
+ caused multiple closes of the handles associated with this tty. Since
+ close_all_files is not called until after the cygwin process has synced
+ or before a non-cygwin process has exited, it should be safe to just
+ close this normally. cgf 2006-05-20 */
+ cygheap->manage_console_count ("fhandler_tty_slave::close", -1);
+
+ archetype->usecount--;
+ report_tty_counts (this, "closed", "");
+
+ if (archetype->usecount)
+ {
+#ifdef DEBUGGING
+ if (archetype->usecount < 0)
+ system_printf ("error: usecount %d", archetype->usecount);
+#endif
+ termios_printf ("just returning because archetype usecount is != 0");
+ return 0;
+ }
+
+ termios_printf ("closing last open %s handle", ttyname ());
+ if (inuse && !CloseHandle (inuse))
+ termios_printf ("CloseHandle (inuse), %E");
+ return fhandler_tty_common::close ();
+}
+
+int
+fhandler_tty_slave::cygserver_attach_tty (LPHANDLE from_master_ptr,
+ LPHANDLE to_master_ptr)
+{
+#ifndef USE_SERVER
+ return 0;
+#else
+ if (!from_master_ptr || !to_master_ptr)
+ return 0;
+
+ client_request_attach_tty req ((DWORD) get_ttyp ()->master_pid,
+ (HANDLE) get_ttyp ()->from_master,
+ (HANDLE) get_ttyp ()->to_master);
+
+ if (req.make_request () == -1 || req.error_code ())
+ return 0;
+
+ *from_master_ptr = req.from_master ();
+ *to_master_ptr = req.to_master ();
+
+ return 1;
+#endif
+}
+
+void
+fhandler_tty_slave::init (HANDLE, DWORD a, mode_t)
+{
+ int flags = 0;
+
+ a &= GENERIC_READ | GENERIC_WRITE;
+ if (a == GENERIC_READ)
+ flags = O_RDONLY;
+ if (a == GENERIC_WRITE)
+ flags = O_WRONLY;
+ if (a == (GENERIC_READ | GENERIC_WRITE))
+ flags = O_RDWR;
+
+ open (flags);
+}
+
+int
+fhandler_tty_slave::write (const void *ptr, size_t len)
+{
+ DWORD n, towrite = len;
+
+ termios_printf ("tty%d, write(%x, %d)", get_unit (), ptr, len);
+
+ acquire_output_mutex (INFINITE);
+
+ while (len)
+ {
+ n = min (OUT_BUFFER_SIZE, len);
+ char *buf = (char *)ptr;
+ ptr = (char *) ptr + n;
+ len -= n;
+
+ /* Previous write may have set write_error to != 0. Check it here.
+ This is less than optimal, but the alternative slows down tty
+ writes enormously. */
+ if (get_ttyp ()->write_error)
+ {
+ set_errno (get_ttyp ()->write_error);
+ towrite = (DWORD) -1;
+ break;
+ }
+
+ if (WriteFile (get_output_handle (), buf, n, &n, NULL) == FALSE)
+ {
+ DWORD err = GetLastError ();
+ termios_printf ("WriteFile failed, %E");
+ switch (err)
+ {
+ case ERROR_NO_DATA:
+ err = ERROR_IO_DEVICE;
+ default:
+ __seterrno_from_win_error (err);
+ }
+ raise (SIGHUP); /* FIXME: Should this be SIGTTOU? */
+ towrite = (DWORD) -1;
+ break;
+ }
+
+ if (output_done_event != NULL)
+ {
+ DWORD rc;
+ DWORD x = n * 1000;
+ rc = WaitForSingleObject (output_done_event, x);
+ termios_printf ("waited %d ms for output_done_event, WFSO %d", x, rc);
+ }
+ }
+ release_output_mutex ();
+ return towrite;
+}
+
+void __stdcall
+fhandler_tty_slave::read (void *ptr, size_t& len)
+{
+ int totalread = 0;
+ int vmin = 0;
+ int vtime = 0; /* Initialized to prevent -Wuninitialized warning */
+ size_t readlen;
+ DWORD bytes_in_pipe;
+ char buf[INP_BUFFER_SIZE];
+ char peek_buf[INP_BUFFER_SIZE];
+ DWORD time_to_wait;
+ DWORD rc;
+ HANDLE w4[2];
+
+ termios_printf ("read(%x, %d) handle %p", ptr, len, get_handle ());
+
+ if (!ptr) /* Indicating tcflush(). */
+ time_to_wait = 0;
+ else if ((get_ttyp ()->ti.c_lflag & ICANON))
+ time_to_wait = INFINITE;
+ else
+ {
+ vmin = get_ttyp ()->ti.c_cc[VMIN];
+ if (vmin > INP_BUFFER_SIZE)
+ vmin = INP_BUFFER_SIZE;
+ vtime = get_ttyp ()->ti.c_cc[VTIME];
+ if (vmin < 0)
+ vmin = 0;
+ if (vtime < 0)
+ vtime = 0;
+ if (!vmin && !vtime)
+ time_to_wait = 0;
+ else
+ time_to_wait = !vtime ? INFINITE : 100 * vtime;
+ }
+
+ w4[0] = signal_arrived;
+ w4[1] = input_available_event;
+
+ DWORD waiter = time_to_wait;
+ while (len)
+ {
+ rc = WaitForMultipleObjects (2, w4, FALSE, waiter);
+
+ if (rc == WAIT_TIMEOUT)
+ {
+ termios_printf ("wait timed out, waiter %u", waiter);
+ break;
+ }
+
+ if (rc == WAIT_FAILED)
+ {
+ termios_printf ("wait for input event failed, %E");
+ break;
+ }
+
+ if (rc == WAIT_OBJECT_0)
+ {
+ /* if we've received signal after successfully reading some data,
+ just return all data successfully read */
+ if (totalread > 0)
+ break;
+ set_sig_errno (EINTR);
+ len = (size_t) -1;
+ return;
+ }
+
+ rc = WaitForSingleObject (input_mutex, 1000);
+ if (rc == WAIT_FAILED)
+ {
+ termios_printf ("wait for input mutex failed, %E");
+ break;
+ }
+ else if (rc == WAIT_TIMEOUT)
+ {
+ termios_printf ("failed to acquire input mutex after input event arrived");
+ break;
+ }
+ if (!PeekNamedPipe (get_handle (), peek_buf, sizeof (peek_buf), &bytes_in_pipe, NULL, NULL))
+ {
+ termios_printf ("PeekNamedPipe failed, %E");
+ raise (SIGHUP);
+ bytes_in_pipe = 0;
+ }
+
+ /* On first peek determine no. of bytes to flush. */
+ if (!ptr && len == UINT_MAX)
+ len = (size_t) bytes_in_pipe;
+
+ if (ptr && !bytes_in_pipe && !vmin && !time_to_wait)
+ {
+ ReleaseMutex (input_mutex);
+ len = (size_t) bytes_in_pipe;
+ return;
+ }
+
+ readlen = min (bytes_in_pipe, min (len, sizeof (buf)));
+
+ if (ptr && vmin && readlen > (unsigned) vmin)
+ readlen = vmin;
+
+ DWORD n = 0;
+ if (readlen)
+ {
+ termios_printf ("reading %d bytes (vtime %d)", readlen, vtime);
+ if (ReadFile (get_handle (), buf, readlen, &n, NULL) == FALSE)
+ {
+ termios_printf ("read failed, %E");
+ raise (SIGHUP);
+ }
+ /* MSDN states that 5th prameter can be used to determine total
+ number of bytes in pipe, but for some reason this number doesn't
+ change after successful read. So we have to peek into the pipe
+ again to see if input is still available */
+ if (!PeekNamedPipe (get_handle (), peek_buf, 1, &bytes_in_pipe, NULL, NULL))
+ {
+ termios_printf ("PeekNamedPipe failed, %E");
+ raise (SIGHUP);
+ bytes_in_pipe = 0;
+ }
+ if (n)
+ {
+ len -= n;
+ totalread += n;
+ if (ptr)
+ {
+ memcpy (ptr, buf, n);
+ ptr = (char *) ptr + n;
+ }
+ }
+ }
+
+ if (!bytes_in_pipe)
+ ResetEvent (input_available_event);
+
+ ReleaseMutex (input_mutex);
+
+ if (!ptr)
+ {
+ if (!bytes_in_pipe)
+ break;
+ continue;
+ }
+
+ if (get_ttyp ()->read_retval < 0) // read error
+ {
+ set_errno (-get_ttyp ()->read_retval);
+ totalread = -1;
+ break;
+ }
+ if (get_ttyp ()->read_retval == 0) //EOF
+ {
+ termios_printf ("saw EOF");
+ break;
+ }
+ if (get_ttyp ()->ti.c_lflag & ICANON || is_nonblocking ())
+ break;
+ if (vmin && totalread >= vmin)
+ break;
+
+ /* vmin == 0 && vtime == 0:
+ * we've already read all input, if any, so return immediately
+ * vmin == 0 && vtime > 0:
+ * we've waited for input 10*vtime ms in WFSO(input_available_event),
+ * no matter whether any input arrived, we shouldn't wait any longer,
+ * so return immediately
+ * vmin > 0 && vtime == 0:
+ * here, totalread < vmin, so continue waiting until more data
+ * arrive
+ * vmin > 0 && vtime > 0:
+ * similar to the previous here, totalread < vmin, and timer
+ * hadn't expired -- WFSO(input_available_event) != WAIT_TIMEOUT,
+ * so "restart timer" and wait until more data arrive
+ */
+
+ if (vmin == 0)
+ break;
+
+ if (n)
+ waiter = time_to_wait;
+ }
+ termios_printf ("%d=read(%x, %d)", totalread, ptr, len);
+ len = (size_t) totalread;
+}
+
+int
+fhandler_tty_slave::dup (fhandler_base *child)
+{
+ fhandler_tty_slave *arch = (fhandler_tty_slave *) archetype;
+ *(fhandler_tty_slave *) child = *arch;
+ child->usecount = 0;
+ arch->usecount++;
+ cygheap->manage_console_count ("fhandler_tty_slave::dup", 1);
+ report_tty_counts (child, "duped", "");
+ return 0;
+}
+
+int
+fhandler_pty_master::dup (fhandler_base *child)
+{
+ fhandler_tty_master *arch = (fhandler_tty_master *) archetype;
+ *(fhandler_tty_master *) child = *arch;
+ child->usecount = 0;
+ arch->usecount++;
+ report_tty_counts (child, "duped master", "");
+ return 0;
+}
+
+int
+fhandler_tty_slave::tcgetattr (struct termios *t)
+{
+ *t = get_ttyp ()->ti;
+ return 0;
+}
+
+int
+fhandler_tty_slave::tcsetattr (int, const struct termios *t)
+{
+ acquire_output_mutex (INFINITE);
+ get_ttyp ()->ti = *t;
+ release_output_mutex ();
+ return 0;
+}
+
+int
+fhandler_tty_slave::tcflush (int queue)
+{
+ int ret = 0;
+
+ termios_printf ("tcflush(%d) handle %p", queue, get_handle ());
+
+ if (queue == TCIFLUSH || queue == TCIOFLUSH)
+ {
+ size_t len = UINT_MAX;
+ read (NULL, len);
+ ret = ((int) len) >= 0 ? 0 : -1;
+ }
+ if (queue == TCOFLUSH || queue == TCIOFLUSH)
+ {
+ /* do nothing for now. */
+ }
+
+ termios_printf ("%d=tcflush(%d)", ret, queue);
+ return ret;
+}
+
+int
+fhandler_tty_slave::ioctl (unsigned int cmd, void *arg)
+{
+ termios_printf ("ioctl (%x)", cmd);
+
+ if (myself->pgid && get_ttyp ()->getpgid () != myself->pgid
+ && myself->ctty == get_unit () && (get_ttyp ()->ti.c_lflag & TOSTOP))
+ {
+ /* background process */
+ termios_printf ("bg ioctl pgid %d, tpgid %d, %s", myself->pgid,
+ get_ttyp ()->getpgid (), myctty ());
+ raise (SIGTTOU);
+ }
+
+ int retval;
+ switch (cmd)
+ {
+ case TIOCGWINSZ:
+ case TIOCSWINSZ:
+ case TIOCLINUX:
+ case KDGKBMETA:
+ case KDSKBMETA:
+ break;
+ case FIONBIO:
+ set_nonblocking (*(int *) arg);
+ retval = 0;
+ goto out;
+ default:
+ set_errno (EINVAL);
+ return -1;
+ }
+
+ acquire_output_mutex (INFINITE);
+
+ get_ttyp ()->cmd = cmd;
+ get_ttyp ()->ioctl_retval = 0;
+ int val;
+ switch (cmd)
+ {
+ case TIOCGWINSZ:
+ get_ttyp ()->arg.winsize = get_ttyp ()->winsize;
+ if (ioctl_request_event)
+ SetEvent (ioctl_request_event);
+ *(struct winsize *) arg = get_ttyp ()->arg.winsize;
+ if (ioctl_done_event)
+ WaitForSingleObject (ioctl_done_event, INFINITE);
+ get_ttyp ()->winsize = get_ttyp ()->arg.winsize;
+ break;
+ case TIOCSWINSZ:
+ if (get_ttyp ()->winsize.ws_row != ((struct winsize *) arg)->ws_row
+ || get_ttyp ()->winsize.ws_col != ((struct winsize *) arg)->ws_col)
+ {
+ get_ttyp ()->arg.winsize = *(struct winsize *) arg;
+ if (ioctl_request_event)
+ {
+ get_ttyp ()->ioctl_retval = -EINVAL;
+ SetEvent (ioctl_request_event);
+ }
+ else
+ {
+ get_ttyp ()->winsize = *(struct winsize *) arg;
+ killsys (-get_ttyp ()->getpgid (), SIGWINCH);
+ }
+ if (ioctl_done_event)
+ WaitForSingleObject (ioctl_done_event, INFINITE);
+ }
+ break;
+ case TIOCLINUX:
+ val = *(unsigned char *) arg;
+ if (val != 6 || !ioctl_request_event || !ioctl_done_event)
+ get_ttyp ()->ioctl_retval = -EINVAL;
+ else
+ {
+ get_ttyp ()->arg.value = val;
+ SetEvent (ioctl_request_event);
+ WaitForSingleObject (ioctl_done_event, INFINITE);
+ *(unsigned char *) arg = get_ttyp ()->arg.value & 0xFF;
+ }
+ break;
+ case KDGKBMETA:
+ if (ioctl_request_event)
+ {
+ SetEvent (ioctl_request_event);
+ if (ioctl_done_event)
+ WaitForSingleObject (ioctl_done_event, INFINITE);
+ *(int *) arg = get_ttyp ()->arg.value;
+ }
+ else
+ get_ttyp ()->ioctl_retval = -EINVAL;
+ break;
+ case KDSKBMETA:
+ if (ioctl_request_event)
+ {
+ get_ttyp ()->arg.value = (int) arg;
+ SetEvent (ioctl_request_event);
+ if (ioctl_done_event)
+ WaitForSingleObject (ioctl_done_event, INFINITE);
+ }
+ else
+ get_ttyp ()->ioctl_retval = -EINVAL;
+ break;
+ }
+
+ release_output_mutex ();
+ retval = get_ttyp ()->ioctl_retval;
+ if (retval < 0)
+ {
+ set_errno (-retval);
+ retval = -1;
+ }
+
+out:
+ termios_printf ("%d = ioctl (%x)", retval, cmd);
+ return retval;
+}
+
+/*******************************************************
+ fhandler_pty_master
+*/
+fhandler_pty_master::fhandler_pty_master ()
+ : fhandler_tty_common (), pktmode (0), need_nl (0), dwProcessId (0)
+{
+}
+
+int
+fhandler_pty_master::open (int flags, mode_t)
+{
+ int ntty;
+ ntty = cygwin_shared->tty.allocate (false);
+ if (ntty < 0)
+ return 0;
+
+ dev().devn = FHDEV (DEV_TTYM_MAJOR, ntty);
+ if (!setup (true))
+ {
+ lock_ttys::release ();
+ return 0;
+ }
+ lock_ttys::release ();
+ set_flags ((flags & ~O_TEXT) | O_BINARY);
+ set_open_status ();
+ //
+ // FIXME: Do this better someday
+ fhandler_pty_master *arch = (fhandler_tty_master *) cmalloc (HEAP_ARCHETYPES, sizeof (*this));
+ *((fhandler_pty_master **) cygheap->fdtab.add_archetype ()) = arch;
+ archetype = arch;
+ *arch = *this;
+ arch->dwProcessId = GetCurrentProcessId ();
+
+ usecount = 0;
+ arch->usecount++;
+ char buf[sizeof ("opened pty master for ttyNNNNNNNNNNN")];
+ __small_sprintf (buf, "opened pty master for tty%d", get_unit ());
+ report_tty_counts (this, buf, "");
+ return 1;
+}
+
+_off64_t
+fhandler_tty_common::lseek (_off64_t, int)
+{
+ set_errno (ESPIPE);
+ return -1;
+}
+
+int
+fhandler_tty_common::close ()
+{
+ termios_printf ("tty%d <%p,%p> closing", get_unit (), get_handle (), get_output_handle ());
+ if (output_done_event && !CloseHandle (output_done_event))
+ termios_printf ("CloseHandle (output_done_event), %E");
+ if (ioctl_done_event && !CloseHandle (ioctl_done_event))
+ termios_printf ("CloseHandle (ioctl_done_event), %E");
+ if (ioctl_request_event && !CloseHandle (ioctl_request_event))
+ termios_printf ("CloseHandle (ioctl_request_event), %E");
+ if (!ForceCloseHandle (input_mutex))
+ termios_printf ("CloseHandle (input_mutex<%p>), %E", input_mutex);
+ if (!ForceCloseHandle (output_mutex))
+ termios_printf ("CloseHandle (output_mutex<%p>), %E", output_mutex);
+ if (!ForceCloseHandle1 (get_handle (), from_pty))
+ termios_printf ("CloseHandle (get_handle ()<%p>), %E", get_handle ());
+ if (!ForceCloseHandle1 (get_output_handle (), to_pty))
+ termios_printf ("CloseHandle (get_output_handle ()<%p>), %E", get_output_handle ());
+
+ if (!ForceCloseHandle (input_available_event))
+ termios_printf ("CloseHandle (input_available_event<%p>), %E", input_available_event);
+
+ return 0;
+}
+
+int
+fhandler_pty_master::close ()
+{
+#if 0
+ while (accept_input () > 0)
+ continue;
+#endif
+ archetype->usecount--;
+ report_tty_counts (this, "closing master", "");
+
+ if (archetype->usecount)
+ {
+#ifdef DEBUGGING
+ if (archetype->usecount < 0)
+ system_printf ("error: usecount %d", archetype->usecount);
+#endif
+ termios_printf ("just returning because archetype usecount is != 0");
+ return 0;
+ }
+
+ fhandler_tty_master *arch = (fhandler_tty_master *) archetype;
+ termios_printf ("closing from_master(%p)/to_master(%p) since we own them(%d)",
+ arch->from_master, arch->to_master, arch->dwProcessId);
+ if (!ForceCloseHandle (arch->from_master))
+ termios_printf ("error closing from_master %p, %E", arch->from_master);
+ if (!ForceCloseHandle (arch->to_master))
+ termios_printf ("error closing from_master %p, %E", arch->to_master);
+ fhandler_tty_common::close ();
+
+ if (hExeced || get_ttyp ()->master_pid != myself->pid)
+ termios_printf ("not clearing: %d, master_pid %d", hExeced, get_ttyp ()->master_pid);
+ else
+ get_ttyp ()->set_master_closed ();
+
+ return 0;
+}
+
+int
+fhandler_pty_master::write (const void *ptr, size_t len)
+{
+ int i;
+ char *p = (char *) ptr;
+ termios ti = tc->ti;
+
+ for (i = 0; i < (int) len; i++)
+ {
+ line_edit_status status = line_edit (p++, 1, ti);
+ if (status > line_edit_signalled)
+ {
+ if (status != line_edit_pipe_full)
+ i = -1;
+ break;
+ }
+ }
+ return i;
+}
+
+void __stdcall
+fhandler_pty_master::read (void *ptr, size_t& len)
+{
+ len = (size_t) process_slave_output ((char *) ptr, len, pktmode);
+}
+
+int
+fhandler_pty_master::tcgetattr (struct termios *t)
+{
+ *t = cygwin_shared->tty[get_unit ()]->ti;
+ return 0;
+}
+
+int
+fhandler_pty_master::tcsetattr (int, const struct termios *t)
+{
+ cygwin_shared->tty[get_unit ()]->ti = *t;
+ return 0;
+}
+
+int
+fhandler_pty_master::tcflush (int queue)
+{
+ int ret = 0;
+
+ termios_printf ("tcflush(%d) handle %p", queue, get_handle ());
+
+ if (queue == TCIFLUSH || queue == TCIOFLUSH)
+ ret = process_slave_output (NULL, OUT_BUFFER_SIZE, 0);
+ else if (queue == TCIFLUSH || queue == TCIOFLUSH)
+ {
+ /* do nothing for now. */
+ }
+
+ termios_printf ("%d=tcflush(%d)", ret, queue);
+ return ret;
+}
+
+int
+fhandler_pty_master::ioctl (unsigned int cmd, void *arg)
+{
+ switch (cmd)
+ {
+ case TIOCPKT:
+ pktmode = *(int *) arg;
+ break;
+ case TIOCGWINSZ:
+ *(struct winsize *) arg = get_ttyp ()->winsize;
+ break;
+ case TIOCSWINSZ:
+ if (get_ttyp ()->winsize.ws_row != ((struct winsize *) arg)->ws_row
+ || get_ttyp ()->winsize.ws_col != ((struct winsize *) arg)->ws_col)
+ {
+ get_ttyp ()->winsize = *(struct winsize *) arg;
+ killsys (-get_ttyp ()->getpgid (), SIGWINCH);
+ }
+ break;
+ case FIONBIO:
+ set_nonblocking (*(int *) arg);
+ break;
+ default:
+ set_errno (EINVAL);
+ return -1;
+ }
+ return 0;
+}
+
+char *
+fhandler_pty_master::ptsname ()
+{
+ static char buf[32];
+
+ __small_sprintf (buf, "/dev/tty%d", get_unit ());
+ return buf;
+}
+
+void
+fhandler_tty_common::set_close_on_exec (bool val)
+{
+ // Cygwin processes will handle this specially on exec.
+ close_on_exec (val);
+}
+
+void
+fhandler_tty_slave::fixup_after_fork (HANDLE parent)
+{
+ // fork_fixup (parent, inuse, "inuse");
+ // fhandler_tty_common::fixup_after_fork (parent);
+ report_tty_counts (this, "inherited", "");
+}
+
+void
+fhandler_tty_slave::fixup_after_exec ()
+{
+ if (!close_on_exec ())
+ fixup_after_fork (NULL);
+}
+
+int
+fhandler_tty_master::init_console ()
+{
+ console = (fhandler_console *) build_fh_dev (*console_dev, "/dev/ttym");
+ if (console == NULL)
+ return -1;
+
+ console->init (INVALID_HANDLE_VALUE, GENERIC_READ | GENERIC_WRITE, O_BINARY);
+ cygheap->manage_console_count ("fhandler_tty_master::init_console", -1, true);
+ console->uninterruptible_io (true);
+ return 0;
+}
+
+#define close_maybe(h) \
+ do { \
+ if (h) \
+ CloseHandle (h); \
+ } while (0)
+
+bool
+fhandler_pty_master::setup (bool ispty)
+{
+ tty& t = *cygwin_shared->tty[get_unit ()];
+
+ tcinit (&t, true); /* Set termios information. Force initialization. */
+
+ const char *errstr = NULL;
+ DWORD pipe_mode = PIPE_NOWAIT;
+
+ /* Create communication pipes */
+
+ /* FIXME: should this be sec_none_nih? */
+ if (!CreatePipe (&from_master, &get_output_handle (), &sec_all, 128 * 1024))
+ {
+ errstr = "input pipe";
+ goto err;
+ }
+
+ if (!CreatePipe (&get_io_handle (), &to_master, &sec_all, 128 * 1024))
+ {
+ errstr = "output pipe";
+ goto err;
+ }
+
+ if (!SetNamedPipeHandleState (get_output_handle (), &pipe_mode, NULL, NULL))
+ termios_printf ("can't set output_handle(%p) to non-blocking mode",
+ get_output_handle ());
+
+ need_nl = 0;
+
+ /* We do not open allow the others to open us (for handle duplication)
+ but rely on cygheap->inherited_ctty for descendant processes.
+ In the future the cygserver may allow access by others. */
+
+#ifdef USE_SERVER
+ if (wincap.has_security ())
+ {
+ if (cygserver_running == CYGSERVER_UNKNOWN)
+ cygserver_init ();
+ }
+#endif
+
+ /* Create synchronisation events */
+
+ if (!ispty)
+ {
+ if (!(output_done_event = t.get_event (errstr = OUTPUT_DONE_EVENT)))
+ goto err;
+ if (!(ioctl_done_event = t.get_event (errstr = IOCTL_DONE_EVENT)))
+ goto err;
+ if (!(ioctl_request_event = t.get_event (errstr = IOCTL_REQUEST_EVENT)))
+ goto err;
+ }
+
+ if (!(input_available_event = t.get_event (errstr = INPUT_AVAILABLE_EVENT, TRUE)))
+ goto err;
+
+ char buf[CYG_MAX_PATH];
+ errstr = shared_name (buf, OUTPUT_MUTEX, t.ntty);
+ if (!(output_mutex = CreateMutex (&sec_all, FALSE, buf)))
+ goto err;
+
+ errstr = shared_name (buf, INPUT_MUTEX, t.ntty);
+ if (!(input_mutex = CreateMutex (&sec_all, FALSE, buf)))
+ goto err;
+
+ if (!DuplicateHandle (hMainProc, from_master, hMainProc, &from_master, 0, false,
+ DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE))
+ {
+ errstr = "non-inheritable from_master";
+ goto err;
+ }
+
+ if (!DuplicateHandle (hMainProc, to_master, hMainProc, &to_master, 0, false,
+ DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE))
+ {
+ errstr = "non-inheritable to_master";
+ goto err;
+ }
+
+ t.from_master = from_master;
+ t.to_master = to_master;
+ // /* screws up tty master */ ProtectHandle1INH (output_mutex, output_mutex);
+ // /* screws up tty master */ ProtectHandle1INH (input_mutex, input_mutex);
+ t.winsize.ws_col = 80;
+ t.winsize.ws_row = 25;
+ t.master_pid = myself->pid;
+
+ termios_printf ("tty%d opened - from_slave %p, to_slave %p", t.ntty,
+ get_io_handle (), get_output_handle ());
+ return true;
+
+err:
+ __seterrno ();
+ close_maybe (get_io_handle ());
+ close_maybe (get_output_handle ());
+ close_maybe (output_done_event);
+ close_maybe (ioctl_done_event);
+ close_maybe (ioctl_request_event);
+ close_maybe (input_available_event);
+ close_maybe (output_mutex);
+ close_maybe (input_mutex);
+ close_maybe (from_master);
+ close_maybe (to_master);
+ termios_printf ("tty%d open failed - failed to create %s", errstr);
+ return false;
+}
+
+void
+fhandler_pty_master::fixup_after_fork (HANDLE parent)
+{
+ DWORD wpid = GetCurrentProcessId ();
+ fhandler_tty_master *arch = (fhandler_tty_master *) archetype;
+ if (arch->dwProcessId != wpid)
+ {
+ tty& t = *get_ttyp ();
+ if (!DuplicateHandle (parent, arch->from_master, hMainProc,
+ &arch->from_master, 0, false, DUPLICATE_SAME_ACCESS))
+ system_printf ("couldn't duplicate from_parent(%p), %E", arch->from_master);
+ if (!DuplicateHandle (parent, arch->to_master, hMainProc,
+ &arch->to_master, 0, false, DUPLICATE_SAME_ACCESS))
+ system_printf ("couldn't duplicate to_parent(%p), %E", arch->from_master);
+ if (myself->pid == t.master_pid)
+ {
+ t.from_master = arch->from_master;
+ t.to_master = arch->to_master;
+ }
+ arch->dwProcessId = wpid;
+ }
+ from_master = arch->from_master;
+ to_master = arch->to_master;
+ report_tty_counts (this, "inherited master", "");
+}
+
+void
+fhandler_pty_master::fixup_after_exec ()
+{
+ if (!close_on_exec ())
+ fixup_after_fork (spawn_info->parent);
+ else
+ from_master = to_master = NULL;
+}
diff --git a/winsup/cygwin/fork.cc b/winsup/cygwin/fork.cc
index 20436291143..ed85e74cf02 100644
--- a/winsup/cygwin/fork.cc
+++ b/winsup/cygwin/fork.cc
@@ -533,6 +533,7 @@ fork ()
return -1;
}
+ lock_process now;
if (sig_send (NULL, __SIGHOLD))
{
if (exit_state)
@@ -547,7 +548,10 @@ fork ()
__asm__ volatile ("movl %%esp,%0": "=r" (esp));
if (ischild)
- res = grouped.child (esp);
+ {
+ res = grouped.child (esp);
+ now.dont_bother ();
+ }
else
{
res = grouped.parent (esp);
diff --git a/winsup/cygwin/include/cygwin/types.h b/winsup/cygwin/include/cygwin/types.h
new file mode 100644
index 00000000000..f9242111659
--- /dev/null
+++ b/winsup/cygwin/include/cygwin/types.h
@@ -0,0 +1,252 @@
+/* types.h
+
+ Copyright 2001, 2002, 2003, 2005 Red Hat Inc.
+ Written by Robert Collins <rbtcollins@hotmail.com>
+
+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. */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#ifndef _CYGWIN_TYPES_H
+#define _CYGWIN_TYPES_H
+
+#include <sys/sysmacros.h>
+#include <stdint.h>
+#include <endian.h>
+
+#ifndef __timespec_t_defined
+#define __timespec_t_defined
+typedef struct timespec timespec_t;
+#endif /*__timespec_t_defined*/
+
+#ifndef __timestruc_t_defined
+#define __timestruc_t_defined
+typedef struct timespec timestruc_t;
+#endif /*__timestruc_t_defined*/
+
+#ifndef __off_t_defined
+#define __off_t_defined
+#ifdef __CYGWIN_USE_BIG_TYPES__
+typedef _off64_t off_t;
+#else
+typedef _off_t off_t;
+#endif
+#endif /*__off_t_defined*/
+
+typedef __loff_t loff_t;
+
+#ifndef __dev_t_defined
+#define __dev_t_defined
+typedef short __dev16_t;
+typedef unsigned long __dev32_t;
+#ifdef __CYGWIN_USE_BIG_TYPES__
+typedef __dev32_t dev_t;
+#else
+typedef __dev16_t dev_t;
+#endif
+#endif /*__dev_t_defined*/
+
+#ifndef __blksize_t_defined
+#define __blksize_t_defined
+typedef long blksize_t;
+#endif /*__blksize_t_defined*/
+
+#ifndef __blkcnt_t_defined
+#define __blkcnt_t_defined
+typedef long __blkcnt32_t;
+typedef long long __blkcnt64_t;
+#ifdef __CYGWIN_USE_BIG_TYPES__
+typedef __blkcnt64_t blkcnt_t;
+#else
+typedef __blkcnt32_t blkcnt_t;
+#endif
+#endif /*__blkcnt_t_defined*/
+
+#ifndef __fsblkcnt_t_defined
+#define __fsblkcnt_t_defined
+typedef unsigned long fsblkcnt_t;
+#endif /* __fsblkcnt_t_defined */
+
+#ifndef __fsfilcnt_t_defined
+#define __fsfilcnt_t_defined
+typedef unsigned long fsfilcnt_t;
+#endif /* __fsfilcnt_t_defined */
+
+#ifndef __uid_t_defined
+#define __uid_t_defined
+typedef unsigned short __uid16_t;
+typedef unsigned long __uid32_t;
+#ifdef __CYGWIN_USE_BIG_TYPES__
+typedef __uid32_t uid_t;
+#else
+typedef __uid16_t uid_t;
+#endif
+#endif /*__uid_t_defined*/
+
+#ifndef __gid_t_defined
+#define __gid_t_defined
+typedef unsigned short __gid16_t;
+typedef unsigned long __gid32_t;
+#ifdef __CYGWIN_USE_BIG_TYPES__
+typedef __gid32_t gid_t;
+#else
+typedef __gid16_t gid_t;
+#endif
+#endif /*__gid_t_defined*/
+
+#ifndef __ino_t_defined
+#define __ino_t_defined
+typedef unsigned long __ino32_t;
+typedef unsigned long long __ino64_t;
+#ifdef __CYGWIN_USE_BIG_TYPES__
+typedef __ino64_t ino_t;
+#else
+typedef __ino32_t ino_t;
+#endif
+#endif /*__ino_t_defined*/
+
+/* Generic ID type, must match at least pid_t, uid_t and gid_t in size. */
+#ifndef __id_t_defined
+#define __id_t_defined
+typedef unsigned long id_t;
+#endif /* __id_t_defined */
+
+#if defined (__INSIDE_CYGWIN__)
+struct __flock32 {
+ short l_type; /* F_RDLCK, F_WRLCK, or F_UNLCK */
+ short l_whence; /* flag to choose starting offset */
+ _off_t l_start; /* relative offset, in bytes */
+ _off_t l_len; /* length, in bytes; 0 means lock to EOF */
+ short l_pid; /* returned with F_GETLK */
+ short l_xxx; /* reserved for future use */
+};
+
+struct __flock64 {
+ short l_type; /* F_RDLCK, F_WRLCK, or F_UNLCK */
+ short l_whence; /* flag to choose starting offset */
+ _off64_t l_start; /* relative offset, in bytes */
+ _off64_t l_len; /* length, in bytes; 0 means lock to EOF */
+ pid_t l_pid; /* returned with F_GETLK */
+};
+#endif
+
+struct flock {
+ short l_type; /* F_RDLCK, F_WRLCK, or F_UNLCK */
+ short l_whence; /* flag to choose starting offset */
+ off_t l_start; /* relative offset, in bytes */
+ off_t l_len; /* length, in bytes; 0 means lock to EOF */
+#ifdef __CYGWIN_USE_BIG_TYPES__
+ pid_t l_pid; /* returned with F_GETLK */
+#else
+ short l_pid; /* returned with F_GETLK */
+ short l_xxx; /* reserved for future use */
+#endif
+};
+
+#ifndef __key_t_defined
+#define __key_t_defined
+typedef long long key_t;
+#endif /* __key_t_defined */
+
+#ifndef __BIT_TYPES_DEFINED
+#define __BIT_TYPES_DEFINED__ 1
+
+#ifndef __vm_offset_t_defined
+#define __vm_offset_t_defined
+typedef unsigned long vm_offset_t;
+#endif /*__vm_offset_t_defined*/
+
+#ifndef __vm_size_t_defined
+#define __vm_size_t_defined
+typedef unsigned long vm_size_t;
+#endif /*__vm_size_t_defined*/
+
+#ifndef __vm_object_t_defined
+#define __vm_object_t_defined
+typedef void *vm_object_t;
+#endif /* __vm_object_t_defined */
+
+#ifndef __u_int8_t_defined
+#define __u_int8_t_defined
+typedef unsigned char u_int8_t;
+#endif
+#ifndef __u_int16_t_defined
+#define __u_int16_t_defined
+typedef __uint16_t u_int16_t;
+#endif
+#ifndef __u_int32_t_defined
+#define __u_int32_t_defined
+typedef __uint32_t u_int32_t;
+#endif
+#ifndef __u_int64_t_defined
+#define __u_int64_t_defined
+typedef __uint64_t u_int64_t;
+#endif
+
+#ifndef __register_t_defined
+#define __register_t_defined
+typedef __int32_t register_t;
+#endif
+
+#ifndef __addr_t_defined
+#define __addr_t_defined
+typedef char *addr_t;
+#endif
+
+#ifndef __mode_t_defined
+#define __mode_t_defined
+typedef unsigned mode_t;
+#endif
+#endif /*__BIT_TYPES_DEFINED*/
+
+#if !defined(__INSIDE_CYGWIN__) || !defined(__cplusplus)
+
+typedef struct __pthread_t {char __dummy;} *pthread_t;
+typedef struct __pthread_mutex_t {char __dummy;} *pthread_mutex_t;
+
+typedef struct __pthread_key_t {char __dummy;} *pthread_key_t;
+typedef struct __pthread_attr_t {char __dummy;} *pthread_attr_t;
+typedef struct __pthread_mutexattr_t {char __dummy;} *pthread_mutexattr_t;
+typedef struct __pthread_condattr_t {char __dummy;} *pthread_condattr_t;
+typedef struct __pthread_cond_t {char __dummy;} *pthread_cond_t;
+
+ /* These variables are not user alterable. This means you!. */
+typedef struct
+{
+ pthread_mutex_t mutex;
+ int state;
+}
+pthread_once_t;
+typedef struct __pthread_rwlock_t {char __dummy;} *pthread_rwlock_t;
+typedef struct __pthread_rwlockattr_t {char __dummy;} *pthread_rwlockattr_t;
+
+#else
+
+/* pthreads types */
+
+typedef class pthread *pthread_t;
+typedef class pthread_mutex *pthread_mutex_t;
+typedef class pthread_key *pthread_key_t;
+typedef class pthread_attr *pthread_attr_t;
+typedef class pthread_mutexattr *pthread_mutexattr_t;
+typedef class pthread_condattr *pthread_condattr_t;
+typedef class pthread_cond *pthread_cond_t;
+typedef class pthread_once pthread_once_t;
+typedef class pthread_rwlock *pthread_rwlock_t;
+typedef class pthread_rwlockattr *pthread_rwlockattr_t;
+
+/* semaphores types */
+typedef class semaphore *sem_t;
+#endif /* __INSIDE_CYGWIN__ */
+#endif /* _CYGWIN_TYPES_H */
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/winsup/cygwin/mmap.cc b/winsup/cygwin/mmap.cc
index 85718eec745..5ace55c0a1d 100644
--- a/winsup/cygwin/mmap.cc
+++ b/winsup/cygwin/mmap.cc
@@ -977,6 +977,7 @@ mmap64 (void *addr, size_t len, int prot, int flags, int fd, _off64_t off)
caddr_t base = NULL;
DWORD pagesize = getpagesize ();
+ DWORD checkpagesize;
fh_anonymous.set_io_handle (INVALID_HANDLE_VALUE);
fh_anonymous.set_access (GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE);
@@ -1006,8 +1007,8 @@ mmap64 (void *addr, size_t len, int prot, int flags, int fd, _off64_t off)
at least most of the time is, allow 4K aligned addresses in 98,
to enable remapping of formerly mapped pages. If no matching
free pages exist, check addr again, this time for the real alignment. */
- DWORD checkpagesize = wincap.has_mmap_alignment_bug () ?
- getsystempagesize () : pagesize;
+ checkpagesize = wincap.has_mmap_alignment_bug () ?
+ getsystempagesize () : pagesize;
if (fixed (flags) && ((uintptr_t) addr % checkpagesize))
{
set_errno (EINVAL);
diff --git a/winsup/cygwin/pipe.cc b/winsup/cygwin/pipe.cc
new file mode 100644
index 00000000000..a6171f2f9e7
--- /dev/null
+++ b/winsup/cygwin/pipe.cc
@@ -0,0 +1,544 @@
+/* pipe.cc: pipe for Cygwin.
+
+ Copyright 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
+ Hat, Inc.
+
+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 <unistd.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <limits.h>
+#include "cygerrno.h"
+#include "security.h"
+#include "path.h"
+#include "fhandler.h"
+#include "dtable.h"
+#include "cygheap.h"
+#include "thread.h"
+#include "pinfo.h"
+#include "cygthread.h"
+#include "ntdll.h"
+
+static unsigned pipecount;
+static const NO_COPY char pipeid_fmt[] = "stupid_pipe.%u.%u";
+
+fhandler_pipe::fhandler_pipe ()
+ : fhandler_base (), guard (NULL), broken_pipe (false), writepipe_exists (NULL),
+ orig_pid (0), id (0)
+{
+ need_fork_fixup (true);
+}
+
+extern "C" int sscanf (const char *, const char *, ...);
+
+int
+fhandler_pipe::open (int flags, mode_t mode)
+{
+ HANDLE proc, pipe_hdl, nio_hdl = NULL;
+ fhandler_pipe *fh = NULL;
+ size_t size;
+ int pid, rwflags = (flags & O_ACCMODE);
+ bool inh;
+
+ sscanf (get_name (), "/proc/%d/fd/pipe:[%d]", &pid, (int *) &pipe_hdl);
+ if (pid == myself->pid)
+ {
+ cygheap_fdenum cfd (true);
+ while (cfd.next () >= 0)
+ {
+ if (cfd->get_handle () != pipe_hdl)
+ continue;
+ if ((rwflags == O_RDONLY && !(cfd->get_access () & GENERIC_READ))
+ || (rwflags == O_WRONLY && !(cfd->get_access () & GENERIC_WRITE)))
+ {
+ set_errno (EACCES);
+ return 0;
+ }
+ if (!cfd->dup (this))
+ return 1;
+ return 0;
+ }
+ set_errno (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;
+ }
+ if (!(fh = p->pipe_fhandler (pipe_hdl, size)) || !size)
+ {
+ set_errno (ENOENT);
+ goto out;
+ }
+ /* Too bad, but Windows only allows the same access mode when dup'ing
+ the pipe. */
+ if ((rwflags == O_RDONLY && !(fh->get_access () & GENERIC_READ))
+ || (rwflags == O_WRONLY && !(fh->get_access () & GENERIC_WRITE)))
+ {
+ set_errno (EACCES);
+ goto out;
+ }
+ inh = !(flags & O_NOINHERIT);
+ if (!DuplicateHandle (proc, pipe_hdl, hMainProc, &nio_hdl,
+ 0, inh, DUPLICATE_SAME_ACCESS))
+ {
+ __seterrno ();
+ goto out;
+ }
+ if (!fh->guard)
+ /* nothing to do */;
+ else if (DuplicateHandle (proc, fh->guard, hMainProc, &guard,
+ 0, inh, DUPLICATE_SAME_ACCESS))
+ ProtectHandle (guard);
+ else
+ {
+ __seterrno ();
+ goto out;
+ }
+ if (!fh->writepipe_exists)
+ /* nothing to do */;
+ else if (!DuplicateHandle (proc, fh->writepipe_exists,
+ hMainProc, &writepipe_exists,
+ 0, inh, DUPLICATE_SAME_ACCESS))
+ {
+ __seterrno ();
+ goto out;
+ }
+ if (fh->read_state)
+ create_read_state (2);
+ init (nio_hdl, fh->get_access (), mode & O_TEXT ?: O_BINARY);
+ if (flags & O_NOINHERIT)
+ close_on_exec (true);
+ uninterruptible_io (fh->uninterruptible_io ());
+ cfree (fh);
+ CloseHandle (proc);
+ return 1;
+out:
+ if (writepipe_exists)
+ CloseHandle (writepipe_exists);
+ if (guard)
+ CloseHandle (guard);
+ if (nio_hdl)
+ CloseHandle (nio_hdl);
+ if (fh)
+ free (fh);
+ if (proc)
+ CloseHandle (proc);
+ return 0;
+}
+
+_off64_t
+fhandler_pipe::lseek (_off64_t offset, int whence)
+{
+ debug_printf ("(%d, %d)", offset, whence);
+ set_errno (ESPIPE);
+ return -1;
+}
+
+void
+fhandler_pipe::set_close_on_exec (bool val)
+{
+ fhandler_base::set_close_on_exec (val);
+ if (guard)
+ {
+ set_no_inheritance (guard, val);
+ ModifyHandle (guard, !val);
+ }
+ if (writepipe_exists)
+ set_no_inheritance (writepipe_exists, val);
+}
+
+char *
+fhandler_pipe::get_proc_fd_name (char *buf)
+{
+ __small_sprintf (buf, "pipe:[%d]", get_handle ());
+ return buf;
+}
+
+struct pipeargs
+{
+ fhandler_base *fh;
+ void *ptr;
+ size_t *len;
+};
+
+static DWORD WINAPI
+read_pipe (void *arg)
+{
+ pipeargs *pi = (pipeargs *) arg;
+ pi->fh->fhandler_base::read (pi->ptr, *pi->len);
+ return 0;
+}
+
+void __stdcall
+fhandler_pipe::read (void *in_ptr, size_t& in_len)
+{
+ if (broken_pipe)
+ in_len = 0;
+ else
+ {
+ pipeargs pi = {dynamic_cast<fhandler_base *>(this), in_ptr, &in_len};
+ cygthread *th = new cygthread (read_pipe, 0, &pi, "read_pipe");
+ if (th->detach (read_state) && !in_len)
+ in_len = (size_t) -1; /* received a signal */
+ }
+ ReleaseMutex (guard);
+}
+
+int
+fhandler_pipe::close ()
+{
+ if (guard)
+ ForceCloseHandle (guard);
+ if (writepipe_exists)
+ CloseHandle (writepipe_exists);
+#ifndef NEWVFORK
+ if (read_state)
+#else
+ // FIXME is this vfork_cleanup test right? Is it responsible for some of
+ // the strange pipe behavior that has been reported in the cygwin mailing
+ // list?
+ if (read_state && !cygheap->fdtab.in_vfork_cleanup ())
+#endif
+ ForceCloseHandle (read_state);
+ return fhandler_base::close ();
+}
+
+bool
+fhandler_pipe::hit_eof ()
+{
+ char buf[80];
+ HANDLE ev;
+ if (broken_pipe)
+ return 1;
+ if (!orig_pid)
+ return false;
+ __small_sprintf (buf, pipeid_fmt, orig_pid, id);
+ if ((ev = OpenEvent (EVENT_ALL_ACCESS, FALSE, buf)))
+ CloseHandle (ev);
+ debug_printf ("%s %p", buf, ev);
+ return ev == NULL;
+}
+
+void
+fhandler_pipe::fixup_in_child ()
+{
+ if (read_state)
+ create_read_state (2);
+}
+
+void
+fhandler_pipe::fixup_after_exec ()
+{
+ if (!close_on_exec ())
+ fixup_in_child ();
+}
+
+void
+fhandler_pipe::fixup_after_fork (HANDLE parent)
+{
+ fhandler_base::fixup_after_fork (parent);
+ if (guard && fork_fixup (parent, guard, "guard"))
+ ProtectHandle (guard);
+ if (writepipe_exists)
+ fork_fixup (parent, writepipe_exists, "writepipe_exists");
+ fixup_in_child ();
+}
+
+int
+fhandler_pipe::dup (fhandler_base *child)
+{
+ int res = -1;
+ fhandler_pipe *ftp = (fhandler_pipe *) child;
+ ftp->guard = ftp->writepipe_exists = ftp->read_state = NULL;
+
+ if (get_handle () && fhandler_base::dup (child))
+ goto err;
+
+ if (!guard)
+ /* nothing to do */;
+ else if (DuplicateHandle (hMainProc, guard, hMainProc, &ftp->guard, 0, true,
+ DUPLICATE_SAME_ACCESS))
+ ProtectHandle1 (ftp->guard, guard);
+ else
+ {
+ debug_printf ("couldn't duplicate guard %p, %E", guard);
+ goto err;
+ }
+
+ if (!writepipe_exists)
+ /* nothing to do */;
+ else if (!DuplicateHandle (hMainProc, writepipe_exists, hMainProc,
+ &ftp->writepipe_exists, 0, true,
+ DUPLICATE_SAME_ACCESS))
+ {
+ debug_printf ("couldn't duplicate writepipe_exists %p, %E", writepipe_exists);
+ goto err;
+ }
+
+ if (!read_state)
+ /* nothing to do */;
+ else if (DuplicateHandle (hMainProc, read_state, hMainProc,
+ &ftp->read_state, 0, false,
+ DUPLICATE_SAME_ACCESS))
+ ProtectHandle1 (ftp->read_state, read_state);
+ else
+ {
+ debug_printf ("couldn't duplicate read_state %p, %E", read_state);
+ goto err;
+ }
+
+ res = 0;
+ goto out;
+
+err:
+ if (ftp->guard)
+ ForceCloseHandle1 (ftp->guard, guard);
+ if (ftp->writepipe_exists)
+ CloseHandle (ftp->writepipe_exists);
+ if (ftp->read_state)
+ ForceCloseHandle1 (ftp->read_state, read_state);
+ goto leave;
+
+out:
+ ftp->id = id;
+ ftp->orig_pid = orig_pid;
+ VerifyHandle (ftp->writepipe_exists);
+
+leave:
+ debug_printf ("res %d", res);
+ return res;
+}
+
+/* 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. */
+int
+fhandler_pipe::create_selectable (LPSECURITY_ATTRIBUTES sa_ptr, HANDLE& r,
+ HANDLE& w, DWORD psize, bool fifo)
+{
+ /* Default to error. */
+ r = w = INVALID_HANDLE_VALUE;
+
+ /* Ensure that there is enough pipe buffer space for atomic writes. */
+ if (!fifo && psize < PIPE_BUF)
+ psize = PIPE_BUF;
+
+ char pipename[CYG_MAX_PATH];
+
+ /* 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. */
+ while (1)
+ {
+ static volatile ULONG pipe_unique_id;
+
+ __small_sprintf (pipename, "\\\\.\\pipe\\cygwin-%p-%p", myself->pid,
+ InterlockedIncrement ((LONG *) &pipe_unique_id));
+
+ debug_printf ("CreateNamedPipe: name %s, size %lu", pipename, psize);
+
+ /* 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
+ the pid has been reused. We avoid FILE_FLAG_FIRST_PIPE_INSTANCE
+ because that is only available for Win2k SP2 and WinXP. */
+ r = CreateNamedPipe (pipename, PIPE_ACCESS_INBOUND,
+ PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, psize,
+ psize, NMPWAIT_USE_DEFAULT_WAIT, sa_ptr);
+
+ /* Win 95 seems to return NULL instead of INVALID_HANDLE_VALUE */
+ if (r && r != INVALID_HANDLE_VALUE)
+ {
+ debug_printf ("pipe read handle %p", r);
+ break;
+ }
+
+ DWORD err = GetLastError ();
+ switch (err)
+ {
+ case ERROR_PIPE_BUSY:
+ /* The pipe is already open with compatible parameters.
+ Pick a new name and retry. */
+ debug_printf ("pipe busy, retrying");
+ break;
+ case ERROR_ACCESS_DENIED:
+ /* The pipe is already open with incompatible parameters.
+ Pick a new name and retry. */
+ debug_printf ("pipe access denied, retrying");
+ break;
+ default:
+ /* CreateNamePipe failed. Maybe we are on an older Win9x platform without
+ named pipes. Return an anonymous pipe as the best approximation. */
+ debug_printf ("CreateNamedPipe failed, resorting to CreatePipe size %lu",
+ psize);
+ if (CreatePipe (&r, &w, sa_ptr, psize))
+ {
+ debug_printf ("pipe read handle %p", r);
+ debug_printf ("pipe write handle %p", w);
+ return 0;
+ }
+ err = GetLastError ();
+ debug_printf ("CreatePipe failed, %E");
+ return err;
+ }
+ }
+
+ debug_printf ("CreateFile: name %s", pipename);
+
+ /* Open the named pipe for writing.
+ Be sure to permit FILE_READ_ATTRIBUTES access. */
+ w = CreateFile (pipename, GENERIC_WRITE | FILE_READ_ATTRIBUTES, 0, sa_ptr,
+ OPEN_EXISTING, 0, 0);
+
+ if (!w || w == INVALID_HANDLE_VALUE)
+ {
+ /* Failure. */
+ DWORD err = GetLastError ();
+ debug_printf ("CreateFile failed, %E");
+ CloseHandle (r);
+ return err;
+ }
+
+ debug_printf ("pipe write handle %p", w);
+
+ /* Success. */
+ return 0;
+}
+
+int
+fhandler_pipe::create (fhandler_pipe *fhs[2], unsigned psize, int mode, bool fifo)
+{
+ HANDLE r, w;
+ SECURITY_ATTRIBUTES *sa = (mode & O_NOINHERIT) ? &sec_none_nih : &sec_none;
+ int res = -1;
+
+ int ret = create_selectable (sa, r, w, psize, fifo);
+ if (ret)
+ __seterrno_from_win_error (ret);
+ else
+ {
+ fhs[0] = (fhandler_pipe *) build_fh_dev (*piper_dev);
+ fhs[1] = (fhandler_pipe *) build_fh_dev (*pipew_dev);
+
+ int binmode = mode & O_TEXT ?: O_BINARY;
+ fhs[0]->init (r, GENERIC_READ, binmode);
+ fhs[1]->init (w, GENERIC_WRITE, binmode);
+ if (mode & O_NOINHERIT)
+ {
+ fhs[0]->close_on_exec (true);
+ fhs[1]->close_on_exec (true);
+ }
+
+ fhs[0]->create_read_state (2);
+
+ res = 0;
+ fhs[0]->create_guard (sa);
+ if (wincap.has_unreliable_pipes ())
+ {
+ char buf[80];
+ int count = pipecount++; /* FIXME: Should this be InterlockedIncrement? */
+ __small_sprintf (buf, pipeid_fmt, myself->pid, count);
+ fhs[1]->writepipe_exists = CreateEvent (sa, TRUE, FALSE, buf);
+ fhs[0]->orig_pid = myself->pid;
+ fhs[0]->id = count;
+ }
+ }
+
+ syscall_printf ("%d = pipe ([%p, %p], %d, %p)", res, fhs[0], fhs[1], psize, mode);
+ return res;
+}
+
+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;
+}
+
+#define DEFAULT_PIPEBUFSIZE (16 * PIPE_BUF)
+
+extern "C" int
+pipe (int filedes[2])
+{
+ extern DWORD binmode;
+ fhandler_pipe *fhs[2];
+ int res = fhandler_pipe::create (fhs, DEFAULT_PIPEBUFSIZE,
+ (!binmode || binmode == O_BINARY)
+ ? O_BINARY : O_TEXT);
+ if (res == 0)
+ {
+ cygheap_fdnew fdin;
+ cygheap_fdnew fdout (fdin, false);
+ fdin = fhs[0];
+ fdout = fhs[1];
+ filedes[0] = fdin;
+ filedes[1] = fdout;
+ }
+
+ return res;
+}
+
+extern "C" int
+_pipe (int filedes[2], unsigned int psize, int mode)
+{
+ fhandler_pipe *fhs[2];
+ int res = fhandler_pipe::create (fhs, psize, mode);
+ /* This type of pipe is not interruptible so set the appropriate flag. */
+ if (!res)
+ {
+ cygheap_fdnew fdin;
+ cygheap_fdnew fdout (fdin, false);
+ fhs[0]->uninterruptible_io (true);
+ fdin = fhs[0];
+ fdout = fhs[1];
+ filedes[0] = fdin;
+ filedes[1] = fdout;
+ }
+
+ return res;
+}
diff --git a/winsup/cygwin/sec_helper.cc b/winsup/cygwin/sec_helper.cc
new file mode 100644
index 00000000000..a32dcb8f54b
--- /dev/null
+++ b/winsup/cygwin/sec_helper.cc
@@ -0,0 +1,561 @@
+/* sec_helper.cc: NT security helper functions
+
+ Copyright 2000, 2001, 2002, 2003, 2004 Red Hat, Inc.
+
+ Written by Corinna Vinschen <corinna@vinschen.de>
+
+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. */
+
+#include "winsup.h"
+#include <grp.h>
+#include <pwd.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <sys/stat.h>
+#include <sys/acl.h>
+#include <ctype.h>
+#include <wingdi.h>
+#include <winuser.h>
+#include <wininet.h>
+#include "cygerrno.h"
+#include "security.h"
+#include "path.h"
+#include "fhandler.h"
+#include "dtable.h"
+#include "pinfo.h"
+#include "cygheap.h"
+#include "cygtls.h"
+#include "pwdgrp.h"
+
+/* General purpose security attribute objects for global use. */
+SECURITY_ATTRIBUTES NO_COPY sec_none;
+SECURITY_ATTRIBUTES NO_COPY sec_none_nih;
+SECURITY_ATTRIBUTES NO_COPY sec_all;
+SECURITY_ATTRIBUTES NO_COPY sec_all_nih;
+
+SID_IDENTIFIER_AUTHORITY NO_COPY sid_auth[] = {
+ {SECURITY_NULL_SID_AUTHORITY},
+ {SECURITY_WORLD_SID_AUTHORITY},
+ {SECURITY_LOCAL_SID_AUTHORITY},
+ {SECURITY_CREATOR_SID_AUTHORITY},
+ {SECURITY_NON_UNIQUE_AUTHORITY},
+ {SECURITY_NT_AUTHORITY}
+};
+
+SID (well_known_null_sid, "S-1-0-0",
+ SECURITY_NULL_SID_AUTHORITY, 1, SECURITY_NULL_RID);
+SID (well_known_world_sid, "S-1-1-0",
+ SECURITY_WORLD_SID_AUTHORITY, 1, SECURITY_WORLD_RID);
+SID (well_known_local_sid, "S-1-2-0",
+ SECURITY_LOCAL_SID_AUTHORITY, 1, SECURITY_LOCAL_RID);
+SID (well_known_creator_owner_sid, "S-1-3-0",
+ SECURITY_CREATOR_SID_AUTHORITY, 1, SECURITY_CREATOR_OWNER_RID);
+SID (well_known_creator_group_sid, "S-1-3-1",
+ SECURITY_CREATOR_SID_AUTHORITY, 1, SECURITY_CREATOR_GROUP_RID);
+SID (well_known_dialup_sid, "S-1-5-1",
+ SECURITY_NT_AUTHORITY, 1, SECURITY_DIALUP_RID);
+SID (well_known_network_sid, "S-1-5-2",
+ SECURITY_NT_AUTHORITY, 1, SECURITY_NETWORK_RID);
+SID (well_known_batch_sid, "S-1-5-3",
+ SECURITY_NT_AUTHORITY, 1, SECURITY_BATCH_RID);
+SID (well_known_interactive_sid, "S-1-5-4",
+ SECURITY_NT_AUTHORITY, 1, SECURITY_INTERACTIVE_RID);
+SID (well_known_service_sid, "S-1-5-6",
+ SECURITY_NT_AUTHORITY, 1, SECURITY_SERVICE_RID);
+SID (well_known_authenticated_users_sid, "S-1-5-11",
+ SECURITY_NT_AUTHORITY, 1, SECURITY_AUTHENTICATED_USER_RID);
+SID (well_known_system_sid, "S-1-5-18",
+ SECURITY_NT_AUTHORITY, 1, SECURITY_LOCAL_SYSTEM_RID);
+SID (well_known_admins_sid, "S-1-5-32-544",
+ SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID,
+ DOMAIN_ALIAS_RID_ADMINS);
+
+bool
+cygpsid::operator== (const char *nsidstr) const
+{
+ cygsid nsid (nsidstr);
+ return psid == nsid;
+}
+
+__uid32_t
+cygpsid::get_id (BOOL search_grp, int *type)
+{
+ /* First try to get SID from group, then passwd */
+ __uid32_t id = ILLEGAL_UID;
+
+ if (search_grp)
+ {
+ struct __group32 *gr;
+ if (cygheap->user.groups.pgsid == psid)
+ id = myself->gid;
+ else if ((gr = internal_getgrsid (*this)))
+ id = gr->gr_gid;
+ if (id != ILLEGAL_UID)
+ {
+ if (type)
+ *type = GROUP;
+ return id;
+ }
+ }
+ if (!search_grp || type)
+ {
+ struct passwd *pw;
+ if (*this == cygheap->user.sid ())
+ id = myself->uid;
+ else if ((pw = internal_getpwsid (*this)))
+ id = pw->pw_uid;
+ if (id != ILLEGAL_UID && type)
+ *type = USER;
+ }
+ return id;
+}
+
+
+char *
+cygpsid::string (char *nsidstr) const
+{
+ char *t;
+ DWORD i;
+
+ if (!psid || !nsidstr)
+ return NULL;
+ strcpy (nsidstr, "S-1-");
+ t = nsidstr + sizeof ("S-1-") - 1;
+ t += __small_sprintf (t, "%u", GetSidIdentifierAuthority (psid)->Value[5]);
+ for (i = 0; i < *GetSidSubAuthorityCount (psid); ++i)
+ t += __small_sprintf (t, "-%lu", *GetSidSubAuthority (psid, i));
+ return nsidstr;
+}
+
+PSID
+cygsid::get_sid (DWORD s, DWORD cnt, DWORD *r)
+{
+ DWORD i;
+
+ if (s > 5 || cnt < 1 || cnt > 8)
+ {
+ psid = NO_SID;
+ return NULL;
+ }
+ set ();
+ InitializeSid (psid, &sid_auth[s], cnt);
+ for (i = 0; i < cnt; ++i)
+ memcpy ((char *) psid + 8 + sizeof (DWORD) * i, &r[i], sizeof (DWORD));
+ return psid;
+}
+
+const PSID
+cygsid::getfromstr (const char *nsidstr)
+{
+ char *lasts;
+ DWORD s, cnt = 0;
+ DWORD r[8];
+
+ if (nsidstr && !strncmp (nsidstr, "S-1-", 4))
+ {
+ s = strtoul (nsidstr + 4, &lasts, 10);
+ while (cnt < 8 && *lasts == '-')
+ r[cnt++] = strtoul (lasts + 1, &lasts, 10);
+ if (!*lasts)
+ return get_sid (s, cnt, r);
+ }
+ return psid = NO_SID;
+}
+
+BOOL
+cygsid::getfrompw (const struct passwd *pw)
+{
+ char *sp = (pw && pw->pw_gecos) ? strrchr (pw->pw_gecos, ',') : NULL;
+ return (*this = sp ? sp + 1 : sp) != NULL;
+}
+
+BOOL
+cygsid::getfromgr (const struct __group32 *gr)
+{
+ char *sp = (gr && gr->gr_passwd) ? gr->gr_passwd : NULL;
+ return (*this = sp) != NULL;
+}
+
+bool
+get_sids_info (cygpsid owner_sid, cygpsid group_sid, __uid32_t * uidret, __gid32_t * gidret)
+{
+ struct passwd *pw;
+ struct __group32 *gr = NULL;
+ bool ret = false;
+
+ owner_sid.debug_print ("get_sids_info: owner SID =");
+ group_sid.debug_print ("get_sids_info: group SID =");
+
+ if (group_sid == cygheap->user.groups.pgsid)
+ *gidret = myself->gid;
+ else if ((gr = internal_getgrsid (group_sid)))
+ *gidret = gr->gr_gid;
+ else
+ *gidret = ILLEGAL_GID;
+
+ if (owner_sid == cygheap->user.sid ())
+ {
+ *uidret = myself->uid;
+ if (*gidret == myself->gid)
+ ret = true;
+ else
+ ret = (internal_getgroups (0, NULL, &group_sid) > 0);
+ }
+ else if ((pw = internal_getpwsid (owner_sid)))
+ {
+ *uidret = pw->pw_uid;
+ if (gr || (*gidret != ILLEGAL_GID
+ && (gr = internal_getgrgid (*gidret))))
+ for (int idx = 0; gr->gr_mem[idx]; ++idx)
+ if ((ret = strcasematch (pw->pw_name, gr->gr_mem[idx])))
+ break;
+ }
+ else
+ *uidret = ILLEGAL_UID;
+
+ return ret;
+}
+
+PSECURITY_DESCRIPTOR
+security_descriptor::malloc (size_t nsize)
+{
+ if (psd)
+ ::free (psd);
+ psd = (PSECURITY_DESCRIPTOR) ::malloc (nsize);
+ sd_size = psd ? nsize : 0;
+ return psd;
+}
+
+PSECURITY_DESCRIPTOR
+security_descriptor::realloc (size_t nsize)
+{
+ PSECURITY_DESCRIPTOR tmp = (PSECURITY_DESCRIPTOR) ::realloc (psd, nsize);
+ if (!tmp)
+ return NULL;
+ sd_size = nsize;
+ return psd = tmp;
+}
+
+void
+security_descriptor::free ()
+{
+ if (psd)
+ ::free (psd);
+ psd = NULL;
+ sd_size = 0;
+}
+
+#if 0 // unused
+#define SIDLEN (sidlen = MAX_SID_LEN, &sidlen)
+#define DOMLEN (domlen = INTERNET_MAX_HOST_NAME_LENGTH, &domlen)
+
+BOOL
+lookup_name (const char *name, const char *logsrv, PSID ret_sid)
+{
+ cygsid sid;
+ DWORD sidlen;
+ char domuser[INTERNET_MAX_HOST_NAME_LENGTH + UNLEN + 2];
+ char dom[INTERNET_MAX_HOST_NAME_LENGTH + 1];
+ DWORD domlen;
+ SID_NAME_USE acc_type;
+
+ debug_printf ("name : %s", name ? name : "NULL");
+
+ if (!name)
+ return FALSE;
+
+ if (cygheap->user.domain ())
+ {
+ strcat (strcat (strcpy (domuser, cygheap->user.domain ()), "\\"), name);
+ if (LookupAccountName (NULL, domuser, sid, SIDLEN, dom, DOMLEN, &acc_type)
+ && legal_sid_type (acc_type))
+ goto got_it;
+ if (logsrv && *logsrv
+ && LookupAccountName (logsrv, domuser, sid, SIDLEN,
+ dom, DOMLEN, &acc_type)
+ && legal_sid_type (acc_type))
+ goto got_it;
+ }
+ if (logsrv && *logsrv)
+ {
+ if (LookupAccountName (logsrv, name, sid, SIDLEN, dom, DOMLEN, &acc_type)
+ && legal_sid_type (acc_type))
+ goto got_it;
+ if (acc_type == SidTypeDomain)
+ {
+ strcat (strcat (strcpy (domuser, dom), "\\"), name);
+ if (LookupAccountName (logsrv, domuser, sid, SIDLEN,
+ dom, DOMLEN, &acc_type))
+ goto got_it;
+ }
+ }
+ if (LookupAccountName (NULL, name, sid, SIDLEN, dom, DOMLEN, &acc_type)
+ && legal_sid_type (acc_type))
+ goto got_it;
+ if (acc_type == SidTypeDomain)
+ {
+ strcat (strcat (strcpy (domuser, dom), "\\"), name);
+ if (LookupAccountName (NULL, domuser, sid, SIDLEN, dom, DOMLEN,&acc_type))
+ goto got_it;
+ }
+ debug_printf ("LookupAccountName (%s) %E", name);
+ __seterrno ();
+ return FALSE;
+
+got_it:
+ debug_printf ("sid : [%d]", *GetSidSubAuthority ((PSID) sid,
+ *GetSidSubAuthorityCount ((PSID) sid) - 1));
+
+ if (ret_sid)
+ memcpy (ret_sid, sid, sidlen);
+
+ return TRUE;
+}
+
+#undef SIDLEN
+#undef DOMLEN
+#endif //unused
+
+/* Order must be same as cygperm_idx in winsup.h. */
+static const char *cygpriv[] =
+{
+ SE_CREATE_TOKEN_NAME,
+ SE_ASSIGNPRIMARYTOKEN_NAME,
+ SE_LOCK_MEMORY_NAME,
+ SE_INCREASE_QUOTA_NAME,
+ SE_UNSOLICITED_INPUT_NAME,
+ SE_MACHINE_ACCOUNT_NAME,
+ SE_TCB_NAME,
+ SE_SECURITY_NAME,
+ SE_TAKE_OWNERSHIP_NAME,
+ SE_LOAD_DRIVER_NAME,
+ SE_SYSTEM_PROFILE_NAME,
+ SE_SYSTEMTIME_NAME,
+ SE_PROF_SINGLE_PROCESS_NAME,
+ SE_INC_BASE_PRIORITY_NAME,
+ SE_CREATE_PAGEFILE_NAME,
+ SE_CREATE_PERMANENT_NAME,
+ SE_BACKUP_NAME,
+ SE_RESTORE_NAME,
+ SE_SHUTDOWN_NAME,
+ SE_DEBUG_NAME,
+ SE_AUDIT_NAME,
+ SE_SYSTEM_ENVIRONMENT_NAME,
+ SE_CHANGE_NOTIFY_NAME,
+ SE_REMOTE_SHUTDOWN_NAME,
+ SE_CREATE_GLOBAL_NAME,
+ SE_UNDOCK_NAME,
+ SE_MANAGE_VOLUME_NAME,
+ SE_IMPERSONATE_NAME,
+ SE_ENABLE_DELEGATION_NAME,
+ SE_SYNC_AGENT_NAME
+};
+
+const LUID *
+privilege_luid (cygpriv_idx idx)
+{
+ if (idx < 0 || idx >= SE_NUM_PRIVS)
+ return NULL;
+ if (!cygheap->luid[idx].LowPart && !cygheap->luid[idx].HighPart
+ && !LookupPrivilegeValue (NULL, cygpriv[idx], &cygheap->luid[idx]))
+ {
+ __seterrno ();
+ return NULL;
+ }
+ return &cygheap->luid[idx];
+}
+
+const LUID *
+privilege_luid_by_name (const char *pname)
+{
+ int idx;
+
+ if (!pname)
+ return NULL;
+ for (idx = 0; idx < SE_NUM_PRIVS; ++idx)
+ if (!strcmp (pname, cygpriv[idx]))
+ return privilege_luid ((cygpriv_idx) idx);
+ return NULL;
+}
+
+const char *
+privilege_name (cygpriv_idx idx)
+{
+ if (idx < 0 || idx >= SE_NUM_PRIVS)
+ return "<unknown privilege>";
+ return cygpriv[idx];
+}
+
+int
+set_privilege (HANDLE token, cygpriv_idx privilege, bool enable)
+{
+ int ret = -1;
+ const LUID *priv_luid;
+ TOKEN_PRIVILEGES new_priv, orig_priv;
+ DWORD size;
+
+ if (!(priv_luid = privilege_luid (privilege)))
+ {
+ __seterrno ();
+ goto out;
+ }
+
+ new_priv.PrivilegeCount = 1;
+ new_priv.Privileges[0].Luid = *priv_luid;
+ new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
+
+ if (!AdjustTokenPrivileges (token, FALSE, &new_priv,
+ sizeof orig_priv, &orig_priv, &size))
+ {
+ __seterrno ();
+ goto out;
+ }
+ /* AdjustTokenPrivileges returns TRUE even if the privilege could not
+ be enabled. GetLastError () returns an correct error code, though. */
+ if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
+ {
+ __seterrno ();
+ goto out;
+ }
+
+ /* If orig_priv.PrivilegeCount is 0, the privilege hasn't been changed. */
+ if (!orig_priv.PrivilegeCount)
+ ret = enable ? 1 : 0;
+ else
+ ret = (orig_priv.Privileges[0].Attributes & SE_PRIVILEGE_ENABLED) ? 1 : 0;
+
+out:
+ syscall_printf ("%d = set_privilege ((token %x) %s, %d)",
+ ret, token, privilege_name (privilege), enable);
+ return ret;
+}
+
+void
+set_cygwin_privileges (HANDLE token)
+{
+ set_privilege (token, SE_RESTORE_PRIV, true);
+ set_privilege (token, SE_BACKUP_PRIV, true);
+ set_privilege (token, SE_CHANGE_NOTIFY_PRIV, !allow_traverse);
+}
+
+/* Function to return a common SECURITY_DESCRIPTOR that
+ allows all access. */
+
+
+SECURITY_DESCRIPTOR *__stdcall
+get_null_sd ()
+{
+ static NO_COPY SECURITY_DESCRIPTOR sd;
+ static NO_COPY SECURITY_DESCRIPTOR *null_sdp;
+
+ if (!null_sdp)
+ {
+ InitializeSecurityDescriptor (&sd, SECURITY_DESCRIPTOR_REVISION);
+ SetSecurityDescriptorDacl (&sd, TRUE, 0, FALSE);
+ null_sdp = &sd;
+ }
+ return null_sdp;
+}
+
+/* Initialize global security attributes.
+ Called from dcrt0.cc (_dll_crt0). */
+
+void
+init_global_security ()
+{
+ sec_none.nLength = sec_none_nih.nLength =
+ sec_all.nLength = sec_all_nih.nLength = sizeof (SECURITY_ATTRIBUTES);
+ sec_none.bInheritHandle = sec_all.bInheritHandle = TRUE;
+ sec_none_nih.bInheritHandle = sec_all_nih.bInheritHandle = FALSE;
+ sec_none.lpSecurityDescriptor = sec_none_nih.lpSecurityDescriptor = NULL;
+ sec_all.lpSecurityDescriptor = sec_all_nih.lpSecurityDescriptor =
+ get_null_sd ();
+}
+
+bool
+sec_acl (PACL acl, bool original, bool admins, PSID sid1, PSID sid2, DWORD access2)
+{
+ size_t acl_len = MAX_DACL_LEN(5);
+ LPVOID pAce;
+ cygpsid psid;
+
+#ifdef DEBUGGING
+ if ((unsigned long) acl % 4)
+ api_fatal ("Incorrectly aligned incoming ACL buffer!");
+#endif
+ if (!InitializeAcl (acl, acl_len, ACL_REVISION))
+ {
+ debug_printf ("InitializeAcl %E");
+ return false;
+ }
+ if (sid1)
+ if (!AddAccessAllowedAce (acl, ACL_REVISION,
+ GENERIC_ALL, sid1))
+ debug_printf ("AddAccessAllowedAce(sid1) %E");
+ if (original && (psid = cygheap->user.saved_sid ())
+ && psid != sid1 && psid != well_known_system_sid)
+ if (!AddAccessAllowedAce (acl, ACL_REVISION,
+ GENERIC_ALL, psid))
+ debug_printf ("AddAccessAllowedAce(original) %E");
+ if (sid2)
+ if (!AddAccessAllowedAce (acl, ACL_REVISION,
+ access2, sid2))
+ debug_printf ("AddAccessAllowedAce(sid2) %E");
+ if (admins)
+ if (!AddAccessAllowedAce (acl, ACL_REVISION,
+ GENERIC_ALL, well_known_admins_sid))
+ debug_printf ("AddAccessAllowedAce(admin) %E");
+ if (!AddAccessAllowedAce (acl, ACL_REVISION,
+ GENERIC_ALL, well_known_system_sid))
+ debug_printf ("AddAccessAllowedAce(system) %E");
+ FindFirstFreeAce (acl, &pAce);
+ if (pAce)
+ acl->AclSize = (char *) pAce - (char *) acl;
+ else
+ debug_printf ("FindFirstFreeAce %E");
+
+ return true;
+}
+
+PSECURITY_ATTRIBUTES __stdcall
+__sec_user (PVOID sa_buf, PSID sid1, PSID sid2, DWORD access2, BOOL inherit)
+{
+ PSECURITY_ATTRIBUTES psa = (PSECURITY_ATTRIBUTES) sa_buf;
+ PSECURITY_DESCRIPTOR psd = (PSECURITY_DESCRIPTOR)
+ ((char *) sa_buf + sizeof (*psa));
+ PACL acl = (PACL) ((char *) sa_buf + sizeof (*psa) + sizeof (*psd));
+
+#ifdef DEBUGGING
+ if ((unsigned long) sa_buf % 4)
+ api_fatal ("Incorrectly aligned incoming SA buffer!");
+#endif
+ if (!wincap.has_security ()
+ || !sec_acl (acl, true, true, sid1, sid2, access2))
+ return inherit ? &sec_none : &sec_none_nih;
+
+ if (!InitializeSecurityDescriptor (psd, SECURITY_DESCRIPTOR_REVISION))
+ debug_printf ("InitializeSecurityDescriptor %E");
+
+/*
+ * Setting the owner lets the created security attribute not work
+ * on NT4 SP3 Server. Don't know why, but the function still does
+ * what it should do also if the owner isn't set.
+*/
+#if 0
+ if (!SetSecurityDescriptorOwner (psd, sid, FALSE))
+ debug_printf ("SetSecurityDescriptorOwner %E");
+#endif
+
+ if (!SetSecurityDescriptorDacl (psd, TRUE, acl, FALSE))
+ debug_printf ("SetSecurityDescriptorDacl %E");
+
+ psa->nLength = sizeof (SECURITY_ATTRIBUTES);
+ psa->lpSecurityDescriptor = psd;
+ psa->bInheritHandle = inherit;
+ return psa;
+}
diff --git a/winsup/cygwin/spawn.cc b/winsup/cygwin/spawn.cc
new file mode 100644
index 00000000000..d1ee321e511
--- /dev/null
+++ b/winsup/cygwin/spawn.cc
@@ -0,0 +1,1025 @@
+/* spawn.cc
+
+ Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+ 2005, 2006 Red Hat, Inc.
+
+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. */
+
+#include "winsup.h"
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <process.h>
+#include <sys/wait.h>
+#include <limits.h>
+#include <wingdi.h>
+#include <winuser.h>
+#include <ctype.h>
+#include "cygerrno.h"
+#include <sys/cygwin.h>
+#include "security.h"
+#include "path.h"
+#include "fhandler.h"
+#include "dtable.h"
+#include "sigproc.h"
+#include "cygheap.h"
+#include "child_info.h"
+#include "shared_info.h"
+#include "pinfo.h"
+#include "registry.h"
+#include "environ.h"
+#include "cygtls.h"
+#include "winf.h"
+
+static suffix_info exe_suffixes[] =
+{
+ suffix_info ("", 1),
+ suffix_info (".exe", 1),
+ suffix_info (".com"),
+ suffix_info (NULL)
+};
+
+static suffix_info dll_suffixes[] =
+{
+ suffix_info (".dll"),
+ suffix_info ("", 1),
+ suffix_info (".exe", 1),
+ suffix_info (NULL)
+};
+
+HANDLE hExeced;
+child_info_spawn *chExeced;
+
+/* Add .exe to PROG if not already present and see if that exists.
+ If not, return PROG (converted from posix to win32 rules if necessary).
+ The result is always BUF.
+
+ Returns (possibly NULL) suffix */
+
+static const char *
+perhaps_suffix (const char *prog, path_conv& buf, int& err, unsigned opt)
+{
+ char *ext;
+
+ err = 0;
+ debug_printf ("prog '%s'", prog);
+ buf.check (prog, PC_SYM_FOLLOW | PC_NULLEMPTY,
+ (opt & FE_DLL) ? dll_suffixes : exe_suffixes);
+
+ if (buf.isdir ())
+ {
+ err = EACCES;
+ ext = NULL;
+ }
+ else if (!buf.exists ())
+ {
+ err = ENOENT;
+ ext = NULL;
+ }
+ else if (buf.known_suffix)
+ ext = (char *) buf + (buf.known_suffix - buf.get_win32 ());
+ else
+ ext = strchr (buf, '\0');
+
+ debug_printf ("buf %s, suffix found '%s'", (char *) buf, ext);
+ return ext;
+}
+
+/* Find an executable name, possibly by appending known executable
+ suffixes to it. The win32-translated name is placed in 'buf'.
+ Any found suffix is returned in known_suffix.
+
+ If the file is not found and !null_if_not_found then the win32 version
+ of name is placed in buf and returned. Otherwise the contents of buf
+ is undefined and NULL is returned. */
+
+const char * __stdcall
+find_exec (const char *name, path_conv& buf, const char *mywinenv,
+ unsigned opt, const char **known_suffix)
+{
+ const char *suffix = "";
+ debug_printf ("find_exec (%s)", name);
+ const char *retval = buf;
+ char tmp[CYG_MAX_PATH];
+ const char *posix = (opt & FE_NATIVE) ? NULL : name;
+ bool has_slash = strchr (name, '/');
+ int err;
+
+ /* Check to see if file can be opened as is first.
+ Win32 systems always check . first, but PATH may not be set up to
+ do this. */
+ if ((has_slash || opt & FE_CWD)
+ && (suffix = perhaps_suffix (name, buf, err, opt)) != NULL)
+ {
+ if (posix && !has_slash)
+ {
+ tmp[0] = '.';
+ tmp[1] = '/';
+ strcpy (tmp + 2, name);
+ posix = tmp;
+ }
+ goto out;
+ }
+
+ win_env *winpath;
+ const char *path;
+ const char *posix_path;
+
+ posix = (opt & FE_NATIVE) ? NULL : tmp;
+
+ if (strchr (mywinenv, '/'))
+ {
+ /* it's not really an environment variable at all */
+ int n = cygwin_posix_to_win32_path_list_buf_size (mywinenv);
+ char *s = (char *) alloca (n + 1);
+ if (cygwin_posix_to_win32_path_list (mywinenv, s))
+ goto errout;
+ path = s;
+ posix_path = mywinenv - 1;
+ }
+ else if (has_slash || strchr (name, '\\') || isdrive (name)
+ || !(winpath = getwinenv (mywinenv))
+ || !(path = winpath->get_native ()) || *path == '\0')
+ /* Return the error condition if this is an absolute path or if there
+ is no PATH to search. */
+ goto errout;
+ else
+ posix_path = winpath->get_posix () - 1;
+
+ debug_printf ("%s%s", mywinenv, path);
+ /* Iterate over the specified path, looking for the file with and without
+ executable extensions. */
+ do
+ {
+ posix_path++;
+ char *eotmp = strccpy (tmp, &path, ';');
+ /* An empty path or '.' means the current directory, but we've
+ already tried that. */
+ if (opt & FE_CWD && (tmp[0] == '\0' || (tmp[0] == '.' && tmp[1] == '\0')))
+ continue;
+
+ *eotmp++ = '\\';
+ strcpy (eotmp, name);
+
+ debug_printf ("trying %s", tmp);
+
+ if ((suffix = perhaps_suffix (tmp, buf, err, opt)) != NULL)
+ {
+ if (buf.has_acls () && allow_ntsec && check_file_access (buf, X_OK))
+ continue;
+
+ if (posix == tmp)
+ {
+ eotmp = strccpy (tmp, &posix_path, ':');
+ if (eotmp == tmp)
+ *eotmp++ = '.';
+ *eotmp++ = '/';
+ strcpy (eotmp, name);
+ }
+ goto out;
+ }
+ }
+ while (*path && *++path && (posix_path = strchr (posix_path, ':')));
+
+ errout:
+ posix = NULL;
+ /* Couldn't find anything in the given path.
+ Take the appropriate action based on null_if_not_found. */
+ if (opt & FE_NNF)
+ retval = NULL;
+ else if (opt & FE_NATIVE)
+ buf.check (name);
+ else
+ retval = name;
+
+ out:
+ if (posix)
+ buf.set_path (posix);
+ debug_printf ("%s = find_exec (%s)", (char *) buf, name);
+ if (known_suffix)
+ *known_suffix = suffix ?: strchr (buf, '\0');
+ if (!retval && err)
+ set_errno (err);
+ return retval;
+}
+
+/* Utility for spawn_guts. */
+
+static HANDLE
+handle (int fd, int direction)
+{
+ HANDLE h;
+ cygheap_fdget cfd (fd);
+
+ if (cfd < 0)
+ h = INVALID_HANDLE_VALUE;
+ else if (cfd->close_on_exec ())
+ h = INVALID_HANDLE_VALUE;
+ else if (direction == 0)
+ h = cfd->get_handle ();
+ else
+ h = cfd->get_output_handle ();
+ return h;
+}
+
+int
+iscmd (const char *argv0, const char *what)
+{
+ int n;
+ n = strlen (argv0) - strlen (what);
+ if (n >= 2 && argv0[1] != ':')
+ return 0;
+ return n >= 0 && strcasematch (argv0 + n, what) &&
+ (n == 0 || isdirsep (argv0[n - 1]));
+}
+
+struct pthread_cleanup
+{
+ _sig_func_ptr oldint;
+ _sig_func_ptr oldquit;
+ sigset_t oldmask;
+ pthread_cleanup (): oldint (NULL), oldquit (NULL), oldmask ((sigset_t) -1) {}
+};
+
+static void
+do_cleanup (void *args)
+{
+# define cleanup ((pthread_cleanup *) args)
+ if (cleanup->oldmask != (sigset_t) -1)
+ {
+ signal (SIGINT, cleanup->oldint);
+ signal (SIGQUIT, cleanup->oldquit);
+ sigprocmask (SIG_SETMASK, &(cleanup->oldmask), NULL);
+ }
+# undef cleanup
+}
+
+
+static int __stdcall
+spawn_guts (const char * prog_arg, const char *const *argv,
+ const char *const envp[], int mode)
+{
+ bool rc;
+ pid_t cygpid;
+ int res = -1;
+
+ if (prog_arg == NULL)
+ {
+ syscall_printf ("prog_arg is NULL");
+ set_errno (EINVAL);
+ return -1;
+ }
+
+ syscall_printf ("spawn_guts (%d, %.9500s)", mode, prog_arg);
+
+ if (argv == NULL)
+ {
+ syscall_printf ("argv is NULL");
+ set_errno (EINVAL);
+ return -1;
+ }
+
+ /* FIXME: There is a small race here and FIXME: not thread safe! */
+
+ pthread_cleanup cleanup;
+ if (mode == _P_SYSTEM)
+ {
+ sigset_t child_block;
+ cleanup.oldint = signal (SIGINT, SIG_IGN);
+ cleanup.oldquit = signal (SIGQUIT, SIG_IGN);
+ sigemptyset (&child_block);
+ sigaddset (&child_block, SIGCHLD);
+ sigprocmask (SIG_BLOCK, &child_block, &cleanup.oldmask);
+ }
+ pthread_cleanup_push (do_cleanup, (void *) &cleanup);
+ av newargv;
+ linebuf one_line;
+ child_info_spawn ch;
+
+ char *envblock = NULL;
+ path_conv real_path;
+ bool reset_sendsig = false;
+
+ const char *runpath;
+ int c_flags;
+ bool wascygexec;
+ cygheap_exec_info *moreinfo;
+
+ bool null_app_name = false;
+ STARTUPINFO si = {0, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL};
+ int looped = 0;
+ HANDLE orig_wr_proc_pipe = NULL;
+
+ myfault efault;
+ if (efault.faulted ())
+ {
+ if (get_errno () == ENOMEM)
+ set_errno (E2BIG);
+ else
+ set_errno (EFAULT);
+ res = -1;
+ goto out;
+ }
+
+ child_info_types chtype;
+ if (mode != _P_OVERLAY)
+ chtype = PROC_SPAWN;
+ else
+ chtype = PROC_EXEC;
+
+ moreinfo = (cygheap_exec_info *) ccalloc (HEAP_1_EXEC, 1, sizeof (cygheap_exec_info));
+ moreinfo->old_title = NULL;
+
+ /* CreateProcess takes one long string that is the command line (sigh).
+ We need to quote any argument that has whitespace or embedded "'s. */
+
+ int ac;
+ for (ac = 0; argv[ac]; ac++)
+ /* nothing */;
+
+ newargv.set (ac, argv);
+
+ int err;
+ const char *ext;
+ if ((ext = perhaps_suffix (prog_arg, real_path, err, FE_NADA)) == NULL)
+ {
+ set_errno (err);
+ res = -1;
+ goto out;
+ }
+
+
+ wascygexec = real_path.iscygexec ();
+ res = newargv.fixup (prog_arg, real_path, ext);
+
+ if (res)
+ goto out;
+
+ if (ac == 3 && argv[1][0] == '/' && argv[1][1] == 'c' &&
+ (iscmd (argv[0], "command.com") || iscmd (argv[0], "cmd.exe")))
+ {
+ real_path.check (prog_arg);
+ one_line.add ("\"");
+ if (!real_path.error)
+ one_line.add (real_path);
+ else
+ one_line.add (argv[0]);
+ one_line.add ("\"");
+ one_line.add (" ");
+ one_line.add (argv[1]);
+ one_line.add (" ");
+ one_line.add (argv[2]);
+ strcpy (real_path, argv[0]);
+ null_app_name = true;
+ }
+ else
+ {
+ if (wascygexec)
+ newargv.dup_all ();
+ else if (!one_line.fromargv (newargv, real_path, real_path.iscygexec ()))
+ {
+ res = -1;
+ goto out;
+ }
+
+
+ newargv.all_calloced ();
+ moreinfo->argc = newargv.argc;
+ moreinfo->argv = newargv;
+
+ if (mode != _P_OVERLAY ||
+ !DuplicateHandle (hMainProc, myself.shared_handle (), hMainProc,
+ &moreinfo->myself_pinfo, 0,
+ TRUE, DUPLICATE_SAME_ACCESS))
+ moreinfo->myself_pinfo = NULL;
+ else
+ VerifyHandle (moreinfo->myself_pinfo);
+ }
+
+ PROCESS_INFORMATION pi;
+ pi.hProcess = pi.hThread = NULL;
+ pi.dwProcessId = pi.dwThreadId = 0;
+ si.lpReserved = NULL;
+ si.lpDesktop = NULL;
+ si.dwFlags = STARTF_USESTDHANDLES;
+ si.hStdInput = handle (0, 0); /* Get input handle */
+ si.hStdOutput = handle (1, 1); /* Get output handle */
+ si.hStdError = handle (2, 1); /* Get output handle */
+ si.cb = sizeof (si);
+ if (!wincap.pty_needs_alloc_console () && newargv.iscui && myself->ctty == -1)
+ {
+ si.dwFlags |= STARTF_USESHOWWINDOW;
+ si.wShowWindow = SW_HIDE;
+ }
+
+ c_flags = GetPriorityClass (hMainProc);
+ sigproc_printf ("priority class %d", c_flags);
+ c_flags |= CREATE_SEPARATE_WOW_VDM;
+
+ if (mode == _P_DETACH)
+ c_flags |= DETACHED_PROCESS;
+
+ if (mode != _P_OVERLAY)
+ myself->exec_sendsig = NULL;
+ else
+ {
+ /* Reset sendsig so that any process which wants to send a signal
+ to this pid will wait for the new process to become active.
+ Save the old value in case the exec fails. */
+ if (!myself->exec_sendsig)
+ {
+ myself->exec_sendsig = myself->sendsig;
+ myself->exec_dwProcessId = myself->dwProcessId;
+ myself->sendsig = NULL;
+ reset_sendsig = true;
+ }
+ /* Save a copy of a handle to the current process around the first time we
+ exec so that the pid will not be reused. Why did I stop cygwin from
+ generating its own pids again? */
+ if (cygheap->pid_handle)
+ /* already done previously */;
+ else if (DuplicateHandle (hMainProc, hMainProc, hMainProc, &cygheap->pid_handle,
+ PROCESS_QUERY_INFORMATION, TRUE, 0))
+ ProtectHandleINH (cygheap->pid_handle);
+ else
+ system_printf ("duplicate to pid_handle failed, %E");
+ if (mode != _P_DETACH)
+ set_console_state_for_spawn (real_path.iscygexec ());
+ }
+
+ /* Some file types (currently only sockets) need extra effort in the parent
+ after CreateProcess and before copying the datastructures to the child.
+ So we have to start the child in suspend state, unfortunately, to avoid
+ a race condition. */
+ if (!newargv.win16_exe
+ && (wincap.start_proc_suspended () || mode != _P_OVERLAY
+ || cygheap->fdtab.need_fixup_before ()))
+ c_flags |= CREATE_SUSPENDED;
+
+ runpath = null_app_name ? NULL : (const char *) real_path;
+
+ syscall_printf ("null_app_name %d (%s, %.9500s)", null_app_name, runpath, one_line.buf);
+
+ cygbench ("spawn-guts");
+
+ cygheap->fdtab.set_file_pointers_for_exec ();
+
+ moreinfo->envp = build_env (envp, envblock, moreinfo->envc, real_path.iscygexec ());
+ if (!moreinfo->envp || !envblock)
+ {
+ set_errno (E2BIG);
+ res = -1;
+ goto out;
+ }
+ ch.set (chtype, real_path.iscygexec ());
+ ch.moreinfo = moreinfo;
+
+ si.lpReserved2 = (LPBYTE) &ch;
+ si.cbReserved2 = sizeof (ch);
+
+ /* When ruid != euid we create the new process under the current original
+ account and impersonate in child, this way maintaining the different
+ effective vs. real ids.
+ FIXME: If ruid != euid and ruid != saved_uid we currently give
+ up on ruid. The new process will have ruid == euid. */
+loop:
+ cygheap->user.deimpersonate ();
+
+ if (!cygheap->user.issetuid ()
+ || (cygheap->user.saved_uid == cygheap->user.real_uid
+ && cygheap->user.saved_gid == cygheap->user.real_gid
+ && !cygheap->user.groups.issetgroups ()))
+ {
+ rc = CreateProcess (runpath, /* image name - with full path */
+ one_line.buf, /* what was passed to exec */
+ &sec_none_nih,/* process security attrs */
+ &sec_none_nih,/* thread security attrs */
+ TRUE, /* inherit handles from parent */
+ c_flags,
+ envblock, /* environment */
+ 0, /* use current drive/directory */
+ &si,
+ &pi);
+ }
+ else
+ {
+ /* Give access to myself */
+ if (mode == _P_OVERLAY)
+ myself.set_acl();
+
+ /* allow the child to interact with our window station/desktop */
+ HANDLE hwst, hdsk;
+ SECURITY_INFORMATION dsi = DACL_SECURITY_INFORMATION;
+ DWORD n;
+ char wstname[1024];
+ char dskname[1024];
+
+ hwst = GetProcessWindowStation ();
+ SetUserObjectSecurity (hwst, &dsi, get_null_sd ());
+ GetUserObjectInformation (hwst, UOI_NAME, wstname, 1024, &n);
+ hdsk = GetThreadDesktop (GetCurrentThreadId ());
+ SetUserObjectSecurity (hdsk, &dsi, get_null_sd ());
+ GetUserObjectInformation (hdsk, UOI_NAME, dskname, 1024, &n);
+ strcat (wstname, "\\");
+ strcat (wstname, dskname);
+ si.lpDesktop = wstname;
+
+ rc = CreateProcessAsUser (cygheap->user.primary_token (),
+ runpath, /* image name - with full path */
+ one_line.buf, /* what was passed to exec */
+ &sec_none_nih, /* process security attrs */
+ &sec_none_nih, /* thread security attrs */
+ TRUE, /* inherit handles from parent */
+ c_flags,
+ envblock, /* environment */
+ 0, /* use current drive/directory */
+ &si,
+ &pi);
+ }
+
+ /* Restore impersonation. In case of _P_OVERLAY this isn't
+ allowed since it would overwrite child data. */
+ if (mode != _P_OVERLAY || !rc)
+ cygheap->user.reimpersonate ();
+
+ /* Set errno now so that debugging messages from it appear before our
+ final debugging message [this is a general rule for debugging
+ messages]. */
+ if (!rc)
+ {
+ __seterrno ();
+ syscall_printf ("CreateProcess failed, %E");
+ /* If this was a failed exec, restore the saved sendsig. */
+ if (reset_sendsig)
+ {
+ myself->sendsig = myself->exec_sendsig;
+ myself->exec_sendsig = NULL;
+ }
+ res = -1;
+ if (moreinfo->myself_pinfo)
+ CloseHandle (moreinfo->myself_pinfo);
+ goto out;
+ }
+
+ if (!(c_flags & CREATE_SUSPENDED))
+ strace.write_childpid (ch, pi.dwProcessId);
+
+ /* Fixup the parent data structures if needed and resume the child's
+ main thread. */
+ if (cygheap->fdtab.need_fixup_before ())
+ cygheap->fdtab.fixup_before_exec (pi.dwProcessId);
+
+ if (mode != _P_OVERLAY)
+ cygpid = cygwin_pid (pi.dwProcessId);
+ else
+ cygpid = myself->pid;
+
+ /* We print the original program name here so the user can see that too. */
+ syscall_printf ("%d = spawn_guts (%s, %.9500s)",
+ rc ? cygpid : (unsigned int) -1, prog_arg, one_line.buf);
+
+ /* Name the handle similarly to proc_subproc. */
+ ProtectHandle1 (pi.hProcess, childhProc);
+
+ bool synced;
+ pid_t pid;
+ if (mode == _P_OVERLAY)
+ {
+ chExeced = &ch; /* FIXME: there's a race here if a user sneaks in CTRL-C */
+ myself->dwProcessId = pi.dwProcessId;
+ strace.execing = 1;
+ myself.hProcess = hExeced = pi.hProcess;
+ strcpy (myself->progname, real_path); // FIXME: race?
+ sigproc_printf ("new process name %s", myself->progname);
+ /* If wr_proc_pipe doesn't exist then this process was not started by a cygwin
+ process. So, we need to wait around until the process we've just "execed"
+ dies. Use our own wait facility to wait for our own pid to exit (there
+ is some minor special case code in proc_waiter and friends to accommodate
+ this).
+
+ If wr_proc_pipe exists, then it should be duplicated to the child.
+ If the child has exited already, that's ok. The parent will pick up
+ on this fact when we exit. dup_proc_pipe will close our end of the pipe.
+ Note that wr_proc_pipe may also be == INVALID_HANDLE_VALUE. That will make
+ dup_proc_pipe essentially a no-op. */
+ if (!newargv.win16_exe && myself->wr_proc_pipe)
+ {
+ if (!looped)
+ {
+ myself->sync_proc_pipe (); /* Make sure that we own wr_proc_pipe
+ just in case we've been previously
+ execed. */
+ myself.zap_cwd ();
+ }
+ orig_wr_proc_pipe = myself->dup_proc_pipe (pi.hProcess);
+ }
+ pid = myself->pid;
+ if (!ch.iscygwin ())
+ close_all_files ();
+ }
+ else
+ {
+ myself->set_has_pgid_children ();
+ ProtectHandle (pi.hThread);
+ pinfo child (cygpid, PID_IN_USE);
+ if (!child)
+ {
+ syscall_printf ("pinfo failed");
+ if (get_errno () != ENOMEM)
+ set_errno (EAGAIN);
+ res = -1;
+ goto out;
+ }
+ child->dwProcessId = pi.dwProcessId;
+ child.hProcess = pi.hProcess;
+
+ strcpy (child->progname, real_path);
+ /* FIXME: This introduces an unreferenced, open handle into the child.
+ The purpose is to keep the pid shared memory open so that all of
+ the fields filled out by child.remember do not disappear and so there
+ is not a brief period during which the pid is not available.
+ However, we should try to find another way to do this eventually. */
+ DuplicateHandle (hMainProc, child.shared_handle (), pi.hProcess,
+ NULL, 0, 0, DUPLICATE_SAME_ACCESS);
+ child->start_time = time (NULL); /* Register child's starting time. */
+ child->nice = myself->nice;
+ if (!child.remember (mode == _P_DETACH))
+ {
+ /* FIXME: Child in strange state now */
+ CloseHandle (pi.hProcess);
+ ForceCloseHandle (pi.hThread);
+ res = -1;
+ goto out;
+ }
+ pid = child->pid;
+ }
+
+ /* Start the child running */
+ if (c_flags & CREATE_SUSPENDED)
+ {
+ ResumeThread (pi.hThread);
+ strace.write_childpid (ch, pi.dwProcessId);
+ }
+ ForceCloseHandle (pi.hThread);
+
+ sigproc_printf ("spawned windows pid %d", pi.dwProcessId);
+
+ synced = ch.sync (pi.dwProcessId, pi.hProcess, INFINITE);
+
+ switch (mode)
+ {
+ case _P_OVERLAY:
+ myself.hProcess = pi.hProcess;
+ if (!synced)
+ {
+ if (orig_wr_proc_pipe)
+ {
+ myself->wr_proc_pipe_owner = GetCurrentProcessId ();
+ myself->wr_proc_pipe = orig_wr_proc_pipe;
+ }
+ DWORD res = ch.proc_retry (pi.hProcess);
+ if (!res)
+ {
+ looped++;
+ goto loop;
+ }
+ close_all_files (true);
+ }
+ else
+ {
+ close_all_files (true);
+ if (!myself->wr_proc_pipe
+ && WaitForSingleObject (pi.hProcess, 0) == WAIT_TIMEOUT)
+ {
+ extern bool is_toplevel_proc;
+ is_toplevel_proc = true;
+ myself.remember (false);
+ waitpid (myself->pid, &res, 0);
+ }
+ }
+ myself.exit (EXITCODE_NOSET);
+ break;
+ case _P_WAIT:
+ case _P_SYSTEM:
+ if (waitpid (cygpid, &res, 0) != cygpid)
+ res = -1;
+ break;
+ case _P_DETACH:
+ res = 0; /* Lost all memory of this child. */
+ break;
+ case _P_NOWAIT:
+ case _P_NOWAITO:
+ case _P_VFORK:
+ res = cygpid;
+ break;
+ default:
+ break;
+ }
+
+out:
+ if (envblock)
+ free (envblock);
+ pthread_cleanup_pop (1);
+ return (int) res;
+}
+
+extern "C" int
+cwait (int *result, int pid, int)
+{
+ return waitpid (pid, result, 0);
+}
+
+/*
+* Helper function for spawn runtime calls.
+* Doesn't search the path.
+*/
+
+extern "C" int
+spawnve (int mode, const char *path, const char *const *argv,
+ const char *const *envp)
+{
+ int ret;
+#ifdef NEWVFORK
+ vfork_save *vf = vfork_storage.val ();
+
+ if (vf != NULL && (vf->pid < 0) && mode == _P_OVERLAY)
+ mode = _P_NOWAIT;
+ else
+ vf = NULL;
+#endif
+
+ syscall_printf ("spawnve (%s, %s, %x)", path, argv[0], envp);
+
+ switch (mode)
+ {
+ case _P_OVERLAY:
+ /* We do not pass _P_SEARCH_PATH here. execve doesn't search PATH.*/
+ /* Just act as an exec if _P_OVERLAY set. */
+ spawn_guts (path, argv, envp, mode);
+ /* Errno should be set by spawn_guts. */
+ ret = -1;
+ break;
+ case _P_VFORK:
+ case _P_NOWAIT:
+ case _P_NOWAITO:
+ case _P_WAIT:
+ case _P_DETACH:
+ case _P_SYSTEM:
+ ret = spawn_guts (path, argv, envp, mode);
+#ifdef NEWVFORK
+ if (vf)
+ {
+ if (ret > 0)
+ {
+ debug_printf ("longjmping due to vfork");
+ vf->restore_pid (ret);
+ }
+ }
+#endif
+ break;
+ default:
+ set_errno (EINVAL);
+ ret = -1;
+ break;
+ }
+ return ret;
+}
+
+/*
+* spawn functions as implemented in the MS runtime library.
+* Most of these based on (and copied from) newlib/libc/posix/execXX.c
+*/
+
+extern "C" int
+spawnl (int mode, const char *path, const char *arg0, ...)
+{
+ int i;
+ va_list args;
+ const char *argv[256];
+
+ va_start (args, arg0);
+ argv[0] = arg0;
+ i = 1;
+
+ do
+ argv[i] = va_arg (args, const char *);
+ while (argv[i++] != NULL);
+
+ va_end (args);
+
+ return spawnve (mode, path, (char * const *) argv, cur_environ ());
+}
+
+extern "C" int
+spawnle (int mode, const char *path, const char *arg0, ...)
+{
+ int i;
+ va_list args;
+ const char * const *envp;
+ const char *argv[256];
+
+ va_start (args, arg0);
+ argv[0] = arg0;
+ i = 1;
+
+ do
+ argv[i] = va_arg (args, const char *);
+ while (argv[i++] != NULL);
+
+ envp = va_arg (args, const char * const *);
+ va_end (args);
+
+ return spawnve (mode, path, (char * const *) argv, (char * const *) envp);
+}
+
+extern "C" int
+spawnlp (int mode, const char *path, const char *arg0, ...)
+{
+ int i;
+ va_list args;
+ const char *argv[256];
+
+ va_start (args, arg0);
+ argv[0] = arg0;
+ i = 1;
+
+ do
+ argv[i] = va_arg (args, const char *);
+ while (argv[i++] != NULL);
+
+ va_end (args);
+
+ return spawnvpe (mode, path, (char * const *) argv, cur_environ ());
+}
+
+extern "C" int
+spawnlpe (int mode, const char *path, const char *arg0, ...)
+{
+ int i;
+ va_list args;
+ const char * const *envp;
+ const char *argv[256];
+
+ va_start (args, arg0);
+ argv[0] = arg0;
+ i = 1;
+
+ do
+ argv[i] = va_arg (args, const char *);
+ while (argv[i++] != NULL);
+
+ envp = va_arg (args, const char * const *);
+ va_end (args);
+
+ return spawnvpe (mode, path, (char * const *) argv, envp);
+}
+
+extern "C" int
+spawnv (int mode, const char *path, const char * const *argv)
+{
+ return spawnve (mode, path, argv, cur_environ ());
+}
+
+extern "C" int
+spawnvp (int mode, const char *path, const char * const *argv)
+{
+ return spawnvpe (mode, path, argv, cur_environ ());
+}
+
+extern "C" int
+spawnvpe (int mode, const char *file, const char * const *argv,
+ const char * const *envp)
+{
+ path_conv buf;
+ return spawnve (mode, find_exec (file, buf), argv, envp);
+}
+
+int
+av::fixup (const char *prog_arg, path_conv& real_path, const char *ext)
+{
+ const char *p;
+ bool exeext = strcasematch (ext, ".exe");
+ if (exeext && real_path.iscygexec () || strcasematch (ext, ".bat"))
+ return 0;
+ if (!*ext && ((p = ext - 4) > (char *) real_path)
+ && (strcasematch (p, ".bat") || strcasematch (p, ".cmd")
+ || strcasematch (p, ".btm")))
+ return 0;
+ while (1)
+ {
+ char *pgm = NULL;
+ char *arg1 = NULL;
+ char *ptr, *buf;
+
+ HANDLE h = CreateFile (real_path, GENERIC_READ,
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
+ &sec_none_nih, OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL, 0);
+ if (h == INVALID_HANDLE_VALUE)
+ goto err;
+
+ HANDLE hm = CreateFileMapping (h, &sec_none_nih, PAGE_READONLY, 0, 0, NULL);
+ CloseHandle (h);
+ if (!hm)
+ {
+ /* ERROR_FILE_INVALID indicates very likely an empty file. */
+ if (GetLastError () == ERROR_FILE_INVALID)
+ {
+ debug_printf ("zero length file, treat as script.");
+ goto just_shell;
+ }
+ goto err;
+ }
+ buf = (char *) MapViewOfFile(hm, FILE_MAP_READ, 0, 0, 0);
+ CloseHandle (hm);
+ if (!buf)
+ goto err;
+
+ {
+ myfault efault;
+ if (efault.faulted ())
+ {
+ UnmapViewOfFile (buf);
+ real_path.set_cygexec (false);
+ break;
+ }
+ if (buf[0] == 'M' && buf[1] == 'Z')
+ {
+ WORD subsys;
+ unsigned off = (unsigned char) buf[0x18] | (((unsigned char) buf[0x19]) << 8);
+ win16_exe = off < sizeof (IMAGE_DOS_HEADER);
+ if (!win16_exe)
+ real_path.set_cygexec (!!hook_or_detect_cygwin (buf, NULL, subsys));
+ else
+ real_path.set_cygexec (false);
+ UnmapViewOfFile (buf);
+ iscui = subsys == IMAGE_SUBSYSTEM_WINDOWS_CUI;
+ break;
+ }
+ }
+
+ debug_printf ("%s is possibly a script", (char *) real_path);
+
+ ptr = buf;
+ if (*ptr++ == '#' && *ptr++ == '!')
+ {
+ ptr += strspn (ptr, " \t");
+ size_t len = strcspn (ptr, "\r\n");
+ if (len)
+ {
+ char *namebuf = (char *) alloca (len + 1);
+ memcpy (namebuf, ptr, len);
+ namebuf[len] = '\0';
+ for (ptr = pgm = namebuf; *ptr; ptr++)
+ if (!arg1 && (*ptr == ' ' || *ptr == '\t'))
+ {
+ /* Null terminate the initial command and step over any additional white
+ space. If we've hit the end of the line, exit the loop. Otherwise,
+ we've found the first argument. Position the current pointer on the
+ last known white space. */
+ *ptr = '\0';
+ char *newptr = ptr + 1;
+ newptr += strspn (newptr, " \t");
+ if (!*newptr)
+ break;
+ arg1 = newptr;
+ ptr = newptr - 1;
+ }
+ }
+ }
+ UnmapViewOfFile (buf);
+just_shell:
+ if (!pgm)
+ {
+ if (strcasematch (ext, ".com"))
+ break;
+ pgm = (char *) "/bin/sh";
+ arg1 = NULL;
+ }
+
+ /* Replace argv[0] with the full path to the script if this is the
+ first time through the loop. */
+ replace0_maybe (prog_arg);
+
+ /* pointers:
+ * pgm interpreter name
+ * arg1 optional string
+ */
+ if (arg1)
+ unshift (arg1);
+
+ /* FIXME: This should not be using FE_NATIVE. It should be putting
+ the posix path on the argv list. */
+ find_exec (pgm, real_path, "PATH=", FE_NATIVE, &ext);
+ unshift (real_path, 1);
+ }
+ return 0;
+
+err:
+ __seterrno ();
+ return -1;
+}
diff --git a/winsup/cygwin/sync.h b/winsup/cygwin/sync.h
new file mode 100644
index 00000000000..f7ce7e1b4b3
--- /dev/null
+++ b/winsup/cygwin/sync.h
@@ -0,0 +1,73 @@
+/* sync.h: Header file for cygwin synchronization primitives.
+
+ Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Red Hat, Inc.
+
+ Written by Christopher Faylor <cgf@cygnus.com>
+
+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. */
+
+#ifndef _SYNC_H
+#define _SYNC_H
+/* FIXME: Note that currently this class cannot be allocated via `new' since
+ there are issues with malloc and fork. */
+class muto
+{
+public:
+ const char *name;
+private:
+ static DWORD exiting_thread;
+ LONG sync; /* Used to serialize access to this class. */
+ LONG waiters; /* Number of threads waiting for lock. */
+ HANDLE bruteforce; /* event handle used to control waiting for lock. */
+public:
+ LONG visits; /* Count of number of times a thread has called acquire. */
+ void *tls; /* Tls of lock owner. */
+ // class muto *next;
+
+ /* The real constructor. */
+ muto *init (const char *) __attribute__ ((regparm (2)));
+
+#if 0 /* FIXME: See comment in sync.cc */
+ ~muto ()
+#endif
+ int acquire (DWORD ms = INFINITE) __attribute__ ((regparm (2))); /* Acquire the lock. */
+ int release () __attribute__ ((regparm (1))); /* Release the lock. */
+
+ bool acquired () __attribute__ ((regparm (1)));
+ void upforgrabs () {tls = this;} // just set to an invalid address
+ void grab () __attribute__ ((regparm (1)));
+ operator int () const {return !!name;}
+ static void set_exiting_thread () {exiting_thread = GetCurrentThreadId ();}
+};
+
+class lock_process
+{
+ bool skip_unlock;
+ static muto locker;
+public:
+ static void init () {locker.init ("lock_process");}
+ void dont_bother () {skip_unlock = true;}
+ lock_process (bool exiting = false)
+ {
+ locker.acquire ();
+ skip_unlock = exiting;
+ if (exiting && exit_state < ES_SET_MUTO)
+ {
+ exit_state = ES_SET_MUTO;
+ muto::set_exiting_thread ();
+ }
+ }
+ ~lock_process ()
+ {
+ if (!skip_unlock)
+ locker.release ();
+ }
+ friend class dtable;
+ friend class fhandler_fifo;
+};
+
+#endif /*_SYNC_H*/
diff --git a/winsup/cygwin/wininfo.h b/winsup/cygwin/wininfo.h
new file mode 100644
index 00000000000..f67cf9a4b92
--- /dev/null
+++ b/winsup/cygwin/wininfo.h
@@ -0,0 +1,25 @@
+/* wininfo.h: main Cygwin header file.
+
+ Copyright 2004 Red Hat, Inc.
+
+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. */
+
+class muto;
+class wininfo
+{
+ HWND hwnd;
+ static muto _lock;
+public:
+ operator HWND ();
+ int __stdcall process (HWND, UINT, WPARAM, LPARAM)
+ __attribute__ ((regparm (3)));
+ void lock ();
+ void release ();
+ DWORD WINAPI winthread () __attribute__ ((regparm (1)));
+};
+
+extern wininfo winmsg;