* config/fpu-387.h (set_fpu): Add "=m" for stmxcsr.
[official-gcc.git] / libgfortran / io / unix.c
blobde018af1f032dba5e588dca6a6d2a2182251e1ed
1 /* Copyright (C) 2002, 2003, 2004, 2005
2 Free Software Foundation, Inc.
3 Contributed by Andy Vaught
5 This file is part of the GNU Fortran 95 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 2, or (at your option)
10 any later version.
12 In addition to the permissions in the GNU General Public License, the
13 Free Software Foundation gives you unlimited permission to link the
14 compiled version of this file into combinations with other programs,
15 and to distribute those combinations without any restriction coming
16 from the use of this file. (The General Public License restrictions
17 do apply in other respects; for example, they cover modification of
18 the file, and distribution when not linked into a combine
19 executable.)
21 Libgfortran is distributed in the hope that it will be useful,
22 but WITHOUT ANY WARRANTY; without even the implied warranty of
23 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 GNU General Public License for more details.
26 You should have received a copy of the GNU General Public License
27 along with Libgfortran; see the file COPYING. If not, write to
28 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
29 Boston, MA 02110-1301, USA. */
31 /* Unix stream I/O module */
33 #include "config.h"
34 #include <stdlib.h>
35 #include <limits.h>
37 #include <unistd.h>
38 #include <stdio.h>
39 #include <sys/stat.h>
40 #include <fcntl.h>
41 #include <assert.h>
43 #include <string.h>
44 #include <errno.h>
46 #include "libgfortran.h"
47 #include "io.h"
49 #ifndef PATH_MAX
50 #define PATH_MAX 1024
51 #endif
53 #ifndef PROT_READ
54 #define PROT_READ 1
55 #endif
57 #ifndef PROT_WRITE
58 #define PROT_WRITE 2
59 #endif
61 /* These flags aren't defined on all targets (mingw32), so provide them
62 here. */
63 #ifndef S_IRGRP
64 #define S_IRGRP 0
65 #endif
67 #ifndef S_IWGRP
68 #define S_IWGRP 0
69 #endif
71 #ifndef S_IROTH
72 #define S_IROTH 0
73 #endif
75 #ifndef S_IWOTH
76 #define S_IWOTH 0
77 #endif
79 /* This implementation of stream I/O is based on the paper:
81 * "Exploiting the advantages of mapped files for stream I/O",
82 * O. Krieger, M. Stumm and R. Umrau, "Proceedings of the 1992 Winter
83 * USENIX conference", p. 27-42.
85 * It differs in a number of ways from the version described in the
86 * paper. First of all, threads are not an issue during I/O and we
87 * also don't have to worry about having multiple regions, since
88 * fortran's I/O model only allows you to be one place at a time.
90 * On the other hand, we have to be able to writing at the end of a
91 * stream, read from the start of a stream or read and write blocks of
92 * bytes from an arbitrary position. After opening a file, a pointer
93 * to a stream structure is returned, which is used to handle file
94 * accesses until the file is closed.
96 * salloc_at_r(stream, len, where)-- Given a stream pointer, return a
97 * pointer to a block of memory that mirror the file at position
98 * 'where' that is 'len' bytes long. The len integer is updated to
99 * reflect how many bytes were actually read. The only reason for a
100 * short read is end of file. The file pointer is updated. The
101 * pointer is valid until the next call to salloc_*.
103 * salloc_at_w(stream, len, where)-- Given the stream pointer, returns
104 * a pointer to a block of memory that is updated to reflect the state
105 * of the file. The length of the buffer is always equal to that
106 * requested. The buffer must be completely set by the caller. When
107 * data has been written, the sfree() function must be called to
108 * indicate that the caller is done writing data to the buffer. This
109 * may or may not cause a physical write.
111 * Short forms of these are salloc_r() and salloc_w() which drop the
112 * 'where' parameter and use the current file pointer. */
115 #define BUFFER_SIZE 8192
117 typedef struct
119 stream st;
121 int fd;
122 gfc_offset buffer_offset; /* File offset of the start of the buffer */
123 gfc_offset physical_offset; /* Current physical file offset */
124 gfc_offset logical_offset; /* Current logical file offset */
125 gfc_offset dirty_offset; /* Start of modified bytes in buffer */
126 gfc_offset file_length; /* Length of the file, -1 if not seekable. */
128 char *buffer;
129 int len; /* Physical length of the current buffer */
130 int active; /* Length of valid bytes in the buffer */
132 int prot;
133 int ndirty; /* Dirty bytes starting at dirty_offset */
135 int special_file; /* =1 if the fd refers to a special file */
137 unsigned unbuffered:1;
139 char small_buffer[BUFFER_SIZE];
142 unix_stream;
144 /*move_pos_offset()-- Move the record pointer right or left
145 *relative to current position */
148 move_pos_offset (stream* st, int pos_off)
150 unix_stream * str = (unix_stream*)st;
151 if (pos_off < 0)
153 str->logical_offset += pos_off;
155 if (str->dirty_offset + str->ndirty > str->logical_offset)
157 if (str->ndirty + pos_off > 0)
158 str->ndirty += pos_off;
159 else
161 str->dirty_offset += pos_off + pos_off;
162 str->ndirty = 0;
166 return pos_off;
168 return 0;
172 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
173 * standard descriptors, returning a non-standard descriptor. If the
174 * user specifies that system errors should go to standard output,
175 * then closes standard output, we don't want the system errors to a
176 * file that has been given file descriptor 1 or 0. We want to send
177 * the error to the invalid descriptor. */
179 static int
180 fix_fd (int fd)
182 int input, output, error;
184 input = output = error = 0;
186 /* Unix allocates the lowest descriptors first, so a loop is not
187 required, but this order is. */
189 if (fd == STDIN_FILENO)
191 fd = dup (fd);
192 input = 1;
194 if (fd == STDOUT_FILENO)
196 fd = dup (fd);
197 output = 1;
199 if (fd == STDERR_FILENO)
201 fd = dup (fd);
202 error = 1;
205 if (input)
206 close (STDIN_FILENO);
207 if (output)
208 close (STDOUT_FILENO);
209 if (error)
210 close (STDERR_FILENO);
212 return fd;
216 is_preconnected (stream * s)
218 int fd;
220 fd = ((unix_stream *) s)->fd;
221 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
222 return 1;
223 else
224 return 0;
228 /* Reset a stream after reading/writing. Assumes that the buffers have
229 been flushed. */
231 inline static void
232 reset_stream (unix_stream * s, size_t bytes_rw)
234 s->physical_offset += bytes_rw;
235 s->logical_offset = s->physical_offset;
236 if (s->file_length != -1 && s->physical_offset > s->file_length)
237 s->file_length = s->physical_offset;
241 /* Read bytes into a buffer, allowing for short reads. If the nbytes
242 * argument is less on return than on entry, it is because we've hit
243 * the end of file. */
245 static int
246 do_read (unix_stream * s, void * buf, size_t * nbytes)
248 ssize_t trans;
249 size_t bytes_left;
250 char *buf_st;
251 int status;
253 status = 0;
254 bytes_left = *nbytes;
255 buf_st = (char *) buf;
257 /* We must read in a loop since some systems don't restart system
258 calls in case of a signal. */
259 while (bytes_left > 0)
261 /* Requests between SSIZE_MAX and SIZE_MAX are undefined by SUSv3,
262 so we must read in chunks smaller than SSIZE_MAX. */
263 trans = (bytes_left < SSIZE_MAX) ? bytes_left : SSIZE_MAX;
264 trans = read (s->fd, buf_st, trans);
265 if (trans < 0)
267 if (errno == EINTR)
268 continue;
269 else
271 status = errno;
272 break;
275 else if (trans == 0) /* We hit EOF. */
276 break;
277 buf_st += trans;
278 bytes_left -= trans;
281 *nbytes -= bytes_left;
282 return status;
286 /* Write a buffer to a stream, allowing for short writes. */
288 static int
289 do_write (unix_stream * s, const void * buf, size_t * nbytes)
291 ssize_t trans;
292 size_t bytes_left;
293 char *buf_st;
294 int status;
296 status = 0;
297 bytes_left = *nbytes;
298 buf_st = (char *) buf;
300 /* We must write in a loop since some systems don't restart system
301 calls in case of a signal. */
302 while (bytes_left > 0)
304 /* Requests between SSIZE_MAX and SIZE_MAX are undefined by SUSv3,
305 so we must write in chunks smaller than SSIZE_MAX. */
306 trans = (bytes_left < SSIZE_MAX) ? bytes_left : SSIZE_MAX;
307 trans = write (s->fd, buf_st, trans);
308 if (trans < 0)
310 if (errno == EINTR)
311 continue;
312 else
314 status = errno;
315 break;
318 buf_st += trans;
319 bytes_left -= trans;
322 *nbytes -= bytes_left;
323 return status;
327 /* get_oserror()-- Get the most recent operating system error. For
328 * unix, this is errno. */
330 const char *
331 get_oserror (void)
333 return strerror (errno);
337 /* sys_exit()-- Terminate the program with an exit code */
339 void
340 sys_exit (int code)
342 exit (code);
346 /*********************************************************************
347 File descriptor stream functions
348 *********************************************************************/
351 /* fd_flush()-- Write bytes that need to be written */
353 static try
354 fd_flush (unix_stream * s)
356 size_t writelen;
358 if (s->ndirty == 0)
359 return SUCCESS;;
361 if (s->physical_offset != s->dirty_offset &&
362 lseek (s->fd, s->dirty_offset, SEEK_SET) < 0)
363 return FAILURE;
365 writelen = s->ndirty;
366 if (do_write (s, s->buffer + (s->dirty_offset - s->buffer_offset),
367 &writelen) != 0)
368 return FAILURE;
370 s->physical_offset = s->dirty_offset + writelen;
372 /* don't increment file_length if the file is non-seekable */
373 if (s->file_length != -1 && s->physical_offset > s->file_length)
374 s->file_length = s->physical_offset;
376 s->ndirty -= writelen;
377 if (s->ndirty != 0)
378 return FAILURE;
380 return SUCCESS;
384 /* fd_alloc()-- Arrange a buffer such that the salloc() request can be
385 * satisfied. This subroutine gets the buffer ready for whatever is
386 * to come next. */
388 static void
389 fd_alloc (unix_stream * s, gfc_offset where,
390 int *len __attribute__ ((unused)))
392 char *new_buffer;
393 int n, read_len;
395 if (*len <= BUFFER_SIZE)
397 new_buffer = s->small_buffer;
398 read_len = BUFFER_SIZE;
400 else
402 new_buffer = get_mem (*len);
403 read_len = *len;
406 /* Salvage bytes currently within the buffer. This is important for
407 * devices that cannot seek. */
409 if (s->buffer != NULL && s->buffer_offset <= where &&
410 where <= s->buffer_offset + s->active)
413 n = s->active - (where - s->buffer_offset);
414 memmove (new_buffer, s->buffer + (where - s->buffer_offset), n);
416 s->active = n;
418 else
419 { /* new buffer starts off empty */
420 s->active = 0;
423 s->buffer_offset = where;
425 /* free the old buffer if necessary */
427 if (s->buffer != NULL && s->buffer != s->small_buffer)
428 free_mem (s->buffer);
430 s->buffer = new_buffer;
431 s->len = read_len;
435 /* fd_alloc_r_at()-- Allocate a stream buffer for reading. Either
436 * we've already buffered the data or we need to load it. Returns
437 * NULL on I/O error. */
439 static char *
440 fd_alloc_r_at (unix_stream * s, int *len, gfc_offset where)
442 gfc_offset m;
443 int n;
445 if (where == -1)
446 where = s->logical_offset;
448 if (s->buffer != NULL && s->buffer_offset <= where &&
449 where + *len <= s->buffer_offset + s->active)
452 /* Return a position within the current buffer */
454 s->logical_offset = where + *len;
455 return s->buffer + where - s->buffer_offset;
458 fd_alloc (s, where, len);
460 m = where + s->active;
462 if (s->physical_offset != m && lseek (s->fd, m, SEEK_SET) < 0)
463 return NULL;
465 n = read (s->fd, s->buffer + s->active, s->len - s->active);
466 if (n < 0)
467 return NULL;
469 s->physical_offset = where + n;
471 s->active += n;
472 if (s->active < *len)
473 *len = s->active; /* Bytes actually available */
475 s->logical_offset = where + *len;
477 return s->buffer;
481 /* fd_alloc_w_at()-- Allocate a stream buffer for writing. Either
482 * we've already buffered the data or we need to load it. */
484 static char *
485 fd_alloc_w_at (unix_stream * s, int *len, gfc_offset where)
487 gfc_offset n;
489 if (where == -1)
490 where = s->logical_offset;
492 if (s->buffer == NULL || s->buffer_offset > where ||
493 where + *len > s->buffer_offset + s->len)
496 if (fd_flush (s) == FAILURE)
497 return NULL;
498 fd_alloc (s, where, len);
501 /* Return a position within the current buffer */
502 if (s->ndirty == 0
503 || where > s->dirty_offset + s->ndirty
504 || s->dirty_offset > where + *len)
505 { /* Discontiguous blocks, start with a clean buffer. */
506 /* Flush the buffer. */
507 if (s->ndirty != 0)
508 fd_flush (s);
509 s->dirty_offset = where;
510 s->ndirty = *len;
512 else
514 gfc_offset start; /* Merge with the existing data. */
515 if (where < s->dirty_offset)
516 start = where;
517 else
518 start = s->dirty_offset;
519 if (where + *len > s->dirty_offset + s->ndirty)
520 s->ndirty = where + *len - start;
521 else
522 s->ndirty = s->dirty_offset + s->ndirty - start;
523 s->dirty_offset = start;
526 s->logical_offset = where + *len;
528 if (where + *len > s->file_length)
529 s->file_length = where + *len;
531 n = s->logical_offset - s->buffer_offset;
532 if (n > s->active)
533 s->active = n;
535 return s->buffer + where - s->buffer_offset;
539 static try
540 fd_sfree (unix_stream * s)
542 if (s->ndirty != 0 &&
543 (s->buffer != s->small_buffer || options.all_unbuffered ||
544 s->unbuffered))
545 return fd_flush (s);
547 return SUCCESS;
551 static try
552 fd_seek (unix_stream * s, gfc_offset offset)
554 if (s->physical_offset == offset) /* Are we lucky and avoid syscall? */
556 s->logical_offset = offset;
557 return SUCCESS;
560 s->physical_offset = s->logical_offset = offset;
562 return (lseek (s->fd, offset, SEEK_SET) < 0) ? FAILURE : SUCCESS;
566 /* truncate_file()-- Given a unit, truncate the file at the current
567 * position. Sets the physical location to the new end of the file.
568 * Returns nonzero on error. */
570 static try
571 fd_truncate (unix_stream * s)
573 if (lseek (s->fd, s->logical_offset, SEEK_SET) == -1)
574 return FAILURE;
576 /* non-seekable files, like terminals and fifo's fail the lseek.
577 Using ftruncate on a seekable special file (like /dev/null)
578 is undefined, so we treat it as if the ftruncate failed.
580 #ifdef HAVE_FTRUNCATE
581 if (s->special_file || ftruncate (s->fd, s->logical_offset))
582 #else
583 #ifdef HAVE_CHSIZE
584 if (s->special_file || chsize (s->fd, s->logical_offset))
585 #endif
586 #endif
588 s->physical_offset = s->file_length = 0;
589 return FAILURE;
592 s->physical_offset = s->file_length = s->logical_offset;
594 return SUCCESS;
600 /* Stream read function. Avoids using a buffer for big reads. The
601 interface is like POSIX read(), but the nbytes argument is a
602 pointer; on return it contains the number of bytes written. The
603 function return value is the status indicator (0 for success). */
605 static int
606 fd_read (unix_stream * s, void * buf, size_t * nbytes)
608 void *p;
609 int tmp, status;
611 if (*nbytes < BUFFER_SIZE && !s->unbuffered)
613 tmp = *nbytes;
614 p = fd_alloc_r_at (s, &tmp, -1);
615 if (p)
617 *nbytes = tmp;
618 memcpy (buf, p, *nbytes);
619 return 0;
621 else
623 *nbytes = 0;
624 return errno;
628 /* If the request is bigger than BUFFER_SIZE we flush the buffers
629 and read directly. */
630 if (fd_flush (s) == FAILURE)
632 *nbytes = 0;
633 return errno;
636 if (is_seekable ((stream *) s) && fd_seek (s, s->logical_offset) == FAILURE)
638 *nbytes = 0;
639 return errno;
642 status = do_read (s, buf, nbytes);
643 reset_stream (s, *nbytes);
644 return status;
648 /* Stream write function. Avoids using a buffer for big writes. The
649 interface is like POSIX write(), but the nbytes argument is a
650 pointer; on return it contains the number of bytes written. The
651 function return value is the status indicator (0 for success). */
653 static int
654 fd_write (unix_stream * s, const void * buf, size_t * nbytes)
656 void *p;
657 int tmp, status;
659 if (*nbytes < BUFFER_SIZE && !s->unbuffered)
661 tmp = *nbytes;
662 p = fd_alloc_w_at (s, &tmp, -1);
663 if (p)
665 *nbytes = tmp;
666 memcpy (p, buf, *nbytes);
667 return 0;
669 else
671 *nbytes = 0;
672 return errno;
676 /* If the request is bigger than BUFFER_SIZE we flush the buffers
677 and write directly. */
678 if (fd_flush (s) == FAILURE)
680 *nbytes = 0;
681 return errno;
684 if (is_seekable ((stream *) s) && fd_seek (s, s->logical_offset) == FAILURE)
686 *nbytes = 0;
687 return errno;
690 status = do_write (s, buf, nbytes);
691 reset_stream (s, *nbytes);
692 return status;
696 static try
697 fd_close (unix_stream * s)
699 if (fd_flush (s) == FAILURE)
700 return FAILURE;
702 if (s->buffer != NULL && s->buffer != s->small_buffer)
703 free_mem (s->buffer);
705 if (s->fd != STDOUT_FILENO && s->fd != STDERR_FILENO)
707 if (close (s->fd) < 0)
708 return FAILURE;
711 free_mem (s);
713 return SUCCESS;
717 static void
718 fd_open (unix_stream * s)
720 if (isatty (s->fd))
721 s->unbuffered = 1;
723 s->st.alloc_r_at = (void *) fd_alloc_r_at;
724 s->st.alloc_w_at = (void *) fd_alloc_w_at;
725 s->st.sfree = (void *) fd_sfree;
726 s->st.close = (void *) fd_close;
727 s->st.seek = (void *) fd_seek;
728 s->st.truncate = (void *) fd_truncate;
729 s->st.read = (void *) fd_read;
730 s->st.write = (void *) fd_write;
732 s->buffer = NULL;
738 /*********************************************************************
739 memory stream functions - These are used for internal files
741 The idea here is that a single stream structure is created and all
742 requests must be satisfied from it. The location and size of the
743 buffer is the character variable supplied to the READ or WRITE
744 statement.
746 *********************************************************************/
749 static char *
750 mem_alloc_r_at (unix_stream * s, int *len, gfc_offset where)
752 gfc_offset n;
754 if (where == -1)
755 where = s->logical_offset;
757 if (where < s->buffer_offset || where > s->buffer_offset + s->active)
758 return NULL;
760 s->logical_offset = where + *len;
762 n = s->buffer_offset + s->active - where;
763 if (*len > n)
764 *len = n;
766 return s->buffer + (where - s->buffer_offset);
770 static char *
771 mem_alloc_w_at (unix_stream * s, int *len, gfc_offset where)
773 gfc_offset m;
775 assert (*len >= 0); /* Negative values not allowed. */
777 if (where == -1)
778 where = s->logical_offset;
780 m = where + *len;
782 if (where < s->buffer_offset)
783 return NULL;
785 if (m > s->file_length)
786 return NULL;
788 s->logical_offset = m;
790 return s->buffer + (where - s->buffer_offset);
794 /* Stream read function for internal units. This is not actually used
795 at the moment, as all internal IO is formatted and the formatted IO
796 routines use mem_alloc_r_at. */
798 static int
799 mem_read (unix_stream * s, void * buf, size_t * nbytes)
801 void *p;
802 int tmp;
804 tmp = *nbytes;
805 p = mem_alloc_r_at (s, &tmp, -1);
806 if (p)
808 *nbytes = tmp;
809 memcpy (buf, p, *nbytes);
810 return 0;
812 else
814 *nbytes = 0;
815 return errno;
820 /* Stream write function for internal units. This is not actually used
821 at the moment, as all internal IO is formatted and the formatted IO
822 routines use mem_alloc_w_at. */
824 static int
825 mem_write (unix_stream * s, const void * buf, size_t * nbytes)
827 void *p;
828 int tmp;
830 errno = 0;
832 tmp = *nbytes;
833 p = mem_alloc_w_at (s, &tmp, -1);
834 if (p)
836 *nbytes = tmp;
837 memcpy (p, buf, *nbytes);
838 return 0;
840 else
842 *nbytes = 0;
843 return errno;
848 static int
849 mem_seek (unix_stream * s, gfc_offset offset)
851 if (offset > s->file_length)
853 errno = ESPIPE;
854 return FAILURE;
857 s->logical_offset = offset;
858 return SUCCESS;
862 static int
863 mem_truncate (unix_stream * s __attribute__ ((unused)))
865 return SUCCESS;
869 static try
870 mem_close (unix_stream * s)
872 free_mem (s);
874 return SUCCESS;
878 static try
879 mem_sfree (unix_stream * s __attribute__ ((unused)))
881 return SUCCESS;
886 /*********************************************************************
887 Public functions -- A reimplementation of this module needs to
888 define functional equivalents of the following.
889 *********************************************************************/
891 /* empty_internal_buffer()-- Zero the buffer of Internal file */
893 void
894 empty_internal_buffer(stream *strm)
896 unix_stream * s = (unix_stream *) strm;
897 memset(s->buffer, ' ', s->file_length);
900 /* open_internal()-- Returns a stream structure from an internal file */
902 stream *
903 open_internal (char *base, int length)
905 unix_stream *s;
907 s = get_mem (sizeof (unix_stream));
908 memset (s, '\0', sizeof (unix_stream));
910 s->buffer = base;
911 s->buffer_offset = 0;
913 s->logical_offset = 0;
914 s->active = s->file_length = length;
916 s->st.alloc_r_at = (void *) mem_alloc_r_at;
917 s->st.alloc_w_at = (void *) mem_alloc_w_at;
918 s->st.sfree = (void *) mem_sfree;
919 s->st.close = (void *) mem_close;
920 s->st.seek = (void *) mem_seek;
921 s->st.truncate = (void *) mem_truncate;
922 s->st.read = (void *) mem_read;
923 s->st.write = (void *) mem_write;
925 return (stream *) s;
929 /* fd_to_stream()-- Given an open file descriptor, build a stream
930 * around it. */
932 static stream *
933 fd_to_stream (int fd, int prot)
935 struct stat statbuf;
936 unix_stream *s;
938 s = get_mem (sizeof (unix_stream));
939 memset (s, '\0', sizeof (unix_stream));
941 s->fd = fd;
942 s->buffer_offset = 0;
943 s->physical_offset = 0;
944 s->logical_offset = 0;
945 s->prot = prot;
947 /* Get the current length of the file. */
949 fstat (fd, &statbuf);
950 s->file_length = S_ISREG (statbuf.st_mode) ? statbuf.st_size : -1;
951 s->special_file = !S_ISREG (statbuf.st_mode);
953 fd_open (s);
955 return (stream *) s;
959 /* Given the Fortran unit number, convert it to a C file descriptor. */
962 unit_to_fd(int unit)
964 gfc_unit *us;
966 us = find_unit(unit);
967 if (us == NULL)
968 return -1;
970 return ((unix_stream *) us->s)->fd;
974 /* unpack_filename()-- Given a fortran string and a pointer to a
975 * buffer that is PATH_MAX characters, convert the fortran string to a
976 * C string in the buffer. Returns nonzero if this is not possible. */
979 unpack_filename (char *cstring, const char *fstring, int len)
981 len = fstrlen (fstring, len);
982 if (len >= PATH_MAX)
983 return 1;
985 memmove (cstring, fstring, len);
986 cstring[len] = '\0';
988 return 0;
992 /* tempfile()-- Generate a temporary filename for a scratch file and
993 * open it. mkstemp() opens the file for reading and writing, but the
994 * library mode prevents anything that is not allowed. The descriptor
995 * is returned, which is -1 on error. The template is pointed to by
996 * ioparm.file, which is copied into the unit structure
997 * and freed later. */
999 static int
1000 tempfile (void)
1002 const char *tempdir;
1003 char *template;
1004 int fd;
1006 tempdir = getenv ("GFORTRAN_TMPDIR");
1007 if (tempdir == NULL)
1008 tempdir = getenv ("TMP");
1009 if (tempdir == NULL)
1010 tempdir = getenv ("TEMP");
1011 if (tempdir == NULL)
1012 tempdir = DEFAULT_TEMPDIR;
1014 template = get_mem (strlen (tempdir) + 20);
1016 st_sprintf (template, "%s/gfortrantmpXXXXXX", tempdir);
1018 #ifdef HAVE_MKSTEMP
1020 fd = mkstemp (template);
1022 #else /* HAVE_MKSTEMP */
1024 if (mktemp (template))
1026 #ifdef HAVE_CRLF
1027 fd = open (template, O_RDWR | O_CREAT | O_EXCL | O_BINARY,
1028 S_IREAD | S_IWRITE);
1029 #else
1030 fd = open (template, O_RDWR | O_CREAT | O_EXCL, S_IREAD | S_IWRITE);
1031 #endif
1032 while (!(fd == -1 && errno == EEXIST) && mktemp (template));
1033 else
1034 fd = -1;
1036 #endif /* HAVE_MKSTEMP */
1038 if (fd < 0)
1039 free_mem (template);
1040 else
1042 ioparm.file = template;
1043 ioparm.file_len = strlen (template); /* Don't include trailing nul */
1046 return fd;
1050 /* regular_file()-- Open a regular file.
1051 * Change flags->action if it is ACTION_UNSPECIFIED on entry,
1052 * unless an error occurs.
1053 * Returns the descriptor, which is less than zero on error. */
1055 static int
1056 regular_file (unit_flags *flags)
1058 char path[PATH_MAX + 1];
1059 int mode;
1060 int rwflag;
1061 int crflag;
1062 int fd;
1064 if (unpack_filename (path, ioparm.file, ioparm.file_len))
1066 errno = ENOENT; /* Fake an OS error */
1067 return -1;
1070 rwflag = 0;
1072 switch (flags->action)
1074 case ACTION_READ:
1075 rwflag = O_RDONLY;
1076 break;
1078 case ACTION_WRITE:
1079 rwflag = O_WRONLY;
1080 break;
1082 case ACTION_READWRITE:
1083 case ACTION_UNSPECIFIED:
1084 rwflag = O_RDWR;
1085 break;
1087 default:
1088 internal_error ("regular_file(): Bad action");
1091 switch (flags->status)
1093 case STATUS_NEW:
1094 crflag = O_CREAT | O_EXCL;
1095 break;
1097 case STATUS_OLD: /* open will fail if the file does not exist*/
1098 crflag = 0;
1099 break;
1101 case STATUS_UNKNOWN:
1102 case STATUS_SCRATCH:
1103 crflag = O_CREAT;
1104 break;
1106 case STATUS_REPLACE:
1107 crflag = O_CREAT | O_TRUNC;
1108 break;
1110 default:
1111 internal_error ("regular_file(): Bad status");
1114 /* rwflag |= O_LARGEFILE; */
1116 #ifdef HAVE_CRLF
1117 crflag |= O_BINARY;
1118 #endif
1120 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1121 fd = open (path, rwflag | crflag, mode);
1122 if (flags->action != ACTION_UNSPECIFIED)
1123 return fd;
1125 if (fd >= 0)
1127 flags->action = ACTION_READWRITE;
1128 return fd;
1130 if (errno != EACCES)
1131 return fd;
1133 /* retry for read-only access */
1134 rwflag = O_RDONLY;
1135 fd = open (path, rwflag | crflag, mode);
1136 if (fd >=0)
1138 flags->action = ACTION_READ;
1139 return fd; /* success */
1142 if (errno != EACCES)
1143 return fd; /* failure */
1145 /* retry for write-only access */
1146 rwflag = O_WRONLY;
1147 fd = open (path, rwflag | crflag, mode);
1148 if (fd >=0)
1150 flags->action = ACTION_WRITE;
1151 return fd; /* success */
1153 return fd; /* failure */
1157 /* open_external()-- Open an external file, unix specific version.
1158 * Change flags->action if it is ACTION_UNSPECIFIED on entry.
1159 * Returns NULL on operating system error. */
1161 stream *
1162 open_external (unit_flags *flags)
1164 int fd, prot;
1166 if (flags->status == STATUS_SCRATCH)
1168 fd = tempfile ();
1169 if (flags->action == ACTION_UNSPECIFIED)
1170 flags->action = ACTION_READWRITE;
1172 #if HAVE_UNLINK_OPEN_FILE
1173 /* We can unlink scratch files now and it will go away when closed. */
1174 unlink (ioparm.file);
1175 #endif
1177 else
1179 /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1180 * if it succeeds */
1181 fd = regular_file (flags);
1184 if (fd < 0)
1185 return NULL;
1186 fd = fix_fd (fd);
1188 switch (flags->action)
1190 case ACTION_READ:
1191 prot = PROT_READ;
1192 break;
1194 case ACTION_WRITE:
1195 prot = PROT_WRITE;
1196 break;
1198 case ACTION_READWRITE:
1199 prot = PROT_READ | PROT_WRITE;
1200 break;
1202 default:
1203 internal_error ("open_external(): Bad action");
1206 return fd_to_stream (fd, prot);
1210 /* input_stream()-- Return a stream pointer to the default input stream.
1211 * Called on initialization. */
1213 stream *
1214 input_stream (void)
1216 return fd_to_stream (STDIN_FILENO, PROT_READ);
1220 /* output_stream()-- Return a stream pointer to the default output stream.
1221 * Called on initialization. */
1223 stream *
1224 output_stream (void)
1226 return fd_to_stream (STDOUT_FILENO, PROT_WRITE);
1230 /* error_stream()-- Return a stream pointer to the default error stream.
1231 * Called on initialization. */
1233 stream *
1234 error_stream (void)
1236 return fd_to_stream (STDERR_FILENO, PROT_WRITE);
1239 /* init_error_stream()-- Return a pointer to the error stream. This
1240 * subroutine is called when the stream is needed, rather than at
1241 * initialization. We want to work even if memory has been seriously
1242 * corrupted. */
1244 stream *
1245 init_error_stream (void)
1247 static unix_stream error;
1249 memset (&error, '\0', sizeof (error));
1251 error.fd = options.use_stderr ? STDERR_FILENO : STDOUT_FILENO;
1253 error.st.alloc_w_at = (void *) fd_alloc_w_at;
1254 error.st.sfree = (void *) fd_sfree;
1256 error.unbuffered = 1;
1257 error.buffer = error.small_buffer;
1259 return (stream *) & error;
1263 /* compare_file_filename()-- Given an open stream and a fortran string
1264 * that is a filename, figure out if the file is the same as the
1265 * filename. */
1268 compare_file_filename (stream * s, const char *name, int len)
1270 char path[PATH_MAX + 1];
1271 struct stat st1, st2;
1273 if (unpack_filename (path, name, len))
1274 return 0; /* Can't be the same */
1276 /* If the filename doesn't exist, then there is no match with the
1277 * existing file. */
1279 if (stat (path, &st1) < 0)
1280 return 0;
1282 fstat (((unix_stream *) s)->fd, &st2);
1284 return (st1.st_dev == st2.st_dev) && (st1.st_ino == st2.st_ino);
1288 /* find_file0()-- Recursive work function for find_file() */
1290 static gfc_unit *
1291 find_file0 (gfc_unit * u, struct stat *st1)
1293 struct stat st2;
1294 gfc_unit *v;
1296 if (u == NULL)
1297 return NULL;
1299 if (fstat (((unix_stream *) u->s)->fd, &st2) >= 0 &&
1300 st1->st_dev == st2.st_dev && st1->st_ino == st2.st_ino)
1301 return u;
1303 v = find_file0 (u->left, st1);
1304 if (v != NULL)
1305 return v;
1307 v = find_file0 (u->right, st1);
1308 if (v != NULL)
1309 return v;
1311 return NULL;
1315 /* find_file()-- Take the current filename and see if there is a unit
1316 * that has the file already open. Returns a pointer to the unit if so. */
1318 gfc_unit *
1319 find_file (void)
1321 char path[PATH_MAX + 1];
1322 struct stat statbuf;
1324 if (unpack_filename (path, ioparm.file, ioparm.file_len))
1325 return NULL;
1327 if (stat (path, &statbuf) < 0)
1328 return NULL;
1330 return find_file0 (g.unit_root, &statbuf);
1334 /* stream_at_bof()-- Returns nonzero if the stream is at the beginning
1335 * of the file. */
1338 stream_at_bof (stream * s)
1340 unix_stream *us;
1342 if (!is_seekable (s))
1343 return 0;
1345 us = (unix_stream *) s;
1347 return us->logical_offset == 0;
1351 /* stream_at_eof()-- Returns nonzero if the stream is at the beginning
1352 * of the file. */
1355 stream_at_eof (stream * s)
1357 unix_stream *us;
1359 if (!is_seekable (s))
1360 return 0;
1362 us = (unix_stream *) s;
1364 return us->logical_offset == us->dirty_offset;
1368 /* delete_file()-- Given a unit structure, delete the file associated
1369 * with the unit. Returns nonzero if something went wrong. */
1372 delete_file (gfc_unit * u)
1374 char path[PATH_MAX + 1];
1376 if (unpack_filename (path, u->file, u->file_len))
1377 { /* Shouldn't be possible */
1378 errno = ENOENT;
1379 return 1;
1382 return unlink (path);
1386 /* file_exists()-- Returns nonzero if the current filename exists on
1387 * the system */
1390 file_exists (void)
1392 char path[PATH_MAX + 1];
1393 struct stat statbuf;
1395 if (unpack_filename (path, ioparm.file, ioparm.file_len))
1396 return 0;
1398 if (stat (path, &statbuf) < 0)
1399 return 0;
1401 return 1;
1406 static const char yes[] = "YES", no[] = "NO", unknown[] = "UNKNOWN";
1408 /* inquire_sequential()-- Given a fortran string, determine if the
1409 * file is suitable for sequential access. Returns a C-style
1410 * string. */
1412 const char *
1413 inquire_sequential (const char *string, int len)
1415 char path[PATH_MAX + 1];
1416 struct stat statbuf;
1418 if (string == NULL ||
1419 unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1420 return unknown;
1422 if (S_ISREG (statbuf.st_mode) ||
1423 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1424 return yes;
1426 if (S_ISDIR (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1427 return no;
1429 return unknown;
1433 /* inquire_direct()-- Given a fortran string, determine if the file is
1434 * suitable for direct access. Returns a C-style string. */
1436 const char *
1437 inquire_direct (const char *string, int len)
1439 char path[PATH_MAX + 1];
1440 struct stat statbuf;
1442 if (string == NULL ||
1443 unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1444 return unknown;
1446 if (S_ISREG (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1447 return yes;
1449 if (S_ISDIR (statbuf.st_mode) ||
1450 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1451 return no;
1453 return unknown;
1457 /* inquire_formatted()-- Given a fortran string, determine if the file
1458 * is suitable for formatted form. Returns a C-style string. */
1460 const char *
1461 inquire_formatted (const char *string, int len)
1463 char path[PATH_MAX + 1];
1464 struct stat statbuf;
1466 if (string == NULL ||
1467 unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1468 return unknown;
1470 if (S_ISREG (statbuf.st_mode) ||
1471 S_ISBLK (statbuf.st_mode) ||
1472 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1473 return yes;
1475 if (S_ISDIR (statbuf.st_mode))
1476 return no;
1478 return unknown;
1482 /* inquire_unformatted()-- Given a fortran string, determine if the file
1483 * is suitable for unformatted form. Returns a C-style string. */
1485 const char *
1486 inquire_unformatted (const char *string, int len)
1488 return inquire_formatted (string, len);
1492 /* inquire_access()-- Given a fortran string, determine if the file is
1493 * suitable for access. */
1495 static const char *
1496 inquire_access (const char *string, int len, int mode)
1498 char path[PATH_MAX + 1];
1500 if (string == NULL || unpack_filename (path, string, len) ||
1501 access (path, mode) < 0)
1502 return no;
1504 return yes;
1508 /* inquire_read()-- Given a fortran string, determine if the file is
1509 * suitable for READ access. */
1511 const char *
1512 inquire_read (const char *string, int len)
1514 return inquire_access (string, len, R_OK);
1518 /* inquire_write()-- Given a fortran string, determine if the file is
1519 * suitable for READ access. */
1521 const char *
1522 inquire_write (const char *string, int len)
1524 return inquire_access (string, len, W_OK);
1528 /* inquire_readwrite()-- Given a fortran string, determine if the file is
1529 * suitable for read and write access. */
1531 const char *
1532 inquire_readwrite (const char *string, int len)
1534 return inquire_access (string, len, R_OK | W_OK);
1538 /* file_length()-- Return the file length in bytes, -1 if unknown */
1540 gfc_offset
1541 file_length (stream * s)
1543 return ((unix_stream *) s)->file_length;
1547 /* file_position()-- Return the current position of the file */
1549 gfc_offset
1550 file_position (stream * s)
1552 return ((unix_stream *) s)->logical_offset;
1556 /* is_seekable()-- Return nonzero if the stream is seekable, zero if
1557 * it is not */
1560 is_seekable (stream * s)
1562 /* By convention, if file_length == -1, the file is not
1563 seekable. */
1564 return ((unix_stream *) s)->file_length!=-1;
1568 flush (stream *s)
1570 return fd_flush( (unix_stream *) s);
1574 stream_isatty (stream *s)
1576 return isatty (((unix_stream *) s)->fd);
1579 char *
1580 stream_ttyname (stream *s)
1582 #ifdef HAVE_TTYNAME
1583 return ttyname (((unix_stream *) s)->fd);
1584 #else
1585 return NULL;
1586 #endif
1590 /* How files are stored: This is an operating-system specific issue,
1591 and therefore belongs here. There are three cases to consider.
1593 Direct Access:
1594 Records are written as block of bytes corresponding to the record
1595 length of the file. This goes for both formatted and unformatted
1596 records. Positioning is done explicitly for each data transfer,
1597 so positioning is not much of an issue.
1599 Sequential Formatted:
1600 Records are separated by newline characters. The newline character
1601 is prohibited from appearing in a string. If it does, this will be
1602 messed up on the next read. End of file is also the end of a record.
1604 Sequential Unformatted:
1605 In this case, we are merely copying bytes to and from main storage,
1606 yet we need to keep track of varying record lengths. We adopt
1607 the solution used by f2c. Each record contains a pair of length
1608 markers:
1610 Length of record n in bytes
1611 Data of record n
1612 Length of record n in bytes
1614 Length of record n+1 in bytes
1615 Data of record n+1
1616 Length of record n+1 in bytes
1618 The length is stored at the end of a record to allow backspacing to the
1619 previous record. Between data transfer statements, the file pointer
1620 is left pointing to the first length of the current record.
1622 ENDFILE records are never explicitly stored.