OSDN Git Service

1d0b9cb9a28ef96ccd1c0ffe9328b149208c1054
[pf3gnuchains/pf3gnuchains4x.git] / winsup / cygwin / dtable.cc
1 /* dtable.cc: file descriptor support.
2
3    Copyright 1996, 1997, 1998, 1999, 2000 Cygnus Solutions.
4
5 This file is part of Cygwin.
6
7 This software is a copyrighted work licensed under the terms of the
8 Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
9 details. */
10
11 #define  __INSIDE_CYGWIN_NET__
12
13 #define Win32_Winsock
14 #include "winsup.h"
15 #include <errno.h>
16 #include <sys/socket.h>
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <unistd.h>
20 #include <fcntl.h>
21 #include <sys/cygwin.h>
22
23 #include <winsock.h>
24 #include "sync.h"
25 #include "sigproc.h"
26 #include "pinfo.h"
27 #include "cygheap.h"
28 #include "cygerrno.h"
29 #include "fhandler.h"
30 #include "path.h"
31 #include "dtable.h"
32
33 dtable fdtab;
34
35 static DWORD std_consts[] = {STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
36                            STD_ERROR_HANDLE};
37
38 /* Set aside space for the table of fds */
39 void
40 dtable_init (void)
41 {
42   if (!fdtab.size)
43     fdtab.extend(NOFILE_INCR);
44 }
45
46 void __stdcall
47 set_std_handle (int fd)
48 {
49   if (fd == 0)
50     SetStdHandle (std_consts[fd], fdtab[fd]->get_handle ());
51   else if (fd <= 2)
52     SetStdHandle (std_consts[fd], fdtab[fd]->get_output_handle ());
53 }
54
55 int
56 dtable::extend (int howmuch)
57 {
58   int new_size = size + howmuch;
59   fhandler_base **newfds;
60
61   if (howmuch <= 0)
62     return 0;
63
64   /* Try to allocate more space for fd table. We can't call realloc()
65      here to preserve old table if memory allocation fails */
66
67   if (!(newfds = (fhandler_base **) ccalloc (HEAP_ARGV, new_size, sizeof newfds[0])))
68     {
69       debug_printf ("calloc failed");
70       return 0;
71     }
72   if (fds)
73     {
74       memcpy (newfds, fds, size * sizeof (fds[0]));
75       cfree (fds);
76     }
77
78   size = new_size;
79   fds = newfds;
80   debug_printf ("size %d, fds %p", size, fds);
81   return 1;
82 }
83
84 /* Initialize the file descriptor/handle mapping table.
85    We only initialize the parent table here.  The child table is
86    initialized at each fork () call.  */
87
88 void
89 stdio_init (void)
90 {
91   /* Set these before trying to output anything from strace.
92      Also, always set them even if we're to pick up our parent's fds
93      in case they're missed.  */
94
95   if (!myself->ppid_handle && NOTSTATE(myself, PID_CYGPARENT))
96     {
97       HANDLE in = GetStdHandle (STD_INPUT_HANDLE);
98       HANDLE out = GetStdHandle (STD_OUTPUT_HANDLE);
99       HANDLE err = GetStdHandle (STD_ERROR_HANDLE);
100
101       fdtab.init_std_file_from_handle (0, in, GENERIC_READ, "{stdin}");
102
103       /* STD_ERROR_HANDLE has been observed to be the same as
104          STD_OUTPUT_HANDLE.  We need separate handles (e.g. using pipes
105          to pass data from child to parent).  */
106       if (out == err)
107         {
108           /* Since this code is not invoked for forked tasks, we don't have
109              to worry about the close-on-exec flag here.  */
110           if (!DuplicateHandle (hMainProc, out, hMainProc, &err, 0,
111                                  1, DUPLICATE_SAME_ACCESS))
112             {
113               /* If that fails, do this as a fall back.  */
114               err = out;
115               system_printf ("couldn't make stderr distinct from stdout");
116             }
117         }
118
119       fdtab.init_std_file_from_handle (1, out, GENERIC_WRITE, "{stdout}");
120       fdtab.init_std_file_from_handle (2, err, GENERIC_WRITE, "{stderr}");
121     }
122 }
123
124 int
125 dtable::not_open (int fd)
126 {
127   SetResourceLock(LOCK_FD_LIST,READ_LOCK," not_open");
128
129   int res = fd < 0 || fd >= (int)size || fds[fd] == NULL;
130
131   ReleaseResourceLock(LOCK_FD_LIST,READ_LOCK," not open");
132   return res;
133 }
134
135 int
136 dtable::find_unused_handle (int start)
137 {
138   AssertResourceOwner(LOCK_FD_LIST, READ_LOCK);
139
140   do
141     {
142       for (int i = start; i < (int) size; i++)
143         /* See if open -- no need for overhead of not_open */
144         if (fds[i] == NULL)
145           return i;
146     }
147   while (extend (NOFILE_INCR));
148   return -1;
149 }
150
151 void
152 dtable::release (int fd)
153 {
154   if (!not_open (fd))
155     {
156       if ((fds[fd]->get_device () & FH_DEVMASK) == FH_SOCKET)
157         dec_need_fixup_before ();
158       delete fds[fd];
159       fds[fd] = NULL;
160     }
161 }
162
163 void
164 dtable::init_std_file_from_handle (int fd, HANDLE handle,
165                                   DWORD myaccess, const char *name)
166 {
167   int bin = binmode ? O_BINARY : 0;
168   /* Check to see if we're being redirected - if not then
169      we open then as consoles */
170   if (fd == 0 || fd == 1 || fd == 2)
171     {
172       first_fd_for_open = 0;
173       /* See if we can consoleify it  - if it is a console,
174        don't open it in binary.  That will screw up our crlfs*/
175       CONSOLE_SCREEN_BUFFER_INFO buf;
176       if (GetConsoleScreenBufferInfo (handle, &buf))
177         {
178           bin = 0;
179           if (ISSTATE (myself, PID_USETTY))
180             name = "/dev/tty";
181           else
182             name = "/dev/conout";
183         }
184       else if (FlushConsoleInputBuffer (handle))
185         {
186           bin = 0;
187           if (ISSTATE (myself, PID_USETTY))
188             name = "/dev/tty";
189           else
190             name = "/dev/conin";
191         }
192     }
193
194   build_fhandler (fd, name, handle)->init (handle, myaccess, bin);
195   set_std_handle (fd);
196   paranoid_printf ("fd %d, handle %p", fd, handle);
197 }
198
199 extern "C"
200 int
201 cygwin_attach_handle_to_fd (char *name, int fd, HANDLE handle, mode_t bin,
202                               DWORD myaccess)
203 {
204   if (fd == -1)
205     fd = fdtab.find_unused_handle();
206   fhandler_base *res = fdtab.build_fhandler (fd, name, handle);
207   res->init (handle, myaccess, bin);
208   return fd;
209 }
210
211 fhandler_base *
212 dtable::build_fhandler (int fd, const char *name, HANDLE handle)
213 {
214   int unit;
215   DWORD devn;
216
217   if ((devn = get_device_number (name, unit)) == FH_BAD)
218     {
219       struct sockaddr sa;
220       int sal = sizeof (sa);
221       CONSOLE_SCREEN_BUFFER_INFO cinfo;
222       DCB dcb;
223
224       if (handle == NULL)
225         devn = FH_DISK;
226       else if (GetNumberOfConsoleInputEvents (handle, (DWORD *) &cinfo))
227         devn = FH_CONIN;
228       else if (GetConsoleScreenBufferInfo (handle, &cinfo))
229         devn= FH_CONOUT;
230       else if (wsock32_handle && getpeername ((SOCKET) handle, &sa, &sal))
231         devn = FH_SOCKET;
232       else if (GetFileType (handle) == FILE_TYPE_PIPE)
233         devn = FH_PIPE;
234       else if (GetCommState (handle, &dcb))
235         devn = FH_SERIAL;
236       else
237         devn = FH_DISK;
238     }
239
240   return build_fhandler (fd, devn, name, unit);
241 }
242
243 fhandler_base *
244 dtable::build_fhandler (int fd, DWORD dev, const char *name, int unit)
245 {
246   fhandler_base *fh;
247   void *buf = ccalloc (HEAP_FHANDLER, 1, sizeof (fhandler_union) + 100);
248
249   dev &= FH_DEVMASK;
250   switch (dev)
251     {
252       case FH_TTYM:
253         fh = new (buf) fhandler_tty_master (name, unit);
254         break;
255       case FH_CONSOLE:
256       case FH_CONIN:
257       case FH_CONOUT:
258         fh = new (buf) fhandler_console (name);
259         break;
260       case FH_PTYM:
261         fh = new (buf) fhandler_pty_master (name);
262         break;
263       case FH_TTYS:
264         if (unit < 0)
265           fh = new (buf) fhandler_tty_slave (name);
266         else
267           fh = new (buf) fhandler_tty_slave (unit, name);
268         break;
269       case FH_WINDOWS:
270         fh = new (buf) fhandler_windows (name);
271         break;
272       case FH_SERIAL:
273         fh = new (buf) fhandler_serial (name, dev, unit);
274         break;
275       case FH_PIPE:
276       case FH_PIPER:
277       case FH_PIPEW:
278         fh = new (buf) fhandler_pipe (name, dev);
279         break;
280       case FH_SOCKET:
281         fh = new (buf) fhandler_socket (name);
282         break;
283       case FH_DISK:
284         fh = new (buf) fhandler_disk_file (NULL);
285         break;
286       case FH_FLOPPY:
287         fh = new (buf) fhandler_dev_floppy (name, unit);
288         break;
289       case FH_TAPE:
290         fh = new (buf) fhandler_dev_tape (name, unit);
291         break;
292       case FH_NULL:
293         fh = new (buf) fhandler_dev_null (name);
294         break;
295       case FH_ZERO:
296         fh = new (buf) fhandler_dev_zero (name);
297         break;
298       case FH_RANDOM:
299         fh = new (buf) fhandler_dev_random (name, unit);
300         break;
301       case FH_MEM:
302         fh = new (buf) fhandler_dev_mem (name, unit);
303         break;
304       case FH_CLIPBOARD:
305         fh = new (buf) fhandler_dev_clipboard (name);
306         break;
307       default:
308         /* FIXME - this could recurse forever */
309         return build_fhandler (fd, name, NULL);
310     }
311
312   debug_printf ("%s - cb %d, fd %d, fh %p", fh->get_name () ?: "", fh->cb,
313                 fd, fh);
314   return fd >= 0 ? (fds[fd] = fh) : fh;
315 }
316
317 fhandler_base *
318 dtable::dup_worker (fhandler_base *oldfh)
319 {
320   fhandler_base *newfh = build_fhandler (-1, oldfh->get_device (), NULL);
321   *newfh = *oldfh;
322   newfh->set_io_handle (NULL);
323   if (oldfh->dup (newfh))
324     {
325       cfree (newfh);
326       newfh = NULL;
327       return NULL;
328     }
329
330   newfh->set_close_on_exec_flag (0);
331   MALLOC_CHECK;
332   return newfh;
333 }
334
335 int
336 dtable::dup2 (int oldfd, int newfd)
337 {
338   int res = -1;
339   fhandler_base *newfh = NULL;  // = NULL to avoid an incorrect warning
340
341   MALLOC_CHECK;
342   debug_printf ("dup2 (%d, %d)", oldfd, newfd);
343
344   if (not_open (oldfd))
345     {
346       syscall_printf ("fd %d not open", oldfd);
347       set_errno (EBADF);
348       goto done;
349     }
350
351   if (newfd == oldfd)
352     {
353       res = 0;
354       goto done;
355     }
356
357   if ((newfh = dup_worker (fds[oldfd])) == NULL)
358     {
359       res = -1;
360       goto done;
361     }
362
363   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
364
365   if ((size_t) newfd >= fdtab.size || newfd < 0)
366     {
367       syscall_printf ("new fd out of bounds: %d", newfd);
368       set_errno (EBADF);
369       goto done;
370     }
371
372   if ((size_t) newfd >= fdtab.size)
373    {
374      int inc_size = NOFILE_INCR * ((newfd + NOFILE_INCR - 1) / NOFILE_INCR) -
375                     fdtab.size;
376      fdtab.extend (inc_size);
377    }
378
379   if (!not_open (newfd))
380     _close (newfd);
381   fds[newfd] = newfh;
382
383   /* Count sockets. */
384   if ((fds[newfd]->get_device () & FH_DEVMASK) == FH_SOCKET)
385     inc_need_fixup_before ();
386
387   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
388   MALLOC_CHECK;
389
390   if ((res = newfd) <= 2)
391     set_std_handle (res);
392
393   MALLOC_CHECK;
394 done:
395   syscall_printf ("%d = dup2 (%d, %d)", res, oldfd, newfd);
396
397   return res;
398 }
399
400 select_record *
401 dtable::select_read (int fd, select_record *s)
402 {
403   if (not_open (fd))
404     {
405       set_errno (EBADF);
406       return NULL;
407     }
408   fhandler_base *fh = fds[fd];
409   s = fh->select_read (s);
410   s->fd = fd;
411   s->fh = fh;
412   s->saw_error = 0;
413   debug_printf ("%s fd %d", fh->get_name (), fd);
414   return s;
415 }
416
417 select_record *
418 dtable::select_write (int fd, select_record *s)
419 {
420   if (not_open (fd))
421     {
422       set_errno (EBADF);
423       return NULL;
424     }
425   fhandler_base *fh = fds[fd];
426   s = fh->select_write (s);
427   s->fd = fd;
428   s->fh = fh;
429   s->saw_error = 0;
430   debug_printf ("%s fd %d", fh->get_name (), fd);
431   return s;
432 }
433
434 select_record *
435 dtable::select_except (int fd, select_record *s)
436 {
437   if (not_open (fd))
438     {
439       set_errno (EBADF);
440       return NULL;
441     }
442   fhandler_base *fh = fds[fd];
443   s = fh->select_except (s);
444   s->fd = fd;
445   s->fh = fh;
446   s->saw_error = 0;
447   debug_printf ("%s fd %d", fh->get_name (), fd);
448   return s;
449 }
450
451 /* Function to walk the fd table after an exec and perform
452    per-fhandler type fixups. */
453 void
454 dtable::fixup_before_fork (DWORD target_proc_id)
455 {
456   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
457   fhandler_base *fh;
458   for (size_t i = 0; i < size; i++)
459     if ((fh = fds[i]) != NULL)
460       {
461         debug_printf ("fd %d(%s)", i, fh->get_name ());
462         fh->fixup_before_fork_exec (target_proc_id);
463       }
464   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
465 }
466
467 void
468 dtable::fixup_before_exec (DWORD target_proc_id)
469 {
470   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
471   fhandler_base *fh;
472   for (size_t i = 0; i < size; i++)
473     if ((fh = fds[i]) != NULL && (!fh->get_close_on_exec ()))
474       {
475         debug_printf ("fd %d(%s)", i, fh->get_name ());
476         fh->fixup_before_fork_exec (target_proc_id);
477       }
478   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
479 }
480
481 void
482 dtable::fixup_after_exec (HANDLE parent, size_t sz, fhandler_base **f)
483 {
484   size = sz;
485   fds = f;
486   first_fd_for_open = 0;
487   fhandler_base *fh;
488   for (size_t i = 0; i < size; i++)
489     if ((fh = fds[i]) != NULL)
490       {
491         fh->clear_readahead ();
492         if (fh->get_close_on_exec ())
493           release (i);
494         else
495           {
496             fh->fixup_after_exec (parent);
497             if (i == 0)
498               SetStdHandle (std_consts[i], fh->get_io_handle ());
499             else if (i <= 2)
500               SetStdHandle (std_consts[i], fh->get_output_handle ());
501           }
502       }
503 }
504
505 void
506 dtable::fixup_after_fork (HANDLE parent)
507 {
508   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
509   fhandler_base *fh;
510   for (size_t i = 0; i < size; i++)
511     if ((fh = fds[i]) != NULL)
512       {
513         if (fh->get_close_on_exec () || fh->get_need_fork_fixup ())
514           {
515             debug_printf ("fd %d(%s)", i, fh->get_name ());
516             fh->fixup_after_fork (parent);
517           }
518       }
519   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
520 }
521
522 int
523 dtable::vfork_child_dup ()
524 {
525   fhandler_base **newtable;
526   newtable = (fhandler_base **) ccalloc (HEAP_ARGV, size, sizeof(fds[0]));
527   int res = 1;
528
529   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
530   for (size_t i = 0; i < size; i++)
531     if (not_open (i))
532       continue;
533     else if ((newtable[i] = dup_worker (fds[i])) == NULL)
534       {
535         res = 0;
536         set_errno (EBADF);
537         goto out;
538       }
539
540   fds_on_hold = fds;
541   fds = newtable;
542 out:
543   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
544   return 1;
545 }
546
547 void
548 dtable::vfork_parent_restore ()
549 {
550   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
551
552   close_all_files ();
553   fhandler_base **deleteme = fds;
554   fds = fds_on_hold;
555   fds_on_hold = NULL;
556   cfree (deleteme);
557
558   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
559   return;
560 }