OSDN Git Service

* winsup.h: Split out dtable definitions into separate header file.
[pf3gnuchains/sourceware.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
22 #include <winsock.h>
23 #include "dtable.h"
24 #include "pinfo.h"
25
26 dtable fdtab;
27
28 /* Set aside space for the table of fds */
29 void
30 dtable_init (void)
31 {
32   if (!fdtab.size)
33     fdtab.extend(NOFILE_INCR);
34 }
35
36 void __stdcall
37 set_std_handle (int fd)
38 {
39   if (fd == 0)
40     SetStdHandle (STD_INPUT_HANDLE, fdtab[fd]->get_handle ());
41   else if (fd == 1)
42     SetStdHandle (STD_OUTPUT_HANDLE, fdtab[fd]->get_output_handle ());
43   else if (fd == 2)
44     SetStdHandle (STD_ERROR_HANDLE, fdtab[fd]->get_output_handle ());
45 }
46
47 int
48 dtable::extend (int howmuch)
49 {
50   int new_size = size + howmuch;
51   fhandler_base **newfds;
52
53   if (howmuch <= 0)
54     return 0;
55
56   /* Try to allocate more space for fd table. We can't call realloc()
57      here to preserve old table if memory allocation fails */
58
59   if (!(newfds = (fhandler_base **) calloc (new_size, sizeof newfds[0])))
60     {
61       debug_printf ("calloc failed");
62       return 0;
63     }
64   if (fds)
65     {
66       memcpy (newfds, fds, size * sizeof (fds[0]));
67       free (fds);
68     }
69
70   size = new_size;
71   fds = newfds;
72   debug_printf ("size %d, fds %p", size, fds);
73   return 1;
74 }
75
76 /* Initialize the file descriptor/handle mapping table.
77    We only initialize the parent table here.  The child table is
78    initialized at each fork () call.  */
79
80 void
81 stdio_init (void)
82 {
83   /* Set these before trying to output anything from strace.
84      Also, always set them even if we're to pick up our parent's fds
85      in case they're missed.  */
86
87   if (!parent_alive && NOTSTATE(myself, PID_CYGPARENT))
88     {
89       HANDLE in = GetStdHandle (STD_INPUT_HANDLE);
90       HANDLE out = GetStdHandle (STD_OUTPUT_HANDLE);
91       HANDLE err = GetStdHandle (STD_ERROR_HANDLE);
92
93       fdtab.init_std_file_from_handle (0, in, GENERIC_READ, "{stdin}");
94
95       /* STD_ERROR_HANDLE has been observed to be the same as
96          STD_OUTPUT_HANDLE.  We need separate handles (e.g. using pipes
97          to pass data from child to parent).  */
98       if (out == err)
99         {
100           /* Since this code is not invoked for forked tasks, we don't have
101              to worry about the close-on-exec flag here.  */
102           if (!DuplicateHandle (hMainProc, out, hMainProc, &err, 0,
103                                  1, DUPLICATE_SAME_ACCESS))
104             {
105               /* If that fails, do this as a fall back.  */
106               err = out;
107               system_printf ("couldn't make stderr distinct from stdout");
108             }
109         }
110
111       fdtab.init_std_file_from_handle (1, out, GENERIC_WRITE, "{stdout}");
112       fdtab.init_std_file_from_handle (2, err, GENERIC_WRITE, "{stderr}");
113     }
114 }
115
116 int
117 dtable::not_open (int fd)
118 {
119   SetResourceLock(LOCK_FD_LIST,READ_LOCK," not_open");
120
121   int res = fd < 0 || fd >= (int)size || fds[fd] == NULL;
122
123   ReleaseResourceLock(LOCK_FD_LIST,READ_LOCK," not open");
124   return res;
125 }
126
127 int
128 dtable::find_unused_handle (int start)
129 {
130   AssertResourceOwner(LOCK_FD_LIST, READ_LOCK);
131
132   do
133     {
134       for (int i = start; i < (int) size; i++)
135         /* See if open -- no need for overhead of not_open */
136         if (fds[i] == NULL)
137           return i;
138     }
139   while (extend (NOFILE_INCR));
140   return -1;
141 }
142
143 void
144 dtable::release (int fd)
145 {
146   if (!not_open (fd))
147     {
148       delete (fds[fd]);
149       fds[fd] = NULL;
150     }
151 }
152
153 void
154 dtable::init_std_file_from_handle (int fd, HANDLE handle,
155                                   DWORD myaccess, const char *name)
156 {
157   int bin = binmode ? O_BINARY : 0;
158   /* Check to see if we're being redirected - if not then
159      we open then as consoles */
160   if (fd == 0 || fd == 1 || fd == 2)
161     {
162       first_fd_for_open = 0;
163       /* See if we can consoleify it  - if it is a console,
164        don't open it in binary.  That will screw up our crlfs*/
165       CONSOLE_SCREEN_BUFFER_INFO buf;
166       if (GetConsoleScreenBufferInfo (handle, &buf))
167         {
168           bin = 0;
169           if (ISSTATE (myself, PID_USETTY))
170             name = "/dev/tty";
171           else
172             name = "/dev/conout";
173         }
174       else if (FlushConsoleInputBuffer (handle))
175         {
176           bin = 0;
177           if (ISSTATE (myself, PID_USETTY))
178             name = "/dev/tty";
179           else
180             name = "/dev/conin";
181         }
182     }
183
184   build_fhandler (fd, name, handle)->init (handle, myaccess, bin);
185   set_std_handle (fd);
186   paranoid_printf ("fd %d, handle %p", fd, handle);
187 }
188
189 extern "C"
190 int
191 cygwin_attach_handle_to_fd (char *name, int fd, HANDLE handle, mode_t bin,
192                               DWORD myaccess)
193 {
194   if (fd == -1)
195     fd = fdtab.find_unused_handle();
196   fhandler_base *res = fdtab.build_fhandler (fd, name, handle);
197   res->init (handle, myaccess, bin);
198   return fd;
199 }
200
201 fhandler_base *
202 dtable::build_fhandler (int fd, const char *name, HANDLE handle)
203 {
204   int unit;
205   DWORD devn;
206
207   if ((devn = get_device_number (name, unit)) == FH_BAD)
208     {
209       struct sockaddr sa;
210       int sal = sizeof (sa);
211       CONSOLE_SCREEN_BUFFER_INFO cinfo;
212       DCB dcb;
213
214       if (handle == NULL)
215         devn = FH_DISK;
216       else if (GetNumberOfConsoleInputEvents (handle, (DWORD *) &cinfo))
217         devn = FH_CONIN;
218       else if (GetConsoleScreenBufferInfo (handle, &cinfo))
219         devn= FH_CONOUT;
220       else if (wsock32_handle && getpeername ((SOCKET) handle, &sa, &sal))
221         devn = FH_SOCKET;
222       else if (GetFileType (handle) == FILE_TYPE_PIPE)
223         devn = FH_PIPE;
224       else if (GetCommState (handle, &dcb))
225         devn = FH_SERIAL;
226       else
227         devn = FH_DISK;
228     }
229
230   return build_fhandler (fd, devn, name, unit);
231 }
232
233 fhandler_base *
234 dtable::build_fhandler (int fd, DWORD dev, const char *name, int unit)
235 {
236   fhandler_base *fh;
237   void *buf = calloc (1, sizeof (fhandler_union) + 100);
238
239   dev &= FH_DEVMASK;
240   switch (dev)
241     {
242       case FH_TTYM:
243         fh = new (buf) fhandler_tty_master (name, unit);
244         break;
245       case FH_CONSOLE:
246       case FH_CONIN:
247       case FH_CONOUT:
248         fh = new (buf) fhandler_console (name);
249         break;
250       case FH_PTYM:
251         fh = new (buf) fhandler_pty_master (name);
252         break;
253       case FH_TTYS:
254         if (unit < 0)
255           fh = new (buf) fhandler_tty_slave (name);
256         else
257           fh = new (buf) fhandler_tty_slave (unit, name);
258         break;
259       case FH_WINDOWS:
260         fh = new (buf) fhandler_windows (name);
261         break;
262       case FH_SERIAL:
263         fh = new (buf) fhandler_serial (name, dev, unit);
264         break;
265       case FH_PIPE:
266       case FH_PIPER:
267       case FH_PIPEW:
268         fh = new (buf) fhandler_pipe (name, dev);
269         break;
270       case FH_SOCKET:
271         fh = new (buf) fhandler_socket (name);
272         break;
273       case FH_DISK:
274         fh = new (buf) fhandler_disk_file (NULL);
275         break;
276       case FH_FLOPPY:
277         fh = new (buf) fhandler_dev_floppy (name, unit);
278         break;
279       case FH_TAPE:
280         fh = new (buf) fhandler_dev_tape (name, unit);
281         break;
282       case FH_NULL:
283         fh = new (buf) fhandler_dev_null (name);
284         break;
285       case FH_ZERO:
286         fh = new (buf) fhandler_dev_zero (name);
287         break;
288       case FH_RANDOM:
289         fh = new (buf) fhandler_dev_random (name, unit);
290         break;
291       default:
292         /* FIXME - this could recurse forever */
293         return build_fhandler (fd, name, NULL);
294     }
295
296   debug_printf ("%s - cb %d, fd %d, fh %p", fh->get_name () ?: "", fh->cb,
297                 fd, fh);
298   return fd >= 0 ? (fds[fd] = fh) : fh;
299 }
300
301 fhandler_base *
302 dtable::dup_worker (fhandler_base *oldfh)
303 {
304   fhandler_base *newfh = build_fhandler (-1, oldfh->get_device (), NULL);
305   *newfh = *oldfh;
306   newfh->set_io_handle (NULL);
307   if (oldfh->dup (newfh))
308     {
309       free (newfh);
310       newfh = NULL;
311       return NULL;
312     }
313
314   newfh->set_close_on_exec_flag (0);
315   MALLOC_CHECK;
316   return newfh;
317 }
318
319 int
320 dtable::dup2 (int oldfd, int newfd)
321 {
322   int res = -1;
323   fhandler_base *newfh = NULL;  // = NULL to avoid an incorrect warning
324
325   MALLOC_CHECK;
326   debug_printf ("dup2 (%d, %d)", oldfd, newfd);
327
328   if (not_open (oldfd))
329     {
330       syscall_printf ("fd %d not open", oldfd);
331       set_errno (EBADF);
332       goto done;
333     }
334
335   if (newfd == oldfd)
336     {
337       res = 0;
338       goto done;
339     }
340
341   if ((newfh = dup_worker (fds[oldfd])) == NULL)
342     {
343       res = -1;
344       goto done;
345     }
346
347   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
348   if ((size_t) newfd >= fdtab.size || newfd < 0)
349     {
350       syscall_printf ("new fd out of bounds: %d", newfd);
351       set_errno (EBADF);
352       goto done;
353     }
354   if (!not_open (newfd))
355     _close (newfd);
356   fds[newfd] = newfh;
357   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
358   MALLOC_CHECK;
359
360   if ((res = newfd) <= 2)
361     set_std_handle (res);
362
363   MALLOC_CHECK;
364 done:
365   syscall_printf ("%d = dup2 (%d, %d)", res, oldfd, newfd);
366
367   return res;
368 }
369
370 select_record *
371 dtable::select_read (int fd, select_record *s)
372 {
373   if (fdtab.not_open (fd))
374     {
375       set_errno (EBADF);
376       return NULL;
377     }
378   fhandler_base *fh = fdtab[fd];
379   s = fh->select_read (s);
380   s->fd = fd;
381   s->fh = fh;
382   s->saw_error = 0;
383   debug_printf ("%s fd %d", fh->get_name (), fd);
384   return s;
385 }
386
387 select_record *
388 dtable::select_write (int fd, select_record *s)
389 {
390   if (fdtab.not_open (fd))
391     {
392       set_errno (EBADF);
393       return NULL;
394     }
395   fhandler_base *fh = fdtab[fd];
396   s = fh->select_write (s);
397   s->fd = fd;
398   s->fh = fh;
399   s->saw_error = 0;
400   debug_printf ("%s fd %d", fh->get_name (), fd);
401   return s;
402 }
403
404 select_record *
405 dtable::select_except (int fd, select_record *s)
406 {
407   if (fdtab.not_open (fd))
408     {
409       set_errno (EBADF);
410       return NULL;
411     }
412   fhandler_base *fh = fdtab[fd];
413   s = fh->select_except (s);
414   s->fd = fd;
415   s->fh = fh;
416   s->saw_error = 0;
417   debug_printf ("%s fd %d", fh->get_name (), fd);
418   return s;
419 }
420
421 /*
422  * Function to take an existant dtable array
423  * and linearize it into a memory buffer.
424  * If memory buffer is NULL, it returns the size
425  * of memory buffer needed to do the linearization.
426  * On error returns -1.
427  */
428
429 int
430 dtable::linearize_fd_array (unsigned char *in_buf, int buflen)
431 {
432   /* If buf == NULL, just precalculate length */
433   if (in_buf == NULL)
434     {
435       buflen = sizeof (size_t);
436       for (int i = 0, max_used_fd = -1; i < (int)size; i++)
437         if (!not_open (i) && !fds[i]->get_close_on_exec ())
438           {
439             buflen += i - (max_used_fd + 1);
440             buflen += fds[i]->cb + strlen (fds[i]->get_name ()) + 1
441                                  + strlen (fds[i]->get_win32_name ()) + 1;
442             max_used_fd = i;
443           }
444       debug_printf ("needed buflen %d", buflen);
445       return buflen;
446     }
447
448   debug_printf ("in_buf = %x, buflen = %d", in_buf, buflen);
449
450   /*
451    * Now linearize each open fd (write a 0xff byte for a closed fd).
452    * Write the name of the open fd first (null terminated). This
453    * allows the de_linearizeing code to determine what kind of fhandler_xxx
454    * to create.
455    */
456
457   size_t i;
458   int len, total_size;
459
460   total_size = sizeof (size_t);
461   if (total_size > buflen)
462     {
463       system_printf ("FATAL: linearize_fd_array exceeded buffer size");
464       return -1;
465     }
466
467   unsigned char *buf = in_buf;
468   buf += sizeof (size_t);       /* skip over length which is added later */
469
470   for (i = 0, total_size = sizeof (size_t); total_size < buflen; i++)
471     {
472       if (not_open (i) || fds[i]->get_close_on_exec ())
473         {
474           debug_printf ("linearizing closed fd %d",i);
475           *buf = 0xff;          /* place holder */
476           len = 1;
477         }
478       else
479         {
480           len = fds[i]->linearize (buf);
481           debug_printf ("fd %d, len %d, name %s, device %p", i, len, buf,
482                         fds[i]->get_device ());
483         }
484
485       total_size += len;
486       buf += len;
487     }
488
489   i--;
490   memcpy (in_buf, &i, sizeof (size_t));
491   if (total_size != buflen)
492     system_printf ("out of sync %d != %d", total_size, buflen);
493   return total_size;
494 }
495
496 /*
497  * Function to take a linearized dtable array in a memory buffer and
498  * re-create the original dtable array.
499  */
500
501 LPBYTE
502 dtable::de_linearize_fd_array (LPBYTE buf)
503 {
504   int len, max_used_fd;
505   size_t inc_size;
506
507   debug_printf ("buf %x", buf);
508
509   /* First get the number of fd's - use this to set the fdtabsize.
510      NB. This is the only place in the code this should be done !!
511   */
512
513   memcpy ((char *) &max_used_fd, buf, sizeof (int));
514   buf += sizeof (size_t);
515
516   inc_size = NOFILE_INCR * ((max_used_fd + NOFILE_INCR - 1) / NOFILE_INCR) -
517              size;
518   debug_printf ("max_used_fd %d, inc size %d", max_used_fd, inc_size);
519   if (inc_size > 0 && !extend (inc_size))
520     {
521       system_printf ("out of memory");
522       return NULL;
523     }
524
525   for (int i = 0; i <= max_used_fd; i++)
526     {
527       /* 0xFF means closed */
528       if (*buf == 0xff)
529         {
530           fds[i] = NULL;
531           buf++;
532           debug_printf ("closed fd %d", i);
533           continue;
534         }
535       /* fd was open - de_linearize it */
536       /* Get the null-terminated name.  It is followed by an image of
537          the actual fhandler_* structure.  Use the status field from
538          this to build a new fhandler type. */
539
540       DWORD status;
541       LPBYTE obuf = buf;
542       char *win32;
543       win32 = strchr ((char *)obuf, '\0') + 1;
544       buf = (LPBYTE)strchr ((char *)win32, '\0') + 1;
545       memcpy ((char *)&status, buf + FHSTATOFF, sizeof(DWORD));
546       debug_printf ("fd %d, name %s, win32 name %s, status %p",
547                     i, obuf, win32, status);
548       len = build_fhandler (i, status, (const char *) NULL)->
549             de_linearize ((char *) buf, (char *) obuf, win32);
550       set_std_handle (i);
551       buf += len;
552       debug_printf ("len %d", buf - obuf);
553     }
554   first_fd_for_open = 0;
555   return buf;
556 }
557
558 void
559 dtable::fixup_after_fork (HANDLE parent)
560 {
561   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
562   for (size_t i = 0; i < size; i++)
563     if (!not_open (i))
564       {
565         fhandler_base *fh = fds[i];
566         if (fh->get_close_on_exec () || fh->get_need_fork_fixup ())
567           {
568             debug_printf ("fd %d(%s)", i, fh->get_name ());
569             fh->fixup_after_fork (parent);
570           }
571       }
572   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
573 }
574
575 int
576 dtable::vfork_child_dup ()
577 {
578   fhandler_base **newtable;
579   newtable = (fhandler_base **) calloc (size, sizeof(fds[0]));
580   int res = 1;
581
582   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
583   for (size_t i = 0; i < size; i++)
584     if (not_open (i))
585       continue;
586     else if ((newtable[i] = dup_worker (fds[i])) == NULL)
587       {
588         res = 0;
589         set_errno (EBADF);
590         goto out;
591       }
592   fds_on_hold = fds;
593   fds = newtable;
594 out:
595   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
596   return 1;
597 }
598
599 void
600 dtable::vfork_parent_restore ()
601 {
602   SetResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
603
604   close_all_files ();
605   fhandler_base **deleteme = fds;
606   fds = fds_on_hold;
607   fds_on_hold = NULL;
608   free (deleteme);
609
610   ReleaseResourceLock(LOCK_FD_LIST,WRITE_LOCK|READ_LOCK,"dup");
611   return;
612 }