1 /* Copyright (C) 2002-2014 Free Software Foundation, Inc.
2 Contributed by Andy Vaught
3 F2003 I/O support contributed by Jerry DeLisle
5 This file is part of the GNU Fortran runtime library (libgfortran).
7 Libgfortran is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
12 Libgfortran is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 Under Section 7 of GPL version 3, you are granted additional
18 permissions described in the GCC Runtime Library Exception, version
19 3.1, as published by the Free Software Foundation.
21 You should have received a copy of the GNU General Public License and
22 a copy of the GCC Runtime Library Exception along with this program;
23 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
24 <http://www.gnu.org/licenses/>. */
26 /* Unix stream I/O module */
45 /* For mingw, we don't identify files by their inode number, but by a
46 64-bit identifier created from a BY_HANDLE_FILE_INFORMATION. */
49 #define WIN32_LEAN_AND_MEAN
52 #if !defined(_FILE_OFFSET_BITS) || _FILE_OFFSET_BITS != 64
54 #define lseek _lseeki64
56 #define fstat _fstati64
61 #ifndef HAVE_WORKING_STAT
63 id_from_handle (HANDLE hFile
)
65 BY_HANDLE_FILE_INFORMATION FileInformation
;
67 if (hFile
== INVALID_HANDLE_VALUE
)
70 memset (&FileInformation
, 0, sizeof(FileInformation
));
71 if (!GetFileInformationByHandle (hFile
, &FileInformation
))
74 return ((uint64_t) FileInformation
.nFileIndexLow
)
75 | (((uint64_t) FileInformation
.nFileIndexHigh
) << 32);
80 id_from_path (const char *path
)
85 if (!path
|| !*path
|| access (path
, F_OK
))
88 hFile
= CreateFile (path
, 0, 0, NULL
, OPEN_EXISTING
,
89 FILE_FLAG_BACKUP_SEMANTICS
| FILE_ATTRIBUTE_READONLY
,
91 res
= id_from_handle (hFile
);
98 id_from_fd (const int fd
)
100 return id_from_handle ((HANDLE
) _get_osfhandle (fd
));
103 #endif /* HAVE_WORKING_STAT */
104 #endif /* __MINGW32__ */
107 /* min macro that evaluates its arguments only once. */
113 ({ typeof (a) _a = (a); \
114 typeof (b) _b = (b); \
115 _a < _b ? _a : _b; })
118 #define PATH_MAX 1024
121 /* These flags aren't defined on all targets (mingw32), so provide them
154 /* Fallback implementation of access() on systems that don't have it.
155 Only modes R_OK, W_OK and F_OK are used in this file. */
158 fallback_access (const char *path
, int mode
)
162 if ((mode
& R_OK
) && (fd
= open (path
, O_RDONLY
)) < 0)
166 if ((mode
& W_OK
) && (fd
= open (path
, O_WRONLY
)) < 0)
173 return stat (path
, &st
);
180 #define access fallback_access
184 /* Fallback directory for creating temporary files. P_tmpdir is
185 defined on many POSIX platforms. */
188 #define P_tmpdir _P_tmpdir /* MinGW */
190 #define P_tmpdir "/tmp"
195 /* Unix and internal stream I/O module */
197 static const int BUFFER_SIZE
= 8192;
203 gfc_offset buffer_offset
; /* File offset of the start of the buffer */
204 gfc_offset physical_offset
; /* Current physical file offset */
205 gfc_offset logical_offset
; /* Current logical file offset */
206 gfc_offset file_length
; /* Length of the file. */
208 char *buffer
; /* Pointer to the buffer. */
209 int fd
; /* The POSIX file descriptor. */
211 int active
; /* Length of valid bytes in the buffer */
213 int ndirty
; /* Dirty bytes starting at buffer_offset */
215 /* Cached stat(2) values. */
219 bool unbuffered
; /* Buffer should be flushed after each I/O statement. */
224 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
225 * standard descriptors, returning a non-standard descriptor. If the
226 * user specifies that system errors should go to standard output,
227 * then closes standard output, we don't want the system errors to a
228 * file that has been given file descriptor 1 or 0. We want to send
229 * the error to the invalid descriptor. */
235 int input
, output
, error
;
237 input
= output
= error
= 0;
239 /* Unix allocates the lowest descriptors first, so a loop is not
240 required, but this order is. */
241 if (fd
== STDIN_FILENO
)
246 if (fd
== STDOUT_FILENO
)
251 if (fd
== STDERR_FILENO
)
258 close (STDIN_FILENO
);
260 close (STDOUT_FILENO
);
262 close (STDERR_FILENO
);
269 /* If the stream corresponds to a preconnected unit, we flush the
270 corresponding C stream. This is bugware for mixed C-Fortran codes
271 where the C code doesn't flush I/O before returning. */
273 flush_if_preconnected (stream
* s
)
277 fd
= ((unix_stream
*) s
)->fd
;
278 if (fd
== STDIN_FILENO
)
280 else if (fd
== STDOUT_FILENO
)
282 else if (fd
== STDERR_FILENO
)
287 /********************************************************************
288 Raw I/O functions (read, write, seek, tell, truncate, close).
290 These functions wrap the basic POSIX I/O syscalls. Any deviation in
291 semantics is a bug, except the following: write restarts in case
292 of being interrupted by a signal, and as the first argument the
293 functions take the unix_stream struct rather than an integer file
294 descriptor. Also, for POSIX read() and write() a nbyte argument larger
295 than SSIZE_MAX is undefined; here the type of nbyte is ssize_t rather
296 than size_t as for POSIX read/write.
297 *********************************************************************/
300 raw_flush (unix_stream
* s
__attribute__ ((unused
)))
306 raw_read (unix_stream
* s
, void * buf
, ssize_t nbyte
)
308 /* For read we can't do I/O in a loop like raw_write does, because
309 that will break applications that wait for interactive I/O. */
310 return read (s
->fd
, buf
, nbyte
);
314 raw_write (unix_stream
* s
, const void * buf
, ssize_t nbyte
)
316 ssize_t trans
, bytes_left
;
320 buf_st
= (char *) buf
;
322 /* We must write in a loop since some systems don't restart system
323 calls in case of a signal. */
324 while (bytes_left
> 0)
326 trans
= write (s
->fd
, buf_st
, bytes_left
);
338 return nbyte
- bytes_left
;
342 raw_seek (unix_stream
* s
, gfc_offset offset
, int whence
)
344 return lseek (s
->fd
, offset
, whence
);
348 raw_tell (unix_stream
* s
)
350 return lseek (s
->fd
, 0, SEEK_CUR
);
354 raw_size (unix_stream
* s
)
357 int ret
= fstat (s
->fd
, &statbuf
);
360 if (S_ISREG (statbuf
.st_mode
))
361 return statbuf
.st_size
;
367 raw_truncate (unix_stream
* s
, gfc_offset length
)
378 h
= (HANDLE
) _get_osfhandle (s
->fd
);
379 if (h
== INVALID_HANDLE_VALUE
)
384 cur
= lseek (s
->fd
, 0, SEEK_CUR
);
387 if (lseek (s
->fd
, length
, SEEK_SET
) == -1)
389 if (!SetEndOfFile (h
))
394 if (lseek (s
->fd
, cur
, SEEK_SET
) == -1)
398 lseek (s
->fd
, cur
, SEEK_SET
);
400 #elif defined HAVE_FTRUNCATE
401 return ftruncate (s
->fd
, length
);
402 #elif defined HAVE_CHSIZE
403 return chsize (s
->fd
, length
);
405 runtime_error ("required ftruncate or chsize support not present");
411 raw_close (unix_stream
* s
)
415 if (s
->fd
!= STDOUT_FILENO
416 && s
->fd
!= STDERR_FILENO
417 && s
->fd
!= STDIN_FILENO
)
418 retval
= close (s
->fd
);
425 static const struct stream_vtable raw_vtable
= {
426 .read
= (void *) raw_read
,
427 .write
= (void *) raw_write
,
428 .seek
= (void *) raw_seek
,
429 .tell
= (void *) raw_tell
,
430 .size
= (void *) raw_size
,
431 .trunc
= (void *) raw_truncate
,
432 .close
= (void *) raw_close
,
433 .flush
= (void *) raw_flush
437 raw_init (unix_stream
* s
)
439 s
->st
.vptr
= &raw_vtable
;
446 /*********************************************************************
447 Buffered I/O functions. These functions have the same semantics as the
448 raw I/O functions above, except that they are buffered in order to
449 improve performance. The buffer must be flushed when switching from
450 reading to writing and vice versa.
451 *********************************************************************/
454 buf_flush (unix_stream
* s
)
458 /* Flushing in read mode means discarding read bytes. */
464 if (s
->physical_offset
!= s
->buffer_offset
465 && lseek (s
->fd
, s
->buffer_offset
, SEEK_SET
) < 0)
468 writelen
= raw_write (s
, s
->buffer
, s
->ndirty
);
470 s
->physical_offset
= s
->buffer_offset
+ writelen
;
472 if (s
->physical_offset
> s
->file_length
)
473 s
->file_length
= s
->physical_offset
;
475 s
->ndirty
-= writelen
;
483 buf_read (unix_stream
* s
, void * buf
, ssize_t nbyte
)
486 s
->buffer_offset
= s
->logical_offset
;
488 /* Is the data we want in the buffer? */
489 if (s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ s
->active
490 && s
->buffer_offset
<= s
->logical_offset
)
491 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
), nbyte
);
494 /* First copy the active bytes if applicable, then read the rest
495 either directly or filling the buffer. */
498 ssize_t to_read
, did_read
;
499 gfc_offset new_logical
;
502 if (s
->logical_offset
>= s
->buffer_offset
503 && s
->buffer_offset
+ s
->active
>= s
->logical_offset
)
505 nread
= s
->active
- (s
->logical_offset
- s
->buffer_offset
);
506 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
),
510 /* At this point we consider all bytes in the buffer discarded. */
511 to_read
= nbyte
- nread
;
512 new_logical
= s
->logical_offset
+ nread
;
513 if (s
->physical_offset
!= new_logical
514 && lseek (s
->fd
, new_logical
, SEEK_SET
) < 0)
516 s
->buffer_offset
= s
->physical_offset
= new_logical
;
517 if (to_read
<= BUFFER_SIZE
/2)
519 did_read
= raw_read (s
, s
->buffer
, BUFFER_SIZE
);
520 s
->physical_offset
+= did_read
;
521 s
->active
= did_read
;
522 did_read
= (did_read
> to_read
) ? to_read
: did_read
;
523 memcpy (p
, s
->buffer
, did_read
);
527 did_read
= raw_read (s
, p
, to_read
);
528 s
->physical_offset
+= did_read
;
531 nbyte
= did_read
+ nread
;
533 s
->logical_offset
+= nbyte
;
538 buf_write (unix_stream
* s
, const void * buf
, ssize_t nbyte
)
541 s
->buffer_offset
= s
->logical_offset
;
543 /* Does the data fit into the buffer? As a special case, if the
544 buffer is empty and the request is bigger than BUFFER_SIZE/2,
545 write directly. This avoids the case where the buffer would have
546 to be flushed at every write. */
547 if (!(s
->ndirty
== 0 && nbyte
> BUFFER_SIZE
/2)
548 && s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ BUFFER_SIZE
549 && s
->buffer_offset
<= s
->logical_offset
550 && s
->buffer_offset
+ s
->ndirty
>= s
->logical_offset
)
552 memcpy (s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
), buf
, nbyte
);
553 int nd
= (s
->logical_offset
- s
->buffer_offset
) + nbyte
;
559 /* Flush, and either fill the buffer with the new data, or if
560 the request is bigger than the buffer size, write directly
561 bypassing the buffer. */
563 if (nbyte
<= BUFFER_SIZE
/2)
565 memcpy (s
->buffer
, buf
, nbyte
);
566 s
->buffer_offset
= s
->logical_offset
;
571 if (s
->physical_offset
!= s
->logical_offset
)
573 if (lseek (s
->fd
, s
->logical_offset
, SEEK_SET
) < 0)
575 s
->physical_offset
= s
->logical_offset
;
578 nbyte
= raw_write (s
, buf
, nbyte
);
579 s
->physical_offset
+= nbyte
;
582 s
->logical_offset
+= nbyte
;
583 if (s
->logical_offset
> s
->file_length
)
584 s
->file_length
= s
->logical_offset
;
589 buf_seek (unix_stream
* s
, gfc_offset offset
, int whence
)
596 offset
+= s
->logical_offset
;
599 offset
+= s
->file_length
;
609 s
->logical_offset
= offset
;
614 buf_tell (unix_stream
* s
)
616 return buf_seek (s
, 0, SEEK_CUR
);
620 buf_size (unix_stream
* s
)
622 return s
->file_length
;
626 buf_truncate (unix_stream
* s
, gfc_offset length
)
630 if (buf_flush (s
) != 0)
632 r
= raw_truncate (s
, length
);
634 s
->file_length
= length
;
639 buf_close (unix_stream
* s
)
641 if (buf_flush (s
) != 0)
644 return raw_close (s
);
647 static const struct stream_vtable buf_vtable
= {
648 .read
= (void *) buf_read
,
649 .write
= (void *) buf_write
,
650 .seek
= (void *) buf_seek
,
651 .tell
= (void *) buf_tell
,
652 .size
= (void *) buf_size
,
653 .trunc
= (void *) buf_truncate
,
654 .close
= (void *) buf_close
,
655 .flush
= (void *) buf_flush
659 buf_init (unix_stream
* s
)
661 s
->st
.vptr
= &buf_vtable
;
663 s
->buffer
= xmalloc (BUFFER_SIZE
);
668 /*********************************************************************
669 memory stream functions - These are used for internal files
671 The idea here is that a single stream structure is created and all
672 requests must be satisfied from it. The location and size of the
673 buffer is the character variable supplied to the READ or WRITE
676 *********************************************************************/
679 mem_alloc_r (stream
* strm
, int * len
)
681 unix_stream
* s
= (unix_stream
*) strm
;
683 gfc_offset where
= s
->logical_offset
;
685 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
688 n
= s
->buffer_offset
+ s
->active
- where
;
692 s
->logical_offset
= where
+ *len
;
694 return s
->buffer
+ (where
- s
->buffer_offset
);
699 mem_alloc_r4 (stream
* strm
, int * len
)
701 unix_stream
* s
= (unix_stream
*) strm
;
703 gfc_offset where
= s
->logical_offset
;
705 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
708 n
= s
->buffer_offset
+ s
->active
- where
;
712 s
->logical_offset
= where
+ *len
;
714 return s
->buffer
+ (where
- s
->buffer_offset
) * 4;
719 mem_alloc_w (stream
* strm
, int * len
)
721 unix_stream
* s
= (unix_stream
*) strm
;
723 gfc_offset where
= s
->logical_offset
;
727 if (where
< s
->buffer_offset
)
730 if (m
> s
->file_length
)
733 s
->logical_offset
= m
;
735 return s
->buffer
+ (where
- s
->buffer_offset
);
740 mem_alloc_w4 (stream
* strm
, int * len
)
742 unix_stream
* s
= (unix_stream
*) strm
;
744 gfc_offset where
= s
->logical_offset
;
745 gfc_char4_t
*result
= (gfc_char4_t
*) s
->buffer
;
749 if (where
< s
->buffer_offset
)
752 if (m
> s
->file_length
)
755 s
->logical_offset
= m
;
756 return &result
[where
- s
->buffer_offset
];
760 /* Stream read function for character(kind=1) internal units. */
763 mem_read (stream
* s
, void * buf
, ssize_t nbytes
)
768 p
= mem_alloc_r (s
, &nb
);
779 /* Stream read function for chracter(kind=4) internal units. */
782 mem_read4 (stream
* s
, void * buf
, ssize_t nbytes
)
787 p
= mem_alloc_r (s
, &nb
);
798 /* Stream write function for character(kind=1) internal units. */
801 mem_write (stream
* s
, const void * buf
, ssize_t nbytes
)
806 p
= mem_alloc_w (s
, &nb
);
817 /* Stream write function for character(kind=4) internal units. */
820 mem_write4 (stream
* s
, const void * buf
, ssize_t nwords
)
825 p
= mem_alloc_w4 (s
, &nw
);
829 *p
++ = (gfc_char4_t
) *((char *) buf
);
838 mem_seek (stream
* strm
, gfc_offset offset
, int whence
)
840 unix_stream
* s
= (unix_stream
*) strm
;
846 offset
+= s
->logical_offset
;
849 offset
+= s
->file_length
;
855 /* Note that for internal array I/O it's actually possible to have a
856 negative offset, so don't check for that. */
857 if (offset
> s
->file_length
)
863 s
->logical_offset
= offset
;
865 /* Returning < 0 is the error indicator for sseek(), so return 0 if
866 offset is negative. Thus if the return value is 0, the caller
867 has to use stell() to get the real value of logical_offset. */
875 mem_tell (stream
* s
)
877 return ((unix_stream
*)s
)->logical_offset
;
882 mem_truncate (unix_stream
* s
__attribute__ ((unused
)),
883 gfc_offset length
__attribute__ ((unused
)))
890 mem_flush (unix_stream
* s
__attribute__ ((unused
)))
897 mem_close (unix_stream
* s
)
904 static const struct stream_vtable mem_vtable
= {
905 .read
= (void *) mem_read
,
906 .write
= (void *) mem_write
,
907 .seek
= (void *) mem_seek
,
908 .tell
= (void *) mem_tell
,
909 /* buf_size is not a typo, we just reuse an identical
911 .size
= (void *) buf_size
,
912 .trunc
= (void *) mem_truncate
,
913 .close
= (void *) mem_close
,
914 .flush
= (void *) mem_flush
917 static const struct stream_vtable mem4_vtable
= {
918 .read
= (void *) mem_read4
,
919 .write
= (void *) mem_write4
,
920 .seek
= (void *) mem_seek
,
921 .tell
= (void *) mem_tell
,
922 /* buf_size is not a typo, we just reuse an identical
924 .size
= (void *) buf_size
,
925 .trunc
= (void *) mem_truncate
,
926 .close
= (void *) mem_close
,
927 .flush
= (void *) mem_flush
930 /*********************************************************************
931 Public functions -- A reimplementation of this module needs to
932 define functional equivalents of the following.
933 *********************************************************************/
935 /* open_internal()-- Returns a stream structure from a character(kind=1)
939 open_internal (char *base
, int length
, gfc_offset offset
)
943 s
= xcalloc (1, sizeof (unix_stream
));
946 s
->buffer_offset
= offset
;
948 s
->active
= s
->file_length
= length
;
950 s
->st
.vptr
= &mem_vtable
;
955 /* open_internal4()-- Returns a stream structure from a character(kind=4)
959 open_internal4 (char *base
, int length
, gfc_offset offset
)
963 s
= xcalloc (1, sizeof (unix_stream
));
966 s
->buffer_offset
= offset
;
968 s
->active
= s
->file_length
= length
* sizeof (gfc_char4_t
);
970 s
->st
.vptr
= &mem4_vtable
;
976 /* "Unbuffered" really means I/O statement buffering. For formatted
977 I/O, the fbuf manages this, and then uses raw I/O. For unformatted
978 I/O, buffered I/O is used, and the buffer is flushed at the end of
979 each I/O statement, where this function is called. */
982 flush_if_unbuffered (stream
* s
)
984 unix_stream
* us
= (unix_stream
*) s
;
991 /* fd_to_stream()-- Given an open file descriptor, build a stream
995 fd_to_stream (int fd
, bool unformatted
)
1000 s
= xcalloc (1, sizeof (unix_stream
));
1004 /* Get the current length of the file. */
1006 fstat (fd
, &statbuf
);
1008 s
->st_dev
= statbuf
.st_dev
;
1009 s
->st_ino
= statbuf
.st_ino
;
1010 s
->file_length
= statbuf
.st_size
;
1012 /* Only use buffered IO for regular files. */
1013 if (S_ISREG (statbuf
.st_mode
)
1014 && !options
.all_unbuffered
1015 && !(options
.unbuffered_preconnected
&&
1016 (s
->fd
== STDIN_FILENO
1017 || s
->fd
== STDOUT_FILENO
1018 || s
->fd
== STDERR_FILENO
)))
1024 s
->unbuffered
= true;
1031 return (stream
*) s
;
1035 /* Given the Fortran unit number, convert it to a C file descriptor. */
1038 unit_to_fd (int unit
)
1043 us
= find_unit (unit
);
1047 fd
= ((unix_stream
*) us
->s
)->fd
;
1053 /* unpack_filename()-- Given a fortran string and a pointer to a
1054 * buffer that is PATH_MAX characters, convert the fortran string to a
1055 * C string in the buffer. Returns nonzero if this is not possible. */
1058 unpack_filename (char *cstring
, const char *fstring
, int len
)
1060 if (fstring
== NULL
)
1062 len
= fstrlen (fstring
, len
);
1063 if (len
>= PATH_MAX
)
1064 return ENAMETOOLONG
;
1066 memmove (cstring
, fstring
, len
);
1067 cstring
[len
] = '\0';
1073 /* Set the close-on-exec flag for an existing fd, if the system
1076 static void __attribute__ ((unused
))
1077 set_close_on_exec (int fd
__attribute__ ((unused
)))
1079 /* Mingw does not define F_SETFD. */
1080 #if defined(HAVE_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
1082 fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
1087 /* Helper function for tempfile(). Tries to open a temporary file in
1088 the directory specified by tempdir. If successful, the file name is
1089 stored in fname and the descriptor returned. Returns -1 on
1093 tempfile_open (const char *tempdir
, char **fname
)
1096 const char *slash
= "/";
1097 #if defined(HAVE_UMASK) && defined(HAVE_MKSTEMP)
1104 /* Check for the special case that tempdir ends with a slash or
1106 size_t tempdirlen
= strlen (tempdir
);
1107 if (*tempdir
== 0 || tempdir
[tempdirlen
- 1] == '/'
1109 || tempdir
[tempdirlen
- 1] == '\\'
1114 // Take care that the template is longer in the mktemp() branch.
1115 char * template = xmalloc (tempdirlen
+ 23);
1118 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpXXXXXX",
1122 /* Temporarily set the umask such that the file has 0600 permissions. */
1123 mode_mask
= umask (S_IXUSR
| S_IRWXG
| S_IRWXO
);
1126 #if defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
1127 fd
= mkostemp (template, O_CLOEXEC
);
1129 fd
= mkstemp (template);
1130 set_close_on_exec (fd
);
1134 (void) umask (mode_mask
);
1137 #else /* HAVE_MKSTEMP */
1140 size_t slashlen
= strlen (slash
);
1141 int flags
= O_RDWR
| O_CREAT
| O_EXCL
;
1142 #if defined(HAVE_CRLF) && defined(O_BINARY)
1150 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpaaaXXXXXX",
1155 template[tempdirlen
+ slashlen
+ 13] = 'a' + (c
% 26);
1157 template[tempdirlen
+ slashlen
+ 12] = 'a' + (c
% 26);
1159 template[tempdirlen
+ slashlen
+ 11] = 'a' + (c
% 26);
1164 if (!mktemp (template))
1171 fd
= open (template, flags
, S_IRUSR
| S_IWUSR
);
1173 while (fd
== -1 && errno
== EEXIST
);
1175 set_close_on_exec (fd
);
1177 #endif /* HAVE_MKSTEMP */
1184 /* tempfile()-- Generate a temporary filename for a scratch file and
1185 * open it. mkstemp() opens the file for reading and writing, but the
1186 * library mode prevents anything that is not allowed. The descriptor
1187 * is returned, which is -1 on error. The template is pointed to by
1188 * opp->file, which is copied into the unit structure
1189 * and freed later. */
1192 tempfile (st_parameter_open
*opp
)
1194 const char *tempdir
;
1198 tempdir
= secure_getenv ("TMPDIR");
1199 fd
= tempfile_open (tempdir
, &fname
);
1203 char buffer
[MAX_PATH
+ 1];
1205 ret
= GetTempPath (MAX_PATH
, buffer
);
1206 /* If we are not able to get a temp-directory, we use
1207 current directory. */
1208 if (ret
> MAX_PATH
|| !ret
)
1212 tempdir
= strdup (buffer
);
1213 fd
= tempfile_open (tempdir
, &fname
);
1215 #elif defined(__CYGWIN__)
1218 tempdir
= secure_getenv ("TMP");
1219 fd
= tempfile_open (tempdir
, &fname
);
1223 tempdir
= secure_getenv ("TEMP");
1224 fd
= tempfile_open (tempdir
, &fname
);
1228 fd
= tempfile_open (P_tmpdir
, &fname
);
1231 opp
->file_len
= strlen (fname
); /* Don't include trailing nul */
1237 /* regular_file()-- Open a regular file.
1238 * Change flags->action if it is ACTION_UNSPECIFIED on entry,
1239 * unless an error occurs.
1240 * Returns the descriptor, which is less than zero on error. */
1243 regular_file (st_parameter_open
*opp
, unit_flags
*flags
)
1245 char path
[min(PATH_MAX
, opp
->file_len
+ 1)];
1248 int crflag
, crflag2
;
1252 err
= unpack_filename (path
, opp
->file
, opp
->file_len
);
1255 errno
= err
; /* Fake an OS error */
1260 if (opp
->file_len
== 7)
1262 if (strncmp (path
, "CONOUT$", 7) == 0
1263 || strncmp (path
, "CONERR$", 7) == 0)
1265 fd
= open ("/dev/conout", O_WRONLY
);
1266 flags
->action
= ACTION_WRITE
;
1271 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1273 fd
= open ("/dev/conin", O_RDONLY
);
1274 flags
->action
= ACTION_READ
;
1281 if (opp
->file_len
== 7)
1283 if (strncmp (path
, "CONOUT$", 7) == 0
1284 || strncmp (path
, "CONERR$", 7) == 0)
1286 fd
= open ("CONOUT$", O_WRONLY
);
1287 flags
->action
= ACTION_WRITE
;
1292 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1294 fd
= open ("CONIN$", O_RDONLY
);
1295 flags
->action
= ACTION_READ
;
1300 switch (flags
->action
)
1310 case ACTION_READWRITE
:
1311 case ACTION_UNSPECIFIED
:
1316 internal_error (&opp
->common
, "regular_file(): Bad action");
1319 switch (flags
->status
)
1322 crflag
= O_CREAT
| O_EXCL
;
1325 case STATUS_OLD
: /* open will fail if the file does not exist*/
1329 case STATUS_UNKNOWN
:
1330 if (rwflag
== O_RDONLY
)
1336 case STATUS_REPLACE
:
1337 crflag
= O_CREAT
| O_TRUNC
;
1341 /* Note: STATUS_SCRATCH is handled by tempfile () and should
1342 never be seen here. */
1343 internal_error (&opp
->common
, "regular_file(): Bad status");
1346 /* rwflag |= O_LARGEFILE; */
1348 #if defined(HAVE_CRLF) && defined(O_BINARY)
1353 crflag
|= O_CLOEXEC
;
1356 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
;
1357 fd
= open (path
, rwflag
| crflag
, mode
);
1358 if (flags
->action
!= ACTION_UNSPECIFIED
)
1363 flags
->action
= ACTION_READWRITE
;
1366 if (errno
!= EACCES
&& errno
!= EROFS
)
1369 /* retry for read-only access */
1371 if (flags
->status
== STATUS_UNKNOWN
)
1372 crflag2
= crflag
& ~(O_CREAT
);
1375 fd
= open (path
, rwflag
| crflag2
, mode
);
1378 flags
->action
= ACTION_READ
;
1379 return fd
; /* success */
1382 if (errno
!= EACCES
&& errno
!= ENOENT
)
1383 return fd
; /* failure */
1385 /* retry for write-only access */
1387 fd
= open (path
, rwflag
| crflag
, mode
);
1390 flags
->action
= ACTION_WRITE
;
1391 return fd
; /* success */
1393 return fd
; /* failure */
1397 /* open_external()-- Open an external file, unix specific version.
1398 * Change flags->action if it is ACTION_UNSPECIFIED on entry.
1399 * Returns NULL on operating system error. */
1402 open_external (st_parameter_open
*opp
, unit_flags
*flags
)
1406 if (flags
->status
== STATUS_SCRATCH
)
1408 fd
= tempfile (opp
);
1409 if (flags
->action
== ACTION_UNSPECIFIED
)
1410 flags
->action
= ACTION_READWRITE
;
1412 #if HAVE_UNLINK_OPEN_FILE
1413 /* We can unlink scratch files now and it will go away when closed. */
1420 /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1422 fd
= regular_file (opp
, flags
);
1424 set_close_on_exec (fd
);
1432 return fd_to_stream (fd
, flags
->form
== FORM_UNFORMATTED
);
1436 /* input_stream()-- Return a stream pointer to the default input stream.
1437 * Called on initialization. */
1442 return fd_to_stream (STDIN_FILENO
, false);
1446 /* output_stream()-- Return a stream pointer to the default output stream.
1447 * Called on initialization. */
1450 output_stream (void)
1454 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1455 setmode (STDOUT_FILENO
, O_BINARY
);
1458 s
= fd_to_stream (STDOUT_FILENO
, false);
1463 /* error_stream()-- Return a stream pointer to the default error stream.
1464 * Called on initialization. */
1471 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1472 setmode (STDERR_FILENO
, O_BINARY
);
1475 s
= fd_to_stream (STDERR_FILENO
, false);
1480 /* compare_file_filename()-- Given an open stream and a fortran string
1481 * that is a filename, figure out if the file is the same as the
1485 compare_file_filename (gfc_unit
*u
, const char *name
, int len
)
1487 char path
[min(PATH_MAX
, len
+ 1)];
1489 #ifdef HAVE_WORKING_STAT
1497 if (unpack_filename (path
, name
, len
))
1498 return 0; /* Can't be the same */
1500 /* If the filename doesn't exist, then there is no match with the
1503 if (stat (path
, &st
) < 0)
1506 #ifdef HAVE_WORKING_STAT
1507 s
= (unix_stream
*) (u
->s
);
1508 return (st
.st_dev
== s
->st_dev
) && (st
.st_ino
== s
->st_ino
);
1512 /* We try to match files by a unique ID. On some filesystems (network
1513 fs and FAT), we can't generate this unique ID, and will simply compare
1515 id1
= id_from_path (path
);
1516 id2
= id_from_fd (((unix_stream
*) (u
->s
))->fd
);
1518 return (id1
== id2
);
1521 if (len
!= u
->file_len
)
1523 return (memcmp(path
, u
->file
, len
) == 0);
1528 #ifdef HAVE_WORKING_STAT
1529 # define FIND_FILE0_DECL struct stat *st
1530 # define FIND_FILE0_ARGS st
1532 # define FIND_FILE0_DECL uint64_t id, const char *file, gfc_charlen_type file_len
1533 # define FIND_FILE0_ARGS id, file, file_len
1536 /* find_file0()-- Recursive work function for find_file() */
1539 find_file0 (gfc_unit
*u
, FIND_FILE0_DECL
)
1542 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1549 #ifdef HAVE_WORKING_STAT
1552 unix_stream
*s
= (unix_stream
*) (u
->s
);
1553 if (st
[0].st_dev
== s
->st_dev
&& st
[0].st_ino
== s
->st_ino
)
1558 if (u
->s
&& ((id1
= id_from_fd (((unix_stream
*) u
->s
)->fd
)) || id1
))
1565 if (compare_string (u
->file_len
, u
->file
, file_len
, file
) == 0)
1569 v
= find_file0 (u
->left
, FIND_FILE0_ARGS
);
1573 v
= find_file0 (u
->right
, FIND_FILE0_ARGS
);
1581 /* find_file()-- Take the current filename and see if there is a unit
1582 * that has the file already open. Returns a pointer to the unit if so. */
1585 find_file (const char *file
, gfc_charlen_type file_len
)
1587 char path
[min(PATH_MAX
, file_len
+ 1)];
1590 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1594 if (unpack_filename (path
, file
, file_len
))
1597 if (stat (path
, &st
[0]) < 0)
1600 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1601 id
= id_from_path (path
);
1604 __gthread_mutex_lock (&unit_lock
);
1606 u
= find_file0 (unit_root
, FIND_FILE0_ARGS
);
1610 if (! __gthread_mutex_trylock (&u
->lock
))
1612 /* assert (u->closed == 0); */
1613 __gthread_mutex_unlock (&unit_lock
);
1617 inc_waiting_locked (u
);
1619 __gthread_mutex_unlock (&unit_lock
);
1622 __gthread_mutex_lock (&u
->lock
);
1625 __gthread_mutex_lock (&unit_lock
);
1626 __gthread_mutex_unlock (&u
->lock
);
1627 if (predec_waiting_locked (u
) == 0)
1632 dec_waiting_unlocked (u
);
1638 flush_all_units_1 (gfc_unit
*u
, int min_unit
)
1642 if (u
->unit_number
> min_unit
)
1644 gfc_unit
*r
= flush_all_units_1 (u
->left
, min_unit
);
1648 if (u
->unit_number
>= min_unit
)
1650 if (__gthread_mutex_trylock (&u
->lock
))
1654 __gthread_mutex_unlock (&u
->lock
);
1662 flush_all_units (void)
1667 __gthread_mutex_lock (&unit_lock
);
1670 u
= flush_all_units_1 (unit_root
, min_unit
);
1672 inc_waiting_locked (u
);
1673 __gthread_mutex_unlock (&unit_lock
);
1677 __gthread_mutex_lock (&u
->lock
);
1679 min_unit
= u
->unit_number
+ 1;
1684 __gthread_mutex_lock (&unit_lock
);
1685 __gthread_mutex_unlock (&u
->lock
);
1686 (void) predec_waiting_locked (u
);
1690 __gthread_mutex_lock (&unit_lock
);
1691 __gthread_mutex_unlock (&u
->lock
);
1692 if (predec_waiting_locked (u
) == 0)
1700 /* delete_file()-- Given a unit structure, delete the file associated
1701 * with the unit. Returns nonzero if something went wrong. */
1704 delete_file (gfc_unit
* u
)
1706 char path
[min(PATH_MAX
, u
->file_len
+ 1)];
1707 int err
= unpack_filename (path
, u
->file
, u
->file_len
);
1710 { /* Shouldn't be possible */
1715 return unlink (path
);
1719 /* file_exists()-- Returns nonzero if the current filename exists on
1723 file_exists (const char *file
, gfc_charlen_type file_len
)
1725 char path
[min(PATH_MAX
, file_len
+ 1)];
1727 if (unpack_filename (path
, file
, file_len
))
1730 return !(access (path
, F_OK
));
1734 /* file_size()-- Returns the size of the file. */
1737 file_size (const char *file
, gfc_charlen_type file_len
)
1739 char path
[min(PATH_MAX
, file_len
+ 1)];
1740 struct stat statbuf
;
1742 if (unpack_filename (path
, file
, file_len
))
1745 if (stat (path
, &statbuf
) < 0)
1748 return (GFC_IO_INT
) statbuf
.st_size
;
1751 static const char yes
[] = "YES", no
[] = "NO", unknown
[] = "UNKNOWN";
1753 /* inquire_sequential()-- Given a fortran string, determine if the
1754 * file is suitable for sequential access. Returns a C-style
1758 inquire_sequential (const char *string
, int len
)
1760 char path
[min(PATH_MAX
, len
+ 1)];
1761 struct stat statbuf
;
1763 if (string
== NULL
||
1764 unpack_filename (path
, string
, len
) || stat (path
, &statbuf
) < 0)
1767 if (S_ISREG (statbuf
.st_mode
) ||
1768 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1771 if (S_ISDIR (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1778 /* inquire_direct()-- Given a fortran string, determine if the file is
1779 * suitable for direct access. Returns a C-style string. */
1782 inquire_direct (const char *string
, int len
)
1784 char path
[min(PATH_MAX
, len
+ 1)];
1785 struct stat statbuf
;
1787 if (string
== NULL
||
1788 unpack_filename (path
, string
, len
) || stat (path
, &statbuf
) < 0)
1791 if (S_ISREG (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1794 if (S_ISDIR (statbuf
.st_mode
) ||
1795 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1802 /* inquire_formatted()-- Given a fortran string, determine if the file
1803 * is suitable for formatted form. Returns a C-style string. */
1806 inquire_formatted (const char *string
, int len
)
1808 char path
[min(PATH_MAX
, len
+ 1)];
1809 struct stat statbuf
;
1811 if (string
== NULL
||
1812 unpack_filename (path
, string
, len
) || stat (path
, &statbuf
) < 0)
1815 if (S_ISREG (statbuf
.st_mode
) ||
1816 S_ISBLK (statbuf
.st_mode
) ||
1817 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1820 if (S_ISDIR (statbuf
.st_mode
))
1827 /* inquire_unformatted()-- Given a fortran string, determine if the file
1828 * is suitable for unformatted form. Returns a C-style string. */
1831 inquire_unformatted (const char *string
, int len
)
1833 return inquire_formatted (string
, len
);
1837 /* inquire_access()-- Given a fortran string, determine if the file is
1838 * suitable for access. */
1841 inquire_access (const char *string
, int len
, int mode
)
1843 char path
[min(PATH_MAX
, len
+ 1)];
1845 if (string
== NULL
|| unpack_filename (path
, string
, len
) ||
1846 access (path
, mode
) < 0)
1853 /* inquire_read()-- Given a fortran string, determine if the file is
1854 * suitable for READ access. */
1857 inquire_read (const char *string
, int len
)
1859 return inquire_access (string
, len
, R_OK
);
1863 /* inquire_write()-- Given a fortran string, determine if the file is
1864 * suitable for READ access. */
1867 inquire_write (const char *string
, int len
)
1869 return inquire_access (string
, len
, W_OK
);
1873 /* inquire_readwrite()-- Given a fortran string, determine if the file is
1874 * suitable for read and write access. */
1877 inquire_readwrite (const char *string
, int len
)
1879 return inquire_access (string
, len
, R_OK
| W_OK
);
1884 stream_isatty (stream
*s
)
1886 return isatty (((unix_stream
*) s
)->fd
);
1890 stream_ttyname (stream
*s
__attribute__ ((unused
)),
1891 char * buf
__attribute__ ((unused
)),
1892 size_t buflen
__attribute__ ((unused
)))
1894 #ifdef HAVE_TTYNAME_R
1895 return ttyname_r (((unix_stream
*) s
)->fd
, buf
, buflen
);
1896 #elif defined HAVE_TTYNAME
1899 p
= ttyname (((unix_stream
*) s
)->fd
);
1905 memcpy (buf
, p
, plen
);
1915 /* How files are stored: This is an operating-system specific issue,
1916 and therefore belongs here. There are three cases to consider.
1919 Records are written as block of bytes corresponding to the record
1920 length of the file. This goes for both formatted and unformatted
1921 records. Positioning is done explicitly for each data transfer,
1922 so positioning is not much of an issue.
1924 Sequential Formatted:
1925 Records are separated by newline characters. The newline character
1926 is prohibited from appearing in a string. If it does, this will be
1927 messed up on the next read. End of file is also the end of a record.
1929 Sequential Unformatted:
1930 In this case, we are merely copying bytes to and from main storage,
1931 yet we need to keep track of varying record lengths. We adopt
1932 the solution used by f2c. Each record contains a pair of length
1935 Length of record n in bytes
1937 Length of record n in bytes
1939 Length of record n+1 in bytes
1941 Length of record n+1 in bytes
1943 The length is stored at the end of a record to allow backspacing to the
1944 previous record. Between data transfer statements, the file pointer
1945 is left pointing to the first length of the current record.
1947 ENDFILE records are never explicitly stored.