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 /* These flags aren't defined on all targets (mingw32), so provide them
146 /* Fallback implementation of access() on systems that don't have it.
147 Only modes R_OK, W_OK and F_OK are used in this file. */
150 fallback_access (const char *path
, int mode
)
154 if ((mode
& R_OK
) && (fd
= open (path
, O_RDONLY
)) < 0)
158 if ((mode
& W_OK
) && (fd
= open (path
, O_WRONLY
)) < 0)
165 return stat (path
, &st
);
172 #define access fallback_access
176 /* Fallback directory for creating temporary files. P_tmpdir is
177 defined on many POSIX platforms. */
180 #define P_tmpdir _P_tmpdir /* MinGW */
182 #define P_tmpdir "/tmp"
187 /* Unix and internal stream I/O module */
189 static const int BUFFER_SIZE
= 8192;
195 gfc_offset buffer_offset
; /* File offset of the start of the buffer */
196 gfc_offset physical_offset
; /* Current physical file offset */
197 gfc_offset logical_offset
; /* Current logical file offset */
198 gfc_offset file_length
; /* Length of the file. */
200 char *buffer
; /* Pointer to the buffer. */
201 int fd
; /* The POSIX file descriptor. */
203 int active
; /* Length of valid bytes in the buffer */
205 int ndirty
; /* Dirty bytes starting at buffer_offset */
207 /* Cached stat(2) values. */
211 bool unbuffered
; /* Buffer should be flushed after each I/O statement. */
216 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
217 * standard descriptors, returning a non-standard descriptor. If the
218 * user specifies that system errors should go to standard output,
219 * then closes standard output, we don't want the system errors to a
220 * file that has been given file descriptor 1 or 0. We want to send
221 * the error to the invalid descriptor. */
227 int input
, output
, error
;
229 input
= output
= error
= 0;
231 /* Unix allocates the lowest descriptors first, so a loop is not
232 required, but this order is. */
233 if (fd
== STDIN_FILENO
)
238 if (fd
== STDOUT_FILENO
)
243 if (fd
== STDERR_FILENO
)
250 close (STDIN_FILENO
);
252 close (STDOUT_FILENO
);
254 close (STDERR_FILENO
);
261 /* If the stream corresponds to a preconnected unit, we flush the
262 corresponding C stream. This is bugware for mixed C-Fortran codes
263 where the C code doesn't flush I/O before returning. */
265 flush_if_preconnected (stream
* s
)
269 fd
= ((unix_stream
*) s
)->fd
;
270 if (fd
== STDIN_FILENO
)
272 else if (fd
== STDOUT_FILENO
)
274 else if (fd
== STDERR_FILENO
)
279 /********************************************************************
280 Raw I/O functions (read, write, seek, tell, truncate, close).
282 These functions wrap the basic POSIX I/O syscalls. Any deviation in
283 semantics is a bug, except the following: write restarts in case
284 of being interrupted by a signal, and as the first argument the
285 functions take the unix_stream struct rather than an integer file
286 descriptor. Also, for POSIX read() and write() a nbyte argument larger
287 than SSIZE_MAX is undefined; here the type of nbyte is ssize_t rather
288 than size_t as for POSIX read/write.
289 *********************************************************************/
292 raw_flush (unix_stream
* s
__attribute__ ((unused
)))
298 raw_read (unix_stream
* s
, void * buf
, ssize_t nbyte
)
300 /* For read we can't do I/O in a loop like raw_write does, because
301 that will break applications that wait for interactive I/O. */
302 return read (s
->fd
, buf
, nbyte
);
306 raw_write (unix_stream
* s
, const void * buf
, ssize_t nbyte
)
308 ssize_t trans
, bytes_left
;
312 buf_st
= (char *) buf
;
314 /* We must write in a loop since some systems don't restart system
315 calls in case of a signal. */
316 while (bytes_left
> 0)
318 trans
= write (s
->fd
, buf_st
, bytes_left
);
330 return nbyte
- bytes_left
;
334 raw_seek (unix_stream
* s
, gfc_offset offset
, int whence
)
336 return lseek (s
->fd
, offset
, whence
);
340 raw_tell (unix_stream
* s
)
342 return lseek (s
->fd
, 0, SEEK_CUR
);
346 raw_size (unix_stream
* s
)
349 int ret
= fstat (s
->fd
, &statbuf
);
352 if (S_ISREG (statbuf
.st_mode
))
353 return statbuf
.st_size
;
359 raw_truncate (unix_stream
* s
, gfc_offset length
)
370 h
= (HANDLE
) _get_osfhandle (s
->fd
);
371 if (h
== INVALID_HANDLE_VALUE
)
376 cur
= lseek (s
->fd
, 0, SEEK_CUR
);
379 if (lseek (s
->fd
, length
, SEEK_SET
) == -1)
381 if (!SetEndOfFile (h
))
386 if (lseek (s
->fd
, cur
, SEEK_SET
) == -1)
390 lseek (s
->fd
, cur
, SEEK_SET
);
392 #elif defined HAVE_FTRUNCATE
393 return ftruncate (s
->fd
, length
);
394 #elif defined HAVE_CHSIZE
395 return chsize (s
->fd
, length
);
397 runtime_error ("required ftruncate or chsize support not present");
403 raw_close (unix_stream
* s
)
409 else if (s
->fd
!= STDOUT_FILENO
410 && s
->fd
!= STDERR_FILENO
411 && s
->fd
!= STDIN_FILENO
)
412 retval
= close (s
->fd
);
420 raw_markeor (unix_stream
* s
__attribute__ ((unused
)))
425 static const struct stream_vtable raw_vtable
= {
426 .read
= (void *) raw_read
,
427 .write
= (void *) raw_write
,
428 .seek
= (void *) raw_seek
,
429 .tell
= (void *) raw_tell
,
430 .size
= (void *) raw_size
,
431 .trunc
= (void *) raw_truncate
,
432 .close
= (void *) raw_close
,
433 .flush
= (void *) raw_flush
,
434 .markeor
= (void *) raw_markeor
438 raw_init (unix_stream
* s
)
440 s
->st
.vptr
= &raw_vtable
;
447 /*********************************************************************
448 Buffered I/O functions. These functions have the same semantics as the
449 raw I/O functions above, except that they are buffered in order to
450 improve performance. The buffer must be flushed when switching from
451 reading to writing and vice versa.
452 *********************************************************************/
455 buf_flush (unix_stream
* s
)
459 /* Flushing in read mode means discarding read bytes. */
465 if (s
->physical_offset
!= s
->buffer_offset
466 && lseek (s
->fd
, s
->buffer_offset
, SEEK_SET
) < 0)
469 writelen
= raw_write (s
, s
->buffer
, s
->ndirty
);
471 s
->physical_offset
= s
->buffer_offset
+ writelen
;
473 if (s
->physical_offset
> s
->file_length
)
474 s
->file_length
= s
->physical_offset
;
476 s
->ndirty
-= writelen
;
484 buf_read (unix_stream
* s
, void * buf
, ssize_t nbyte
)
487 s
->buffer_offset
= s
->logical_offset
;
489 /* Is the data we want in the buffer? */
490 if (s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ s
->active
491 && s
->buffer_offset
<= s
->logical_offset
)
492 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
), nbyte
);
495 /* First copy the active bytes if applicable, then read the rest
496 either directly or filling the buffer. */
499 ssize_t to_read
, did_read
;
500 gfc_offset new_logical
;
503 if (s
->logical_offset
>= s
->buffer_offset
504 && s
->buffer_offset
+ s
->active
>= s
->logical_offset
)
506 nread
= s
->active
- (s
->logical_offset
- s
->buffer_offset
);
507 memcpy (buf
, s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
),
511 /* At this point we consider all bytes in the buffer discarded. */
512 to_read
= nbyte
- nread
;
513 new_logical
= s
->logical_offset
+ nread
;
514 if (s
->physical_offset
!= new_logical
515 && lseek (s
->fd
, new_logical
, SEEK_SET
) < 0)
517 s
->buffer_offset
= s
->physical_offset
= new_logical
;
518 if (to_read
<= BUFFER_SIZE
/2)
520 did_read
= raw_read (s
, s
->buffer
, BUFFER_SIZE
);
521 s
->physical_offset
+= did_read
;
522 s
->active
= did_read
;
523 did_read
= (did_read
> to_read
) ? to_read
: did_read
;
524 memcpy (p
, s
->buffer
, did_read
);
528 did_read
= raw_read (s
, p
, to_read
);
529 s
->physical_offset
+= did_read
;
532 nbyte
= did_read
+ nread
;
534 s
->logical_offset
+= nbyte
;
539 buf_write (unix_stream
* s
, const void * buf
, ssize_t nbyte
)
542 s
->buffer_offset
= s
->logical_offset
;
544 /* Does the data fit into the buffer? As a special case, if the
545 buffer is empty and the request is bigger than BUFFER_SIZE/2,
546 write directly. This avoids the case where the buffer would have
547 to be flushed at every write. */
548 if (!(s
->ndirty
== 0 && nbyte
> BUFFER_SIZE
/2)
549 && s
->logical_offset
+ nbyte
<= s
->buffer_offset
+ BUFFER_SIZE
550 && s
->buffer_offset
<= s
->logical_offset
551 && s
->buffer_offset
+ s
->ndirty
>= s
->logical_offset
)
553 memcpy (s
->buffer
+ (s
->logical_offset
- s
->buffer_offset
), buf
, nbyte
);
554 int nd
= (s
->logical_offset
- s
->buffer_offset
) + nbyte
;
560 /* Flush, and either fill the buffer with the new data, or if
561 the request is bigger than the buffer size, write directly
562 bypassing the buffer. */
564 if (nbyte
<= BUFFER_SIZE
/2)
566 memcpy (s
->buffer
, buf
, nbyte
);
567 s
->buffer_offset
= s
->logical_offset
;
572 if (s
->physical_offset
!= s
->logical_offset
)
574 if (lseek (s
->fd
, s
->logical_offset
, SEEK_SET
) < 0)
576 s
->physical_offset
= s
->logical_offset
;
579 nbyte
= raw_write (s
, buf
, nbyte
);
580 s
->physical_offset
+= nbyte
;
583 s
->logical_offset
+= nbyte
;
584 if (s
->logical_offset
> s
->file_length
)
585 s
->file_length
= s
->logical_offset
;
590 /* "Unbuffered" really means I/O statement buffering. For formatted
591 I/O, the fbuf manages this, and then uses raw I/O. For unformatted
592 I/O, buffered I/O is used, and the buffer is flushed at the end of
593 each I/O statement, where this function is called. Alternatively,
594 the buffer is flushed at the end of the record if the buffer is
595 more than half full; this prevents needless seeking back and forth
596 when writing sequential unformatted. */
599 buf_markeor (unix_stream
* s
)
601 if (s
->unbuffered
|| s
->ndirty
>= BUFFER_SIZE
/ 2)
602 return buf_flush (s
);
607 buf_seek (unix_stream
* s
, gfc_offset offset
, int whence
)
614 offset
+= s
->logical_offset
;
617 offset
+= s
->file_length
;
627 s
->logical_offset
= offset
;
632 buf_tell (unix_stream
* s
)
634 return buf_seek (s
, 0, SEEK_CUR
);
638 buf_size (unix_stream
* s
)
640 return s
->file_length
;
644 buf_truncate (unix_stream
* s
, gfc_offset length
)
648 if (buf_flush (s
) != 0)
650 r
= raw_truncate (s
, length
);
652 s
->file_length
= length
;
657 buf_close (unix_stream
* s
)
659 if (buf_flush (s
) != 0)
662 return raw_close (s
);
665 static const struct stream_vtable buf_vtable
= {
666 .read
= (void *) buf_read
,
667 .write
= (void *) buf_write
,
668 .seek
= (void *) buf_seek
,
669 .tell
= (void *) buf_tell
,
670 .size
= (void *) buf_size
,
671 .trunc
= (void *) buf_truncate
,
672 .close
= (void *) buf_close
,
673 .flush
= (void *) buf_flush
,
674 .markeor
= (void *) buf_markeor
678 buf_init (unix_stream
* s
)
680 s
->st
.vptr
= &buf_vtable
;
682 s
->buffer
= xmalloc (BUFFER_SIZE
);
687 /*********************************************************************
688 memory stream functions - These are used for internal files
690 The idea here is that a single stream structure is created and all
691 requests must be satisfied from it. The location and size of the
692 buffer is the character variable supplied to the READ or WRITE
695 *********************************************************************/
698 mem_alloc_r (stream
* strm
, int * len
)
700 unix_stream
* s
= (unix_stream
*) strm
;
702 gfc_offset where
= s
->logical_offset
;
704 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
707 n
= s
->buffer_offset
+ s
->active
- where
;
711 s
->logical_offset
= where
+ *len
;
713 return s
->buffer
+ (where
- s
->buffer_offset
);
718 mem_alloc_r4 (stream
* strm
, int * len
)
720 unix_stream
* s
= (unix_stream
*) strm
;
722 gfc_offset where
= s
->logical_offset
;
724 if (where
< s
->buffer_offset
|| where
> s
->buffer_offset
+ s
->active
)
727 n
= s
->buffer_offset
+ s
->active
- where
;
731 s
->logical_offset
= where
+ *len
;
733 return s
->buffer
+ (where
- s
->buffer_offset
) * 4;
738 mem_alloc_w (stream
* strm
, int * len
)
740 unix_stream
* s
= (unix_stream
*) strm
;
742 gfc_offset where
= s
->logical_offset
;
746 if (where
< s
->buffer_offset
)
749 if (m
> s
->file_length
)
752 s
->logical_offset
= m
;
754 return s
->buffer
+ (where
- s
->buffer_offset
);
759 mem_alloc_w4 (stream
* strm
, int * len
)
761 unix_stream
* s
= (unix_stream
*) strm
;
763 gfc_offset where
= s
->logical_offset
;
764 gfc_char4_t
*result
= (gfc_char4_t
*) s
->buffer
;
768 if (where
< s
->buffer_offset
)
771 if (m
> s
->file_length
)
774 s
->logical_offset
= m
;
775 return &result
[where
- s
->buffer_offset
];
779 /* Stream read function for character(kind=1) internal units. */
782 mem_read (stream
* s
, void * buf
, ssize_t nbytes
)
787 p
= mem_alloc_r (s
, &nb
);
798 /* Stream read function for chracter(kind=4) internal units. */
801 mem_read4 (stream
* s
, void * buf
, ssize_t nbytes
)
806 p
= mem_alloc_r4 (s
, &nb
);
809 memcpy (buf
, p
, nb
* 4);
817 /* Stream write function for character(kind=1) internal units. */
820 mem_write (stream
* s
, const void * buf
, ssize_t nbytes
)
825 p
= mem_alloc_w (s
, &nb
);
836 /* Stream write function for character(kind=4) internal units. */
839 mem_write4 (stream
* s
, const void * buf
, ssize_t nwords
)
844 p
= mem_alloc_w4 (s
, &nw
);
848 *p
++ = (gfc_char4_t
) *((char *) buf
);
857 mem_seek (stream
* strm
, gfc_offset offset
, int whence
)
859 unix_stream
* s
= (unix_stream
*) strm
;
865 offset
+= s
->logical_offset
;
868 offset
+= s
->file_length
;
874 /* Note that for internal array I/O it's actually possible to have a
875 negative offset, so don't check for that. */
876 if (offset
> s
->file_length
)
882 s
->logical_offset
= offset
;
884 /* Returning < 0 is the error indicator for sseek(), so return 0 if
885 offset is negative. Thus if the return value is 0, the caller
886 has to use stell() to get the real value of logical_offset. */
894 mem_tell (stream
* s
)
896 return ((unix_stream
*)s
)->logical_offset
;
901 mem_truncate (unix_stream
* s
__attribute__ ((unused
)),
902 gfc_offset length
__attribute__ ((unused
)))
909 mem_flush (unix_stream
* s
__attribute__ ((unused
)))
916 mem_close (unix_stream
* s
)
923 static const struct stream_vtable mem_vtable
= {
924 .read
= (void *) mem_read
,
925 .write
= (void *) mem_write
,
926 .seek
= (void *) mem_seek
,
927 .tell
= (void *) mem_tell
,
928 /* buf_size is not a typo, we just reuse an identical
930 .size
= (void *) buf_size
,
931 .trunc
= (void *) mem_truncate
,
932 .close
= (void *) mem_close
,
933 .flush
= (void *) mem_flush
,
934 .markeor
= (void *) raw_markeor
937 static const struct stream_vtable mem4_vtable
= {
938 .read
= (void *) mem_read4
,
939 .write
= (void *) mem_write4
,
940 .seek
= (void *) mem_seek
,
941 .tell
= (void *) mem_tell
,
942 /* buf_size is not a typo, we just reuse an identical
944 .size
= (void *) buf_size
,
945 .trunc
= (void *) mem_truncate
,
946 .close
= (void *) mem_close
,
947 .flush
= (void *) mem_flush
,
948 .markeor
= (void *) raw_markeor
951 /*********************************************************************
952 Public functions -- A reimplementation of this module needs to
953 define functional equivalents of the following.
954 *********************************************************************/
956 /* open_internal()-- Returns a stream structure from a character(kind=1)
960 open_internal (char *base
, int length
, gfc_offset offset
)
964 s
= xcalloc (1, sizeof (unix_stream
));
967 s
->buffer_offset
= offset
;
969 s
->active
= s
->file_length
= length
;
971 s
->st
.vptr
= &mem_vtable
;
976 /* open_internal4()-- Returns a stream structure from a character(kind=4)
980 open_internal4 (char *base
, int length
, gfc_offset offset
)
984 s
= xcalloc (1, sizeof (unix_stream
));
987 s
->buffer_offset
= offset
;
989 s
->active
= s
->file_length
= length
* sizeof (gfc_char4_t
);
991 s
->st
.vptr
= &mem4_vtable
;
997 /* fd_to_stream()-- Given an open file descriptor, build a stream
1001 fd_to_stream (int fd
, bool unformatted
)
1003 struct stat statbuf
;
1006 s
= xcalloc (1, sizeof (unix_stream
));
1010 /* Get the current length of the file. */
1012 if (fstat (fd
, &statbuf
) == -1)
1014 s
->st_dev
= s
->st_ino
= -1;
1019 return (stream
*) s
;
1022 s
->st_dev
= statbuf
.st_dev
;
1023 s
->st_ino
= statbuf
.st_ino
;
1024 s
->file_length
= statbuf
.st_size
;
1026 /* Only use buffered IO for regular files. */
1027 if (S_ISREG (statbuf
.st_mode
)
1028 && !options
.all_unbuffered
1029 && !(options
.unbuffered_preconnected
&&
1030 (s
->fd
== STDIN_FILENO
1031 || s
->fd
== STDOUT_FILENO
1032 || s
->fd
== STDERR_FILENO
)))
1038 s
->unbuffered
= true;
1045 return (stream
*) s
;
1049 /* Given the Fortran unit number, convert it to a C file descriptor. */
1052 unit_to_fd (int unit
)
1057 us
= find_unit (unit
);
1061 fd
= ((unix_stream
*) us
->s
)->fd
;
1067 /* Set the close-on-exec flag for an existing fd, if the system
1070 static void __attribute__ ((unused
))
1071 set_close_on_exec (int fd
__attribute__ ((unused
)))
1073 /* Mingw does not define F_SETFD. */
1074 #if defined(HAVE_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
1076 fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
1081 /* Helper function for tempfile(). Tries to open a temporary file in
1082 the directory specified by tempdir. If successful, the file name is
1083 stored in fname and the descriptor returned. Returns -1 on
1087 tempfile_open (const char *tempdir
, char **fname
)
1090 const char *slash
= "/";
1091 #if defined(HAVE_UMASK) && defined(HAVE_MKSTEMP)
1098 /* Check for the special case that tempdir ends with a slash or
1100 size_t tempdirlen
= strlen (tempdir
);
1101 if (*tempdir
== 0 || tempdir
[tempdirlen
- 1] == '/'
1103 || tempdir
[tempdirlen
- 1] == '\\'
1108 // Take care that the template is longer in the mktemp() branch.
1109 char * template = xmalloc (tempdirlen
+ 23);
1112 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpXXXXXX",
1116 /* Temporarily set the umask such that the file has 0600 permissions. */
1117 mode_mask
= umask (S_IXUSR
| S_IRWXG
| S_IRWXO
);
1120 #if defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
1121 fd
= mkostemp (template, O_CLOEXEC
);
1123 fd
= mkstemp (template);
1124 set_close_on_exec (fd
);
1128 (void) umask (mode_mask
);
1131 #else /* HAVE_MKSTEMP */
1134 size_t slashlen
= strlen (slash
);
1135 int flags
= O_RDWR
| O_CREAT
| O_EXCL
;
1136 #if defined(HAVE_CRLF) && defined(O_BINARY)
1144 snprintf (template, tempdirlen
+ 23, "%s%sgfortrantmpaaaXXXXXX",
1149 template[tempdirlen
+ slashlen
+ 13] = 'a' + (c
% 26);
1151 template[tempdirlen
+ slashlen
+ 12] = 'a' + (c
% 26);
1153 template[tempdirlen
+ slashlen
+ 11] = 'a' + (c
% 26);
1158 if (!mktemp (template))
1165 fd
= open (template, flags
, S_IRUSR
| S_IWUSR
);
1167 while (fd
== -1 && errno
== EEXIST
);
1169 set_close_on_exec (fd
);
1171 #endif /* HAVE_MKSTEMP */
1178 /* tempfile()-- Generate a temporary filename for a scratch file and
1179 * open it. mkstemp() opens the file for reading and writing, but the
1180 * library mode prevents anything that is not allowed. The descriptor
1181 * is returned, which is -1 on error. The template is pointed to by
1182 * opp->file, which is copied into the unit structure
1183 * and freed later. */
1186 tempfile (st_parameter_open
*opp
)
1188 const char *tempdir
;
1192 tempdir
= secure_getenv ("TMPDIR");
1193 fd
= tempfile_open (tempdir
, &fname
);
1197 char buffer
[MAX_PATH
+ 1];
1199 ret
= GetTempPath (MAX_PATH
, buffer
);
1200 /* If we are not able to get a temp-directory, we use
1201 current directory. */
1202 if (ret
> MAX_PATH
|| !ret
)
1206 tempdir
= strdup (buffer
);
1207 fd
= tempfile_open (tempdir
, &fname
);
1209 #elif defined(__CYGWIN__)
1212 tempdir
= secure_getenv ("TMP");
1213 fd
= tempfile_open (tempdir
, &fname
);
1217 tempdir
= secure_getenv ("TEMP");
1218 fd
= tempfile_open (tempdir
, &fname
);
1222 fd
= tempfile_open (P_tmpdir
, &fname
);
1225 opp
->file_len
= strlen (fname
); /* Don't include trailing nul */
1231 /* regular_file2()-- Open a regular file.
1232 * Change flags->action if it is ACTION_UNSPECIFIED on entry,
1233 * unless an error occurs.
1234 * Returns the descriptor, which is less than zero on error. */
1237 regular_file2 (const char *path
, st_parameter_open
*opp
, unit_flags
*flags
)
1241 int crflag
, crflag2
;
1245 if (opp
->file_len
== 7)
1247 if (strncmp (path
, "CONOUT$", 7) == 0
1248 || strncmp (path
, "CONERR$", 7) == 0)
1250 fd
= open ("/dev/conout", O_WRONLY
);
1251 flags
->action
= ACTION_WRITE
;
1256 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1258 fd
= open ("/dev/conin", O_RDONLY
);
1259 flags
->action
= ACTION_READ
;
1266 if (opp
->file_len
== 7)
1268 if (strncmp (path
, "CONOUT$", 7) == 0
1269 || strncmp (path
, "CONERR$", 7) == 0)
1271 fd
= open ("CONOUT$", O_WRONLY
);
1272 flags
->action
= ACTION_WRITE
;
1277 if (opp
->file_len
== 6 && strncmp (path
, "CONIN$", 6) == 0)
1279 fd
= open ("CONIN$", O_RDONLY
);
1280 flags
->action
= ACTION_READ
;
1285 switch (flags
->action
)
1295 case ACTION_READWRITE
:
1296 case ACTION_UNSPECIFIED
:
1301 internal_error (&opp
->common
, "regular_file(): Bad action");
1304 switch (flags
->status
)
1307 crflag
= O_CREAT
| O_EXCL
;
1310 case STATUS_OLD
: /* open will fail if the file does not exist*/
1314 case STATUS_UNKNOWN
:
1315 if (rwflag
== O_RDONLY
)
1321 case STATUS_REPLACE
:
1322 crflag
= O_CREAT
| O_TRUNC
;
1326 /* Note: STATUS_SCRATCH is handled by tempfile () and should
1327 never be seen here. */
1328 internal_error (&opp
->common
, "regular_file(): Bad status");
1331 /* rwflag |= O_LARGEFILE; */
1333 #if defined(HAVE_CRLF) && defined(O_BINARY)
1338 crflag
|= O_CLOEXEC
;
1341 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
;
1342 fd
= open (path
, rwflag
| crflag
, mode
);
1343 if (flags
->action
!= ACTION_UNSPECIFIED
)
1348 flags
->action
= ACTION_READWRITE
;
1351 if (errno
!= EACCES
&& errno
!= EPERM
&& errno
!= EROFS
)
1354 /* retry for read-only access */
1356 if (flags
->status
== STATUS_UNKNOWN
)
1357 crflag2
= crflag
& ~(O_CREAT
);
1360 fd
= open (path
, rwflag
| crflag2
, mode
);
1363 flags
->action
= ACTION_READ
;
1364 return fd
; /* success */
1367 if (errno
!= EACCES
&& errno
!= EPERM
&& errno
!= ENOENT
)
1368 return fd
; /* failure */
1370 /* retry for write-only access */
1372 fd
= open (path
, rwflag
| crflag
, mode
);
1375 flags
->action
= ACTION_WRITE
;
1376 return fd
; /* success */
1378 return fd
; /* failure */
1382 /* Wrapper around regular_file2, to make sure we free the path after
1386 regular_file (st_parameter_open
*opp
, unit_flags
*flags
)
1388 char *path
= fc_strdup (opp
->file
, opp
->file_len
);
1389 int fd
= regular_file2 (path
, opp
, flags
);
1394 /* open_external()-- Open an external file, unix specific version.
1395 * Change flags->action if it is ACTION_UNSPECIFIED on entry.
1396 * Returns NULL on operating system error. */
1399 open_external (st_parameter_open
*opp
, unit_flags
*flags
)
1403 if (flags
->status
== STATUS_SCRATCH
)
1405 fd
= tempfile (opp
);
1406 if (flags
->action
== ACTION_UNSPECIFIED
)
1407 flags
->action
= ACTION_READWRITE
;
1409 #if HAVE_UNLINK_OPEN_FILE
1410 /* We can unlink scratch files now and it will go away when closed. */
1417 /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1419 fd
= regular_file (opp
, flags
);
1421 set_close_on_exec (fd
);
1429 return fd_to_stream (fd
, flags
->form
== FORM_UNFORMATTED
);
1433 /* input_stream()-- Return a stream pointer to the default input stream.
1434 * Called on initialization. */
1439 return fd_to_stream (STDIN_FILENO
, false);
1443 /* output_stream()-- Return a stream pointer to the default output stream.
1444 * Called on initialization. */
1447 output_stream (void)
1451 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1452 setmode (STDOUT_FILENO
, O_BINARY
);
1455 s
= fd_to_stream (STDOUT_FILENO
, false);
1460 /* error_stream()-- Return a stream pointer to the default error stream.
1461 * Called on initialization. */
1468 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1469 setmode (STDERR_FILENO
, O_BINARY
);
1472 s
= fd_to_stream (STDERR_FILENO
, false);
1477 /* compare_file_filename()-- Given an open stream and a fortran string
1478 * that is a filename, figure out if the file is the same as the
1482 compare_file_filename (gfc_unit
*u
, const char *name
, int len
)
1486 #ifdef HAVE_WORKING_STAT
1494 char *path
= fc_strdup (name
, len
);
1496 /* If the filename doesn't exist, then there is no match with the
1499 if (stat (path
, &st
) < 0)
1505 #ifdef HAVE_WORKING_STAT
1506 s
= (unix_stream
*) (u
->s
);
1507 ret
= (st
.st_dev
== s
->st_dev
) && (st
.st_ino
== s
->st_ino
);
1512 /* We try to match files by a unique ID. On some filesystems (network
1513 fs and FAT), we can't generate this unique ID, and will simply compare
1515 id1
= id_from_path (path
);
1516 id2
= id_from_fd (((unix_stream
*) (u
->s
))->fd
);
1524 ret
= (strcmp(path
, u
->filename
) == 0);
1534 #ifdef HAVE_WORKING_STAT
1535 # define FIND_FILE0_DECL struct stat *st
1536 # define FIND_FILE0_ARGS st
1538 # define FIND_FILE0_DECL uint64_t id, const char *path
1539 # define FIND_FILE0_ARGS id, path
1542 /* find_file0()-- Recursive work function for find_file() */
1545 find_file0 (gfc_unit
*u
, FIND_FILE0_DECL
)
1548 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1555 #ifdef HAVE_WORKING_STAT
1558 unix_stream
*s
= (unix_stream
*) (u
->s
);
1559 if (st
[0].st_dev
== s
->st_dev
&& st
[0].st_ino
== s
->st_ino
)
1564 if (u
->s
&& ((id1
= id_from_fd (((unix_stream
*) u
->s
)->fd
)) || id1
))
1571 if (u
->filename
&& strcmp (u
->filename
, path
) == 0)
1575 v
= find_file0 (u
->left
, FIND_FILE0_ARGS
);
1579 v
= find_file0 (u
->right
, FIND_FILE0_ARGS
);
1587 /* find_file()-- Take the current filename and see if there is a unit
1588 * that has the file already open. Returns a pointer to the unit if so. */
1591 find_file (const char *file
, gfc_charlen_type file_len
)
1595 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1599 char *path
= fc_strdup (file
, file_len
);
1601 if (stat (path
, &st
[0]) < 0)
1607 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1608 id
= id_from_path (path
);
1611 __gthread_mutex_lock (&unit_lock
);
1613 u
= find_file0 (unit_root
, FIND_FILE0_ARGS
);
1617 if (! __gthread_mutex_trylock (&u
->lock
))
1619 /* assert (u->closed == 0); */
1620 __gthread_mutex_unlock (&unit_lock
);
1624 inc_waiting_locked (u
);
1626 __gthread_mutex_unlock (&unit_lock
);
1629 __gthread_mutex_lock (&u
->lock
);
1632 __gthread_mutex_lock (&unit_lock
);
1633 __gthread_mutex_unlock (&u
->lock
);
1634 if (predec_waiting_locked (u
) == 0)
1639 dec_waiting_unlocked (u
);
1647 flush_all_units_1 (gfc_unit
*u
, int min_unit
)
1651 if (u
->unit_number
> min_unit
)
1653 gfc_unit
*r
= flush_all_units_1 (u
->left
, min_unit
);
1657 if (u
->unit_number
>= min_unit
)
1659 if (__gthread_mutex_trylock (&u
->lock
))
1663 __gthread_mutex_unlock (&u
->lock
);
1671 flush_all_units (void)
1676 __gthread_mutex_lock (&unit_lock
);
1679 u
= flush_all_units_1 (unit_root
, min_unit
);
1681 inc_waiting_locked (u
);
1682 __gthread_mutex_unlock (&unit_lock
);
1686 __gthread_mutex_lock (&u
->lock
);
1688 min_unit
= u
->unit_number
+ 1;
1693 __gthread_mutex_lock (&unit_lock
);
1694 __gthread_mutex_unlock (&u
->lock
);
1695 (void) predec_waiting_locked (u
);
1699 __gthread_mutex_lock (&unit_lock
);
1700 __gthread_mutex_unlock (&u
->lock
);
1701 if (predec_waiting_locked (u
) == 0)
1709 /* delete_file()-- Given a unit structure, delete the file associated
1710 * with the unit. Returns nonzero if something went wrong. */
1713 delete_file (gfc_unit
* u
)
1715 return unlink (u
->filename
);
1719 /* file_exists()-- Returns nonzero if the current filename exists on
1723 file_exists (const char *file
, gfc_charlen_type file_len
)
1725 char *path
= fc_strdup (file
, file_len
);
1726 int res
= !(access (path
, F_OK
));
1732 /* file_size()-- Returns the size of the file. */
1735 file_size (const char *file
, gfc_charlen_type file_len
)
1737 char *path
= fc_strdup (file
, file_len
);
1738 struct stat statbuf
;
1739 int err
= stat (path
, &statbuf
);
1743 return (GFC_IO_INT
) statbuf
.st_size
;
1746 static const char yes
[] = "YES", no
[] = "NO", unknown
[] = "UNKNOWN";
1748 /* inquire_sequential()-- Given a fortran string, determine if the
1749 * file is suitable for sequential access. Returns a C-style
1753 inquire_sequential (const char *string
, int len
)
1755 struct stat statbuf
;
1760 char *path
= fc_strdup (string
, len
);
1761 int err
= stat (path
, &statbuf
);
1766 if (S_ISREG (statbuf
.st_mode
) ||
1767 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1770 if (S_ISDIR (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1777 /* inquire_direct()-- Given a fortran string, determine if the file is
1778 * suitable for direct access. Returns a C-style string. */
1781 inquire_direct (const char *string
, int len
)
1783 struct stat statbuf
;
1788 char *path
= fc_strdup (string
, len
);
1789 int err
= stat (path
, &statbuf
);
1794 if (S_ISREG (statbuf
.st_mode
) || S_ISBLK (statbuf
.st_mode
))
1797 if (S_ISDIR (statbuf
.st_mode
) ||
1798 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1805 /* inquire_formatted()-- Given a fortran string, determine if the file
1806 * is suitable for formatted form. Returns a C-style string. */
1809 inquire_formatted (const char *string
, int len
)
1811 struct stat statbuf
;
1816 char *path
= fc_strdup (string
, len
);
1817 int err
= stat (path
, &statbuf
);
1822 if (S_ISREG (statbuf
.st_mode
) ||
1823 S_ISBLK (statbuf
.st_mode
) ||
1824 S_ISCHR (statbuf
.st_mode
) || S_ISFIFO (statbuf
.st_mode
))
1827 if (S_ISDIR (statbuf
.st_mode
))
1834 /* inquire_unformatted()-- Given a fortran string, determine if the file
1835 * is suitable for unformatted form. Returns a C-style string. */
1838 inquire_unformatted (const char *string
, int len
)
1840 return inquire_formatted (string
, len
);
1844 /* inquire_access()-- Given a fortran string, determine if the file is
1845 * suitable for access. */
1848 inquire_access (const char *string
, int len
, int mode
)
1852 char *path
= fc_strdup (string
, len
);
1853 int res
= access (path
, mode
);
1862 /* inquire_read()-- Given a fortran string, determine if the file is
1863 * suitable for READ access. */
1866 inquire_read (const char *string
, int len
)
1868 return inquire_access (string
, len
, R_OK
);
1872 /* inquire_write()-- Given a fortran string, determine if the file is
1873 * suitable for READ access. */
1876 inquire_write (const char *string
, int len
)
1878 return inquire_access (string
, len
, W_OK
);
1882 /* inquire_readwrite()-- Given a fortran string, determine if the file is
1883 * suitable for read and write access. */
1886 inquire_readwrite (const char *string
, int len
)
1888 return inquire_access (string
, len
, R_OK
| W_OK
);
1893 stream_isatty (stream
*s
)
1895 return isatty (((unix_stream
*) s
)->fd
);
1899 stream_ttyname (stream
*s
__attribute__ ((unused
)),
1900 char * buf
__attribute__ ((unused
)),
1901 size_t buflen
__attribute__ ((unused
)))
1903 #ifdef HAVE_TTYNAME_R
1904 return ttyname_r (((unix_stream
*) s
)->fd
, buf
, buflen
);
1905 #elif defined HAVE_TTYNAME
1908 p
= ttyname (((unix_stream
*) s
)->fd
);
1914 memcpy (buf
, p
, plen
);
1924 /* How files are stored: This is an operating-system specific issue,
1925 and therefore belongs here. There are three cases to consider.
1928 Records are written as block of bytes corresponding to the record
1929 length of the file. This goes for both formatted and unformatted
1930 records. Positioning is done explicitly for each data transfer,
1931 so positioning is not much of an issue.
1933 Sequential Formatted:
1934 Records are separated by newline characters. The newline character
1935 is prohibited from appearing in a string. If it does, this will be
1936 messed up on the next read. End of file is also the end of a record.
1938 Sequential Unformatted:
1939 In this case, we are merely copying bytes to and from main storage,
1940 yet we need to keep track of varying record lengths. We adopt
1941 the solution used by f2c. Each record contains a pair of length
1944 Length of record n in bytes
1946 Length of record n in bytes
1948 Length of record n+1 in bytes
1950 Length of record n+1 in bytes
1952 The length is stored at the end of a record to allow backspacing to the
1953 previous record. Between data transfer statements, the file pointer
1954 is left pointing to the first length of the current record.
1956 ENDFILE records are never explicitly stored.