OSDN Git Service

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