1 /* Copyright (C) 2002-2018 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 */
44 /* For mingw, we don't identify files by their inode number, but by a
45 64-bit identifier created from a BY_HANDLE_FILE_INFORMATION. */
48 #define WIN32_LEAN_AND_MEAN
51 #if !defined(_FILE_OFFSET_BITS) || _FILE_OFFSET_BITS != 64
53 #define lseek _lseeki64
55 #define fstat _fstati64
60 #ifndef HAVE_WORKING_STAT
62 id_from_handle (HANDLE hFile
)
64 BY_HANDLE_FILE_INFORMATION FileInformation
;
66 if (hFile
== INVALID_HANDLE_VALUE
)
69 memset (&FileInformation
, 0, sizeof(FileInformation
));
70 if (!GetFileInformationByHandle (hFile
, &FileInformation
))
73 return ((uint64_t) FileInformation
.nFileIndexLow
)
74 | (((uint64_t) FileInformation
.nFileIndexHigh
) << 32);
79 id_from_path (const char *path
)
84 if (!path
|| !*path
|| access (path
, F_OK
))
87 hFile
= CreateFile (path
, 0, 0, NULL
, OPEN_EXISTING
,
88 FILE_FLAG_BACKUP_SEMANTICS
| FILE_ATTRIBUTE_READONLY
,
90 res
= id_from_handle (hFile
);
97 id_from_fd (const int fd
)
99 return id_from_handle ((HANDLE
) _get_osfhandle (fd
));
102 #endif /* HAVE_WORKING_STAT */
105 /* On mingw, we don't use umask in tempfile_open(), because it
106 doesn't support the user/group/other-based permissions. */
109 #endif /* __MINGW32__ */
112 /* These flags aren't defined on all targets (mingw32), so provide them
145 /* Fallback implementation of access() on systems that don't have it.
146 Only modes R_OK, W_OK and F_OK are used in this file. */
149 fallback_access (const char *path
, int mode
)
153 if ((mode
& R_OK
) && (fd
= open (path
, O_RDONLY
)) < 0)
157 if ((mode
& W_OK
) && (fd
= open (path
, O_WRONLY
)) < 0)
164 return stat (path
, &st
);
171 #define access fallback_access
175 /* Fallback directory for creating temporary files. P_tmpdir is
176 defined on many POSIX platforms. */
179 #define P_tmpdir _P_tmpdir /* MinGW */
181 #define P_tmpdir "/tmp"
186 /* Unix and internal stream I/O module */
188 static const int BUFFER_SIZE
= 8192;
194 gfc_offset buffer_offset
; /* File offset of the start of the buffer */
195 gfc_offset physical_offset
; /* Current physical file offset */
196 gfc_offset logical_offset
; /* Current logical file offset */
197 gfc_offset file_length
; /* Length of the file. */
199 char *buffer
; /* Pointer to the buffer. */
200 int fd
; /* The POSIX file descriptor. */
202 int active
; /* Length of valid bytes in the buffer */
204 int ndirty
; /* Dirty bytes starting at buffer_offset */
206 /* Cached stat(2) values. */
210 bool unbuffered
; /* Buffer should be flushed after each I/O statement. */
215 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
216 standard descriptors, returning a non-standard descriptor. If the
217 user specifies that system errors should go to standard output,
218 then closes standard output, we don't want the system errors to a
219 file that has been given file descriptor 1 or 0. We want to send
220 the error to the invalid descriptor. */
226 int input
, output
, error
;
228 input
= output
= error
= 0;
230 /* Unix allocates the lowest descriptors first, so a loop is not
231 required, but this order is. */
232 if (fd
== STDIN_FILENO
)
237 if (fd
== STDOUT_FILENO
)
242 if (fd
== STDERR_FILENO
)
249 close (STDIN_FILENO
);
251 close (STDOUT_FILENO
);
253 close (STDERR_FILENO
);
260 /* If the stream corresponds to a preconnected unit, we flush the
261 corresponding C stream. This is bugware for mixed C-Fortran codes
262 where the C code doesn't flush I/O before returning. */
264 flush_if_preconnected (stream
*s
)
268 fd
= ((unix_stream
*) s
)->fd
;
269 if (fd
== STDIN_FILENO
)
271 else if (fd
== STDOUT_FILENO
)
273 else if (fd
== STDERR_FILENO
)
278 /********************************************************************
279 Raw I/O functions (read, write, seek, tell, truncate, close).
281 These functions wrap the basic POSIX I/O syscalls. Any deviation in
282 semantics is a bug, except the following: write restarts in case
283 of being interrupted by a signal, and as the first argument the
284 functions take the unix_stream struct rather than an integer file
285 descriptor. Also, for POSIX read() and write() a nbyte argument larger
286 than SSIZE_MAX is undefined; here the type of nbyte is ssize_t rather
287 than size_t as for POSIX read/write.
288 *********************************************************************/
291 raw_flush (unix_stream
*s
__attribute__ ((unused
)))
296 /* Write/read at most 2 GB - 4k chunks at a time. Linux never reads or
297 writes more than this, and there are reports that macOS fails for
298 larger than 2 GB as well. */
299 #define MAX_CHUNK 2147479552
302 raw_read (unix_stream
*s
, void *buf
, ssize_t nbyte
)
304 /* For read we can't do I/O in a loop like raw_write does, because
305 that will break applications that wait for interactive I/O. We
306 still can loop around EINTR, though. This however causes a
307 problem for large reads which must be chunked, see comment above.
308 So assume that if the size is larger than the chunk size, we're
309 reading from a file and not the terminal. */
310 if (nbyte
<= MAX_CHUNK
)
314 ssize_t trans
= read (s
->fd
, buf
, nbyte
);
315 if (trans
== -1 && errno
== EINTR
)
322 ssize_t bytes_left
= nbyte
;
324 while (bytes_left
> 0)
326 ssize_t to_read
= bytes_left
< MAX_CHUNK
? bytes_left
: MAX_CHUNK
;
327 ssize_t trans
= read (s
->fd
, buf_st
, to_read
);
338 return nbyte
- bytes_left
;
343 raw_write (unix_stream
*s
, const void *buf
, ssize_t nbyte
)
345 ssize_t trans
, bytes_left
;
349 buf_st
= (char *) buf
;
351 /* We must write in a loop since some systems don't restart system
352 calls in case of a signal. Also some systems might fail outright
353 if we try to write more than 2 GB in a single syscall, so chunk
355 while (bytes_left
> 0)
357 ssize_t to_write
= bytes_left
< MAX_CHUNK
? bytes_left
: MAX_CHUNK
;
358 trans
= write (s
->fd
, buf_st
, to_write
);
370 return nbyte
- bytes_left
;
374 raw_seek (unix_stream
*s
, gfc_offset offset
, int whence
)
378 gfc_offset off
= lseek (s
->fd
, offset
, whence
);
379 if (off
== (gfc_offset
) -1 && errno
== EINTR
)
386 raw_tell (unix_stream
*s
)
390 gfc_offset off
= lseek (s
->fd
, 0, SEEK_CUR
);
391 if (off
== (gfc_offset
) -1 && errno
== EINTR
)
398 raw_size (unix_stream
*s
)
401 if (TEMP_FAILURE_RETRY (fstat (s
->fd
, &statbuf
)) == -1)
403 if (S_ISREG (statbuf
.st_mode
))
404 return statbuf
.st_size
;
410 raw_truncate (unix_stream
*s
, gfc_offset length
)
421 h
= (HANDLE
) _get_osfhandle (s
->fd
);
422 if (h
== INVALID_HANDLE_VALUE
)
427 cur
= lseek (s
->fd
, 0, SEEK_CUR
);
430 if (lseek (s
->fd
, length
, SEEK_SET
) == -1)
432 if (!SetEndOfFile (h
))
437 if (lseek (s
->fd
, cur
, SEEK_SET
) == -1)
441 lseek (s
->fd
, cur
, SEEK_SET
);
443 #elif defined HAVE_FTRUNCATE
444 if (TEMP_FAILURE_RETRY (ftruncate (s
->fd
, length
)) == -1)
447 #elif defined HAVE_CHSIZE
448 return chsize (s
->fd
, length
);
450 runtime_error ("required ftruncate or chsize support not present");
456 raw_close (unix_stream
*s
)
462 else if (s
->fd
!= STDOUT_FILENO
463 && s
->fd
!= STDERR_FILENO
464 && s
->fd
!= STDIN_FILENO
)
466 retval
= close (s
->fd
);
467 /* close() and EINTR is special, as the file descriptor is
468 deallocated before doing anything that might cause the
469 operation to be interrupted. Thus if we get EINTR the best we
470 can do is ignore it and continue (otherwise if we try again
471 the file descriptor may have been allocated again to some
473 if (retval
== -1 && errno
== EINTR
)
483 raw_markeor (unix_stream
*s
__attribute__ ((unused
)))
488 static const struct stream_vtable raw_vtable
= {
489 .read
= (void *) raw_read
,
490 .write
= (void *) raw_write
,
491 .seek
= (void *) raw_seek
,
492 .tell
= (void *) raw_tell
,
493 .size
= (void *) raw_size
,
494 .trunc
= (void *) raw_truncate
,
495 .close
= (void *) raw_close
,
496 .flush
= (void *) raw_flush
,
497 .markeor
= (void *) raw_markeor
501 raw_init (unix_stream
*s
)
503 s
->st
.vptr
= &raw_vtable
;
510 /*********************************************************************
511 Buffered I/O functions. These functions have the same semantics as the
512 raw I/O functions above, except that they are buffered in order to
513 improve performance. The buffer must be flushed when switching from
514 reading to writing and vice versa.
515 *********************************************************************/
518 buf_flush (unix_stream
*s
)
522 /* Flushing in read mode means discarding read bytes. */
528 if (s
->physical_offset
!= s
->buffer_offset
529 && raw_seek (s
, s
->buffer_offset
, SEEK_SET
) < 0)
532 writelen
= raw_write (s
, s
->buffer
, s
->ndirty
);
534 s
->physical_offset
= s
->buffer_offset
+ writelen
;
536 if (s
->physical_offset
> s
->file_length
)
537 s
->file_length
= s
->physical_offset
;
539 s
->ndirty
-= writelen
;
547 buf_read (unix_stream
*s
, void *buf
, ssize_t nbyte
)
550 s
->buffer_offset
= s
->logical_offset
;
552 /* Is the data we want in the buffer? */
553 if (s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ s
->active
554 && s
->buffer_offset
<= s
->logical_offset
)
556 /* When nbyte == 0, buf can be NULL which would lead to undefined
557 behavior if we called memcpy(). */
559 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
),
564 /* First copy the active bytes if applicable, then read the rest
565 either directly or filling the buffer. */
568 ssize_t to_read
, did_read
;
569 gfc_offset new_logical
;
572 if (s
->logical_offset
>= s
->buffer_offset
573 && s
->buffer_offset
+ s
->active
>= s
->logical_offset
)
575 nread
= s
->active
- (s
->logical_offset
- s
->buffer_offset
);
576 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
),
580 /* At this point we consider all bytes in the buffer discarded. */
581 to_read
= nbyte
- nread
;
582 new_logical
= s
->logical_offset
+ nread
;
583 if (s
->physical_offset
!= new_logical
584 && raw_seek (s
, new_logical
, SEEK_SET
) < 0)
586 s
->buffer_offset
= s
->physical_offset
= new_logical
;
587 if (to_read
<= BUFFER_SIZE
/2)
589 did_read
= raw_read (s
, s
->buffer
, BUFFER_SIZE
);
590 if (likely (did_read
>= 0))
592 s
->physical_offset
+= did_read
;
593 s
->active
= did_read
;
594 did_read
= (did_read
> to_read
) ? to_read
: did_read
;
595 memcpy (p
, s
->buffer
, did_read
);
602 did_read
= raw_read (s
, p
, to_read
);
603 if (likely (did_read
>= 0))
605 s
->physical_offset
+= did_read
;
611 nbyte
= did_read
+ nread
;
613 s
->logical_offset
+= nbyte
;
618 buf_write (unix_stream
*s
, const void *buf
, ssize_t nbyte
)
624 s
->buffer_offset
= s
->logical_offset
;
626 /* Does the data fit into the buffer? As a special case, if the
627 buffer is empty and the request is bigger than BUFFER_SIZE/2,
628 write directly. This avoids the case where the buffer would have
629 to be flushed at every write. */
630 if (!(s
->ndirty
== 0 && nbyte
> BUFFER_SIZE
/2)
631 && s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ BUFFER_SIZE
632 && s
->buffer_offset
<= s
->logical_offset
633 && s
->buffer_offset
+ s
->ndirty
>= s
->logical_offset
)
635 memcpy (s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
), buf
, nbyte
);
636 int nd
= (s
->logical_offset
- s
->buffer_offset
) + nbyte
;
642 /* Flush, and either fill the buffer with the new data, or if
643 the request is bigger than the buffer size, write directly
644 bypassing the buffer. */
646 if (nbyte
<= BUFFER_SIZE
/2)
648 memcpy (s
->buffer
, buf
, nbyte
);
649 s
->buffer_offset
= s
->logical_offset
;
654 if (s
->physical_offset
!= s
->logical_offset
)
656 if (raw_seek (s
, s
->logical_offset
, SEEK_SET
) < 0)
658 s
->physical_offset
= s
->logical_offset
;
661 nbyte
= raw_write (s
, buf
, nbyte
);
662 s
->physical_offset
+= nbyte
;
665 s
->logical_offset
+= nbyte
;
666 if (s
->logical_offset
> s
->file_length
)
667 s
->file_length
= s
->logical_offset
;
672 /* "Unbuffered" really means I/O statement buffering. For formatted
673 I/O, the fbuf manages this, and then uses raw I/O. For unformatted
674 I/O, buffered I/O is used, and the buffer is flushed at the end of
675 each I/O statement, where this function is called. Alternatively,
676 the buffer is flushed at the end of the record if the buffer is
677 more than half full; this prevents needless seeking back and forth
678 when writing sequential unformatted. */
681 buf_markeor (unix_stream
*s
)
683 if (s
->unbuffered
|| s
->ndirty
>= BUFFER_SIZE
/ 2)
684 return buf_flush (s
);
689 buf_seek (unix_stream
*s
, gfc_offset offset
, int whence
)
696 offset
+= s
->logical_offset
;
699 offset
+= s
->file_length
;
709 s
->logical_offset
= offset
;
714 buf_tell (unix_stream
*s
)
716 return buf_seek (s
, 0, SEEK_CUR
);
720 buf_size (unix_stream
*s
)
722 return s
->file_length
;
726 buf_truncate (unix_stream
*s
, gfc_offset length
)
730 if (buf_flush (s
) != 0)
732 r
= raw_truncate (s
, length
);
734 s
->file_length
= length
;
739 buf_close (unix_stream
*s
)
741 if (buf_flush (s
) != 0)
744 return raw_close (s
);
747 static const struct stream_vtable buf_vtable
= {
748 .read
= (void *) buf_read
,
749 .write
= (void *) buf_write
,
750 .seek
= (void *) buf_seek
,
751 .tell
= (void *) buf_tell
,
752 .size
= (void *) buf_size
,
753 .trunc
= (void *) buf_truncate
,
754 .close
= (void *) buf_close
,
755 .flush
= (void *) buf_flush
,
756 .markeor
= (void *) buf_markeor
760 buf_init (unix_stream
*s
)
762 s
->st
.vptr
= &buf_vtable
;
764 s
->buffer
= xmalloc (BUFFER_SIZE
);
769 /*********************************************************************
770 memory stream functions - These are used for internal files
772 The idea here is that a single stream structure is created and all
773 requests must be satisfied from it. The location and size of the
774 buffer is the character variable supplied to the READ or WRITE
777 *********************************************************************/
780 mem_alloc_r (stream
*strm
, size_t *len
)
782 unix_stream
*s
= (unix_stream
*) strm
;
784 gfc_offset where
= s
->logical_offset
;
786 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
789 n
= s
->buffer_offset
+ s
->active
- where
;
790 if ((gfc_offset
) *len
> n
)
793 s
->logical_offset
= where
+ *len
;
795 return s
->buffer
+ (where
- s
->buffer_offset
);
800 mem_alloc_r4 (stream
*strm
, size_t *len
)
802 unix_stream
*s
= (unix_stream
*) strm
;
804 gfc_offset where
= s
->logical_offset
;
806 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
809 n
= s
->buffer_offset
+ s
->active
- where
;
810 if ((gfc_offset
) *len
> n
)
813 s
->logical_offset
= where
+ *len
;
815 return s
->buffer
+ (where
- s
->buffer_offset
) * 4;
820 mem_alloc_w (stream
*strm
, size_t *len
)
822 unix_stream
*s
= (unix_stream
*)strm
;
824 gfc_offset where
= s
->logical_offset
;
828 if (where
< s
->buffer_offset
)
831 if (m
> s
->file_length
)
834 s
->logical_offset
= m
;
836 return s
->buffer
+ (where
- s
->buffer_offset
);
841 mem_alloc_w4 (stream
*strm
, size_t *len
)
843 unix_stream
*s
= (unix_stream
*)strm
;
845 gfc_offset where
= s
->logical_offset
;
846 gfc_char4_t
*result
= (gfc_char4_t
*) s
->buffer
;
850 if (where
< s
->buffer_offset
)
853 if (m
> s
->file_length
)
856 s
->logical_offset
= m
;
857 return &result
[where
- s
->buffer_offset
];
861 /* Stream read function for character(kind=1) internal units. */
864 mem_read (stream
*s
, void *buf
, ssize_t nbytes
)
869 p
= mem_alloc_r (s
, &nb
);
880 /* Stream read function for chracter(kind=4) internal units. */
883 mem_read4 (stream
*s
, void *buf
, ssize_t nbytes
)
888 p
= mem_alloc_r4 (s
, &nb
);
891 memcpy (buf
, p
, nb
* 4);
899 /* Stream write function for character(kind=1) internal units. */
902 mem_write (stream
*s
, const void *buf
, ssize_t nbytes
)
907 p
= mem_alloc_w (s
, &nb
);
918 /* Stream write function for character(kind=4) internal units. */
921 mem_write4 (stream
*s
, const void *buf
, ssize_t nwords
)
926 p
= mem_alloc_w4 (s
, &nw
);
930 *p
++ = (gfc_char4_t
) *((char *) buf
);
939 mem_seek (stream
*strm
, gfc_offset offset
, int whence
)
941 unix_stream
*s
= (unix_stream
*)strm
;
947 offset
+= s
->logical_offset
;
950 offset
+= s
->file_length
;
956 /* Note that for internal array I/O it's actually possible to have a
957 negative offset, so don't check for that. */
958 if (offset
> s
->file_length
)
964 s
->logical_offset
= offset
;
966 /* Returning < 0 is the error indicator for sseek(), so return 0 if
967 offset is negative. Thus if the return value is 0, the caller
968 has to use stell() to get the real value of logical_offset. */
978 return ((unix_stream
*)s
)->logical_offset
;
983 mem_truncate (unix_stream
*s
__attribute__ ((unused
)),
984 gfc_offset length
__attribute__ ((unused
)))
991 mem_flush (unix_stream
*s
__attribute__ ((unused
)))
998 mem_close (unix_stream
*s
)
1005 static const struct stream_vtable mem_vtable
= {
1006 .read
= (void *) mem_read
,
1007 .write
= (void *) mem_write
,
1008 .seek
= (void *) mem_seek
,
1009 .tell
= (void *) mem_tell
,
1010 /* buf_size is not a typo, we just reuse an identical
1012 .size
= (void *) buf_size
,
1013 .trunc
= (void *) mem_truncate
,
1014 .close
= (void *) mem_close
,
1015 .flush
= (void *) mem_flush
,
1016 .markeor
= (void *) raw_markeor
1019 static const struct stream_vtable mem4_vtable
= {
1020 .read
= (void *) mem_read4
,
1021 .write
= (void *) mem_write4
,
1022 .seek
= (void *) mem_seek
,
1023 .tell
= (void *) mem_tell
,
1024 /* buf_size is not a typo, we just reuse an identical
1026 .size
= (void *) buf_size
,
1027 .trunc
= (void *) mem_truncate
,
1028 .close
= (void *) mem_close
,
1029 .flush
= (void *) mem_flush
,
1030 .markeor
= (void *) raw_markeor
1033 /*********************************************************************
1034 Public functions -- A reimplementation of this module needs to
1035 define functional equivalents of the following.
1036 *********************************************************************/
1038 /* open_internal()-- Returns a stream structure from a character(kind=1)
1042 open_internal (char *base
, size_t length
, gfc_offset offset
)
1046 s
= xcalloc (1, sizeof (unix_stream
));
1049 s
->buffer_offset
= offset
;
1051 s
->active
= s
->file_length
= length
;
1053 s
->st
.vptr
= &mem_vtable
;
1055 return (stream
*) s
;
1058 /* open_internal4()-- Returns a stream structure from a character(kind=4)
1062 open_internal4 (char *base
, size_t length
, gfc_offset offset
)
1066 s
= xcalloc (1, sizeof (unix_stream
));
1069 s
->buffer_offset
= offset
;
1071 s
->active
= s
->file_length
= length
* sizeof (gfc_char4_t
);
1073 s
->st
.vptr
= &mem4_vtable
;
1079 /* fd_to_stream()-- Given an open file descriptor, build a stream
1083 fd_to_stream (int fd
, bool unformatted
)
1085 struct stat statbuf
;
1088 s
= xcalloc (1, sizeof (unix_stream
));
1092 /* Get the current length of the file. */
1094 if (TEMP_FAILURE_RETRY (fstat (fd
, &statbuf
)) == -1)
1096 s
->st_dev
= s
->st_ino
= -1;
1101 return (stream
*) s
;
1104 s
->st_dev
= statbuf
.st_dev
;
1105 s
->st_ino
= statbuf
.st_ino
;
1106 s
->file_length
= statbuf
.st_size
;
1108 /* Only use buffered IO for regular files. */
1109 if (S_ISREG (statbuf
.st_mode
)
1110 && !options
.all_unbuffered
1111 && !(options
.unbuffered_preconnected
&&
1112 (s
->fd
== STDIN_FILENO
1113 || s
->fd
== STDOUT_FILENO
1114 || s
->fd
== STDERR_FILENO
)))
1120 s
->unbuffered
= true;
1127 return (stream
*) s
;
1131 /* Given the Fortran unit number, convert it to a C file descriptor. */
1134 unit_to_fd (int unit
)
1139 us
= find_unit (unit
);
1143 fd
= ((unix_stream
*) us
->s
)->fd
;
1149 /* Set the close-on-exec flag for an existing fd, if the system
1152 static void __attribute__ ((unused
))
1153 set_close_on_exec (int fd
__attribute__ ((unused
)))
1155 /* Mingw does not define F_SETFD. */
1156 #if defined(HAVE_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
1158 fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
1163 /* Helper function for tempfile(). Tries to open a temporary file in
1164 the directory specified by tempdir. If successful, the file name is
1165 stored in fname and the descriptor returned. Returns -1 on
1169 tempfile_open (const char *tempdir
, char **fname
)
1172 const char *slash
= "/";
1173 #if defined(HAVE_UMASK) && defined(HAVE_MKSTEMP)
1180 /* Check for the special case that tempdir ends with a slash or
1182 size_t tempdirlen
= strlen (tempdir
);
1183 if (*tempdir
== 0 || tempdir
[tempdirlen
- 1] == '/'
1185 || tempdir
[tempdirlen
- 1] == '\\'
1190 /* Take care that the template is longer in the mktemp() branch. */
1191 char *template = xmalloc (tempdirlen
+ 23);
1194 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpXXXXXX",
1198 /* Temporarily set the umask such that the file has 0600 permissions. */
1199 mode_mask
= umask (S_IXUSR
| S_IRWXG
| S_IRWXO
);
1202 #if defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
1203 TEMP_FAILURE_RETRY (fd
= mkostemp (template, O_CLOEXEC
));
1205 TEMP_FAILURE_RETRY (fd
= mkstemp (template));
1206 set_close_on_exec (fd
);
1210 (void) umask (mode_mask
);
1213 #else /* HAVE_MKSTEMP */
1216 size_t slashlen
= strlen (slash
);
1217 int flags
= O_RDWR
| O_CREAT
| O_EXCL
;
1218 #if defined(HAVE_CRLF) && defined(O_BINARY)
1226 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpaaaXXXXXX",
1231 template[tempdirlen
+ slashlen
+ 13] = 'a' + (c
% 26);
1233 template[tempdirlen
+ slashlen
+ 12] = 'a' + (c
% 26);
1235 template[tempdirlen
+ slashlen
+ 11] = 'a' + (c
% 26);
1240 if (!mktemp (template))
1247 TEMP_FAILURE_RETRY (fd
= open (template, flags
, S_IRUSR
| S_IWUSR
));
1249 while (fd
== -1 && errno
== EEXIST
);
1251 set_close_on_exec (fd
);
1253 #endif /* HAVE_MKSTEMP */
1260 /* tempfile()-- Generate a temporary filename for a scratch file and
1261 open it. mkstemp() opens the file for reading and writing, but the
1262 library mode prevents anything that is not allowed. The descriptor
1263 is returned, which is -1 on error. The template is pointed to by
1264 opp->file, which is copied into the unit structure
1268 tempfile (st_parameter_open
*opp
)
1270 const char *tempdir
;
1274 tempdir
= secure_getenv ("TMPDIR");
1275 fd
= tempfile_open (tempdir
, &fname
);
1279 char buffer
[MAX_PATH
+ 1];
1281 ret
= GetTempPath (MAX_PATH
, buffer
);
1282 /* If we are not able to get a temp-directory, we use
1283 current directory. */
1284 if (ret
> MAX_PATH
|| !ret
)
1288 tempdir
= strdup (buffer
);
1289 fd
= tempfile_open (tempdir
, &fname
);
1291 #elif defined(__CYGWIN__)
1294 tempdir
= secure_getenv ("TMP");
1295 fd
= tempfile_open (tempdir
, &fname
);
1299 tempdir
= secure_getenv ("TEMP");
1300 fd
= tempfile_open (tempdir
, &fname
);
1304 fd
= tempfile_open (P_tmpdir
, &fname
);
1307 opp
->file_len
= strlen (fname
); /* Don't include trailing nul */
1313 /* regular_file2()-- Open a regular file.
1314 Change flags->action if it is ACTION_UNSPECIFIED on entry,
1315 unless an error occurs.
1316 Returns the descriptor, which is less than zero on error. */
1319 regular_file2 (const char *path
, st_parameter_open
*opp
, unit_flags
*flags
)
1323 int crflag
, crflag2
;
1327 if (opp
->file_len
== 7)
1329 if (strncmp (path
, "CONOUT$", 7) == 0
1330 || strncmp (path
, "CONERR$", 7) == 0)
1332 fd
= open ("/dev/conout", O_WRONLY
);
1333 flags
->action
= ACTION_WRITE
;
1338 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1340 fd
= open ("/dev/conin", O_RDONLY
);
1341 flags
->action
= ACTION_READ
;
1348 if (opp
->file_len
== 7)
1350 if (strncmp (path
, "CONOUT$", 7) == 0
1351 || strncmp (path
, "CONERR$", 7) == 0)
1353 fd
= open ("CONOUT$", O_WRONLY
);
1354 flags
->action
= ACTION_WRITE
;
1359 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1361 fd
= open ("CONIN$", O_RDONLY
);
1362 flags
->action
= ACTION_READ
;
1367 switch (flags
->action
)
1377 case ACTION_READWRITE
:
1378 case ACTION_UNSPECIFIED
:
1383 internal_error (&opp
->common
, "regular_file(): Bad action");
1386 switch (flags
->status
)
1389 crflag
= O_CREAT
| O_EXCL
;
1392 case STATUS_OLD
: /* open will fail if the file does not exist*/
1396 case STATUS_UNKNOWN
:
1397 if (rwflag
== O_RDONLY
)
1403 case STATUS_REPLACE
:
1404 crflag
= O_CREAT
| O_TRUNC
;
1408 /* Note: STATUS_SCRATCH is handled by tempfile () and should
1409 never be seen here. */
1410 internal_error (&opp
->common
, "regular_file(): Bad status");
1413 /* rwflag |= O_LARGEFILE; */
1415 #if defined(HAVE_CRLF) && defined(O_BINARY)
1420 crflag
|= O_CLOEXEC
;
1423 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
;
1424 TEMP_FAILURE_RETRY (fd
= open (path
, rwflag
| crflag
, mode
));
1425 if (flags
->action
!= ACTION_UNSPECIFIED
)
1430 flags
->action
= ACTION_READWRITE
;
1433 if (errno
!= EACCES
&& errno
!= EPERM
&& errno
!= EROFS
)
1436 /* retry for read-only access */
1438 if (flags
->status
== STATUS_UNKNOWN
)
1439 crflag2
= crflag
& ~(O_CREAT
);
1442 TEMP_FAILURE_RETRY (fd
= open (path
, rwflag
| crflag2
, mode
));
1445 flags
->action
= ACTION_READ
;
1446 return fd
; /* success */
1449 if (errno
!= EACCES
&& errno
!= EPERM
&& errno
!= ENOENT
)
1450 return fd
; /* failure */
1452 /* retry for write-only access */
1454 TEMP_FAILURE_RETRY (fd
= open (path
, rwflag
| crflag
, mode
));
1457 flags
->action
= ACTION_WRITE
;
1458 return fd
; /* success */
1460 return fd
; /* failure */
1464 /* Lock the file, if necessary, based on SHARE flags. */
1466 #if defined(HAVE_FCNTL) && defined(F_SETLK) && defined(F_UNLCK)
1468 open_share (st_parameter_open
*opp
, int fd
, unit_flags
*flags
)
1472 if (fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
|| fd
== STDIN_FILENO
)
1477 f
.l_whence
= SEEK_SET
;
1479 switch (flags
->share
)
1481 case SHARE_DENYNONE
:
1483 r
= fcntl (fd
, F_SETLK
, &f
);
1486 /* Must be writable to hold write lock. */
1487 if (flags
->action
== ACTION_READ
)
1489 generate_error (&opp
->common
, LIBERROR_BAD_ACTION
,
1490 "Cannot set write lock on file opened for READ");
1494 r
= fcntl (fd
, F_SETLK
, &f
);
1496 case SHARE_UNSPECIFIED
:
1505 open_share (st_parameter_open
*opp
__attribute__ ((unused
)),
1506 int fd
__attribute__ ((unused
)),
1507 unit_flags
*flags
__attribute__ ((unused
)))
1511 #endif /* defined(HAVE_FCNTL) ... */
1514 /* Wrapper around regular_file2, to make sure we free the path after
1518 regular_file (st_parameter_open
*opp
, unit_flags
*flags
)
1520 char *path
= fc_strdup (opp
->file
, opp
->file_len
);
1521 int fd
= regular_file2 (path
, opp
, flags
);
1526 /* open_external()-- Open an external file, unix specific version.
1527 Change flags->action if it is ACTION_UNSPECIFIED on entry.
1528 Returns NULL on operating system error. */
1531 open_external (st_parameter_open
*opp
, unit_flags
*flags
)
1535 if (flags
->status
== STATUS_SCRATCH
)
1537 fd
= tempfile (opp
);
1538 if (flags
->action
== ACTION_UNSPECIFIED
)
1539 flags
->action
= flags
->readonly
? ACTION_READ
: ACTION_READWRITE
;
1541 #if HAVE_UNLINK_OPEN_FILE
1542 /* We can unlink scratch files now and it will go away when closed. */
1549 /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1551 fd
= regular_file (opp
, flags
);
1553 set_close_on_exec (fd
);
1561 if (open_share (opp
, fd
, flags
) < 0)
1564 return fd_to_stream (fd
, flags
->form
== FORM_UNFORMATTED
);
1568 /* input_stream()-- Return a stream pointer to the default input stream.
1569 Called on initialization. */
1574 return fd_to_stream (STDIN_FILENO
, false);
1578 /* output_stream()-- Return a stream pointer to the default output stream.
1579 Called on initialization. */
1582 output_stream (void)
1586 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1587 setmode (STDOUT_FILENO
, O_BINARY
);
1590 s
= fd_to_stream (STDOUT_FILENO
, false);
1595 /* error_stream()-- Return a stream pointer to the default error stream.
1596 Called on initialization. */
1603 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1604 setmode (STDERR_FILENO
, O_BINARY
);
1607 s
= fd_to_stream (STDERR_FILENO
, false);
1612 /* compare_file_filename()-- Given an open stream and a fortran string
1613 that is a filename, figure out if the file is the same as the
1617 compare_file_filename (gfc_unit
*u
, const char *name
, int len
)
1621 #ifdef HAVE_WORKING_STAT
1629 char *path
= fc_strdup (name
, len
);
1631 /* If the filename doesn't exist, then there is no match with the
1634 if (TEMP_FAILURE_RETRY (stat (path
, &st
)) < 0)
1640 #ifdef HAVE_WORKING_STAT
1641 s
= (unix_stream
*) (u
->s
);
1642 ret
= (st
.st_dev
== s
->st_dev
) && (st
.st_ino
== s
->st_ino
);
1647 /* We try to match files by a unique ID. On some filesystems (network
1648 fs and FAT), we can't generate this unique ID, and will simply compare
1650 id1
= id_from_path (path
);
1651 id2
= id_from_fd (((unix_stream
*) (u
->s
))->fd
);
1659 ret
= (strcmp(path
, u
->filename
) == 0);
1669 #ifdef HAVE_WORKING_STAT
1670 # define FIND_FILE0_DECL struct stat *st
1671 # define FIND_FILE0_ARGS st
1673 # define FIND_FILE0_DECL uint64_t id, const char *path
1674 # define FIND_FILE0_ARGS id, path
1677 /* find_file0()-- Recursive work function for find_file() */
1680 find_file0 (gfc_unit
*u
, FIND_FILE0_DECL
)
1683 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1690 #ifdef HAVE_WORKING_STAT
1693 unix_stream
*s
= (unix_stream
*) (u
->s
);
1694 if (st
[0].st_dev
== s
->st_dev
&& st
[0].st_ino
== s
->st_ino
)
1699 if (u
->s
&& ((id1
= id_from_fd (((unix_stream
*) u
->s
)->fd
)) || id1
))
1706 if (u
->filename
&& strcmp (u
->filename
, path
) == 0)
1710 v
= find_file0 (u
->left
, FIND_FILE0_ARGS
);
1714 v
= find_file0 (u
->right
, FIND_FILE0_ARGS
);
1722 /* find_file()-- Take the current filename and see if there is a unit
1723 that has the file already open. Returns a pointer to the unit if so. */
1726 find_file (const char *file
, gfc_charlen_type file_len
)
1730 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1734 char *path
= fc_strdup (file
, file_len
);
1736 if (TEMP_FAILURE_RETRY (stat (path
, &st
[0])) < 0)
1742 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1743 id
= id_from_path (path
);
1748 u
= find_file0 (unit_root
, FIND_FILE0_ARGS
);
1752 if (! __gthread_mutex_trylock (&u
->lock
))
1754 /* assert (u->closed == 0); */
1755 UNLOCK (&unit_lock
);
1759 inc_waiting_locked (u
);
1761 UNLOCK (&unit_lock
);
1769 if (predec_waiting_locked (u
) == 0)
1774 dec_waiting_unlocked (u
);
1782 flush_all_units_1 (gfc_unit
*u
, int min_unit
)
1786 if (u
->unit_number
> min_unit
)
1788 gfc_unit
*r
= flush_all_units_1 (u
->left
, min_unit
);
1792 if (u
->unit_number
>= min_unit
)
1794 if (__gthread_mutex_trylock (&u
->lock
))
1806 flush_all_units (void)
1814 u
= flush_all_units_1 (unit_root
, min_unit
);
1816 inc_waiting_locked (u
);
1817 UNLOCK (&unit_lock
);
1823 min_unit
= u
->unit_number
+ 1;
1830 (void) predec_waiting_locked (u
);
1836 if (predec_waiting_locked (u
) == 0)
1844 /* Unlock the unit if necessary, based on SHARE flags. */
1847 close_share (gfc_unit
*u
__attribute__ ((unused
)))
1850 #if defined(HAVE_FCNTL) && defined(F_SETLK) && defined(F_UNLCK)
1851 unix_stream
*s
= (unix_stream
*) u
->s
;
1855 switch (u
->flags
.share
)
1858 case SHARE_DENYNONE
:
1859 if (fd
!= STDOUT_FILENO
&& fd
!= STDERR_FILENO
&& fd
!= STDIN_FILENO
)
1863 f
.l_whence
= SEEK_SET
;
1865 r
= fcntl (fd
, F_SETLK
, &f
);
1868 case SHARE_UNSPECIFIED
:
1878 /* file_exists()-- Returns nonzero if the current filename exists on
1882 file_exists (const char *file
, gfc_charlen_type file_len
)
1884 char *path
= fc_strdup (file
, file_len
);
1885 int res
= !(access (path
, F_OK
));
1891 /* file_size()-- Returns the size of the file. */
1894 file_size (const char *file
, gfc_charlen_type file_len
)
1896 char *path
= fc_strdup (file
, file_len
);
1897 struct stat statbuf
;
1899 TEMP_FAILURE_RETRY (err
= stat (path
, &statbuf
));
1903 return (GFC_IO_INT
) statbuf
.st_size
;
1906 static const char yes
[] = "YES", no
[] = "NO", unknown
[] = "UNKNOWN";
1908 /* inquire_sequential()-- Given a fortran string, determine if the
1909 file is suitable for sequential access. Returns a C-style
1913 inquire_sequential (const char *string
, int len
)
1915 struct stat statbuf
;
1920 char *path
= fc_strdup (string
, len
);
1922 TEMP_FAILURE_RETRY (err
= stat (path
, &statbuf
));
1927 if (S_ISREG (statbuf
.st_mode
) ||
1928 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1931 if (S_ISDIR (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1938 /* inquire_direct()-- Given a fortran string, determine if the file is
1939 suitable for direct access. Returns a C-style string. */
1942 inquire_direct (const char *string
, int len
)
1944 struct stat statbuf
;
1949 char *path
= fc_strdup (string
, len
);
1951 TEMP_FAILURE_RETRY (err
= stat (path
, &statbuf
));
1956 if (S_ISREG (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1959 if (S_ISDIR (statbuf
.st_mode
) ||
1960 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1967 /* inquire_formatted()-- Given a fortran string, determine if the file
1968 is suitable for formatted form. Returns a C-style string. */
1971 inquire_formatted (const char *string
, int len
)
1973 struct stat statbuf
;
1978 char *path
= fc_strdup (string
, len
);
1980 TEMP_FAILURE_RETRY (err
= stat (path
, &statbuf
));
1985 if (S_ISREG (statbuf
.st_mode
) ||
1986 S_ISBLK (statbuf
.st_mode
) ||
1987 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1990 if (S_ISDIR (statbuf
.st_mode
))
1997 /* inquire_unformatted()-- Given a fortran string, determine if the file
1998 is suitable for unformatted form. Returns a C-style string. */
2001 inquire_unformatted (const char *string
, int len
)
2003 return inquire_formatted (string
, len
);
2007 /* inquire_access()-- Given a fortran string, determine if the file is
2008 suitable for access. */
2011 inquire_access (const char *string
, int len
, int mode
)
2015 char *path
= fc_strdup (string
, len
);
2016 int res
= access (path
, mode
);
2025 /* inquire_read()-- Given a fortran string, determine if the file is
2026 suitable for READ access. */
2029 inquire_read (const char *string
, int len
)
2031 return inquire_access (string
, len
, R_OK
);
2035 /* inquire_write()-- Given a fortran string, determine if the file is
2036 suitable for READ access. */
2039 inquire_write (const char *string
, int len
)
2041 return inquire_access (string
, len
, W_OK
);
2045 /* inquire_readwrite()-- Given a fortran string, determine if the file is
2046 suitable for read and write access. */
2049 inquire_readwrite (const char *string
, int len
)
2051 return inquire_access (string
, len
, R_OK
| W_OK
);
2056 stream_isatty (stream
*s
)
2058 return isatty (((unix_stream
*) s
)->fd
);
2062 stream_ttyname (stream
*s
__attribute__ ((unused
)),
2063 char *buf
__attribute__ ((unused
)),
2064 size_t buflen
__attribute__ ((unused
)))
2066 #ifdef HAVE_TTYNAME_R
2067 return ttyname_r (((unix_stream
*)s
)->fd
, buf
, buflen
);
2068 #elif defined HAVE_TTYNAME
2071 p
= ttyname (((unix_stream
*)s
)->fd
);
2077 memcpy (buf
, p
, plen
);
2087 /* How files are stored: This is an operating-system specific issue,
2088 and therefore belongs here. There are three cases to consider.
2091 Records are written as block of bytes corresponding to the record
2092 length of the file. This goes for both formatted and unformatted
2093 records. Positioning is done explicitly for each data transfer,
2094 so positioning is not much of an issue.
2096 Sequential Formatted:
2097 Records are separated by newline characters. The newline character
2098 is prohibited from appearing in a string. If it does, this will be
2099 messed up on the next read. End of file is also the end of a record.
2101 Sequential Unformatted:
2102 In this case, we are merely copying bytes to and from main storage,
2103 yet we need to keep track of varying record lengths. We adopt
2104 the solution used by f2c. Each record contains a pair of length
2107 Length of record n in bytes
2109 Length of record n in bytes
2111 Length of record n+1 in bytes
2113 Length of record n+1 in bytes
2115 The length is stored at the end of a record to allow backspacing to the
2116 previous record. Between data transfer statements, the file pointer
2117 is left pointing to the first length of the current record.
2119 ENDFILE records are never explicitly stored.