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 */
43 /* For mingw, we don't identify files by their inode number, but by a
44 64-bit identifier created from a BY_HANDLE_FILE_INFORMATION. */
47 #define WIN32_LEAN_AND_MEAN
50 #if !defined(_FILE_OFFSET_BITS) || _FILE_OFFSET_BITS != 64
52 #define lseek _lseeki64
54 #define fstat _fstati64
59 #ifndef HAVE_WORKING_STAT
61 id_from_handle (HANDLE hFile
)
63 BY_HANDLE_FILE_INFORMATION FileInformation
;
65 if (hFile
== INVALID_HANDLE_VALUE
)
68 memset (&FileInformation
, 0, sizeof(FileInformation
));
69 if (!GetFileInformationByHandle (hFile
, &FileInformation
))
72 return ((uint64_t) FileInformation
.nFileIndexLow
)
73 | (((uint64_t) FileInformation
.nFileIndexHigh
) << 32);
78 id_from_path (const char *path
)
83 if (!path
|| !*path
|| access (path
, F_OK
))
86 hFile
= CreateFile (path
, 0, 0, NULL
, OPEN_EXISTING
,
87 FILE_FLAG_BACKUP_SEMANTICS
| FILE_ATTRIBUTE_READONLY
,
89 res
= id_from_handle (hFile
);
96 id_from_fd (const int fd
)
98 return id_from_handle ((HANDLE
) _get_osfhandle (fd
));
101 #endif /* HAVE_WORKING_STAT */
104 /* On mingw, we don't use umask in tempfile_open(), because it
105 doesn't support the user/group/other-based permissions. */
108 #endif /* __MINGW32__ */
111 /* These flags aren't defined on all targets (mingw32), so provide them
144 /* Fallback implementation of access() on systems that don't have it.
145 Only modes R_OK, W_OK and F_OK are used in this file. */
148 fallback_access (const char *path
, int mode
)
152 if ((mode
& R_OK
) && (fd
= open (path
, O_RDONLY
)) < 0)
156 if ((mode
& W_OK
) && (fd
= open (path
, O_WRONLY
)) < 0)
163 return stat (path
, &st
);
170 #define access fallback_access
174 /* Fallback directory for creating temporary files. P_tmpdir is
175 defined on many POSIX platforms. */
178 #define P_tmpdir _P_tmpdir /* MinGW */
180 #define P_tmpdir "/tmp"
185 /* Unix and internal stream I/O module */
187 static const int BUFFER_SIZE
= 8192;
193 gfc_offset buffer_offset
; /* File offset of the start of the buffer */
194 gfc_offset physical_offset
; /* Current physical file offset */
195 gfc_offset logical_offset
; /* Current logical file offset */
196 gfc_offset file_length
; /* Length of the file. */
198 char *buffer
; /* Pointer to the buffer. */
199 int fd
; /* The POSIX file descriptor. */
201 int active
; /* Length of valid bytes in the buffer */
203 int ndirty
; /* Dirty bytes starting at buffer_offset */
205 /* Cached stat(2) values. */
209 bool unbuffered
; /* Buffer should be flushed after each I/O statement. */
214 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
215 standard descriptors, returning a non-standard descriptor. If the
216 user specifies that system errors should go to standard output,
217 then closes standard output, we don't want the system errors to a
218 file that has been given file descriptor 1 or 0. We want to send
219 the error to the invalid descriptor. */
225 int input
, output
, error
;
227 input
= output
= error
= 0;
229 /* Unix allocates the lowest descriptors first, so a loop is not
230 required, but this order is. */
231 if (fd
== STDIN_FILENO
)
236 if (fd
== STDOUT_FILENO
)
241 if (fd
== STDERR_FILENO
)
248 close (STDIN_FILENO
);
250 close (STDOUT_FILENO
);
252 close (STDERR_FILENO
);
259 /* If the stream corresponds to a preconnected unit, we flush the
260 corresponding C stream. This is bugware for mixed C-Fortran codes
261 where the C code doesn't flush I/O before returning. */
263 flush_if_preconnected (stream
*s
)
267 fd
= ((unix_stream
*) s
)->fd
;
268 if (fd
== STDIN_FILENO
)
270 else if (fd
== STDOUT_FILENO
)
272 else if (fd
== STDERR_FILENO
)
277 /********************************************************************
278 Raw I/O functions (read, write, seek, tell, truncate, close).
280 These functions wrap the basic POSIX I/O syscalls. Any deviation in
281 semantics is a bug, except the following: write restarts in case
282 of being interrupted by a signal, and as the first argument the
283 functions take the unix_stream struct rather than an integer file
284 descriptor. Also, for POSIX read() and write() a nbyte argument larger
285 than SSIZE_MAX is undefined; here the type of nbyte is ssize_t rather
286 than size_t as for POSIX read/write.
287 *********************************************************************/
290 raw_flush (unix_stream
*s
__attribute__ ((unused
)))
295 /* Write/read at most 2 GB - 4k chunks at a time. Linux never reads or
296 writes more than this, and there are reports that macOS fails for
297 larger than 2 GB as well. */
298 #define MAX_CHUNK 2147479552
301 raw_read (unix_stream
*s
, void *buf
, ssize_t nbyte
)
303 /* For read we can't do I/O in a loop like raw_write does, because
304 that will break applications that wait for interactive I/O. We
305 still can loop around EINTR, though. This however causes a
306 problem for large reads which must be chunked, see comment above.
307 So assume that if the size is larger than the chunk size, we're
308 reading from a file and not the terminal. */
309 if (nbyte
<= MAX_CHUNK
)
313 ssize_t trans
= read (s
->fd
, buf
, nbyte
);
314 if (trans
== -1 && errno
== EINTR
)
321 ssize_t bytes_left
= nbyte
;
323 while (bytes_left
> 0)
325 ssize_t to_read
= bytes_left
< MAX_CHUNK
? bytes_left
: MAX_CHUNK
;
326 ssize_t trans
= read (s
->fd
, buf_st
, to_read
);
337 return nbyte
- bytes_left
;
342 raw_write (unix_stream
*s
, const void *buf
, ssize_t nbyte
)
344 ssize_t trans
, bytes_left
;
348 buf_st
= (char *) buf
;
350 /* We must write in a loop since some systems don't restart system
351 calls in case of a signal. Also some systems might fail outright
352 if we try to write more than 2 GB in a single syscall, so chunk
354 while (bytes_left
> 0)
356 ssize_t to_write
= bytes_left
< MAX_CHUNK
? bytes_left
: MAX_CHUNK
;
357 trans
= write (s
->fd
, buf_st
, to_write
);
369 return nbyte
- bytes_left
;
373 raw_seek (unix_stream
*s
, gfc_offset offset
, int whence
)
377 gfc_offset off
= lseek (s
->fd
, offset
, whence
);
378 if (off
== (gfc_offset
) -1 && errno
== EINTR
)
385 raw_tell (unix_stream
*s
)
389 gfc_offset off
= lseek (s
->fd
, 0, SEEK_CUR
);
390 if (off
== (gfc_offset
) -1 && errno
== EINTR
)
397 raw_size (unix_stream
*s
)
400 if (TEMP_FAILURE_RETRY (fstat (s
->fd
, &statbuf
)) == -1)
402 if (S_ISREG (statbuf
.st_mode
))
403 return statbuf
.st_size
;
409 raw_truncate (unix_stream
*s
, gfc_offset length
)
420 h
= (HANDLE
) _get_osfhandle (s
->fd
);
421 if (h
== INVALID_HANDLE_VALUE
)
426 cur
= lseek (s
->fd
, 0, SEEK_CUR
);
429 if (lseek (s
->fd
, length
, SEEK_SET
) == -1)
431 if (!SetEndOfFile (h
))
436 if (lseek (s
->fd
, cur
, SEEK_SET
) == -1)
440 lseek (s
->fd
, cur
, SEEK_SET
);
442 #elif defined HAVE_FTRUNCATE
443 if (TEMP_FAILURE_RETRY (ftruncate (s
->fd
, length
)) == -1)
446 #elif defined HAVE_CHSIZE
447 return chsize (s
->fd
, length
);
449 runtime_error ("required ftruncate or chsize support not present");
455 raw_close (unix_stream
*s
)
461 else if (s
->fd
!= STDOUT_FILENO
462 && s
->fd
!= STDERR_FILENO
463 && s
->fd
!= STDIN_FILENO
)
465 retval
= close (s
->fd
);
466 /* close() and EINTR is special, as the file descriptor is
467 deallocated before doing anything that might cause the
468 operation to be interrupted. Thus if we get EINTR the best we
469 can do is ignore it and continue (otherwise if we try again
470 the file descriptor may have been allocated again to some
472 if (retval
== -1 && errno
== EINTR
)
482 raw_markeor (unix_stream
*s
__attribute__ ((unused
)))
487 static const struct stream_vtable raw_vtable
= {
488 .read
= (void *) raw_read
,
489 .write
= (void *) raw_write
,
490 .seek
= (void *) raw_seek
,
491 .tell
= (void *) raw_tell
,
492 .size
= (void *) raw_size
,
493 .trunc
= (void *) raw_truncate
,
494 .close
= (void *) raw_close
,
495 .flush
= (void *) raw_flush
,
496 .markeor
= (void *) raw_markeor
500 raw_init (unix_stream
*s
)
502 s
->st
.vptr
= &raw_vtable
;
509 /*********************************************************************
510 Buffered I/O functions. These functions have the same semantics as the
511 raw I/O functions above, except that they are buffered in order to
512 improve performance. The buffer must be flushed when switching from
513 reading to writing and vice versa.
514 *********************************************************************/
517 buf_flush (unix_stream
*s
)
521 /* Flushing in read mode means discarding read bytes. */
527 if (s
->physical_offset
!= s
->buffer_offset
528 && raw_seek (s
, s
->buffer_offset
, SEEK_SET
) < 0)
531 writelen
= raw_write (s
, s
->buffer
, s
->ndirty
);
533 s
->physical_offset
= s
->buffer_offset
+ writelen
;
535 if (s
->physical_offset
> s
->file_length
)
536 s
->file_length
= s
->physical_offset
;
538 s
->ndirty
-= writelen
;
546 buf_read (unix_stream
*s
, void *buf
, ssize_t nbyte
)
549 s
->buffer_offset
= s
->logical_offset
;
551 /* Is the data we want in the buffer? */
552 if (s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ s
->active
553 && s
->buffer_offset
<= s
->logical_offset
)
555 /* When nbyte == 0, buf can be NULL which would lead to undefined
556 behavior if we called memcpy(). */
558 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
),
563 /* First copy the active bytes if applicable, then read the rest
564 either directly or filling the buffer. */
567 ssize_t to_read
, did_read
;
568 gfc_offset new_logical
;
571 if (s
->logical_offset
>= s
->buffer_offset
572 && s
->buffer_offset
+ s
->active
>= s
->logical_offset
)
574 nread
= s
->active
- (s
->logical_offset
- s
->buffer_offset
);
575 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
),
579 /* At this point we consider all bytes in the buffer discarded. */
580 to_read
= nbyte
- nread
;
581 new_logical
= s
->logical_offset
+ nread
;
582 if (s
->physical_offset
!= new_logical
583 && raw_seek (s
, new_logical
, SEEK_SET
) < 0)
585 s
->buffer_offset
= s
->physical_offset
= new_logical
;
586 if (to_read
<= BUFFER_SIZE
/2)
588 did_read
= raw_read (s
, s
->buffer
, BUFFER_SIZE
);
589 if (likely (did_read
>= 0))
591 s
->physical_offset
+= did_read
;
592 s
->active
= did_read
;
593 did_read
= (did_read
> to_read
) ? to_read
: did_read
;
594 memcpy (p
, s
->buffer
, did_read
);
601 did_read
= raw_read (s
, p
, to_read
);
602 if (likely (did_read
>= 0))
604 s
->physical_offset
+= did_read
;
610 nbyte
= did_read
+ nread
;
612 s
->logical_offset
+= nbyte
;
617 buf_write (unix_stream
*s
, const void *buf
, ssize_t nbyte
)
623 s
->buffer_offset
= s
->logical_offset
;
625 /* Does the data fit into the buffer? As a special case, if the
626 buffer is empty and the request is bigger than BUFFER_SIZE/2,
627 write directly. This avoids the case where the buffer would have
628 to be flushed at every write. */
629 if (!(s
->ndirty
== 0 && nbyte
> BUFFER_SIZE
/2)
630 && s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ BUFFER_SIZE
631 && s
->buffer_offset
<= s
->logical_offset
632 && s
->buffer_offset
+ s
->ndirty
>= s
->logical_offset
)
634 memcpy (s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
), buf
, nbyte
);
635 int nd
= (s
->logical_offset
- s
->buffer_offset
) + nbyte
;
641 /* Flush, and either fill the buffer with the new data, or if
642 the request is bigger than the buffer size, write directly
643 bypassing the buffer. */
645 if (nbyte
<= BUFFER_SIZE
/2)
647 memcpy (s
->buffer
, buf
, nbyte
);
648 s
->buffer_offset
= s
->logical_offset
;
653 if (s
->physical_offset
!= s
->logical_offset
)
655 if (raw_seek (s
, s
->logical_offset
, SEEK_SET
) < 0)
657 s
->physical_offset
= s
->logical_offset
;
660 nbyte
= raw_write (s
, buf
, nbyte
);
661 s
->physical_offset
+= nbyte
;
664 s
->logical_offset
+= nbyte
;
665 if (s
->logical_offset
> s
->file_length
)
666 s
->file_length
= s
->logical_offset
;
671 /* "Unbuffered" really means I/O statement buffering. For formatted
672 I/O, the fbuf manages this, and then uses raw I/O. For unformatted
673 I/O, buffered I/O is used, and the buffer is flushed at the end of
674 each I/O statement, where this function is called. Alternatively,
675 the buffer is flushed at the end of the record if the buffer is
676 more than half full; this prevents needless seeking back and forth
677 when writing sequential unformatted. */
680 buf_markeor (unix_stream
*s
)
682 if (s
->unbuffered
|| s
->ndirty
>= BUFFER_SIZE
/ 2)
683 return buf_flush (s
);
688 buf_seek (unix_stream
*s
, gfc_offset offset
, int whence
)
695 offset
+= s
->logical_offset
;
698 offset
+= s
->file_length
;
708 s
->logical_offset
= offset
;
713 buf_tell (unix_stream
*s
)
715 return buf_seek (s
, 0, SEEK_CUR
);
719 buf_size (unix_stream
*s
)
721 return s
->file_length
;
725 buf_truncate (unix_stream
*s
, gfc_offset length
)
729 if (buf_flush (s
) != 0)
731 r
= raw_truncate (s
, length
);
733 s
->file_length
= length
;
738 buf_close (unix_stream
*s
)
740 if (buf_flush (s
) != 0)
743 return raw_close (s
);
746 static const struct stream_vtable buf_vtable
= {
747 .read
= (void *) buf_read
,
748 .write
= (void *) buf_write
,
749 .seek
= (void *) buf_seek
,
750 .tell
= (void *) buf_tell
,
751 .size
= (void *) buf_size
,
752 .trunc
= (void *) buf_truncate
,
753 .close
= (void *) buf_close
,
754 .flush
= (void *) buf_flush
,
755 .markeor
= (void *) buf_markeor
759 buf_init (unix_stream
*s
)
761 s
->st
.vptr
= &buf_vtable
;
763 s
->buffer
= xmalloc (BUFFER_SIZE
);
768 /*********************************************************************
769 memory stream functions - These are used for internal files
771 The idea here is that a single stream structure is created and all
772 requests must be satisfied from it. The location and size of the
773 buffer is the character variable supplied to the READ or WRITE
776 *********************************************************************/
779 mem_alloc_r (stream
*strm
, size_t *len
)
781 unix_stream
*s
= (unix_stream
*) strm
;
783 gfc_offset where
= s
->logical_offset
;
785 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
788 n
= s
->buffer_offset
+ s
->active
- where
;
789 if ((gfc_offset
) *len
> n
)
792 s
->logical_offset
= where
+ *len
;
794 return s
->buffer
+ (where
- s
->buffer_offset
);
799 mem_alloc_r4 (stream
*strm
, size_t *len
)
801 unix_stream
*s
= (unix_stream
*) strm
;
803 gfc_offset where
= s
->logical_offset
;
805 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
808 n
= s
->buffer_offset
+ s
->active
- where
;
809 if ((gfc_offset
) *len
> n
)
812 s
->logical_offset
= where
+ *len
;
814 return s
->buffer
+ (where
- s
->buffer_offset
) * 4;
819 mem_alloc_w (stream
*strm
, size_t *len
)
821 unix_stream
*s
= (unix_stream
*)strm
;
823 gfc_offset where
= s
->logical_offset
;
827 if (where
< s
->buffer_offset
)
830 if (m
> s
->file_length
)
833 s
->logical_offset
= m
;
835 return s
->buffer
+ (where
- s
->buffer_offset
);
840 mem_alloc_w4 (stream
*strm
, size_t *len
)
842 unix_stream
*s
= (unix_stream
*)strm
;
844 gfc_offset where
= s
->logical_offset
;
845 gfc_char4_t
*result
= (gfc_char4_t
*) s
->buffer
;
849 if (where
< s
->buffer_offset
)
852 if (m
> s
->file_length
)
855 s
->logical_offset
= m
;
856 return &result
[where
- s
->buffer_offset
];
860 /* Stream read function for character(kind=1) internal units. */
863 mem_read (stream
*s
, void *buf
, ssize_t nbytes
)
868 p
= mem_alloc_r (s
, &nb
);
879 /* Stream read function for chracter(kind=4) internal units. */
882 mem_read4 (stream
*s
, void *buf
, ssize_t nbytes
)
887 p
= mem_alloc_r4 (s
, &nb
);
890 memcpy (buf
, p
, nb
* 4);
898 /* Stream write function for character(kind=1) internal units. */
901 mem_write (stream
*s
, const void *buf
, ssize_t nbytes
)
906 p
= mem_alloc_w (s
, &nb
);
917 /* Stream write function for character(kind=4) internal units. */
920 mem_write4 (stream
*s
, const void *buf
, ssize_t nwords
)
925 p
= mem_alloc_w4 (s
, &nw
);
929 *p
++ = (gfc_char4_t
) *((char *) buf
);
938 mem_seek (stream
*strm
, gfc_offset offset
, int whence
)
940 unix_stream
*s
= (unix_stream
*)strm
;
946 offset
+= s
->logical_offset
;
949 offset
+= s
->file_length
;
955 /* Note that for internal array I/O it's actually possible to have a
956 negative offset, so don't check for that. */
957 if (offset
> s
->file_length
)
963 s
->logical_offset
= offset
;
965 /* Returning < 0 is the error indicator for sseek(), so return 0 if
966 offset is negative. Thus if the return value is 0, the caller
967 has to use stell() to get the real value of logical_offset. */
977 return ((unix_stream
*)s
)->logical_offset
;
982 mem_truncate (unix_stream
*s
__attribute__ ((unused
)),
983 gfc_offset length
__attribute__ ((unused
)))
990 mem_flush (unix_stream
*s
__attribute__ ((unused
)))
997 mem_close (unix_stream
*s
)
1004 static const struct stream_vtable mem_vtable
= {
1005 .read
= (void *) mem_read
,
1006 .write
= (void *) mem_write
,
1007 .seek
= (void *) mem_seek
,
1008 .tell
= (void *) mem_tell
,
1009 /* buf_size is not a typo, we just reuse an identical
1011 .size
= (void *) buf_size
,
1012 .trunc
= (void *) mem_truncate
,
1013 .close
= (void *) mem_close
,
1014 .flush
= (void *) mem_flush
,
1015 .markeor
= (void *) raw_markeor
1018 static const struct stream_vtable mem4_vtable
= {
1019 .read
= (void *) mem_read4
,
1020 .write
= (void *) mem_write4
,
1021 .seek
= (void *) mem_seek
,
1022 .tell
= (void *) mem_tell
,
1023 /* buf_size is not a typo, we just reuse an identical
1025 .size
= (void *) buf_size
,
1026 .trunc
= (void *) mem_truncate
,
1027 .close
= (void *) mem_close
,
1028 .flush
= (void *) mem_flush
,
1029 .markeor
= (void *) raw_markeor
1032 /*********************************************************************
1033 Public functions -- A reimplementation of this module needs to
1034 define functional equivalents of the following.
1035 *********************************************************************/
1037 /* open_internal()-- Returns a stream structure from a character(kind=1)
1041 open_internal (char *base
, size_t length
, gfc_offset offset
)
1045 s
= xcalloc (1, sizeof (unix_stream
));
1048 s
->buffer_offset
= offset
;
1050 s
->active
= s
->file_length
= length
;
1052 s
->st
.vptr
= &mem_vtable
;
1054 return (stream
*) s
;
1057 /* open_internal4()-- Returns a stream structure from a character(kind=4)
1061 open_internal4 (char *base
, size_t length
, gfc_offset offset
)
1065 s
= xcalloc (1, sizeof (unix_stream
));
1068 s
->buffer_offset
= offset
;
1070 s
->active
= s
->file_length
= length
* sizeof (gfc_char4_t
);
1072 s
->st
.vptr
= &mem4_vtable
;
1078 /* fd_to_stream()-- Given an open file descriptor, build a stream
1082 fd_to_stream (int fd
, bool unformatted
)
1084 struct stat statbuf
;
1087 s
= xcalloc (1, sizeof (unix_stream
));
1091 /* Get the current length of the file. */
1093 if (TEMP_FAILURE_RETRY (fstat (fd
, &statbuf
)) == -1)
1095 s
->st_dev
= s
->st_ino
= -1;
1100 return (stream
*) s
;
1103 s
->st_dev
= statbuf
.st_dev
;
1104 s
->st_ino
= statbuf
.st_ino
;
1105 s
->file_length
= statbuf
.st_size
;
1107 /* Only use buffered IO for regular files. */
1108 if (S_ISREG (statbuf
.st_mode
)
1109 && !options
.all_unbuffered
1110 && !(options
.unbuffered_preconnected
&&
1111 (s
->fd
== STDIN_FILENO
1112 || s
->fd
== STDOUT_FILENO
1113 || s
->fd
== STDERR_FILENO
)))
1119 s
->unbuffered
= true;
1126 return (stream
*) s
;
1130 /* Given the Fortran unit number, convert it to a C file descriptor. */
1133 unit_to_fd (int unit
)
1138 us
= find_unit (unit
);
1142 fd
= ((unix_stream
*) us
->s
)->fd
;
1148 /* Set the close-on-exec flag for an existing fd, if the system
1151 static void __attribute__ ((unused
))
1152 set_close_on_exec (int fd
__attribute__ ((unused
)))
1154 /* Mingw does not define F_SETFD. */
1155 #if defined(HAVE_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
1157 fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
1162 /* Helper function for tempfile(). Tries to open a temporary file in
1163 the directory specified by tempdir. If successful, the file name is
1164 stored in fname and the descriptor returned. Returns -1 on
1168 tempfile_open (const char *tempdir
, char **fname
)
1171 const char *slash
= "/";
1172 #if defined(HAVE_UMASK) && defined(HAVE_MKSTEMP)
1179 /* Check for the special case that tempdir ends with a slash or
1181 size_t tempdirlen
= strlen (tempdir
);
1182 if (*tempdir
== 0 || tempdir
[tempdirlen
- 1] == '/'
1184 || tempdir
[tempdirlen
- 1] == '\\'
1189 /* Take care that the template is longer in the mktemp() branch. */
1190 char *template = xmalloc (tempdirlen
+ 23);
1193 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpXXXXXX",
1197 /* Temporarily set the umask such that the file has 0600 permissions. */
1198 mode_mask
= umask (S_IXUSR
| S_IRWXG
| S_IRWXO
);
1201 #if defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
1202 TEMP_FAILURE_RETRY (fd
= mkostemp (template, O_CLOEXEC
));
1204 TEMP_FAILURE_RETRY (fd
= mkstemp (template));
1205 set_close_on_exec (fd
);
1209 (void) umask (mode_mask
);
1212 #else /* HAVE_MKSTEMP */
1215 size_t slashlen
= strlen (slash
);
1216 int flags
= O_RDWR
| O_CREAT
| O_EXCL
;
1217 #if defined(HAVE_CRLF) && defined(O_BINARY)
1225 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpaaaXXXXXX",
1230 template[tempdirlen
+ slashlen
+ 13] = 'a' + (c
% 26);
1232 template[tempdirlen
+ slashlen
+ 12] = 'a' + (c
% 26);
1234 template[tempdirlen
+ slashlen
+ 11] = 'a' + (c
% 26);
1239 if (!mktemp (template))
1246 TEMP_FAILURE_RETRY (fd
= open (template, flags
, S_IRUSR
| S_IWUSR
));
1248 while (fd
== -1 && errno
== EEXIST
);
1250 set_close_on_exec (fd
);
1252 #endif /* HAVE_MKSTEMP */
1259 /* tempfile()-- Generate a temporary filename for a scratch file and
1260 open it. mkstemp() opens the file for reading and writing, but the
1261 library mode prevents anything that is not allowed. The descriptor
1262 is returned, which is -1 on error. The template is pointed to by
1263 opp->file, which is copied into the unit structure
1267 tempfile (st_parameter_open
*opp
)
1269 const char *tempdir
;
1273 tempdir
= secure_getenv ("TMPDIR");
1274 fd
= tempfile_open (tempdir
, &fname
);
1278 char buffer
[MAX_PATH
+ 1];
1280 ret
= GetTempPath (MAX_PATH
, buffer
);
1281 /* If we are not able to get a temp-directory, we use
1282 current directory. */
1283 if (ret
> MAX_PATH
|| !ret
)
1287 tempdir
= strdup (buffer
);
1288 fd
= tempfile_open (tempdir
, &fname
);
1290 #elif defined(__CYGWIN__)
1293 tempdir
= secure_getenv ("TMP");
1294 fd
= tempfile_open (tempdir
, &fname
);
1298 tempdir
= secure_getenv ("TEMP");
1299 fd
= tempfile_open (tempdir
, &fname
);
1303 fd
= tempfile_open (P_tmpdir
, &fname
);
1306 opp
->file_len
= strlen (fname
); /* Don't include trailing nul */
1312 /* regular_file2()-- Open a regular file.
1313 Change flags->action if it is ACTION_UNSPECIFIED on entry,
1314 unless an error occurs.
1315 Returns the descriptor, which is less than zero on error. */
1318 regular_file2 (const char *path
, st_parameter_open
*opp
, unit_flags
*flags
)
1322 int crflag
, crflag2
;
1326 if (opp
->file_len
== 7)
1328 if (strncmp (path
, "CONOUT$", 7) == 0
1329 || strncmp (path
, "CONERR$", 7) == 0)
1331 fd
= open ("/dev/conout", O_WRONLY
);
1332 flags
->action
= ACTION_WRITE
;
1337 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1339 fd
= open ("/dev/conin", O_RDONLY
);
1340 flags
->action
= ACTION_READ
;
1347 if (opp
->file_len
== 7)
1349 if (strncmp (path
, "CONOUT$", 7) == 0
1350 || strncmp (path
, "CONERR$", 7) == 0)
1352 fd
= open ("CONOUT$", O_WRONLY
);
1353 flags
->action
= ACTION_WRITE
;
1358 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1360 fd
= open ("CONIN$", O_RDONLY
);
1361 flags
->action
= ACTION_READ
;
1366 switch (flags
->action
)
1376 case ACTION_READWRITE
:
1377 case ACTION_UNSPECIFIED
:
1382 internal_error (&opp
->common
, "regular_file(): Bad action");
1385 switch (flags
->status
)
1388 crflag
= O_CREAT
| O_EXCL
;
1391 case STATUS_OLD
: /* open will fail if the file does not exist*/
1395 case STATUS_UNKNOWN
:
1396 if (rwflag
== O_RDONLY
)
1402 case STATUS_REPLACE
:
1403 crflag
= O_CREAT
| O_TRUNC
;
1407 /* Note: STATUS_SCRATCH is handled by tempfile () and should
1408 never be seen here. */
1409 internal_error (&opp
->common
, "regular_file(): Bad status");
1412 /* rwflag |= O_LARGEFILE; */
1414 #if defined(HAVE_CRLF) && defined(O_BINARY)
1419 crflag
|= O_CLOEXEC
;
1422 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
;
1423 TEMP_FAILURE_RETRY (fd
= open (path
, rwflag
| crflag
, mode
));
1424 if (flags
->action
!= ACTION_UNSPECIFIED
)
1429 flags
->action
= ACTION_READWRITE
;
1432 if (errno
!= EACCES
&& errno
!= EPERM
&& errno
!= EROFS
)
1435 /* retry for read-only access */
1437 if (flags
->status
== STATUS_UNKNOWN
)
1438 crflag2
= crflag
& ~(O_CREAT
);
1441 TEMP_FAILURE_RETRY (fd
= open (path
, rwflag
| crflag2
, mode
));
1444 flags
->action
= ACTION_READ
;
1445 return fd
; /* success */
1448 if (errno
!= EACCES
&& errno
!= EPERM
&& errno
!= ENOENT
)
1449 return fd
; /* failure */
1451 /* retry for write-only access */
1453 TEMP_FAILURE_RETRY (fd
= open (path
, rwflag
| crflag
, mode
));
1456 flags
->action
= ACTION_WRITE
;
1457 return fd
; /* success */
1459 return fd
; /* failure */
1463 /* Lock the file, if necessary, based on SHARE flags. */
1465 #if defined(HAVE_FCNTL) && defined(F_SETLK) && defined(F_UNLCK)
1467 open_share (st_parameter_open
*opp
, int fd
, unit_flags
*flags
)
1471 if (fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
|| fd
== STDIN_FILENO
)
1476 f
.l_whence
= SEEK_SET
;
1478 switch (flags
->share
)
1480 case SHARE_DENYNONE
:
1482 r
= fcntl (fd
, F_SETLK
, &f
);
1485 /* Must be writable to hold write lock. */
1486 if (flags
->action
== ACTION_READ
)
1488 generate_error (&opp
->common
, LIBERROR_BAD_ACTION
,
1489 "Cannot set write lock on file opened for READ");
1493 r
= fcntl (fd
, F_SETLK
, &f
);
1495 case SHARE_UNSPECIFIED
:
1504 open_share (st_parameter_open
*opp
__attribute__ ((unused
)),
1505 int fd
__attribute__ ((unused
)),
1506 unit_flags
*flags
__attribute__ ((unused
)))
1510 #endif /* defined(HAVE_FCNTL) ... */
1513 /* Wrapper around regular_file2, to make sure we free the path after
1517 regular_file (st_parameter_open
*opp
, unit_flags
*flags
)
1519 char *path
= fc_strdup (opp
->file
, opp
->file_len
);
1520 int fd
= regular_file2 (path
, opp
, flags
);
1525 /* open_external()-- Open an external file, unix specific version.
1526 Change flags->action if it is ACTION_UNSPECIFIED on entry.
1527 Returns NULL on operating system error. */
1530 open_external (st_parameter_open
*opp
, unit_flags
*flags
)
1534 if (flags
->status
== STATUS_SCRATCH
)
1536 fd
= tempfile (opp
);
1537 if (flags
->action
== ACTION_UNSPECIFIED
)
1538 flags
->action
= flags
->readonly
? ACTION_READ
: ACTION_READWRITE
;
1540 #if HAVE_UNLINK_OPEN_FILE
1541 /* We can unlink scratch files now and it will go away when closed. */
1548 /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1550 fd
= regular_file (opp
, flags
);
1552 set_close_on_exec (fd
);
1560 if (open_share (opp
, fd
, flags
) < 0)
1563 return fd_to_stream (fd
, flags
->form
== FORM_UNFORMATTED
);
1567 /* input_stream()-- Return a stream pointer to the default input stream.
1568 Called on initialization. */
1573 return fd_to_stream (STDIN_FILENO
, false);
1577 /* output_stream()-- Return a stream pointer to the default output stream.
1578 Called on initialization. */
1581 output_stream (void)
1585 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1586 setmode (STDOUT_FILENO
, O_BINARY
);
1589 s
= fd_to_stream (STDOUT_FILENO
, false);
1594 /* error_stream()-- Return a stream pointer to the default error stream.
1595 Called on initialization. */
1602 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1603 setmode (STDERR_FILENO
, O_BINARY
);
1606 s
= fd_to_stream (STDERR_FILENO
, false);
1611 /* compare_file_filename()-- Given an open stream and a fortran string
1612 that is a filename, figure out if the file is the same as the
1616 compare_file_filename (gfc_unit
*u
, const char *name
, int len
)
1620 #ifdef HAVE_WORKING_STAT
1628 char *path
= fc_strdup (name
, len
);
1630 /* If the filename doesn't exist, then there is no match with the
1633 if (TEMP_FAILURE_RETRY (stat (path
, &st
)) < 0)
1639 #ifdef HAVE_WORKING_STAT
1640 s
= (unix_stream
*) (u
->s
);
1641 ret
= (st
.st_dev
== s
->st_dev
) && (st
.st_ino
== s
->st_ino
);
1646 /* We try to match files by a unique ID. On some filesystems (network
1647 fs and FAT), we can't generate this unique ID, and will simply compare
1649 id1
= id_from_path (path
);
1650 id2
= id_from_fd (((unix_stream
*) (u
->s
))->fd
);
1658 ret
= (strcmp(path
, u
->filename
) == 0);
1668 #ifdef HAVE_WORKING_STAT
1669 # define FIND_FILE0_DECL struct stat *st
1670 # define FIND_FILE0_ARGS st
1672 # define FIND_FILE0_DECL uint64_t id, const char *path
1673 # define FIND_FILE0_ARGS id, path
1676 /* find_file0()-- Recursive work function for find_file() */
1679 find_file0 (gfc_unit
*u
, FIND_FILE0_DECL
)
1682 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1689 #ifdef HAVE_WORKING_STAT
1692 unix_stream
*s
= (unix_stream
*) (u
->s
);
1693 if (st
[0].st_dev
== s
->st_dev
&& st
[0].st_ino
== s
->st_ino
)
1698 if (u
->s
&& ((id1
= id_from_fd (((unix_stream
*) u
->s
)->fd
)) || id1
))
1705 if (u
->filename
&& strcmp (u
->filename
, path
) == 0)
1709 v
= find_file0 (u
->left
, FIND_FILE0_ARGS
);
1713 v
= find_file0 (u
->right
, FIND_FILE0_ARGS
);
1721 /* find_file()-- Take the current filename and see if there is a unit
1722 that has the file already open. Returns a pointer to the unit if so. */
1725 find_file (const char *file
, gfc_charlen_type file_len
)
1729 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1733 char *path
= fc_strdup (file
, file_len
);
1735 if (TEMP_FAILURE_RETRY (stat (path
, &st
[0])) < 0)
1741 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1742 id
= id_from_path (path
);
1745 __gthread_mutex_lock (&unit_lock
);
1747 u
= find_file0 (unit_root
, FIND_FILE0_ARGS
);
1751 if (! __gthread_mutex_trylock (&u
->lock
))
1753 /* assert (u->closed == 0); */
1754 __gthread_mutex_unlock (&unit_lock
);
1758 inc_waiting_locked (u
);
1760 __gthread_mutex_unlock (&unit_lock
);
1763 __gthread_mutex_lock (&u
->lock
);
1766 __gthread_mutex_lock (&unit_lock
);
1767 __gthread_mutex_unlock (&u
->lock
);
1768 if (predec_waiting_locked (u
) == 0)
1773 dec_waiting_unlocked (u
);
1781 flush_all_units_1 (gfc_unit
*u
, int min_unit
)
1785 if (u
->unit_number
> min_unit
)
1787 gfc_unit
*r
= flush_all_units_1 (u
->left
, min_unit
);
1791 if (u
->unit_number
>= min_unit
)
1793 if (__gthread_mutex_trylock (&u
->lock
))
1797 __gthread_mutex_unlock (&u
->lock
);
1805 flush_all_units (void)
1810 __gthread_mutex_lock (&unit_lock
);
1813 u
= flush_all_units_1 (unit_root
, min_unit
);
1815 inc_waiting_locked (u
);
1816 __gthread_mutex_unlock (&unit_lock
);
1820 __gthread_mutex_lock (&u
->lock
);
1822 min_unit
= u
->unit_number
+ 1;
1827 __gthread_mutex_lock (&unit_lock
);
1828 __gthread_mutex_unlock (&u
->lock
);
1829 (void) predec_waiting_locked (u
);
1833 __gthread_mutex_lock (&unit_lock
);
1834 __gthread_mutex_unlock (&u
->lock
);
1835 if (predec_waiting_locked (u
) == 0)
1843 /* Unlock the unit if necessary, based on SHARE flags. */
1846 close_share (gfc_unit
*u
__attribute__ ((unused
)))
1849 #if defined(HAVE_FCNTL) && defined(F_SETLK) && defined(F_UNLCK)
1850 unix_stream
*s
= (unix_stream
*) u
->s
;
1854 switch (u
->flags
.share
)
1857 case SHARE_DENYNONE
:
1858 if (fd
!= STDOUT_FILENO
&& fd
!= STDERR_FILENO
&& fd
!= STDIN_FILENO
)
1862 f
.l_whence
= SEEK_SET
;
1864 r
= fcntl (fd
, F_SETLK
, &f
);
1867 case SHARE_UNSPECIFIED
:
1877 /* file_exists()-- Returns nonzero if the current filename exists on
1881 file_exists (const char *file
, gfc_charlen_type file_len
)
1883 char *path
= fc_strdup (file
, file_len
);
1884 int res
= !(access (path
, F_OK
));
1890 /* file_size()-- Returns the size of the file. */
1893 file_size (const char *file
, gfc_charlen_type file_len
)
1895 char *path
= fc_strdup (file
, file_len
);
1896 struct stat statbuf
;
1898 TEMP_FAILURE_RETRY (err
= stat (path
, &statbuf
));
1902 return (GFC_IO_INT
) statbuf
.st_size
;
1905 static const char yes
[] = "YES", no
[] = "NO", unknown
[] = "UNKNOWN";
1907 /* inquire_sequential()-- Given a fortran string, determine if the
1908 file is suitable for sequential access. Returns a C-style
1912 inquire_sequential (const char *string
, int len
)
1914 struct stat statbuf
;
1919 char *path
= fc_strdup (string
, len
);
1921 TEMP_FAILURE_RETRY (err
= stat (path
, &statbuf
));
1926 if (S_ISREG (statbuf
.st_mode
) ||
1927 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1930 if (S_ISDIR (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1937 /* inquire_direct()-- Given a fortran string, determine if the file is
1938 suitable for direct access. Returns a C-style string. */
1941 inquire_direct (const char *string
, int len
)
1943 struct stat statbuf
;
1948 char *path
= fc_strdup (string
, len
);
1950 TEMP_FAILURE_RETRY (err
= stat (path
, &statbuf
));
1955 if (S_ISREG (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1958 if (S_ISDIR (statbuf
.st_mode
) ||
1959 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1966 /* inquire_formatted()-- Given a fortran string, determine if the file
1967 is suitable for formatted form. Returns a C-style string. */
1970 inquire_formatted (const char *string
, int len
)
1972 struct stat statbuf
;
1977 char *path
= fc_strdup (string
, len
);
1979 TEMP_FAILURE_RETRY (err
= stat (path
, &statbuf
));
1984 if (S_ISREG (statbuf
.st_mode
) ||
1985 S_ISBLK (statbuf
.st_mode
) ||
1986 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1989 if (S_ISDIR (statbuf
.st_mode
))
1996 /* inquire_unformatted()-- Given a fortran string, determine if the file
1997 is suitable for unformatted form. Returns a C-style string. */
2000 inquire_unformatted (const char *string
, int len
)
2002 return inquire_formatted (string
, len
);
2006 /* inquire_access()-- Given a fortran string, determine if the file is
2007 suitable for access. */
2010 inquire_access (const char *string
, int len
, int mode
)
2014 char *path
= fc_strdup (string
, len
);
2015 int res
= access (path
, mode
);
2024 /* inquire_read()-- Given a fortran string, determine if the file is
2025 suitable for READ access. */
2028 inquire_read (const char *string
, int len
)
2030 return inquire_access (string
, len
, R_OK
);
2034 /* inquire_write()-- Given a fortran string, determine if the file is
2035 suitable for READ access. */
2038 inquire_write (const char *string
, int len
)
2040 return inquire_access (string
, len
, W_OK
);
2044 /* inquire_readwrite()-- Given a fortran string, determine if the file is
2045 suitable for read and write access. */
2048 inquire_readwrite (const char *string
, int len
)
2050 return inquire_access (string
, len
, R_OK
| W_OK
);
2055 stream_isatty (stream
*s
)
2057 return isatty (((unix_stream
*) s
)->fd
);
2061 stream_ttyname (stream
*s
__attribute__ ((unused
)),
2062 char *buf
__attribute__ ((unused
)),
2063 size_t buflen
__attribute__ ((unused
)))
2065 #ifdef HAVE_TTYNAME_R
2066 return ttyname_r (((unix_stream
*)s
)->fd
, buf
, buflen
);
2067 #elif defined HAVE_TTYNAME
2070 p
= ttyname (((unix_stream
*)s
)->fd
);
2076 memcpy (buf
, p
, plen
);
2086 /* How files are stored: This is an operating-system specific issue,
2087 and therefore belongs here. There are three cases to consider.
2090 Records are written as block of bytes corresponding to the record
2091 length of the file. This goes for both formatted and unformatted
2092 records. Positioning is done explicitly for each data transfer,
2093 so positioning is not much of an issue.
2095 Sequential Formatted:
2096 Records are separated by newline characters. The newline character
2097 is prohibited from appearing in a string. If it does, this will be
2098 messed up on the next read. End of file is also the end of a record.
2100 Sequential Unformatted:
2101 In this case, we are merely copying bytes to and from main storage,
2102 yet we need to keep track of varying record lengths. We adopt
2103 the solution used by f2c. Each record contains a pair of length
2106 Length of record n in bytes
2108 Length of record n in bytes
2110 Length of record n+1 in bytes
2112 Length of record n+1 in bytes
2114 The length is stored at the end of a record to allow backspacing to the
2115 previous record. Between data transfer statements, the file pointer
2116 is left pointing to the first length of the current record.
2118 ENDFILE records are never explicitly stored.