PR lto/42531
[official-gcc.git] / libgfortran / io / unix.c
blob07aa4d95972a1f91cfd77f226722f15eeb7c02e3
1 /* Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
2 Free Software Foundation, Inc.
3 Contributed by Andy Vaught
4 F2003 I/O support contributed by Jerry DeLisle
6 This file is part of the GNU Fortran 95 runtime library (libgfortran).
8 Libgfortran is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 Libgfortran is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 Under Section 7 of GPL version 3, you are granted additional
19 permissions described in the GCC Runtime Library Exception, version
20 3.1, as published by the Free Software Foundation.
22 You should have received a copy of the GNU General Public License and
23 a copy of the GCC Runtime Library Exception along with this program;
24 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
25 <http://www.gnu.org/licenses/>. */
27 /* Unix stream I/O module */
29 #include "io.h"
30 #include "unix.h"
31 #include <stdlib.h>
32 #include <limits.h>
34 #include <unistd.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <assert.h>
39 #include <string.h>
40 #include <errno.h>
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. */
45 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
47 #define WIN32_LEAN_AND_MEAN
48 #include <windows.h>
50 #define lseek _lseeki64
52 static uint64_t
53 id_from_handle (HANDLE hFile)
55 BY_HANDLE_FILE_INFORMATION FileInformation;
57 if (hFile == INVALID_HANDLE_VALUE)
58 return 0;
60 memset (&FileInformation, 0, sizeof(FileInformation));
61 if (!GetFileInformationByHandle (hFile, &FileInformation))
62 return 0;
64 return ((uint64_t) FileInformation.nFileIndexLow)
65 | (((uint64_t) FileInformation.nFileIndexHigh) << 32);
69 static uint64_t
70 id_from_path (const char *path)
72 HANDLE hFile;
73 uint64_t res;
75 if (!path || !*path || access (path, F_OK))
76 return (uint64_t) -1;
78 hFile = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
79 FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_READONLY,
80 NULL);
81 res = id_from_handle (hFile);
82 CloseHandle (hFile);
83 return res;
87 static uint64_t
88 id_from_fd (const int fd)
90 return id_from_handle ((HANDLE) _get_osfhandle (fd));
93 #endif
95 #ifndef PATH_MAX
96 #define PATH_MAX 1024
97 #endif
99 #ifndef PROT_READ
100 #define PROT_READ 1
101 #endif
103 #ifndef PROT_WRITE
104 #define PROT_WRITE 2
105 #endif
107 /* These flags aren't defined on all targets (mingw32), so provide them
108 here. */
109 #ifndef S_IRGRP
110 #define S_IRGRP 0
111 #endif
113 #ifndef S_IWGRP
114 #define S_IWGRP 0
115 #endif
117 #ifndef S_IROTH
118 #define S_IROTH 0
119 #endif
121 #ifndef S_IWOTH
122 #define S_IWOTH 0
123 #endif
126 /* Unix and internal stream I/O module */
128 static const int BUFFER_SIZE = 8192;
130 typedef struct
132 stream st;
134 gfc_offset buffer_offset; /* File offset of the start of the buffer */
135 gfc_offset physical_offset; /* Current physical file offset */
136 gfc_offset logical_offset; /* Current logical file offset */
137 gfc_offset file_length; /* Length of the file, -1 if not seekable. */
139 char *buffer; /* Pointer to the buffer. */
140 int fd; /* The POSIX file descriptor. */
142 int active; /* Length of valid bytes in the buffer */
144 int prot;
145 int ndirty; /* Dirty bytes starting at buffer_offset */
147 int special_file; /* =1 if the fd refers to a special file */
149 unix_stream;
152 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
153 * standard descriptors, returning a non-standard descriptor. If the
154 * user specifies that system errors should go to standard output,
155 * then closes standard output, we don't want the system errors to a
156 * file that has been given file descriptor 1 or 0. We want to send
157 * the error to the invalid descriptor. */
159 static int
160 fix_fd (int fd)
162 #ifdef HAVE_DUP
163 int input, output, error;
165 input = output = error = 0;
167 /* Unix allocates the lowest descriptors first, so a loop is not
168 required, but this order is. */
169 if (fd == STDIN_FILENO)
171 fd = dup (fd);
172 input = 1;
174 if (fd == STDOUT_FILENO)
176 fd = dup (fd);
177 output = 1;
179 if (fd == STDERR_FILENO)
181 fd = dup (fd);
182 error = 1;
185 if (input)
186 close (STDIN_FILENO);
187 if (output)
188 close (STDOUT_FILENO);
189 if (error)
190 close (STDERR_FILENO);
191 #endif
193 return fd;
197 /* If the stream corresponds to a preconnected unit, we flush the
198 corresponding C stream. This is bugware for mixed C-Fortran codes
199 where the C code doesn't flush I/O before returning. */
200 void
201 flush_if_preconnected (stream * s)
203 int fd;
205 fd = ((unix_stream *) s)->fd;
206 if (fd == STDIN_FILENO)
207 fflush (stdin);
208 else if (fd == STDOUT_FILENO)
209 fflush (stdout);
210 else if (fd == STDERR_FILENO)
211 fflush (stderr);
215 /* get_oserror()-- Get the most recent operating system error. For
216 * unix, this is errno. */
218 const char *
219 get_oserror (void)
221 return strerror (errno);
225 /********************************************************************
226 Raw I/O functions (read, write, seek, tell, truncate, close).
228 These functions wrap the basic POSIX I/O syscalls. Any deviation in
229 semantics is a bug, except the following: write restarts in case
230 of being interrupted by a signal, and as the first argument the
231 functions take the unix_stream struct rather than an integer file
232 descriptor. Also, for POSIX read() and write() a nbyte argument larger
233 than SSIZE_MAX is undefined; here the type of nbyte is ssize_t rather
234 than size_t as for POSIX read/write.
235 *********************************************************************/
237 static int
238 raw_flush (unix_stream * s __attribute__ ((unused)))
240 return 0;
243 static ssize_t
244 raw_read (unix_stream * s, void * buf, ssize_t nbyte)
246 /* For read we can't do I/O in a loop like raw_write does, because
247 that will break applications that wait for interactive I/O. */
248 return read (s->fd, buf, nbyte);
251 static ssize_t
252 raw_write (unix_stream * s, const void * buf, ssize_t nbyte)
254 ssize_t trans, bytes_left;
255 char *buf_st;
257 bytes_left = nbyte;
258 buf_st = (char *) buf;
260 /* We must write in a loop since some systems don't restart system
261 calls in case of a signal. */
262 while (bytes_left > 0)
264 trans = write (s->fd, buf_st, bytes_left);
265 if (trans < 0)
267 if (errno == EINTR)
268 continue;
269 else
270 return trans;
272 buf_st += trans;
273 bytes_left -= trans;
276 return nbyte - bytes_left;
279 static gfc_offset
280 raw_seek (unix_stream * s, gfc_offset offset, int whence)
282 return lseek (s->fd, offset, whence);
285 static gfc_offset
286 raw_tell (unix_stream * s)
288 return lseek (s->fd, 0, SEEK_CUR);
291 static int
292 raw_truncate (unix_stream * s, gfc_offset length)
294 #ifdef __MINGW32__
295 HANDLE h;
296 gfc_offset cur;
298 if (isatty (s->fd))
300 errno = EBADF;
301 return -1;
303 h = _get_osfhandle (s->fd);
304 if (h == INVALID_HANDLE_VALUE)
306 errno = EBADF;
307 return -1;
309 cur = lseek (s->fd, 0, SEEK_CUR);
310 if (cur == -1)
311 return -1;
312 if (lseek (s->fd, length, SEEK_SET) == -1)
313 goto error;
314 if (!SetEndOfFile (h))
316 errno = EBADF;
317 goto error;
319 if (lseek (s->fd, cur, SEEK_SET) == -1)
320 return -1;
321 return 0;
322 error:
323 lseek (s->fd, cur, SEEK_SET);
324 return -1;
325 #elif defined HAVE_FTRUNCATE
326 return ftruncate (s->fd, length);
327 #elif defined HAVE_CHSIZE
328 return chsize (s->fd, length);
329 #else
330 runtime_error ("required ftruncate or chsize support not present");
331 return -1;
332 #endif
335 static int
336 raw_close (unix_stream * s)
338 int retval;
340 if (s->fd != STDOUT_FILENO
341 && s->fd != STDERR_FILENO
342 && s->fd != STDIN_FILENO)
343 retval = close (s->fd);
344 else
345 retval = 0;
346 free_mem (s);
347 return retval;
350 static int
351 raw_init (unix_stream * s)
353 s->st.read = (void *) raw_read;
354 s->st.write = (void *) raw_write;
355 s->st.seek = (void *) raw_seek;
356 s->st.tell = (void *) raw_tell;
357 s->st.trunc = (void *) raw_truncate;
358 s->st.close = (void *) raw_close;
359 s->st.flush = (void *) raw_flush;
361 s->buffer = NULL;
362 return 0;
366 /*********************************************************************
367 Buffered I/O functions. These functions have the same semantics as the
368 raw I/O functions above, except that they are buffered in order to
369 improve performance. The buffer must be flushed when switching from
370 reading to writing and vice versa.
371 *********************************************************************/
373 static int
374 buf_flush (unix_stream * s)
376 int writelen;
378 /* Flushing in read mode means discarding read bytes. */
379 s->active = 0;
381 if (s->ndirty == 0)
382 return 0;
384 if (s->file_length != -1 && s->physical_offset != s->buffer_offset
385 && lseek (s->fd, s->buffer_offset, SEEK_SET) < 0)
386 return -1;
388 writelen = raw_write (s, s->buffer, s->ndirty);
390 s->physical_offset = s->buffer_offset + writelen;
392 /* Don't increment file_length if the file is non-seekable. */
393 if (s->file_length != -1 && s->physical_offset > s->file_length)
394 s->file_length = s->physical_offset;
396 s->ndirty -= writelen;
397 if (s->ndirty != 0)
398 return -1;
400 return 0;
403 static ssize_t
404 buf_read (unix_stream * s, void * buf, ssize_t nbyte)
406 if (s->active == 0)
407 s->buffer_offset = s->logical_offset;
409 /* Is the data we want in the buffer? */
410 if (s->logical_offset + nbyte <= s->buffer_offset + s->active
411 && s->buffer_offset <= s->logical_offset)
412 memcpy (buf, s->buffer + (s->logical_offset - s->buffer_offset), nbyte);
413 else
415 /* First copy the active bytes if applicable, then read the rest
416 either directly or filling the buffer. */
417 char *p;
418 int nread = 0;
419 ssize_t to_read, did_read;
420 gfc_offset new_logical;
422 p = (char *) buf;
423 if (s->logical_offset >= s->buffer_offset
424 && s->buffer_offset + s->active >= s->logical_offset)
426 nread = s->active - (s->logical_offset - s->buffer_offset);
427 memcpy (buf, s->buffer + (s->logical_offset - s->buffer_offset),
428 nread);
429 p += nread;
431 /* At this point we consider all bytes in the buffer discarded. */
432 to_read = nbyte - nread;
433 new_logical = s->logical_offset + nread;
434 if (s->file_length != -1 && s->physical_offset != new_logical
435 && lseek (s->fd, new_logical, SEEK_SET) < 0)
436 return -1;
437 s->buffer_offset = s->physical_offset = new_logical;
438 if (to_read <= BUFFER_SIZE/2)
440 did_read = raw_read (s, s->buffer, BUFFER_SIZE);
441 s->physical_offset += did_read;
442 s->active = did_read;
443 did_read = (did_read > to_read) ? to_read : did_read;
444 memcpy (p, s->buffer, did_read);
446 else
448 did_read = raw_read (s, p, to_read);
449 s->physical_offset += did_read;
450 s->active = 0;
452 nbyte = did_read + nread;
454 s->logical_offset += nbyte;
455 return nbyte;
458 static ssize_t
459 buf_write (unix_stream * s, const void * buf, ssize_t nbyte)
461 if (s->ndirty == 0)
462 s->buffer_offset = s->logical_offset;
464 /* Does the data fit into the buffer? As a special case, if the
465 buffer is empty and the request is bigger than BUFFER_SIZE/2,
466 write directly. This avoids the case where the buffer would have
467 to be flushed at every write. */
468 if (!(s->ndirty == 0 && nbyte > BUFFER_SIZE/2)
469 && s->logical_offset + nbyte <= s->buffer_offset + BUFFER_SIZE
470 && s->buffer_offset <= s->logical_offset
471 && s->buffer_offset + s->ndirty >= s->logical_offset)
473 memcpy (s->buffer + (s->logical_offset - s->buffer_offset), buf, nbyte);
474 int nd = (s->logical_offset - s->buffer_offset) + nbyte;
475 if (nd > s->ndirty)
476 s->ndirty = nd;
478 else
480 /* Flush, and either fill the buffer with the new data, or if
481 the request is bigger than the buffer size, write directly
482 bypassing the buffer. */
483 buf_flush (s);
484 if (nbyte <= BUFFER_SIZE/2)
486 memcpy (s->buffer, buf, nbyte);
487 s->buffer_offset = s->logical_offset;
488 s->ndirty += nbyte;
490 else
492 if (s->file_length != -1 && s->physical_offset != s->logical_offset
493 && lseek (s->fd, s->logical_offset, SEEK_SET) < 0)
494 return -1;
495 nbyte = raw_write (s, buf, nbyte);
496 s->physical_offset += nbyte;
499 s->logical_offset += nbyte;
500 /* Don't increment file_length if the file is non-seekable. */
501 if (s->file_length != -1 && s->logical_offset > s->file_length)
502 s->file_length = s->logical_offset;
503 return nbyte;
506 static gfc_offset
507 buf_seek (unix_stream * s, gfc_offset offset, int whence)
509 switch (whence)
511 case SEEK_SET:
512 break;
513 case SEEK_CUR:
514 offset += s->logical_offset;
515 break;
516 case SEEK_END:
517 offset += s->file_length;
518 break;
519 default:
520 return -1;
522 if (offset < 0)
524 errno = EINVAL;
525 return -1;
527 s->logical_offset = offset;
528 return offset;
531 static gfc_offset
532 buf_tell (unix_stream * s)
534 return s->logical_offset;
537 static int
538 buf_truncate (unix_stream * s, gfc_offset length)
540 int r;
542 if (buf_flush (s) != 0)
543 return -1;
544 r = raw_truncate (s, length);
545 if (r == 0)
546 s->file_length = length;
547 return r;
550 static int
551 buf_close (unix_stream * s)
553 if (buf_flush (s) != 0)
554 return -1;
555 free_mem (s->buffer);
556 return raw_close (s);
559 static int
560 buf_init (unix_stream * s)
562 s->st.read = (void *) buf_read;
563 s->st.write = (void *) buf_write;
564 s->st.seek = (void *) buf_seek;
565 s->st.tell = (void *) buf_tell;
566 s->st.trunc = (void *) buf_truncate;
567 s->st.close = (void *) buf_close;
568 s->st.flush = (void *) buf_flush;
570 s->buffer = get_mem (BUFFER_SIZE);
571 return 0;
575 /*********************************************************************
576 memory stream functions - These are used for internal files
578 The idea here is that a single stream structure is created and all
579 requests must be satisfied from it. The location and size of the
580 buffer is the character variable supplied to the READ or WRITE
581 statement.
583 *********************************************************************/
586 char *
587 mem_alloc_r (stream * strm, int * len)
589 unix_stream * s = (unix_stream *) strm;
590 gfc_offset n;
591 gfc_offset where = s->logical_offset;
593 if (where < s->buffer_offset || where > s->buffer_offset + s->active)
594 return NULL;
596 n = s->buffer_offset + s->active - where;
597 if (*len > n)
598 *len = n;
600 s->logical_offset = where + *len;
602 return s->buffer + (where - s->buffer_offset);
606 char *
607 mem_alloc_w (stream * strm, int * len)
609 unix_stream * s = (unix_stream *) strm;
610 gfc_offset m;
611 gfc_offset where = s->logical_offset;
613 m = where + *len;
615 if (where < s->buffer_offset)
616 return NULL;
618 if (m > s->file_length)
619 return NULL;
621 s->logical_offset = m;
623 return s->buffer + (where - s->buffer_offset);
627 /* Stream read function for internal units. */
629 static ssize_t
630 mem_read (stream * s, void * buf, ssize_t nbytes)
632 void *p;
633 int nb = nbytes;
635 p = mem_alloc_r (s, &nb);
636 if (p)
638 memcpy (buf, p, nb);
639 return (ssize_t) nb;
641 else
642 return 0;
646 /* Stream write function for internal units. This is not actually used
647 at the moment, as all internal IO is formatted and the formatted IO
648 routines use mem_alloc_w_at. */
650 static ssize_t
651 mem_write (stream * s, const void * buf, ssize_t nbytes)
653 void *p;
654 int nb = nbytes;
656 p = mem_alloc_w (s, &nb);
657 if (p)
659 memcpy (p, buf, nb);
660 return (ssize_t) nb;
662 else
663 return 0;
667 static gfc_offset
668 mem_seek (stream * strm, gfc_offset offset, int whence)
670 unix_stream * s = (unix_stream *) strm;
671 switch (whence)
673 case SEEK_SET:
674 break;
675 case SEEK_CUR:
676 offset += s->logical_offset;
677 break;
678 case SEEK_END:
679 offset += s->file_length;
680 break;
681 default:
682 return -1;
685 /* Note that for internal array I/O it's actually possible to have a
686 negative offset, so don't check for that. */
687 if (offset > s->file_length)
689 errno = EINVAL;
690 return -1;
693 s->logical_offset = offset;
695 /* Returning < 0 is the error indicator for sseek(), so return 0 if
696 offset is negative. Thus if the return value is 0, the caller
697 has to use stell() to get the real value of logical_offset. */
698 if (offset >= 0)
699 return offset;
700 return 0;
704 static gfc_offset
705 mem_tell (stream * s)
707 return ((unix_stream *)s)->logical_offset;
711 static int
712 mem_truncate (unix_stream * s __attribute__ ((unused)),
713 gfc_offset length __attribute__ ((unused)))
715 return 0;
719 static int
720 mem_flush (unix_stream * s __attribute__ ((unused)))
722 return 0;
726 static int
727 mem_close (unix_stream * s)
729 if (s != NULL)
730 free_mem (s);
732 return 0;
736 /*********************************************************************
737 Public functions -- A reimplementation of this module needs to
738 define functional equivalents of the following.
739 *********************************************************************/
741 /* empty_internal_buffer()-- Zero the buffer of Internal file */
743 void
744 empty_internal_buffer(stream *strm)
746 unix_stream * s = (unix_stream *) strm;
747 memset(s->buffer, ' ', s->file_length);
750 /* open_internal()-- Returns a stream structure from an internal file */
752 stream *
753 open_internal (char *base, int length, gfc_offset offset)
755 unix_stream *s;
757 s = get_mem (sizeof (unix_stream));
758 memset (s, '\0', sizeof (unix_stream));
760 s->buffer = base;
761 s->buffer_offset = offset;
763 s->logical_offset = 0;
764 s->active = s->file_length = length;
766 s->st.close = (void *) mem_close;
767 s->st.seek = (void *) mem_seek;
768 s->st.tell = (void *) mem_tell;
769 s->st.trunc = (void *) mem_truncate;
770 s->st.read = (void *) mem_read;
771 s->st.write = (void *) mem_write;
772 s->st.flush = (void *) mem_flush;
774 return (stream *) s;
778 /* fd_to_stream()-- Given an open file descriptor, build a stream
779 * around it. */
781 static stream *
782 fd_to_stream (int fd, int prot)
784 struct stat statbuf;
785 unix_stream *s;
787 s = get_mem (sizeof (unix_stream));
788 memset (s, '\0', sizeof (unix_stream));
790 s->fd = fd;
791 s->buffer_offset = 0;
792 s->physical_offset = 0;
793 s->logical_offset = 0;
794 s->prot = prot;
796 /* Get the current length of the file. */
798 fstat (fd, &statbuf);
800 if (lseek (fd, 0, SEEK_CUR) == (gfc_offset) -1)
801 s->file_length = -1;
802 else
803 s->file_length = S_ISREG (statbuf.st_mode) ? statbuf.st_size : -1;
805 s->special_file = !S_ISREG (statbuf.st_mode);
807 if (isatty (s->fd) || options.all_unbuffered
808 ||(options.unbuffered_preconnected &&
809 (s->fd == STDIN_FILENO
810 || s->fd == STDOUT_FILENO
811 || s->fd == STDERR_FILENO)))
812 raw_init (s);
813 else
814 buf_init (s);
816 return (stream *) s;
820 /* Given the Fortran unit number, convert it to a C file descriptor. */
823 unit_to_fd (int unit)
825 gfc_unit *us;
826 int fd;
828 us = find_unit (unit);
829 if (us == NULL)
830 return -1;
832 fd = ((unix_stream *) us->s)->fd;
833 unlock_unit (us);
834 return fd;
838 /* unpack_filename()-- Given a fortran string and a pointer to a
839 * buffer that is PATH_MAX characters, convert the fortran string to a
840 * C string in the buffer. Returns nonzero if this is not possible. */
843 unpack_filename (char *cstring, const char *fstring, int len)
845 len = fstrlen (fstring, len);
846 if (len >= PATH_MAX)
847 return 1;
849 memmove (cstring, fstring, len);
850 cstring[len] = '\0';
852 return 0;
856 /* tempfile()-- Generate a temporary filename for a scratch file and
857 * open it. mkstemp() opens the file for reading and writing, but the
858 * library mode prevents anything that is not allowed. The descriptor
859 * is returned, which is -1 on error. The template is pointed to by
860 * opp->file, which is copied into the unit structure
861 * and freed later. */
863 static int
864 tempfile (st_parameter_open *opp)
866 const char *tempdir;
867 char *template;
868 int fd;
870 tempdir = getenv ("GFORTRAN_TMPDIR");
871 if (tempdir == NULL)
872 tempdir = getenv ("TMP");
873 if (tempdir == NULL)
874 tempdir = getenv ("TEMP");
875 if (tempdir == NULL)
876 tempdir = DEFAULT_TEMPDIR;
878 template = get_mem (strlen (tempdir) + 20);
880 sprintf (template, "%s/gfortrantmpXXXXXX", tempdir);
882 #ifdef HAVE_MKSTEMP
884 fd = mkstemp (template);
886 #else /* HAVE_MKSTEMP */
888 if (mktemp (template))
890 #if defined(HAVE_CRLF) && defined(O_BINARY)
891 fd = open (template, O_RDWR | O_CREAT | O_EXCL | O_BINARY,
892 S_IREAD | S_IWRITE);
893 #else
894 fd = open (template, O_RDWR | O_CREAT | O_EXCL, S_IREAD | S_IWRITE);
895 #endif
896 while (!(fd == -1 && errno == EEXIST) && mktemp (template));
897 else
898 fd = -1;
900 #endif /* HAVE_MKSTEMP */
902 if (fd < 0)
903 free_mem (template);
904 else
906 opp->file = template;
907 opp->file_len = strlen (template); /* Don't include trailing nul */
910 return fd;
914 /* regular_file()-- Open a regular file.
915 * Change flags->action if it is ACTION_UNSPECIFIED on entry,
916 * unless an error occurs.
917 * Returns the descriptor, which is less than zero on error. */
919 static int
920 regular_file (st_parameter_open *opp, unit_flags *flags)
922 char path[PATH_MAX + 1];
923 int mode;
924 int rwflag;
925 int crflag;
926 int fd;
928 if (unpack_filename (path, opp->file, opp->file_len))
930 errno = ENOENT; /* Fake an OS error */
931 return -1;
934 #ifdef __CYGWIN__
935 if (opp->file_len == 7)
937 if (strncmp (path, "CONOUT$", 7) == 0
938 || strncmp (path, "CONERR$", 7) == 0)
940 fd = open ("/dev/conout", O_WRONLY);
941 flags->action = ACTION_WRITE;
942 return fd;
946 if (opp->file_len == 6 && strncmp (path, "CONIN$", 6) == 0)
948 fd = open ("/dev/conin", O_RDONLY);
949 flags->action = ACTION_READ;
950 return fd;
952 #endif
955 #ifdef __MINGW32__
956 if (opp->file_len == 7)
958 if (strncmp (path, "CONOUT$", 7) == 0
959 || strncmp (path, "CONERR$", 7) == 0)
961 fd = open ("CONOUT$", O_WRONLY);
962 flags->action = ACTION_WRITE;
963 return fd;
967 if (opp->file_len == 6 && strncmp (path, "CONIN$", 6) == 0)
969 fd = open ("CONIN$", O_RDONLY);
970 flags->action = ACTION_READ;
971 return fd;
973 #endif
975 rwflag = 0;
977 switch (flags->action)
979 case ACTION_READ:
980 rwflag = O_RDONLY;
981 break;
983 case ACTION_WRITE:
984 rwflag = O_WRONLY;
985 break;
987 case ACTION_READWRITE:
988 case ACTION_UNSPECIFIED:
989 rwflag = O_RDWR;
990 break;
992 default:
993 internal_error (&opp->common, "regular_file(): Bad action");
996 switch (flags->status)
998 case STATUS_NEW:
999 crflag = O_CREAT | O_EXCL;
1000 break;
1002 case STATUS_OLD: /* open will fail if the file does not exist*/
1003 crflag = 0;
1004 break;
1006 case STATUS_UNKNOWN:
1007 case STATUS_SCRATCH:
1008 crflag = O_CREAT;
1009 break;
1011 case STATUS_REPLACE:
1012 crflag = O_CREAT | O_TRUNC;
1013 break;
1015 default:
1016 internal_error (&opp->common, "regular_file(): Bad status");
1019 /* rwflag |= O_LARGEFILE; */
1021 #if defined(HAVE_CRLF) && defined(O_BINARY)
1022 crflag |= O_BINARY;
1023 #endif
1025 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1026 fd = open (path, rwflag | crflag, mode);
1027 if (flags->action != ACTION_UNSPECIFIED)
1028 return fd;
1030 if (fd >= 0)
1032 flags->action = ACTION_READWRITE;
1033 return fd;
1035 if (errno != EACCES && errno != EROFS)
1036 return fd;
1038 /* retry for read-only access */
1039 rwflag = O_RDONLY;
1040 fd = open (path, rwflag | crflag, mode);
1041 if (fd >=0)
1043 flags->action = ACTION_READ;
1044 return fd; /* success */
1047 if (errno != EACCES)
1048 return fd; /* failure */
1050 /* retry for write-only access */
1051 rwflag = O_WRONLY;
1052 fd = open (path, rwflag | crflag, mode);
1053 if (fd >=0)
1055 flags->action = ACTION_WRITE;
1056 return fd; /* success */
1058 return fd; /* failure */
1062 /* open_external()-- Open an external file, unix specific version.
1063 * Change flags->action if it is ACTION_UNSPECIFIED on entry.
1064 * Returns NULL on operating system error. */
1066 stream *
1067 open_external (st_parameter_open *opp, unit_flags *flags)
1069 int fd, prot;
1071 if (flags->status == STATUS_SCRATCH)
1073 fd = tempfile (opp);
1074 if (flags->action == ACTION_UNSPECIFIED)
1075 flags->action = ACTION_READWRITE;
1077 #if HAVE_UNLINK_OPEN_FILE
1078 /* We can unlink scratch files now and it will go away when closed. */
1079 if (fd >= 0)
1080 unlink (opp->file);
1081 #endif
1083 else
1085 /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1086 * if it succeeds */
1087 fd = regular_file (opp, flags);
1090 if (fd < 0)
1091 return NULL;
1092 fd = fix_fd (fd);
1094 switch (flags->action)
1096 case ACTION_READ:
1097 prot = PROT_READ;
1098 break;
1100 case ACTION_WRITE:
1101 prot = PROT_WRITE;
1102 break;
1104 case ACTION_READWRITE:
1105 prot = PROT_READ | PROT_WRITE;
1106 break;
1108 default:
1109 internal_error (&opp->common, "open_external(): Bad action");
1112 return fd_to_stream (fd, prot);
1116 /* input_stream()-- Return a stream pointer to the default input stream.
1117 * Called on initialization. */
1119 stream *
1120 input_stream (void)
1122 return fd_to_stream (STDIN_FILENO, PROT_READ);
1126 /* output_stream()-- Return a stream pointer to the default output stream.
1127 * Called on initialization. */
1129 stream *
1130 output_stream (void)
1132 stream * s;
1134 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1135 setmode (STDOUT_FILENO, O_BINARY);
1136 #endif
1138 s = fd_to_stream (STDOUT_FILENO, PROT_WRITE);
1139 return s;
1143 /* error_stream()-- Return a stream pointer to the default error stream.
1144 * Called on initialization. */
1146 stream *
1147 error_stream (void)
1149 stream * s;
1151 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1152 setmode (STDERR_FILENO, O_BINARY);
1153 #endif
1155 s = fd_to_stream (STDERR_FILENO, PROT_WRITE);
1156 return s;
1160 /* st_vprintf()-- vprintf function for error output. To avoid buffer
1161 overruns, we limit the length of the buffer to ST_VPRINTF_SIZE. 2k
1162 is big enough to completely fill a 80x25 terminal, so it shuld be
1163 OK. We use a direct write() because it is simpler and least likely
1164 to be clobbered by memory corruption. Writing an error message
1165 longer than that is an error. */
1167 #define ST_VPRINTF_SIZE 2048
1170 st_vprintf (const char *format, va_list ap)
1172 static char buffer[ST_VPRINTF_SIZE];
1173 int written;
1174 int fd;
1176 fd = options.use_stderr ? STDERR_FILENO : STDOUT_FILENO;
1177 #ifdef HAVE_VSNPRINTF
1178 written = vsnprintf(buffer, ST_VPRINTF_SIZE, format, ap);
1179 #else
1180 written = vsprintf(buffer, format, ap);
1182 if (written >= ST_VPRINTF_SIZE-1)
1184 /* The error message was longer than our buffer. Ouch. Because
1185 we may have messed up things badly, report the error and
1186 quit. */
1187 #define ERROR_MESSAGE "Internal error: buffer overrun in st_vprintf()\n"
1188 write (fd, buffer, ST_VPRINTF_SIZE-1);
1189 write (fd, ERROR_MESSAGE, strlen(ERROR_MESSAGE));
1190 sys_exit(2);
1191 #undef ERROR_MESSAGE
1194 #endif
1196 written = write (fd, buffer, written);
1197 return written;
1200 /* st_printf()-- printf() function for error output. This just calls
1201 st_vprintf() to do the actual work. */
1204 st_printf (const char *format, ...)
1206 int written;
1207 va_list ap;
1208 va_start (ap, format);
1209 written = st_vprintf(format, ap);
1210 va_end (ap);
1211 return written;
1215 /* compare_file_filename()-- Given an open stream and a fortran string
1216 * that is a filename, figure out if the file is the same as the
1217 * filename. */
1220 compare_file_filename (gfc_unit *u, const char *name, int len)
1222 char path[PATH_MAX + 1];
1223 struct stat st1;
1224 #ifdef HAVE_WORKING_STAT
1225 struct stat st2;
1226 #else
1227 # ifdef __MINGW32__
1228 uint64_t id1, id2;
1229 # endif
1230 #endif
1232 if (unpack_filename (path, name, len))
1233 return 0; /* Can't be the same */
1235 /* If the filename doesn't exist, then there is no match with the
1236 * existing file. */
1238 if (stat (path, &st1) < 0)
1239 return 0;
1241 #ifdef HAVE_WORKING_STAT
1242 fstat (((unix_stream *) (u->s))->fd, &st2);
1243 return (st1.st_dev == st2.st_dev) && (st1.st_ino == st2.st_ino);
1244 #else
1246 # ifdef __MINGW32__
1247 /* We try to match files by a unique ID. On some filesystems (network
1248 fs and FAT), we can't generate this unique ID, and will simply compare
1249 filenames. */
1250 id1 = id_from_path (path);
1251 id2 = id_from_fd (((unix_stream *) (u->s))->fd);
1252 if (id1 || id2)
1253 return (id1 == id2);
1254 # endif
1256 if (len != u->file_len)
1257 return 0;
1258 return (memcmp(path, u->file, len) == 0);
1259 #endif
1263 #ifdef HAVE_WORKING_STAT
1264 # define FIND_FILE0_DECL struct stat *st
1265 # define FIND_FILE0_ARGS st
1266 #else
1267 # define FIND_FILE0_DECL uint64_t id, const char *file, gfc_charlen_type file_len
1268 # define FIND_FILE0_ARGS id, file, file_len
1269 #endif
1271 /* find_file0()-- Recursive work function for find_file() */
1273 static gfc_unit *
1274 find_file0 (gfc_unit *u, FIND_FILE0_DECL)
1276 gfc_unit *v;
1277 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1278 uint64_t id1;
1279 #endif
1281 if (u == NULL)
1282 return NULL;
1284 #ifdef HAVE_WORKING_STAT
1285 if (u->s != NULL
1286 && fstat (((unix_stream *) u->s)->fd, &st[1]) >= 0 &&
1287 st[0].st_dev == st[1].st_dev && st[0].st_ino == st[1].st_ino)
1288 return u;
1289 #else
1290 # ifdef __MINGW32__
1291 if (u->s && ((id1 = id_from_fd (((unix_stream *) u->s)->fd)) || id1))
1293 if (id == id1)
1294 return u;
1296 else
1297 # endif
1298 if (compare_string (u->file_len, u->file, file_len, file) == 0)
1299 return u;
1300 #endif
1302 v = find_file0 (u->left, FIND_FILE0_ARGS);
1303 if (v != NULL)
1304 return v;
1306 v = find_file0 (u->right, FIND_FILE0_ARGS);
1307 if (v != NULL)
1308 return v;
1310 return NULL;
1314 /* find_file()-- Take the current filename and see if there is a unit
1315 * that has the file already open. Returns a pointer to the unit if so. */
1317 gfc_unit *
1318 find_file (const char *file, gfc_charlen_type file_len)
1320 char path[PATH_MAX + 1];
1321 struct stat st[2];
1322 gfc_unit *u;
1323 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1324 uint64_t id = 0ULL;
1325 #endif
1327 if (unpack_filename (path, file, file_len))
1328 return NULL;
1330 if (stat (path, &st[0]) < 0)
1331 return NULL;
1333 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1334 id = id_from_path (path);
1335 #endif
1337 __gthread_mutex_lock (&unit_lock);
1338 retry:
1339 u = find_file0 (unit_root, FIND_FILE0_ARGS);
1340 if (u != NULL)
1342 /* Fast path. */
1343 if (! __gthread_mutex_trylock (&u->lock))
1345 /* assert (u->closed == 0); */
1346 __gthread_mutex_unlock (&unit_lock);
1347 return u;
1350 inc_waiting_locked (u);
1352 __gthread_mutex_unlock (&unit_lock);
1353 if (u != NULL)
1355 __gthread_mutex_lock (&u->lock);
1356 if (u->closed)
1358 __gthread_mutex_lock (&unit_lock);
1359 __gthread_mutex_unlock (&u->lock);
1360 if (predec_waiting_locked (u) == 0)
1361 free_mem (u);
1362 goto retry;
1365 dec_waiting_unlocked (u);
1367 return u;
1370 static gfc_unit *
1371 flush_all_units_1 (gfc_unit *u, int min_unit)
1373 while (u != NULL)
1375 if (u->unit_number > min_unit)
1377 gfc_unit *r = flush_all_units_1 (u->left, min_unit);
1378 if (r != NULL)
1379 return r;
1381 if (u->unit_number >= min_unit)
1383 if (__gthread_mutex_trylock (&u->lock))
1384 return u;
1385 if (u->s)
1386 sflush (u->s);
1387 __gthread_mutex_unlock (&u->lock);
1389 u = u->right;
1391 return NULL;
1394 void
1395 flush_all_units (void)
1397 gfc_unit *u;
1398 int min_unit = 0;
1400 __gthread_mutex_lock (&unit_lock);
1403 u = flush_all_units_1 (unit_root, min_unit);
1404 if (u != NULL)
1405 inc_waiting_locked (u);
1406 __gthread_mutex_unlock (&unit_lock);
1407 if (u == NULL)
1408 return;
1410 __gthread_mutex_lock (&u->lock);
1412 min_unit = u->unit_number + 1;
1414 if (u->closed == 0)
1416 sflush (u->s);
1417 __gthread_mutex_lock (&unit_lock);
1418 __gthread_mutex_unlock (&u->lock);
1419 (void) predec_waiting_locked (u);
1421 else
1423 __gthread_mutex_lock (&unit_lock);
1424 __gthread_mutex_unlock (&u->lock);
1425 if (predec_waiting_locked (u) == 0)
1426 free_mem (u);
1429 while (1);
1433 /* delete_file()-- Given a unit structure, delete the file associated
1434 * with the unit. Returns nonzero if something went wrong. */
1437 delete_file (gfc_unit * u)
1439 char path[PATH_MAX + 1];
1441 if (unpack_filename (path, u->file, u->file_len))
1442 { /* Shouldn't be possible */
1443 errno = ENOENT;
1444 return 1;
1447 return unlink (path);
1451 /* file_exists()-- Returns nonzero if the current filename exists on
1452 * the system */
1455 file_exists (const char *file, gfc_charlen_type file_len)
1457 char path[PATH_MAX + 1];
1458 struct stat statbuf;
1460 if (unpack_filename (path, file, file_len))
1461 return 0;
1463 if (stat (path, &statbuf) < 0)
1464 return 0;
1466 return 1;
1471 static const char yes[] = "YES", no[] = "NO", unknown[] = "UNKNOWN";
1473 /* inquire_sequential()-- Given a fortran string, determine if the
1474 * file is suitable for sequential access. Returns a C-style
1475 * string. */
1477 const char *
1478 inquire_sequential (const char *string, int len)
1480 char path[PATH_MAX + 1];
1481 struct stat statbuf;
1483 if (string == NULL ||
1484 unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1485 return unknown;
1487 if (S_ISREG (statbuf.st_mode) ||
1488 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1489 return unknown;
1491 if (S_ISDIR (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1492 return no;
1494 return unknown;
1498 /* inquire_direct()-- Given a fortran string, determine if the file is
1499 * suitable for direct access. Returns a C-style string. */
1501 const char *
1502 inquire_direct (const char *string, int len)
1504 char path[PATH_MAX + 1];
1505 struct stat statbuf;
1507 if (string == NULL ||
1508 unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1509 return unknown;
1511 if (S_ISREG (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1512 return unknown;
1514 if (S_ISDIR (statbuf.st_mode) ||
1515 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1516 return no;
1518 return unknown;
1522 /* inquire_formatted()-- Given a fortran string, determine if the file
1523 * is suitable for formatted form. Returns a C-style string. */
1525 const char *
1526 inquire_formatted (const char *string, int len)
1528 char path[PATH_MAX + 1];
1529 struct stat statbuf;
1531 if (string == NULL ||
1532 unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1533 return unknown;
1535 if (S_ISREG (statbuf.st_mode) ||
1536 S_ISBLK (statbuf.st_mode) ||
1537 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1538 return unknown;
1540 if (S_ISDIR (statbuf.st_mode))
1541 return no;
1543 return unknown;
1547 /* inquire_unformatted()-- Given a fortran string, determine if the file
1548 * is suitable for unformatted form. Returns a C-style string. */
1550 const char *
1551 inquire_unformatted (const char *string, int len)
1553 return inquire_formatted (string, len);
1557 #ifndef HAVE_ACCESS
1559 #ifndef W_OK
1560 #define W_OK 2
1561 #endif
1563 #ifndef R_OK
1564 #define R_OK 4
1565 #endif
1567 /* Fallback implementation of access() on systems that don't have it.
1568 Only modes R_OK and W_OK are used in this file. */
1570 static int
1571 fallback_access (const char *path, int mode)
1573 if ((mode & R_OK) && open (path, O_RDONLY) < 0)
1574 return -1;
1576 if ((mode & W_OK) && open (path, O_WRONLY) < 0)
1577 return -1;
1579 return 0;
1582 #undef access
1583 #define access fallback_access
1584 #endif
1587 /* inquire_access()-- Given a fortran string, determine if the file is
1588 * suitable for access. */
1590 static const char *
1591 inquire_access (const char *string, int len, int mode)
1593 char path[PATH_MAX + 1];
1595 if (string == NULL || unpack_filename (path, string, len) ||
1596 access (path, mode) < 0)
1597 return no;
1599 return yes;
1603 /* inquire_read()-- Given a fortran string, determine if the file is
1604 * suitable for READ access. */
1606 const char *
1607 inquire_read (const char *string, int len)
1609 return inquire_access (string, len, R_OK);
1613 /* inquire_write()-- Given a fortran string, determine if the file is
1614 * suitable for READ access. */
1616 const char *
1617 inquire_write (const char *string, int len)
1619 return inquire_access (string, len, W_OK);
1623 /* inquire_readwrite()-- Given a fortran string, determine if the file is
1624 * suitable for read and write access. */
1626 const char *
1627 inquire_readwrite (const char *string, int len)
1629 return inquire_access (string, len, R_OK | W_OK);
1633 /* file_length()-- Return the file length in bytes, -1 if unknown */
1635 gfc_offset
1636 file_length (stream * s)
1638 gfc_offset curr, end;
1639 if (!is_seekable (s))
1640 return -1;
1641 curr = stell (s);
1642 if (curr == -1)
1643 return curr;
1644 end = sseek (s, 0, SEEK_END);
1645 sseek (s, curr, SEEK_SET);
1646 return end;
1650 /* is_seekable()-- Return nonzero if the stream is seekable, zero if
1651 * it is not */
1654 is_seekable (stream *s)
1656 /* By convention, if file_length == -1, the file is not
1657 seekable. */
1658 return ((unix_stream *) s)->file_length!=-1;
1662 /* is_special()-- Return nonzero if the stream is not a regular file. */
1665 is_special (stream *s)
1667 return ((unix_stream *) s)->special_file;
1672 stream_isatty (stream *s)
1674 return isatty (((unix_stream *) s)->fd);
1677 char *
1678 stream_ttyname (stream *s __attribute__ ((unused)))
1680 #ifdef HAVE_TTYNAME
1681 return ttyname (((unix_stream *) s)->fd);
1682 #else
1683 return NULL;
1684 #endif
1688 /* How files are stored: This is an operating-system specific issue,
1689 and therefore belongs here. There are three cases to consider.
1691 Direct Access:
1692 Records are written as block of bytes corresponding to the record
1693 length of the file. This goes for both formatted and unformatted
1694 records. Positioning is done explicitly for each data transfer,
1695 so positioning is not much of an issue.
1697 Sequential Formatted:
1698 Records are separated by newline characters. The newline character
1699 is prohibited from appearing in a string. If it does, this will be
1700 messed up on the next read. End of file is also the end of a record.
1702 Sequential Unformatted:
1703 In this case, we are merely copying bytes to and from main storage,
1704 yet we need to keep track of varying record lengths. We adopt
1705 the solution used by f2c. Each record contains a pair of length
1706 markers:
1708 Length of record n in bytes
1709 Data of record n
1710 Length of record n in bytes
1712 Length of record n+1 in bytes
1713 Data of record n+1
1714 Length of record n+1 in bytes
1716 The length is stored at the end of a record to allow backspacing to the
1717 previous record. Between data transfer statements, the file pointer
1718 is left pointing to the first length of the current record.
1720 ENDFILE records are never explicitly stored.