1 /* Copyright (C) 2002-2015 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 */
106 /* On mingw, we don't use umask in tempfile_open(), because it
107 doesn't support the user/group/other-based permissions. */
110 #endif /* __MINGW32__ */
113 /* min macro that evaluates its arguments only once. */
119 ({ typeof (a) _a = (a); \
120 typeof (b) _b = (b); \
121 _a < _b ? _a : _b; })
124 /* These flags aren't defined on all targets (mingw32), so provide them
157 /* Fallback implementation of access() on systems that don't have it.
158 Only modes R_OK, W_OK and F_OK are used in this file. */
161 fallback_access (const char *path
, int mode
)
165 if ((mode
& R_OK
) && (fd
= open (path
, O_RDONLY
)) < 0)
169 if ((mode
& W_OK
) && (fd
= open (path
, O_WRONLY
)) < 0)
176 return stat (path
, &st
);
183 #define access fallback_access
187 /* Fallback directory for creating temporary files. P_tmpdir is
188 defined on many POSIX platforms. */
191 #define P_tmpdir _P_tmpdir /* MinGW */
193 #define P_tmpdir "/tmp"
198 /* Unix and internal stream I/O module */
200 static const int BUFFER_SIZE
= 8192;
206 gfc_offset buffer_offset
; /* File offset of the start of the buffer */
207 gfc_offset physical_offset
; /* Current physical file offset */
208 gfc_offset logical_offset
; /* Current logical file offset */
209 gfc_offset file_length
; /* Length of the file. */
211 char *buffer
; /* Pointer to the buffer. */
212 int fd
; /* The POSIX file descriptor. */
214 int active
; /* Length of valid bytes in the buffer */
216 int ndirty
; /* Dirty bytes starting at buffer_offset */
218 /* Cached stat(2) values. */
222 bool unbuffered
; /* Buffer should be flushed after each I/O statement. */
227 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
228 * standard descriptors, returning a non-standard descriptor. If the
229 * user specifies that system errors should go to standard output,
230 * then closes standard output, we don't want the system errors to a
231 * file that has been given file descriptor 1 or 0. We want to send
232 * the error to the invalid descriptor. */
238 int input
, output
, error
;
240 input
= output
= error
= 0;
242 /* Unix allocates the lowest descriptors first, so a loop is not
243 required, but this order is. */
244 if (fd
== STDIN_FILENO
)
249 if (fd
== STDOUT_FILENO
)
254 if (fd
== STDERR_FILENO
)
261 close (STDIN_FILENO
);
263 close (STDOUT_FILENO
);
265 close (STDERR_FILENO
);
272 /* If the stream corresponds to a preconnected unit, we flush the
273 corresponding C stream. This is bugware for mixed C-Fortran codes
274 where the C code doesn't flush I/O before returning. */
276 flush_if_preconnected (stream
* s
)
280 fd
= ((unix_stream
*) s
)->fd
;
281 if (fd
== STDIN_FILENO
)
283 else if (fd
== STDOUT_FILENO
)
285 else if (fd
== STDERR_FILENO
)
290 /********************************************************************
291 Raw I/O functions (read, write, seek, tell, truncate, close).
293 These functions wrap the basic POSIX I/O syscalls. Any deviation in
294 semantics is a bug, except the following: write restarts in case
295 of being interrupted by a signal, and as the first argument the
296 functions take the unix_stream struct rather than an integer file
297 descriptor. Also, for POSIX read() and write() a nbyte argument larger
298 than SSIZE_MAX is undefined; here the type of nbyte is ssize_t rather
299 than size_t as for POSIX read/write.
300 *********************************************************************/
303 raw_flush (unix_stream
* s
__attribute__ ((unused
)))
309 raw_read (unix_stream
* s
, void * buf
, ssize_t nbyte
)
311 /* For read we can't do I/O in a loop like raw_write does, because
312 that will break applications that wait for interactive I/O. */
313 return read (s
->fd
, buf
, nbyte
);
317 raw_write (unix_stream
* s
, const void * buf
, ssize_t nbyte
)
319 ssize_t trans
, bytes_left
;
323 buf_st
= (char *) buf
;
325 /* We must write in a loop since some systems don't restart system
326 calls in case of a signal. */
327 while (bytes_left
> 0)
329 trans
= write (s
->fd
, buf_st
, bytes_left
);
341 return nbyte
- bytes_left
;
345 raw_seek (unix_stream
* s
, gfc_offset offset
, int whence
)
347 return lseek (s
->fd
, offset
, whence
);
351 raw_tell (unix_stream
* s
)
353 return lseek (s
->fd
, 0, SEEK_CUR
);
357 raw_size (unix_stream
* s
)
360 int ret
= fstat (s
->fd
, &statbuf
);
363 if (S_ISREG (statbuf
.st_mode
))
364 return statbuf
.st_size
;
370 raw_truncate (unix_stream
* s
, gfc_offset length
)
381 h
= (HANDLE
) _get_osfhandle (s
->fd
);
382 if (h
== INVALID_HANDLE_VALUE
)
387 cur
= lseek (s
->fd
, 0, SEEK_CUR
);
390 if (lseek (s
->fd
, length
, SEEK_SET
) == -1)
392 if (!SetEndOfFile (h
))
397 if (lseek (s
->fd
, cur
, SEEK_SET
) == -1)
401 lseek (s
->fd
, cur
, SEEK_SET
);
403 #elif defined HAVE_FTRUNCATE
404 return ftruncate (s
->fd
, length
);
405 #elif defined HAVE_CHSIZE
406 return chsize (s
->fd
, length
);
408 runtime_error ("required ftruncate or chsize support not present");
414 raw_close (unix_stream
* s
)
420 else if (s
->fd
!= STDOUT_FILENO
421 && s
->fd
!= STDERR_FILENO
422 && s
->fd
!= STDIN_FILENO
)
423 retval
= close (s
->fd
);
431 raw_markeor (unix_stream
* s
__attribute__ ((unused
)))
436 static const struct stream_vtable raw_vtable
= {
437 .read
= (void *) raw_read
,
438 .write
= (void *) raw_write
,
439 .seek
= (void *) raw_seek
,
440 .tell
= (void *) raw_tell
,
441 .size
= (void *) raw_size
,
442 .trunc
= (void *) raw_truncate
,
443 .close
= (void *) raw_close
,
444 .flush
= (void *) raw_flush
,
445 .markeor
= (void *) raw_markeor
449 raw_init (unix_stream
* s
)
451 s
->st
.vptr
= &raw_vtable
;
458 /*********************************************************************
459 Buffered I/O functions. These functions have the same semantics as the
460 raw I/O functions above, except that they are buffered in order to
461 improve performance. The buffer must be flushed when switching from
462 reading to writing and vice versa.
463 *********************************************************************/
466 buf_flush (unix_stream
* s
)
470 /* Flushing in read mode means discarding read bytes. */
476 if (s
->physical_offset
!= s
->buffer_offset
477 && lseek (s
->fd
, s
->buffer_offset
, SEEK_SET
) < 0)
480 writelen
= raw_write (s
, s
->buffer
, s
->ndirty
);
482 s
->physical_offset
= s
->buffer_offset
+ writelen
;
484 if (s
->physical_offset
> s
->file_length
)
485 s
->file_length
= s
->physical_offset
;
487 s
->ndirty
-= writelen
;
495 buf_read (unix_stream
* s
, void * buf
, ssize_t nbyte
)
498 s
->buffer_offset
= s
->logical_offset
;
500 /* Is the data we want in the buffer? */
501 if (s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ s
->active
502 && s
->buffer_offset
<= s
->logical_offset
)
503 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
), nbyte
);
506 /* First copy the active bytes if applicable, then read the rest
507 either directly or filling the buffer. */
510 ssize_t to_read
, did_read
;
511 gfc_offset new_logical
;
514 if (s
->logical_offset
>= s
->buffer_offset
515 && s
->buffer_offset
+ s
->active
>= s
->logical_offset
)
517 nread
= s
->active
- (s
->logical_offset
- s
->buffer_offset
);
518 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
),
522 /* At this point we consider all bytes in the buffer discarded. */
523 to_read
= nbyte
- nread
;
524 new_logical
= s
->logical_offset
+ nread
;
525 if (s
->physical_offset
!= new_logical
526 && lseek (s
->fd
, new_logical
, SEEK_SET
) < 0)
528 s
->buffer_offset
= s
->physical_offset
= new_logical
;
529 if (to_read
<= BUFFER_SIZE
/2)
531 did_read
= raw_read (s
, s
->buffer
, BUFFER_SIZE
);
532 s
->physical_offset
+= did_read
;
533 s
->active
= did_read
;
534 did_read
= (did_read
> to_read
) ? to_read
: did_read
;
535 memcpy (p
, s
->buffer
, did_read
);
539 did_read
= raw_read (s
, p
, to_read
);
540 s
->physical_offset
+= did_read
;
543 nbyte
= did_read
+ nread
;
545 s
->logical_offset
+= nbyte
;
550 buf_write (unix_stream
* s
, const void * buf
, ssize_t nbyte
)
553 s
->buffer_offset
= s
->logical_offset
;
555 /* Does the data fit into the buffer? As a special case, if the
556 buffer is empty and the request is bigger than BUFFER_SIZE/2,
557 write directly. This avoids the case where the buffer would have
558 to be flushed at every write. */
559 if (!(s
->ndirty
== 0 && nbyte
> BUFFER_SIZE
/2)
560 && s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ BUFFER_SIZE
561 && s
->buffer_offset
<= s
->logical_offset
562 && s
->buffer_offset
+ s
->ndirty
>= s
->logical_offset
)
564 memcpy (s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
), buf
, nbyte
);
565 int nd
= (s
->logical_offset
- s
->buffer_offset
) + nbyte
;
571 /* Flush, and either fill the buffer with the new data, or if
572 the request is bigger than the buffer size, write directly
573 bypassing the buffer. */
575 if (nbyte
<= BUFFER_SIZE
/2)
577 memcpy (s
->buffer
, buf
, nbyte
);
578 s
->buffer_offset
= s
->logical_offset
;
583 if (s
->physical_offset
!= s
->logical_offset
)
585 if (lseek (s
->fd
, s
->logical_offset
, SEEK_SET
) < 0)
587 s
->physical_offset
= s
->logical_offset
;
590 nbyte
= raw_write (s
, buf
, nbyte
);
591 s
->physical_offset
+= nbyte
;
594 s
->logical_offset
+= nbyte
;
595 if (s
->logical_offset
> s
->file_length
)
596 s
->file_length
= s
->logical_offset
;
601 /* "Unbuffered" really means I/O statement buffering. For formatted
602 I/O, the fbuf manages this, and then uses raw I/O. For unformatted
603 I/O, buffered I/O is used, and the buffer is flushed at the end of
604 each I/O statement, where this function is called. Alternatively,
605 the buffer is flushed at the end of the record if the buffer is
606 more than half full; this prevents needless seeking back and forth
607 when writing sequential unformatted. */
610 buf_markeor (unix_stream
* s
)
612 if (s
->unbuffered
|| s
->ndirty
>= BUFFER_SIZE
/ 2)
613 return buf_flush (s
);
618 buf_seek (unix_stream
* s
, gfc_offset offset
, int whence
)
625 offset
+= s
->logical_offset
;
628 offset
+= s
->file_length
;
638 s
->logical_offset
= offset
;
643 buf_tell (unix_stream
* s
)
645 return buf_seek (s
, 0, SEEK_CUR
);
649 buf_size (unix_stream
* s
)
651 return s
->file_length
;
655 buf_truncate (unix_stream
* s
, gfc_offset length
)
659 if (buf_flush (s
) != 0)
661 r
= raw_truncate (s
, length
);
663 s
->file_length
= length
;
668 buf_close (unix_stream
* s
)
670 if (buf_flush (s
) != 0)
673 return raw_close (s
);
676 static const struct stream_vtable buf_vtable
= {
677 .read
= (void *) buf_read
,
678 .write
= (void *) buf_write
,
679 .seek
= (void *) buf_seek
,
680 .tell
= (void *) buf_tell
,
681 .size
= (void *) buf_size
,
682 .trunc
= (void *) buf_truncate
,
683 .close
= (void *) buf_close
,
684 .flush
= (void *) buf_flush
,
685 .markeor
= (void *) buf_markeor
689 buf_init (unix_stream
* s
)
691 s
->st
.vptr
= &buf_vtable
;
693 s
->buffer
= xmalloc (BUFFER_SIZE
);
698 /*********************************************************************
699 memory stream functions - These are used for internal files
701 The idea here is that a single stream structure is created and all
702 requests must be satisfied from it. The location and size of the
703 buffer is the character variable supplied to the READ or WRITE
706 *********************************************************************/
709 mem_alloc_r (stream
* strm
, int * len
)
711 unix_stream
* s
= (unix_stream
*) strm
;
713 gfc_offset where
= s
->logical_offset
;
715 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
718 n
= s
->buffer_offset
+ s
->active
- where
;
722 s
->logical_offset
= where
+ *len
;
724 return s
->buffer
+ (where
- s
->buffer_offset
);
729 mem_alloc_r4 (stream
* strm
, int * len
)
731 unix_stream
* s
= (unix_stream
*) strm
;
733 gfc_offset where
= s
->logical_offset
;
735 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
738 n
= s
->buffer_offset
+ s
->active
- where
;
742 s
->logical_offset
= where
+ *len
;
744 return s
->buffer
+ (where
- s
->buffer_offset
) * 4;
749 mem_alloc_w (stream
* strm
, int * len
)
751 unix_stream
* s
= (unix_stream
*) strm
;
753 gfc_offset where
= s
->logical_offset
;
757 if (where
< s
->buffer_offset
)
760 if (m
> s
->file_length
)
763 s
->logical_offset
= m
;
765 return s
->buffer
+ (where
- s
->buffer_offset
);
770 mem_alloc_w4 (stream
* strm
, int * len
)
772 unix_stream
* s
= (unix_stream
*) strm
;
774 gfc_offset where
= s
->logical_offset
;
775 gfc_char4_t
*result
= (gfc_char4_t
*) s
->buffer
;
779 if (where
< s
->buffer_offset
)
782 if (m
> s
->file_length
)
785 s
->logical_offset
= m
;
786 return &result
[where
- s
->buffer_offset
];
790 /* Stream read function for character(kind=1) internal units. */
793 mem_read (stream
* s
, void * buf
, ssize_t nbytes
)
798 p
= mem_alloc_r (s
, &nb
);
809 /* Stream read function for chracter(kind=4) internal units. */
812 mem_read4 (stream
* s
, void * buf
, ssize_t nbytes
)
817 p
= mem_alloc_r4 (s
, &nb
);
820 memcpy (buf
, p
, nb
* 4);
828 /* Stream write function for character(kind=1) internal units. */
831 mem_write (stream
* s
, const void * buf
, ssize_t nbytes
)
836 p
= mem_alloc_w (s
, &nb
);
847 /* Stream write function for character(kind=4) internal units. */
850 mem_write4 (stream
* s
, const void * buf
, ssize_t nwords
)
855 p
= mem_alloc_w4 (s
, &nw
);
859 *p
++ = (gfc_char4_t
) *((char *) buf
);
868 mem_seek (stream
* strm
, gfc_offset offset
, int whence
)
870 unix_stream
* s
= (unix_stream
*) strm
;
876 offset
+= s
->logical_offset
;
879 offset
+= s
->file_length
;
885 /* Note that for internal array I/O it's actually possible to have a
886 negative offset, so don't check for that. */
887 if (offset
> s
->file_length
)
893 s
->logical_offset
= offset
;
895 /* Returning < 0 is the error indicator for sseek(), so return 0 if
896 offset is negative. Thus if the return value is 0, the caller
897 has to use stell() to get the real value of logical_offset. */
905 mem_tell (stream
* s
)
907 return ((unix_stream
*)s
)->logical_offset
;
912 mem_truncate (unix_stream
* s
__attribute__ ((unused
)),
913 gfc_offset length
__attribute__ ((unused
)))
920 mem_flush (unix_stream
* s
__attribute__ ((unused
)))
927 mem_close (unix_stream
* s
)
934 static const struct stream_vtable mem_vtable
= {
935 .read
= (void *) mem_read
,
936 .write
= (void *) mem_write
,
937 .seek
= (void *) mem_seek
,
938 .tell
= (void *) mem_tell
,
939 /* buf_size is not a typo, we just reuse an identical
941 .size
= (void *) buf_size
,
942 .trunc
= (void *) mem_truncate
,
943 .close
= (void *) mem_close
,
944 .flush
= (void *) mem_flush
,
945 .markeor
= (void *) raw_markeor
948 static const struct stream_vtable mem4_vtable
= {
949 .read
= (void *) mem_read4
,
950 .write
= (void *) mem_write4
,
951 .seek
= (void *) mem_seek
,
952 .tell
= (void *) mem_tell
,
953 /* buf_size is not a typo, we just reuse an identical
955 .size
= (void *) buf_size
,
956 .trunc
= (void *) mem_truncate
,
957 .close
= (void *) mem_close
,
958 .flush
= (void *) mem_flush
,
959 .markeor
= (void *) raw_markeor
962 /*********************************************************************
963 Public functions -- A reimplementation of this module needs to
964 define functional equivalents of the following.
965 *********************************************************************/
967 /* open_internal()-- Returns a stream structure from a character(kind=1)
971 open_internal (char *base
, int length
, gfc_offset offset
)
975 s
= xcalloc (1, sizeof (unix_stream
));
978 s
->buffer_offset
= offset
;
980 s
->active
= s
->file_length
= length
;
982 s
->st
.vptr
= &mem_vtable
;
987 /* open_internal4()-- Returns a stream structure from a character(kind=4)
991 open_internal4 (char *base
, int length
, gfc_offset offset
)
995 s
= xcalloc (1, sizeof (unix_stream
));
998 s
->buffer_offset
= offset
;
1000 s
->active
= s
->file_length
= length
* sizeof (gfc_char4_t
);
1002 s
->st
.vptr
= &mem4_vtable
;
1004 return (stream
*) s
;
1008 /* fd_to_stream()-- Given an open file descriptor, build a stream
1012 fd_to_stream (int fd
, bool unformatted
)
1014 struct stat statbuf
;
1017 s
= xcalloc (1, sizeof (unix_stream
));
1021 /* Get the current length of the file. */
1023 if (fstat (fd
, &statbuf
) == -1)
1025 s
->st_dev
= s
->st_ino
= -1;
1030 return (stream
*) s
;
1033 s
->st_dev
= statbuf
.st_dev
;
1034 s
->st_ino
= statbuf
.st_ino
;
1035 s
->file_length
= statbuf
.st_size
;
1037 /* Only use buffered IO for regular files. */
1038 if (S_ISREG (statbuf
.st_mode
)
1039 && !options
.all_unbuffered
1040 && !(options
.unbuffered_preconnected
&&
1041 (s
->fd
== STDIN_FILENO
1042 || s
->fd
== STDOUT_FILENO
1043 || s
->fd
== STDERR_FILENO
)))
1049 s
->unbuffered
= true;
1056 return (stream
*) s
;
1060 /* Given the Fortran unit number, convert it to a C file descriptor. */
1063 unit_to_fd (int unit
)
1068 us
= find_unit (unit
);
1072 fd
= ((unix_stream
*) us
->s
)->fd
;
1078 /* Set the close-on-exec flag for an existing fd, if the system
1081 static void __attribute__ ((unused
))
1082 set_close_on_exec (int fd
__attribute__ ((unused
)))
1084 /* Mingw does not define F_SETFD. */
1085 #if defined(HAVE_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
1087 fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
1092 /* Helper function for tempfile(). Tries to open a temporary file in
1093 the directory specified by tempdir. If successful, the file name is
1094 stored in fname and the descriptor returned. Returns -1 on
1098 tempfile_open (const char *tempdir
, char **fname
)
1101 const char *slash
= "/";
1102 #if defined(HAVE_UMASK) && defined(HAVE_MKSTEMP)
1109 /* Check for the special case that tempdir ends with a slash or
1111 size_t tempdirlen
= strlen (tempdir
);
1112 if (*tempdir
== 0 || tempdir
[tempdirlen
- 1] == '/'
1114 || tempdir
[tempdirlen
- 1] == '\\'
1119 // Take care that the template is longer in the mktemp() branch.
1120 char * template = xmalloc (tempdirlen
+ 23);
1123 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpXXXXXX",
1127 /* Temporarily set the umask such that the file has 0600 permissions. */
1128 mode_mask
= umask (S_IXUSR
| S_IRWXG
| S_IRWXO
);
1131 #if defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
1132 fd
= mkostemp (template, O_CLOEXEC
);
1134 fd
= mkstemp (template);
1135 set_close_on_exec (fd
);
1139 (void) umask (mode_mask
);
1142 #else /* HAVE_MKSTEMP */
1145 size_t slashlen
= strlen (slash
);
1146 int flags
= O_RDWR
| O_CREAT
| O_EXCL
;
1147 #if defined(HAVE_CRLF) && defined(O_BINARY)
1155 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpaaaXXXXXX",
1160 template[tempdirlen
+ slashlen
+ 13] = 'a' + (c
% 26);
1162 template[tempdirlen
+ slashlen
+ 12] = 'a' + (c
% 26);
1164 template[tempdirlen
+ slashlen
+ 11] = 'a' + (c
% 26);
1169 if (!mktemp (template))
1176 fd
= open (template, flags
, S_IRUSR
| S_IWUSR
);
1178 while (fd
== -1 && errno
== EEXIST
);
1180 set_close_on_exec (fd
);
1182 #endif /* HAVE_MKSTEMP */
1189 /* tempfile()-- Generate a temporary filename for a scratch file and
1190 * open it. mkstemp() opens the file for reading and writing, but the
1191 * library mode prevents anything that is not allowed. The descriptor
1192 * is returned, which is -1 on error. The template is pointed to by
1193 * opp->file, which is copied into the unit structure
1194 * and freed later. */
1197 tempfile (st_parameter_open
*opp
)
1199 const char *tempdir
;
1203 tempdir
= secure_getenv ("TMPDIR");
1204 fd
= tempfile_open (tempdir
, &fname
);
1208 char buffer
[MAX_PATH
+ 1];
1210 ret
= GetTempPath (MAX_PATH
, buffer
);
1211 /* If we are not able to get a temp-directory, we use
1212 current directory. */
1213 if (ret
> MAX_PATH
|| !ret
)
1217 tempdir
= strdup (buffer
);
1218 fd
= tempfile_open (tempdir
, &fname
);
1220 #elif defined(__CYGWIN__)
1223 tempdir
= secure_getenv ("TMP");
1224 fd
= tempfile_open (tempdir
, &fname
);
1228 tempdir
= secure_getenv ("TEMP");
1229 fd
= tempfile_open (tempdir
, &fname
);
1233 fd
= tempfile_open (P_tmpdir
, &fname
);
1236 opp
->file_len
= strlen (fname
); /* Don't include trailing nul */
1242 /* regular_file2()-- Open a regular file.
1243 * Change flags->action if it is ACTION_UNSPECIFIED on entry,
1244 * unless an error occurs.
1245 * Returns the descriptor, which is less than zero on error. */
1248 regular_file2 (const char *path
, st_parameter_open
*opp
, unit_flags
*flags
)
1252 int crflag
, crflag2
;
1256 if (opp
->file_len
== 7)
1258 if (strncmp (path
, "CONOUT$", 7) == 0
1259 || strncmp (path
, "CONERR$", 7) == 0)
1261 fd
= open ("/dev/conout", O_WRONLY
);
1262 flags
->action
= ACTION_WRITE
;
1267 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1269 fd
= open ("/dev/conin", O_RDONLY
);
1270 flags
->action
= ACTION_READ
;
1277 if (opp
->file_len
== 7)
1279 if (strncmp (path
, "CONOUT$", 7) == 0
1280 || strncmp (path
, "CONERR$", 7) == 0)
1282 fd
= open ("CONOUT$", O_WRONLY
);
1283 flags
->action
= ACTION_WRITE
;
1288 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1290 fd
= open ("CONIN$", O_RDONLY
);
1291 flags
->action
= ACTION_READ
;
1296 switch (flags
->action
)
1306 case ACTION_READWRITE
:
1307 case ACTION_UNSPECIFIED
:
1312 internal_error (&opp
->common
, "regular_file(): Bad action");
1315 switch (flags
->status
)
1318 crflag
= O_CREAT
| O_EXCL
;
1321 case STATUS_OLD
: /* open will fail if the file does not exist*/
1325 case STATUS_UNKNOWN
:
1326 if (rwflag
== O_RDONLY
)
1332 case STATUS_REPLACE
:
1333 crflag
= O_CREAT
| O_TRUNC
;
1337 /* Note: STATUS_SCRATCH is handled by tempfile () and should
1338 never be seen here. */
1339 internal_error (&opp
->common
, "regular_file(): Bad status");
1342 /* rwflag |= O_LARGEFILE; */
1344 #if defined(HAVE_CRLF) && defined(O_BINARY)
1349 crflag
|= O_CLOEXEC
;
1352 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
;
1353 fd
= open (path
, rwflag
| crflag
, mode
);
1354 if (flags
->action
!= ACTION_UNSPECIFIED
)
1359 flags
->action
= ACTION_READWRITE
;
1362 if (errno
!= EACCES
&& errno
!= EPERM
&& errno
!= EROFS
)
1365 /* retry for read-only access */
1367 if (flags
->status
== STATUS_UNKNOWN
)
1368 crflag2
= crflag
& ~(O_CREAT
);
1371 fd
= open (path
, rwflag
| crflag2
, mode
);
1374 flags
->action
= ACTION_READ
;
1375 return fd
; /* success */
1378 if (errno
!= EACCES
&& errno
!= EPERM
&& errno
!= ENOENT
)
1379 return fd
; /* failure */
1381 /* retry for write-only access */
1383 fd
= open (path
, rwflag
| crflag
, mode
);
1386 flags
->action
= ACTION_WRITE
;
1387 return fd
; /* success */
1389 return fd
; /* failure */
1393 /* Wrapper around regular_file2, to make sure we free the path after
1397 regular_file (st_parameter_open
*opp
, unit_flags
*flags
)
1399 char *path
= fc_strdup (opp
->file
, opp
->file_len
);
1400 int fd
= regular_file2 (path
, opp
, flags
);
1405 /* open_external()-- Open an external file, unix specific version.
1406 * Change flags->action if it is ACTION_UNSPECIFIED on entry.
1407 * Returns NULL on operating system error. */
1410 open_external (st_parameter_open
*opp
, unit_flags
*flags
)
1414 if (flags
->status
== STATUS_SCRATCH
)
1416 fd
= tempfile (opp
);
1417 if (flags
->action
== ACTION_UNSPECIFIED
)
1418 flags
->action
= ACTION_READWRITE
;
1420 #if HAVE_UNLINK_OPEN_FILE
1421 /* We can unlink scratch files now and it will go away when closed. */
1428 /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1430 fd
= regular_file (opp
, flags
);
1432 set_close_on_exec (fd
);
1440 return fd_to_stream (fd
, flags
->form
== FORM_UNFORMATTED
);
1444 /* input_stream()-- Return a stream pointer to the default input stream.
1445 * Called on initialization. */
1450 return fd_to_stream (STDIN_FILENO
, false);
1454 /* output_stream()-- Return a stream pointer to the default output stream.
1455 * Called on initialization. */
1458 output_stream (void)
1462 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1463 setmode (STDOUT_FILENO
, O_BINARY
);
1466 s
= fd_to_stream (STDOUT_FILENO
, false);
1471 /* error_stream()-- Return a stream pointer to the default error stream.
1472 * Called on initialization. */
1479 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1480 setmode (STDERR_FILENO
, O_BINARY
);
1483 s
= fd_to_stream (STDERR_FILENO
, false);
1488 /* compare_file_filename()-- Given an open stream and a fortran string
1489 * that is a filename, figure out if the file is the same as the
1493 compare_file_filename (gfc_unit
*u
, const char *name
, int len
)
1497 #ifdef HAVE_WORKING_STAT
1505 char *path
= fc_strdup (name
, len
);
1507 /* If the filename doesn't exist, then there is no match with the
1510 if (stat (path
, &st
) < 0)
1516 #ifdef HAVE_WORKING_STAT
1517 s
= (unix_stream
*) (u
->s
);
1518 ret
= (st
.st_dev
== s
->st_dev
) && (st
.st_ino
== s
->st_ino
);
1523 /* We try to match files by a unique ID. On some filesystems (network
1524 fs and FAT), we can't generate this unique ID, and will simply compare
1526 id1
= id_from_path (path
);
1527 id2
= id_from_fd (((unix_stream
*) (u
->s
))->fd
);
1535 ret
= (strcmp(path
, u
->filename
) == 0);
1545 #ifdef HAVE_WORKING_STAT
1546 # define FIND_FILE0_DECL struct stat *st
1547 # define FIND_FILE0_ARGS st
1549 # define FIND_FILE0_DECL uint64_t id, const char *path
1550 # define FIND_FILE0_ARGS id, path
1553 /* find_file0()-- Recursive work function for find_file() */
1556 find_file0 (gfc_unit
*u
, FIND_FILE0_DECL
)
1559 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1566 #ifdef HAVE_WORKING_STAT
1569 unix_stream
*s
= (unix_stream
*) (u
->s
);
1570 if (st
[0].st_dev
== s
->st_dev
&& st
[0].st_ino
== s
->st_ino
)
1575 if (u
->s
&& ((id1
= id_from_fd (((unix_stream
*) u
->s
)->fd
)) || id1
))
1582 if (u
->filename
&& strcmp (u
->filename
, path
) == 0)
1586 v
= find_file0 (u
->left
, FIND_FILE0_ARGS
);
1590 v
= find_file0 (u
->right
, FIND_FILE0_ARGS
);
1598 /* find_file()-- Take the current filename and see if there is a unit
1599 * that has the file already open. Returns a pointer to the unit if so. */
1602 find_file (const char *file
, gfc_charlen_type file_len
)
1606 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1610 char *path
= fc_strdup (file
, file_len
);
1612 if (stat (path
, &st
[0]) < 0)
1618 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1619 id
= id_from_path (path
);
1622 __gthread_mutex_lock (&unit_lock
);
1624 u
= find_file0 (unit_root
, FIND_FILE0_ARGS
);
1628 if (! __gthread_mutex_trylock (&u
->lock
))
1630 /* assert (u->closed == 0); */
1631 __gthread_mutex_unlock (&unit_lock
);
1635 inc_waiting_locked (u
);
1637 __gthread_mutex_unlock (&unit_lock
);
1640 __gthread_mutex_lock (&u
->lock
);
1643 __gthread_mutex_lock (&unit_lock
);
1644 __gthread_mutex_unlock (&u
->lock
);
1645 if (predec_waiting_locked (u
) == 0)
1650 dec_waiting_unlocked (u
);
1658 flush_all_units_1 (gfc_unit
*u
, int min_unit
)
1662 if (u
->unit_number
> min_unit
)
1664 gfc_unit
*r
= flush_all_units_1 (u
->left
, min_unit
);
1668 if (u
->unit_number
>= min_unit
)
1670 if (__gthread_mutex_trylock (&u
->lock
))
1674 __gthread_mutex_unlock (&u
->lock
);
1682 flush_all_units (void)
1687 __gthread_mutex_lock (&unit_lock
);
1690 u
= flush_all_units_1 (unit_root
, min_unit
);
1692 inc_waiting_locked (u
);
1693 __gthread_mutex_unlock (&unit_lock
);
1697 __gthread_mutex_lock (&u
->lock
);
1699 min_unit
= u
->unit_number
+ 1;
1704 __gthread_mutex_lock (&unit_lock
);
1705 __gthread_mutex_unlock (&u
->lock
);
1706 (void) predec_waiting_locked (u
);
1710 __gthread_mutex_lock (&unit_lock
);
1711 __gthread_mutex_unlock (&u
->lock
);
1712 if (predec_waiting_locked (u
) == 0)
1720 /* delete_file()-- Given a unit structure, delete the file associated
1721 * with the unit. Returns nonzero if something went wrong. */
1724 delete_file (gfc_unit
* u
)
1726 return unlink (u
->filename
);
1730 /* file_exists()-- Returns nonzero if the current filename exists on
1734 file_exists (const char *file
, gfc_charlen_type file_len
)
1736 char *path
= fc_strdup (file
, file_len
);
1737 int res
= !(access (path
, F_OK
));
1743 /* file_size()-- Returns the size of the file. */
1746 file_size (const char *file
, gfc_charlen_type file_len
)
1748 char *path
= fc_strdup (file
, file_len
);
1749 struct stat statbuf
;
1750 int err
= stat (path
, &statbuf
);
1754 return (GFC_IO_INT
) statbuf
.st_size
;
1757 static const char yes
[] = "YES", no
[] = "NO", unknown
[] = "UNKNOWN";
1759 /* inquire_sequential()-- Given a fortran string, determine if the
1760 * file is suitable for sequential access. Returns a C-style
1764 inquire_sequential (const char *string
, int len
)
1766 struct stat statbuf
;
1771 char *path
= fc_strdup (string
, len
);
1772 int err
= stat (path
, &statbuf
);
1777 if (S_ISREG (statbuf
.st_mode
) ||
1778 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1781 if (S_ISDIR (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1788 /* inquire_direct()-- Given a fortran string, determine if the file is
1789 * suitable for direct access. Returns a C-style string. */
1792 inquire_direct (const char *string
, int len
)
1794 struct stat statbuf
;
1799 char *path
= fc_strdup (string
, len
);
1800 int err
= stat (path
, &statbuf
);
1805 if (S_ISREG (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1808 if (S_ISDIR (statbuf
.st_mode
) ||
1809 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1816 /* inquire_formatted()-- Given a fortran string, determine if the file
1817 * is suitable for formatted form. Returns a C-style string. */
1820 inquire_formatted (const char *string
, int len
)
1822 struct stat statbuf
;
1827 char *path
= fc_strdup (string
, len
);
1828 int err
= stat (path
, &statbuf
);
1833 if (S_ISREG (statbuf
.st_mode
) ||
1834 S_ISBLK (statbuf
.st_mode
) ||
1835 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1838 if (S_ISDIR (statbuf
.st_mode
))
1845 /* inquire_unformatted()-- Given a fortran string, determine if the file
1846 * is suitable for unformatted form. Returns a C-style string. */
1849 inquire_unformatted (const char *string
, int len
)
1851 return inquire_formatted (string
, len
);
1855 /* inquire_access()-- Given a fortran string, determine if the file is
1856 * suitable for access. */
1859 inquire_access (const char *string
, int len
, int mode
)
1863 char *path
= fc_strdup (string
, len
);
1864 int res
= access (path
, mode
);
1873 /* inquire_read()-- Given a fortran string, determine if the file is
1874 * suitable for READ access. */
1877 inquire_read (const char *string
, int len
)
1879 return inquire_access (string
, len
, R_OK
);
1883 /* inquire_write()-- Given a fortran string, determine if the file is
1884 * suitable for READ access. */
1887 inquire_write (const char *string
, int len
)
1889 return inquire_access (string
, len
, W_OK
);
1893 /* inquire_readwrite()-- Given a fortran string, determine if the file is
1894 * suitable for read and write access. */
1897 inquire_readwrite (const char *string
, int len
)
1899 return inquire_access (string
, len
, R_OK
| W_OK
);
1904 stream_isatty (stream
*s
)
1906 return isatty (((unix_stream
*) s
)->fd
);
1910 stream_ttyname (stream
*s
__attribute__ ((unused
)),
1911 char * buf
__attribute__ ((unused
)),
1912 size_t buflen
__attribute__ ((unused
)))
1914 #ifdef HAVE_TTYNAME_R
1915 return ttyname_r (((unix_stream
*) s
)->fd
, buf
, buflen
);
1916 #elif defined HAVE_TTYNAME
1919 p
= ttyname (((unix_stream
*) s
)->fd
);
1925 memcpy (buf
, p
, plen
);
1935 /* How files are stored: This is an operating-system specific issue,
1936 and therefore belongs here. There are three cases to consider.
1939 Records are written as block of bytes corresponding to the record
1940 length of the file. This goes for both formatted and unformatted
1941 records. Positioning is done explicitly for each data transfer,
1942 so positioning is not much of an issue.
1944 Sequential Formatted:
1945 Records are separated by newline characters. The newline character
1946 is prohibited from appearing in a string. If it does, this will be
1947 messed up on the next read. End of file is also the end of a record.
1949 Sequential Unformatted:
1950 In this case, we are merely copying bytes to and from main storage,
1951 yet we need to keep track of varying record lengths. We adopt
1952 the solution used by f2c. Each record contains a pair of length
1955 Length of record n in bytes
1957 Length of record n in bytes
1959 Length of record n+1 in bytes
1961 Length of record n+1 in bytes
1963 The length is stored at the end of a record to allow backspacing to the
1964 previous record. Between data transfer statements, the file pointer
1965 is left pointing to the first length of the current record.
1967 ENDFILE records are never explicitly stored.