OSDN Git Service

2009-11-30 Kai Tietz <Kai.Tietz@onevision.com>
[pf3gnuchains/gcc-fork.git] / libgfortran / io / unix.c
1 /* Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
2    Free Software Foundation, Inc.
3    Contributed by Andy Vaught
4    F2003 I/O support contributed by Jerry DeLisle
5
6 This file is part of the GNU Fortran 95 runtime library (libgfortran).
7
8 Libgfortran is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 Libgfortran is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 Under Section 7 of GPL version 3, you are granted additional
19 permissions described in the GCC Runtime Library Exception, version
20 3.1, as published by the Free Software Foundation.
21
22 You should have received a copy of the GNU General Public License and
23 a copy of the GCC Runtime Library Exception along with this program;
24 see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
25 <http://www.gnu.org/licenses/>.  */
26
27 /* Unix stream I/O module */
28
29 #include "io.h"
30 #include "unix.h"
31 #include <stdlib.h>
32 #include <limits.h>
33
34 #include <unistd.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <assert.h>
38
39 #include <string.h>
40 #include <errno.h>
41
42
43 /* For mingw, we don't identify files by their inode number, but by a
44    64-bit identifier created from a BY_HANDLE_FILE_INFORMATION. */
45 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
46
47 #define WIN32_LEAN_AND_MEAN
48 #include <windows.h>
49
50 static uint64_t
51 id_from_handle (HANDLE hFile)
52 {
53   BY_HANDLE_FILE_INFORMATION FileInformation;
54
55   if (hFile == INVALID_HANDLE_VALUE)
56       return 0;
57
58   memset (&FileInformation, 0, sizeof(FileInformation));
59   if (!GetFileInformationByHandle (hFile, &FileInformation))
60     return 0;
61
62   return ((uint64_t) FileInformation.nFileIndexLow)
63          | (((uint64_t) FileInformation.nFileIndexHigh) << 32);
64 }
65
66
67 static uint64_t
68 id_from_path (const char *path)
69 {
70   HANDLE hFile;
71   uint64_t res;
72
73   if (!path || !*path || access (path, F_OK))
74     return (uint64_t) -1;
75
76   hFile = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
77                       FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_READONLY,
78                       NULL);
79   res = id_from_handle (hFile);
80   CloseHandle (hFile);
81   return res;
82 }
83
84
85 static uint64_t
86 id_from_fd (const int fd)
87 {
88   return id_from_handle ((HANDLE) _get_osfhandle (fd));
89 }
90
91 #endif
92
93 #ifndef PATH_MAX
94 #define PATH_MAX 1024
95 #endif
96
97 #ifndef PROT_READ
98 #define PROT_READ 1
99 #endif
100
101 #ifndef PROT_WRITE
102 #define PROT_WRITE 2
103 #endif
104
105 /* These flags aren't defined on all targets (mingw32), so provide them
106    here.  */
107 #ifndef S_IRGRP
108 #define S_IRGRP 0
109 #endif
110
111 #ifndef S_IWGRP
112 #define S_IWGRP 0
113 #endif
114
115 #ifndef S_IROTH
116 #define S_IROTH 0
117 #endif
118
119 #ifndef S_IWOTH
120 #define S_IWOTH 0
121 #endif
122
123
124 /* Unix and internal stream I/O module */
125
126 static const int BUFFER_SIZE = 8192;
127
128 typedef struct
129 {
130   stream st;
131
132   gfc_offset buffer_offset;     /* File offset of the start of the buffer */
133   gfc_offset physical_offset;   /* Current physical file offset */
134   gfc_offset logical_offset;    /* Current logical file offset */
135   gfc_offset file_length;       /* Length of the file, -1 if not seekable. */
136
137   char *buffer;                 /* Pointer to the buffer.  */
138   int fd;                       /* The POSIX file descriptor.  */
139
140   int active;                   /* Length of valid bytes in the buffer */
141
142   int prot;
143   int ndirty;                   /* Dirty bytes starting at buffer_offset */
144
145   int special_file;             /* =1 if the fd refers to a special file */
146 }
147 unix_stream;
148
149
150 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
151  * standard descriptors, returning a non-standard descriptor.  If the
152  * user specifies that system errors should go to standard output,
153  * then closes standard output, we don't want the system errors to a
154  * file that has been given file descriptor 1 or 0.  We want to send
155  * the error to the invalid descriptor. */
156
157 static int
158 fix_fd (int fd)
159 {
160 #ifdef HAVE_DUP
161   int input, output, error;
162
163   input = output = error = 0;
164
165   /* Unix allocates the lowest descriptors first, so a loop is not
166      required, but this order is. */
167   if (fd == STDIN_FILENO)
168     {
169       fd = dup (fd);
170       input = 1;
171     }
172   if (fd == STDOUT_FILENO)
173     {
174       fd = dup (fd);
175       output = 1;
176     }
177   if (fd == STDERR_FILENO)
178     {
179       fd = dup (fd);
180       error = 1;
181     }
182
183   if (input)
184     close (STDIN_FILENO);
185   if (output)
186     close (STDOUT_FILENO);
187   if (error)
188     close (STDERR_FILENO);
189 #endif
190
191   return fd;
192 }
193
194
195 /* If the stream corresponds to a preconnected unit, we flush the
196    corresponding C stream.  This is bugware for mixed C-Fortran codes
197    where the C code doesn't flush I/O before returning.  */
198 void
199 flush_if_preconnected (stream * s)
200 {
201   int fd;
202
203   fd = ((unix_stream *) s)->fd;
204   if (fd == STDIN_FILENO)
205     fflush (stdin);
206   else if (fd == STDOUT_FILENO)
207     fflush (stdout);
208   else if (fd == STDERR_FILENO)
209     fflush (stderr);
210 }
211
212
213 /* get_oserror()-- Get the most recent operating system error.  For
214  * unix, this is errno. */
215
216 const char *
217 get_oserror (void)
218 {
219   return strerror (errno);
220 }
221
222
223 /********************************************************************
224 Raw I/O functions (read, write, seek, tell, truncate, close).
225
226 These functions wrap the basic POSIX I/O syscalls. Any deviation in
227 semantics is a bug, except the following: write restarts in case
228 of being interrupted by a signal, and as the first argument the
229 functions take the unix_stream struct rather than an integer file
230 descriptor. Also, for POSIX read() and write() a nbyte argument larger
231 than SSIZE_MAX is undefined; here the type of nbyte is ssize_t rather
232 than size_t as for POSIX read/write.
233 *********************************************************************/
234
235 static int
236 raw_flush (unix_stream * s  __attribute__ ((unused)))
237 {
238   return 0;
239 }
240
241 static ssize_t
242 raw_read (unix_stream * s, void * buf, ssize_t nbyte)
243 {
244   /* For read we can't do I/O in a loop like raw_write does, because
245      that will break applications that wait for interactive I/O.  */
246   return read (s->fd, buf, nbyte);
247 }
248
249 static ssize_t
250 raw_write (unix_stream * s, const void * buf, ssize_t nbyte)
251 {
252   ssize_t trans, bytes_left;
253   char *buf_st;
254
255   bytes_left = nbyte;
256   buf_st = (char *) buf;
257
258   /* We must write in a loop since some systems don't restart system
259      calls in case of a signal.  */
260   while (bytes_left > 0)
261     {
262       trans = write (s->fd, buf_st, bytes_left);
263       if (trans < 0)
264         {
265           if (errno == EINTR)
266             continue;
267           else
268             return trans;
269         }
270       buf_st += trans;
271       bytes_left -= trans;
272     }
273
274   return nbyte - bytes_left;
275 }
276
277 static off_t
278 raw_seek (unix_stream * s, off_t offset, int whence)
279 {
280   return lseek (s->fd, offset, whence);
281 }
282
283 static off_t
284 raw_tell (unix_stream * s)
285 {
286   return lseek (s->fd, 0, SEEK_CUR);
287 }
288
289 static int
290 raw_truncate (unix_stream * s, off_t length)
291 {
292 #ifdef HAVE_FTRUNCATE
293   return ftruncate (s->fd, length);
294 #elif defined HAVE_CHSIZE
295   return chsize (s->fd, length);
296 #else
297   runtime_error ("required ftruncate or chsize support not present");
298   return -1;
299 #endif
300 }
301
302 static int
303 raw_close (unix_stream * s)
304 {
305   int retval;
306   
307   if (s->fd != STDOUT_FILENO
308       && s->fd != STDERR_FILENO
309       && s->fd != STDIN_FILENO)
310     retval = close (s->fd);
311   else
312     retval = 0;
313   free_mem (s);
314   return retval;
315 }
316
317 static int
318 raw_init (unix_stream * s)
319 {
320   s->st.read = (void *) raw_read;
321   s->st.write = (void *) raw_write;
322   s->st.seek = (void *) raw_seek;
323   s->st.tell = (void *) raw_tell;
324   s->st.trunc = (void *) raw_truncate;
325   s->st.close = (void *) raw_close;
326   s->st.flush = (void *) raw_flush;
327
328   s->buffer = NULL;
329   return 0;
330 }
331
332
333 /*********************************************************************
334 Buffered I/O functions. These functions have the same semantics as the
335 raw I/O functions above, except that they are buffered in order to
336 improve performance. The buffer must be flushed when switching from
337 reading to writing and vice versa.
338 *********************************************************************/
339
340 static int
341 buf_flush (unix_stream * s)
342 {
343   int writelen;
344
345   /* Flushing in read mode means discarding read bytes.  */
346   s->active = 0;
347
348   if (s->ndirty == 0)
349     return 0;
350   
351   if (s->file_length != -1 && s->physical_offset != s->buffer_offset
352       && lseek (s->fd, s->buffer_offset, SEEK_SET) < 0)
353     return -1;
354
355   writelen = raw_write (s, s->buffer, s->ndirty);
356
357   s->physical_offset = s->buffer_offset + writelen;
358
359   /* Don't increment file_length if the file is non-seekable.  */
360   if (s->file_length != -1 && s->physical_offset > s->file_length)
361       s->file_length = s->physical_offset;
362
363   s->ndirty -= writelen;
364   if (s->ndirty != 0)
365     return -1;
366
367   return 0;
368 }
369
370 static ssize_t
371 buf_read (unix_stream * s, void * buf, ssize_t nbyte)
372 {
373   if (s->active == 0)
374     s->buffer_offset = s->logical_offset;
375
376   /* Is the data we want in the buffer?  */
377   if (s->logical_offset + nbyte <= s->buffer_offset + s->active
378       && s->buffer_offset <= s->logical_offset)
379     memcpy (buf, s->buffer + (s->logical_offset - s->buffer_offset), nbyte);
380   else
381     {
382       /* First copy the active bytes if applicable, then read the rest
383          either directly or filling the buffer.  */
384       char *p;
385       int nread = 0;
386       ssize_t to_read, did_read;
387       gfc_offset new_logical;
388       
389       p = (char *) buf;
390       if (s->logical_offset >= s->buffer_offset 
391           && s->buffer_offset + s->active >= s->logical_offset)
392         {
393           nread = s->active - (s->logical_offset - s->buffer_offset);
394           memcpy (buf, s->buffer + (s->logical_offset - s->buffer_offset), 
395                   nread);
396           p += nread;
397         }
398       /* At this point we consider all bytes in the buffer discarded.  */
399       to_read = nbyte - nread;
400       new_logical = s->logical_offset + nread;
401       if (s->file_length != -1 && s->physical_offset != new_logical
402           && lseek (s->fd, new_logical, SEEK_SET) < 0)
403         return -1;
404       s->buffer_offset = s->physical_offset = new_logical;
405       if (to_read <= BUFFER_SIZE/2)
406         {
407           did_read = raw_read (s, s->buffer, BUFFER_SIZE);
408           s->physical_offset += did_read;
409           s->active = did_read;
410           did_read = (did_read > to_read) ? to_read : did_read;
411           memcpy (p, s->buffer, did_read);
412         }
413       else
414         {
415           did_read = raw_read (s, p, to_read);
416           s->physical_offset += did_read;
417           s->active = 0;
418         }
419       nbyte = did_read + nread;
420     }
421   s->logical_offset += nbyte;
422   return nbyte;
423 }
424
425 static ssize_t
426 buf_write (unix_stream * s, const void * buf, ssize_t nbyte)
427 {
428   if (s->ndirty == 0)
429     s->buffer_offset = s->logical_offset;
430
431   /* Does the data fit into the buffer?  As a special case, if the
432      buffer is empty and the request is bigger than BUFFER_SIZE/2,
433      write directly. This avoids the case where the buffer would have
434      to be flushed at every write.  */
435   if (!(s->ndirty == 0 && nbyte > BUFFER_SIZE/2)
436       && s->logical_offset + nbyte <= s->buffer_offset + BUFFER_SIZE
437       && s->buffer_offset <= s->logical_offset
438       && s->buffer_offset + s->ndirty >= s->logical_offset)
439     {
440       memcpy (s->buffer + (s->logical_offset - s->buffer_offset), buf, nbyte);
441       int nd = (s->logical_offset - s->buffer_offset) + nbyte;
442       if (nd > s->ndirty)
443         s->ndirty = nd;
444     }
445   else
446     {
447       /* Flush, and either fill the buffer with the new data, or if
448          the request is bigger than the buffer size, write directly
449          bypassing the buffer.  */
450       buf_flush (s);
451       if (nbyte <= BUFFER_SIZE/2)
452         {
453           memcpy (s->buffer, buf, nbyte);
454           s->buffer_offset = s->logical_offset;
455           s->ndirty += nbyte;
456         }
457       else
458         {
459           if (s->file_length != -1 && s->physical_offset != s->logical_offset
460               && lseek (s->fd, s->logical_offset, SEEK_SET) < 0)
461             return -1;
462           nbyte = raw_write (s, buf, nbyte);
463           s->physical_offset += nbyte;
464         }
465     }
466   s->logical_offset += nbyte;
467   /* Don't increment file_length if the file is non-seekable.  */
468   if (s->file_length != -1 && s->logical_offset > s->file_length)
469     s->file_length = s->logical_offset;
470   return nbyte;
471 }
472
473 static off_t
474 buf_seek (unix_stream * s, off_t offset, int whence)
475 {
476   switch (whence)
477     {
478     case SEEK_SET:
479       break;
480     case SEEK_CUR:
481       offset += s->logical_offset;
482       break;
483     case SEEK_END:
484       offset += s->file_length;
485       break;
486     default:
487       return -1;
488     }
489   if (offset < 0)
490     {
491       errno = EINVAL;
492       return -1;
493     }
494   s->logical_offset = offset;
495   return offset;
496 }
497
498 static off_t
499 buf_tell (unix_stream * s)
500 {
501   return s->logical_offset;
502 }
503
504 static int
505 buf_truncate (unix_stream * s, off_t length)
506 {
507   int r;
508
509   if (buf_flush (s) != 0)
510     return -1;
511   r = raw_truncate (s, length);
512   if (r == 0)
513     s->file_length = length;
514   return r;
515 }
516
517 static int
518 buf_close (unix_stream * s)
519 {
520   if (buf_flush (s) != 0)
521     return -1;
522   free_mem (s->buffer);
523   return raw_close (s);
524 }
525
526 static int
527 buf_init (unix_stream * s)
528 {
529   s->st.read = (void *) buf_read;
530   s->st.write = (void *) buf_write;
531   s->st.seek = (void *) buf_seek;
532   s->st.tell = (void *) buf_tell;
533   s->st.trunc = (void *) buf_truncate;
534   s->st.close = (void *) buf_close;
535   s->st.flush = (void *) buf_flush;
536
537   s->buffer = get_mem (BUFFER_SIZE);
538   return 0;
539 }
540
541
542 /*********************************************************************
543   memory stream functions - These are used for internal files
544
545   The idea here is that a single stream structure is created and all
546   requests must be satisfied from it.  The location and size of the
547   buffer is the character variable supplied to the READ or WRITE
548   statement.
549
550 *********************************************************************/
551
552
553 char *
554 mem_alloc_r (stream * strm, int * len)
555 {
556   unix_stream * s = (unix_stream *) strm;
557   gfc_offset n;
558   gfc_offset where = s->logical_offset;
559
560   if (where < s->buffer_offset || where > s->buffer_offset + s->active)
561     return NULL;
562
563   n = s->buffer_offset + s->active - where;
564   if (*len > n)
565     *len = n;
566
567   s->logical_offset = where + *len;
568
569   return s->buffer + (where - s->buffer_offset);
570 }
571
572
573 char *
574 mem_alloc_w (stream * strm, int * len)
575 {
576   unix_stream * s = (unix_stream *) strm;
577   gfc_offset m;
578   gfc_offset where = s->logical_offset;
579
580   m = where + *len;
581
582   if (where < s->buffer_offset)
583     return NULL;
584
585   if (m > s->file_length)
586     return NULL;
587
588   s->logical_offset = m;
589
590   return s->buffer + (where - s->buffer_offset);
591 }
592
593
594 /* Stream read function for internal units.  */
595
596 static ssize_t
597 mem_read (stream * s, void * buf, ssize_t nbytes)
598 {
599   void *p;
600   int nb = nbytes;
601
602   p = mem_alloc_r (s, &nb);
603   if (p)
604     {
605       memcpy (buf, p, nb);
606       return (ssize_t) nb;
607     }
608   else
609     return 0;
610 }
611
612
613 /* Stream write function for internal units. This is not actually used
614    at the moment, as all internal IO is formatted and the formatted IO
615    routines use mem_alloc_w_at.  */
616
617 static ssize_t
618 mem_write (stream * s, const void * buf, ssize_t nbytes)
619 {
620   void *p;
621   int nb = nbytes;
622
623   p = mem_alloc_w (s, &nb);
624   if (p)
625     {
626       memcpy (p, buf, nb);
627       return (ssize_t) nb;
628     }
629   else
630     return 0;
631 }
632
633
634 static off_t
635 mem_seek (stream * strm, off_t offset, int whence)
636 {
637   unix_stream * s = (unix_stream *) strm;
638   switch (whence)
639     {
640     case SEEK_SET:
641       break;
642     case SEEK_CUR:
643       offset += s->logical_offset;
644       break;
645     case SEEK_END:
646       offset += s->file_length;
647       break;
648     default:
649       return -1;
650     }
651
652   /* Note that for internal array I/O it's actually possible to have a
653      negative offset, so don't check for that.  */
654   if (offset > s->file_length)
655     {
656       errno = EINVAL;
657       return -1;
658     }
659
660   s->logical_offset = offset;
661
662   /* Returning < 0 is the error indicator for sseek(), so return 0 if
663      offset is negative.  Thus if the return value is 0, the caller
664      has to use stell() to get the real value of logical_offset.  */
665   if (offset >= 0)
666     return offset;
667   return 0;
668 }
669
670
671 static off_t
672 mem_tell (stream * s)
673 {
674   return ((unix_stream *)s)->logical_offset;
675 }
676
677
678 static int
679 mem_truncate (unix_stream * s __attribute__ ((unused)), 
680               off_t length __attribute__ ((unused)))
681 {
682   return 0;
683 }
684
685
686 static int
687 mem_flush (unix_stream * s __attribute__ ((unused)))
688 {
689   return 0;
690 }
691
692
693 static int
694 mem_close (unix_stream * s)
695 {
696   if (s != NULL)
697     free_mem (s);
698
699   return 0;
700 }
701
702
703 /*********************************************************************
704   Public functions -- A reimplementation of this module needs to
705   define functional equivalents of the following.
706 *********************************************************************/
707
708 /* empty_internal_buffer()-- Zero the buffer of Internal file */
709
710 void
711 empty_internal_buffer(stream *strm)
712 {
713   unix_stream * s = (unix_stream *) strm;
714   memset(s->buffer, ' ', s->file_length);
715 }
716
717 /* open_internal()-- Returns a stream structure from an internal file */
718
719 stream *
720 open_internal (char *base, int length, gfc_offset offset)
721 {
722   unix_stream *s;
723
724   s = get_mem (sizeof (unix_stream));
725   memset (s, '\0', sizeof (unix_stream));
726
727   s->buffer = base;
728   s->buffer_offset = offset;
729
730   s->logical_offset = 0;
731   s->active = s->file_length = length;
732
733   s->st.close = (void *) mem_close;
734   s->st.seek = (void *) mem_seek;
735   s->st.tell = (void *) mem_tell;
736   s->st.trunc = (void *) mem_truncate;
737   s->st.read = (void *) mem_read;
738   s->st.write = (void *) mem_write;
739   s->st.flush = (void *) mem_flush;
740
741   return (stream *) s;
742 }
743
744
745 /* fd_to_stream()-- Given an open file descriptor, build a stream
746  * around it. */
747
748 static stream *
749 fd_to_stream (int fd, int prot)
750 {
751   struct stat statbuf;
752   unix_stream *s;
753
754   s = get_mem (sizeof (unix_stream));
755   memset (s, '\0', sizeof (unix_stream));
756
757   s->fd = fd;
758   s->buffer_offset = 0;
759   s->physical_offset = 0;
760   s->logical_offset = 0;
761   s->prot = prot;
762
763   /* Get the current length of the file. */
764
765   fstat (fd, &statbuf);
766
767   if (lseek (fd, 0, SEEK_CUR) == (off_t) -1)
768     s->file_length = -1;
769   else
770     s->file_length = S_ISREG (statbuf.st_mode) ? statbuf.st_size : -1;
771
772   s->special_file = !S_ISREG (statbuf.st_mode);
773
774   if (isatty (s->fd) || options.all_unbuffered
775       ||(options.unbuffered_preconnected && 
776          (s->fd == STDIN_FILENO 
777           || s->fd == STDOUT_FILENO 
778           || s->fd == STDERR_FILENO)))
779     raw_init (s);
780   else
781     buf_init (s);
782
783   return (stream *) s;
784 }
785
786
787 /* Given the Fortran unit number, convert it to a C file descriptor.  */
788
789 int
790 unit_to_fd (int unit)
791 {
792   gfc_unit *us;
793   int fd;
794
795   us = find_unit (unit);
796   if (us == NULL)
797     return -1;
798
799   fd = ((unix_stream *) us->s)->fd;
800   unlock_unit (us);
801   return fd;
802 }
803
804
805 /* unpack_filename()-- Given a fortran string and a pointer to a
806  * buffer that is PATH_MAX characters, convert the fortran string to a
807  * C string in the buffer.  Returns nonzero if this is not possible.  */
808
809 int
810 unpack_filename (char *cstring, const char *fstring, int len)
811 {
812   len = fstrlen (fstring, len);
813   if (len >= PATH_MAX)
814     return 1;
815
816   memmove (cstring, fstring, len);
817   cstring[len] = '\0';
818
819   return 0;
820 }
821
822
823 /* tempfile()-- Generate a temporary filename for a scratch file and
824  * open it.  mkstemp() opens the file for reading and writing, but the
825  * library mode prevents anything that is not allowed.  The descriptor
826  * is returned, which is -1 on error.  The template is pointed to by 
827  * opp->file, which is copied into the unit structure
828  * and freed later. */
829
830 static int
831 tempfile (st_parameter_open *opp)
832 {
833   const char *tempdir;
834   char *template;
835   int fd;
836
837   tempdir = getenv ("GFORTRAN_TMPDIR");
838   if (tempdir == NULL)
839     tempdir = getenv ("TMP");
840   if (tempdir == NULL)
841     tempdir = getenv ("TEMP");
842   if (tempdir == NULL)
843     tempdir = DEFAULT_TEMPDIR;
844
845   template = get_mem (strlen (tempdir) + 20);
846
847   sprintf (template, "%s/gfortrantmpXXXXXX", tempdir);
848
849 #ifdef HAVE_MKSTEMP
850
851   fd = mkstemp (template);
852
853 #else /* HAVE_MKSTEMP */
854
855   if (mktemp (template))
856     do
857 #if defined(HAVE_CRLF) && defined(O_BINARY)
858       fd = open (template, O_RDWR | O_CREAT | O_EXCL | O_BINARY,
859                  S_IREAD | S_IWRITE);
860 #else
861       fd = open (template, O_RDWR | O_CREAT | O_EXCL, S_IREAD | S_IWRITE);
862 #endif
863     while (!(fd == -1 && errno == EEXIST) && mktemp (template));
864   else
865     fd = -1;
866
867 #endif /* HAVE_MKSTEMP */
868
869   if (fd < 0)
870     free_mem (template);
871   else
872     {
873       opp->file = template;
874       opp->file_len = strlen (template);        /* Don't include trailing nul */
875     }
876
877   return fd;
878 }
879
880
881 /* regular_file()-- Open a regular file.
882  * Change flags->action if it is ACTION_UNSPECIFIED on entry,
883  * unless an error occurs.
884  * Returns the descriptor, which is less than zero on error. */
885
886 static int
887 regular_file (st_parameter_open *opp, unit_flags *flags)
888 {
889   char path[PATH_MAX + 1];
890   int mode;
891   int rwflag;
892   int crflag;
893   int fd;
894
895   if (unpack_filename (path, opp->file, opp->file_len))
896     {
897       errno = ENOENT;           /* Fake an OS error */
898       return -1;
899     }
900
901 #ifdef __CYGWIN__
902   if (opp->file_len == 7)
903     {
904       if (strncmp (path, "CONOUT$", 7) == 0
905           || strncmp (path, "CONERR$", 7) == 0)
906         {
907           fd = open ("/dev/conout", O_WRONLY);
908           flags->action = ACTION_WRITE;
909           return fd;
910         }
911     }
912
913   if (opp->file_len == 6 && strncmp (path, "CONIN$", 6) == 0)
914     {
915       fd = open ("/dev/conin", O_RDONLY);
916       flags->action = ACTION_READ;
917       return fd;
918     }
919 #endif
920
921
922 #ifdef __MINGW32__
923   if (opp->file_len == 7)
924     {
925       if (strncmp (path, "CONOUT$", 7) == 0
926           || strncmp (path, "CONERR$", 7) == 0)
927         {
928           fd = open ("CONOUT$", O_WRONLY);
929           flags->action = ACTION_WRITE;
930           return fd;
931         }
932     }
933
934   if (opp->file_len == 6 && strncmp (path, "CONIN$", 6) == 0)
935     {
936       fd = open ("CONIN$", O_RDONLY);
937       flags->action = ACTION_READ;
938       return fd;
939     }
940 #endif
941
942   rwflag = 0;
943
944   switch (flags->action)
945     {
946     case ACTION_READ:
947       rwflag = O_RDONLY;
948       break;
949
950     case ACTION_WRITE:
951       rwflag = O_WRONLY;
952       break;
953
954     case ACTION_READWRITE:
955     case ACTION_UNSPECIFIED:
956       rwflag = O_RDWR;
957       break;
958
959     default:
960       internal_error (&opp->common, "regular_file(): Bad action");
961     }
962
963   switch (flags->status)
964     {
965     case STATUS_NEW:
966       crflag = O_CREAT | O_EXCL;
967       break;
968
969     case STATUS_OLD:            /* open will fail if the file does not exist*/
970       crflag = 0;
971       break;
972
973     case STATUS_UNKNOWN:
974     case STATUS_SCRATCH:
975       crflag = O_CREAT;
976       break;
977
978     case STATUS_REPLACE:
979       crflag = O_CREAT | O_TRUNC;
980       break;
981
982     default:
983       internal_error (&opp->common, "regular_file(): Bad status");
984     }
985
986   /* rwflag |= O_LARGEFILE; */
987
988 #if defined(HAVE_CRLF) && defined(O_BINARY)
989   crflag |= O_BINARY;
990 #endif
991
992   mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
993   fd = open (path, rwflag | crflag, mode);
994   if (flags->action != ACTION_UNSPECIFIED)
995     return fd;
996
997   if (fd >= 0)
998     {
999       flags->action = ACTION_READWRITE;
1000       return fd;
1001     }
1002   if (errno != EACCES && errno != EROFS)
1003      return fd;
1004
1005   /* retry for read-only access */
1006   rwflag = O_RDONLY;
1007   fd = open (path, rwflag | crflag, mode);
1008   if (fd >=0)
1009     {
1010       flags->action = ACTION_READ;
1011       return fd;                /* success */
1012     }
1013   
1014   if (errno != EACCES)
1015     return fd;                  /* failure */
1016
1017   /* retry for write-only access */
1018   rwflag = O_WRONLY;
1019   fd = open (path, rwflag | crflag, mode);
1020   if (fd >=0)
1021     {
1022       flags->action = ACTION_WRITE;
1023       return fd;                /* success */
1024     }
1025   return fd;                    /* failure */
1026 }
1027
1028
1029 /* open_external()-- Open an external file, unix specific version.
1030  * Change flags->action if it is ACTION_UNSPECIFIED on entry.
1031  * Returns NULL on operating system error. */
1032
1033 stream *
1034 open_external (st_parameter_open *opp, unit_flags *flags)
1035 {
1036   int fd, prot;
1037
1038   if (flags->status == STATUS_SCRATCH)
1039     {
1040       fd = tempfile (opp);
1041       if (flags->action == ACTION_UNSPECIFIED)
1042         flags->action = ACTION_READWRITE;
1043
1044 #if HAVE_UNLINK_OPEN_FILE
1045       /* We can unlink scratch files now and it will go away when closed. */
1046       if (fd >= 0)
1047         unlink (opp->file);
1048 #endif
1049     }
1050   else
1051     {
1052       /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1053        * if it succeeds */
1054       fd = regular_file (opp, flags);
1055     }
1056
1057   if (fd < 0)
1058     return NULL;
1059   fd = fix_fd (fd);
1060
1061   switch (flags->action)
1062     {
1063     case ACTION_READ:
1064       prot = PROT_READ;
1065       break;
1066
1067     case ACTION_WRITE:
1068       prot = PROT_WRITE;
1069       break;
1070
1071     case ACTION_READWRITE:
1072       prot = PROT_READ | PROT_WRITE;
1073       break;
1074
1075     default:
1076       internal_error (&opp->common, "open_external(): Bad action");
1077     }
1078
1079   return fd_to_stream (fd, prot);
1080 }
1081
1082
1083 /* input_stream()-- Return a stream pointer to the default input stream.
1084  * Called on initialization. */
1085
1086 stream *
1087 input_stream (void)
1088 {
1089   return fd_to_stream (STDIN_FILENO, PROT_READ);
1090 }
1091
1092
1093 /* output_stream()-- Return a stream pointer to the default output stream.
1094  * Called on initialization. */
1095
1096 stream *
1097 output_stream (void)
1098 {
1099   stream * s;
1100
1101 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1102   setmode (STDOUT_FILENO, O_BINARY);
1103 #endif
1104
1105   s = fd_to_stream (STDOUT_FILENO, PROT_WRITE);
1106   return s;
1107 }
1108
1109
1110 /* error_stream()-- Return a stream pointer to the default error stream.
1111  * Called on initialization. */
1112
1113 stream *
1114 error_stream (void)
1115 {
1116   stream * s;
1117
1118 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1119   setmode (STDERR_FILENO, O_BINARY);
1120 #endif
1121
1122   s = fd_to_stream (STDERR_FILENO, PROT_WRITE);
1123   return s;
1124 }
1125
1126
1127 /* st_vprintf()-- vprintf function for error output.  To avoid buffer
1128    overruns, we limit the length of the buffer to ST_VPRINTF_SIZE.  2k
1129    is big enough to completely fill a 80x25 terminal, so it shuld be
1130    OK.  We use a direct write() because it is simpler and least likely
1131    to be clobbered by memory corruption.  Writing an error message
1132    longer than that is an error.  */
1133
1134 #define ST_VPRINTF_SIZE 2048
1135
1136 int
1137 st_vprintf (const char *format, va_list ap)
1138 {
1139   static char buffer[ST_VPRINTF_SIZE];
1140   int written;
1141   int fd;
1142
1143   fd = options.use_stderr ? STDERR_FILENO : STDOUT_FILENO;
1144 #ifdef HAVE_VSNPRINTF
1145   written = vsnprintf(buffer, ST_VPRINTF_SIZE, format, ap);
1146 #else
1147   written = vsprintf(buffer, format, ap);
1148
1149   if (written >= ST_VPRINTF_SIZE-1)
1150     {
1151       /* The error message was longer than our buffer.  Ouch.  Because
1152          we may have messed up things badly, report the error and
1153          quit.  */
1154 #define ERROR_MESSAGE "Internal error: buffer overrun in st_vprintf()\n"
1155       write (fd, buffer, ST_VPRINTF_SIZE-1);
1156       write (fd, ERROR_MESSAGE, strlen(ERROR_MESSAGE));
1157       sys_exit(2);
1158 #undef ERROR_MESSAGE
1159
1160     }
1161 #endif
1162
1163   written = write (fd, buffer, written);
1164   return written;
1165 }
1166
1167 /* st_printf()-- printf() function for error output.  This just calls
1168    st_vprintf() to do the actual work.  */
1169
1170 int
1171 st_printf (const char *format, ...)
1172 {
1173   int written;
1174   va_list ap;
1175   va_start (ap, format);
1176   written = st_vprintf(format, ap);
1177   va_end (ap);
1178   return written;
1179 }
1180
1181
1182 /* compare_file_filename()-- Given an open stream and a fortran string
1183  * that is a filename, figure out if the file is the same as the
1184  * filename. */
1185
1186 int
1187 compare_file_filename (gfc_unit *u, const char *name, int len)
1188 {
1189   char path[PATH_MAX + 1];
1190   struct stat st1;
1191 #ifdef HAVE_WORKING_STAT
1192   struct stat st2;
1193 #else
1194 # ifdef __MINGW32__
1195   uint64_t id1, id2;
1196 # endif
1197 #endif
1198
1199   if (unpack_filename (path, name, len))
1200     return 0;                   /* Can't be the same */
1201
1202   /* If the filename doesn't exist, then there is no match with the
1203    * existing file. */
1204
1205   if (stat (path, &st1) < 0)
1206     return 0;
1207
1208 #ifdef HAVE_WORKING_STAT
1209   fstat (((unix_stream *) (u->s))->fd, &st2);
1210   return (st1.st_dev == st2.st_dev) && (st1.st_ino == st2.st_ino);
1211 #else
1212
1213 # ifdef __MINGW32__
1214   /* We try to match files by a unique ID.  On some filesystems (network
1215      fs and FAT), we can't generate this unique ID, and will simply compare
1216      filenames.  */
1217   id1 = id_from_path (path);
1218   id2 = id_from_fd (((unix_stream *) (u->s))->fd);
1219   if (id1 || id2)
1220     return (id1 == id2);
1221 # endif
1222
1223   if (len != u->file_len)
1224     return 0;
1225   return (memcmp(path, u->file, len) == 0);
1226 #endif
1227 }
1228
1229
1230 #ifdef HAVE_WORKING_STAT
1231 # define FIND_FILE0_DECL struct stat *st
1232 # define FIND_FILE0_ARGS st
1233 #else
1234 # define FIND_FILE0_DECL uint64_t id, const char *file, gfc_charlen_type file_len
1235 # define FIND_FILE0_ARGS id, file, file_len
1236 #endif
1237
1238 /* find_file0()-- Recursive work function for find_file() */
1239
1240 static gfc_unit *
1241 find_file0 (gfc_unit *u, FIND_FILE0_DECL)
1242 {
1243   gfc_unit *v;
1244 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1245   uint64_t id1;
1246 #endif
1247
1248   if (u == NULL)
1249     return NULL;
1250
1251 #ifdef HAVE_WORKING_STAT
1252   if (u->s != NULL
1253       && fstat (((unix_stream *) u->s)->fd, &st[1]) >= 0 &&
1254       st[0].st_dev == st[1].st_dev && st[0].st_ino == st[1].st_ino)
1255     return u;
1256 #else
1257 # ifdef __MINGW32__ 
1258   if (u->s && ((id1 = id_from_fd (((unix_stream *) u->s)->fd)) || id1))
1259     {
1260       if (id == id1)
1261         return u;
1262     }
1263   else
1264 # endif
1265     if (compare_string (u->file_len, u->file, file_len, file) == 0)
1266       return u;
1267 #endif
1268
1269   v = find_file0 (u->left, FIND_FILE0_ARGS);
1270   if (v != NULL)
1271     return v;
1272
1273   v = find_file0 (u->right, FIND_FILE0_ARGS);
1274   if (v != NULL)
1275     return v;
1276
1277   return NULL;
1278 }
1279
1280
1281 /* find_file()-- Take the current filename and see if there is a unit
1282  * that has the file already open.  Returns a pointer to the unit if so. */
1283
1284 gfc_unit *
1285 find_file (const char *file, gfc_charlen_type file_len)
1286 {
1287   char path[PATH_MAX + 1];
1288   struct stat st[2];
1289   gfc_unit *u;
1290 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1291   uint64_t id = 0ULL;
1292 #endif
1293
1294   if (unpack_filename (path, file, file_len))
1295     return NULL;
1296
1297   if (stat (path, &st[0]) < 0)
1298     return NULL;
1299
1300 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1301   id = id_from_path (path);
1302 #endif
1303
1304   __gthread_mutex_lock (&unit_lock);
1305 retry:
1306   u = find_file0 (unit_root, FIND_FILE0_ARGS);
1307   if (u != NULL)
1308     {
1309       /* Fast path.  */
1310       if (! __gthread_mutex_trylock (&u->lock))
1311         {
1312           /* assert (u->closed == 0); */
1313           __gthread_mutex_unlock (&unit_lock);
1314           return u;
1315         }
1316
1317       inc_waiting_locked (u);
1318     }
1319   __gthread_mutex_unlock (&unit_lock);
1320   if (u != NULL)
1321     {
1322       __gthread_mutex_lock (&u->lock);
1323       if (u->closed)
1324         {
1325           __gthread_mutex_lock (&unit_lock);
1326           __gthread_mutex_unlock (&u->lock);
1327           if (predec_waiting_locked (u) == 0)
1328             free_mem (u);
1329           goto retry;
1330         }
1331
1332       dec_waiting_unlocked (u);
1333     }
1334   return u;
1335 }
1336
1337 static gfc_unit *
1338 flush_all_units_1 (gfc_unit *u, int min_unit)
1339 {
1340   while (u != NULL)
1341     {
1342       if (u->unit_number > min_unit)
1343         {
1344           gfc_unit *r = flush_all_units_1 (u->left, min_unit);
1345           if (r != NULL)
1346             return r;
1347         }
1348       if (u->unit_number >= min_unit)
1349         {
1350           if (__gthread_mutex_trylock (&u->lock))
1351             return u;
1352           if (u->s)
1353             sflush (u->s);
1354           __gthread_mutex_unlock (&u->lock);
1355         }
1356       u = u->right;
1357     }
1358   return NULL;
1359 }
1360
1361 void
1362 flush_all_units (void)
1363 {
1364   gfc_unit *u;
1365   int min_unit = 0;
1366
1367   __gthread_mutex_lock (&unit_lock);
1368   do
1369     {
1370       u = flush_all_units_1 (unit_root, min_unit);
1371       if (u != NULL)
1372         inc_waiting_locked (u);
1373       __gthread_mutex_unlock (&unit_lock);
1374       if (u == NULL)
1375         return;
1376
1377       __gthread_mutex_lock (&u->lock);
1378
1379       min_unit = u->unit_number + 1;
1380
1381       if (u->closed == 0)
1382         {
1383           sflush (u->s);
1384           __gthread_mutex_lock (&unit_lock);
1385           __gthread_mutex_unlock (&u->lock);
1386           (void) predec_waiting_locked (u);
1387         }
1388       else
1389         {
1390           __gthread_mutex_lock (&unit_lock);
1391           __gthread_mutex_unlock (&u->lock);
1392           if (predec_waiting_locked (u) == 0)
1393             free_mem (u);
1394         }
1395     }
1396   while (1);
1397 }
1398
1399
1400 /* delete_file()-- Given a unit structure, delete the file associated
1401  * with the unit.  Returns nonzero if something went wrong. */
1402
1403 int
1404 delete_file (gfc_unit * u)
1405 {
1406   char path[PATH_MAX + 1];
1407
1408   if (unpack_filename (path, u->file, u->file_len))
1409     {                           /* Shouldn't be possible */
1410       errno = ENOENT;
1411       return 1;
1412     }
1413
1414   return unlink (path);
1415 }
1416
1417
1418 /* file_exists()-- Returns nonzero if the current filename exists on
1419  * the system */
1420
1421 int
1422 file_exists (const char *file, gfc_charlen_type file_len)
1423 {
1424   char path[PATH_MAX + 1];
1425   struct stat statbuf;
1426
1427   if (unpack_filename (path, file, file_len))
1428     return 0;
1429
1430   if (stat (path, &statbuf) < 0)
1431     return 0;
1432
1433   return 1;
1434 }
1435
1436
1437
1438 static const char yes[] = "YES", no[] = "NO", unknown[] = "UNKNOWN";
1439
1440 /* inquire_sequential()-- Given a fortran string, determine if the
1441  * file is suitable for sequential access.  Returns a C-style
1442  * string. */
1443
1444 const char *
1445 inquire_sequential (const char *string, int len)
1446 {
1447   char path[PATH_MAX + 1];
1448   struct stat statbuf;
1449
1450   if (string == NULL ||
1451       unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1452     return unknown;
1453
1454   if (S_ISREG (statbuf.st_mode) ||
1455       S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1456     return unknown;
1457
1458   if (S_ISDIR (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1459     return no;
1460
1461   return unknown;
1462 }
1463
1464
1465 /* inquire_direct()-- Given a fortran string, determine if the file is
1466  * suitable for direct access.  Returns a C-style string. */
1467
1468 const char *
1469 inquire_direct (const char *string, int len)
1470 {
1471   char path[PATH_MAX + 1];
1472   struct stat statbuf;
1473
1474   if (string == NULL ||
1475       unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1476     return unknown;
1477
1478   if (S_ISREG (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1479     return unknown;
1480
1481   if (S_ISDIR (statbuf.st_mode) ||
1482       S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1483     return no;
1484
1485   return unknown;
1486 }
1487
1488
1489 /* inquire_formatted()-- Given a fortran string, determine if the file
1490  * is suitable for formatted form.  Returns a C-style string. */
1491
1492 const char *
1493 inquire_formatted (const char *string, int len)
1494 {
1495   char path[PATH_MAX + 1];
1496   struct stat statbuf;
1497
1498   if (string == NULL ||
1499       unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1500     return unknown;
1501
1502   if (S_ISREG (statbuf.st_mode) ||
1503       S_ISBLK (statbuf.st_mode) ||
1504       S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1505     return unknown;
1506
1507   if (S_ISDIR (statbuf.st_mode))
1508     return no;
1509
1510   return unknown;
1511 }
1512
1513
1514 /* inquire_unformatted()-- Given a fortran string, determine if the file
1515  * is suitable for unformatted form.  Returns a C-style string. */
1516
1517 const char *
1518 inquire_unformatted (const char *string, int len)
1519 {
1520   return inquire_formatted (string, len);
1521 }
1522
1523
1524 #ifndef HAVE_ACCESS
1525
1526 #ifndef W_OK
1527 #define W_OK 2
1528 #endif
1529
1530 #ifndef R_OK
1531 #define R_OK 4
1532 #endif
1533
1534 /* Fallback implementation of access() on systems that don't have it.
1535    Only modes R_OK and W_OK are used in this file.  */
1536
1537 static int
1538 fallback_access (const char *path, int mode)
1539 {
1540   if ((mode & R_OK) && open (path, O_RDONLY) < 0)
1541     return -1;
1542
1543   if ((mode & W_OK) && open (path, O_WRONLY) < 0)
1544     return -1;
1545
1546   return 0;
1547 }
1548
1549 #undef access
1550 #define access fallback_access
1551 #endif
1552
1553
1554 /* inquire_access()-- Given a fortran string, determine if the file is
1555  * suitable for access. */
1556
1557 static const char *
1558 inquire_access (const char *string, int len, int mode)
1559 {
1560   char path[PATH_MAX + 1];
1561
1562   if (string == NULL || unpack_filename (path, string, len) ||
1563       access (path, mode) < 0)
1564     return no;
1565
1566   return yes;
1567 }
1568
1569
1570 /* inquire_read()-- Given a fortran string, determine if the file is
1571  * suitable for READ access. */
1572
1573 const char *
1574 inquire_read (const char *string, int len)
1575 {
1576   return inquire_access (string, len, R_OK);
1577 }
1578
1579
1580 /* inquire_write()-- Given a fortran string, determine if the file is
1581  * suitable for READ access. */
1582
1583 const char *
1584 inquire_write (const char *string, int len)
1585 {
1586   return inquire_access (string, len, W_OK);
1587 }
1588
1589
1590 /* inquire_readwrite()-- Given a fortran string, determine if the file is
1591  * suitable for read and write access. */
1592
1593 const char *
1594 inquire_readwrite (const char *string, int len)
1595 {
1596   return inquire_access (string, len, R_OK | W_OK);
1597 }
1598
1599
1600 /* file_length()-- Return the file length in bytes, -1 if unknown */
1601
1602 gfc_offset
1603 file_length (stream * s)
1604 {
1605   off_t curr, end;
1606   if (!is_seekable (s))
1607     return -1;
1608   curr = stell (s);
1609   if (curr == -1)
1610     return curr;
1611   end = sseek (s, 0, SEEK_END);
1612   sseek (s, curr, SEEK_SET);
1613   return end;
1614 }
1615
1616
1617 /* is_seekable()-- Return nonzero if the stream is seekable, zero if
1618  * it is not */
1619
1620 int
1621 is_seekable (stream *s)
1622 {
1623   /* By convention, if file_length == -1, the file is not
1624      seekable.  */
1625   return ((unix_stream *) s)->file_length!=-1;
1626 }
1627
1628
1629 /* is_special()-- Return nonzero if the stream is not a regular file.  */
1630
1631 int
1632 is_special (stream *s)
1633 {
1634   return ((unix_stream *) s)->special_file;
1635 }
1636
1637
1638 int
1639 stream_isatty (stream *s)
1640 {
1641   return isatty (((unix_stream *) s)->fd);
1642 }
1643
1644 char *
1645 stream_ttyname (stream *s __attribute__ ((unused)))
1646 {
1647 #ifdef HAVE_TTYNAME
1648   return ttyname (((unix_stream *) s)->fd);
1649 #else
1650   return NULL;
1651 #endif
1652 }
1653
1654
1655 /* How files are stored:  This is an operating-system specific issue,
1656    and therefore belongs here.  There are three cases to consider.
1657
1658    Direct Access:
1659       Records are written as block of bytes corresponding to the record
1660       length of the file.  This goes for both formatted and unformatted
1661       records.  Positioning is done explicitly for each data transfer,
1662       so positioning is not much of an issue.
1663
1664    Sequential Formatted:
1665       Records are separated by newline characters.  The newline character
1666       is prohibited from appearing in a string.  If it does, this will be
1667       messed up on the next read.  End of file is also the end of a record.
1668
1669    Sequential Unformatted:
1670       In this case, we are merely copying bytes to and from main storage,
1671       yet we need to keep track of varying record lengths.  We adopt
1672       the solution used by f2c.  Each record contains a pair of length
1673       markers:
1674
1675         Length of record n in bytes
1676         Data of record n
1677         Length of record n in bytes
1678
1679         Length of record n+1 in bytes
1680         Data of record n+1
1681         Length of record n+1 in bytes
1682
1683      The length is stored at the end of a record to allow backspacing to the
1684      previous record.  Between data transfer statements, the file pointer
1685      is left pointing to the first length of the current record.
1686
1687      ENDFILE records are never explicitly stored.
1688
1689 */