1 /* Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
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)
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 */
43 /* For mingw, we don't identify files by their inode number, but by a
44 64-bit identifier created from a BY_HANDLE_FILE_INFORMATION. */
47 #define WIN32_LEAN_AND_MEAN
50 #define lseek _lseeki64
51 #define fstat _fstati64
53 typedef struct _stati64 gfstat_t;
55 #ifndef HAVE_WORKING_STAT
57 id_from_handle (HANDLE hFile)
59 BY_HANDLE_FILE_INFORMATION FileInformation;
61 if (hFile == INVALID_HANDLE_VALUE)
64 memset (&FileInformation, 0, sizeof(FileInformation));
65 if (!GetFileInformationByHandle (hFile, &FileInformation))
68 return ((uint64_t) FileInformation.nFileIndexLow)
69 | (((uint64_t) FileInformation.nFileIndexHigh) << 32);
74 id_from_path (const char *path)
79 if (!path || !*path || access (path, F_OK))
82 hFile = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
83 FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_READONLY,
85 res = id_from_handle (hFile);
92 id_from_fd (const int fd)
94 return id_from_handle ((HANDLE) _get_osfhandle (fd));
100 typedef struct stat gfstat_t;
104 #define PATH_MAX 1024
115 /* These flags aren't defined on all targets (mingw32), so provide them
134 /* Unix and internal stream I/O module */
136 static const int BUFFER_SIZE = 8192;
142 gfc_offset buffer_offset; /* File offset of the start of the buffer */
143 gfc_offset physical_offset; /* Current physical file offset */
144 gfc_offset logical_offset; /* Current logical file offset */
145 gfc_offset file_length; /* Length of the file, -1 if not seekable. */
147 char *buffer; /* Pointer to the buffer. */
148 int fd; /* The POSIX file descriptor. */
150 int active; /* Length of valid bytes in the buffer */
153 int ndirty; /* Dirty bytes starting at buffer_offset */
155 int special_file; /* =1 if the fd refers to a special file */
160 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
161 * standard descriptors, returning a non-standard descriptor. If the
162 * user specifies that system errors should go to standard output,
163 * then closes standard output, we don't want the system errors to a
164 * file that has been given file descriptor 1 or 0. We want to send
165 * the error to the invalid descriptor. */
171 int input, output, error;
173 input = output = error = 0;
175 /* Unix allocates the lowest descriptors first, so a loop is not
176 required, but this order is. */
177 if (fd == STDIN_FILENO)
182 if (fd == STDOUT_FILENO)
187 if (fd == STDERR_FILENO)
194 close (STDIN_FILENO);
196 close (STDOUT_FILENO);
198 close (STDERR_FILENO);
205 /* If the stream corresponds to a preconnected unit, we flush the
206 corresponding C stream. This is bugware for mixed C-Fortran codes
207 where the C code doesn't flush I/O before returning. */
209 flush_if_preconnected (stream * s)
213 fd = ((unix_stream *) s)->fd;
214 if (fd == STDIN_FILENO)
216 else if (fd == STDOUT_FILENO)
218 else if (fd == STDERR_FILENO)
223 /* get_oserror()-- Get the most recent operating system error. For
224 * unix, this is errno. */
229 return strerror (errno);
233 /********************************************************************
234 Raw I/O functions (read, write, seek, tell, truncate, close).
236 These functions wrap the basic POSIX I/O syscalls. Any deviation in
237 semantics is a bug, except the following: write restarts in case
238 of being interrupted by a signal, and as the first argument the
239 functions take the unix_stream struct rather than an integer file
240 descriptor. Also, for POSIX read() and write() a nbyte argument larger
241 than SSIZE_MAX is undefined; here the type of nbyte is ssize_t rather
242 than size_t as for POSIX read/write.
243 *********************************************************************/
246 raw_flush (unix_stream * s __attribute__ ((unused)))
252 raw_read (unix_stream * s, void * buf, ssize_t nbyte)
254 /* For read we can't do I/O in a loop like raw_write does, because
255 that will break applications that wait for interactive I/O. */
256 return read (s->fd, buf, nbyte);
260 raw_write (unix_stream * s, const void * buf, ssize_t nbyte)
262 ssize_t trans, bytes_left;
266 buf_st = (char *) buf;
268 /* We must write in a loop since some systems don't restart system
269 calls in case of a signal. */
270 while (bytes_left > 0)
272 trans = write (s->fd, buf_st, bytes_left);
284 return nbyte - bytes_left;
288 raw_seek (unix_stream * s, gfc_offset offset, int whence)
290 return lseek (s->fd, offset, whence);
294 raw_tell (unix_stream * s)
296 return lseek (s->fd, 0, SEEK_CUR);
300 raw_truncate (unix_stream * s, gfc_offset length)
311 h = (HANDLE) _get_osfhandle (s->fd);
312 if (h == INVALID_HANDLE_VALUE)
317 cur = lseek (s->fd, 0, SEEK_CUR);
320 if (lseek (s->fd, length, SEEK_SET) == -1)
322 if (!SetEndOfFile (h))
327 if (lseek (s->fd, cur, SEEK_SET) == -1)
331 lseek (s->fd, cur, SEEK_SET);
333 #elif defined HAVE_FTRUNCATE
334 return ftruncate (s->fd, length);
335 #elif defined HAVE_CHSIZE
336 return chsize (s->fd, length);
338 runtime_error ("required ftruncate or chsize support not present");
344 raw_close (unix_stream * s)
348 if (s->fd != STDOUT_FILENO
349 && s->fd != STDERR_FILENO
350 && s->fd != STDIN_FILENO)
351 retval = close (s->fd);
359 raw_init (unix_stream * s)
361 s->st.read = (void *) raw_read;
362 s->st.write = (void *) raw_write;
363 s->st.seek = (void *) raw_seek;
364 s->st.tell = (void *) raw_tell;
365 s->st.trunc = (void *) raw_truncate;
366 s->st.close = (void *) raw_close;
367 s->st.flush = (void *) raw_flush;
374 /*********************************************************************
375 Buffered I/O functions. These functions have the same semantics as the
376 raw I/O functions above, except that they are buffered in order to
377 improve performance. The buffer must be flushed when switching from
378 reading to writing and vice versa.
379 *********************************************************************/
382 buf_flush (unix_stream * s)
386 /* Flushing in read mode means discarding read bytes. */
392 if (s->file_length != -1 && s->physical_offset != s->buffer_offset
393 && lseek (s->fd, s->buffer_offset, SEEK_SET) < 0)
396 writelen = raw_write (s, s->buffer, s->ndirty);
398 s->physical_offset = s->buffer_offset + writelen;
400 /* Don't increment file_length if the file is non-seekable. */
401 if (s->file_length != -1 && s->physical_offset > s->file_length)
402 s->file_length = s->physical_offset;
404 s->ndirty -= writelen;
412 buf_read (unix_stream * s, void * buf, ssize_t nbyte)
415 s->buffer_offset = s->logical_offset;
417 /* Is the data we want in the buffer? */
418 if (s->logical_offset + nbyte <= s->buffer_offset + s->active
419 && s->buffer_offset <= s->logical_offset)
420 memcpy (buf, s->buffer + (s->logical_offset - s->buffer_offset), nbyte);
423 /* First copy the active bytes if applicable, then read the rest
424 either directly or filling the buffer. */
427 ssize_t to_read, did_read;
428 gfc_offset new_logical;
431 if (s->logical_offset >= s->buffer_offset
432 && s->buffer_offset + s->active >= s->logical_offset)
434 nread = s->active - (s->logical_offset - s->buffer_offset);
435 memcpy (buf, s->buffer + (s->logical_offset - s->buffer_offset),
439 /* At this point we consider all bytes in the buffer discarded. */
440 to_read = nbyte - nread;
441 new_logical = s->logical_offset + nread;
442 if (s->file_length != -1 && s->physical_offset != new_logical
443 && lseek (s->fd, new_logical, SEEK_SET) < 0)
445 s->buffer_offset = s->physical_offset = new_logical;
446 if (to_read <= BUFFER_SIZE/2)
448 did_read = raw_read (s, s->buffer, BUFFER_SIZE);
449 s->physical_offset += did_read;
450 s->active = did_read;
451 did_read = (did_read > to_read) ? to_read : did_read;
452 memcpy (p, s->buffer, did_read);
456 did_read = raw_read (s, p, to_read);
457 s->physical_offset += did_read;
460 nbyte = did_read + nread;
462 s->logical_offset += nbyte;
467 buf_write (unix_stream * s, const void * buf, ssize_t nbyte)
470 s->buffer_offset = s->logical_offset;
472 /* Does the data fit into the buffer? As a special case, if the
473 buffer is empty and the request is bigger than BUFFER_SIZE/2,
474 write directly. This avoids the case where the buffer would have
475 to be flushed at every write. */
476 if (!(s->ndirty == 0 && nbyte > BUFFER_SIZE/2)
477 && s->logical_offset + nbyte <= s->buffer_offset + BUFFER_SIZE
478 && s->buffer_offset <= s->logical_offset
479 && s->buffer_offset + s->ndirty >= s->logical_offset)
481 memcpy (s->buffer + (s->logical_offset - s->buffer_offset), buf, nbyte);
482 int nd = (s->logical_offset - s->buffer_offset) + nbyte;
488 /* Flush, and either fill the buffer with the new data, or if
489 the request is bigger than the buffer size, write directly
490 bypassing the buffer. */
492 if (nbyte <= BUFFER_SIZE/2)
494 memcpy (s->buffer, buf, nbyte);
495 s->buffer_offset = s->logical_offset;
500 if (s->file_length != -1 && s->physical_offset != s->logical_offset)
502 if (lseek (s->fd, s->logical_offset, SEEK_SET) < 0)
504 s->physical_offset = s->logical_offset;
507 nbyte = raw_write (s, buf, nbyte);
508 s->physical_offset += nbyte;
511 s->logical_offset += nbyte;
512 /* Don't increment file_length if the file is non-seekable. */
513 if (s->file_length != -1 && s->logical_offset > s->file_length)
514 s->file_length = s->logical_offset;
519 buf_seek (unix_stream * s, gfc_offset offset, int whence)
526 offset += s->logical_offset;
529 offset += s->file_length;
539 s->logical_offset = offset;
544 buf_tell (unix_stream * s)
546 return s->logical_offset;
550 buf_truncate (unix_stream * s, gfc_offset length)
554 if (buf_flush (s) != 0)
556 r = raw_truncate (s, length);
558 s->file_length = length;
563 buf_close (unix_stream * s)
565 if (buf_flush (s) != 0)
567 free_mem (s->buffer);
568 return raw_close (s);
572 buf_init (unix_stream * s)
574 s->st.read = (void *) buf_read;
575 s->st.write = (void *) buf_write;
576 s->st.seek = (void *) buf_seek;
577 s->st.tell = (void *) buf_tell;
578 s->st.trunc = (void *) buf_truncate;
579 s->st.close = (void *) buf_close;
580 s->st.flush = (void *) buf_flush;
582 s->buffer = get_mem (BUFFER_SIZE);
587 /*********************************************************************
588 memory stream functions - These are used for internal files
590 The idea here is that a single stream structure is created and all
591 requests must be satisfied from it. The location and size of the
592 buffer is the character variable supplied to the READ or WRITE
595 *********************************************************************/
599 mem_alloc_r (stream * strm, int * len)
601 unix_stream * s = (unix_stream *) strm;
603 gfc_offset where = s->logical_offset;
605 if (where < s->buffer_offset || where > s->buffer_offset + s->active)
608 n = s->buffer_offset + s->active - where;
612 s->logical_offset = where + *len;
614 return s->buffer + (where - s->buffer_offset);
619 mem_alloc_w (stream * strm, int * len)
621 unix_stream * s = (unix_stream *) strm;
623 gfc_offset where = s->logical_offset;
627 if (where < s->buffer_offset)
630 if (m > s->file_length)
633 s->logical_offset = m;
635 return s->buffer + (where - s->buffer_offset);
639 /* Stream read function for internal units. */
642 mem_read (stream * s, void * buf, ssize_t nbytes)
647 p = mem_alloc_r (s, &nb);
658 /* Stream write function for internal units. This is not actually used
659 at the moment, as all internal IO is formatted and the formatted IO
660 routines use mem_alloc_w_at. */
663 mem_write (stream * s, const void * buf, ssize_t nbytes)
668 p = mem_alloc_w (s, &nb);
680 mem_seek (stream * strm, gfc_offset offset, int whence)
682 unix_stream * s = (unix_stream *) strm;
688 offset += s->logical_offset;
691 offset += s->file_length;
697 /* Note that for internal array I/O it's actually possible to have a
698 negative offset, so don't check for that. */
699 if (offset > s->file_length)
705 s->logical_offset = offset;
707 /* Returning < 0 is the error indicator for sseek(), so return 0 if
708 offset is negative. Thus if the return value is 0, the caller
709 has to use stell() to get the real value of logical_offset. */
717 mem_tell (stream * s)
719 return ((unix_stream *)s)->logical_offset;
724 mem_truncate (unix_stream * s __attribute__ ((unused)),
725 gfc_offset length __attribute__ ((unused)))
732 mem_flush (unix_stream * s __attribute__ ((unused)))
739 mem_close (unix_stream * s)
748 /*********************************************************************
749 Public functions -- A reimplementation of this module needs to
750 define functional equivalents of the following.
751 *********************************************************************/
753 /* empty_internal_buffer()-- Zero the buffer of Internal file */
756 empty_internal_buffer(stream *strm)
758 unix_stream * s = (unix_stream *) strm;
759 memset(s->buffer, ' ', s->file_length);
762 /* open_internal()-- Returns a stream structure from an internal file */
765 open_internal (char *base, int length, gfc_offset offset)
769 s = get_mem (sizeof (unix_stream));
770 memset (s, '\0', sizeof (unix_stream));
773 s->buffer_offset = offset;
775 s->logical_offset = 0;
776 s->active = s->file_length = length;
778 s->st.close = (void *) mem_close;
779 s->st.seek = (void *) mem_seek;
780 s->st.tell = (void *) mem_tell;
781 s->st.trunc = (void *) mem_truncate;
782 s->st.read = (void *) mem_read;
783 s->st.write = (void *) mem_write;
784 s->st.flush = (void *) mem_flush;
790 /* fd_to_stream()-- Given an open file descriptor, build a stream
794 fd_to_stream (int fd, int prot)
799 s = get_mem (sizeof (unix_stream));
800 memset (s, '\0', sizeof (unix_stream));
803 s->buffer_offset = 0;
804 s->physical_offset = 0;
805 s->logical_offset = 0;
808 /* Get the current length of the file. */
810 fstat (fd, &statbuf);
812 if (lseek (fd, 0, SEEK_CUR) == (gfc_offset) -1)
815 s->file_length = S_ISREG (statbuf.st_mode) ? statbuf.st_size : -1;
817 s->special_file = !S_ISREG (statbuf.st_mode);
819 if (isatty (s->fd) || options.all_unbuffered
820 ||(options.unbuffered_preconnected &&
821 (s->fd == STDIN_FILENO
822 || s->fd == STDOUT_FILENO
823 || s->fd == STDERR_FILENO)))
832 /* Given the Fortran unit number, convert it to a C file descriptor. */
835 unit_to_fd (int unit)
840 us = find_unit (unit);
844 fd = ((unix_stream *) us->s)->fd;
850 /* unpack_filename()-- Given a fortran string and a pointer to a
851 * buffer that is PATH_MAX characters, convert the fortran string to a
852 * C string in the buffer. Returns nonzero if this is not possible. */
855 unpack_filename (char *cstring, const char *fstring, int len)
857 len = fstrlen (fstring, len);
861 memmove (cstring, fstring, len);
868 /* tempfile()-- Generate a temporary filename for a scratch file and
869 * open it. mkstemp() opens the file for reading and writing, but the
870 * library mode prevents anything that is not allowed. The descriptor
871 * is returned, which is -1 on error. The template is pointed to by
872 * opp->file, which is copied into the unit structure
873 * and freed later. */
876 tempfile (st_parameter_open *opp)
880 const char *slash = "/";
883 tempdir = getenv ("GFORTRAN_TMPDIR");
887 char buffer[MAX_PATH + 1];
889 ret = GetTempPath (MAX_PATH, buffer);
890 /* If we are not able to get a temp-directory, we use
891 current directory. */
892 if (ret > MAX_PATH || !ret)
896 tempdir = strdup (buffer);
900 tempdir = getenv ("TMP");
902 tempdir = getenv ("TEMP");
904 tempdir = DEFAULT_TEMPDIR;
906 /* Check for special case that tempdir contains slash
907 or backslash at end. */
908 if (*tempdir == 0 || tempdir[strlen (tempdir) - 1] == '/'
910 || tempdir[strlen (tempdir) - 1] == '\\'
915 template = get_mem (strlen (tempdir) + 20);
918 sprintf (template, "%s%sgfortrantmpXXXXXX", tempdir, slash);
920 fd = mkstemp (template);
922 #else /* HAVE_MKSTEMP */
926 sprintf (template, "%s%sgfortrantmpXXXXXX", tempdir, slash);
927 if (!mktemp (template))
929 #if defined(HAVE_CRLF) && defined(O_BINARY)
930 fd = open (template, O_RDWR | O_CREAT | O_EXCL | O_BINARY,
933 fd = open (template, O_RDWR | O_CREAT | O_EXCL, S_IREAD | S_IWRITE);
936 while (fd == -1 && errno == EEXIST);
937 #endif /* HAVE_MKSTEMP */
943 opp->file = template;
944 opp->file_len = strlen (template); /* Don't include trailing nul */
951 /* regular_file()-- Open a regular file.
952 * Change flags->action if it is ACTION_UNSPECIFIED on entry,
953 * unless an error occurs.
954 * Returns the descriptor, which is less than zero on error. */
957 regular_file (st_parameter_open *opp, unit_flags *flags)
959 char path[PATH_MAX + 1];
965 if (unpack_filename (path, opp->file, opp->file_len))
967 errno = ENOENT; /* Fake an OS error */
972 if (opp->file_len == 7)
974 if (strncmp (path, "CONOUT$", 7) == 0
975 || strncmp (path, "CONERR$", 7) == 0)
977 fd = open ("/dev/conout", O_WRONLY);
978 flags->action = ACTION_WRITE;
983 if (opp->file_len == 6 && strncmp (path, "CONIN$", 6) == 0)
985 fd = open ("/dev/conin", O_RDONLY);
986 flags->action = ACTION_READ;
993 if (opp->file_len == 7)
995 if (strncmp (path, "CONOUT$", 7) == 0
996 || strncmp (path, "CONERR$", 7) == 0)
998 fd = open ("CONOUT$", O_WRONLY);
999 flags->action = ACTION_WRITE;
1004 if (opp->file_len == 6 && strncmp (path, "CONIN$", 6) == 0)
1006 fd = open ("CONIN$", O_RDONLY);
1007 flags->action = ACTION_READ;
1014 switch (flags->action)
1024 case ACTION_READWRITE:
1025 case ACTION_UNSPECIFIED:
1030 internal_error (&opp->common, "regular_file(): Bad action");
1033 switch (flags->status)
1036 crflag = O_CREAT | O_EXCL;
1039 case STATUS_OLD: /* open will fail if the file does not exist*/
1043 case STATUS_UNKNOWN:
1044 case STATUS_SCRATCH:
1048 case STATUS_REPLACE:
1049 crflag = O_CREAT | O_TRUNC;
1053 internal_error (&opp->common, "regular_file(): Bad status");
1056 /* rwflag |= O_LARGEFILE; */
1058 #if defined(HAVE_CRLF) && defined(O_BINARY)
1062 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1063 fd = open (path, rwflag | crflag, mode);
1064 if (flags->action != ACTION_UNSPECIFIED)
1069 flags->action = ACTION_READWRITE;
1072 if (errno != EACCES && errno != EROFS)
1075 /* retry for read-only access */
1077 fd = open (path, rwflag | crflag, mode);
1080 flags->action = ACTION_READ;
1081 return fd; /* success */
1084 if (errno != EACCES)
1085 return fd; /* failure */
1087 /* retry for write-only access */
1089 fd = open (path, rwflag | crflag, mode);
1092 flags->action = ACTION_WRITE;
1093 return fd; /* success */
1095 return fd; /* failure */
1099 /* open_external()-- Open an external file, unix specific version.
1100 * Change flags->action if it is ACTION_UNSPECIFIED on entry.
1101 * Returns NULL on operating system error. */
1104 open_external (st_parameter_open *opp, unit_flags *flags)
1108 if (flags->status == STATUS_SCRATCH)
1110 fd = tempfile (opp);
1111 if (flags->action == ACTION_UNSPECIFIED)
1112 flags->action = ACTION_READWRITE;
1114 #if HAVE_UNLINK_OPEN_FILE
1115 /* We can unlink scratch files now and it will go away when closed. */
1122 /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1124 fd = regular_file (opp, flags);
1131 switch (flags->action)
1141 case ACTION_READWRITE:
1142 prot = PROT_READ | PROT_WRITE;
1146 internal_error (&opp->common, "open_external(): Bad action");
1149 return fd_to_stream (fd, prot);
1153 /* input_stream()-- Return a stream pointer to the default input stream.
1154 * Called on initialization. */
1159 return fd_to_stream (STDIN_FILENO, PROT_READ);
1163 /* output_stream()-- Return a stream pointer to the default output stream.
1164 * Called on initialization. */
1167 output_stream (void)
1171 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1172 setmode (STDOUT_FILENO, O_BINARY);
1175 s = fd_to_stream (STDOUT_FILENO, PROT_WRITE);
1180 /* error_stream()-- Return a stream pointer to the default error stream.
1181 * Called on initialization. */
1188 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1189 setmode (STDERR_FILENO, O_BINARY);
1192 s = fd_to_stream (STDERR_FILENO, PROT_WRITE);
1197 /* st_vprintf()-- vprintf function for error output. To avoid buffer
1198 overruns, we limit the length of the buffer to ST_VPRINTF_SIZE. 2k
1199 is big enough to completely fill a 80x25 terminal, so it shuld be
1200 OK. We use a direct write() because it is simpler and least likely
1201 to be clobbered by memory corruption. Writing an error message
1202 longer than that is an error. */
1204 #define ST_VPRINTF_SIZE 2048
1207 st_vprintf (const char *format, va_list ap)
1209 static char buffer[ST_VPRINTF_SIZE];
1213 fd = options.use_stderr ? STDERR_FILENO : STDOUT_FILENO;
1214 #ifdef HAVE_VSNPRINTF
1215 written = vsnprintf(buffer, ST_VPRINTF_SIZE, format, ap);
1217 written = vsprintf(buffer, format, ap);
1219 if (written >= ST_VPRINTF_SIZE-1)
1221 /* The error message was longer than our buffer. Ouch. Because
1222 we may have messed up things badly, report the error and
1224 #define ERROR_MESSAGE "Internal error: buffer overrun in st_vprintf()\n"
1225 write (fd, buffer, ST_VPRINTF_SIZE-1);
1226 write (fd, ERROR_MESSAGE, strlen(ERROR_MESSAGE));
1228 #undef ERROR_MESSAGE
1233 written = write (fd, buffer, written);
1237 /* st_printf()-- printf() function for error output. This just calls
1238 st_vprintf() to do the actual work. */
1241 st_printf (const char *format, ...)
1245 va_start (ap, format);
1246 written = st_vprintf(format, ap);
1252 /* compare_file_filename()-- Given an open stream and a fortran string
1253 * that is a filename, figure out if the file is the same as the
1257 compare_file_filename (gfc_unit *u, const char *name, int len)
1259 char path[PATH_MAX + 1];
1261 #ifdef HAVE_WORKING_STAT
1269 if (unpack_filename (path, name, len))
1270 return 0; /* Can't be the same */
1272 /* If the filename doesn't exist, then there is no match with the
1275 if (stat (path, &st1) < 0)
1278 #ifdef HAVE_WORKING_STAT
1279 fstat (((unix_stream *) (u->s))->fd, &st2);
1280 return (st1.st_dev == st2.st_dev) && (st1.st_ino == st2.st_ino);
1284 /* We try to match files by a unique ID. On some filesystems (network
1285 fs and FAT), we can't generate this unique ID, and will simply compare
1287 id1 = id_from_path (path);
1288 id2 = id_from_fd (((unix_stream *) (u->s))->fd);
1290 return (id1 == id2);
1293 if (len != u->file_len)
1295 return (memcmp(path, u->file, len) == 0);
1300 #ifdef HAVE_WORKING_STAT
1301 # define FIND_FILE0_DECL gfstat_t *st
1302 # define FIND_FILE0_ARGS st
1304 # define FIND_FILE0_DECL uint64_t id, const char *file, gfc_charlen_type file_len
1305 # define FIND_FILE0_ARGS id, file, file_len
1308 /* find_file0()-- Recursive work function for find_file() */
1311 find_file0 (gfc_unit *u, FIND_FILE0_DECL)
1314 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1321 #ifdef HAVE_WORKING_STAT
1323 && fstat (((unix_stream *) u->s)->fd, &st[1]) >= 0 &&
1324 st[0].st_dev == st[1].st_dev && st[0].st_ino == st[1].st_ino)
1328 if (u->s && ((id1 = id_from_fd (((unix_stream *) u->s)->fd)) || id1))
1335 if (compare_string (u->file_len, u->file, file_len, file) == 0)
1339 v = find_file0 (u->left, FIND_FILE0_ARGS);
1343 v = find_file0 (u->right, FIND_FILE0_ARGS);
1351 /* find_file()-- Take the current filename and see if there is a unit
1352 * that has the file already open. Returns a pointer to the unit if so. */
1355 find_file (const char *file, gfc_charlen_type file_len)
1357 char path[PATH_MAX + 1];
1360 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1364 if (unpack_filename (path, file, file_len))
1367 if (stat (path, &st[0]) < 0)
1370 #if defined(__MINGW32__) && !HAVE_WORKING_STAT
1371 id = id_from_path (path);
1374 __gthread_mutex_lock (&unit_lock);
1376 u = find_file0 (unit_root, FIND_FILE0_ARGS);
1380 if (! __gthread_mutex_trylock (&u->lock))
1382 /* assert (u->closed == 0); */
1383 __gthread_mutex_unlock (&unit_lock);
1387 inc_waiting_locked (u);
1389 __gthread_mutex_unlock (&unit_lock);
1392 __gthread_mutex_lock (&u->lock);
1395 __gthread_mutex_lock (&unit_lock);
1396 __gthread_mutex_unlock (&u->lock);
1397 if (predec_waiting_locked (u) == 0)
1402 dec_waiting_unlocked (u);
1408 flush_all_units_1 (gfc_unit *u, int min_unit)
1412 if (u->unit_number > min_unit)
1414 gfc_unit *r = flush_all_units_1 (u->left, min_unit);
1418 if (u->unit_number >= min_unit)
1420 if (__gthread_mutex_trylock (&u->lock))
1424 __gthread_mutex_unlock (&u->lock);
1432 flush_all_units (void)
1437 __gthread_mutex_lock (&unit_lock);
1440 u = flush_all_units_1 (unit_root, min_unit);
1442 inc_waiting_locked (u);
1443 __gthread_mutex_unlock (&unit_lock);
1447 __gthread_mutex_lock (&u->lock);
1449 min_unit = u->unit_number + 1;
1454 __gthread_mutex_lock (&unit_lock);
1455 __gthread_mutex_unlock (&u->lock);
1456 (void) predec_waiting_locked (u);
1460 __gthread_mutex_lock (&unit_lock);
1461 __gthread_mutex_unlock (&u->lock);
1462 if (predec_waiting_locked (u) == 0)
1470 /* delete_file()-- Given a unit structure, delete the file associated
1471 * with the unit. Returns nonzero if something went wrong. */
1474 delete_file (gfc_unit * u)
1476 char path[PATH_MAX + 1];
1478 if (unpack_filename (path, u->file, u->file_len))
1479 { /* Shouldn't be possible */
1484 return unlink (path);
1488 /* file_exists()-- Returns nonzero if the current filename exists on
1492 file_exists (const char *file, gfc_charlen_type file_len)
1494 char path[PATH_MAX + 1];
1497 if (unpack_filename (path, file, file_len))
1500 if (stat (path, &statbuf) < 0)
1507 /* file_size()-- Returns the size of the file. */
1510 file_size (const char *file, gfc_charlen_type file_len)
1512 char path[PATH_MAX + 1];
1515 if (unpack_filename (path, file, file_len))
1518 if (stat (path, &statbuf) < 0)
1521 return (GFC_IO_INT) statbuf.st_size;
1524 static const char yes[] = "YES", no[] = "NO", unknown[] = "UNKNOWN";
1526 /* inquire_sequential()-- Given a fortran string, determine if the
1527 * file is suitable for sequential access. Returns a C-style
1531 inquire_sequential (const char *string, int len)
1533 char path[PATH_MAX + 1];
1536 if (string == NULL ||
1537 unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1540 if (S_ISREG (statbuf.st_mode) ||
1541 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1544 if (S_ISDIR (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1551 /* inquire_direct()-- Given a fortran string, determine if the file is
1552 * suitable for direct access. Returns a C-style string. */
1555 inquire_direct (const char *string, int len)
1557 char path[PATH_MAX + 1];
1560 if (string == NULL ||
1561 unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1564 if (S_ISREG (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1567 if (S_ISDIR (statbuf.st_mode) ||
1568 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1575 /* inquire_formatted()-- Given a fortran string, determine if the file
1576 * is suitable for formatted form. Returns a C-style string. */
1579 inquire_formatted (const char *string, int len)
1581 char path[PATH_MAX + 1];
1584 if (string == NULL ||
1585 unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1588 if (S_ISREG (statbuf.st_mode) ||
1589 S_ISBLK (statbuf.st_mode) ||
1590 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1593 if (S_ISDIR (statbuf.st_mode))
1600 /* inquire_unformatted()-- Given a fortran string, determine if the file
1601 * is suitable for unformatted form. Returns a C-style string. */
1604 inquire_unformatted (const char *string, int len)
1606 return inquire_formatted (string, len);
1620 /* Fallback implementation of access() on systems that don't have it.
1621 Only modes R_OK and W_OK are used in this file. */
1624 fallback_access (const char *path, int mode)
1626 if ((mode & R_OK) && open (path, O_RDONLY) < 0)
1629 if ((mode & W_OK) && open (path, O_WRONLY) < 0)
1636 #define access fallback_access
1640 /* inquire_access()-- Given a fortran string, determine if the file is
1641 * suitable for access. */
1644 inquire_access (const char *string, int len, int mode)
1646 char path[PATH_MAX + 1];
1648 if (string == NULL || unpack_filename (path, string, len) ||
1649 access (path, mode) < 0)
1656 /* inquire_read()-- Given a fortran string, determine if the file is
1657 * suitable for READ access. */
1660 inquire_read (const char *string, int len)
1662 return inquire_access (string, len, R_OK);
1666 /* inquire_write()-- Given a fortran string, determine if the file is
1667 * suitable for READ access. */
1670 inquire_write (const char *string, int len)
1672 return inquire_access (string, len, W_OK);
1676 /* inquire_readwrite()-- Given a fortran string, determine if the file is
1677 * suitable for read and write access. */
1680 inquire_readwrite (const char *string, int len)
1682 return inquire_access (string, len, R_OK | W_OK);
1686 /* file_length()-- Return the file length in bytes, -1 if unknown */
1689 file_length (stream * s)
1691 gfc_offset curr, end;
1692 if (!is_seekable (s))
1697 end = sseek (s, 0, SEEK_END);
1698 sseek (s, curr, SEEK_SET);
1703 /* is_seekable()-- Return nonzero if the stream is seekable, zero if
1707 is_seekable (stream *s)
1709 /* By convention, if file_length == -1, the file is not
1711 return ((unix_stream *) s)->file_length!=-1;
1715 /* is_special()-- Return nonzero if the stream is not a regular file. */
1718 is_special (stream *s)
1720 return ((unix_stream *) s)->special_file;
1725 stream_isatty (stream *s)
1727 return isatty (((unix_stream *) s)->fd);
1731 stream_ttyname (stream *s __attribute__ ((unused)))
1734 return ttyname (((unix_stream *) s)->fd);
1741 /* How files are stored: This is an operating-system specific issue,
1742 and therefore belongs here. There are three cases to consider.
1745 Records are written as block of bytes corresponding to the record
1746 length of the file. This goes for both formatted and unformatted
1747 records. Positioning is done explicitly for each data transfer,
1748 so positioning is not much of an issue.
1750 Sequential Formatted:
1751 Records are separated by newline characters. The newline character
1752 is prohibited from appearing in a string. If it does, this will be
1753 messed up on the next read. End of file is also the end of a record.
1755 Sequential Unformatted:
1756 In this case, we are merely copying bytes to and from main storage,
1757 yet we need to keep track of varying record lengths. We adopt
1758 the solution used by f2c. Each record contains a pair of length
1761 Length of record n in bytes
1763 Length of record n in bytes
1765 Length of record n+1 in bytes
1767 Length of record n+1 in bytes
1769 The length is stored at the end of a record to allow backspacing to the
1770 previous record. Between data transfer statements, the file pointer
1771 is left pointing to the first length of the current record.
1773 ENDFILE records are never explicitly stored.